package torrent import ( "os" mapset "github.com/deckarep/golang-set/v2" ) const BINS_FILE = "data/bins.json" // initializeBins reads from bins.json and assigns values to t.trashBin and t.repairBin func (t *TorrentManager) initializeBins() { if _, err := os.Stat(BINS_FILE); os.IsNotExist(err) { t.repairLog.Info("data/bins.json does not exist. Initializing empty bins.") return } fileData, err := os.ReadFile(BINS_FILE) if err != nil { t.repairLog.Errorf("Failed to read bins.json file: %v Initializing empty bins.", err) return } data := map[string][]string{} err = json.Unmarshal(fileData, &data) if err != nil { t.repairLog.Errorf("Failed to unmarshal bin data: %v Initializing empty bins.", err) return } t.OnceDoneBin = mapset.NewSet[string](data["repair_bin"]...) t.repairLog.Debugf("These IDs will be deleted after completion: %v", t.OnceDoneBin.ToSlice()) } func (t *TorrentManager) persistBins() { data := map[string]interface{}{ "repair_bin": t.OnceDoneBin.ToSlice(), // Assuming repairBin is a mapset.Set[string] } jsonData, err := json.Marshal(data) if err != nil { t.repairLog.Errorf("Failed to marshal bin data: %v", err) return } file, err := os.Create(BINS_FILE) if err != nil { t.repairLog.Errorf("Failed to create bins.json file: %v", err) return } defer file.Close() _, err = file.Write(jsonData) if err != nil { t.repairLog.Errorf("Failed to write to bins.json file: %v", err) } } func (t *TorrentManager) willDeleteOnceDone(torrentId string) { t.repairLog.Debugf("Torrent id=%s will be deleted once it is completed", torrentId) t.OnceDoneBin.Add(torrentId) t.persistBins() } func (t *TorrentManager) cleanupBins(freshIDs mapset.Set[string]) { 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() } // deleteOnceDone checks if the torrent is in the OnceDoneBin and deletes it if it is. // returns true if the torrent was in the bin and was deleted, false otherwise func (t *TorrentManager) deleteOnceDone(completedTorrentId string, failed bool) { if !t.OnceDoneBin.ContainsOne(completedTorrentId) { return } t.DeleteByID(completedTorrentId) t.OnceDoneBin.Remove(completedTorrentId) if failed { t.repairLog.Infof("Deleting torrent id=%s early because it has encountered an error", completedTorrentId) } else { t.repairLog.Debugf("Deleting unnecessary torrent id=%s", completedTorrentId) } t.persistBins() }