Initial commit: LastRecc discovery feed and weekly engine
This commit is contained in:
40 files changed
+6972
No files matched your search
@@ -0,0 +1,93 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"lastrecc-go/internal/lastfm"
|
||||
"lastrecc-go/internal/navidrome"
|
||||
"lastrecc-go/internal/text"
|
||||
)
|
||||
|
||||
func TestSelectFavoriteSongs(t *testing.T) {
|
||||
songs := []navidrome.Song{
|
||||
{ID: "a", Artist: "A", Title: "First"},
|
||||
{ID: "b", Artist: "A", Title: "Second"},
|
||||
{ID: "c", Artist: "A", Title: "Third"},
|
||||
}
|
||||
top := []lastfm.Track{
|
||||
{Name: "Third"},
|
||||
{Name: "First"},
|
||||
}
|
||||
heard := map[string]bool{text.TrackKey("A", "Second"): true}
|
||||
selected := selectFavoriteSongs(songs, top, heard, 2)
|
||||
if len(selected) != 2 {
|
||||
t.Fatalf("expected 2 songs, got %d", len(selected))
|
||||
}
|
||||
if selected[0].ID != "c" || selected[1].ID != "a" {
|
||||
t.Fatalf("unexpected order: %+v", selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectFavoriteSongsFallsBackToAlbumOrder(t *testing.T) {
|
||||
songs := []navidrome.Song{
|
||||
{ID: "a", Artist: "A", Title: "First"},
|
||||
{ID: "b", Artist: "A", Title: "Second"},
|
||||
}
|
||||
selected := selectFavoriteSongs(songs, nil, map[string]bool{}, 1)
|
||||
if len(selected) != 1 || selected[0].ID != "a" {
|
||||
t.Fatalf("unexpected selection: %+v", selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPlaylistTracksDedupesAndCaps(t *testing.T) {
|
||||
plan := &Plan{
|
||||
SeedAlbums: []AlbumPlan{
|
||||
{
|
||||
Score: 0.5,
|
||||
SelectedSongs: []navidrome.Song{
|
||||
{ID: "1", Artist: "A", Title: "One", Album: "X"},
|
||||
{ID: "2", Artist: "A", Title: "Two", Album: "X"},
|
||||
},
|
||||
},
|
||||
},
|
||||
Artists: []ArtistPlan{
|
||||
{
|
||||
Score: 0.9,
|
||||
Album: &AlbumPlan{
|
||||
Action: "downloaded",
|
||||
SelectedSongs: []navidrome.Song{
|
||||
{ID: "1", Artist: "A", Title: "One", Album: "X"},
|
||||
{ID: "3", Artist: "B", Title: "Three", Album: "Y"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
tracks := BuildPlaylistTracks(plan, Options{PlaylistMaxTracks: 2}, nil)
|
||||
if len(tracks) != 2 {
|
||||
t.Fatalf("expected cap of 2, got %d", len(tracks))
|
||||
}
|
||||
if tracks[0].SongID != "3" || tracks[1].SongID != "1" {
|
||||
t.Fatalf("unexpected order/dedupe: %+v", tracks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPlaylistTracksRepeatWindow(t *testing.T) {
|
||||
plan := &Plan{
|
||||
SeedAlbums: []AlbumPlan{
|
||||
{
|
||||
Score: 1,
|
||||
SelectedSongs: []navidrome.Song{
|
||||
{ID: "1", Artist: "A", Title: "One"},
|
||||
{ID: "2", Artist: "A", Title: "Two"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
current := text.WeekIndex(nowUTC())
|
||||
history := map[string]int{text.TrackKey("A", "One"): current}
|
||||
tracks := BuildPlaylistTracks(plan, Options{RepeatWeeks: 4}, history)
|
||||
if len(tracks) != 1 || tracks[0].SongID != "2" {
|
||||
t.Fatalf("expected only unheard track, got %+v", tracks)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lastrecc-go/internal/cache"
|
||||
"lastrecc-go/internal/config"
|
||||
"lastrecc-go/internal/navidrome"
|
||||
"lastrecc-go/internal/rip"
|
||||
"lastrecc-go/internal/text"
|
||||
)
|
||||
|
||||
func Download(ctx context.Context, plan *Plan, ripRunner *rip.Runner, logf func(string, ...any)) error {
|
||||
if len(plan.Downloads) == 0 {
|
||||
return nil
|
||||
}
|
||||
hits := make([]rip.Hit, 0, len(plan.Downloads))
|
||||
seen := map[string]bool{}
|
||||
for _, album := range plan.Downloads {
|
||||
if album.QobuzID == "" || seen[album.QobuzID] {
|
||||
continue
|
||||
}
|
||||
seen[album.QobuzID] = true
|
||||
hits = append(hits, rip.Hit{ID: album.QobuzID, Title: album.QobuzTitle})
|
||||
}
|
||||
if len(hits) == 0 {
|
||||
return nil
|
||||
}
|
||||
logf("downloading %d album(s) through streamrip-go", len(hits))
|
||||
return ripRunner.DownloadAlbums(ctx, hits)
|
||||
}
|
||||
|
||||
func Scan(ctx context.Context, nav *navidrome.Client, scanNav *navidrome.Client, cfg *config.Config, downloadCount int, logf func(string, ...any)) {
|
||||
if downloadCount == 0 {
|
||||
return
|
||||
}
|
||||
if !cfg.Scan {
|
||||
logf("scan disabled; waiting %s for the library watcher", cfg.Settle)
|
||||
sleepCtx(ctx, cfg.Settle)
|
||||
return
|
||||
}
|
||||
if scanNav == nil {
|
||||
scanNav = nav
|
||||
}
|
||||
logf("starting Navidrome scan")
|
||||
if err := scanNav.StartScan(ctx); err != nil {
|
||||
logf("warning: could not start scan: %v", err)
|
||||
sleepCtx(ctx, cfg.Settle)
|
||||
return
|
||||
}
|
||||
deadline := time.Now().Add(cfg.ScanTimeout)
|
||||
for {
|
||||
status, err := scanNav.ScanStatus(ctx)
|
||||
if err != nil {
|
||||
logf("warning: scan status: %v", err)
|
||||
} else if !status.Scanning {
|
||||
logf("scan finished (%d files)", status.Count)
|
||||
sleepCtx(ctx, cfg.Settle)
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
logf("warning: scan timeout after %s; continuing", cfg.ScanTimeout)
|
||||
return
|
||||
}
|
||||
sleepCtx(ctx, 5*time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func ResolveDownloads(ctx context.Context, plan *Plan, nav *navidrome.Client, opts Options, logf func(string, ...any)) {
|
||||
if plan.History == nil {
|
||||
plan.History = &historyData{HeardTracks: map[string]bool{}}
|
||||
}
|
||||
for index := range plan.Artists {
|
||||
artist := &plan.Artists[index]
|
||||
if artist.Album == nil || artist.Album.Action != "download" {
|
||||
continue
|
||||
}
|
||||
album := artist.Album
|
||||
var foundAlbum navidrome.Album
|
||||
var songs []navidrome.Song
|
||||
var lastErr error
|
||||
names := []string{album.Name}
|
||||
if album.QobuzTitle != "" && album.QobuzTitle != album.Name {
|
||||
names = append([]string{album.QobuzTitle}, names...)
|
||||
}
|
||||
for attempt := 0; attempt < 6; attempt++ {
|
||||
for _, name := range names {
|
||||
libAlbum, found, err := nav.FindAlbum(ctx, artist.Artist, name)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
foundAlbum = libAlbum
|
||||
_, songs, lastErr = nav.GetAlbum(ctx, libAlbum.ID)
|
||||
if lastErr == nil && len(songs) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(songs) > 0 {
|
||||
break
|
||||
}
|
||||
sleepCtx(ctx, 5*time.Second)
|
||||
}
|
||||
if len(songs) == 0 {
|
||||
album.Action = "skipped"
|
||||
album.Error = fmt.Sprintf("not found in Navidrome after scan: %v", lastErr)
|
||||
artist.Action = "skipped"
|
||||
artist.Error = album.Error
|
||||
plan.Errors = append(plan.Errors, fmt.Sprintf("%s — %s: %s", artist.Artist, album.Name, album.Error))
|
||||
continue
|
||||
}
|
||||
selected := selectFavoriteSongs(songs, album.TopTracks, plan.History.HeardTracks, opts.TracksPerAlbum)
|
||||
if len(selected) == 0 {
|
||||
album.Action = "skipped"
|
||||
album.Error = "no unheard tracks after scan"
|
||||
artist.Action = "skipped"
|
||||
artist.Error = album.Error
|
||||
continue
|
||||
}
|
||||
album.Action = "downloaded"
|
||||
album.InLibrary = true
|
||||
album.AlbumID = foundAlbum.ID
|
||||
album.SelectedSongs = selected
|
||||
artist.Action = "downloaded"
|
||||
logf("resolved %s — %s (%d tracks on playlist)", artist.Artist, album.Name, len(selected))
|
||||
}
|
||||
}
|
||||
|
||||
func ReplacePlaylist(ctx context.Context, nav *navidrome.Client, name string, tracks []PlaylistTrack, logf func(string, ...any)) error {
|
||||
if len(tracks) == 0 {
|
||||
return errors.New("playlist would be empty; leaving the existing playlist untouched")
|
||||
}
|
||||
playlists, err := nav.GetPlaylists(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get playlists: %w", err)
|
||||
}
|
||||
for _, playlist := range playlists {
|
||||
if strings.EqualFold(playlist.Name, name) {
|
||||
if err := nav.DeletePlaylist(ctx, playlist.ID); err != nil {
|
||||
return fmt.Errorf("delete playlist %s: %w", playlist.ID, err)
|
||||
}
|
||||
logf("deleted old playlist %q", name)
|
||||
}
|
||||
}
|
||||
ids := make([]string, 0, len(tracks))
|
||||
seen := map[string]bool{}
|
||||
for _, track := range tracks {
|
||||
if track.SongID == "" || seen[track.SongID] {
|
||||
continue
|
||||
}
|
||||
seen[track.SongID] = true
|
||||
ids = append(ids, track.SongID)
|
||||
}
|
||||
if err := nav.CreatePlaylist(ctx, name, ids); err != nil {
|
||||
return fmt.Errorf("create playlist: %w", err)
|
||||
}
|
||||
logf("created playlist %q with %d tracks", name, len(ids))
|
||||
return nil
|
||||
}
|
||||
|
||||
func LoadPlaylistHistory(stateDir string) (map[string]int, error) {
|
||||
path := filepath.Join(stateDir, "playlist_history.json")
|
||||
history := map[string]int{}
|
||||
err := cache.LoadJSON(path, &history)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return history, err
|
||||
}
|
||||
return history, nil
|
||||
}
|
||||
|
||||
func UpdatePlaylistHistory(stateDir string, history map[string]int, tracks []PlaylistTrack) error {
|
||||
week := text.WeekIndex(nowUTC())
|
||||
for _, track := range tracks {
|
||||
history[text.TrackKey(track.Artist, track.Title)] = week
|
||||
}
|
||||
return cache.SaveJSON(filepath.Join(stateDir, "playlist_history.json"), history)
|
||||
}
|
||||
|
||||
func SaveReport(stateDir string, plan *Plan) error {
|
||||
name := "last-run.json"
|
||||
if plan.DryRun {
|
||||
name = "last-plan.json"
|
||||
}
|
||||
return cache.SaveJSON(filepath.Join(stateDir, name), plan)
|
||||
}
|
||||
|
||||
func BuildFinalPlaylist(plan *Plan, opts Options, history map[string]int) {
|
||||
plan.Playlist = BuildPlaylistTracks(plan, opts, history)
|
||||
plan.Stats.PlaylistTracks = len(plan.Playlist)
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, delay time.Duration) {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"lastrecc-go/internal/navidrome"
|
||||
"lastrecc-go/internal/text"
|
||||
)
|
||||
|
||||
func recencyWeight(timestamp int64, now time.Time, halfLifeDays float64) float64 {
|
||||
ageDays := now.Sub(time.Unix(timestamp, 0)).Hours() / 24
|
||||
if ageDays < 0 {
|
||||
ageDays = 0
|
||||
}
|
||||
return math.Pow(0.5, ageDays/halfLifeDays)
|
||||
}
|
||||
|
||||
func loadHistory(ctx context.Context, nav *navidrome.Client, days int, logf func(string, ...any)) (*historyData, error) {
|
||||
scrobbles, err := nav.Scrobbles(ctx, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(scrobbles) == 0 {
|
||||
return nil, errNoScrobbles
|
||||
}
|
||||
ids := make([]string, 0, len(scrobbles))
|
||||
seen := map[string]bool{}
|
||||
for _, scrobble := range scrobbles {
|
||||
if scrobble.MediaFileID != "" && !seen[scrobble.MediaFileID] {
|
||||
seen[scrobble.MediaFileID] = true
|
||||
ids = append(ids, scrobble.MediaFileID)
|
||||
}
|
||||
}
|
||||
if logf != nil {
|
||||
logf("resolving metadata for %d scrobbled tracks", len(ids))
|
||||
}
|
||||
songs, err := nav.Songs(ctx, ids, logf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
windowStart := now.Add(-time.Duration(days) * 24 * time.Hour).Unix()
|
||||
data := &historyData{
|
||||
AllSongs: songs,
|
||||
ArtistPlays: map[string]int{},
|
||||
ArtistWeight: map[string]float64{},
|
||||
TrackPlays: map[string]int{},
|
||||
TrackWeight: map[string]float64{},
|
||||
TrackMeta: map[string]SeedTrack{},
|
||||
HeardTracks: map[string]bool{},
|
||||
HeardAlbums: map[string]bool{},
|
||||
HeardAlbumKeys: map[string]bool{},
|
||||
}
|
||||
windowIDs := map[string]bool{}
|
||||
windowAlbums := map[string]bool{}
|
||||
totalSeconds := 0
|
||||
for _, scrobble := range scrobbles {
|
||||
song, ok := songs[scrobble.MediaFileID]
|
||||
if !ok || song.Title == "" {
|
||||
continue
|
||||
}
|
||||
key := text.TrackKey(song.Artist, song.Title)
|
||||
data.HeardTracks[key] = true
|
||||
if song.AlbumID != "" {
|
||||
data.HeardAlbums[song.AlbumID] = true
|
||||
}
|
||||
if song.Album != "" {
|
||||
data.HeardAlbumKeys[text.AlbumKey(song.Artist, song.Album)] = true
|
||||
}
|
||||
if scrobble.SubmissionTime < windowStart {
|
||||
continue
|
||||
}
|
||||
windowIDs[scrobble.MediaFileID] = true
|
||||
if song.AlbumID != "" {
|
||||
windowAlbums[song.AlbumID] = true
|
||||
}
|
||||
data.Window = append(data.Window, scrobble)
|
||||
weight := recencyWeight(scrobble.SubmissionTime, now, 14)
|
||||
data.ArtistPlays[song.Artist]++
|
||||
data.ArtistWeight[song.Artist] += weight
|
||||
data.TrackPlays[key]++
|
||||
data.TrackWeight[key] += weight
|
||||
data.TrackMeta[key] = SeedTrack{Artist: song.Artist, Title: song.Title, Plays: data.TrackPlays[key], Weight: data.TrackWeight[key]}
|
||||
totalSeconds += int(song.Duration)
|
||||
}
|
||||
data.Stats = Stats{
|
||||
Plays: len(data.Window),
|
||||
UniqueTracks: len(windowIDs),
|
||||
Artists: len(data.ArtistPlays),
|
||||
Albums: len(windowAlbums),
|
||||
Hours: float64(totalSeconds) / 3600,
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func LoadSeeds(ctx context.Context, nav *navidrome.Client, days, seedArtists, seedTracks int, logf func(string, ...any)) ([]SeedArtist, []SeedTrack, Stats, error) {
|
||||
history, err := loadHistory(ctx, nav, days, logf)
|
||||
if err != nil {
|
||||
return nil, nil, Stats{}, err
|
||||
}
|
||||
artists := topSeedArtists(history, seedArtists)
|
||||
tracks := topSeedTracks(history, seedTracks)
|
||||
stats := history.Stats
|
||||
stats.TopArtists = topArtistNames(history, 10)
|
||||
return artists, tracks, stats, nil
|
||||
}
|
||||
|
||||
func topSeedArtists(data *historyData, limit int) []SeedArtist {
|
||||
type pair struct {
|
||||
name string
|
||||
weight float64
|
||||
}
|
||||
pairs := make([]pair, 0, len(data.ArtistWeight))
|
||||
for name, weight := range data.ArtistWeight {
|
||||
pairs = append(pairs, pair{name: name, weight: weight})
|
||||
}
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return pairs[i].weight > pairs[j].weight })
|
||||
if limit > 0 && len(pairs) > limit {
|
||||
pairs = pairs[:limit]
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return nil
|
||||
}
|
||||
maxWeight := pairs[0].weight
|
||||
if maxWeight <= 0 {
|
||||
maxWeight = 1
|
||||
}
|
||||
out := make([]SeedArtist, 0, len(pairs))
|
||||
for _, item := range pairs {
|
||||
out = append(out, SeedArtist{
|
||||
Name: item.name,
|
||||
Plays: data.ArtistPlays[item.name],
|
||||
Weight: item.weight / maxWeight,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func topSeedTracks(data *historyData, limit int) []SeedTrack {
|
||||
type pair struct {
|
||||
key string
|
||||
weight float64
|
||||
}
|
||||
pairs := make([]pair, 0, len(data.TrackWeight))
|
||||
for key, weight := range data.TrackWeight {
|
||||
pairs = append(pairs, pair{key: key, weight: weight})
|
||||
}
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return pairs[i].weight > pairs[j].weight })
|
||||
if limit > 0 && len(pairs) > limit {
|
||||
pairs = pairs[:limit]
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return nil
|
||||
}
|
||||
maxWeight := pairs[0].weight
|
||||
if maxWeight <= 0 {
|
||||
maxWeight = 1
|
||||
}
|
||||
out := make([]SeedTrack, 0, len(pairs))
|
||||
for _, item := range pairs {
|
||||
meta := data.TrackMeta[item.key]
|
||||
meta.Weight = item.weight / maxWeight
|
||||
meta.Plays = data.TrackPlays[item.key]
|
||||
out = append(out, meta)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"lastrecc-go/internal/config"
|
||||
"lastrecc-go/internal/lastfm"
|
||||
"lastrecc-go/internal/navidrome"
|
||||
"lastrecc-go/internal/rip"
|
||||
"lastrecc-go/internal/text"
|
||||
)
|
||||
|
||||
var errNoScrobbles = errors.New("no scrobbles found for this user")
|
||||
|
||||
type artistAgg struct {
|
||||
Name string
|
||||
Score float64
|
||||
Similarity float64
|
||||
Seeds []string
|
||||
}
|
||||
|
||||
func BuildPlan(
|
||||
ctx context.Context,
|
||||
cfg *config.Config,
|
||||
opts Options,
|
||||
nav *navidrome.Client,
|
||||
fm *lastfm.Client,
|
||||
ripRunner *rip.Runner,
|
||||
logf func(string, ...any),
|
||||
) (*Plan, error) {
|
||||
history, err := loadHistory(ctx, nav, opts.Days, logf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan := &Plan{
|
||||
WindowDays: opts.Days,
|
||||
PlaylistName: cfg.PlaylistName,
|
||||
DryRun: cfg.DryRun,
|
||||
History: history,
|
||||
}
|
||||
plan.SeedArtists = topSeedArtists(history, opts.SeedArtists)
|
||||
plan.SeedTracks = topSeedTracks(history, opts.SeedTracks)
|
||||
if len(plan.SeedArtists) == 0 {
|
||||
return nil, fmt.Errorf("could not determine any seed artists")
|
||||
}
|
||||
plan.Stats = history.Stats
|
||||
plan.Stats.TopArtists = topArtistNames(history, 8)
|
||||
logf("seeds: %s", strings.Join(topSeedNames(plan.SeedArtists, 6), ", "))
|
||||
if ripRunner != nil {
|
||||
logf("streamrip binary: %s (available=%v)", ripRunner.Binary, ripRunner.Available())
|
||||
}
|
||||
|
||||
// Unplayed albums from artists the listener already plays.
|
||||
for _, seed := range plan.SeedArtists {
|
||||
topTracks, err := fm.ArtistTopTracks(ctx, seed.Name, 50)
|
||||
if err != nil {
|
||||
plan.Errors = append(plan.Errors, fmt.Sprintf("top tracks for %s: %v", seed.Name, err))
|
||||
continue
|
||||
}
|
||||
album, err := findSeedLibraryAlbum(ctx, nav, fm, history, seed, topTracks, opts.TracksPerAlbum)
|
||||
if err != nil {
|
||||
plan.Errors = append(plan.Errors, fmt.Sprintf("seed album for %s: %v", seed.Name, err))
|
||||
continue
|
||||
}
|
||||
if album != nil {
|
||||
album.Score = seed.Weight * 0.8
|
||||
plan.SeedAlbums = append(plan.SeedAlbums, *album)
|
||||
}
|
||||
}
|
||||
|
||||
// Similar artists, aggregated from artist seeds and track seeds.
|
||||
aggregated := aggregateArtists(ctx, history, plan, fm)
|
||||
if opts.MaxArtists > 0 && len(aggregated) > opts.MaxArtists {
|
||||
aggregated = aggregated[:opts.MaxArtists]
|
||||
}
|
||||
logf("%d recommended artists", len(aggregated))
|
||||
|
||||
for index, agg := range aggregated {
|
||||
artistPlan := planArtist(ctx, nav, fm, ripRunner, history, agg, opts, logf)
|
||||
artistPlan.Artist = agg.Name
|
||||
artistPlan.Score = agg.Score
|
||||
artistPlan.Similarity = agg.Similarity
|
||||
artistPlan.Seeds = agg.Seeds
|
||||
plan.Artists = append(plan.Artists, artistPlan)
|
||||
if artistPlan.Album != nil && artistPlan.Album.Action == "download" {
|
||||
plan.Downloads = append(plan.Downloads, *artistPlan.Album)
|
||||
}
|
||||
if logf != nil && (index+1)%5 == 0 {
|
||||
logf("planned %d/%d artists", index+1, len(aggregated))
|
||||
}
|
||||
}
|
||||
|
||||
plan.Stats.Recommended = len(plan.Artists)
|
||||
plan.Stats.LibraryAlbums = len(plan.SeedAlbums)
|
||||
for _, artist := range plan.Artists {
|
||||
switch artist.Action {
|
||||
case "library":
|
||||
plan.Stats.LibraryAlbums++
|
||||
case "download":
|
||||
plan.Stats.Downloads++
|
||||
default:
|
||||
plan.Stats.Skipped++
|
||||
}
|
||||
}
|
||||
plan.GeneratedAt = nowUTC().Format("2006-01-02T15:04:05Z")
|
||||
plan.Playlist = BuildPlaylistTracks(plan, opts, nil)
|
||||
plan.Stats.PlaylistTracks = len(plan.Playlist)
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
func aggregateArtists(ctx context.Context, history *historyData, plan *Plan, fm *lastfm.Client) []artistAgg {
|
||||
seedNames := map[string]bool{}
|
||||
for _, seed := range plan.SeedArtists {
|
||||
seedNames[text.Normalize(seed.Name)] = true
|
||||
}
|
||||
byName := map[string]*artistAgg{}
|
||||
add := func(name string, score, similarity float64, seedLabel string) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
key := text.Normalize(name)
|
||||
if seedNames[key] {
|
||||
return
|
||||
}
|
||||
agg, ok := byName[key]
|
||||
if !ok {
|
||||
agg = &artistAgg{Name: name}
|
||||
byName[key] = agg
|
||||
}
|
||||
agg.Score += score
|
||||
if similarity > agg.Similarity {
|
||||
agg.Similarity = similarity
|
||||
}
|
||||
if seedLabel != "" && !contains(agg.Seeds, seedLabel) {
|
||||
agg.Seeds = append(agg.Seeds, seedLabel)
|
||||
}
|
||||
}
|
||||
for _, seed := range plan.SeedArtists {
|
||||
similar, err := fm.SimilarArtists(ctx, seed.Name, 20)
|
||||
if err != nil {
|
||||
plan.Errors = append(plan.Errors, fmt.Sprintf("similar artists for %s: %v", seed.Name, err))
|
||||
continue
|
||||
}
|
||||
for _, artist := range similar {
|
||||
add(artist.Name, float64(artist.Match)*seed.Weight, float64(artist.Match), seed.Name)
|
||||
}
|
||||
}
|
||||
for _, seed := range plan.SeedTracks {
|
||||
similar, err := fm.SimilarTracks(ctx, seed.Artist, seed.Title, 12)
|
||||
if err != nil {
|
||||
plan.Errors = append(plan.Errors, fmt.Sprintf("similar tracks for %s — %s: %v", seed.Artist, seed.Title, err))
|
||||
continue
|
||||
}
|
||||
for _, track := range similar {
|
||||
add(track.Artist.Name, float64(track.Match)*seed.Weight*0.8, float64(track.Match), seed.Artist+" — "+seed.Title)
|
||||
}
|
||||
}
|
||||
out := make([]artistAgg, 0, len(byName))
|
||||
for _, agg := range byName {
|
||||
out = append(out, *agg)
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].Score == out[j].Score {
|
||||
return out[i].Name < out[j].Name
|
||||
}
|
||||
return out[i].Score > out[j].Score
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func planArtist(
|
||||
ctx context.Context,
|
||||
nav *navidrome.Client,
|
||||
fm *lastfm.Client,
|
||||
ripRunner *rip.Runner,
|
||||
history *historyData,
|
||||
agg artistAgg,
|
||||
opts Options,
|
||||
logf func(string, ...any),
|
||||
) ArtistPlan {
|
||||
artistPlan := ArtistPlan{Artist: agg.Name}
|
||||
if _, found, err := nav.FindArtist(ctx, agg.Name); err == nil {
|
||||
artistPlan.InLibrary = found
|
||||
}
|
||||
topTracks, err := fm.ArtistTopTracks(ctx, agg.Name, 50)
|
||||
if err != nil {
|
||||
artistPlan.Action = "skipped"
|
||||
artistPlan.Error = err.Error()
|
||||
return artistPlan
|
||||
}
|
||||
if artistPlan.InLibrary {
|
||||
artistPlan.LibraryTracks = collectLibraryTracks(ctx, nav, history, agg.Name, topTracks, opts.TracksPerAlbum)
|
||||
}
|
||||
album, action, err := chooseAlbum(ctx, nav, fm, ripRunner, history, agg.Name, topTracks, opts.TracksPerAlbum, logf)
|
||||
if err != nil {
|
||||
artistPlan.Action = "skipped"
|
||||
artistPlan.Error = err.Error()
|
||||
return artistPlan
|
||||
}
|
||||
artistPlan.Action = action
|
||||
artistPlan.Album = album
|
||||
if action == "skipped" && len(artistPlan.LibraryTracks) > 0 {
|
||||
artistPlan.Action = "library"
|
||||
}
|
||||
return artistPlan
|
||||
}
|
||||
|
||||
func chooseAlbum(
|
||||
ctx context.Context,
|
||||
nav *navidrome.Client,
|
||||
fm *lastfm.Client,
|
||||
ripRunner *rip.Runner,
|
||||
history *historyData,
|
||||
artist string,
|
||||
topTracks []lastfm.Track,
|
||||
tracksPerAlbum int,
|
||||
logf func(string, ...any),
|
||||
) (*AlbumPlan, string, error) {
|
||||
albums, err := fm.ArtistTopAlbums(ctx, artist, 12)
|
||||
if err != nil {
|
||||
return nil, "skipped", err
|
||||
}
|
||||
if logf != nil {
|
||||
logf("%s: %d top albums", artist, len(albums))
|
||||
}
|
||||
filtered := make([]lastfm.Album, 0, len(albums))
|
||||
for _, album := range albums {
|
||||
if album.Name != "" && !text.IsNoisyAlbum(album.Name) {
|
||||
filtered = append(filtered, album)
|
||||
}
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
filtered = albums
|
||||
}
|
||||
sort.SliceStable(filtered, func(i, j int) bool {
|
||||
return filtered[i].Playcount > filtered[j].Playcount
|
||||
})
|
||||
if len(filtered) > 3 {
|
||||
filtered = filtered[:3]
|
||||
}
|
||||
for _, album := range filtered {
|
||||
info, err := fm.AlbumInfo(ctx, artist, album.Name)
|
||||
if err != nil || len(info.Tracks.Track) == 0 {
|
||||
if logf != nil {
|
||||
logf("%s — %s: album info err=%v tracks=%d", artist, album.Name, err, len(info.Tracks.Track))
|
||||
}
|
||||
continue
|
||||
}
|
||||
plan := &AlbumPlan{
|
||||
Artist: artist,
|
||||
Name: album.Name,
|
||||
MBID: album.MBID,
|
||||
Playcount: int(album.Playcount),
|
||||
TrackCount: len(info.Tracks.Track),
|
||||
TopTracks: topTracks,
|
||||
}
|
||||
libraryAlbum, found, err := nav.FindAlbum(ctx, artist, album.Name)
|
||||
if err != nil {
|
||||
return nil, "skipped", err
|
||||
}
|
||||
if found {
|
||||
_, songs, err := nav.GetAlbum(ctx, libraryAlbum.ID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
selected := selectFavoriteSongs(songs, topTracks, history.HeardTracks, tracksPerAlbum)
|
||||
if logf != nil {
|
||||
logf("%s — %s: in library, %d songs, %d unheard selected", artist, album.Name, len(songs), len(selected))
|
||||
}
|
||||
if len(selected) == 0 {
|
||||
continue
|
||||
}
|
||||
plan.InLibrary = true
|
||||
plan.AlbumID = libraryAlbum.ID
|
||||
plan.SelectedSongs = selected
|
||||
plan.Action = "library"
|
||||
return plan, "library", nil
|
||||
}
|
||||
if ripRunner == nil || !ripRunner.Available() {
|
||||
if logf != nil {
|
||||
logf("%s — %s: streamrip not available", artist, album.Name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
hit, err := ripRunner.SearchAlbum(ctx, artist, album.Name)
|
||||
if err != nil {
|
||||
return nil, "skipped", err
|
||||
}
|
||||
if logf != nil {
|
||||
if hit == nil {
|
||||
logf("%s — %s: no Qobuz match", artist, album.Name)
|
||||
} else {
|
||||
logf("%s — %s: Qobuz %s (%s, %.0f%%)", artist, album.Name, hit.ID, hit.Title, hit.Score*100)
|
||||
}
|
||||
}
|
||||
if hit == nil {
|
||||
continue
|
||||
}
|
||||
plan.Action = "download"
|
||||
plan.QobuzID = hit.ID
|
||||
plan.QobuzTitle = hit.Title
|
||||
plan.QobuzScore = hit.Score
|
||||
return plan, "download", nil
|
||||
}
|
||||
return nil, "skipped", nil
|
||||
}
|
||||
|
||||
func findSeedLibraryAlbum(
|
||||
ctx context.Context,
|
||||
nav *navidrome.Client,
|
||||
fm *lastfm.Client,
|
||||
history *historyData,
|
||||
seed SeedArtist,
|
||||
topTracks []lastfm.Track,
|
||||
tracksPerAlbum int,
|
||||
) (*AlbumPlan, error) {
|
||||
albums, err := fm.ArtistTopAlbums(ctx, seed.Name, 10)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filtered := make([]lastfm.Album, 0, len(albums))
|
||||
for _, album := range albums {
|
||||
if album.Name != "" && !text.IsNoisyAlbum(album.Name) {
|
||||
filtered = append(filtered, album)
|
||||
}
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
filtered = albums
|
||||
}
|
||||
sort.SliceStable(filtered, func(i, j int) bool {
|
||||
return filtered[i].Playcount > filtered[j].Playcount
|
||||
})
|
||||
for _, album := range filtered {
|
||||
libraryAlbum, found, err := nav.FindAlbum(ctx, seed.Name, album.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found || history.HeardAlbums[libraryAlbum.ID] {
|
||||
continue
|
||||
}
|
||||
if history.HeardAlbumKeys[text.AlbumKey(seed.Name, album.Name)] {
|
||||
continue
|
||||
}
|
||||
_, songs, err := nav.GetAlbum(ctx, libraryAlbum.ID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
selected := selectFavoriteSongs(songs, topTracks, history.HeardTracks, tracksPerAlbum)
|
||||
if len(selected) == 0 {
|
||||
continue
|
||||
}
|
||||
return &AlbumPlan{
|
||||
Artist: seed.Name,
|
||||
Name: album.Name,
|
||||
MBID: album.MBID,
|
||||
Playcount: int(album.Playcount),
|
||||
TrackCount: len(songs),
|
||||
InLibrary: true,
|
||||
AlbumID: libraryAlbum.ID,
|
||||
Action: "library",
|
||||
SelectedSongs: selected,
|
||||
TopTracks: topTracks,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func collectLibraryTracks(ctx context.Context, nav *navidrome.Client, history *historyData, artist string, topTracks []lastfm.Track, limit int) []navidrome.Song {
|
||||
if limit <= 0 {
|
||||
return nil
|
||||
}
|
||||
seenID := map[string]bool{}
|
||||
seenKey := map[string]bool{}
|
||||
var out []navidrome.Song
|
||||
maxLookup := 10
|
||||
if len(topTracks) < maxLookup {
|
||||
maxLookup = len(topTracks)
|
||||
}
|
||||
for _, track := range topTracks[:maxLookup] {
|
||||
if track.Name == "" {
|
||||
continue
|
||||
}
|
||||
if history.HeardTracks[text.TrackKey(artist, track.Name)] {
|
||||
continue
|
||||
}
|
||||
song, found, err := nav.FindSong(ctx, artist, track.Name)
|
||||
if err != nil || !found {
|
||||
continue
|
||||
}
|
||||
key := text.TrackKey(song.Artist, song.Title)
|
||||
if seenID[song.ID] || seenKey[key] || history.HeardTracks[key] {
|
||||
continue
|
||||
}
|
||||
seenID[song.ID] = true
|
||||
seenKey[key] = true
|
||||
out = append(out, song)
|
||||
if len(out) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func selectFavoriteSongs(songs []navidrome.Song, topTracks []lastfm.Track, heard map[string]bool, limit int) []navidrome.Song {
|
||||
rank := map[string]int{}
|
||||
for index, track := range topTracks {
|
||||
key := text.Normalize(track.Name)
|
||||
if _, ok := rank[key]; !ok {
|
||||
rank[key] = index
|
||||
}
|
||||
}
|
||||
candidates := make([]navidrome.Song, 0, len(songs))
|
||||
for _, song := range songs {
|
||||
if song.ID == "" || song.Title == "" {
|
||||
continue
|
||||
}
|
||||
if heard[text.TrackKey(song.Artist, song.Title)] {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, song)
|
||||
}
|
||||
sort.SliceStable(candidates, func(i, j int) bool {
|
||||
ri, iok := rank[text.Normalize(candidates[i].Title)]
|
||||
rj, jok := rank[text.Normalize(candidates[j].Title)]
|
||||
if iok && jok {
|
||||
return ri < rj
|
||||
}
|
||||
if iok {
|
||||
return true
|
||||
}
|
||||
if jok {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
})
|
||||
if limit > 0 && len(candidates) > limit {
|
||||
candidates = candidates[:limit]
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
func BuildPlaylistTracks(plan *Plan, opts Options, history map[string]int) []PlaylistTrack {
|
||||
var tracks []PlaylistTrack
|
||||
add := func(songs []navidrome.Song, source string, score float64) {
|
||||
for index, song := range songs {
|
||||
tracks = append(tracks, PlaylistTrack{
|
||||
SongID: song.ID,
|
||||
Artist: song.Artist,
|
||||
Title: song.Title,
|
||||
Album: song.Album,
|
||||
Source: source,
|
||||
Score: score,
|
||||
Order: index,
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, album := range plan.SeedAlbums {
|
||||
add(album.SelectedSongs, "seed-album", album.Score)
|
||||
}
|
||||
for _, artist := range plan.Artists {
|
||||
add(artist.LibraryTracks, "library-track", artist.Score)
|
||||
if artist.Album == nil || len(artist.Album.SelectedSongs) == 0 {
|
||||
continue
|
||||
}
|
||||
source := "library"
|
||||
if artist.Album.Action == "downloaded" {
|
||||
source = "downloaded"
|
||||
}
|
||||
add(artist.Album.SelectedSongs, source, artist.Score)
|
||||
}
|
||||
|
||||
seenID := map[string]bool{}
|
||||
seenKey := map[string]bool{}
|
||||
unique := tracks[:0]
|
||||
for _, track := range tracks {
|
||||
if track.SongID == "" || seenID[track.SongID] {
|
||||
continue
|
||||
}
|
||||
key := text.TrackKey(track.Artist, track.Title)
|
||||
if seenKey[key] {
|
||||
continue
|
||||
}
|
||||
seenID[track.SongID] = true
|
||||
seenKey[key] = true
|
||||
unique = append(unique, track)
|
||||
}
|
||||
tracks = unique
|
||||
|
||||
if opts.RepeatWeeks > 0 && len(history) > 0 {
|
||||
currentWeek := text.WeekIndex(nowUTC())
|
||||
filtered := tracks[:0]
|
||||
for _, track := range tracks {
|
||||
last, ok := history[text.TrackKey(track.Artist, track.Title)]
|
||||
if ok && currentWeek-last < opts.RepeatWeeks {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, track)
|
||||
}
|
||||
if len(filtered) > 0 {
|
||||
tracks = filtered
|
||||
}
|
||||
}
|
||||
|
||||
sort.SliceStable(tracks, func(i, j int) bool {
|
||||
if tracks[i].Score == tracks[j].Score {
|
||||
if tracks[i].Artist == tracks[j].Artist {
|
||||
return tracks[i].Order < tracks[j].Order
|
||||
}
|
||||
return tracks[i].Artist < tracks[j].Artist
|
||||
}
|
||||
return tracks[i].Score > tracks[j].Score
|
||||
})
|
||||
if opts.PlaylistMaxTracks > 0 && len(tracks) > opts.PlaylistMaxTracks {
|
||||
tracks = tracks[:opts.PlaylistMaxTracks]
|
||||
}
|
||||
return tracks
|
||||
}
|
||||
|
||||
func topArtistNames(data *historyData, limit int) []string {
|
||||
seeds := topSeedArtists(data, limit)
|
||||
names := make([]string, 0, len(seeds))
|
||||
for _, seed := range seeds {
|
||||
names = append(names, seed.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func topSeedNames(seeds []SeedArtist, limit int) []string {
|
||||
if limit > 0 && len(seeds) > limit {
|
||||
seeds = seeds[:limit]
|
||||
}
|
||||
names := make([]string, 0, len(seeds))
|
||||
for _, seed := range seeds {
|
||||
names = append(names, fmt.Sprintf("%s (%d)", seed.Name, seed.Plays))
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func contains(items []string, value string) bool {
|
||||
for _, item := range items {
|
||||
if item == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"lastrecc-go/internal/lastfm"
|
||||
"lastrecc-go/internal/navidrome"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Days int
|
||||
SeedArtists int
|
||||
SeedTracks int
|
||||
MaxArtists int
|
||||
TracksPerAlbum int
|
||||
PlaylistMaxTracks int
|
||||
RepeatWeeks int
|
||||
}
|
||||
|
||||
type SeedArtist struct {
|
||||
Name string `json:"name"`
|
||||
Plays int `json:"plays"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type SeedTrack struct {
|
||||
Artist string `json:"artist"`
|
||||
Title string `json:"title"`
|
||||
Plays int `json:"plays"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type Stats struct {
|
||||
Plays int `json:"plays"`
|
||||
UniqueTracks int `json:"unique_tracks"`
|
||||
Artists int `json:"artists"`
|
||||
Albums int `json:"albums"`
|
||||
Hours float64 `json:"hours"`
|
||||
TopArtists []string `json:"top_artists"`
|
||||
Recommended int `json:"recommended_artists"`
|
||||
LibraryAlbums int `json:"library_albums"`
|
||||
Downloads int `json:"downloads"`
|
||||
Skipped int `json:"skipped"`
|
||||
PlaylistTracks int `json:"playlist_tracks"`
|
||||
}
|
||||
|
||||
type AlbumPlan struct {
|
||||
Artist string `json:"artist"`
|
||||
Name string `json:"name"`
|
||||
MBID string `json:"mbid,omitempty"`
|
||||
Playcount int `json:"playcount"`
|
||||
TrackCount int `json:"track_count"`
|
||||
InLibrary bool `json:"in_library"`
|
||||
AlbumID string `json:"album_id,omitempty"`
|
||||
QobuzID string `json:"qobuz_id,omitempty"`
|
||||
QobuzTitle string `json:"qobuz_title,omitempty"`
|
||||
QobuzScore float64 `json:"qobuz_score,omitempty"`
|
||||
Score float64 `json:"score,omitempty"`
|
||||
Action string `json:"action"` // library, download, skipped
|
||||
SelectedSongs []navidrome.Song `json:"selected_songs,omitempty"`
|
||||
TopTracks []lastfm.Track `json:"-"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type ArtistPlan struct {
|
||||
Artist string `json:"artist"`
|
||||
Score float64 `json:"score"`
|
||||
Similarity float64 `json:"similarity"`
|
||||
Seeds []string `json:"seeds"`
|
||||
InLibrary bool `json:"in_library"`
|
||||
LibraryTracks []navidrome.Song `json:"library_tracks,omitempty"`
|
||||
Album *AlbumPlan `json:"album,omitempty"`
|
||||
Action string `json:"action"` // library, download, skipped
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type PlaylistTrack struct {
|
||||
SongID string `json:"song_id"`
|
||||
Artist string `json:"artist"`
|
||||
Title string `json:"title"`
|
||||
Album string `json:"album"`
|
||||
Source string `json:"source"`
|
||||
Score float64 `json:"score"`
|
||||
Order int `json:"order"`
|
||||
}
|
||||
|
||||
type Plan struct {
|
||||
GeneratedAt string `json:"generated_at"`
|
||||
WindowDays int `json:"window_days"`
|
||||
PlaylistName string `json:"playlist_name"`
|
||||
Stats Stats `json:"stats"`
|
||||
SeedArtists []SeedArtist `json:"seed_artists"`
|
||||
SeedTracks []SeedTrack `json:"seed_tracks"`
|
||||
SeedAlbums []AlbumPlan `json:"seed_albums"`
|
||||
Artists []ArtistPlan `json:"artists"`
|
||||
Downloads []AlbumPlan `json:"downloads"`
|
||||
Playlist []PlaylistTrack `json:"playlist"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
History *historyData `json:"-"`
|
||||
}
|
||||
|
||||
type playlistHistory map[string]int
|
||||
|
||||
type historyData struct {
|
||||
AllSongs map[string]navidrome.Song
|
||||
Window []navidrome.Scrobble
|
||||
ArtistPlays map[string]int
|
||||
ArtistWeight map[string]float64
|
||||
TrackPlays map[string]int
|
||||
TrackWeight map[string]float64
|
||||
TrackMeta map[string]SeedTrack
|
||||
HeardTracks map[string]bool
|
||||
HeardAlbums map[string]bool
|
||||
HeardAlbumKeys map[string]bool
|
||||
Stats Stats
|
||||
}
|
||||
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
Reference in new issue
Block a user