package torrent import ( "context" "fmt" "math" "strings" "sync" "time" "github.com/debridmediamanager/zurg/internal/config" "github.com/debridmediamanager/zurg/pkg/realdebrid" mapset "github.com/deckarep/golang-set/v2" cmap "github.com/orcaman/concurrent-map/v2" ) const ( EXPIRED_LINK_TOLERANCE_HOURS = 24 ) func (t *TorrentManager) StartRepairJob() { if !t.Config.EnableRepair() { t.log.Debug("Repair is disabled, skipping repair job") return } t.repairTrigger = make(chan *Torrent) t.repairQueue = mapset.NewSet[*Torrent]() // there is 1 repair worker, with max 1 blocking task go func() { t.log.Debug("Starting periodic repair job") repairTicker := time.NewTicker(time.Duration(t.Config.GetRepairEveryMins()) * time.Minute) defer repairTicker.Stop() for { select { case <-repairTicker.C: t.invokeRepair(nil) case torrent := <-t.repairTrigger: // On-demand trigger with a specific torrent t.invokeRepair(torrent) case <-t.RepairKillSwitch: t.log.Info("Stopping periodic repair job") return } } }() } func (t *TorrentManager) invokeRepair(torrent *Torrent) { t.repairRunningMu.Lock() if t.repairRunning { t.repairRunningMu.Unlock() t.repairQueue.Add(torrent) // don't do anything if repair is already running return } t.repairRunning = true t.repairRunningMu.Unlock() // Execute the repair job t.repairAll(torrent) // After repair is done t.repairRunningMu.Lock() t.repairRunning = false t.repairRunningMu.Unlock() // before we let go, let's check repairQueue t.workerPool.Submit(func() { queuedTorrent, exists := t.repairQueue.Pop() if exists { t.TriggerRepair(queuedTorrent) } }) } // TriggerRepair allows an on-demand repair to be initiated. func (t *TorrentManager) TriggerRepair(torrent *Torrent) { t.repairTrigger <- torrent } func (t *TorrentManager) repairAll(torrent *Torrent) { // todo: a more elegant way to do this var haystack cmap.ConcurrentMap[string, *Torrent] if torrent == nil { haystack, _ = t.DirectoryMap.Get(INT_ALL) t.log.Debug("Periodic repair started; searching for broken torrents") } else { haystack = cmap.New[*Torrent]() haystack.Set("", torrent) } // collect all torrents that need to be repaired toRepair := mapset.NewSet[*Torrent]() var wg sync.WaitGroup haystack.IterCb(func(_ string, torrent *Torrent) { wg.Add(1) _ = t.workerPool.Submit(func() { defer wg.Done() if torrent.UnrepairableReason != "" { return } // check 1: for broken files brokenFileCount := 0 torrent.SelectedFiles.IterCb(func(_ string, file *File) { if file.State.Is("broken_file") { brokenFileCount++ } }) if brokenFileCount > 0 { t.log.Debugf("Torrent %s has %d/%d broken files, adding to repair list", t.GetKey(torrent), brokenFileCount, torrent.SelectedFiles.Count()) toRepair.Add(torrent) return } // check 2: for unassigned links (this means the torrent has started to deteriorate) unassignedCount := torrent.UnassignedLinks.Cardinality() if unassignedCount > 0 { t.log.Debugf("Torrent %s has %d unassigned links, adding to repair list", t.GetKey(torrent), unassignedCount) toRepair.Add(torrent) return } }) }) wg.Wait() toRepair.Each(func(torrent *Torrent) bool { wg.Add(1) t.Repair(torrent, &wg) return false }) wg.Wait() t.log.Infof("Finished periodic repair sequence for %d broken torrent(s)", toRepair.Cardinality()) } func (t *TorrentManager) Repair(torrent *Torrent, wg *sync.WaitGroup) { // blocks for approx 45 minutes if active torrents are full if !t.canCapacityHandle() { t.log.Error("Blocked for too long due to limit of active torrents, cannot continue with the repair") wg.Done() return } // assign to a worker _ = t.workerPool.Submit(func() { defer wg.Done() if err := torrent.State.Event(context.Background(), "repair_torrent"); err != nil { t.log.Errorf("Failed to mark torrent %s as under repair: %v", t.GetKey(torrent), err) return } t.repair(torrent) }) } func (t *TorrentManager) repair(torrent *Torrent) { torrentIDs := torrent.Components.Keys() t.log.Infof("Started repair process for torrent %s (ids=%v)", t.GetKey(torrent), torrentIDs) // handle torrents with incomplete links for selected files // torrent can be rar'ed by RD, so we need to check for that if torrent.UnassignedLinks.Cardinality() > 0 && !t.assignUnassignedLinks(torrent) { return } // get all broken files brokenFiles, allBroken := getBrokenFiles(torrent) // first step: redownload the whole torrent t.log.Debugf("Torrent %s has %d broken files (out of %d), repairing by redownloading whole torrent", t.GetKey(torrent), len(brokenFiles), torrent.SelectedFiles.Count()) info, err := t.redownloadTorrent(torrent, []string{}) // reinsert the whole torrent, passing empty selection if info != nil && info.Progress == 100 && !t.isStillBroken(info, brokenFiles) { // successful repair if err := torrent.State.Event(context.Background(), "mark_as_repaired"); err != nil { t.log.Errorf("Cannot repair torrent %s: %v", torrent.Hash, err) return } // delete old torrents torrent.Components.IterCb(func(id string, _ *realdebrid.TorrentInfo) { if id != info.ID { t.api.DeleteTorrent(id) } }) t.log.Infof("Successfully repaired torrent %s by redownloading all files", t.GetKey(torrent)) return } else if info != nil && info.Progress != 100 { t.log.Infof("Torrent %s is still in progress after redownloading but it should be repaired once done", t.GetKey(torrent)) return } if err != nil { t.log.Warnf("Cannot repair torrent %s by redownloading all files (error=%s)", t.GetKey(torrent), err.Error()) } else { t.log.Warnf("Cannot repair torrent %s by redownloading all files", t.GetKey(torrent)) } if torrent.UnrepairableReason != "" { t.log.Debugf("Torrent %s has been marked as unfixable during redownload (%s), ending repair process early", t.GetKey(torrent), torrent.UnrepairableReason) return } // second step: download just the broken files if len(brokenFiles) == 1 && allBroken { // if all files are broken, we can't do anything! t.log.Warnf("Torrent %s has only 1 cached file and it's broken; marking as unfixable (to fix, select other files)", t.GetKey(torrent)) t.markAsUnfixable(torrent, "the lone cached file is broken") return } t.log.Infof("Torrent %s will be repaired by downloading %d batches of the %d broken files", int(math.Ceil(float64(len(brokenFiles))/100)), len(brokenFiles), t.GetKey(torrent)) newlyDownloadedIds := make([]string, 0) batchNum := 1 brokenFileIDs := getFileIDs(brokenFiles) var group []string for _, fileIDStr := range brokenFileIDs { group = append(group, fileIDStr) if len(group) >= 100 { t.log.Debugf("Downloading batch %d of broken files of torrent %s", batchNum, t.GetKey(torrent)) batchNum++ redownloadedInfo, err := t.redownloadTorrent(torrent, group) if err != nil { t.log.Warnf("Cannot repair torrent %s by downloading broken files (error=%s) giving up", t.GetKey(torrent), err.Error()) for _, newId := range newlyDownloadedIds { t.trash(newId) } return } newlyDownloadedIds = append(newlyDownloadedIds, redownloadedInfo.ID) group = make([]string, 0) } } t.log.Debugf("Downloading last batch of broken files of torrent %s", t.GetKey(torrent)) if len(group) > 0 { redownloadedInfo, err := t.redownloadTorrent(torrent, group) if err != nil { t.log.Warnf("Cannot repair torrent %s by downloading broken files (error=%s) giving up", t.GetKey(torrent), err.Error()) for _, newId := range newlyDownloadedIds { t.trash(newId) } return } newlyDownloadedIds = append(newlyDownloadedIds, redownloadedInfo.ID) } for _, newId := range newlyDownloadedIds { t.trashOnceCompleted(newId) } } func (t *TorrentManager) assignUnassignedLinks(torrent *Torrent) bool { unassignedTotal := torrent.UnassignedLinks.Cardinality() t.log.Infof("Trying to assign %d links to the %d selected of incomplete torrent %s", unassignedTotal, torrent.SelectedFiles.Count(), t.GetKey(torrent)) // handle torrents with incomplete links for selected files assignedCount := 0 expiredCount := 0 rarCount := 0 unassignedCount := 0 newUnassignedLinks := cmap.New[*realdebrid.Download]() torrent.UnassignedLinks.Each(func(link string) bool { // unrestrict each unassigned link that was filled out during torrent init unrestrict := t.UnrestrictLinkUntilOk(link) if unrestrict == nil { expiredCount++ return false // next unassigned link } // try to assign to a selected file assigned := false torrent.SelectedFiles.IterCb(func(_ string, file *File) { // base it on size because why not? if !assigned && file.State.Is("broken_file") && file.Bytes == unrestrict.Filesize && strings.HasSuffix(strings.ToLower(file.Path), strings.ToLower(unrestrict.Filename)) { file.Link = link if strings.HasPrefix(file.Link, "https://real-debrid.com/d/") { file.Link = file.Link[0:39] } if err := file.State.Event(context.Background(), "repair_file"); err != nil { t.log.Errorf("Failed to mark file %s as repaired: %v", file.Path, err) return } assigned = true assignedCount++ } }) if !assigned { // if not assigned and is a rar, likely it was rar'ed by RD if strings.HasSuffix(strings.ToLower(unrestrict.Filename), ".rar") { rarCount++ } else { t.log.Warnf("Cannot assign %s to any file in torrent %s", unrestrict.Filename, t.GetKey(torrent)) } newUnassignedLinks.Set(link, unrestrict) } processedCount := assignedCount + unassignedCount + expiredCount if processedCount%10 == 0 || processedCount == unassignedTotal { t.log.Infof("Processed %d out of %d links (%d expired) to broken torrent %s", processedCount, unassignedTotal, expiredCount, t.GetKey(torrent)) } return false // next unassigned link }) // magnet:?xt=urn:btih:ba8720dde2472e650a87efbb78efb4fbcea3f7ee // empty/reset the unassigned links as we have assigned them already if unassignedTotal > 0 { torrent.UnassignedLinks = mapset.NewSet[string]() t.writeTorrentToFile(torrent) } // this is a rar'ed torrent, nothing we can do if assignedCount == 0 && rarCount == 1 { if t.Config.ShouldDeleteRarFiles() { t.log.Warnf("Torrent %s is rar'ed and we cannot repair it, deleting it as configured", t.GetKey(torrent)) t.Delete(t.GetKey(torrent), true) } else { t.log.Warnf("Torrent %s is rar'ed and we cannot repair it", t.GetKey(torrent)) newUnassignedLinks.IterCb(func(_ string, unassigned *realdebrid.Download) { // if unassigned == nil { // return // } newFile := &File{ File: realdebrid.File{ ID: 0, Path: unassigned.Filename, Bytes: unassigned.Filesize, Selected: 0, }, Ended: torrent.Added, Link: unassigned.Link, State: NewFileState("ok_file"), } torrent.SelectedFiles.Set(unassigned.Filename, newFile) }) torrent.UnassignedLinks = mapset.NewSet[string]() t.markAsUnfixable(torrent, "rar'ed by RD") t.markAsUnplayable(torrent, "rar'ed by RD") if err := torrent.State.Event(context.Background(), "mark_as_repaired"); err != nil { t.log.Errorf("Cannot repair torrent %s: %v", torrent.Hash, err) } } return false // end repair } return true } func (t *TorrentManager) redownloadTorrent(torrent *Torrent, selection []string) (*realdebrid.TorrentInfo, error) { // broken files means broken links // if brokenFiles is not provided, we will redownload all files finalSelection := strings.Join(selection, ",") if len(selection) == 0 { torrent.SelectedFiles.IterCb(func(_ string, file *File) { selection = append(selection, fmt.Sprintf("%d", file.ID)) }) if len(selection) == 0 { return nil, nil } else { finalSelection = strings.Join(selection, ",") } } // redownload torrent resp, err := t.api.AddMagnetHash(torrent.Hash) if err != nil { if strings.Contains(err.Error(), "infringing") { t.markAsUnfixable(torrent, "infringing torrent") } else if strings.Contains(err.Error(), "unsupported") { t.markAsUnfixable(torrent, "unsupported torrent") } else if strings.Contains(err.Error(), "unavailable") { t.markAsUnfixable(torrent, "unavailable torrent") } else if strings.Contains(err.Error(), "invalid") { t.markAsUnfixable(torrent, "invalid torrent") } else if strings.Contains(err.Error(), "big") { t.markAsUnfixable(torrent, "torrent too big") } else if strings.Contains(err.Error(), "allowed") { t.markAsUnfixable(torrent, "torrent not allowed") } return nil, fmt.Errorf("cannot redownload torrent: %v", err) } newTorrentID := resp.ID // sleep for 1 second to let RD process the magnet time.Sleep(1 * time.Second) var info *realdebrid.TorrentInfo for { // select files err = t.api.SelectTorrentFiles(newTorrentID, finalSelection) if err != nil { t.trash(newTorrentID) return nil, fmt.Errorf("cannot start redownloading torrent %s (id=%s): %v", t.GetKey(torrent), newTorrentID, err) } // sleep for 2 second to let RD process the magnet time.Sleep(2 * time.Second) // see if the torrent is ready info, err = t.api.GetTorrentInfo(newTorrentID) if err != nil { t.trash(newTorrentID) return nil, fmt.Errorf("cannot get info on redownloaded torrent %s (id=%s) : %v", t.GetKey(torrent), newTorrentID, err) } if info.Status == "magnet_conversion" { time.Sleep(60 * time.Second) continue } else if info.Status == "waiting_files_selection" { time.Sleep(10 * time.Second) return nil, fmt.Errorf("torrent %s (id=%s) is stuck on waiting_files_selection", t.GetKey(torrent), newTorrentID) } break } // documented status: magnet_error, magnet_conversion, waiting_files_selection, queued, downloading, downloaded, error, virus, compressing, uploading, dead isOkStatus := false okStatuses := []string{"downloading", "downloaded", "uploading", "queued", "compressing"} // not compressing because we need playable files for _, status := range okStatuses { if info.Status == status { isOkStatus = true break } } if !isOkStatus { t.trash(info.ID) return nil, fmt.Errorf("the redownloaded torrent %s is in a non-OK state: %s", t.GetKey(torrent), info.Status) } // check if incorrect number of links if info.Progress == 100 && len(info.Links) != len(selection) { t.trash(newTorrentID) return nil, fmt.Errorf("torrent %s only got %d links but we need %d", t.GetKey(torrent), len(info.Links), len(selection)) } t.log.Infof("Redownloading torrent %s successful (id=%s, progress=%d)", t.GetKey(torrent), info.ID, info.Progress) return info, nil } func (t *TorrentManager) canCapacityHandle() bool { // max waiting time is 45 minutes const maxRetries = 50 const baseDelay = 1 * time.Second const maxDelay = 60 * time.Second retryCount := 0 for { count, err := t.api.GetActiveTorrentCount() if err != nil { t.log.Warnf("Cannot get active downloads count: %v", err) if retryCount >= maxRetries { t.log.Error("Max retries reached. Exiting.") return false } delay := time.Duration(math.Pow(2, float64(retryCount))) * baseDelay if delay > maxDelay { delay = maxDelay } time.Sleep(delay) retryCount++ continue } if count.DownloadingCount < count.MaxNumberOfTorrents-1 { return true } delay := time.Duration(math.Pow(2, float64(retryCount))) * baseDelay if delay > maxDelay { delay = maxDelay } t.log.Infof("We have reached the max number of active torrents, waiting for %s seconds before retrying", delay) if retryCount >= maxRetries { t.log.Error("Max retries reached. Exiting.") return false } time.Sleep(delay) retryCount++ } } func (t *TorrentManager) markAsUnplayable(torrent *Torrent, reason string) { t.log.Warnf("Torrent %s is unplayable (reason: %s), moving to unplayable directory", t.GetKey(torrent), reason) // reassign to unplayable torrents directory t.DirectoryMap.IterCb(func(directory string, torrents cmap.ConcurrentMap[string, *Torrent]) { if strings.HasPrefix(directory, "int__") { return } torrents.Remove(t.GetKey(torrent)) }) torrents, _ := t.DirectoryMap.Get(config.UNPLAYABLE_TORRENTS) torrents.Set(t.GetKey(torrent), torrent) } func (t *TorrentManager) markAsUnfixable(torrent *Torrent, reason string) { t.log.Warnf("Marking torrent %s as unfixable - %s", t.GetKey(torrent), reason) torrent.UnrepairableReason = reason t.writeTorrentToFile(torrent) } // getBrokenFiles returns the files that are not http links and not deleted func getBrokenFiles(torrent *Torrent) ([]*File, bool) { var brokenFiles []*File allBroken := true torrent.SelectedFiles.IterCb(func(_ string, file *File) { if file.State.Is("broken_file") { brokenFiles = append(brokenFiles, file) } else { allBroken = false } }) return brokenFiles, allBroken } // isStillBroken checks if the torrent is still broken // if it's not broken anymore, it will assign the links to the files func (t *TorrentManager) isStillBroken(info *realdebrid.TorrentInfo, brokenFiles []*File) bool { var selectedFiles []*File for _, file := range info.Files { if file.Selected == 0 { continue } selectedFiles = append(selectedFiles, &File{ File: file, Ended: info.Ended, Link: "", 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] if strings.HasPrefix(file.Link, "https://real-debrid.com/d/") { file.Link = file.Link[0:39] } if err := file.State.Event(context.Background(), "repair_file"); err != nil { t.log.Errorf("Failed to mark file %s as repaired: %v", file.Path, err) return true } } } else { // if we can't assign links then it's still broken return true } if len(brokenFiles) == 0 { // just check for the last file brokenFiles = append(brokenFiles, selectedFiles[len(selectedFiles)-1]) } // check if the broken files can now be unrestricted for _, oldFile := range brokenFiles { for idx, newFile := range selectedFiles { if oldFile.Bytes == newFile.Bytes { unrestrict := t.UnrestrictFileUntilOk(selectedFiles[idx]) if unrestrict == nil || oldFile.Bytes != unrestrict.Filesize { return true } } } } return false }