Initial commit: LastRecc discovery feed and weekly engine
This commit is contained in:
40 files changed
+6972
No files matched your search
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
type JSONCache struct {
|
||||
Dir string
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
func (c JSONCache) path(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return filepath.Join(c.Dir, hex.EncodeToString(sum[:])+".json")
|
||||
}
|
||||
|
||||
func (c JSONCache) Get(key string, out any) bool {
|
||||
path := c.path(key)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || time.Since(info.ModTime()) > c.TTL {
|
||||
return false
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return json.Unmarshal(data, out) == nil
|
||||
}
|
||||
|
||||
func (c JSONCache) GetBytes(key string) ([]byte, bool) {
|
||||
path := c.path(key)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || time.Since(info.ModTime()) > c.TTL {
|
||||
return nil, false
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
return data, err == nil
|
||||
}
|
||||
|
||||
func (c JSONCache) Set(key string, value any) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.SetBytes(key, data)
|
||||
}
|
||||
|
||||
func (c JSONCache) SetBytes(key string, data []byte) error {
|
||||
return WriteFileAtomic(c.path(key), data)
|
||||
}
|
||||
|
||||
func LoadJSON(path string, out any) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(data, out)
|
||||
}
|
||||
|
||||
func SaveJSON(path string, value any) error {
|
||||
data, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return WriteFileAtomic(path, data)
|
||||
}
|
||||
|
||||
func WriteFileAtomic(path string, data []byte) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer func() {
|
||||
_ = os.Remove(tmp)
|
||||
}()
|
||||
if _, err := f.Write(data); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
func Fresh(path string, ttl time.Duration) bool {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return time.Since(info.ModTime()) <= ttl
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultDays = 7
|
||||
defaultSeedArtists = 10
|
||||
defaultSeedTracks = 10
|
||||
defaultTracksPerAlbum = 3
|
||||
defaultPlaylistMax = 60
|
||||
defaultRepeatWeeks = 4
|
||||
defaultScanTimeout = 30 * time.Minute
|
||||
defaultSettle = 5 * time.Second
|
||||
defaultSearchDelay = 800 * time.Millisecond
|
||||
defaultPlaylistName = "LastRecc Weekly"
|
||||
defaultScan = true
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
EnvPath string
|
||||
|
||||
NavidromeURL string
|
||||
NavidromeUser string
|
||||
NavidromePassword string
|
||||
BasicUser string
|
||||
BasicPassword string
|
||||
ScanUser string
|
||||
ScanPassword string
|
||||
|
||||
LastFMKey string
|
||||
|
||||
Days int
|
||||
SeedArtists int
|
||||
SeedTracks int
|
||||
MaxArtists int
|
||||
TracksPerAlbum int
|
||||
PlaylistMaxTracks int
|
||||
PlaylistName string
|
||||
RepeatWeeks int
|
||||
Scan bool
|
||||
ScanTimeout time.Duration
|
||||
Settle time.Duration
|
||||
SearchDelay time.Duration
|
||||
RipBinary string
|
||||
RipConfig string
|
||||
Quality int
|
||||
StateDir string
|
||||
Verbose bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
func Load(envPath string, getenv func(string) string) (*Config, error) {
|
||||
path := findEnv(envPath)
|
||||
if path != "" {
|
||||
if err := loadDotEnv(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
cfg := &Config{
|
||||
EnvPath: path,
|
||||
NavidromeURL: strings.TrimRight(getenv("NAVIDROME_URL"), "/"),
|
||||
NavidromeUser: getenv("NAVIDROME_USER"),
|
||||
NavidromePassword: getenv("NAVIDROME_PASSWORD"),
|
||||
BasicUser: getenv("NAVIDROME_BASIC_USER"),
|
||||
BasicPassword: getenv("NAVIDROME_BASIC_PASSWORD"),
|
||||
ScanUser: getenv("SCAN_USER"),
|
||||
ScanPassword: getenv("SCAN_PASSWORD"),
|
||||
LastFMKey: getenv("LASTFM_API_KEY"),
|
||||
Days: envInt(getenv, "DAYS", defaultDays),
|
||||
SeedArtists: envInt(getenv, "SEED_ARTISTS", defaultSeedArtists),
|
||||
SeedTracks: envInt(getenv, "SEED_TRACKS", defaultSeedTracks),
|
||||
MaxArtists: envInt(getenv, "MAX_ARTISTS", 30),
|
||||
TracksPerAlbum: envInt(getenv, "TRACKS_PER_ALBUM", defaultTracksPerAlbum),
|
||||
PlaylistMaxTracks: envInt(getenv, "PLAYLIST_MAX_TRACKS", defaultPlaylistMax),
|
||||
PlaylistName: envString(getenv, "PLAYLIST_NAME", defaultPlaylistName),
|
||||
RepeatWeeks: envInt(getenv, "REPEAT_WINDOW_WEEKS", defaultRepeatWeeks),
|
||||
Scan: envBool(getenv, "SCAN", defaultScan),
|
||||
ScanTimeout: time.Duration(envInt(getenv, "SCAN_TIMEOUT_SECONDS", int(defaultScanTimeout.Seconds()))) * time.Second,
|
||||
Settle: time.Duration(envInt(getenv, "SCAN_SETTLE_SECONDS", int(defaultSettle.Seconds()))) * time.Second,
|
||||
SearchDelay: time.Duration(envInt(getenv, "SEARCH_DELAY_MS", int(defaultSearchDelay.Milliseconds()))) * time.Millisecond,
|
||||
RipBinary: envString(getenv, "RIP_BINARY", defaultRipBinary()),
|
||||
RipConfig: getenv("RIP_CONFIG"),
|
||||
Quality: envInt(getenv, "QUALITY", -1),
|
||||
StateDir: envString(getenv, "STATE_DIR", "state"),
|
||||
}
|
||||
if cfg.ScanUser == "" {
|
||||
cfg.ScanUser = cfg.NavidromeUser
|
||||
cfg.ScanPassword = cfg.NavidromePassword
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
var missing []string
|
||||
if c.NavidromeURL == "" {
|
||||
missing = append(missing, "NAVIDROME_URL")
|
||||
}
|
||||
if c.NavidromeUser == "" {
|
||||
missing = append(missing, "NAVIDROME_USER")
|
||||
}
|
||||
if c.NavidromePassword == "" {
|
||||
missing = append(missing, "NAVIDROME_PASSWORD")
|
||||
}
|
||||
if c.LastFMKey == "" {
|
||||
missing = append(missing, "LASTFM_API_KEY")
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return fmt.Errorf("missing %s (looked at %s)", strings.Join(missing, ", "), c.EnvPath)
|
||||
}
|
||||
if c.Days < 1 || c.Days > 90 {
|
||||
return fmt.Errorf("DAYS must be between 1 and 90")
|
||||
}
|
||||
if c.TracksPerAlbum < 1 {
|
||||
c.TracksPerAlbum = defaultTracksPerAlbum
|
||||
}
|
||||
if c.PlaylistMaxTracks < 0 {
|
||||
c.PlaylistMaxTracks = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findEnv(explicit string) string {
|
||||
if explicit != "" {
|
||||
return explicit
|
||||
}
|
||||
for _, candidate := range []string{".env", "../.env", "../../.env"} {
|
||||
if fileExists(candidate) {
|
||||
abs, _ := filepath.Abs(candidate)
|
||||
return abs
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func loadDotEnv(path string) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
line = strings.TrimPrefix(line, "export ")
|
||||
key, value, ok := strings.Cut(line, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key = strings.TrimSpace(key)
|
||||
value = strings.TrimSpace(value)
|
||||
if len(value) >= 2 && ((value[0] == '"' && value[len(value)-1] == '"') || (value[0] == '\'' && value[len(value)-1] == '\'')) {
|
||||
value = value[1 : len(value)-1]
|
||||
}
|
||||
if _, exists := os.LookupEnv(key); !exists {
|
||||
_ = os.Setenv(key, value)
|
||||
}
|
||||
}
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
func defaultRipBinary() string {
|
||||
// Prefer a bundled Go `rip` next to this binary, then the local clone.
|
||||
// A Python streamrip `rip` may also be on PATH and has a different
|
||||
// CLI/config format.
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
sibling := filepath.Join(filepath.Dir(exe), "rip")
|
||||
if fileExists(sibling) {
|
||||
return sibling
|
||||
}
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
fallback := filepath.Join(home, "cloned", "streamrip-go", "rip")
|
||||
if fileExists(fallback) {
|
||||
return fallback
|
||||
}
|
||||
if p, err := exec.LookPath("rip"); err == nil {
|
||||
return p
|
||||
}
|
||||
return "rip"
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
func envString(getenv func(string) string, key, fallback string) string {
|
||||
if value := strings.TrimSpace(getenv(key)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(getenv func(string) string, key string, fallback int) int {
|
||||
value := strings.TrimSpace(getenv(key))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func envBool(getenv func(string) string, key string, fallback bool) bool {
|
||||
value := strings.ToLower(strings.TrimSpace(getenv(key)))
|
||||
switch value {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
case "0", "false", "no", "off":
|
||||
return false
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package httpclient
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BasicAuth struct {
|
||||
User string
|
||||
Password string
|
||||
}
|
||||
|
||||
type StatusError struct {
|
||||
Status int
|
||||
URL string
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *StatusError) Error() string {
|
||||
return fmt.Sprintf("HTTP %d for %s: %s", e.Status, e.URL, truncate(e.Body, 240))
|
||||
}
|
||||
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
interval time.Duration
|
||||
next time.Time
|
||||
}
|
||||
|
||||
func NewRateLimiter(perSecond float64) *RateLimiter {
|
||||
if perSecond <= 0 {
|
||||
perSecond = 1
|
||||
}
|
||||
return &RateLimiter{interval: time.Duration(float64(time.Second) / perSecond)}
|
||||
}
|
||||
|
||||
func (r *RateLimiter) Wait(ctx context.Context) error {
|
||||
r.mu.Lock()
|
||||
now := time.Now()
|
||||
delay := time.Duration(0)
|
||||
if now.Before(r.next) {
|
||||
delay = r.next.Sub(now)
|
||||
}
|
||||
r.next = maxTime(now, r.next).Add(r.interval)
|
||||
r.mu.Unlock()
|
||||
if delay <= 0 {
|
||||
return nil
|
||||
}
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
HTTP *http.Client
|
||||
UA string
|
||||
Basic *BasicAuth
|
||||
Limiter *RateLimiter
|
||||
}
|
||||
|
||||
func New(ua string, basic *BasicAuth, limiter *RateLimiter) *Client {
|
||||
return &Client{
|
||||
HTTP: &http.Client{Timeout: 60 * time.Second},
|
||||
UA: ua,
|
||||
Basic: basic,
|
||||
Limiter: limiter,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Get(ctx context.Context, rawURL string, params url.Values) ([]byte, http.Header, error) {
|
||||
if len(params) > 0 {
|
||||
sep := "?"
|
||||
if strings.Contains(rawURL, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
rawURL += sep + params.Encode()
|
||||
}
|
||||
return c.do(ctx, http.MethodGet, rawURL, nil, nil)
|
||||
}
|
||||
|
||||
func (c *Client) GetJSON(ctx context.Context, rawURL string, params url.Values, out any) error {
|
||||
data, _, err := c.Get(ctx, rawURL, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(data, out)
|
||||
}
|
||||
|
||||
func (c *Client) GetWithHeaders(ctx context.Context, rawURL string, params url.Values, headers map[string]string) ([]byte, http.Header, error) {
|
||||
if len(params) > 0 {
|
||||
sep := "?"
|
||||
if strings.Contains(rawURL, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
rawURL += sep + params.Encode()
|
||||
}
|
||||
return c.do(ctx, http.MethodGet, rawURL, nil, headers)
|
||||
}
|
||||
|
||||
func (c *Client) PostJSON(ctx context.Context, rawURL string, value any) ([]byte, http.Header, error) {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
headers := map[string]string{"Content-Type": "application/json"}
|
||||
return c.do(ctx, http.MethodPost, rawURL, data, headers)
|
||||
}
|
||||
|
||||
func (c *Client) PostForm(ctx context.Context, rawURL string, values url.Values) ([]byte, http.Header, error) {
|
||||
headers := map[string]string{"Content-Type": "application/x-www-form-urlencoded"}
|
||||
return c.do(ctx, http.MethodPost, rawURL, []byte(values.Encode()), headers)
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, rawURL string, body []byte, headers map[string]string) ([]byte, http.Header, error) {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= 3; attempt++ {
|
||||
if c.Limiter != nil {
|
||||
if err := c.Limiter.Wait(ctx); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
var bodyReader io.Reader
|
||||
if body != nil {
|
||||
bodyReader = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, bodyReader)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", c.UA)
|
||||
req.Header.Set("Accept", "application/json, text/plain, */*")
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
if c.Basic != nil {
|
||||
req.SetBasicAuth(c.Basic.User, c.Basic.Password)
|
||||
}
|
||||
for key, value := range headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
if attempt == 3 {
|
||||
return nil, nil, err
|
||||
}
|
||||
sleep(ctx, attempt)
|
||||
continue
|
||||
}
|
||||
data, readErr := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if readErr != nil {
|
||||
lastErr = readErr
|
||||
sleep(ctx, attempt)
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode < 400 {
|
||||
return data, resp.Header, nil
|
||||
}
|
||||
statusErr := &StatusError{
|
||||
Status: resp.StatusCode,
|
||||
URL: redactURL(rawURL),
|
||||
Body: string(data),
|
||||
}
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
return nil, resp.Header, statusErr
|
||||
}
|
||||
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
|
||||
lastErr = statusErr
|
||||
if attempt == 3 {
|
||||
return nil, resp.Header, statusErr
|
||||
}
|
||||
sleep(ctx, attempt)
|
||||
continue
|
||||
}
|
||||
return nil, resp.Header, statusErr
|
||||
}
|
||||
return nil, nil, lastErr
|
||||
}
|
||||
|
||||
func sleep(ctx context.Context, attempt int) {
|
||||
delay := time.Duration(1<<attempt)*500*time.Millisecond + time.Duration(rand.Intn(300))*time.Millisecond
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
|
||||
func redactURL(raw string) string {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
parsed.RawQuery = ""
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
if len(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return value[:limit] + "…"
|
||||
}
|
||||
|
||||
func maxTime(a, b time.Time) time.Time {
|
||||
if a.After(b) {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package lastfm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"lastrecc-go/internal/cache"
|
||||
"lastrecc-go/internal/httpclient"
|
||||
)
|
||||
|
||||
const apiRoot = "https://ws.audioscrobbler.com/2.0/"
|
||||
|
||||
type FlexFloat float64
|
||||
|
||||
func (f *FlexFloat) UnmarshalJSON(data []byte) error {
|
||||
if len(data) == 0 || string(data) == "null" {
|
||||
*f = 0
|
||||
return nil
|
||||
}
|
||||
if data[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
v, _ := strconv.ParseFloat(s, 64)
|
||||
*f = FlexFloat(v)
|
||||
return nil
|
||||
}
|
||||
var v float64
|
||||
if err := json.Unmarshal(data, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
*f = FlexFloat(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
type FlexInt int
|
||||
|
||||
func (f *FlexInt) UnmarshalJSON(data []byte) error {
|
||||
if len(data) == 0 || string(data) == "null" {
|
||||
*f = 0
|
||||
return nil
|
||||
}
|
||||
if data[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
v, _ := strconv.Atoi(s)
|
||||
*f = FlexInt(v)
|
||||
return nil
|
||||
}
|
||||
var v int
|
||||
if err := json.Unmarshal(data, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
*f = FlexInt(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
type List[T any] []T
|
||||
|
||||
func (l *List[T]) UnmarshalJSON(data []byte) error {
|
||||
if len(data) == 0 || string(data) == "null" {
|
||||
*l = nil
|
||||
return nil
|
||||
}
|
||||
if data[0] == '[' {
|
||||
var items []T
|
||||
if err := json.Unmarshal(data, &items); err != nil {
|
||||
return err
|
||||
}
|
||||
*l = items
|
||||
return nil
|
||||
}
|
||||
var one T
|
||||
if err := json.Unmarshal(data, &one); err != nil {
|
||||
return err
|
||||
}
|
||||
*l = []T{one}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Artist struct {
|
||||
Name string `json:"name"`
|
||||
MBID string `json:"mbid"`
|
||||
URL string `json:"url"`
|
||||
Match FlexFloat `json:"match"`
|
||||
}
|
||||
|
||||
type Track struct {
|
||||
Name string `json:"name"`
|
||||
Artist Artist `json:"artist"`
|
||||
Match FlexFloat `json:"match"`
|
||||
Playcount FlexInt `json:"playcount"`
|
||||
URL string `json:"url"`
|
||||
Duration FlexInt `json:"duration"`
|
||||
}
|
||||
|
||||
type Album struct {
|
||||
Name string `json:"name"`
|
||||
MBID string `json:"mbid"`
|
||||
URL string `json:"url"`
|
||||
Artist Artist `json:"artist"`
|
||||
Playcount FlexInt `json:"playcount"`
|
||||
}
|
||||
|
||||
type AlbumInfo struct {
|
||||
Name string `json:"name"`
|
||||
MBID string `json:"mbid"`
|
||||
URL string `json:"url"`
|
||||
Playcount FlexInt `json:"playcount"`
|
||||
ReleaseDate string `json:"releaseDate"`
|
||||
Tracks struct {
|
||||
Track List[Track] `json:"track"`
|
||||
} `json:"tracks"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
key string
|
||||
http *httpclient.Client
|
||||
cache cache.JSONCache
|
||||
}
|
||||
|
||||
func New(apiKey string, cacheDir string) *Client {
|
||||
return &Client{
|
||||
key: apiKey,
|
||||
http: httpclient.New("LastRecc-Go/0.1", nil, httpclient.NewRateLimiter(4)),
|
||||
cache: cache.JSONCache{Dir: filepath.Join(cacheDir, "lastfm"), TTL: 14 * 24 * time.Hour},
|
||||
}
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
Error int `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (c *Client) call(ctx context.Context, method string, params url.Values, out any) error {
|
||||
values := url.Values{
|
||||
"method": {method},
|
||||
"api_key": {c.key},
|
||||
"format": {"json"},
|
||||
}
|
||||
for key, vals := range params {
|
||||
for _, value := range vals {
|
||||
values.Add(key, value)
|
||||
}
|
||||
}
|
||||
cacheKey := method + "::" + values.Encode()
|
||||
if raw, ok := c.cache.GetBytes(cacheKey); ok {
|
||||
if err := json.Unmarshal(raw, out); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
raw, _, err := c.http.Get(ctx, apiRoot, values)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lastfm %s: %w", method, err)
|
||||
}
|
||||
var apiErr apiError
|
||||
if err := json.Unmarshal(raw, &apiErr); err == nil && apiErr.Error != 0 {
|
||||
return fmt.Errorf("lastfm %s: %s", method, apiErr.Message)
|
||||
}
|
||||
if err := json.Unmarshal(raw, out); err != nil {
|
||||
return fmt.Errorf("lastfm %s decode: %w", method, err)
|
||||
}
|
||||
_ = c.cache.SetBytes(cacheKey, raw)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) SimilarArtists(ctx context.Context, artist string, limit int) ([]Artist, error) {
|
||||
var response struct {
|
||||
Similar struct {
|
||||
Artist List[Artist] `json:"artist"`
|
||||
} `json:"similarartists"`
|
||||
}
|
||||
err := c.call(ctx, "artist.getSimilar", url.Values{
|
||||
"artist": {artist},
|
||||
"limit": {strconv.Itoa(limit)},
|
||||
"autocorrect": {"1"},
|
||||
}, &response)
|
||||
return response.Similar.Artist, err
|
||||
}
|
||||
|
||||
func (c *Client) SimilarTracks(ctx context.Context, artist, track string, limit int) ([]Track, error) {
|
||||
var response struct {
|
||||
Similar struct {
|
||||
Track List[Track] `json:"track"`
|
||||
} `json:"similartracks"`
|
||||
}
|
||||
err := c.call(ctx, "track.getSimilar", url.Values{
|
||||
"artist": {artist},
|
||||
"track": {track},
|
||||
"limit": {strconv.Itoa(limit)},
|
||||
"autocorrect": {"1"},
|
||||
}, &response)
|
||||
return response.Similar.Track, err
|
||||
}
|
||||
|
||||
func (c *Client) ArtistTopTracks(ctx context.Context, artist string, limit int) ([]Track, error) {
|
||||
var response struct {
|
||||
Top struct {
|
||||
Track List[Track] `json:"track"`
|
||||
} `json:"toptracks"`
|
||||
}
|
||||
err := c.call(ctx, "artist.getTopTracks", url.Values{
|
||||
"artist": {artist},
|
||||
"limit": {strconv.Itoa(limit)},
|
||||
"autocorrect": {"1"},
|
||||
}, &response)
|
||||
return response.Top.Track, err
|
||||
}
|
||||
|
||||
func (c *Client) ArtistTopAlbums(ctx context.Context, artist string, limit int) ([]Album, error) {
|
||||
var response struct {
|
||||
Top struct {
|
||||
Album List[Album] `json:"album"`
|
||||
} `json:"topalbums"`
|
||||
}
|
||||
err := c.call(ctx, "artist.getTopAlbums", url.Values{
|
||||
"artist": {artist},
|
||||
"limit": {strconv.Itoa(limit)},
|
||||
"autocorrect": {"1"},
|
||||
}, &response)
|
||||
return response.Top.Album, err
|
||||
}
|
||||
|
||||
func (c *Client) AlbumInfo(ctx context.Context, artist, album string) (AlbumInfo, error) {
|
||||
var response struct {
|
||||
Album AlbumInfo `json:"album"`
|
||||
}
|
||||
err := c.call(ctx, "album.getInfo", url.Values{
|
||||
"artist": {artist},
|
||||
"album": {album},
|
||||
"autocorrect": {"1"},
|
||||
}, &response)
|
||||
return response.Album, err
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
package navidrome
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"lastrecc-go/internal/cache"
|
||||
"lastrecc-go/internal/config"
|
||||
"lastrecc-go/internal/httpclient"
|
||||
"lastrecc-go/internal/text"
|
||||
)
|
||||
|
||||
type Song struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Artist string `json:"artist"`
|
||||
Album string `json:"album"`
|
||||
AlbumID string `json:"albumId"`
|
||||
ArtistID string `json:"artistId"`
|
||||
CoverArt string `json:"coverArt"`
|
||||
Duration float64 `json:"duration"`
|
||||
PlayCount int `json:"playCount"`
|
||||
Played string `json:"played"`
|
||||
}
|
||||
|
||||
type Scrobble struct {
|
||||
ID int64 `json:"id"`
|
||||
MediaFileID string `json:"mediaFileId"`
|
||||
SubmissionTime int64 `json:"submissionTime"`
|
||||
}
|
||||
|
||||
type Album struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Artist string `json:"artist"`
|
||||
ArtistID string `json:"artistId"`
|
||||
CoverArt string `json:"coverArt"`
|
||||
SongCount int `json:"songCount"`
|
||||
Duration float64 `json:"duration"`
|
||||
PlayCount int `json:"playCount"`
|
||||
Played string `json:"played"`
|
||||
}
|
||||
|
||||
type Artist struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type Playlist struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SongCount int `json:"songCount"`
|
||||
}
|
||||
|
||||
type ScanStatus struct {
|
||||
Scanning bool
|
||||
Count int
|
||||
LastScan string
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
cfg *config.Config
|
||||
http *httpclient.Client
|
||||
cacheDir string
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
salt string
|
||||
subToken string
|
||||
}
|
||||
|
||||
type loginResponse struct {
|
||||
Token string `json:"token"`
|
||||
SubsonicSalt string `json:"subsonicSalt"`
|
||||
SubsonicToken string `json:"subsonicToken"`
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, cacheDir string) *Client {
|
||||
var basic *httpclient.BasicAuth
|
||||
if cfg.BasicUser != "" {
|
||||
basic = &httpclient.BasicAuth{User: cfg.BasicUser, Password: cfg.BasicPassword}
|
||||
}
|
||||
return &Client{
|
||||
cfg: cfg,
|
||||
http: httpclient.New("LastRecc-Go/0.1", basic, httpclient.NewRateLimiter(8)),
|
||||
cacheDir: cacheDir,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Login(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
body, _, err := c.http.PostJSON(ctx, c.cfg.NavidromeURL+"/auth/login", map[string]string{
|
||||
"username": c.cfg.NavidromeUser,
|
||||
"password": c.cfg.NavidromePassword,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("navidrome login: %w", err)
|
||||
}
|
||||
var resp loginResponse
|
||||
if err := json.Unmarshal(body, &resp); err != nil {
|
||||
return fmt.Errorf("navidrome login response: %w", err)
|
||||
}
|
||||
if resp.Token == "" || resp.SubsonicSalt == "" || resp.SubsonicToken == "" {
|
||||
return fmt.Errorf("navidrome login: incomplete response")
|
||||
}
|
||||
c.token = resp.Token
|
||||
c.salt = resp.SubsonicSalt
|
||||
c.subToken = resp.SubsonicToken
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureLogin(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
ok := c.token != ""
|
||||
c.mu.Unlock()
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
return c.Login(ctx)
|
||||
}
|
||||
|
||||
func (c *Client) nativeGet(ctx context.Context, path string, params url.Values) ([]byte, http.Header, error) {
|
||||
if err := c.ensureLogin(ctx); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
c.mu.Lock()
|
||||
token := c.token
|
||||
c.mu.Unlock()
|
||||
data, headers, err := c.http.GetWithHeaders(ctx, c.cfg.NavidromeURL+path, params, map[string]string{
|
||||
"X-ND-Authorization": "Bearer " + token,
|
||||
})
|
||||
if err != nil {
|
||||
if statusErr, ok := err.(*httpclient.StatusError); ok && statusErr.Status == http.StatusUnauthorized && attempt == 0 {
|
||||
if loginErr := c.Login(ctx); loginErr != nil {
|
||||
return nil, nil, loginErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
return data, headers, nil
|
||||
}
|
||||
return nil, nil, fmt.Errorf("navidrome request failed after re-authentication")
|
||||
}
|
||||
|
||||
type scrobbleCache struct {
|
||||
FetchedAt int64 `json:"fetched_at"`
|
||||
Items []Scrobble `json:"items"`
|
||||
}
|
||||
|
||||
func (c *Client) Scrobbles(ctx context.Context, force bool) ([]Scrobble, error) {
|
||||
cachePath := filepath.Join(c.cacheDir, "scrobbles.json")
|
||||
if !force && cache.Fresh(cachePath, 10*time.Minute) {
|
||||
var cached scrobbleCache
|
||||
if err := cache.LoadJSON(cachePath, &cached); err == nil && cached.Items != nil {
|
||||
return cached.Items, nil
|
||||
}
|
||||
}
|
||||
var items []Scrobble
|
||||
start := 0
|
||||
for {
|
||||
params := url.Values{
|
||||
"_end": {"5000"},
|
||||
"_order": {"DESC"},
|
||||
"_sort": {"submission_time"},
|
||||
"_start": {strconv.Itoa(start)},
|
||||
}
|
||||
data, headers, err := c.nativeGet(ctx, "/api/scrobble", params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var chunk []Scrobble
|
||||
if err := json.Unmarshal(data, &chunk); err != nil {
|
||||
return nil, fmt.Errorf("decode scrobbles: %w", err)
|
||||
}
|
||||
items = append(items, chunk...)
|
||||
total, _ := strconv.Atoi(headers.Get("X-Total-Count"))
|
||||
if len(chunk) == 0 || (total > 0 && len(items) >= total) {
|
||||
break
|
||||
}
|
||||
start += len(chunk)
|
||||
if start > 200000 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := cache.SaveJSON(cachePath, scrobbleCache{FetchedAt: time.Now().Unix(), Items: items}); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "warning: could not save scrobble cache: %v\n", err)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (c *Client) Songs(ctx context.Context, ids []string, logf func(string, ...any)) (map[string]Song, error) {
|
||||
cachePath := filepath.Join(c.cacheDir, "navidrome_songs.json")
|
||||
all := map[string]Song{}
|
||||
if err := cache.LoadJSON(cachePath, &all); err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintf(os.Stderr, "warning: could not read song cache: %v\n", err)
|
||||
}
|
||||
if all == nil {
|
||||
all = map[string]Song{}
|
||||
}
|
||||
var missing []string
|
||||
for _, id := range ids {
|
||||
if _, ok := all[id]; !ok {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
for offset := 0; offset < len(missing); offset += 80 {
|
||||
end := offset + 80
|
||||
if end > len(missing) {
|
||||
end = len(missing)
|
||||
}
|
||||
params := url.Values{}
|
||||
for _, id := range missing[offset:end] {
|
||||
params.Add("id", id)
|
||||
}
|
||||
data, _, err := c.nativeGet(ctx, "/api/song", params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var songs []Song
|
||||
if err := json.Unmarshal(data, &songs); err != nil {
|
||||
return nil, fmt.Errorf("decode songs: %w", err)
|
||||
}
|
||||
for _, song := range songs {
|
||||
if song.ID != "" {
|
||||
all[song.ID] = song
|
||||
}
|
||||
}
|
||||
if logf != nil {
|
||||
logf("metadata %d/%d", min(end, len(missing)), len(missing))
|
||||
}
|
||||
if err := cache.SaveJSON(cachePath, all); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "warning: could not save song cache: %v\n", err)
|
||||
}
|
||||
}
|
||||
result := make(map[string]Song, len(ids))
|
||||
for _, id := range ids {
|
||||
if song, ok := all[id]; ok {
|
||||
result[id] = song
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *Client) subsonic(ctx context.Context, method string, params url.Values, post bool) (map[string]any, error) {
|
||||
if err := c.ensureLogin(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.mu.Lock()
|
||||
salt, token := c.salt, c.subToken
|
||||
c.mu.Unlock()
|
||||
values := url.Values{
|
||||
"u": {c.cfg.NavidromeUser},
|
||||
"t": {token},
|
||||
"s": {salt},
|
||||
"v": {"1.16.1"},
|
||||
"c": {"LastRecc-Go"},
|
||||
"f": {"json"},
|
||||
}
|
||||
for key, vals := range params {
|
||||
for _, value := range vals {
|
||||
values.Add(key, value)
|
||||
}
|
||||
}
|
||||
rawURL := c.cfg.NavidromeURL + "/rest/" + method + ".view"
|
||||
var data []byte
|
||||
var err error
|
||||
if post {
|
||||
data, _, err = c.http.PostForm(ctx, rawURL, values)
|
||||
} else {
|
||||
data, _, err = c.http.Get(ctx, rawURL, values)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var envelope map[string]any
|
||||
if err := json.Unmarshal(data, &envelope); err != nil {
|
||||
return nil, fmt.Errorf("decode subsonic %s: %w", method, err)
|
||||
}
|
||||
response, _ := envelope["subsonic-response"].(map[string]any)
|
||||
if response == nil {
|
||||
return nil, fmt.Errorf("subsonic %s: missing response", method)
|
||||
}
|
||||
if status, _ := response["status"].(string); status != "ok" {
|
||||
return nil, fmt.Errorf("subsonic %s: %v", method, response["error"])
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c *Client) SearchSongs(ctx context.Context, query string, limit int) ([]Song, error) {
|
||||
response, err := c.subsonic(ctx, "search3", url.Values{
|
||||
"query": {query},
|
||||
"songCount": {strconv.Itoa(limit)},
|
||||
"albumCount": {"0"},
|
||||
"artistCount": {"0"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, _ := response["searchResult3"].(map[string]any)
|
||||
if result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var songs []Song
|
||||
for _, raw := range asList(result["song"]) {
|
||||
if item, ok := raw.(map[string]any); ok {
|
||||
songs = append(songs, parseSong(item))
|
||||
}
|
||||
}
|
||||
return songs, nil
|
||||
}
|
||||
|
||||
func (c *Client) SearchAlbums(ctx context.Context, query string, limit int) ([]Album, error) {
|
||||
response, err := c.subsonic(ctx, "search3", url.Values{
|
||||
"query": {query},
|
||||
"songCount": {"0"},
|
||||
"albumCount": {strconv.Itoa(limit)},
|
||||
"artistCount": {"0"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, _ := response["searchResult3"].(map[string]any)
|
||||
if result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var albums []Album
|
||||
for _, raw := range asList(result["album"]) {
|
||||
if item, ok := raw.(map[string]any); ok {
|
||||
albums = append(albums, Album{
|
||||
ID: asString(item["id"]),
|
||||
Name: asString(item["name"]),
|
||||
Artist: asString(item["artist"]),
|
||||
ArtistID: asString(item["artistId"]),
|
||||
CoverArt: asString(item["coverArt"]),
|
||||
SongCount: asInt(item["songCount"]),
|
||||
Duration: float64(asInt(item["duration"])),
|
||||
PlayCount: asInt(item["playCount"]),
|
||||
Played: asString(item["played"]),
|
||||
})
|
||||
}
|
||||
}
|
||||
return albums, nil
|
||||
}
|
||||
|
||||
func (c *Client) SearchArtists(ctx context.Context, query string, limit int) ([]Artist, error) {
|
||||
response, err := c.subsonic(ctx, "search3", url.Values{
|
||||
"query": {query},
|
||||
"songCount": {"0"},
|
||||
"albumCount": {"0"},
|
||||
"artistCount": {strconv.Itoa(limit)},
|
||||
}, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, _ := response["searchResult3"].(map[string]any)
|
||||
if result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var artists []Artist
|
||||
for _, raw := range asList(result["artist"]) {
|
||||
if item, ok := raw.(map[string]any); ok {
|
||||
artists = append(artists, Artist{ID: asString(item["id"]), Name: asString(item["name"])})
|
||||
}
|
||||
}
|
||||
return artists, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetAlbum(ctx context.Context, id string) (Album, []Song, error) {
|
||||
response, err := c.subsonic(ctx, "getAlbum", url.Values{"id": {id}}, false)
|
||||
if err != nil {
|
||||
return Album{}, nil, err
|
||||
}
|
||||
item, _ := response["album"].(map[string]any)
|
||||
if item == nil {
|
||||
return Album{}, nil, fmt.Errorf("album %s not found", id)
|
||||
}
|
||||
album := Album{
|
||||
ID: asString(item["id"]),
|
||||
Name: asString(item["name"]),
|
||||
Artist: asString(item["artist"]),
|
||||
ArtistID: asString(item["artistId"]),
|
||||
CoverArt: asString(item["coverArt"]),
|
||||
SongCount: asInt(item["songCount"]),
|
||||
Duration: float64(asInt(item["duration"])),
|
||||
PlayCount: asInt(item["playCount"]),
|
||||
Played: asString(item["played"]),
|
||||
}
|
||||
var songs []Song
|
||||
for _, raw := range asList(item["song"]) {
|
||||
if rawMap, ok := raw.(map[string]any); ok {
|
||||
songs = append(songs, parseSong(rawMap))
|
||||
}
|
||||
}
|
||||
return album, songs, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetPlaylists(ctx context.Context) ([]Playlist, error) {
|
||||
response, err := c.subsonic(ctx, "getPlaylists", nil, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
container, _ := response["playlists"].(map[string]any)
|
||||
if container == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var playlists []Playlist
|
||||
for _, raw := range asList(container["playlist"]) {
|
||||
if item, ok := raw.(map[string]any); ok {
|
||||
playlists = append(playlists, Playlist{
|
||||
ID: asString(item["id"]),
|
||||
Name: asString(item["name"]),
|
||||
SongCount: asInt(item["songCount"]),
|
||||
})
|
||||
}
|
||||
}
|
||||
return playlists, nil
|
||||
}
|
||||
|
||||
func (c *Client) CreatePlaylist(ctx context.Context, name string, songIDs []string) error {
|
||||
params := url.Values{"name": {name}}
|
||||
for _, id := range songIDs {
|
||||
params.Add("songId", id)
|
||||
}
|
||||
_, err := c.subsonic(ctx, "createPlaylist", params, true)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) DeletePlaylist(ctx context.Context, id string) error {
|
||||
_, err := c.subsonic(ctx, "deletePlaylist", url.Values{"id": {id}}, true)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) ScanStatus(ctx context.Context) (ScanStatus, error) {
|
||||
response, err := c.subsonic(ctx, "getScanStatus", nil, false)
|
||||
if err != nil {
|
||||
return ScanStatus{}, err
|
||||
}
|
||||
item, _ := response["scanStatus"].(map[string]any)
|
||||
if item == nil {
|
||||
return ScanStatus{}, nil
|
||||
}
|
||||
return ScanStatus{
|
||||
Scanning: asBool(item["scanning"]),
|
||||
Count: asInt(item["count"]),
|
||||
LastScan: asString(item["lastScan"]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) StartScan(ctx context.Context) error {
|
||||
_, err := c.subsonic(ctx, "startScan", nil, true)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) FindArtist(ctx context.Context, artist string) (Artist, bool, error) {
|
||||
artists, err := c.SearchArtists(ctx, artist, 5)
|
||||
if err != nil {
|
||||
return Artist{}, false, err
|
||||
}
|
||||
for _, candidate := range artists {
|
||||
if text.Similarity(candidate.Name, artist) >= 0.9 {
|
||||
return candidate, true, nil
|
||||
}
|
||||
}
|
||||
return Artist{}, false, nil
|
||||
}
|
||||
|
||||
func (c *Client) FindSong(ctx context.Context, artist, title string) (Song, bool, error) {
|
||||
songs, err := c.SearchSongs(ctx, artist+" "+title, 5)
|
||||
if err != nil {
|
||||
return Song{}, false, err
|
||||
}
|
||||
best, bestScore := Song{}, 0.0
|
||||
for _, song := range songs {
|
||||
score := text.Similarity(song.Title, title)*0.65 + text.Similarity(song.Artist, artist)*0.35
|
||||
if score > bestScore {
|
||||
best, bestScore = song, score
|
||||
}
|
||||
}
|
||||
if bestScore >= 0.86 {
|
||||
return best, true, nil
|
||||
}
|
||||
return Song{}, false, nil
|
||||
}
|
||||
|
||||
func (c *Client) FindAlbum(ctx context.Context, artist, album string) (Album, bool, error) {
|
||||
albums, err := c.SearchAlbums(ctx, artist+" "+album, 8)
|
||||
if err != nil {
|
||||
return Album{}, false, err
|
||||
}
|
||||
best, bestScore := Album{}, 0.0
|
||||
for _, candidate := range albums {
|
||||
score := text.Similarity(candidate.Name, album)*0.65 + text.Similarity(candidate.Artist, artist)*0.35
|
||||
if score > bestScore {
|
||||
best, bestScore = candidate, score
|
||||
}
|
||||
}
|
||||
if bestScore >= 0.86 {
|
||||
return best, true, nil
|
||||
}
|
||||
return Album{}, false, nil
|
||||
}
|
||||
|
||||
func parseSong(item map[string]any) Song {
|
||||
return Song{
|
||||
ID: asString(item["id"]),
|
||||
Title: asString(item["title"]),
|
||||
Artist: asString(item["artist"]),
|
||||
Album: asString(item["album"]),
|
||||
AlbumID: asString(item["albumId"]),
|
||||
ArtistID: asString(item["artistId"]),
|
||||
CoverArt: asString(item["coverArt"]),
|
||||
Duration: float64(asInt(item["duration"])),
|
||||
PlayCount: asInt(item["playCount"]),
|
||||
Played: asString(item["played"]),
|
||||
}
|
||||
}
|
||||
|
||||
func asList(value any) []any {
|
||||
switch v := value.(type) {
|
||||
case []any:
|
||||
return v
|
||||
case map[string]any:
|
||||
return []any{v}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func asString(value any) string {
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return v
|
||||
case float64:
|
||||
return strconv.FormatFloat(v, 'f', -1, 64)
|
||||
case json.Number:
|
||||
return v.String()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func asInt(value any) int {
|
||||
switch v := value.(type) {
|
||||
case float64:
|
||||
return int(v)
|
||||
case int:
|
||||
return v
|
||||
case string:
|
||||
parsed, _ := strconv.Atoi(v)
|
||||
return parsed
|
||||
case json.Number:
|
||||
parsed, _ := v.Int64()
|
||||
return int(parsed)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func asBool(value any) bool {
|
||||
switch v := value.(type) {
|
||||
case bool:
|
||||
return v
|
||||
case string:
|
||||
return strings.EqualFold(v, "true") || v == "1"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package rip
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lastrecc-go/internal/cache"
|
||||
"lastrecc-go/internal/text"
|
||||
)
|
||||
|
||||
var idLineRe = regexp.MustCompile(`(?m)^\s*\d+\.\s+id=([A-Za-z0-9]+)\s+\|\s+(.+?)\s*$`)
|
||||
|
||||
type Hit struct {
|
||||
ID string
|
||||
Title string
|
||||
Score float64
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
Binary string
|
||||
ConfigPath string
|
||||
Quality int
|
||||
SearchDelay time.Duration
|
||||
StateDir string
|
||||
Logf func(string, ...any)
|
||||
}
|
||||
|
||||
func (r *Runner) logf(format string, args ...any) {
|
||||
if r.Logf != nil {
|
||||
r.Logf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) Available() bool {
|
||||
if r.Binary == "" {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(r.Binary, "/") {
|
||||
info, err := os.Stat(r.Binary)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
_, err := exec.LookPath(r.Binary)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (r *Runner) globalArgs() []string {
|
||||
args := []string{"--no-progress"}
|
||||
if r.ConfigPath != "" {
|
||||
args = append(args, "--config-path", r.ConfigPath)
|
||||
}
|
||||
if r.Quality >= 0 {
|
||||
args = append(args, "-q", strconv.Itoa(r.Quality))
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func (r *Runner) search(ctx context.Context, query string) ([]Hit, error) {
|
||||
searchCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
args := append(r.globalArgs(), "search", "qobuz", "album", query, "--no-download", "--first")
|
||||
cmd := exec.CommandContext(searchCtx, r.Binary, args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rip search failed: %w: %s", err, truncate(string(output), 500))
|
||||
}
|
||||
return parseSearchOutput(string(output)), nil
|
||||
}
|
||||
|
||||
func parseSearchOutput(output string) []Hit {
|
||||
if strings.Contains(strings.ToLower(output), "no results") {
|
||||
return nil
|
||||
}
|
||||
matches := idLineRe.FindAllStringSubmatch(output, -1)
|
||||
hits := make([]Hit, 0, len(matches))
|
||||
seen := map[string]bool{}
|
||||
for _, match := range matches {
|
||||
id := match[1]
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
hits = append(hits, Hit{ID: id, Title: strings.TrimSpace(match[2])})
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
// SearchAlbum checks Qobuz for the album and returns the best title match.
|
||||
func (r *Runner) SearchAlbum(ctx context.Context, artist, album string) (*Hit, error) {
|
||||
if r.SearchDelay > 0 {
|
||||
timer := time.NewTimer(r.SearchDelay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return nil, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
queries := []string{artist + " " + album, album + " " + artist, album}
|
||||
var best *Hit
|
||||
for _, query := range queries {
|
||||
hits, err := r.search(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, hit := range hits {
|
||||
if text.IsNoisyAlbum(hit.Title) {
|
||||
continue
|
||||
}
|
||||
score := text.Similarity(hit.Title, album)
|
||||
if best == nil || score > best.Score {
|
||||
candidate := hit
|
||||
candidate.Score = score
|
||||
best = &candidate
|
||||
}
|
||||
}
|
||||
if best != nil && best.Score >= 0.9 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if best == nil || best.Score < 0.9 {
|
||||
return nil, nil
|
||||
}
|
||||
return best, nil
|
||||
}
|
||||
|
||||
type batchItem struct {
|
||||
Source string `json:"source"`
|
||||
MediaType string `json:"media_type"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
// DownloadAlbums writes a batch file and lets streamrip-go fetch all albums
|
||||
// with its own config (Qobuz auth, quality, destination folder, dedupe DB).
|
||||
func (r *Runner) DownloadAlbums(ctx context.Context, hits []Hit) error {
|
||||
if len(hits) == 0 {
|
||||
return nil
|
||||
}
|
||||
items := make([]batchItem, 0, len(hits))
|
||||
for _, hit := range hits {
|
||||
items = append(items, batchItem{Source: "qobuz", MediaType: "album", ID: hit.ID})
|
||||
}
|
||||
if err := os.MkdirAll(r.StateDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
batchPath := filepath.Join(r.StateDir, "qobuz_batch.json")
|
||||
if err := cache.SaveJSON(batchPath, items); err != nil {
|
||||
return err
|
||||
}
|
||||
args := append(r.globalArgs(), "file", batchPath)
|
||||
r.logf("running %s %s", r.Binary, strings.Join(args, " "))
|
||||
cmd := exec.CommandContext(ctx, r.Binary, args...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
if len(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return value[:limit] + "…"
|
||||
}
|
||||
|
||||
var _ = errors.New
|
||||
@@ -0,0 +1,24 @@
|
||||
package rip
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseSearchOutput(t *testing.T) {
|
||||
output := `results: 100
|
||||
1. id=dpkjsfxlbkrwa | Intimate Fonk
|
||||
results: 1
|
||||
1. id=dpkjsfxlbkrwa | Intimate Fonk
|
||||
`
|
||||
hits := parseSearchOutput(output)
|
||||
if len(hits) != 1 {
|
||||
t.Fatalf("expected 1 deduped hit, got %d", len(hits))
|
||||
}
|
||||
if hits[0].ID != "dpkjsfxlbkrwa" || hits[0].Title != "Intimate Fonk" {
|
||||
t.Fatalf("unexpected hit: %+v", hits[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNoResults(t *testing.T) {
|
||||
if hits := parseSearchOutput("no results\n"); len(hits) != 0 {
|
||||
t.Fatalf("expected no hits, got %+v", hits)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package text
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var (
|
||||
parenRe = regexp.MustCompile(`\([^)]*\)|\[[^\]]*\]`)
|
||||
featRe = regexp.MustCompile(`(?i)\b(feat\.?|ft\.?|featuring|with)\b.*$`)
|
||||
noisePhrases = []string{
|
||||
"live", "concert", "greatest hits", "best of", "compilation",
|
||||
"anthology", "collection", "essential", "hits", "remix", "remixes",
|
||||
"tribute", "karaoke", "instrumental", "cover", "edits",
|
||||
"концерт", "живой", "сборник", "лучшее", "хиты",
|
||||
"антология", "коллекция", "избранное", "ремикс", "караоке",
|
||||
"инструментал", "дискография", "трибьют", "кавер",
|
||||
}
|
||||
)
|
||||
|
||||
func Normalize(value string) string {
|
||||
value = strings.ToLower(value)
|
||||
value = parenRe.ReplaceAllString(value, " ")
|
||||
value = featRe.ReplaceAllString(value, " ")
|
||||
var b strings.Builder
|
||||
space := true
|
||||
for _, r := range value {
|
||||
if unicode.IsLetter(r) || unicode.IsDigit(r) {
|
||||
b.WriteRune(r)
|
||||
space = false
|
||||
} else if !space {
|
||||
b.WriteRune(' ')
|
||||
space = true
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(b.String())
|
||||
}
|
||||
|
||||
func TrackKey(artist, title string) string {
|
||||
return Normalize(artist) + "::" + Normalize(title)
|
||||
}
|
||||
|
||||
func AlbumKey(artist, album string) string {
|
||||
return Normalize(artist) + "::" + Normalize(album)
|
||||
}
|
||||
|
||||
func Similarity(a, b string) float64 {
|
||||
a = Normalize(a)
|
||||
b = Normalize(b)
|
||||
if a == "" || b == "" {
|
||||
return 0
|
||||
}
|
||||
if a == b {
|
||||
return 1
|
||||
}
|
||||
distance := levenshtein([]rune(a), []rune(b))
|
||||
maxLen := len([]rune(a))
|
||||
if len([]rune(b)) > maxLen {
|
||||
maxLen = len([]rune(b))
|
||||
}
|
||||
if maxLen == 0 {
|
||||
return 1
|
||||
}
|
||||
return 1 - float64(distance)/float64(maxLen)
|
||||
}
|
||||
|
||||
func levenshtein(a, b []rune) int {
|
||||
if len(a) == 0 {
|
||||
return len(b)
|
||||
}
|
||||
if len(b) == 0 {
|
||||
return len(a)
|
||||
}
|
||||
prev := make([]int, len(b)+1)
|
||||
for j := range prev {
|
||||
prev[j] = j
|
||||
}
|
||||
for i := 1; i <= len(a); i++ {
|
||||
cur := make([]int, len(b)+1)
|
||||
cur[0] = i
|
||||
for j := 1; j <= len(b); j++ {
|
||||
cost := 1
|
||||
if a[i-1] == b[j-1] {
|
||||
cost = 0
|
||||
}
|
||||
cur[j] = min3(cur[j-1]+1, prev[j]+1, prev[j-1]+cost)
|
||||
}
|
||||
prev = cur
|
||||
}
|
||||
return prev[len(b)]
|
||||
}
|
||||
|
||||
func min3(a, b, c int) int {
|
||||
if a < b {
|
||||
if a < c {
|
||||
return a
|
||||
}
|
||||
return c
|
||||
}
|
||||
if b < c {
|
||||
return b
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func IsNoisyAlbum(name string) bool {
|
||||
lower := strings.ToLower(name)
|
||||
replacer := strings.NewReplacer("(", " ", ")", " ", "[", " ", "]", " ", "-", " ", "—", " ")
|
||||
padded := " " + replacer.Replace(lower) + " "
|
||||
for _, phrase := range noisePhrases {
|
||||
if strings.Contains(padded, " "+phrase) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func WeekIndex(t time.Time) int {
|
||||
year, week := t.ISOWeek()
|
||||
return year*100 + week
|
||||
}
|
||||
|
||||
func WeekLabel(t time.Time) string {
|
||||
year, week := t.ISOWeek()
|
||||
return fmt.Sprintf("%d-W%02d", year, week)
|
||||
}
|
||||
|
||||
func FormatDuration(seconds int) string {
|
||||
if seconds <= 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d:%02d", seconds/60, seconds%60)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package text
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeCyrillic(t *testing.T) {
|
||||
got := Normalize("Кино — Звезда по имени Солнце")
|
||||
want := "кино звезда по имени солнце"
|
||||
if got != want {
|
||||
t.Fatalf("Normalize() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeFeaturesAndBrackets(t *testing.T) {
|
||||
got := Normalize("Someday (Remastered 2011) [Live] feat. Someone")
|
||||
if got != "someday" {
|
||||
t.Fatalf("Normalize() = %q, want %q", got, "someday")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoisyAlbums(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"Крылья": false,
|
||||
"Акустический концерт": true,
|
||||
"Квартирные концерты в Москве": true,
|
||||
"Полная Дискография": true,
|
||||
"Greatest Hits": true,
|
||||
"Live at Leeds": true,
|
||||
"Alive": false,
|
||||
"Communiqué": false,
|
||||
}
|
||||
for name, want := range cases {
|
||||
if got := IsNoisyAlbum(name); got != want {
|
||||
t.Errorf("IsNoisyAlbum(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimilarity(t *testing.T) {
|
||||
if Similarity("Кино", "кино") != 1 {
|
||||
t.Fatal("expected case-insensitive exact match")
|
||||
}
|
||||
if Similarity("Someday", "Someday (Remastered)") < 0.9 {
|
||||
t.Fatal("expected high similarity after normalization")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user