package storage import ( "context" "database/sql" "errors" "fmt" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/feedback" ) // FeedbackRepo stores what users decided about artists. It implements feedback.Store. type FeedbackRepo struct{ db *bun.DB } // NewFeedbackRepo builds a FeedbackRepo. func NewFeedbackRepo(db *bun.DB) *FeedbackRepo { return &FeedbackRepo{db: db} } // seenBy returns feedback.ErrArtistNotFound unless the user can see the artist: it has // music to play, or a provider named it, or the user marked it themselves. Another // user's mark does not count, or the answer would tell what others marked. func seenBy(ctx context.Context, tx bun.Tx, userID, artistID int64) error { var one int err := tx.QueryRowContext(ctx, "SELECT 1 FROM artists a WHERE a.id = ? AND ("+playableArtist("a.id")+" OR "+discoveredArtist("a.id")+ " OR EXISTS (SELECT 1 FROM artist_feedback f WHERE f.artist_id = a.id AND f.user_id = ?))", artistID, userID).Scan(&one) if err != nil { return mapNoRows(err, feedback.ErrArtistNotFound, "check artist") } return nil } // Mark records the decision, replacing the other kind. The first date is kept when // the same kind is marked again. func (r *FeedbackRepo) Mark(ctx context.Context, userID, artistID int64, kind feedback.Kind, at time.Time) error { return r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { // Artists are removed by the cleanup of replaced lists: take its turn, or the // artist could go, and the mark with it, a moment after it was seen here. if err := lockArtistWrites(ctx, tx); err != nil { return err } var one int if err := tx.QueryRowContext(ctx, "SELECT 1 FROM users WHERE id = ?", userID).Scan(&one); err != nil { return mapNoRows(err, feedback.ErrUserNotFound, "check user") } if err := seenBy(ctx, tx, userID, artistID); err != nil { return err } if _, err := tx.ExecContext(ctx, `INSERT INTO artist_feedback (user_id, artist_id, kind, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (user_id, artist_id) DO UPDATE SET created_at = CASE WHEN artist_feedback.kind = excluded.kind THEN artist_feedback.created_at ELSE excluded.created_at END, kind = excluded.kind`, userID, artistID, string(kind), at.Unix()); err != nil { return fmt.Errorf("write feedback: %w", err) } return nil }) } // Unmark removes the decision of that kind. When it was the last mark of an artist // that only a provider named and nobody names any more, the artist goes too: the // marks were all that kept it. func (r *FeedbackRepo) Unmark(ctx context.Context, userID, artistID int64, kind feedback.Kind) error { return r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { if err := lockArtistWrites(ctx, tx); err != nil { return err } if err := seenBy(ctx, tx, userID, artistID); err != nil { return err } if _, err := tx.ExecContext(ctx, "DELETE FROM artist_feedback WHERE user_id = ? AND artist_id = ? AND kind = ?", userID, artistID, string(kind)); err != nil { return fmt.Errorf("remove feedback: %w", err) } _, err := removeUnnamedArtists(ctx, tx, true, "id = ? AND ", artistID) return err }) } // List returns the user's artists of one kind, newest first. func (r *FeedbackRepo) List(ctx context.Context, userID int64, kind feedback.Kind, limit, offset int) ([]feedback.Entry, int, error) { var total int if err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM artist_feedback WHERE user_id = ? AND kind = ?", userID, string(kind)).Scan(&total); err != nil { return nil, 0, fmt.Errorf("count feedback: %w", err) } out := []feedback.Entry{} if offset >= total { return out, total, nil } rows, err := r.db.QueryContext(ctx, `SELECT a.id, a.name, `+playableArtist("a.id")+`, f.created_at FROM artist_feedback f JOIN artists a ON a.id = f.artist_id WHERE f.user_id = ? AND f.kind = ? ORDER BY f.created_at DESC, a.id LIMIT ? OFFSET ?`, userID, string(kind), limit, offset) if err != nil { return nil, 0, fmt.Errorf("list feedback: %w", err) } defer rows.Close() for rows.Next() { var ( e feedback.Entry at int64 ) if err := rows.Scan(&e.Artist.ID, &e.Artist.Name, &e.InLibrary, &at); err != nil { return nil, 0, err } e.At = time.Unix(at, 0) out = append(out, e) } return out, total, rows.Err() } // Marks returns every decision of the user, by artist. func (r *FeedbackRepo) Marks(ctx context.Context, userID int64) (map[int64]feedback.Kind, error) { rows, err := r.db.QueryContext(ctx, "SELECT artist_id, kind FROM artist_feedback WHERE user_id = ?", userID) if err != nil { return nil, fmt.Errorf("read feedback: %w", err) } defer rows.Close() out := map[int64]feedback.Kind{} for rows.Next() { var ( id int64 kind string ) if err := rows.Scan(&id, &kind); err != nil { return nil, err } out[id] = feedback.Kind(kind) } return out, rows.Err() } // mapNoRows turns "no row" into the given error and wraps any other failure. func mapNoRows(err, notFound error, what string) error { if errors.Is(err, sql.ErrNoRows) { return notFound } return fmt.Errorf("%s: %w", what, err) }