feat(smart): the songs I play most, in rotation lately and over the year
- A smart playlist rule, plays_within_days, that counts only the plays of the last N days where plays are counted: the minimum of plays and the most and least played orders. The other listening rules are not changed. - Two more suggested smart playlists on it: on-rotation (the most played of the last 30 days, at least twice) and top-year (the same over 365 days). most-played stays as the plays of all time. - The editor has the new rule and the page says it in words. Texts in English and Italian.
This commit is contained in:
parent
322b6e5530
commit
bf5c108785
14 changed files with 297 additions and 28 deletions
|
|
@ -22,7 +22,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Artist photos.** `GET /artists/{id}/image` serves a free picture of an artist from Wikimedia Commons, and `GET /artists/{id}/image/credit` says whose it is and under which licence, which you must show next to it. Only free licences are kept (public domain, CC0, CC BY, CC BY-SA): non-commercial, no-derivatives, fair-use and unknown ones are refused, because Sonda stores a copy (`?size=small` is 300 pixels, `large` 1000) in the data folder. With the `commons` provider and the `musicbrainz` one switched on, Sonda follows ids and never a name: the artist's MusicBrainz id, the Wikidata item MusicBrainz links to it, the picture Wikidata names for it, and Commons for its licence. Many artists will have none. Kept for 30 days (a week when there is none) and removed, files included, with the provider's data. To look for the pictures of the whole library in one go, an admin starts a background job like a scan: `POST /library/artist-images` (follow it with `GET /library/artist-images`, stop it with `DELETE /library/artist-images`; `?refresh=true` searches every artist again). It only goes through artists that have a MusicBrainz id, never replaces a picture by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
|
||||
- **Album covers.** `GET /albums/{id}/cover` serves the cover of an album from your own files: the picture embedded in them, or else a `cover`, `folder`, `front`, `album` or `albumart` image in the album's folder. It is built the first time it is asked for (a few at a time), scaled (`?size=small` is 300 pixels, `large` 1000) and kept in the data folder (`storage.data_dir`, you can delete it: covers are built again). A picture you replace in a folder is noticed within a week, or at once after a full rescan. When your files have no picture at all and an admin switched on the `coverartarchive` provider, the cover is asked from the Cover Art Archive by the MusicBrainz release group id that the tags of the album's files carry (`MUSICBRAINZ_RELEASEGROUPID`; run a full rescan to read it for music you already indexed); your own files always come first, and only that id leaves the server. An album whose files have no id is looked up in MusicBrainz by its artist and title when the `musicbrainz` provider is on too (see the list of what leaves your server). For an album split in `CD1`/`Disc 2` folders, the picture in the folder above is used. Nothing is sent anywhere unless you switched on the `coverartarchive` provider (see [External providers](#external-providers)). It also takes `?access_token=`, so an `<img>` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off).
|
||||
- **Mixes.** `GET /mixes` lists playlists that Sonda makes for you, like the mixes of a streaming service, from what you listen to and from the genres of your music: one mix for each genre of your library that has at least 30 songs by 4 artists (the genres you play most first), and, once you have some listening history, *Your favourites* and *Rediscover* (artists you like and have not played for a month); *New to you* is the songs you never played. `GET /mixes/{id}` gives a mix of up to 50 songs, at most 3 by one artist and never two of the same artist in a row. They are picked by weighted chance: the artists you play weigh more and songs you skipped lately or artists you avoid are left out. A mix stays the same for a day, and `?variant=2` gives another; `POST /mixes/{id}/playlist` keeps the one you are looking at as a playlist of your own. A mix is worked out when you ask for it, from your own history and the genre tags of your files: nothing is stored and nothing is sent to a provider. The id of a genre mix has the genre in it (`genre:hard rock`), so it is percent-encoded in the path. Each mix says which albums stand for it (`album_ids`: up to 4 albums that have a cover, by different artists, with most of the songs the mix draws from), for a picture made of their covers; the covers are the ones the library already has, so a mix has a picture once the covers of its albums were looked up (browsing the albums, or the covers job), and none is fetched for it.
|
||||
- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times, skipped or not skipped lately, only artists you like or without the ones you avoid, and the length of the song. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `never-played`, `most-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. The year of a song is not in the index yet, so there is no rule about it. A user can have 200.
|
||||
- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times (optionally counting only the plays of the last N days, which is what makes the songs in rotation lately and the top of the year), skipped or not skipped lately, only artists you like or without the ones you avoid, and the length of the song. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `on-rotation`, `top-year`, `most-played`, `never-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and `on-rotation` is the songs you played most in the last 30 days and `top-year` the same over a year, so they change as you listen; a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. The year of a song is not in the index yet, so there is no rule about it. A user can have 200.
|
||||
- **Playlists.** `POST /playlists` makes a playlist (a name and an optional description) and `GET /playlists` lists yours, the one changed last first. `POST /playlists/{id}/tracks` adds 1 to 500 tracks at the end or at a `position`, `GET /playlists/{id}/tracks` lists them in order, `PATCH /playlists/{id}/tracks/{item}` moves one and `DELETE` takes one out; `PATCH /playlists/{id}` renames and `DELETE /playlists/{id}` deletes (the tracks stay in the library). A track can be in a playlist more than once, which is why each place has its own item id. A playlist is yours alone: someone else's answers `playlist_not_found`, as one that does not exist. A track whose files were deleted or moved away stays in the playlist and shows `available: false`; it plays again when the files come back and a scan finds them. A user can have 1000 playlists of up to 10000 tracks. Nothing is shared and nothing leaves your server.
|
||||
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
|
||||
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
|
||||
|
|
|
|||
|
|
@ -291,7 +291,7 @@ func TestSuggestedSmartPlaylistsAreThereForEveryoneWithTheirRules(t *testing.T)
|
|||
s := x.(map[string]any)
|
||||
byKey[s["key"].(string)] = s
|
||||
}
|
||||
for _, key := range []string{"recently-added", "never-played", "most-played", "forgotten", "high-quality", "long-tracks"} {
|
||||
for _, key := range []string{"recently-added", "on-rotation", "top-year", "most-played", "never-played", "forgotten", "high-quality", "long-tracks"} {
|
||||
if byKey[key] == nil {
|
||||
t.Errorf("%s is missing from %v", key, byKey)
|
||||
}
|
||||
|
|
@ -348,3 +348,52 @@ func TestASuggestedSmartPlaylistIsKeptAsAPlaylist(t *testing.T) {
|
|||
t.Errorf("unknown key: %d %v", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaysInTheLastDaysAreCountedForTheListenerOnly(t *testing.T) {
|
||||
m := newMixAPI(t)
|
||||
var ids []int64
|
||||
rows, err := m.db.Query("SELECT id FROM tracks WHERE title LIKE 'hard song%' ORDER BY id LIMIT 3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
// Song 0: three listens long ago. Song 1: two listens this week. Song 2: one this week.
|
||||
events := []struct {
|
||||
track int64
|
||||
days int
|
||||
}{{ids[0], 200}, {ids[0], 201}, {ids[0], 202}, {ids[1], 1}, {ids[1], 2}, {ids[2], 3}}
|
||||
for i, e := range events {
|
||||
if _, err := m.db.Exec(`INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key)
|
||||
VALUES (1, ?, 'complete', strftime('%s','now') - ?, 60000, ?)`, e.track, e.days*86400, fmt.Sprintf("r%d", i)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rot := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/on-rotation/tracks", m.alice, nil))
|
||||
if len(rot) != 1 || rot[0] != float64(ids[1]) {
|
||||
t.Errorf("on rotation = %v, want only the song played twice this week (%d)", rot, ids[1])
|
||||
}
|
||||
year := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/top-year/tracks", m.alice, nil))
|
||||
if len(year) != 2 || year[0] != float64(ids[0]) && year[0] != float64(ids[1]) {
|
||||
t.Errorf("top of the year = %v", year)
|
||||
}
|
||||
all := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/most-played/tracks", m.alice, nil))
|
||||
if len(all) != 3 || all[0] != float64(ids[0]) {
|
||||
t.Errorf("most played ever = %v, want song %d first (three listens)", all, ids[0])
|
||||
}
|
||||
// The rule is in the API for a smart playlist of one's own too.
|
||||
id := smartMade(t, m, map[string]any{"name": "Lately", "sort": "most_played", "rules": map[string]any{"plays_within_days": 7, "min_plays": 1}})
|
||||
got := smartTracks(t, m, id, "")
|
||||
if len(got) != 2 || got[0] != float64(ids[1]) {
|
||||
t.Errorf("a smart playlist with the window = %v, want %d then %d", got, ids[1], ids[2])
|
||||
}
|
||||
if r := do(t, m.h, "POST", sp, m.alice, map[string]any{"name": "x", "rules": map[string]any{"plays_within_days": -1}}); r.Code != http.StatusBadRequest {
|
||||
t.Errorf("a negative window: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1385,8 +1385,10 @@ paths:
|
|||
summary: The smart playlists Sonda makes for you
|
||||
description: |
|
||||
A fixed set that is there without anybody making it, the same rules for everyone and worked out on your
|
||||
own library and history: `recently-added`, `never-played`, `most-played`, `forgotten` (played once, but not
|
||||
in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks` (6 minutes or more).
|
||||
own library and history: `recently-added`, `on-rotation` (the songs you played most in the last 30 days, at
|
||||
least twice), `top-year` (the same over 365 days), `most-played` (over all time), `never-played`, `forgotten`
|
||||
(played once, but not in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks`
|
||||
(6 minutes or more).
|
||||
Nothing is stored for them. A client says their names in its own language from the `key`. To change one,
|
||||
make a smart playlist of your own from its rules with `POST /smart-playlists`.
|
||||
security: [{bearerAuth: []}]
|
||||
|
|
@ -2881,7 +2883,7 @@ components:
|
|||
in: path
|
||||
required: true
|
||||
description: A key from `GET /smart-playlists/suggested`.
|
||||
schema: {type: string, enum: [recently-added, never-played, most-played, forgotten, high-quality, long-tracks]}
|
||||
schema: {type: string, enum: [recently-added, on-rotation, top-year, most-played, never-played, forgotten, high-quality, long-tracks]}
|
||||
MixId:
|
||||
name: id
|
||||
in: path
|
||||
|
|
@ -3646,6 +3648,7 @@ components:
|
|||
played_within_days: {type: integer, minimum: 0, maximum: 36500}
|
||||
not_played_within_days: {type: integer, minimum: 0, maximum: 36500, description: Songs not played for this many days (the ones never played too).}
|
||||
min_plays: {type: integer, minimum: 0, maximum: 1000000}
|
||||
plays_within_days: {type: integer, minimum: 0, maximum: 36500, description: "Counts only the plays of the last N days where plays are counted: `min_plays` and the `most_played` and `least_played` orders. The other listening rules are not changed."}
|
||||
skipped_within_days: {type: integer, minimum: 0, maximum: 36500}
|
||||
not_skipped_within_days: {type: integer, minimum: 0, maximum: 36500, description: Leaves out songs skipped in the last days.}
|
||||
liked_artists_only: {type: boolean, description: Only songs by artists you like.}
|
||||
|
|
@ -3658,7 +3661,7 @@ components:
|
|||
additionalProperties: false
|
||||
required: [key, rules, sort, limit]
|
||||
properties:
|
||||
key: {type: string, enum: [recently-added, never-played, most-played, forgotten, high-quality, long-tracks]}
|
||||
key: {type: string, enum: [recently-added, on-rotation, top-year, most-played, never-played, forgotten, high-quality, long-tracks]}
|
||||
rules: {$ref: '#/components/schemas/SmartRules'}
|
||||
sort: {$ref: '#/components/schemas/SmartSort'}
|
||||
limit: {type: integer, minimum: 1, maximum: 500}
|
||||
|
|
|
|||
|
|
@ -93,12 +93,15 @@ type Rules struct {
|
|||
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"`
|
||||
SkippedWithinDays int `json:"skipped_within_days,omitempty"`
|
||||
NotSkippedWithinDays int `json:"not_skipped_within_days,omitempty"`
|
||||
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"`
|
||||
|
|
@ -179,6 +182,8 @@ type Store interface {
|
|||
// 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)
|
||||
}
|
||||
|
|
@ -311,6 +316,7 @@ func cleanRules(r Rules) (Rules, error) {
|
|||
{"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},
|
||||
} {
|
||||
|
|
@ -533,13 +539,23 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
return nil, fmt.Errorf("read the songs: %w", err)
|
||||
}
|
||||
|
||||
countsPlays := order == SortMostPlayed || order == SortLeastPlayed || r.MinPlays > 0
|
||||
var history map[int64]History
|
||||
if order == SortMostPlayed || order == SortLeastPlayed || r.NeverPlayed || r.MinPlays > 0 ||
|
||||
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 {
|
||||
|
|
@ -561,7 +577,7 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
r.NeverPlayed && h.Plays > 0,
|
||||
r.PlayedWithinDays > 0 && !within(h.LastPlayed, r.PlayedWithinDays),
|
||||
r.NotPlayedWithinDays > 0 && within(h.LastPlayed, r.NotPlayedWithinDays),
|
||||
r.MinPlays > 0 && h.Plays < r.MinPlays,
|
||||
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,
|
||||
|
|
@ -571,7 +587,7 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
kept = append(kept, c)
|
||||
}
|
||||
|
||||
sortCandidates(kept, order, history, func(c Candidate) uint64 {
|
||||
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()
|
||||
|
|
@ -592,7 +608,7 @@ func (s *Service) run(ctx context.Context, userID, id int64, r Rules, order Sort
|
|||
|
||||
// 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, history map[int64]History, hash func(Candidate) uint64) {
|
||||
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))
|
||||
|
|
@ -610,7 +626,7 @@ func sortCandidates(c []Candidate, order Sort, history map[int64]History, hash f
|
|||
return 1
|
||||
}
|
||||
case SortMostPlayed, SortLeastPlayed:
|
||||
pa, pb := history[a.TrackID].Plays, history[b.TrackID].Plays
|
||||
pa, pb := plays(a.TrackID), plays(b.TrackID)
|
||||
if order == SortLeastPlayed {
|
||||
pa, pb = pb, pa
|
||||
}
|
||||
|
|
@ -664,6 +680,7 @@ func (r Rules) Summary() string {
|
|||
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")
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ type fakeStore struct {
|
|||
cands []Candidate
|
||||
history map[int64]History
|
||||
asked []Filter
|
||||
windowed map[int64]int // plays inside the window asked for
|
||||
since []time.Time // the starts of the windows asked for
|
||||
saved map[int64]SmartPlaylist // by id
|
||||
nextID int64
|
||||
listened int // how many times history was read
|
||||
|
|
@ -44,6 +46,11 @@ func (f *fakeStore) History(context.Context, int64, time.Duration) (map[int64]Hi
|
|||
return f.history, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Plays(_ context.Context, _ int64, _ time.Duration, since time.Time) (map[int64]int, error) {
|
||||
f.since = append(f.since, since)
|
||||
return f.windowed, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Tracks(_ context.Context, ids []int64) ([]catalog.Track, error) {
|
||||
out := make([]catalog.Track, len(ids))
|
||||
for i, id := range ids {
|
||||
|
|
@ -539,7 +546,7 @@ func TestSuggestedAreAFixedSetOfValidRules(t *testing.T) {
|
|||
t.Errorf("%s: shape changed by cleaning: %+v", s.Key, in)
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"recently-added", "never-played", "most-played", "forgotten", "high-quality", "long-tracks"} {
|
||||
for _, want := range []string{"recently-added", "on-rotation", "top-year", "most-played", "never-played", "forgotten", "high-quality", "long-tracks"} {
|
||||
if !seen[want] {
|
||||
t.Errorf("%s is missing", want)
|
||||
}
|
||||
|
|
@ -612,3 +619,88 @@ func TestSummaryOfRulesIsAFewWordsInEnglish(t *testing.T) {
|
|||
t.Errorf("ids: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- plays inside a window ----
|
||||
|
||||
func TestPlaysCanBeCountedOverTheLastDaysOnly(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(5)
|
||||
// Over all time song 1 is the most played; in the last 30 days it is song 3.
|
||||
st.history = map[int64]History{1: {Plays: 40, LastPlayed: daysAgo(100)}, 2: {Plays: 9, LastPlayed: daysAgo(3)}, 3: {Plays: 8, LastPlayed: daysAgo(1)}, 4: {Plays: 2, LastPlayed: daysAgo(2)}}
|
||||
st.windowed = map[int64]int{2: 3, 3: 7, 4: 1}
|
||||
svc := newService(st, taste.Learned{})
|
||||
|
||||
got := preview(t, svc, Rules{}, SortMostPlayed)
|
||||
if !slices.Equal(got[:3], []int64{1, 2, 3}) {
|
||||
t.Fatalf("over all time = %v, want 1, 2, 3 first", got)
|
||||
}
|
||||
if len(st.since) != 0 {
|
||||
t.Errorf("a window was asked for with no rule that wants one: %v", st.since)
|
||||
}
|
||||
|
||||
got = preview(t, svc, Rules{PlaysWithinDays: 30}, SortMostPlayed)
|
||||
if want := []int64{3, 2, 4, 1, 5}; !slices.Equal(got, want) {
|
||||
t.Errorf("in the last 30 days = %v, want %v: 40 old plays count for nothing", got, want)
|
||||
}
|
||||
if len(st.since) != 1 || !st.since[0].Equal(daysAgo(30)) {
|
||||
t.Errorf("window starts = %v, want %v", st.since, daysAgo(30))
|
||||
}
|
||||
got = preview(t, svc, Rules{PlaysWithinDays: 30}, SortLeastPlayed)
|
||||
if got[0] != 1 && got[0] != 5 {
|
||||
t.Errorf("least played in the window = %v, want a song with no plays in it first", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheMinimumOfPlaysCountsOnlyTheWindowWhenThereIsOne(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(4)
|
||||
st.history = map[int64]History{1: {Plays: 40}, 2: {Plays: 9}, 3: {Plays: 8}, 4: {Plays: 2}}
|
||||
st.windowed = map[int64]int{2: 3, 3: 7, 4: 1}
|
||||
svc := newService(st, taste.Learned{})
|
||||
if got := preview(t, svc, Rules{MinPlays: 3}, SortTitle); !slices.Equal(got, []int64{1, 2, 3}) {
|
||||
t.Errorf("at least 3 plays, ever = %v", got)
|
||||
}
|
||||
if got := preview(t, svc, Rules{MinPlays: 3, PlaysWithinDays: 30}, SortTitle); !slices.Equal(got, []int64{2, 3}) {
|
||||
t.Errorf("at least 3 plays in the last 30 days = %v, want 2 and 3", got)
|
||||
}
|
||||
// Never played still means never, in the window or not.
|
||||
if got := preview(t, svc, Rules{NeverPlayed: true, PlaysWithinDays: 30}, SortTitle); len(got) != 0 {
|
||||
t.Errorf("never played = %v: every song has been played", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnRotationAndTheTopOfTheYearCountTheirOwnWindows(t *testing.T) {
|
||||
st := newStore()
|
||||
st.cands = songs(6)
|
||||
st.windowed = map[int64]int{1: 1, 2: 5, 3: 9, 4: 2}
|
||||
svc := newService(st, taste.Learned{})
|
||||
|
||||
sug, tracks, err := svc.SuggestedTracks(context.Background(), 1, "on-rotation", 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := ids(tracks); !slices.Equal(got, []int64{3, 2, 4}) {
|
||||
t.Errorf("on rotation = %v, want the songs played at least twice lately, the most first", got)
|
||||
}
|
||||
if sug.Rules.PlaysWithinDays != 30 || sug.Sort != SortMostPlayed {
|
||||
t.Errorf("on-rotation = %+v", sug)
|
||||
}
|
||||
st.since = nil
|
||||
if _, _, err := svc.SuggestedTracks(context.Background(), 1, "top-year", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(st.since) != 1 || !st.since[0].Equal(daysAgo(365)) {
|
||||
t.Errorf("top-year window = %v", st.since)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWindowOfDaysIsChecked(t *testing.T) {
|
||||
for _, n := range []int{-1, MaxDays + 1} {
|
||||
if _, err := newService(newStore(), taste.Learned{}).Preview(context.Background(), 1, Input{Rules: Rules{PlaysWithinDays: n}}, 0); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("plays_within_days %d: %v", n, err)
|
||||
}
|
||||
}
|
||||
if got := (Rules{PlaysWithinDays: 30, MinPlays: 2}).Summary(); got != "played at least 2 times; plays counted over the last 30 days" {
|
||||
t.Errorf("summary = %q", got)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,8 +21,10 @@ type SuggestedPlaylist struct {
|
|||
// the user can make their own with Create.
|
||||
var suggested = []SuggestedPlaylist{
|
||||
{Key: "recently-added", Rules: Rules{AddedWithinDays: 30}, Sort: SortRecentlyAdded, Limit: 100},
|
||||
{Key: "never-played", Rules: Rules{NeverPlayed: true}, Sort: SortRandom, Limit: DefaultLimit},
|
||||
{Key: "on-rotation", Rules: Rules{PlaysWithinDays: 30, MinPlays: 2}, Sort: SortMostPlayed, Limit: DefaultLimit},
|
||||
{Key: "top-year", Rules: Rules{PlaysWithinDays: 365, MinPlays: 2}, Sort: SortMostPlayed, Limit: DefaultLimit},
|
||||
{Key: "most-played", Rules: Rules{MinPlays: 1}, Sort: SortMostPlayed, Limit: DefaultLimit},
|
||||
{Key: "never-played", Rules: Rules{NeverPlayed: true}, Sort: SortRandom, Limit: DefaultLimit},
|
||||
{Key: "forgotten", Rules: Rules{MinPlays: 1, NotPlayedWithinDays: 90}, Sort: SortRandom, Limit: DefaultLimit},
|
||||
{Key: "high-quality", Rules: Rules{MinBitrateKbps: 900}, Sort: SortRandom, Limit: DefaultLimit},
|
||||
{Key: "long-tracks", Rules: Rules{MinDurationSec: 360}, Sort: SortRandom, Limit: DefaultLimit},
|
||||
|
|
|
|||
|
|
@ -165,6 +165,32 @@ func (r *SmartRepo) History(ctx context.Context, userID int64, minListen time.Du
|
|||
return r.mix.History(ctx, userID, minListen)
|
||||
}
|
||||
|
||||
// Plays returns how many listens the user has of each song since a moment (a play counts as a listen when it was
|
||||
// completed or lasted minListen), for the songs they listened to in that time.
|
||||
func (r *SmartRepo) Plays(ctx context.Context, userID int64, minListen time.Duration, since time.Time) (map[int64]int, error) {
|
||||
ms := minListen.Milliseconds()
|
||||
rows, err := r.db.QueryContext(ctx,
|
||||
`SELECT track_id, COUNT(*) FROM listening_events
|
||||
WHERE user_id = ? AND occurred_at >= ? AND (event_type = 'complete' OR duration_played_ms >= ?)
|
||||
GROUP BY track_id`, userID, since.Unix(), ms)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read plays: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[int64]int{}
|
||||
for rows.Next() {
|
||||
var (
|
||||
id int64
|
||||
n int
|
||||
)
|
||||
if err := rows.Scan(&id, &n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[id] = n
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Tracks returns the playable songs among ids, in the order given.
|
||||
func (r *SmartRepo) Tracks(ctx context.Context, ids []int64) ([]catalog.Track, error) {
|
||||
return r.mix.Tracks(ctx, ids)
|
||||
|
|
|
|||
|
|
@ -331,3 +331,41 @@ func TestSmartPlaylistsGoWhenTheirOwnerGoes(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSmartRepoCountsTheListensOfEachSongSinceAMoment(t *testing.T) {
|
||||
smartBackends(t, smartSongs, func(t *testing.T, e *smartEnv) {
|
||||
ctx := context.Background()
|
||||
at := func(track string, user int64, kind string, played int64, when int64, key string) {
|
||||
t.Helper()
|
||||
if _, err := e.db.Exec(`INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, user, e.tracks[track], kind, when, played, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const day = 86_400
|
||||
now := int64(1_700_000_000)
|
||||
at("a", e.alice, "complete", 180_000, now-1*day, "k1") // counts
|
||||
at("a", e.alice, "complete", 180_000, now-2*day, "k2") // counts
|
||||
at("a", e.alice, "play", 30_000, now-3*day, "k3") // played long enough: counts
|
||||
at("a", e.alice, "play", 5_000, now-3*day, "k4") // too short: not a listen
|
||||
at("a", e.alice, "skip", 2_000, now-1*day, "k5") // a skip
|
||||
at("a", e.alice, "complete", 180_000, now-60*day, "k6") // before the window
|
||||
at("b", e.alice, "complete", 180_000, now-5*day, "k7")
|
||||
at("a", e.bob, "complete", 180_000, now-1*day, "k8") // somebody else's
|
||||
|
||||
got, err := e.repo.Plays(ctx, e.alice, 20*time.Second, time.Unix(now-30*day, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[e.tracks["a"]] != 3 || got[e.tracks["b"]] != 1 || len(got) != 2 {
|
||||
t.Errorf("last 30 days = %v, want a: 3, b: 1", got)
|
||||
}
|
||||
all, _ := e.repo.Plays(ctx, e.alice, 20*time.Second, time.Unix(0, 0))
|
||||
if all[e.tracks["a"]] != 4 {
|
||||
t.Errorf("all time = %v, want a: 4", all)
|
||||
}
|
||||
if none, _ := e.repo.Plays(ctx, e.alice, 20*time.Second, time.Unix(now+day, 0)); len(none) != 0 {
|
||||
t.Errorf("a window in the future = %v", none)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
12
web/src/api/schema.d.ts
vendored
12
web/src/api/schema.d.ts
vendored
|
|
@ -972,8 +972,10 @@ export interface paths {
|
|||
/**
|
||||
* The smart playlists Sonda makes for you
|
||||
* @description A fixed set that is there without anybody making it, the same rules for everyone and worked out on your
|
||||
* own library and history: `recently-added`, `never-played`, `most-played`, `forgotten` (played once, but not
|
||||
* in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks` (6 minutes or more).
|
||||
* own library and history: `recently-added`, `on-rotation` (the songs you played most in the last 30 days, at
|
||||
* least twice), `top-year` (the same over 365 days), `most-played` (over all time), `never-played`, `forgotten`
|
||||
* (played once, but not in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks`
|
||||
* (6 minutes or more).
|
||||
* Nothing is stored for them. A client says their names in its own language from the `key`. To change one,
|
||||
* make a smart playlist of your own from its rules with `POST /smart-playlists`.
|
||||
*/
|
||||
|
|
@ -2478,6 +2480,8 @@ export interface components {
|
|||
/** @description Songs not played for this many days (the ones never played too). */
|
||||
not_played_within_days?: number;
|
||||
min_plays?: number;
|
||||
/** @description Counts only the plays of the last N days where plays are counted: `min_plays` and the `most_played` and `least_played` orders. The other listening rules are not changed. */
|
||||
plays_within_days?: number;
|
||||
skipped_within_days?: number;
|
||||
/** @description Leaves out songs skipped in the last days. */
|
||||
not_skipped_within_days?: number;
|
||||
|
|
@ -2490,7 +2494,7 @@ export interface components {
|
|||
};
|
||||
SuggestedSmartPlaylist: {
|
||||
/** @enum {string} */
|
||||
key: "recently-added" | "never-played" | "most-played" | "forgotten" | "high-quality" | "long-tracks";
|
||||
key: "recently-added" | "on-rotation" | "top-year" | "most-played" | "never-played" | "forgotten" | "high-quality" | "long-tracks";
|
||||
rules: components["schemas"]["SmartRules"];
|
||||
sort: components["schemas"]["SmartSort"];
|
||||
limit: number;
|
||||
|
|
@ -2984,7 +2988,7 @@ export interface components {
|
|||
Limit: number;
|
||||
Offset: number;
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
SuggestedKey: "recently-added" | "never-played" | "most-played" | "forgotten" | "high-quality" | "long-tracks";
|
||||
SuggestedKey: "recently-added" | "on-rotation" | "top-year" | "most-played" | "never-played" | "forgotten" | "high-quality" | "long-tracks";
|
||||
/** @description `favourites`, `rediscover`, `unheard` or `genre:<name>` (percent-encoded). */
|
||||
MixId: string;
|
||||
/** @description Only items with a playable file in this library. */
|
||||
|
|
|
|||
|
|
@ -589,6 +589,8 @@
|
|||
"makeMine": "Make it mine",
|
||||
"notFoundSuggested": "This suggested smart playlist does not exist.",
|
||||
"suggested": {
|
||||
"on-rotation": { "name": "In rotation", "description": "The songs you have played most in the last 30 days." },
|
||||
"top-year": { "name": "Top of the year", "description": "The songs you have played most over the last year." },
|
||||
"recently-added": { "name": "Recently added", "description": "Songs added in the last 30 days, the newest first." },
|
||||
"never-played": { "name": "Never played", "description": "Songs you have never listened to." },
|
||||
"most-played": { "name": "Most played", "description": "The songs you have played most." },
|
||||
|
|
@ -643,6 +645,8 @@
|
|||
"notPlayed_one": "Not played for {{count}} day",
|
||||
"notPlayed_other": "Not played for {{count}} days",
|
||||
"minPlays_one": "Played at least {{count}} time",
|
||||
"playsWithin_one": "Counting only the plays of the last {{count}} day",
|
||||
"playsWithin_other": "Counting only the plays of the last {{count}} days",
|
||||
"minPlays_other": "Played at least {{count}} times",
|
||||
"skipped_one": "Skipped in the last {{count}} day",
|
||||
"skipped_other": "Skipped in the last {{count}} days",
|
||||
|
|
@ -674,6 +678,7 @@
|
|||
"neverPlayed": "Never played",
|
||||
"played": "Played in the last (days)",
|
||||
"notPlayed": "Not played for (days)",
|
||||
"playsWithin": "Count plays over the last (days)",
|
||||
"minPlays": "Played at least (times)",
|
||||
"notSkipped": "Not skipped in the last (days)",
|
||||
"taste": "My taste",
|
||||
|
|
|
|||
|
|
@ -589,6 +589,8 @@
|
|||
"makeMine": "Fanne una tua",
|
||||
"notFoundSuggested": "Questa playlist smart suggerita non esiste.",
|
||||
"suggested": {
|
||||
"on-rotation": { "name": "In rotazione", "description": "I brani che hai ascoltato di più negli ultimi 30 giorni." },
|
||||
"top-year": { "name": "Top dell'anno", "description": "I brani che hai ascoltato di più nell'ultimo anno." },
|
||||
"recently-added": { "name": "Aggiunti da poco", "description": "Brani aggiunti negli ultimi 30 giorni, i più nuovi per primi." },
|
||||
"never-played": { "name": "Mai ascoltati", "description": "Brani che non hai mai ascoltato." },
|
||||
"most-played": { "name": "I più ascoltati", "description": "I brani che hai ascoltato di più." },
|
||||
|
|
@ -643,6 +645,8 @@
|
|||
"notPlayed_one": "Non ascoltati da {{count}} giorno",
|
||||
"notPlayed_other": "Non ascoltati da {{count}} giorni",
|
||||
"minPlays_one": "Ascoltati almeno {{count}} volta",
|
||||
"playsWithin_one": "Contando solo gli ascolti dell'ultimo giorno",
|
||||
"playsWithin_other": "Contando solo gli ascolti degli ultimi {{count}} giorni",
|
||||
"minPlays_other": "Ascoltati almeno {{count}} volte",
|
||||
"skipped_one": "Saltati nell'ultimo giorno",
|
||||
"skipped_other": "Saltati negli ultimi {{count}} giorni",
|
||||
|
|
@ -674,6 +678,7 @@
|
|||
"neverPlayed": "Mai ascoltati",
|
||||
"played": "Ascoltati negli ultimi (giorni)",
|
||||
"notPlayed": "Non ascoltati da (giorni)",
|
||||
"playsWithin": "Conta gli ascolti degli ultimi (giorni)",
|
||||
"minPlays": "Ascoltati almeno (volte)",
|
||||
"notSkipped": "Non saltati negli ultimi (giorni)",
|
||||
"taste": "I miei gusti",
|
||||
|
|
|
|||
|
|
@ -141,6 +141,7 @@ function SmartEditor({ existing }: { existing: SmartPlaylist | null }) {
|
|||
<NumberField label={t('smart.editor.played')} value={form.playedDays} onChange={(v) => set('playedDays', v)} />
|
||||
<NumberField label={t('smart.editor.notPlayed')} value={form.notPlayedDays} onChange={(v) => set('notPlayedDays', v)} />
|
||||
<NumberField label={t('smart.editor.minPlays')} value={form.minPlays} onChange={(v) => set('minPlays', v)} />
|
||||
<NumberField label={t('smart.editor.playsWithin')} value={form.playsDays} onChange={(v) => set('playsDays', v)} />
|
||||
<NumberField label={t('smart.editor.notSkipped')} value={form.notSkippedDays} onChange={(v) => set('notSkippedDays', v)} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ beforeEach(async () => {
|
|||
test('rules go into the form and come back unchanged, keeping what the form has no field for', () => {
|
||||
const rules = {
|
||||
genres: ['rock', 'metal'], not_genres: ['pop'], artist_ids: [3, 4], not_album_ids: [7], formats: ['flac'], min_bitrate_kbps: 900,
|
||||
added_within_days: 30, never_played: true, played_within_days: 7, not_played_within_days: 60, min_plays: 2,
|
||||
added_within_days: 30, never_played: true, played_within_days: 7, not_played_within_days: 60, min_plays: 2, plays_within_days: 30,
|
||||
skipped_within_days: 5, not_skipped_within_days: 14, liked_artists_only: true, without_avoided_artists: true,
|
||||
min_duration_sec: 90, max_duration_sec: 600,
|
||||
}
|
||||
|
|
@ -98,10 +98,11 @@ test('the rules are described in words, and no rule says so', async () => {
|
|||
const { default: i18n } = await import('i18next')
|
||||
const t = i18n.t.bind(i18n)
|
||||
expect(describeRules(t, {})).toEqual(['No rules: every song'])
|
||||
expect(describeRules(t, { genres: ['rock'], added_within_days: 1, min_plays: 3, min_duration_sec: 90, liked_artists_only: true })).toEqual([
|
||||
expect(describeRules(t, { genres: ['rock'], added_within_days: 1, min_plays: 3, plays_within_days: 30, min_duration_sec: 90, liked_artists_only: true })).toEqual([
|
||||
'Genres: rock',
|
||||
'Added in the last 1 day',
|
||||
'Played at least 3 times',
|
||||
'Counting only the plays of the last 30 days',
|
||||
'Only artists I like',
|
||||
'At least 1.5 min long',
|
||||
])
|
||||
|
|
@ -111,6 +112,7 @@ test('the rules are described in words, and no rule says so', async () => {
|
|||
|
||||
const SUGGESTED = [
|
||||
{ key: 'recently-added', rules: { added_within_days: 30 }, sort: 'recently_added', limit: 100 },
|
||||
{ key: 'on-rotation', rules: { plays_within_days: 30, min_plays: 2 }, sort: 'most_played', limit: 50 },
|
||||
{ key: 'never-played', rules: { never_played: true }, sort: 'random', limit: 50 },
|
||||
{ key: 'most-played', rules: { min_plays: 1 }, sort: 'most_played', limit: 50 },
|
||||
]
|
||||
|
|
@ -381,7 +383,8 @@ test('the list begins with the smart playlists that are there without making the
|
|||
const made = await screen.findByRole('region', { name: 'Made for you' })
|
||||
const links = within(made).getAllByRole('link')
|
||||
expect(links.map((l) => l.getAttribute('href'))).toEqual([
|
||||
'/smart-playlists/suggested/recently-added', '/smart-playlists/suggested/never-played', '/smart-playlists/suggested/most-played',
|
||||
'/smart-playlists/suggested/recently-added', '/smart-playlists/suggested/on-rotation', '/smart-playlists/suggested/never-played',
|
||||
'/smart-playlists/suggested/most-played',
|
||||
])
|
||||
expect(links[0]).toHaveTextContent('Recently added')
|
||||
expect(links[0]).toHaveTextContent('Songs added in the last 30 days')
|
||||
|
|
@ -487,3 +490,24 @@ test('a new smart playlist has no name to suggest yet: it is not kept', async ()
|
|||
await screen.findByRole('textbox', { name: 'Name' })
|
||||
expect(screen.queryByRole('button', { name: 'Suggest a name' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the songs in rotation say in words what they count, and are the most played of the last 30 days', async () => {
|
||||
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/on-rotation/tracks': () => tracks(0, 5, 6) }))
|
||||
renderApp('/smart-playlists/suggested/on-rotation')
|
||||
expect(await screen.findByRole('heading', { level: 1, name: 'In rotation' })).toBeInTheDocument()
|
||||
expect(screen.getByText('The songs you have played most in the last 30 days.')).toBeInTheDocument()
|
||||
const rules = within(screen.getByRole('list', { name: 'Rules' }))
|
||||
expect(rules.getByText('Counting only the plays of the last 30 days')).toBeInTheDocument()
|
||||
expect(rules.getByText('Played at least 2 times')).toBeInTheDocument()
|
||||
expect(rules.getByText('Most played')).toBeInTheDocument()
|
||||
expect(await screen.findByRole('button', { name: /Song 5/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the editor can count the plays over the last days, and sends it as a rule', async () => {
|
||||
const { calls } = mockFetch(editorRoutes())
|
||||
renderApp('/smart-playlists/new')
|
||||
await userEvent.type(await screen.findByRole('spinbutton', { name: 'Played at least (times)' }), '2')
|
||||
await userEvent.type(screen.getByRole('spinbutton', { name: 'Count plays over the last (days)' }), '30')
|
||||
await userEvent.click(screen.getByRole('radio', { name: 'Most played' }))
|
||||
await waitFor(() => expect(body(previewCalls(calls).at(-1)!)).toEqual({ rules: { min_plays: 2, plays_within_days: 30 }, sort: 'most_played', limit: 50 }), { timeout: 3000 })
|
||||
})
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ export interface RuleForm {
|
|||
playedDays: string
|
||||
notPlayedDays: string
|
||||
minPlays: string
|
||||
playsDays: string
|
||||
notSkippedDays: string
|
||||
likedOnly: boolean
|
||||
noAvoided: boolean
|
||||
|
|
@ -21,7 +22,7 @@ export interface RuleForm {
|
|||
|
||||
export const EMPTY_FORM: RuleForm = {
|
||||
genres: [], notGenres: [], format: 'any', minBitrate: '', addedDays: '', neverPlayed: false, playedDays: '', notPlayedDays: '',
|
||||
minPlays: '', notSkippedDays: '', likedOnly: false, noAvoided: false, minMinutes: '', maxMinutes: '',
|
||||
minPlays: '', playsDays: '', notSkippedDays: '', likedOnly: false, noAvoided: false, minMinutes: '', maxMinutes: '',
|
||||
}
|
||||
|
||||
const text = (n: number | undefined) => (n ? String(n) : '')
|
||||
|
|
@ -45,6 +46,7 @@ export function formFromRules(r: SmartRules): RuleForm {
|
|||
playedDays: text(r.played_within_days),
|
||||
notPlayedDays: text(r.not_played_within_days),
|
||||
minPlays: text(r.min_plays),
|
||||
playsDays: text(r.plays_within_days),
|
||||
notSkippedDays: text(r.not_skipped_within_days),
|
||||
likedOnly: r.liked_artists_only ?? false,
|
||||
noAvoided: r.without_avoided_artists ?? false,
|
||||
|
|
@ -74,7 +76,7 @@ export function rulesFromForm(f: RuleForm, base: SmartRules = {}): SmartRules {
|
|||
if (f.format === 'kept' && base.formats) out.formats = base.formats
|
||||
const numbers: [keyof SmartRules, string][] = [
|
||||
['min_bitrate_kbps', f.minBitrate], ['added_within_days', f.addedDays], ['played_within_days', f.playedDays],
|
||||
['not_played_within_days', f.notPlayedDays], ['min_plays', f.minPlays], ['not_skipped_within_days', f.notSkippedDays],
|
||||
['not_played_within_days', f.notPlayedDays], ['min_plays', f.minPlays], ['plays_within_days', f.playsDays], ['not_skipped_within_days', f.notSkippedDays],
|
||||
]
|
||||
for (const [key, value] of numbers) {
|
||||
const n = whole(value)
|
||||
|
|
@ -110,6 +112,7 @@ export function describeRules(t: TFunction, r: SmartRules): string[] {
|
|||
add(r.played_within_days, 'played', { count: r.played_within_days })
|
||||
add(r.not_played_within_days, 'notPlayed', { count: r.not_played_within_days })
|
||||
add(r.min_plays, 'minPlays', { count: r.min_plays })
|
||||
add(r.plays_within_days, 'playsWithin', { count: r.plays_within_days })
|
||||
add(r.skipped_within_days, 'skipped', { count: r.skipped_within_days })
|
||||
add(r.not_skipped_within_days, 'notSkipped', { count: r.not_skipped_within_days })
|
||||
add(r.liked_artists_only, 'liked')
|
||||
|
|
|
|||
Loading…
Reference in a new issue