sonda/internal/smart/smart.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

758 lines
26 KiB
Go

// Package smart keeps the smart playlists of each user: playlists that are a set of rules instead of a
// list of songs, worked out again every time they are opened, so the songs that arrive and what the
// listener plays change them by themselves.
//
// A smart playlist is made of Rules (every rule that is set must hold), an order and a limit. Only that is
// stored. The songs come from the playable songs of the library, then from the history and the taste of the
// owner, the way the mixes are made (see package mixes): nothing here contacts anyone, and a smart playlist
// that belongs to somebody else is as if it did not exist (ErrNotFound).
//
// "Random" is not new at every request: like a mix it stays the same for a day, and a variant number asks
// for another.
package smart
import (
"context"
"errors"
"fmt"
"hash/fnv"
"regexp"
"slices"
"sort"
"strings"
"time"
"unicode/utf8"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/mixes"
"git.kmalloc.org/squid/sonda/internal/taste"
)
// Limits. They keep one user from filling the database and one request from doing too much.
const (
MaxNameLen = 200
MaxDescriptionLen = 2000
MaxListed = 50 // genres, artists, albums or formats in one rule
MaxDays = 36_500
MaxPlays = 1_000_000
MaxBitrateKbps = 100_000
MaxDurationSec = 86_400
MinYear = 1000 // the first and the last year a rule can name
MaxYear = 2999
DefaultLimit = 50
MaxLimit = 500
MaxPlaylists = 200 // smart playlists of one user
MaxVariant = mixes.MaxVariant
DefaultPageLimit = 50
MaxPageLimit = 200
)
// Errors returned by the service and the store.
var (
ErrInvalidInput = errors.New("invalid input")
ErrNotFound = errors.New("smart playlist not found")
ErrTooMany = errors.New("limit reached")
)
// Sort is the order of the songs of a smart playlist, before the limit cuts the end.
type Sort string
// The orders. A tie always goes to the lower song id.
const (
SortRandom Sort = "random"
SortMostPlayed Sort = "most_played"
SortLeastPlayed Sort = "least_played"
SortRecentlyAdded Sort = "recently_added"
SortTitle Sort = "title"
)
func (s Sort) valid() bool {
switch s {
case SortRandom, SortMostPlayed, SortLeastPlayed, SortRecentlyAdded, SortTitle:
return true
}
return false
}
// Rules say which songs a smart playlist takes. A rule that is not set (empty, false or 0) does not count;
// every rule that is set must hold. The songs of a list rule match when they are by one of the artists, in
// one of the albums, have one of the genres or are in one of the formats.
type Rules struct {
// Genres are kept as they are compared: lower case, with "+", "-", "_" and "/" taken for spaces
// ("jazz+funk" and "jazz-funk" are the same genre).
Genres []string `json:"genres,omitempty"`
NotGenres []string `json:"not_genres,omitempty"`
// Artists are the main artists of the song.
ArtistIDs []int64 `json:"artist_ids,omitempty"`
NotArtistIDs []int64 `json:"not_artist_ids,omitempty"`
AlbumIDs []int64 `json:"album_ids,omitempty"`
NotAlbumIDs []int64 `json:"not_album_ids,omitempty"`
// Formats are those of the files ("flac", "mpeg"), in lower case. A song counts when a file of it, that is
// not missing, has one of them (and, with MinBitrateKbps, that bitrate or more).
Formats []string `json:"formats,omitempty"`
MinBitrateKbps int `json:"min_bitrate_kbps,omitempty"`
// AddedWithinDays is about the date of the file, which is the best the index knows.
AddedWithinDays int `json:"added_within_days,omitempty"`
// The listening rules are about the owner's history: a listen counts when the play was completed or lasted
// the minimum listen of the server, and a skip when it came before that.
NeverPlayed bool `json:"never_played,omitempty"`
PlayedWithinDays int `json:"played_within_days,omitempty"`
NotPlayedWithinDays int `json:"not_played_within_days,omitempty"`
MinPlays int `json:"min_plays,omitempty"`
// PlaysWithinDays counts only the plays of the last N days where plays are counted: the minimum of plays and
// the most and least played orders. It does not change the other listening rules.
PlaysWithinDays int `json:"plays_within_days,omitempty"`
SkippedWithinDays int `json:"skipped_within_days,omitempty"`
NotSkippedWithinDays int `json:"not_skipped_within_days,omitempty"`
// LikedArtistsOnly keeps the songs of artists the owner likes; WithoutAvoidedArtists leaves out the ones
// the owner avoids (see package taste).
LikedArtistsOnly bool `json:"liked_artists_only,omitempty"`
WithoutAvoidedArtists bool `json:"without_avoided_artists,omitempty"`
MinDurationSec int `json:"min_duration_sec,omitempty"`
MaxDurationSec int `json:"max_duration_sec,omitempty"`
// MinYear and MaxYear are about the year the song came out, from the tags of its file: both limits count
// (1980 to 1989 is the eighties). A song whose file has no year never matches a year rule.
MinYear int `json:"min_year,omitempty"`
MaxYear int `json:"max_year,omitempty"`
}
// SmartPlaylist is a smart playlist.
type SmartPlaylist struct {
ID int64
Name string
Description string
Rules Rules
Sort Sort
Limit int
CreatedAt time.Time
UpdatedAt time.Time
}
// Input is what makes a smart playlist, or the preview of one. A zero Sort is random and a zero Limit is
// DefaultLimit.
type Input struct {
Name string
Description string
Rules Rules
Sort Sort
Limit int
}
// Patch changes the smart playlist in the fields that are not nil. Rules replace the old ones whole.
type Patch struct {
Name *string
Description *string
Rules *Rules
Sort *Sort
Limit *int
}
// History is what one listener did with one song.
type History = mixes.History
// Candidate is a playable song the rules may take, with what they need to know of it.
type Candidate struct {
TrackID int64
ArtistID int64 // the main artist, 0 when there is none
Title string
DurationMs int64
AddedAt time.Time // the date of its newest file that is not missing
}
// Filter is the part of the rules that the index answers: every list that is set narrows the songs.
// Genres are spelled as the files have them.
type Filter struct {
Genres, NotGenres []string
ArtistIDs, NotArtistIDs []int64
AlbumIDs, NotAlbumIDs []int64
Formats []string
MinBitrateKbps int
MinYear, MaxYear int // 0 is no limit
}
// Store keeps the smart playlists and reads what they are made of. Every call that is about one playlist is
// for one user and gives ErrNotFound for a playlist that does not exist or is not theirs.
type Store interface {
// Create keeps a playlist (its ID is ignored), or gives ErrTooMany when the user has MaxPlaylists.
Create(ctx context.Context, userID int64, p SmartPlaylist, now time.Time) (SmartPlaylist, error)
// List returns a page of the user's smart playlists, the one changed last first, and how many there are.
List(ctx context.Context, userID int64, limit, offset int) ([]SmartPlaylist, int, error)
Get(ctx context.Context, userID, id int64) (SmartPlaylist, error)
// Update replaces name, description, rules, order and limit.
Update(ctx context.Context, userID, id int64, p SmartPlaylist, now time.Time) (SmartPlaylist, error)
Delete(ctx context.Context, userID, id int64) error
// Genres returns every genre of the playable songs, as spelled in the files.
Genres(ctx context.Context) ([]mixes.Genre, error)
// Candidates returns the playable songs of the filter.
Candidates(ctx context.Context, f Filter) ([]Candidate, error)
// History returns what the user did with the songs they did anything with; minListen is how long a
// play must last to count as a listen.
History(ctx context.Context, userID int64, minListen time.Duration) (map[int64]History, error)
// Plays returns how many listens the user has of each song since a moment, for the songs they listened to.
Plays(ctx context.Context, userID int64, minListen time.Duration, since time.Time) (map[int64]int, error)
// Tracks returns the songs in the order given, leaving out any that cannot be played.
Tracks(ctx context.Context, ids []int64) ([]catalog.Track, error)
// AlbumCovers returns, for the songs in the order given, the albums that have a cover, each once, up to limit.
AlbumCovers(ctx context.Context, trackIDs []int64, limit int) ([]int64, error)
}
// Taster says what the listener likes: *taste.Service.
type Taster interface {
Learn(ctx context.Context, userID int64) (taste.Learned, error)
}
// Service validates what it is given, keeps the smart playlists and works their songs out.
type Service struct {
store Store
taster Taster
minListen time.Duration
now func() time.Time
}
// NewService builds a Service. minListen is how long a play must last to count as a listen.
func NewService(store Store, taster Taster, minListen time.Duration) *Service {
return &Service{store: store, taster: taster, minListen: minListen, now: time.Now}
}
func invalid(format string, a ...any) error {
return fmt.Errorf("%w: %s", ErrInvalidInput, fmt.Sprintf(format, a...))
}
func cleanName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" || utf8.RuneCountInString(name) > MaxNameLen {
return "", invalid("the name must have 1 to %d characters", MaxNameLen)
}
return name, nil
}
func cleanDescription(d string) (string, error) {
d = strings.TrimSpace(d)
if utf8.RuneCountInString(d) > MaxDescriptionLen {
return "", invalid("the description can have up to %d characters", MaxDescriptionLen)
}
return d, nil
}
var formatRe = regexp.MustCompile(`^[a-z0-9]{1,16}$`)
func cleanGenres(rule string, in []string) ([]string, error) {
if len(in) > MaxListed {
return nil, invalid("%s can have up to %d genres", rule, MaxListed)
}
var out []string
for _, g := range in {
n := mixes.NormalizeGenre(g)
if n == "" {
return nil, invalid("%q is not a genre", g)
}
if !slices.Contains(out, n) {
out = append(out, n)
}
}
return out, nil
}
func cleanFormats(in []string) ([]string, error) {
if len(in) > MaxListed {
return nil, invalid("formats can have up to %d items", MaxListed)
}
var out []string
for _, f := range in {
f = strings.ToLower(strings.TrimSpace(f))
if !formatRe.MatchString(f) {
return nil, invalid("%q is not a format", f)
}
if !slices.Contains(out, f) {
out = append(out, f)
}
}
return out, nil
}
func cleanIDs(rule string, in []int64) ([]int64, error) {
if len(in) > MaxListed {
return nil, invalid("%s can have up to %d ids", rule, MaxListed)
}
var out []int64
for _, id := range in {
if id < 1 {
return nil, invalid("%s must be ids, from 1", rule)
}
if !slices.Contains(out, id) {
out = append(out, id)
}
}
return out, nil
}
func inRange(rule string, n, max int) error {
if n < 0 || n > max {
return invalid("%s must be from 0 to %d", rule, max)
}
return nil
}
// cleanRules checks the rules and returns them in the form they are kept in.
func cleanRules(r Rules) (Rules, error) {
var err error
if r.Genres, err = cleanGenres("genres", r.Genres); err != nil {
return Rules{}, err
}
if r.NotGenres, err = cleanGenres("not_genres", r.NotGenres); err != nil {
return Rules{}, err
}
for _, l := range []struct {
name string
ids *[]int64
}{{"artist_ids", &r.ArtistIDs}, {"not_artist_ids", &r.NotArtistIDs}, {"album_ids", &r.AlbumIDs}, {"not_album_ids", &r.NotAlbumIDs}} {
if *l.ids, err = cleanIDs(l.name, *l.ids); err != nil {
return Rules{}, err
}
}
if r.Formats, err = cleanFormats(r.Formats); err != nil {
return Rules{}, err
}
for _, n := range []struct {
name string
got, max int
}{
{"min_bitrate_kbps", r.MinBitrateKbps, MaxBitrateKbps},
{"added_within_days", r.AddedWithinDays, MaxDays},
{"played_within_days", r.PlayedWithinDays, MaxDays},
{"not_played_within_days", r.NotPlayedWithinDays, MaxDays},
{"skipped_within_days", r.SkippedWithinDays, MaxDays},
{"not_skipped_within_days", r.NotSkippedWithinDays, MaxDays},
{"min_plays", r.MinPlays, MaxPlays},
{"plays_within_days", r.PlaysWithinDays, MaxDays},
{"min_duration_sec", r.MinDurationSec, MaxDurationSec},
{"max_duration_sec", r.MaxDurationSec, MaxDurationSec},
} {
if err := inRange(n.name, n.got, n.max); err != nil {
return Rules{}, err
}
}
if r.MaxDurationSec > 0 && r.MinDurationSec > r.MaxDurationSec {
return Rules{}, invalid("min_duration_sec is more than max_duration_sec")
}
for _, y := range []struct {
name string
got int
}{{"min_year", r.MinYear}, {"max_year", r.MaxYear}} {
if y.got != 0 && (y.got < MinYear || y.got > MaxYear) {
return Rules{}, invalid("%s must be 0 or a year from %d to %d", y.name, MinYear, MaxYear)
}
}
if r.MinYear > 0 && r.MaxYear > 0 && r.MinYear > r.MaxYear {
return Rules{}, invalid("min_year is more than max_year")
}
return r, nil
}
// cleanShape checks the order and the limit and gives them their defaults.
func cleanShape(sortBy Sort, limit int) (Sort, int, error) {
if sortBy == "" {
sortBy = SortRandom
}
if !sortBy.valid() {
return "", 0, invalid("sort must be random, most_played, least_played, recently_added or title")
}
if limit == 0 {
limit = DefaultLimit
}
if limit < 1 || limit > MaxLimit {
return "", 0, invalid("limit must be from 1 to %d", MaxLimit)
}
return sortBy, limit, nil
}
// clean checks everything but the name, which a preview does not have.
func clean(in Input) (Input, error) {
var err error
if in.Description, err = cleanDescription(in.Description); err != nil {
return Input{}, err
}
if in.Rules, err = cleanRules(in.Rules); err != nil {
return Input{}, err
}
if in.Sort, in.Limit, err = cleanShape(in.Sort, in.Limit); err != nil {
return Input{}, err
}
return in, nil
}
// Create keeps a smart playlist for the user.
func (s *Service) Create(ctx context.Context, userID int64, in Input) (SmartPlaylist, error) {
name, err := cleanName(in.Name)
if err != nil {
return SmartPlaylist{}, err
}
in, err = clean(in)
if err != nil {
return SmartPlaylist{}, err
}
return s.store.Create(ctx, userID, SmartPlaylist{Name: name, Description: in.Description, Rules: in.Rules, Sort: in.Sort, Limit: in.Limit}, s.now())
}
// Listing is a page of smart playlists.
type Listing struct {
Items []SmartPlaylist
Total int
Limit int
Offset int
}
// List returns a page of the user's smart playlists, the one changed last first. A limit of 0 is
// DefaultPageLimit, and one above MaxPageLimit is lowered to it, as for the playlists.
func (s *Service) List(ctx context.Context, userID int64, limit, offset int) (Listing, error) {
if limit < 0 || offset < 0 {
return Listing{}, invalid("limit and offset cannot be negative")
}
switch {
case limit == 0:
limit = DefaultPageLimit
case limit > MaxPageLimit:
limit = MaxPageLimit
}
items, total, err := s.store.List(ctx, userID, limit, offset)
if err != nil {
return Listing{}, err
}
return Listing{Items: items, Total: total, Limit: limit, Offset: offset}, nil
}
// Get returns a smart playlist of the user, without its songs.
func (s *Service) Get(ctx context.Context, userID, id int64) (SmartPlaylist, error) {
return s.store.Get(ctx, userID, id)
}
// Update changes the fields of the patch that are not nil.
func (s *Service) Update(ctx context.Context, userID, id int64, p Patch) (SmartPlaylist, error) {
cur, err := s.store.Get(ctx, userID, id)
if err != nil {
return SmartPlaylist{}, err
}
in := Input{Name: cur.Name, Description: cur.Description, Rules: cur.Rules, Sort: cur.Sort, Limit: cur.Limit}
if p.Name != nil {
in.Name = *p.Name
}
if p.Description != nil {
in.Description = *p.Description
}
if p.Rules != nil {
in.Rules = *p.Rules
}
if p.Sort != nil {
in.Sort = *p.Sort
}
if p.Limit != nil {
in.Limit = *p.Limit
}
if in.Name, err = cleanName(in.Name); err != nil {
return SmartPlaylist{}, err
}
if in, err = clean(in); err != nil {
return SmartPlaylist{}, err
}
return s.store.Update(ctx, userID, id, SmartPlaylist{Name: in.Name, Description: in.Description, Rules: in.Rules, Sort: in.Sort, Limit: in.Limit}, s.now())
}
// GenreCount is a genre as it is compared (see Rules) with the number of playable songs that have it.
type GenreCount struct {
Name string
Tracks int
}
// Genres returns the genres of the library to choose from in a rule, the one with most songs first, and
// by name among equals. The spellings the files have are one genre; "other" and the like are left out.
func (s *Service) Genres(ctx context.Context) ([]GenreCount, error) {
all, err := s.store.Genres(ctx)
if err != nil {
return nil, fmt.Errorf("read genres: %w", err)
}
byName := map[string]int{}
for _, g := range all {
if n := mixes.NormalizeGenre(g.Name); n != "" {
byName[n] += g.Tracks
}
}
out := make([]GenreCount, 0, len(byName))
for n, c := range byName {
out = append(out, GenreCount{n, c})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Tracks != out[j].Tracks {
return out[i].Tracks > out[j].Tracks
}
return out[i].Name < out[j].Name
})
return out, nil
}
// Delete removes a smart playlist of the user.
func (s *Service) Delete(ctx context.Context, userID, id int64) error {
return s.store.Delete(ctx, userID, id)
}
// Tracks works the songs of a smart playlist out. variant 0 is the one of the day; with a random order,
// another number gives other songs.
func (s *Service) Tracks(ctx context.Context, userID, id int64, variant int) (SmartPlaylist, []catalog.Track, error) {
if err := checkVariant(variant); err != nil {
return SmartPlaylist{}, nil, err
}
p, err := s.store.Get(ctx, userID, id)
if err != nil {
return SmartPlaylist{}, nil, err
}
tracks, err := s.run(ctx, userID, p.ID, p.Rules, p.Sort, p.Limit, variant)
return p, tracks, err
}
// Preview works the songs out for rules that are not kept, to try them before saving.
func (s *Service) Preview(ctx context.Context, userID int64, in Input, variant int) ([]catalog.Track, error) {
if err := checkVariant(variant); err != nil {
return nil, err
}
in, err := clean(in)
if err != nil {
return nil, err
}
return s.run(ctx, userID, 0, in.Rules, in.Sort, in.Limit, variant)
}
func checkVariant(v int) error {
if v < 0 || v > MaxVariant {
return invalid("variant must be from 0 to %d", MaxVariant)
}
return nil
}
// spellings returns the spellings the files have of the genres (all compared as normalized).
func spellings(all []mixes.Genre, genres []string) []string {
var out []string
for _, g := range all {
if slices.Contains(genres, mixes.NormalizeGenre(g.Name)) {
out = append(out, g.Name)
}
}
return out
}
// run works the songs out: the rules, the order and the limit, then the details of the songs.
func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort, limit, variant int) ([]catalog.Track, error) {
picked, err := s.pick(ctx, userID, id, r, order, limit, variant)
if err != nil {
return nil, err
}
tracks, err := s.store.Tracks(ctx, picked)
if err != nil {
return nil, fmt.Errorf("read songs: %w", err)
}
return tracks, nil
}
// pick works out which songs the rules give, in order, as their ids.
func (s *Service) pick(ctx context.Context, userID, id int64, r Rules, order Sort, limit, variant int) ([]int64, error) {
f := Filter{
ArtistIDs: r.ArtistIDs, NotArtistIDs: r.NotArtistIDs, AlbumIDs: r.AlbumIDs, NotAlbumIDs: r.NotAlbumIDs,
Formats: r.Formats, MinBitrateKbps: r.MinBitrateKbps, MinYear: r.MinYear, MaxYear: r.MaxYear,
}
if len(r.Genres) > 0 || len(r.NotGenres) > 0 {
all, err := s.store.Genres(ctx)
if err != nil {
return nil, fmt.Errorf("read genres: %w", err)
}
f.Genres, f.NotGenres = spellings(all, r.Genres), spellings(all, r.NotGenres)
if len(r.Genres) > 0 && len(f.Genres) == 0 {
return []int64{}, nil // no file has any of the genres
}
}
cands, err := s.store.Candidates(ctx, f)
if err != nil {
return nil, fmt.Errorf("read the songs: %w", err)
}
countsPlays := order == SortMostPlayed || order == SortLeastPlayed || r.MinPlays > 0
var history map[int64]History
if (countsPlays && r.PlaysWithinDays == 0) || r.NeverPlayed ||
r.PlayedWithinDays > 0 || r.NotPlayedWithinDays > 0 || r.SkippedWithinDays > 0 || r.NotSkippedWithinDays > 0 {
if history, err = s.store.History(ctx, userID, s.minListen); err != nil {
return nil, fmt.Errorf("read history: %w", err)
}
}
// The plays that are counted: all of them, or only those of the window.
plays := func(id int64) int { return history[id].Plays }
if countsPlays && r.PlaysWithinDays > 0 {
window, err := s.store.Plays(ctx, userID, s.minListen, s.now().Add(-time.Duration(r.PlaysWithinDays)*24*time.Hour))
if err != nil {
return nil, fmt.Errorf("read plays: %w", err)
}
plays = func(id int64) int { return window[id] }
}
var learned taste.Learned
if r.LikedArtistsOnly || r.WithoutAvoidedArtists {
if learned, err = s.taster.Learn(ctx, userID); err != nil {
return nil, fmt.Errorf("learn taste: %w", err)
}
}
now := s.now()
within := func(t time.Time, days int) bool {
return !t.IsZero() && now.Sub(t) <= time.Duration(days)*24*time.Hour
}
kept := make([]Candidate, 0, len(cands))
for _, c := range cands {
h := history[c.TrackID]
switch {
case r.AddedWithinDays > 0 && !within(c.AddedAt, r.AddedWithinDays),
r.MinDurationSec > 0 && c.DurationMs < int64(r.MinDurationSec)*1000,
r.MaxDurationSec > 0 && c.DurationMs > int64(r.MaxDurationSec)*1000,
r.NeverPlayed && h.Plays > 0,
r.PlayedWithinDays > 0 && !within(h.LastPlayed, r.PlayedWithinDays),
r.NotPlayedWithinDays > 0 && within(h.LastPlayed, r.NotPlayedWithinDays),
r.MinPlays > 0 && plays(c.TrackID) < r.MinPlays,
r.SkippedWithinDays > 0 && !within(h.SkippedAt, r.SkippedWithinDays),
r.NotSkippedWithinDays > 0 && within(h.SkippedAt, r.NotSkippedWithinDays),
r.LikedArtistsOnly && learned.Prefs[c.ArtistID].Preference <= 0,
r.WithoutAvoidedArtists && learned.Prefs[c.ArtistID].Preference < 0:
continue
}
kept = append(kept, c)
}
sortCandidates(kept, order, plays, func(c Candidate) uint64 {
h := fnv.New64a()
fmt.Fprintf(h, "%d|%d|%d|%d|%d", userID, id, now.Unix()/86400, variant, c.TrackID)
return h.Sum64()
})
if len(kept) > limit {
kept = kept[:limit]
}
picked := make([]int64, len(kept))
for i, c := range kept {
picked[i] = c.TrackID
}
return picked, nil
}
// MaxCoverAlbums is how many albums make the picture of a smart playlist.
const MaxCoverAlbums = 4
// Covers says which albums stand for a smart playlist: up to MaxCoverAlbums albums that have a cover, in the order of the
// songs it gives now (the ones of variant), each once. It is the picture of the playlist, and is worked out apart from its
// songs so that a list of playlists need not wait for all of them.
func (s *Service) Covers(ctx context.Context, userID, id int64, variant int) ([]int64, error) {
if err := checkVariant(variant); err != nil {
return nil, err
}
p, err := s.store.Get(ctx, userID, id)
if err != nil {
return nil, err
}
picked, err := s.pick(ctx, userID, p.ID, p.Rules, p.Sort, p.Limit, variant)
if err != nil {
return nil, err
}
return s.albumCovers(ctx, picked)
}
func (s *Service) albumCovers(ctx context.Context, picked []int64) ([]int64, error) {
if len(picked) == 0 {
return []int64{}, nil
}
albums, err := s.store.AlbumCovers(ctx, picked, MaxCoverAlbums)
if err != nil {
return nil, fmt.Errorf("read covers: %w", err)
}
if albums == nil {
albums = []int64{}
}
return albums, nil
}
// sortCandidates puts the songs in the order; a tie goes to the lower id. A random order sorts by the
// hash of the song with the seed of the day, which is the same until the day or the variant changes.
func sortCandidates(c []Candidate, order Sort, plays func(int64) int, hash func(Candidate) uint64) {
var keys map[int64]uint64
if order == SortRandom {
keys = make(map[int64]uint64, len(c))
for _, x := range c {
keys[x.TrackID] = hash(x)
}
}
less := func(a, b Candidate) int {
switch order {
case SortRandom:
if ka, kb := keys[a.TrackID], keys[b.TrackID]; ka != kb {
if ka < kb {
return -1
}
return 1
}
case SortMostPlayed, SortLeastPlayed:
pa, pb := plays(a.TrackID), plays(b.TrackID)
if order == SortLeastPlayed {
pa, pb = pb, pa
}
if pa != pb {
if pa > pb {
return -1
}
return 1
}
case SortRecentlyAdded:
if !a.AddedAt.Equal(b.AddedAt) {
if a.AddedAt.After(b.AddedAt) {
return -1
}
return 1
}
case SortTitle:
if a.Title != b.Title {
if a.Title < b.Title {
return -1
}
return 1
}
}
switch {
case a.TrackID < b.TrackID:
return -1
case a.TrackID > b.TrackID:
return 1
}
return 0
}
sort.SliceStable(c, func(i, j int) bool { return less(c[i], c[j]) < 0 })
}
// Summary says the rules in a few words of English, for the facts about a list that a name is made from. Artists
// and albums are ids and say nothing to a reader, so they are left out.
func (r Rules) Summary() string {
var parts []string
add := func(cond bool, format string, a ...any) {
if cond {
parts = append(parts, fmt.Sprintf(format, a...))
}
}
add(len(r.Genres) > 0, "genres: %s", strings.Join(r.Genres, ", "))
add(len(r.NotGenres) > 0, "not genres: %s", strings.Join(r.NotGenres, ", "))
add(len(r.Formats) > 0, "formats: %s", strings.Join(r.Formats, ", "))
add(r.MinBitrateKbps > 0, "at least %d kbps", r.MinBitrateKbps)
add(r.AddedWithinDays > 0, "added in the last %d days", r.AddedWithinDays)
add(r.NeverPlayed, "never played")
add(r.PlayedWithinDays > 0, "played in the last %d days", r.PlayedWithinDays)
add(r.NotPlayedWithinDays > 0, "not played for %d days", r.NotPlayedWithinDays)
add(r.MinPlays > 0, "played at least %d times", r.MinPlays)
add(r.PlaysWithinDays > 0, "plays counted over the last %d days", r.PlaysWithinDays)
add(r.SkippedWithinDays > 0, "skipped in the last %d days", r.SkippedWithinDays)
add(r.NotSkippedWithinDays > 0, "not skipped in the last %d days", r.NotSkippedWithinDays)
add(r.LikedArtistsOnly, "only liked artists")
add(r.WithoutAvoidedArtists, "without avoided artists")
add(r.MinDurationSec > 0, "at least %d minutes long", r.MinDurationSec/60)
add(r.MaxDurationSec > 0, "at most %d minutes long", r.MaxDurationSec/60)
add(r.MinYear > 0, "from %d", r.MinYear)
add(r.MaxYear > 0, "up to %d", r.MaxYear)
return strings.Join(parts, "; ")
}