package library import ( "context" "errors" "fmt" "log/slog" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) // ErrTrackPresent means a track asked to be forgotten has its file: it plays, // and forgetting it would throw away a track the library still holds. var ErrTrackPresent = errors.New("library: track has its file") // ForgottenTrack is one track Forget removed, named for the audit log. type ForgottenTrack struct { ID pgtype.UUID Title string FilePath string } // ForgetMissingTracks removes tracks that wait for a file and that an admin // has given up on: each row goes with its likes, plays and playlist places, // and an album or artist it leaves empty goes too. There is no file to // delete. It is all or nothing: if any of ids is unknown (ErrTrackNotFound) or // has its file (ErrTrackPresent), nothing is forgotten. // // dataDir, when set, also clears the cached art of an artist that went. func ForgetMissingTracks( ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, ids []pgtype.UUID, ) ([]ForgottenTrack, error) { if logger == nil { logger = slog.Default() } var gone []ForgottenTrack var emptiedArtists []pgtype.UUID err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { tq := dbq.New(tx) rows, err := tq.LockTracksForForget(ctx, ids) if err != nil { return fmt.Errorf("lock tracks: %w", err) } if len(rows) != len(uniqueUUIDs(ids)) { return ErrTrackNotFound } for _, r := range rows { if !r.MissingSince.Valid { return ErrTrackPresent } } for _, r := range rows { if _, err := tq.DeleteTrack(ctx, r.ID); err != nil { return fmt.Errorf("delete track: %w", err) } out, err := tidyEmptiedAlbum(ctx, tq, r.AlbumID) if err != nil { return err } if out.ArtistID != nil { emptiedArtists = append(emptiedArtists, *out.ArtistID) } gone = append(gone, ForgottenTrack{ID: r.ID, Title: r.Title, FilePath: r.FilePath}) } return nil }) if err != nil { return nil, err } // After the commit, so neither can undo a forget that happened: an // unlogged change leaves the track in offline clients' caches until the // next scan, and leftover art is only disk. for _, t := range gone { if err := syncpkg.LogChange(ctx, pool, syncpkg.EntityTrack, syncpkg.FormatUUID(t.ID), syncpkg.OpDelete); err != nil { logger.Warn("forget: LogChange failed", "track_id", syncpkg.FormatUUID(t.ID), "err", err) } } if dataDir != "" { for _, a := range emptiedArtists { if err := coverart.CleanupArtistArt(dataDir, a); err != nil { logger.Warn("forget: artist-art cleanup failed", "artist_id", syncpkg.FormatUUID(a), "err", err) } } } return gone, nil } func uniqueUUIDs(ids []pgtype.UUID) map[pgtype.UUID]bool { out := make(map[pgtype.UUID]bool, len(ids)) for _, id := range ids { out[id] = true } return out }