package qbittorrent import ( "context" "errors" "fmt" "log/slog" "os" "path" "git.kmsign.ru/royalcat/tstor/pkg/qbittorrent" "git.kmsign.ru/royalcat/tstor/pkg/rlog" ) func (d *Daemon) Cleanup(ctx context.Context, run bool) ([]string, error) { d.log.Info(ctx, "cleanup started") torrentInfos, err := d.client.qb.Torrent().GetTorrents(ctx, &qbittorrent.TorrentOption{}) if err != nil { d.log.Error(ctx, "failed to get torrents", rlog.Error(err)) return nil, fmt.Errorf("failed to get torrents: %w", err) } torrentToDelete := make([]string, 0, 5) for _, info := range torrentInfos { if d.registeredTorrents.Contains(info.Hash) { continue } d.log.Info(ctx, "torrent not found in registry", slog.String("infohash", info.Hash)) torrentToDelete = append(torrentToDelete, info.Hash) } d.log.Info(ctx, "marked torrents to delete", slog.Int("count", len(torrentToDelete)), slog.Any("infohashes", torrentToDelete), ) if !run { d.log.Info(ctx, "dry run, skipping deletion") return torrentToDelete, nil } err = d.client.qb.Torrent().DeleteTorrents(ctx, torrentToDelete, true) if err != nil { d.log.Error(ctx, "failed to delete torrents", slog.Any("infohashes", torrentToDelete), rlog.Error(err)) return nil, fmt.Errorf("failed to delete torrents: %w", err) } d.log.Info(ctx, "torrents deleted from qbittorrent", slog.Int("count", len(torrentToDelete))) for _, hash := range torrentToDelete { torrentPath := path.Join(d.dataDir, hash) _, err := os.Stat(torrentPath) if errors.Is(err, os.ErrNotExist) { continue } if err != nil { d.log.Error(ctx, "failed to get torrent path", slog.String("path", torrentPath), rlog.Error(err)) continue } d.log.Warn(ctx, "leftover data for torrent detected, cleaning up", slog.String("infohash", hash), slog.String("path", torrentPath)) } return torrentToDelete, nil }