diff --git a/internal/config/config.go b/internal/config/config.go index 84bca76..13750a4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -12,6 +12,13 @@ import ( "sync" ) +type RepairStrategy string + +const ( + RepairStrategyPerFile RepairStrategy = "per_file" + RepairStrategyPerTorrent RepairStrategy = "per_torrent" +) + var ( instance *Config once sync.Once @@ -60,13 +67,14 @@ type Arr struct { } type Repair struct { - Enabled bool `json:"enabled,omitempty"` - Interval string `json:"interval,omitempty"` - ZurgURL string `json:"zurg_url,omitempty"` - AutoProcess bool `json:"auto_process,omitempty"` - UseWebDav bool `json:"use_webdav,omitempty"` - Workers int `json:"workers,omitempty"` - ReInsert bool `json:"reinsert,omitempty"` + Enabled bool `json:"enabled,omitempty"` + Interval string `json:"interval,omitempty"` + ZurgURL string `json:"zurg_url,omitempty"` + AutoProcess bool `json:"auto_process,omitempty"` + UseWebDav bool `json:"use_webdav,omitempty"` + Workers int `json:"workers,omitempty"` + ReInsert bool `json:"reinsert,omitempty"` + Strategy RepairStrategy `json:"strategy,omitempty"` } type Auth struct { @@ -352,6 +360,11 @@ func (c *Config) setDefaults() { c.URLBase += "/" } + // Set repair defaults + if c.Repair.Strategy == "" { + c.Repair.Strategy = RepairStrategyPerTorrent + } + // Load the auth file c.Auth = c.GetAuth() } diff --git a/pkg/arr/arr.go b/pkg/arr/arr.go index 9b77cec..5934d5f 100644 --- a/pkg/arr/arr.go +++ b/pkg/arr/arr.go @@ -115,8 +115,10 @@ func (a *Arr) Validate() error { if err != nil { return err } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("arr test failed: %s", resp.Status) + defer resp.Body.Close() + // If response is not 200 or 404(this is the case for Lidarr, etc), return an error + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("failed to validate arr %s: %s", a.Name, resp.Status) } return nil } diff --git a/pkg/debrid/providers/alldebrid/alldebrid.go b/pkg/debrid/providers/alldebrid/alldebrid.go index c41748f..0430b87 100644 --- a/pkg/debrid/providers/alldebrid/alldebrid.go +++ b/pkg/debrid/providers/alldebrid/alldebrid.go @@ -309,7 +309,7 @@ func (ad *AllDebrid) GetFileDownloadLinks(t *types.Torrent) error { errCh <- err return } - if link != nil { + if link == nil { errCh <- fmt.Errorf("download link is empty") return } diff --git a/pkg/debrid/providers/alldebrid/types.go b/pkg/debrid/providers/alldebrid/types.go index bcc1130..2f0d418 100644 --- a/pkg/debrid/providers/alldebrid/types.go +++ b/pkg/debrid/providers/alldebrid/types.go @@ -1,5 +1,10 @@ package alldebrid +import ( + "encoding/json" + "fmt" +) + type errorResponse struct { Code string `json:"code"` Message string `json:"message"` @@ -32,6 +37,8 @@ type magnetInfo struct { Files []MagnetFile `json:"files"` } +type Magnets []magnetInfo + type TorrentInfoResponse struct { Status string `json:"status"` Data struct { @@ -43,7 +50,7 @@ type TorrentInfoResponse struct { type TorrentsListResponse struct { Status string `json:"status"` Data struct { - Magnets []magnetInfo `json:"magnets"` + Magnets Magnets `json:"magnets"` } `json:"data"` Error *errorResponse `json:"error"` } @@ -81,3 +88,27 @@ type DownloadLink struct { } `json:"data"` Error *errorResponse `json:"error"` } + +// UnmarshalJSON implements custom unmarshaling for Magnets type +// It can handle both an array of magnetInfo objects or a map with string keys. +// If the input is an array, it will be unmarshaled directly into the Magnets slice. +// If the input is a map, it will extract the values and append them to the Magnets slice. +// If the input is neither, it will return an error. +func (m *Magnets) UnmarshalJSON(data []byte) error { + // Try to unmarshal as array + var arr []magnetInfo + if err := json.Unmarshal(data, &arr); err == nil { + *m = arr + return nil + } + + // Try to unmarshal as map + var obj map[string]magnetInfo + if err := json.Unmarshal(data, &obj); err == nil { + for _, v := range obj { + *m = append(*m, v) + } + return nil + } + return fmt.Errorf("magnets: unsupported JSON format") +} diff --git a/pkg/debrid/store/refresh.go b/pkg/debrid/store/refresh.go index 2682441..8d42d87 100644 --- a/pkg/debrid/store/refresh.go +++ b/pkg/debrid/store/refresh.go @@ -136,15 +136,7 @@ func (c *Cache) refreshRclone() error { return nil } - client := &http.Client{ - Timeout: 60 * time.Second, - Transport: &http.Transport{ - MaxIdleConns: 10, - IdleConnTimeout: 60 * time.Second, - DisableCompression: false, - MaxIdleConnsPerHost: 5, - }, - } + client := http.DefaultClient // Create form data data := c.buildRcloneRequestData() diff --git a/pkg/debrid/store/repair.go b/pkg/debrid/store/repair.go index b807f27..dccf0d8 100644 --- a/pkg/debrid/store/repair.go +++ b/pkg/debrid/store/repair.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/sirrobot01/decypharr/internal/config" "github.com/sirrobot01/decypharr/internal/utils" "github.com/sirrobot01/decypharr/pkg/debrid/types" "sync" @@ -60,6 +61,7 @@ func (c *Cache) markAsSuccessfullyReinserted(torrentId string) { func (c *Cache) GetBrokenFiles(t *CachedTorrent, filenames []string) []string { files := make(map[string]types.File) + repairStrategy := config.Get().Repair.Strategy brokenFiles := make([]string, 0) if len(filenames) > 0 { for name, f := range t.Files { @@ -93,6 +95,10 @@ func (c *Cache) GetBrokenFiles(t *CachedTorrent, filenames []string) []string { ctx, cancel := context.WithCancel(context.Background()) defer cancel() + // Use a mutex to protect brokenFiles slice and torrent-wide failure flag + var mu sync.Mutex + torrentWideFailed := false + wg.Add(len(files)) for _, f := range files { @@ -106,14 +112,33 @@ func (c *Cache) GetBrokenFiles(t *CachedTorrent, filenames []string) []string { } if f.Link == "" { - cancel() + mu.Lock() + if repairStrategy == config.RepairStrategyPerTorrent { + torrentWideFailed = true + mu.Unlock() + cancel() // Signal all other goroutines to stop + return + } else { + // per_file strategy - only mark this file as broken + brokenFiles = append(brokenFiles, f.Name) + } + mu.Unlock() return } if err := c.client.CheckLink(f.Link); err != nil { if errors.Is(err, utils.HosterUnavailableError) { - cancel() // Signal all other goroutines to stop - return + mu.Lock() + if repairStrategy == config.RepairStrategyPerTorrent { + torrentWideFailed = true + mu.Unlock() + cancel() // Signal all other goroutines to stop + return + } else { + // per_file strategy - only mark this file as broken + brokenFiles = append(brokenFiles, f.Name) + } + mu.Unlock() } } }(f) @@ -121,12 +146,14 @@ func (c *Cache) GetBrokenFiles(t *CachedTorrent, filenames []string) []string { wg.Wait() - // If context was cancelled, mark all files as broken - if ctx.Err() != nil { + // Handle the result based on strategy + if repairStrategy == config.RepairStrategyPerTorrent && torrentWideFailed { + // Mark all files as broken for per_torrent strategy for _, f := range files { brokenFiles = append(brokenFiles, f.Name) } } + // For per_file strategy, brokenFiles already contains only the broken ones // Try to reinsert the torrent if it's broken if len(brokenFiles) > 0 && t.Torrent != nil { diff --git a/pkg/repair/misc.go b/pkg/repair/misc.go index bc36088..f7f0569 100644 --- a/pkg/repair/misc.go +++ b/pkg/repair/misc.go @@ -88,6 +88,8 @@ func collectFiles(media arr.Content) map[string][]arr.ContentFile { func (r *Repair) checkTorrentFiles(torrentPath string, files []arr.ContentFile, clients map[string]types.Client, caches map[string]*store.Cache) []arr.ContentFile { brokenFiles := make([]arr.ContentFile, 0) + emptyFiles := make([]arr.ContentFile, 0) + r.logger.Debug().Msgf("Checking %s", torrentPath) // Get the debrid client @@ -95,17 +97,18 @@ func (r *Repair) checkTorrentFiles(torrentPath string, files []arr.ContentFile, debridName := r.findDebridForPath(dir, clients) if debridName == "" { r.logger.Debug().Msgf("No debrid found for %s. Skipping", torrentPath) - return files // Return all files as broken if no debrid found + return emptyFiles } cache, ok := caches[debridName] if !ok { r.logger.Debug().Msgf("No cache found for %s. Skipping", debridName) - return files // Return all files as broken if no cache found + return emptyFiles } tor, ok := r.torrentsMap.Load(debridName) if !ok { r.logger.Debug().Msgf("Could not find torrents for %s. Skipping", debridName) + return emptyFiles } torrentsMap := tor.(map[string]store.CachedTorrent) @@ -114,8 +117,9 @@ func (r *Repair) checkTorrentFiles(torrentPath string, files []arr.ContentFile, torrentName := filepath.Clean(filepath.Base(torrentPath)) torrent, ok := torrentsMap[torrentName] if !ok { - r.logger.Debug().Msgf("No torrent found for %s. Skipping", torrentName) - return files // Return all files as broken if torrent not found + r.logger.Debug().Msgf("Can't find torrent %s in %s. Marking as broken", torrentName, debridName) + // Return all files as broken + return files } // Batch check files diff --git a/pkg/store/torrent.go b/pkg/store/torrent.go index 61e39d9..57bac5d 100644 --- a/pkg/store/torrent.go +++ b/pkg/store/torrent.go @@ -9,6 +9,7 @@ import ( "github.com/sirrobot01/decypharr/internal/utils" debridTypes "github.com/sirrobot01/decypharr/pkg/debrid" "github.com/sirrobot01/decypharr/pkg/debrid/types" + "math" "os" "path/filepath" "time" @@ -207,6 +208,9 @@ func (s *Store) partialTorrentUpdate(t *Torrent, debridTorrent *types.Torrent) * } totalSize := debridTorrent.Bytes progress := (cmp.Or(debridTorrent.Progress, 0.0)) / 100.0 + if math.IsNaN(progress) || math.IsInf(progress, 0) { + progress = 0 + } sizeCompleted := int64(float64(totalSize) * progress) var speed int64 diff --git a/pkg/web/templates/config.html b/pkg/web/templates/config.html index eb1999e..45dad9e 100644 --- a/pkg/web/templates/config.html +++ b/pkg/web/templates/config.html @@ -337,6 +337,14 @@