Files
zurg/internal/torrent/refresh.go
2024-07-21 02:37:32 +02:00

433 lines
12 KiB
Go

package torrent
import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
"time"
"github.com/debridmediamanager/zurg/internal/config"
"github.com/debridmediamanager/zurg/pkg/realdebrid"
"github.com/debridmediamanager/zurg/pkg/utils"
mapset "github.com/deckarep/golang-set/v2"
cmap "github.com/orcaman/concurrent-map/v2"
"gopkg.in/vansante/go-ffprobe.v2"
)
func (t *TorrentManager) refreshTorrents(initialRun bool) {
instances, _, err := t.rd.GetTorrents(false)
if err != nil {
t.log.Warnf("Cannot get torrents: %v", err)
t.log.Info("Retrying in 5 seconds")
time.Sleep(5 * time.Second)
t.refreshTorrents(initialRun)
return
}
var wg sync.WaitGroup
var mergeChan = make(chan *Torrent, len(instances))
torrents, _ := t.DirectoryMap.Get(INT_ALL)
oldKeys := mapset.NewSet[string](torrents.Keys()...)
freshIDs := mapset.NewSet[string]()
freshAccessKeys := mapset.NewSet[string]()
for i := range instances {
freshIDs.Add(instances[i].ID)
wg.Add(1)
idx := i
t.workerPool.Submit(func() {
defer wg.Done()
tInfo := t.getMoreInfo(instances[idx])
if tInfo == nil {
// just in case!
mergeChan <- nil
return
}
status := tInfo.Status
if status != "downloading" && status != "downloaded" && status != "uploading" && status != "queued" && status != "compressing" && status != "waiting_files_selection" {
t.deleteOnceDone(tInfo.ID, true)
}
if tInfo.Progress != 100 || len(tInfo.Links) == 0 {
mergeChan <- nil
return
}
torrent := t.convertToTorrent(tInfo)
accessKey := t.GetKey(torrent)
freshAccessKeys.Add(accessKey)
var forMerging *Torrent
mainTorrent, exists := torrents.Get(accessKey)
if !exists {
torrents.Set(accessKey, torrent)
t.writeTorrentToFile(torrent)
t.assignDirectory(torrent, !initialRun, true)
} else if !mainTorrent.DownloadedIDs.ContainsOne(tInfo.ID) {
forMerging = torrent
}
mergeChan <- forMerging
})
}
wg.Wait()
close(mergeChan)
t.log.Infof("Compiling %d torrents", len(instances))
for torrent := range mergeChan {
if torrent == nil {
continue
}
accessKey := t.GetKey(torrent)
existing, ok := torrents.Get(accessKey)
if !ok {
t.log.Warnf("Cannot merge %s", accessKey)
continue
}
mainTorrent := t.mergeTorrents(existing, torrent)
torrents.Set(accessKey, mainTorrent)
t.writeTorrentToFile(mainTorrent)
t.assignDirectory(mainTorrent, !initialRun, true)
}
// new torrents
t.workerPool.Submit(func() {
if !t.hasFFprobe || !t.Config.ShouldAutoAnalyzeNewTorrents() {
return
}
freshAccessKeys.Difference(oldKeys).Each(func(accessKey string) bool {
torrent, _ := torrents.Get(accessKey)
t.applyMediaInfoDetails(torrent)
return false
})
})
// removed torrents
oldKeys.Difference(freshAccessKeys).Each(func(accessKey string) bool {
t.Delete(accessKey, false)
return false
})
t.log.Infof("Compiled into %d unique torrents", torrents.Count())
t.workerPool.Submit(func() {
t.OnceDoneBin.Clone().Each(func(entry string) bool {
// check for: delete once done cases
if !freshIDs.ContainsOne(entry) {
t.OnceDoneBin.Remove(entry)
}
return false
})
t.persistBins()
})
// delete info files that are no longer present
// it also runs binOnceDone (needed for cleanup every refresh)
t.getInfoFiles().Each(func(path string) bool {
path = filepath.Base(path)
torrentID := strings.TrimSuffix(path, ".zurginfo")
if !freshIDs.ContainsOne(torrentID) {
t.deleteInfoFile(torrentID)
return false
}
t.deleteOnceDone(torrentID, false)
return false
})
// cleans up DownloadedIDs field of all torrents
t.workerPool.Submit(func() {
torrents.IterCb(func(accessKey string, torrent *Torrent) {
deletedIDs := torrent.DownloadedIDs.Difference(freshIDs)
if deletedIDs.Cardinality() > 0 {
deletedIDs.Each(func(id string) bool {
torrent.DownloadedIDs.Remove(id)
return false
})
t.writeTorrentToFile(torrent)
}
})
})
}
// StartRefreshJob periodically refreshes the torrents
func (t *TorrentManager) StartRefreshJob() {
t.workerPool.Submit(func() {
t.log.Debug("Starting periodic refresh job")
refreshTicker := time.NewTicker(time.Duration(t.Config.GetRefreshEverySecs()) * time.Second)
defer refreshTicker.Stop()
for {
select {
case <-refreshTicker.C:
checksum := t.getCurrentState()
if t.latestState.Eq(checksum) {
continue
}
t.setNewLatestState(checksum)
t.refreshTorrents(false)
t.log.Info("Finished refreshing torrents")
case <-t.RefreshWorkerKillSwitch:
t.log.Info("Stopping periodic refresh job")
return
}
}
})
}
func (t *TorrentManager) getMoreInfo(rdTorrent realdebrid.Torrent) *realdebrid.TorrentInfo {
info := t.readInfoFromFile(rdTorrent.ID)
if info == nil {
var err error
info, err = t.rd.GetTorrentInfo(rdTorrent.ID)
if err != nil {
t.log.Warnf("Cannot get info for torrent %s (id=%s): %v", rdTorrent.Name, rdTorrent.ID, err)
return nil
}
t.writeInfoToFile(info)
}
for i := range info.Links {
if strings.HasPrefix(info.Links[i], "https://real-debrid.com/d/") {
// set link to max 39 chars (26 + 13)
info.Links[i] = info.Links[i][0:39]
}
}
return info
}
func (t *TorrentManager) convertToTorrent(info *realdebrid.TorrentInfo) *Torrent {
torrent := t.readTorrentFromFile("data/" + t.getTorrentInfoFilename(info) + ".zurgtorrent")
if torrent != nil && torrent.DownloadedIDs.ContainsOne(info.ID) {
return torrent
}
torrent = &Torrent{
Name: info.Name,
OriginalName: info.OriginalName,
Added: info.Added,
Hash: info.Hash,
State: NewTorrentState("broken_torrent"),
DownloadedIDs: mapset.NewSet[string](),
}
// SelectedFiles is a subset of Files with only the selected ones
// it also has a Link field, which can be empty
// if it is empty, it means the file is no longer available
// Files+Links together are the same as SelectedFiles
allFilenames := mapset.NewSet[string]()
dupeFilenames := mapset.NewSet[string]()
var selectedFiles []*File
for _, file := range info.Files {
filename := filepath.Base(file.Path)
if allFilenames.ContainsOne(filename) {
dupeFilenames.Add(filename)
} else {
allFilenames.Add(filename)
}
if file.Selected == 0 {
continue
}
selectedFiles = append(selectedFiles, &File{
File: file,
Ended: info.Ended,
Link: "", // no link yet, consider it broken
State: NewFileState("broken_file"),
})
}
if len(selectedFiles) == len(info.Links) {
// all links are still intact! good!
for i, file := range selectedFiles {
file.Link = info.Links[i]
file.State.Event(context.Background(), "repair_file")
}
torrent.UnassignedLinks = mapset.NewSet[string]()
torrent.State.Event(context.Background(), "mark_as_repaired")
} else {
torrent.UnassignedLinks = mapset.NewSet[string]()
for _, link := range info.Links {
torrent.UnassignedLinks.Add(link)
}
}
torrent.SelectedFiles = cmap.New[*File]()
for _, file := range selectedFiles {
baseFilename := t.GetPath(file)
// todo better handling of duplicate filenames
if dupeFilenames.ContainsOne(baseFilename) {
extension := filepath.Ext(baseFilename)
filenameNoExt := strings.TrimSuffix(baseFilename, extension)
newName := fmt.Sprintf("%s (%d)%s", filenameNoExt, file.ID, extension)
torrent.SelectedFiles.Set(newName, file)
} else {
torrent.SelectedFiles.Set(baseFilename, file)
}
}
torrent.DownloadedIDs.Add(info.ID)
return torrent
}
func (t *TorrentManager) mergeTorrents(existing, toMerge *Torrent) *Torrent {
var newer, older *Torrent
if existing.Added < toMerge.Added {
newer = toMerge
older = existing
} else {
newer = existing
older = toMerge
}
// base of the merged torrent
mergedTorrent := &Torrent{
Name: older.Name,
OriginalName: older.OriginalName,
Rename: older.Rename,
Hash: older.Hash,
Added: older.Added,
DownloadedIDs: older.DownloadedIDs.Union(newer.DownloadedIDs),
State: older.State,
}
// unrepairable reason
reasons := mapset.NewSet[string]()
reasons.Add(older.UnrepairableReason)
reasons.Add(newer.UnrepairableReason)
mergedTorrent.UnrepairableReason = strings.Join(reasons.ToSlice(), ", ")
// selected files
mergedTorrent.SelectedFiles = cmap.New[*File]()
newer.SelectedFiles.IterCb(func(key string, file *File) {
mergedTorrent.SelectedFiles.SetIfAbsent(key, file)
})
older.SelectedFiles.IterCb(func(key string, olderFile *File) {
file, ok := mergedTorrent.SelectedFiles.Get(key)
if !ok || (file.State.Is("broken_file") && olderFile.State.Is("ok_file")) {
mergedTorrent.SelectedFiles.Set(key, olderFile)
}
// get the file again, set the media info
file, ok = mergedTorrent.SelectedFiles.Get(key)
if ok && file.MediaInfo == nil && olderFile.MediaInfo != nil {
file.MediaInfo = olderFile.MediaInfo
}
})
// unassigned links
mergedTorrent.UnassignedLinks = mapset.NewSet[string]()
links := newer.UnassignedLinks.Union(older.UnassignedLinks)
links.Each(func(link string) bool {
found := false
mergedTorrent.SelectedFiles.IterCb(func(key string, file *File) {
if !found && file.Link == link {
found = true
}
})
if !found {
mergedTorrent.UnassignedLinks.Add(link)
}
return false
})
brokenCount := 0
okCount := 0
mergedTorrent.SelectedFiles.IterCb(func(key string, file *File) {
if !utils.IsVideo(file.Path) && !t.IsPlayable(file.Path) {
return
}
if file.State.Is("broken_file") {
brokenCount++
} else if file.State.Is("ok_file") {
okCount++
}
})
if brokenCount == 0 && okCount > 0 {
mergedTorrent.State.Event(context.Background(), "mark_as_repaired")
}
t.log.Debugf("After merging, torrent %s has %d broken file(s)", t.GetKey(mergedTorrent), brokenCount)
return mergedTorrent
}
func (t *TorrentManager) assignDirectory(tor *Torrent, triggerHook bool, outputLogs bool) {
accessKey := t.GetKey(tor)
t.DirectoryMap.IterCb(func(directory string, torrents cmap.ConcurrentMap[string, *Torrent]) {
if strings.HasPrefix(directory, "int__") || directory == config.DUMPED_TORRENTS {
return
}
torrents.Remove(accessKey)
})
torrentIDs := tor.DownloadedIDs.ToSlice()
// get filenames needed for directory conditions
var filenames []string
var fileSizes []int64
var mediaInfos []*ffprobe.ProbeData
unplayable := true
tor.SelectedFiles.IterCb(func(key string, file *File) {
filenames = append(filenames, filepath.Base(file.Path))
fileSizes = append(fileSizes, file.Bytes)
if file.MediaInfo != nil {
mediaInfos = append(mediaInfos, file.MediaInfo)
}
if utils.IsVideo(file.Path) || t.IsPlayable(file.Path) {
unplayable = false
}
})
if unplayable {
if outputLogs {
t.log.Warnf("No playable files for %s, moving to unplayable directory", accessKey)
}
t.markAsUnplayable(tor)
return
}
// Map torrents to directories
switch t.Config.GetVersion() {
case "v1":
updatedPaths := []string{}
dirs := []string{}
configV1 := t.Config.(*config.ZurgConfigV1)
for _, directories := range configV1.GetGroupMap() {
for _, directory := range directories {
if t.Config.MeetsConditions(directory, t.GetKey(tor), tor.ComputeTotalSize(), torrentIDs, filenames, fileSizes, mediaInfos) {
torrents, _ := t.DirectoryMap.Get(directory)
torrents.Set(accessKey, tor)
if directory != config.ALL_TORRENTS {
dirs = append(dirs, directory)
}
if triggerHook {
updatedPaths = append(updatedPaths, fmt.Sprintf("%s/%s", directory, accessKey))
}
break
}
}
}
if triggerHook {
OnLibraryUpdateHook(updatedPaths, t.Config, t.log)
}
if outputLogs {
t.log.Infof("Assigned %s to: %s", accessKey, strings.Join(dirs, ", "))
}
}
}
func (t *TorrentManager) IsPlayable(filePath string) bool {
playableExts := t.Config.GetPlayableExtensions()
filePath = strings.ToLower(filePath)
for _, ext := range playableExts {
if strings.HasSuffix(filePath, fmt.Sprintf(".%s", ext)) {
return true
}
}
return false
}