From 70287e6310e66b328a335150cee7d8a88caf6ccd Mon Sep 17 00:00:00 2001 From: Joren Date: Mon, 23 Nov 2026 12:40:14 +0100 Subject: [PATCH] Initial commit: LastRecc discovery feed and weekly engine --- .env.example | 26 + .gitignore | 9 + Makefile | 22 + README.md | 154 +++ lastrecc-go/Makefile | 13 + lastrecc-go/README.md | 148 +++ lastrecc-go/cmd/lastrecc/main.go | 443 +++++++++ lastrecc-go/go.mod | 3 + lastrecc-go/internal/cache/cache.go | 102 ++ lastrecc-go/internal/config/config.go | 231 +++++ lastrecc-go/internal/engine/engine_test.go | 93 ++ lastrecc-go/internal/engine/execute.go | 208 ++++ lastrecc-go/internal/engine/history.go | 170 ++++ lastrecc-go/internal/engine/plan.go | 551 +++++++++++ lastrecc-go/internal/engine/types.go | 121 +++ lastrecc-go/internal/httpclient/client.go | 223 +++++ lastrecc-go/internal/lastfm/client.go | 242 +++++ lastrecc-go/internal/navidrome/client.go | 580 +++++++++++ lastrecc-go/internal/rip/rip.go | 172 ++++ lastrecc-go/internal/rip/rip_test.go | 24 + lastrecc-go/internal/text/text.go | 136 +++ lastrecc-go/internal/text/text_test.go | 45 + lastrecc-go/scripts/cron.example | 3 + lastrecc/__init__.py | 3 + lastrecc/__main__.py | 83 ++ lastrecc/cache.py | 59 ++ lastrecc/config.py | 90 ++ lastrecc/lastfm.py | 139 +++ lastrecc/navidrome.py | 203 ++++ lastrecc/net.py | 152 +++ lastrecc/recommend.py | 620 ++++++++++++ lastrecc/server.py | 271 ++++++ lastrecc/text.py | 62 ++ requirements.txt | 1 + tests/__init__.py | 0 tests/test_scoring.py | 22 + tests/test_text.py | 51 + web/app.js | 388 ++++++++ web/index.html | 88 ++ web/style.css | 1021 ++++++++++++++++++++ 40 files changed, 6972 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 lastrecc-go/Makefile create mode 100644 lastrecc-go/README.md create mode 100644 lastrecc-go/cmd/lastrecc/main.go create mode 100644 lastrecc-go/go.mod create mode 100644 lastrecc-go/internal/cache/cache.go create mode 100644 lastrecc-go/internal/config/config.go create mode 100644 lastrecc-go/internal/engine/engine_test.go create mode 100644 lastrecc-go/internal/engine/execute.go create mode 100644 lastrecc-go/internal/engine/history.go create mode 100644 lastrecc-go/internal/engine/plan.go create mode 100644 lastrecc-go/internal/engine/types.go create mode 100644 lastrecc-go/internal/httpclient/client.go create mode 100644 lastrecc-go/internal/lastfm/client.go create mode 100644 lastrecc-go/internal/navidrome/client.go create mode 100644 lastrecc-go/internal/rip/rip.go create mode 100644 lastrecc-go/internal/rip/rip_test.go create mode 100644 lastrecc-go/internal/text/text.go create mode 100644 lastrecc-go/internal/text/text_test.go create mode 100644 lastrecc-go/scripts/cron.example create mode 100644 lastrecc/__init__.py create mode 100644 lastrecc/__main__.py create mode 100644 lastrecc/cache.py create mode 100644 lastrecc/config.py create mode 100644 lastrecc/lastfm.py create mode 100644 lastrecc/navidrome.py create mode 100644 lastrecc/net.py create mode 100644 lastrecc/recommend.py create mode 100644 lastrecc/server.py create mode 100644 lastrecc/text.py create mode 100644 requirements.txt create mode 100644 tests/__init__.py create mode 100644 tests/test_scoring.py create mode 100644 tests/test_text.py create mode 100644 web/app.js create mode 100644 web/index.html create mode 100644 web/style.css diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5497057 --- /dev/null +++ b/.env.example @@ -0,0 +1,26 @@ +# Copy to .env and fill in. +NAVIDROME_URL=https://music.example.com +NAVIDROME_USER=joren +NAVIDROME_PASSWORD=change-me +# Optional: HTTP basic auth in front of Navidrome (reverse proxy) +NAVIDROME_BASIC_USER= +NAVIDROME_BASIC_PASSWORD= +LASTFM_API_KEY=change-me +DAYS=7 +FEED_SIZE=36 +# Optional: the weekly Go engine uses this admin account to trigger a library scan +SCAN_USER= +SCAN_PASSWORD= + +# Weekly Go engine +MAX_ARTISTS=30 +TRACKS_PER_ALBUM=3 +PLAYLIST_MAX_TRACKS=60 +PLAYLIST_NAME=LastRecc Weekly +REPEAT_WINDOW_WEEKS=4 +# RIP_BINARY=/path/to/streamrip-go/rip +# RIP_CONFIG=/home/you/.config/streamrip/config.toml +# QUALITY=3 +# Optional request pacing +LASTFM_RATE=4 +NAVIDROME_RATE=8 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..46cc68b --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.env +.cache/ +lastrecc-go/state/ +lastrecc-go/lastrecc +lastrecc-go/*.log +__pycache__/ +*.py[cod] +.DS_Store +feed.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..59ad3f1 --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +.PHONY: build serve test stats weekly-build weekly-plan weekly + +build: + python3 -m lastrecc build --refresh + +serve: + python3 -m lastrecc serve --warm + +test: + python3 -m unittest discover -s tests -v + +stats: + python3 -m lastrecc stats + +weekly-build: + cd lastrecc-go && go build -o lastrecc ./cmd/lastrecc + +weekly-plan: weekly-build + cd lastrecc-go && ./lastrecc plan + +weekly: weekly-build + cd lastrecc-go && ./lastrecc weekly diff --git a/README.md b/README.md new file mode 100644 index 0000000..010c30b --- /dev/null +++ b/README.md @@ -0,0 +1,154 @@ +# LastRecc + +A personal, Last.fm-powered discovery feed for [Navidrome](https://www.navidrome.org/). + +LastRecc reads your Navidrome scrobble history, finds the artists and tracks you actually played recently, asks Last.fm for similar music, filters out what you've already heard, matches the rest against your library, and serves a card feed you can play from the browser. + +``` +Navidrome scrobbles ──► top artists + tracks ──► Last.fm similarity + │ + filter + rank + diversify + │ + match to library ──► playable cards +``` + +A separate **Go weekly engine** in [`lastrecc-go/`](lastrecc-go/) turns the same +kind of recommendations into a rolling Navidrome playlist, downloading missing +albums through `streamrip-go`/Qobuz and adding only the most popular tracks from +each album. See [lastrecc-go/README.md](lastrecc-go/README.md). + +## Features + +- Rolling 7 / 14 / 30 day window, configurable +- Recency-weighted seeds so this week matters more than last month +- Similar artists **and** similar tracks from Last.fm +- Filters out anything already in your Navidrome scrobble history +- Adds **unplayed albums** from artists you already listen to +- Caps repeats per artist and album for a more varied feed +- Best-effort matching back to your Navidrome library +- Cover art and audio streamed through the local server (credentials never reach the browser) +- Zero third-party dependencies — Python standard library only + +## Quick start + +```bash +cp .env.example .env +# edit .env with your Navidrome and Last.fm credentials + +python -m lastrecc build # build the feed +python -m lastrecc serve # http://127.0.0.1:8787 +``` + +With `make`: + +```bash +make build +make serve +make test + +make weekly-plan # dry-run: what the weekly engine would fetch / playlist +make weekly # fetch missing albums + replace the rolling playlist +``` + +Or warm the cache and serve in one step: + +```bash +python -m lastrecc serve --warm +``` + +## Configuration + +| Variable | Required | Description | +|---|---|---| +| `NAVIDROME_URL` | yes | Base URL, e.g. `https://music.example.com` | +| `NAVIDROME_USER` | yes | Navidrome username | +| `NAVIDROME_PASSWORD` | yes | Navidrome password | +| `NAVIDROME_BASIC_USER` | no | HTTP basic auth user, if a reverse proxy adds one | +| `NAVIDROME_BASIC_PASSWORD` | no | HTTP basic auth password | +| `LASTFM_API_KEY` | yes | Last.fm API key | +| `DAYS` | no | Rolling window, default `7` | +| `FEED_SIZE` | no | Number of cards, default `36` | +| `SEED_ARTISTS` | no | Artist seeds, default `10` | +| `SEED_TRACKS` | no | Track seeds, default `10` | +| `CACHE_DIR` | no | Cache directory, default `.cache` | +| `LASTFM_RATE` | no | Last.fm requests/second, default `4` | +| `NAVIDROME_RATE` | no | Navidrome requests/second, default `8` | + +The app uses two Navidrome APIs: + +- **native API** for login and `/api/scrobble` history +- **Subsonic API** for `search3`, cover art, and streaming + +## CLI + +```bash +python -m lastrecc build [--days 7] [--refresh] [--json] +python -m lastrecc serve [--days 7] [--host 127.0.0.1] [--port 8787] [--warm] +python -m lastrecc stats +``` + +`build --refresh` ignores the scrobble, Last.fm, and feed caches. `serve` rebuilds lazily when the feed cache is older than 15 minutes. + +## How ranking works + +1. Each play gets an exponential recency weight (default half-life: 14 days). +2. Top artists and tracks become seeds. +3. `artist.getSimilar` → top tracks, and `track.getSimilar` → similar tracks. +4. Candidates are dropped if their normalized artist/title already appears in your scrobble history. +5. Score = similarity × seed weight × popularity × novelty. +6. The shortlist is diversified (max 2 per artist, 1 per album). +7. Each candidate is enriched with `track.getInfo`, then matched to your library with `search3`. + +## Caching + +Caches live in `.cache/`: + +| Cache | TTL | +|---|---| +| Feed | 15 minutes | +| Navidrome scrobbles | 10 minutes | +| Last.fm responses | 14 days | +| Navidrome song metadata | persistent | +| Cover art | 7 days | + +Last.fm asks applications to cache and be reasonable with request rates. This project uses a 4 req/s limiter. + +## Project layout + +``` +lastrecc/ + config.py .env loading and settings + navidrome.py native + Subsonic API client + lastfm.py Last.fm client with disk cache + recommend.py seeds, candidates, ranking, enrichment + server.py stdlib HTTP server, API, cover/stream proxy + text.py Unicode-safe normalization and fuzzy matching +web/ + index.html feed UI + app.js rendering, filters, player + style.css styling +tests/ +``` + +## Notes and limitations + +- Last.fm's API is free for **non-commercial** use. For commercial use, contact `partners@last.fm`. +- Last.fm does not expose its own homepage recommendation feed; this project builds an approximation from public similarity endpoints. +- Navidrome's native scrobble history is per user. The credentials in `.env` determine whose feed is built. +- The app binds to `127.0.0.1` by default. If you expose it, put it behind auth — it proxies your music library. +- Cover art rights belong to the respective owners. + +## Troubleshooting + +- **Login fails** — check `NAVIDROME_USER` / `NAVIDROME_PASSWORD`, and `NAVIDROME_BASIC_*` if your reverse proxy adds basic auth. +- **No covers or playback** — covers and streams go through the app's proxy; make sure the Navidrome credentials can access the library. +- **Stale recommendations** — click **Refresh**, or delete `.cache/feed.json` and `.cache/scrobbles.json`. Delete `.cache/lastfm` to bypass the 14-day Last.fm cache after changing seed settings. +- **Last.fm rate limit** — lower `LASTFM_RATE` or wait a minute. The app already limits itself to 4 requests/second. +- **Port in use** — `python -m lastrecc serve --port 8788`. + +## Tests + +```bash +python -m unittest discover -s tests -v +``` + diff --git a/lastrecc-go/Makefile b/lastrecc-go/Makefile new file mode 100644 index 0000000..5118374 --- /dev/null +++ b/lastrecc-go/Makefile @@ -0,0 +1,13 @@ +.PHONY: build plan weekly test + +build: + go build -o lastrecc ./cmd/lastrecc + +plan: build + ./lastrecc plan + +weekly: build + ./lastrecc weekly + +test: + go test ./... diff --git a/lastrecc-go/README.md b/lastrecc-go/README.md new file mode 100644 index 0000000..fad69d4 --- /dev/null +++ b/lastrecc-go/README.md @@ -0,0 +1,148 @@ +# LastRecc Go weekly engine + +The Python app in the repo root is the **discovery UI**. This Go tool is the +**weekly action engine**: it turns the same kind of recommendations into a +rolling Navidrome playlist and, when an album is missing, downloads it through +`streamrip-go` (`~/cloned/streamrip-go` by default). + +```text +last 7 days of scrobbles + │ + ▼ +recency-weighted artist/track seeds + │ + ▼ +Last.fm similar artists + biggest albums + │ + ├── album already in Navidrome → use its unheard top tracks + │ + └── album missing → Qobuz search via `rip` → download album + │ + ▼ + Navidrome scan → resolve new tracks + │ + ▼ + replace "LastRecc Weekly" with top N tracks/album +``` + +## What it does + +- Reads joren's Navidrome scrobble history (native API). +- Scores seeds by plays with a 14-day recency half-life. +- Expands through Last.fm `artist.getSimilar` and `track.getSimilar`. +- Picks each recommended artist's most popular suitable album + (filters live/compilation/hits, etc.). +- If the album is already in the library, it selects tracks that have not been + scrobbled yet. +- If the album is missing, it searches Qobuz with `streamrip-go`, downloads the + album using **your** `rip` config (auth, quality, destination folder), then + triggers a Navidrome scan. +- Adds only the **most popular N tracks per album** to the playlist + (`TRACKS_PER_ALBUM`, default 3) and caps the whole playlist + (`PLAYLIST_MAX_TRACKS`, default 60). +- Replaces one rolling playlist (`PLAYLIST_NAME`, default `LastRecc Weekly`) + each run. Files already in the library are never deleted. +- Remembers recently used tracks (`REPEAT_WINDOW_WEEKS`, default 4) so the next + week is not a repeat. +- Uses a lock file, so overlapping cron runs are skipped. + +## Requirements + +- Go 1.25+ +- A configured `streamrip-go` binary. It can be on `PATH` or set + `RIP_BINARY`. The Go port is preferred; the Python `rip` has a different CLI. +- `streamrip-go` must be logged in to Qobuz and configured to download into a + folder Navidrome scans. This tool does **not** touch those settings. +- `ffmpeg`/`ffprobe` for `rip` tagging/conversion (streamrip-go requirement). + +## Configuration + +The tool reads the repo root `.env` (or `../.env`, or `--env PATH`). The +Navidrome and Last.fm values are shared with the Python app. + +| Variable | Default | Meaning | +|---|---|---| +| `NAVIDROME_URL`, `NAVIDROME_USER`, `NAVIDROME_PASSWORD` | — | Navidrome API | +| `NAVIDROME_BASIC_USER/PASSWORD` | — | optional reverse-proxy basic auth | +| `LASTFM_API_KEY` | — | Last.fm API key | +| `SCAN_USER`, `SCAN_PASSWORD` | main user | admin account used for `startScan` | +| `DAYS` | `7` | scrobble window | +| `MAX_ARTISTS` | `30` | top recommended artists to process, `0` = all | +| `TRACKS_PER_ALBUM` | `3` | most-popular tracks added from each album | +| `PLAYLIST_MAX_TRACKS` | `60` | hard playlist cap, `0` = unlimited | +| `PLAYLIST_NAME` | `LastRecc Weekly` | rolling playlist name | +| `REPEAT_WINDOW_WEEKS` | `4` | avoid tracks used in the last N weeks | +| `RIP_BINARY` | clone/PATH | streamrip-go binary | +| `RIP_CONFIG` | `rip` default | optional `--config-path` | +| `QUALITY` | `rip` default | optional Qobuz quality override (`-1` = config) | +| `SCAN` | `true` | trigger Navidrome scan after downloads | +| `SCAN_TIMEOUT_SECONDS` | `1800` | max wait for a library scan | +| `STATE_DIR` | `./state` | cache, lock and report directory | + +CLI flags override these (`--days`, `--max-artists`, `--tracks-per-album`, +`--playlist-max-tracks`, `--playlist-name`, `--repeat-weeks`, `--rip`, +`--rip-config`, `--quality`, `--state-dir`, `--no-scan`, `--dry-run`). + +## Usage + +```bash +cd lastrecc-go +go build -o lastrecc ./cmd/lastrecc + +./lastrecc seeds # inspect weighted seeds +./lastrecc plan # dry run: albums, library matches, Qobuz hits +./lastrecc plan --json # machine-readable plan +./lastrecc weekly # download missing albums + rebuild playlist +./lastrecc weekly --dry-run # same as plan +``` + +Useful limits while experimenting: + +```bash +./lastrecc plan --max-artists 3 +./lastrecc weekly --max-artists 1 --playlist-name "LastRecc Test" +``` + +The default `MAX_ARTISTS=30` mirrors the scale of the web feed. Set +`--max-artists 0` to process every unique recommended artist; that can queue +dozens of albums, so run `plan` first. + +## Cron + +Run once a week (Monday 06:00), from the Go directory: + +```cron +0 6 * * 1 cd /home/joren/dev/LastRecc/lastrecc-go && ./lastrecc weekly --env /home/joren/dev/LastRecc/.env >> state/weekly.log 2>&1 +``` + +`weekly` takes a lock at `state/weekly.lock`; if a previous run is still going, +the new run exits instead of overlapping. A lock older than 24h is removed +automatically. + +## Output + +- `state/last-run.json` — full report: seeds, artists, albums, Qobuz IDs, + selected tracks, warnings. +- `state/last-plan.json` — dry-run report. +- `state/playlist_history.json` — recent playlist keys used for de-duplication. +- `state/qobuz_batch.json` — the last batch handed to `rip file`. +- `state/cache/` — Navidrome metadata and Last.fm responses. + +The playlist itself is the user-facing output. Old downloaded files remain in +the library; only the playlist contents change. + +## Notes + +- The download step is intentionally delegated to `streamrip-go`. It uses your + own Qobuz account and config; use it only in line with Qobuz's terms. +- The tool assumes `rip` downloads into the Navidrome library. If it does not, + the scan succeeds but the new album will not be found for the playlist. +- Qobuz search is matched by album title + query relevance. `plan` shows the + Qobuz title and match score before anything is downloaded. +- Last.fm's API is non-commercial; this is a personal tool. + +## Tests + +```bash +go test ./... +``` diff --git a/lastrecc-go/cmd/lastrecc/main.go b/lastrecc-go/cmd/lastrecc/main.go new file mode 100644 index 0000000..d053263 --- /dev/null +++ b/lastrecc-go/cmd/lastrecc/main.go @@ -0,0 +1,443 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "lastrecc-go/internal/config" + "lastrecc-go/internal/engine" + "lastrecc-go/internal/lastfm" + "lastrecc-go/internal/navidrome" + "lastrecc-go/internal/rip" +) + +type cliFlags struct { + env string + days int + seedArtists int + seedTracks int + maxArtists int + tracksPerAlbum int + playlistMaxTracks int + playlistName string + repeatWeeks int + ripBinary string + ripConfig string + quality int + stateDir string + scanTimeout time.Duration + noScan bool + dryRun bool + json bool + verbose bool +} + +func main() { + if len(os.Args) < 2 { + usage() + os.Exit(2) + } + command := os.Args[1] + switch command { + case "weekly": + os.Exit(runWeekly(os.Args[2:])) + case "plan": + os.Exit(runPlan(os.Args[2:])) + case "seeds": + os.Exit(runSeeds(os.Args[2:])) + case "help", "-h", "--help": + usage() + case "version": + fmt.Println("lastrecc-go 0.1.0") + default: + fmt.Fprintf(os.Stderr, "unknown command %q\n\n", command) + usage() + os.Exit(2) + } +} + +func usage() { + fmt.Fprint(os.Stderr, `LastRecc weekly engine + +Usage: + lastrecc weekly [flags] build the weekly playlist and fetch missing albums + lastrecc plan [flags] dry-run: show seeds, albums and Qobuz hits + lastrecc seeds [flags] show the weighted listening seeds + lastrecc version + +Options are passed after the command. Common flags: + --env PATH .env file (default: .env or ../.env) + --days N listening window (default 7) + --max-artists N 0 = all recommended artists (default 0) + --tracks-per-album N most-popular tracks taken per album (default 3) + --playlist-max-tracks N hard playlist cap (default 60, 0 = unlimited) + --playlist-name NAME rolling playlist name (default "LastRecc Weekly") + --repeat-weeks N avoid tracks used in the last N playlists (default 4) + --rip PATH streamrip-go binary + --rip-config PATH streamrip-go config path + --quality N override Qobuz quality (default: rip config) + --state-dir PATH cache/state directory (default ./state) + --no-scan do not trigger a Navidrome scan + --dry-run for weekly: plan only + --json print the plan as JSON + --verbose +`) +} + +func bindFlags(fs *flag.FlagSet) *cliFlags { + f := &cliFlags{} + fs.StringVar(&f.env, "env", "", "env file") + fs.IntVar(&f.days, "days", -1, "listening window in days") + fs.IntVar(&f.seedArtists, "seed-artists", -1, "number of artist seeds") + fs.IntVar(&f.seedTracks, "seed-tracks", -1, "number of track seeds") + fs.IntVar(&f.maxArtists, "max-artists", -1, "max recommended artists (0 = all)") + fs.IntVar(&f.tracksPerAlbum, "tracks-per-album", -1, "tracks per album on playlist") + fs.IntVar(&f.playlistMaxTracks, "playlist-max-tracks", -1, "playlist cap") + fs.StringVar(&f.playlistName, "playlist-name", "", "rolling playlist name") + fs.IntVar(&f.repeatWeeks, "repeat-weeks", -1, "avoid tracks used in the last N weeks") + fs.StringVar(&f.ripBinary, "rip", "", "streamrip-go binary") + fs.StringVar(&f.ripConfig, "rip-config", "", "streamrip-go config path") + fs.IntVar(&f.quality, "quality", -1, "Qobuz quality override") + fs.StringVar(&f.stateDir, "state-dir", "", "state directory") + fs.DurationVar(&f.scanTimeout, "scan-timeout", 0, "Navidrome scan timeout") + fs.BoolVar(&f.noScan, "no-scan", false, "do not trigger a scan") + fs.BoolVar(&f.dryRun, "dry-run", false, "plan only") + fs.BoolVar(&f.json, "json", false, "print plan JSON") + fs.BoolVar(&f.verbose, "verbose", false, "verbose logging") + return f +} + +func loadConfig(f *cliFlags, fs *flag.FlagSet, dryRun bool) (*config.Config, error) { + visited := map[string]bool{} + fs.Visit(func(fl *flag.Flag) { visited[fl.Name] = true }) + cfg, err := config.Load(f.env, os.Getenv) + if err != nil { + return nil, err + } + if visited["days"] { + cfg.Days = f.days + } + if visited["seed-artists"] { + cfg.SeedArtists = f.seedArtists + } + if visited["seed-tracks"] { + cfg.SeedTracks = f.seedTracks + } + if visited["max-artists"] { + cfg.MaxArtists = f.maxArtists + } + if visited["tracks-per-album"] { + cfg.TracksPerAlbum = f.tracksPerAlbum + } + if visited["playlist-max-tracks"] { + cfg.PlaylistMaxTracks = f.playlistMaxTracks + } + if visited["playlist-name"] { + cfg.PlaylistName = f.playlistName + } + if visited["repeat-weeks"] { + cfg.RepeatWeeks = f.repeatWeeks + } + if visited["rip"] { + cfg.RipBinary = f.ripBinary + } + if visited["rip-config"] { + cfg.RipConfig = f.ripConfig + } + if visited["quality"] { + cfg.Quality = f.quality + } + if visited["state-dir"] { + cfg.StateDir = f.stateDir + } + if visited["scan-timeout"] && f.scanTimeout > 0 { + cfg.ScanTimeout = f.scanTimeout + } + if f.noScan { + cfg.Scan = false + } + cfg.DryRun = dryRun || f.dryRun + cfg.Verbose = f.verbose + if err := cfg.Validate(); err != nil { + return nil, err + } + abs, err := filepath.Abs(cfg.StateDir) + if err == nil { + cfg.StateDir = abs + } + if err := os.MkdirAll(cfg.StateDir, 0o755); err != nil { + return nil, err + } + return cfg, nil +} + +func options(cfg *config.Config) engine.Options { + return engine.Options{ + Days: cfg.Days, + SeedArtists: cfg.SeedArtists, + SeedTracks: cfg.SeedTracks, + MaxArtists: cfg.MaxArtists, + TracksPerAlbum: cfg.TracksPerAlbum, + PlaylistMaxTracks: cfg.PlaylistMaxTracks, + RepeatWeeks: cfg.RepeatWeeks, + } +} + +func logger(verbose bool) func(string, ...any) { + return func(format string, args ...any) { + _ = verbose + fmt.Fprintf(os.Stderr, "[lastrecc] "+format+"\n", args...) + } +} + +type clients struct { + nav *navidrome.Client + scanNav *navidrome.Client + lastfm *lastfm.Client + rip *rip.Runner +} + +func buildClients(cfg *config.Config, logf func(string, ...any)) *clients { + cacheDir := filepath.Join(cfg.StateDir, "cache") + nav := navidrome.New(cfg, cacheDir) + scanCfg := *cfg + scanCfg.NavidromeUser = cfg.ScanUser + scanCfg.NavidromePassword = cfg.ScanPassword + scanNav := nav + if scanCfg.NavidromeUser != cfg.NavidromeUser || scanCfg.NavidromePassword != cfg.NavidromePassword { + scanNav = navidrome.New(&scanCfg, cacheDir) + } + return &clients{ + nav: nav, + scanNav: scanNav, + lastfm: lastfm.New(cfg.LastFMKey, cacheDir), + rip: &rip.Runner{ + Binary: cfg.RipBinary, + ConfigPath: cfg.RipConfig, + Quality: cfg.Quality, + SearchDelay: cfg.SearchDelay, + StateDir: cfg.StateDir, + Logf: logf, + }, + } +} + +func runSeeds(args []string) int { + fs := flag.NewFlagSet("seeds", flag.ContinueOnError) + f := bindFlags(fs) + if err := fs.Parse(args); err != nil { + return 2 + } + cfg, err := loadConfig(f, fs, true) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + logf := logger(cfg.Verbose) + c := buildClients(cfg, logf) + ctx := context.Background() + artists, tracks, stats, err := engine.LoadSeeds(ctx, c.nav, cfg.Days, cfg.SeedArtists, cfg.SeedTracks, logf) + if err != nil { + fmt.Fprintln(os.Stderr, "seeds:", err) + return 1 + } + fmt.Printf("Window: last %d days\n", cfg.Days) + fmt.Printf("Plays: %d · tracks: %d · artists: %d · albums: %d · %.1fh\n", stats.Plays, stats.UniqueTracks, stats.Artists, stats.Albums, stats.Hours) + fmt.Println("\nArtist seeds:") + for i, seed := range artists { + fmt.Printf(" %2d. %-32s %3d plays weight %.2f\n", i+1, seed.Name, seed.Plays, seed.Weight) + } + fmt.Println("\nTrack seeds:") + for i, seed := range tracks { + fmt.Printf(" %2d. %s — %s (%d plays, weight %.2f)\n", i+1, seed.Artist, seed.Title, seed.Plays, seed.Weight) + } + return 0 +} + +func runPlan(args []string) int { + fs := flag.NewFlagSet("plan", flag.ContinueOnError) + f := bindFlags(fs) + if err := fs.Parse(args); err != nil { + return 2 + } + cfg, err := loadConfig(f, fs, true) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + logf := logger(cfg.Verbose) + c := buildClients(cfg, logf) + ctx := context.Background() + plan, err := engine.BuildPlan(ctx, cfg, options(cfg), c.nav, c.lastfm, c.rip, logf) + if err != nil { + fmt.Fprintln(os.Stderr, "plan:", err) + return 1 + } + if f.json { + data, _ := json.MarshalIndent(plan, "", " ") + fmt.Println(string(data)) + } else { + printPlan(plan) + } + if err := engine.SaveReport(cfg.StateDir, plan); err != nil { + fmt.Fprintf(os.Stderr, "warning: save report: %v\n", err) + } + return 0 +} + +func runWeekly(args []string) int { + fs := flag.NewFlagSet("weekly", flag.ContinueOnError) + f := bindFlags(fs) + if err := fs.Parse(args); err != nil { + return 2 + } + cfg, err := loadConfig(f, fs, false) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + logf := logger(cfg.Verbose) + c := buildClients(cfg, logf) + ctx := context.Background() + if !cfg.DryRun { + release, err := acquireLock(cfg.StateDir) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + defer release() + } + plan, err := engine.BuildPlan(ctx, cfg, options(cfg), c.nav, c.lastfm, c.rip, logf) + if err != nil { + fmt.Fprintln(os.Stderr, "weekly:", err) + return 1 + } + printPlan(plan) + if cfg.DryRun { + _ = engine.SaveReport(cfg.StateDir, plan) + return 0 + } + if len(plan.Downloads) > 0 { + if err := engine.Download(ctx, plan, c.rip, logf); err != nil { + logf("download failed: %v", err) + plan.Errors = append(plan.Errors, "download: "+err.Error()) + } + } + engine.Scan(ctx, c.nav, c.scanNav, cfg, len(plan.Downloads), logf) + engine.ResolveDownloads(ctx, plan, c.nav, options(cfg), logf) + history, err := engine.LoadPlaylistHistory(cfg.StateDir) + if err != nil { + logf("warning: playlist history: %v", err) + } + engine.BuildFinalPlaylist(plan, options(cfg), history) + if len(plan.Playlist) == 0 { + _ = engine.SaveReport(cfg.StateDir, plan) + fmt.Fprintln(os.Stderr, "weekly: no tracks to put on the playlist") + return 1 + } + if err := engine.ReplacePlaylist(ctx, c.nav, cfg.PlaylistName, plan.Playlist, logf); err != nil { + _ = engine.SaveReport(cfg.StateDir, plan) + fmt.Fprintln(os.Stderr, "weekly:", err) + return 1 + } + if err := engine.UpdatePlaylistHistory(cfg.StateDir, history, plan.Playlist); err != nil { + logf("warning: save playlist history: %v", err) + } + if err := engine.SaveReport(cfg.StateDir, plan); err != nil { + logf("warning: save report: %v", err) + } + printPlaylist(plan, cfg.StateDir) + return 0 +} + +func printPlan(plan *engine.Plan) { + fmt.Printf("LastRecc weekly plan — %s\n", plan.GeneratedAt) + fmt.Printf("Window: last %d days · %d plays · %d artists · %.1fh\n", + plan.WindowDays, plan.Stats.Plays, plan.Stats.Artists, plan.Stats.Hours) + fmt.Printf("Recommended artists: %d · library albums: %d · to download: %d · skipped: %d\n", + plan.Stats.Recommended, plan.Stats.LibraryAlbums, plan.Stats.Downloads, plan.Stats.Skipped) + if len(plan.SeedArtists) > 0 { + names := make([]string, 0, len(plan.SeedArtists)) + for i, seed := range plan.SeedArtists { + if i >= 6 { + break + } + names = append(names, fmt.Sprintf("%s (%d)", seed.Name, seed.Plays)) + } + fmt.Printf("Seeds: %s\n", strings.Join(names, ", ")) + } + if len(plan.SeedAlbums) > 0 { + fmt.Println("\nUnplayed albums in your library:") + for _, album := range plan.SeedAlbums { + fmt.Printf(" · %s — %s (%d tracks selected)\n", album.Artist, album.Name, len(album.SelectedSongs)) + } + } + fmt.Println("\nRecommended artists:") + for i, artist := range plan.Artists { + if i >= 40 { + fmt.Printf(" … and %d more\n", len(plan.Artists)-i) + break + } + album := "" + if artist.Album != nil { + album = " — " + artist.Album.Name + if artist.Album.QobuzTitle != "" && artist.Album.QobuzTitle != artist.Album.Name { + album += fmt.Sprintf(" [Qobuz: %s, %.0f%%]", artist.Album.QobuzTitle, artist.Album.QobuzScore*100) + } + } + fmt.Printf(" %-14s %-30s%s\n", "["+artist.Action+"]", artist.Artist, album) + } + if len(plan.Downloads) > 0 { + fmt.Println("\nDownload queue:") + for _, album := range plan.Downloads { + fmt.Printf(" · %s — %s (qobuz:%s)\n", album.Artist, album.Name, album.QobuzID) + } + } + if len(plan.Errors) > 0 { + fmt.Println("\nWarnings:") + for _, warning := range plan.Errors { + fmt.Printf(" ! %s\n", warning) + } + } + if plan.DryRun { + fmt.Printf("\nDry run: %d playlist track(s) available without downloading.\n", len(plan.Playlist)) + } +} + +func printPlaylist(plan *engine.Plan, stateDir string) { + fmt.Printf("\nPlaylist %q: %d tracks\n", plan.PlaylistName, len(plan.Playlist)) + counts := map[string]int{} + for _, track := range plan.Playlist { + counts[track.Source]++ + } + fmt.Printf(" sources: library tracks %d · library albums %d · seed albums %d · downloaded %d\n", + counts["library-track"], counts["library"], counts["seed-album"], counts["downloaded"]) + for i, track := range plan.Playlist { + if i >= 12 { + fmt.Printf(" … and %d more\n", len(plan.Playlist)-i) + break + } + fmt.Printf(" %2d. %s — %s\n", i+1, track.Artist, track.Title) + } + fmt.Printf("Report: %s\n", filepath.Join(stateDir, "last-run.json")) +} + +func acquireLock(stateDir string) (func(), error) { + path := filepath.Join(stateDir, "weekly.lock") + if info, err := os.Stat(path); err == nil && time.Since(info.ModTime()) > 24*time.Hour { + _ = os.Remove(path) + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) + if err != nil { + return nil, fmt.Errorf("another weekly run appears active (%s); remove it if this is stale", path) + } + _, _ = fmt.Fprintf(f, "pid=%d started=%s\n", os.Getpid(), time.Now().Format(time.RFC3339)) + _ = f.Close() + return func() { _ = os.Remove(path) }, nil +} diff --git a/lastrecc-go/go.mod b/lastrecc-go/go.mod new file mode 100644 index 0000000..d583357 --- /dev/null +++ b/lastrecc-go/go.mod @@ -0,0 +1,3 @@ +module lastrecc-go + +go 1.25 diff --git a/lastrecc-go/internal/cache/cache.go b/lastrecc-go/internal/cache/cache.go new file mode 100644 index 0000000..925162d --- /dev/null +++ b/lastrecc-go/internal/cache/cache.go @@ -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 +} diff --git a/lastrecc-go/internal/config/config.go b/lastrecc-go/internal/config/config.go new file mode 100644 index 0000000..1447cda --- /dev/null +++ b/lastrecc-go/internal/config/config.go @@ -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 + } +} diff --git a/lastrecc-go/internal/engine/engine_test.go b/lastrecc-go/internal/engine/engine_test.go new file mode 100644 index 0000000..264c81b --- /dev/null +++ b/lastrecc-go/internal/engine/engine_test.go @@ -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) + } +} diff --git a/lastrecc-go/internal/engine/execute.go b/lastrecc-go/internal/engine/execute.go new file mode 100644 index 0000000..47cffe8 --- /dev/null +++ b/lastrecc-go/internal/engine/execute.go @@ -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: + } +} diff --git a/lastrecc-go/internal/engine/history.go b/lastrecc-go/internal/engine/history.go new file mode 100644 index 0000000..98ec6bd --- /dev/null +++ b/lastrecc-go/internal/engine/history.go @@ -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 +} diff --git a/lastrecc-go/internal/engine/plan.go b/lastrecc-go/internal/engine/plan.go new file mode 100644 index 0000000..4c37c4b --- /dev/null +++ b/lastrecc-go/internal/engine/plan.go @@ -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 +} diff --git a/lastrecc-go/internal/engine/types.go b/lastrecc-go/internal/engine/types.go new file mode 100644 index 0000000..9fab9de --- /dev/null +++ b/lastrecc-go/internal/engine/types.go @@ -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() +} diff --git a/lastrecc-go/internal/httpclient/client.go b/lastrecc-go/internal/httpclient/client.go new file mode 100644 index 0000000..44fc950 --- /dev/null +++ b/lastrecc-go/internal/httpclient/client.go @@ -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< 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 + } +} diff --git a/lastrecc-go/internal/rip/rip.go b/lastrecc-go/internal/rip/rip.go new file mode 100644 index 0000000..3a06549 --- /dev/null +++ b/lastrecc-go/internal/rip/rip.go @@ -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 diff --git a/lastrecc-go/internal/rip/rip_test.go b/lastrecc-go/internal/rip/rip_test.go new file mode 100644 index 0000000..5024888 --- /dev/null +++ b/lastrecc-go/internal/rip/rip_test.go @@ -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) + } +} diff --git a/lastrecc-go/internal/text/text.go b/lastrecc-go/internal/text/text.go new file mode 100644 index 0000000..412962a --- /dev/null +++ b/lastrecc-go/internal/text/text.go @@ -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) +} diff --git a/lastrecc-go/internal/text/text_test.go b/lastrecc-go/internal/text/text_test.go new file mode 100644 index 0000000..bcacb24 --- /dev/null +++ b/lastrecc-go/internal/text/text_test.go @@ -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") + } +} diff --git a/lastrecc-go/scripts/cron.example b/lastrecc-go/scripts/cron.example new file mode 100644 index 0000000..8cd4c21 --- /dev/null +++ b/lastrecc-go/scripts/cron.example @@ -0,0 +1,3 @@ +# LastRecc weekly engine — run every Monday at 06:00. +# Build first: cd lastrecc-go && go build -o lastrecc ./cmd/lastrecc +0 6 * * 1 cd /home/joren/dev/LastRecc/lastrecc-go && mkdir -p state && ./lastrecc weekly --env /home/joren/dev/LastRecc/.env >> state/weekly.log 2>&1 diff --git a/lastrecc/__init__.py b/lastrecc/__init__.py new file mode 100644 index 0000000..9d8d70b --- /dev/null +++ b/lastrecc/__init__.py @@ -0,0 +1,3 @@ +"""LastRecc: a personal, Last.fm-powered discovery feed for Navidrome.""" + +__version__ = "0.1.0" diff --git a/lastrecc/__main__.py b/lastrecc/__main__.py new file mode 100644 index 0000000..34bc998 --- /dev/null +++ b/lastrecc/__main__.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import argparse +import json +import sys + +from .config import Settings +from .recommend import build_feed +from .server import serve + + +def _settings(args: argparse.Namespace) -> Settings: + settings = Settings.load() + if getattr(args, "days", None): + settings = settings.with_days(args.days) + return settings + + +def cmd_build(args: argparse.Namespace) -> int: + settings = _settings(args) + feed = build_feed(settings, force=args.refresh) + stats = feed.get("stats", {}) + cards = feed.get("cards", []) + playable = sum(1 for card in cards if card.get("playable")) + print( + f"Built {len(cards)} cards ({playable} playable) from " + f"{stats.get('plays', 0)} plays / {stats.get('artists', 0)} artists" + ) + print(f"Window: {feed['window']['start']} → {feed['window']['end']}") + print(f"Cache: {settings.cache_dir / 'feed.json'}") + if args.json: + print(json.dumps(feed, ensure_ascii=False, indent=2)) + return 0 + + +def cmd_serve(args: argparse.Namespace) -> int: + settings = _settings(args) + if args.warm: + print("Warming feed cache…", file=sys.stderr) + build_feed(settings) + serve(settings, host=args.host, port=args.port) + return 0 + + +def cmd_stats(args: argparse.Namespace) -> int: + settings = _settings(args) + from .cache import load_json + + feed = load_json(settings.cache_dir / "feed.json") + if not feed: + print("No cached feed yet. Run: python -m lastrecc build", file=sys.stderr) + return 1 + print(json.dumps(feed.get("stats", {}), ensure_ascii=False, indent=2)) + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="lastrecc", description="Personal Last.fm + Navidrome discovery feed") + sub = parser.add_subparsers(dest="command", required=True) + + build = sub.add_parser("build", help="Build the recommendation feed") + build.add_argument("--days", type=int, default=None, help="Rolling window in days (default: .env DAYS)") + build.add_argument("--refresh", action="store_true", help="Ignore caches and rebuild") + build.add_argument("--json", action="store_true", help="Print the full feed JSON") + build.set_defaults(func=cmd_build) + + server = sub.add_parser("serve", help="Serve the feed UI") + server.add_argument("--days", type=int, default=None) + server.add_argument("--host", default="127.0.0.1") + server.add_argument("--port", type=int, default=8787) + server.add_argument("--warm", action="store_true", help="Build before serving") + server.set_defaults(func=cmd_serve) + + stats = sub.add_parser("stats", help="Print cached feed stats") + stats.add_argument("--days", type=int, default=None) + stats.set_defaults(func=cmd_stats) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/lastrecc/cache.py b/lastrecc/cache.py new file mode 100644 index 0000000..e9b5757 --- /dev/null +++ b/lastrecc/cache.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import hashlib +import json +import os +import tempfile +import time +from pathlib import Path +from typing import Any + + +def load_json(path: Path, default: Any = None) -> Any: + try: + with path.open(encoding="utf-8") as handle: + return json.load(handle) + except (FileNotFoundError, json.JSONDecodeError, OSError): + return default + + +def save_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(data, handle, ensure_ascii=False, indent=1) + os.replace(tmp, path) + finally: + try: + os.unlink(tmp) + except FileNotFoundError: + pass + + +def is_fresh(path: Path, ttl_seconds: float) -> bool: + try: + return time.time() - path.stat().st_mtime < ttl_seconds + except OSError: + return False + + +class JsonCache: + """Small file cache keyed by a stable hash of the request.""" + + def __init__(self, directory: Path, ttl_seconds: float = 7 * 24 * 3600): + self.directory = directory + self.ttl_seconds = ttl_seconds + + def _path(self, key: str) -> Path: + digest = hashlib.sha256(key.encode("utf-8")).hexdigest() + return self.directory / f"{digest}.json" + + def get(self, key: str) -> Any: + path = self._path(key) + if not is_fresh(path, self.ttl_seconds): + return None + return load_json(path) + + def set(self, key: str, value: Any) -> None: + save_json(self._path(key), value) diff --git a/lastrecc/config.py b/lastrecc/config.py new file mode 100644 index 0000000..d35aa48 --- /dev/null +++ b/lastrecc/config.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import os +from dataclasses import dataclass, replace +from pathlib import Path + + +ROOT = Path(__file__).resolve().parent.parent + + +def _load_dotenv(path: Path) -> None: + """Tiny .env loader so the app stays dependency-free.""" + if not path.exists(): + return + for raw in path.read_text(encoding="utf-8").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if line.startswith("export "): + line = line[7:] + if "=" not in line: + continue + key, value = line.split("=", 1) + key = key.strip() + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": + value = value[1:-1] + os.environ.setdefault(key, value) + + +_load_dotenv(ROOT / ".env") + + +def _env(name: str, default: str | None = None, required: bool = False) -> str: + value = os.environ.get(name, default) + if required and not value: + raise RuntimeError(f"Missing {name}. Copy .env.example to .env and fill it in.") + return value or "" + + +@dataclass(frozen=True) +class Settings: + navidrome_url: str + navidrome_user: str + navidrome_password: str + navidrome_basic_user: str + navidrome_basic_password: str + lastfm_api_key: str + days: int = 7 + feed_size: int = 36 + seed_artists: int = 10 + seed_tracks: int = 10 + similar_artists_per_seed: int = 5 + top_tracks_per_artist: int = 4 + similar_tracks_per_seed: int = 12 + cache_dir: Path = ROOT / ".cache" + web_dir: Path = ROOT / "web" + lastfm_rate: float = 4.0 + navidrome_rate: float = 8.0 + + @classmethod + def load(cls) -> "Settings": + return cls( + navidrome_url=_env("NAVIDROME_URL", required=True).rstrip("/"), + navidrome_user=_env("NAVIDROME_USER", required=True), + navidrome_password=_env("NAVIDROME_PASSWORD", required=True), + navidrome_basic_user=_env("NAVIDROME_BASIC_USER"), + navidrome_basic_password=_env("NAVIDROME_BASIC_PASSWORD"), + lastfm_api_key=_env("LASTFM_API_KEY", required=True), + days=int(_env("DAYS", "7")), + feed_size=int(_env("FEED_SIZE", "36")), + seed_artists=int(_env("SEED_ARTISTS", "10")), + seed_tracks=int(_env("SEED_TRACKS", "10")), + similar_artists_per_seed=int(_env("SIMILAR_ARTISTS_PER_SEED", "5")), + top_tracks_per_artist=int(_env("TOP_TRACKS_PER_ARTIST", "4")), + similar_tracks_per_seed=int(_env("SIMILAR_TRACKS_PER_SEED", "12")), + cache_dir=Path(_env("CACHE_DIR", str(ROOT / ".cache"))).expanduser(), + web_dir=ROOT / "web", + lastfm_rate=float(_env("LASTFM_RATE", "4.0")), + navidrome_rate=float(_env("NAVIDROME_RATE", "8.0")), + ) + + def with_days(self, days: int) -> "Settings": + return replace(self, days=max(1, min(days, 90))) + + +def basic_auth(settings: Settings) -> tuple[str, str] | None: + if settings.navidrome_basic_user: + return settings.navidrome_basic_user, settings.navidrome_basic_password + return None diff --git a/lastrecc/lastfm.py b/lastrecc/lastfm.py new file mode 100644 index 0000000..3ef2d5a --- /dev/null +++ b/lastrecc/lastfm.py @@ -0,0 +1,139 @@ +from __future__ import annotations + +import hashlib +import json +import urllib.error +from typing import Any + +from .cache import JsonCache +from .net import HttpClient, HttpError, RateLimiter + + +API_ROOT = "https://ws.audioscrobbler.com/2.0/" +PLACEHOLDER_HASH = "2a96cbd8b46e442fc41c2b86b821562f" + + +class LastFMError(RuntimeError): + pass + + +def _as_list(value: Any) -> list[dict]: + if isinstance(value, dict): + return [value] + if isinstance(value, list): + return [item for item in value if isinstance(item, dict)] + return [] + + +def _match(value: Any) -> float: + try: + return float(value) + except (TypeError, ValueError): + return 0.0 + + +def _image(images: Any) -> str | None: + for image in reversed(_as_list(images)): + url = (image.get("#text") or "").strip() + if url and PLACEHOLDER_HASH not in url: + return url + return None + + +def _artist_name(track: dict) -> str: + artist = track.get("artist") + if isinstance(artist, dict): + return artist.get("name") or artist.get("#text") or "" + if isinstance(artist, str): + return artist + return track.get("artistName") or "" + + +class LastFM: + def __init__(self, api_key: str, cache_dir, rate_limiter: RateLimiter | None = None): + self.api_key = api_key + self.http = HttpClient( + "LastRecc/0.1 (https://github.com/lastrecc)", + rate_limiter=rate_limiter or RateLimiter(4.0), + ) + self.cache = JsonCache(cache_dir / "lastfm", ttl_seconds=14 * 24 * 3600) + + def _call(self, method: str, **params: Any) -> dict: + clean = {key: value for key, value in params.items() if value is not None} + cache_key = method + "::" + hashlib.sha256( + json.dumps(clean, sort_keys=True, ensure_ascii=False).encode("utf-8") + ).hexdigest() + cached = self.cache.get(cache_key) + if cached is not None: + return cached + + query = {"method": method, "api_key": self.api_key, "format": "json", **clean} + try: + data = self.http.get_json(API_ROOT, params=query) + except (HttpError, urllib.error.URLError, TimeoutError, OSError) as exc: + raise LastFMError(f"Last.fm {method} failed: {exc}") from exc + except ValueError as exc: + raise LastFMError(f"Last.fm {method} returned invalid JSON") from exc + if not isinstance(data, dict): + raise LastFMError(f"Last.fm {method} returned no data") + if data.get("error"): + raise LastFMError(f"Last.fm {method}: {data.get('message', 'unknown error')}") + self.cache.set(cache_key, data) + return data + + # ----------------------------------------------------------------- artists + def artist_similar(self, artist: str, limit: int = 20) -> list[dict]: + data = self._call("artist.getSimilar", artist=artist, limit=limit, autocorrect=1) + return _as_list(data.get("similarartists", {}).get("artist")) + + def artist_top_tracks(self, artist: str, limit: int = 5) -> list[dict]: + data = self._call("artist.getTopTracks", artist=artist, limit=limit, autocorrect=1) + return _as_list(data.get("toptracks", {}).get("track")) + + def artist_top_albums(self, artist: str, limit: int = 5) -> list[dict]: + data = self._call("artist.getTopAlbums", artist=artist, limit=limit, autocorrect=1) + return _as_list(data.get("topalbums", {}).get("album")) + + def artist_info(self, artist: str) -> dict: + data = self._call("artist.getInfo", artist=artist, autocorrect=1) + return data.get("artist", {}) or {} + + # ------------------------------------------------------------------ tracks + def track_similar(self, artist: str, track: str, limit: int = 15) -> list[dict]: + data = self._call( + "track.getSimilar", + artist=artist, + track=track, + limit=limit, + autocorrect=1, + ) + return _as_list(data.get("similartracks", {}).get("track")) + + def track_info(self, artist: str, track: str) -> dict: + data = self._call("track.getInfo", artist=artist, track=track, autocorrect=1) + return data.get("track", {}) or {} + + # ------------------------------------------------------------------ albums + def album_info(self, artist: str, album: str) -> dict: + data = self._call("album.getInfo", artist=artist, album=album, autocorrect=1) + return data.get("album", {}) or {} + + # ------------------------------------------------------------------- utils + @staticmethod + def image_from_track(track: dict) -> str | None: + album = track.get("album") + if isinstance(album, dict): + return _image(album.get("image")) or _image(track.get("image")) + return _image(track.get("image")) + + @staticmethod + def image_from_album(album: dict) -> str | None: + return _image(album.get("image")) + + @staticmethod + def artist_name(track: dict) -> str: + return _artist_name(track) + + @staticmethod + def match(value: Any) -> float: + return _match(value) diff --git a/lastrecc/navidrome.py b/lastrecc/navidrome.py new file mode 100644 index 0000000..ab8b2bc --- /dev/null +++ b/lastrecc/navidrome.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import json +import sys +import threading +import time +import urllib.parse +from typing import Any + +from .cache import is_fresh, load_json, save_json +from .config import Settings, basic_auth +from .net import HttpClient, HttpError, RateLimiter + + +class NavidromeError(RuntimeError): + pass + + +class Navidrome: + """Navidrome native API + Subsonic API client.""" + + def __init__(self, settings: Settings): + self.settings = settings + self.base = settings.navidrome_url + self.http = HttpClient( + "LastRecc/0.1 (https://github.com/lastrecc)", + rate_limiter=RateLimiter(settings.navidrome_rate), + basic_auth=basic_auth(settings), + default_headers={"X-ND-Client-Unique-Id": "lastrecc"}, + ) + self._token: str | None = None + self._salt: str | None = None + self._subsonic_token: str | None = None + self._login_lock = threading.Lock() + self._songs: dict[str, dict] = {} + self._songs_path = settings.cache_dir / "navidrome_songs.json" + self._songs_loaded = False + + # ------------------------------------------------------------------ auth + def login(self, force: bool = False) -> None: + with self._login_lock: + if self._token and not force: + return + try: + data = self.http.post_json( + f"{self.base}/auth/login", + { + "username": self.settings.navidrome_user, + "password": self.settings.navidrome_password, + }, + ) + except HttpError as exc: + raise NavidromeError(f"Navidrome login failed: {exc}") from exc + if not data or "token" not in data: + raise NavidromeError("Navidrome login returned no token") + self._token = data["token"] + self._salt = data.get("subsonicSalt") + self._subsonic_token = data.get("subsonicToken") + + def _native_headers(self) -> dict[str, str]: + self.login() + return {"X-ND-Authorization": f"Bearer {self._token}"} + + def _native_request(self, url: str) -> tuple[int, dict[str, str], bytes]: + for attempt in range(2): + try: + return self.http.request(url, headers=self._native_headers()) + except HttpError as exc: + if exc.status == 401 and attempt == 0: + self.login(force=True) + continue + raise + raise NavidromeError("Navidrome request failed after re-authentication") + + # --------------------------------------------------------------- scrobbles + def get_scrobbles(self, force: bool = False, ttl: int = 600) -> list[dict]: + path = self.settings.cache_dir / "scrobbles.json" + if not force and is_fresh(path, ttl): + cached = load_json(path) + if cached and isinstance(cached.get("items"), list): + return cached["items"] + + items: list[dict] = [] + start = 0 + total = None + while True: + url = ( + f"{self.base}/api/scrobble" + f"?_end=5000&_order=DESC&_sort=submission_time&_start={start}" + ) + _, headers, payload = self._native_request(url) + chunk = json.loads(payload.decode("utf-8")) if payload else [] + if not isinstance(chunk, list): + raise NavidromeError(f"Unexpected scrobble response: {chunk!r}") + items.extend(chunk) + total = int(headers.get("X-Total-Count", len(items))) + if not chunk or len(items) >= total: + break + start += len(chunk) + if start > 200_000: + break + save_json(path, {"fetched_at": time.time(), "items": items}) + return items + + # ------------------------------------------------------------------- songs + def _load_songs(self) -> None: + if self._songs_loaded: + return + cached = load_json(self._songs_path, {}) + if isinstance(cached, dict): + self._songs = {str(k): v for k, v in cached.items() if isinstance(v, dict)} + self._songs_loaded = True + + def get_songs(self, ids: set[str] | list[str]) -> dict[str, dict]: + """Fetch song metadata for IDs, batching and caching aggressively.""" + self._load_songs() + missing = [song_id for song_id in ids if song_id not in self._songs] + if not missing: + return {song_id: self._songs[song_id] for song_id in ids} + + for offset in range(0, len(missing), 80): + chunk = missing[offset : offset + 80] + query = urllib.parse.urlencode([("id", song_id) for song_id in chunk]) + try: + _, _, payload = self._native_request(f"{self.base}/api/song?{query}") + songs = json.loads(payload.decode("utf-8")) if payload else [] + except (HttpError, NavidromeError) as exc: + print(f" ! song metadata batch failed: {exc}", file=sys.stderr) + continue + if not isinstance(songs, list): + continue + for song in songs: + if song.get("id"): + self._songs[song["id"]] = song + if (offset // 80) % 5 == 0: + save_json(self._songs_path, self._songs) + print( + f" · metadata {min(offset + 80, len(missing))}/{len(missing)}", + file=sys.stderr, + end="\r", + ) + save_json(self._songs_path, self._songs) + print(" " * 60, file=sys.stderr, end="\r") + return {song_id: self._songs[song_id] for song_id in ids if song_id in self._songs} + + # ---------------------------------------------------------------- subsonic + def _subsonic_params(self) -> dict[str, str]: + self.login() + if not self._salt or not self._subsonic_token: + raise NavidromeError("Navidrome did not return Subsonic credentials") + return { + "u": self.settings.navidrome_user, + "t": self._subsonic_token, + "s": self._salt, + "v": "1.16.1", + "c": "LastRecc", + "f": "json", + } + + def subsonic(self, method: str, **params: Any) -> dict: + query = self._subsonic_params() + query.update({key: value for key, value in params.items() if value is not None}) + url = f"{self.base}/rest/{method}.view?{urllib.parse.urlencode(query)}" + data = self.http.get_json(url) + response = (data or {}).get("subsonic-response", {}) + if response.get("status") != "ok": + error = response.get("error", {}) + raise NavidromeError(f"Subsonic {method} failed: {error or response}") + return response + + def search_songs(self, query: str, limit: int = 5) -> list[dict]: + try: + data = self.subsonic( + "search3", + query=query, + songCount=limit, + albumCount=0, + artistCount=0, + ) + except (HttpError, NavidromeError): + return [] + result = data.get("searchResult3", {}) + songs = result.get("song", []) + if isinstance(songs, dict): + songs = [songs] + return [song for song in songs if isinstance(song, dict)] + + def cover_url(self, cover_id: str, size: int = 300) -> str: + query = self._subsonic_params() + query.update({"id": cover_id, "size": str(size)}) + return f"{self.base}/rest/getCoverArt.view?{urllib.parse.urlencode(query)}" + + def stream_url(self, song_id: str) -> str: + query = self._subsonic_params() + query.update({"id": song_id}) + return f"{self.base}/rest/stream.view?{urllib.parse.urlencode(query)}" + + def page_url(self, album_id: str | None = None, song_id: str | None = None) -> str: + if album_id: + return f"{self.base}/app/#/album/{urllib.parse.quote(album_id)}/show" + if song_id: + return f"{self.base}/app/#/song/{urllib.parse.quote(song_id)}/show" + return f"{self.base}/app/" diff --git a/lastrecc/net.py b/lastrecc/net.py new file mode 100644 index 0000000..f48b448 --- /dev/null +++ b/lastrecc/net.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +import base64 +import json +import random +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from typing import Any + + +class HttpError(RuntimeError): + def __init__(self, status: int, url: str, body: str = ""): + # Never put API keys / Subsonic tokens from the query string into logs. + parts = urllib.parse.urlsplit(url) + safe_url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, "", "")) + self.status = status + self.url = safe_url + self.body = body + super().__init__(f"HTTP {status} for {safe_url}: {body[:240]}") + + +class RateLimiter: + """A simple shared token bucket. Good enough for personal API use.""" + + def __init__(self, rate_per_second: float): + self.interval = 1.0 / max(rate_per_second, 0.1) + self._next = 0.0 + self._lock = threading.Lock() + + def wait(self) -> None: + with self._lock: + now = time.monotonic() + if now < self._next: + delay = self._next - now + else: + delay = 0.0 + self._next = max(now, self._next) + self.interval + if delay: + time.sleep(delay) + + +class HttpClient: + def __init__( + self, + user_agent: str, + *, + rate_limiter: RateLimiter | None = None, + basic_auth: tuple[str, str] | None = None, + default_headers: dict[str, str] | None = None, + timeout: float = 60.0, + ): + self.user_agent = user_agent + self.rate_limiter = rate_limiter + self.basic_auth = basic_auth + self.default_headers = default_headers or {} + self.timeout = timeout + + def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]: + headers = { + "User-Agent": self.user_agent, + "Accept": "application/json, text/plain, */*", + "Accept-Encoding": "identity", + } + headers.update(self.default_headers) + if self.basic_auth: + token = base64.b64encode( + f"{self.basic_auth[0]}:{self.basic_auth[1]}".encode() + ).decode() + headers["Authorization"] = f"Basic {token}" + if extra: + headers.update(extra) + return headers + + def open( + self, + url: str, + *, + method: str = "GET", + data: Any = None, + headers: dict[str, str] | None = None, + timeout: float | None = None, + ): + body = None + final_headers = self._headers(headers) + if data is not None: + if isinstance(data, (dict, list)): + body = json.dumps(data).encode("utf-8") + final_headers.setdefault("Content-Type", "application/json") + elif isinstance(data, str): + body = data.encode("utf-8") + else: + body = data + if self.rate_limiter: + self.rate_limiter.wait() + request = urllib.request.Request(url, data=body, headers=final_headers, method=method) + return urllib.request.urlopen(request, timeout=timeout or self.timeout) + + def request( + self, + url: str, + *, + method: str = "GET", + data: Any = None, + headers: dict[str, str] | None = None, + retries: int = 3, + ) -> tuple[int, dict[str, str], bytes]: + last_error: Exception | None = None + for attempt in range(retries + 1): + try: + with self.open(url, method=method, data=data, headers=headers) as response: + return response.status, dict(response.headers), response.read() + except urllib.error.HTTPError as exc: + payload = exc.read().decode("utf-8", "replace") + last_error = HttpError(exc.code, url, payload) + if exc.code not in (429, 500, 502, 503, 504) or attempt == retries: + raise last_error + except (urllib.error.URLError, TimeoutError, OSError) as exc: + last_error = exc + if attempt == retries: + raise + time.sleep((2**attempt) * 0.5 + random.random() * 0.3) + raise RuntimeError(f"Request failed: {last_error}") + + def get_json( + self, + url: str, + *, + params: dict[str, Any] | None = None, + headers: dict[str, str] | None = None, + ) -> Any: + if params: + query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None}) + url = f"{url}{'&' if '?' in url else '?'}{query}" + status, _, payload = self.request(url, headers=headers) + if not payload: + return None + return json.loads(payload.decode("utf-8")) + + def post_json( + self, + url: str, + data: Any, + *, + headers: dict[str, str] | None = None, + ) -> Any: + status, _, payload = self.request(url, method="POST", data=data, headers=headers) + if not payload: + return None + return json.loads(payload.decode("utf-8")) diff --git a/lastrecc/recommend.py b/lastrecc/recommend.py new file mode 100644 index 0000000..c80bddb --- /dev/null +++ b/lastrecc/recommend.py @@ -0,0 +1,620 @@ +from __future__ import annotations + +import math +import sys +import time +import urllib.parse +from collections import Counter, defaultdict +from datetime import datetime, timezone + +from .cache import is_fresh, load_json, save_json +from .config import Settings +from .lastfm import LastFM, LastFMError +from .navidrome import Navidrome +from .net import RateLimiter +from .text import best_match, normalize, track_key + + +def _log(message: str) -> None: + print(f"[lastrecc] {message}", file=sys.stderr, flush=True) + + +def _iso(timestamp: int | float) -> str: + return datetime.fromtimestamp(timestamp, timezone.utc).isoformat().replace("+00:00", "Z") + + +def _int(value) -> int: + try: + return int(value) + except (TypeError, ValueError): + return 0 + + +def _duration_seconds(value) -> int: + seconds = _int(value) + if seconds > 10_000: # Last.fm's track.getInfo returns milliseconds + seconds //= 1000 + return seconds + + +def _recency_weight(timestamp: int, now: int, half_life_days: float = 14.0) -> float: + age_days = max(0.0, (now - timestamp) / 86400.0) + return 0.5 ** (age_days / half_life_days) + + +def _artist_of(track: dict) -> str: + artist = track.get("artist") + if isinstance(artist, dict): + return artist.get("name") or "" + return artist or "" + + +def _candidate( + *, + artist: str, + title: str, + source: str, + seed: dict, + similarity: float, + playcount: int = 0, + url: str = "", + image: str | None = None, +) -> dict: + return { + "artist": artist.strip(), + "title": title.strip(), + "album": "", + "source": source, + "seed": seed, + "similarity": max(0.0, min(1.0, similarity)), + "playcount": playcount, + "url": url, + "image_hint": image, + "sources": [{"source": source, "seed": seed, "similarity": similarity}], + } + + +def build_feed(settings: Settings, force: bool = False) -> dict: + feed_path = settings.cache_dir / "feed.json" + if not force: + cached = load_json(feed_path) + if ( + cached + and cached.get("window", {}).get("days") == settings.days + and is_fresh(feed_path, 15 * 60) + ): + return cached + + _log(f"building {settings.days}-day feed for {settings.navidrome_user}") + nav = Navidrome(settings) + lastfm = LastFM( + settings.lastfm_api_key, + settings.cache_dir, + rate_limiter=RateLimiter(settings.lastfm_rate), + ) + + all_scrobbles = nav.get_scrobbles(force=force) + if not all_scrobbles: + raise RuntimeError("No scrobbles found for this Navidrome user") + + now = int(time.time()) + window_start = now - settings.days * 86400 + week = [ + item + for item in all_scrobbles + if _int(item.get("submissionTime")) >= window_start + ] + if not week: + raise RuntimeError(f"No plays in the last {settings.days} days") + + all_ids = {item["mediaFileId"] for item in all_scrobbles if item.get("mediaFileId")} + week_ids = {item["mediaFileId"] for item in week if item.get("mediaFileId")} + _log(f"{len(week)} plays / {len(week_ids)} tracks in window; resolving metadata") + songs = nav.get_songs(all_ids) + _log(f"resolved metadata for {len(songs)} of {len(all_ids)} tracks") + + artist_plays: Counter[str] = Counter() + artist_weight: defaultdict[str, float] = defaultdict(float) + track_plays: Counter[tuple[str, str]] = Counter() + track_weight: defaultdict[tuple[str, str], float] = defaultdict(float) + album_plays: Counter[tuple[str, str]] = Counter() + day_plays: Counter[str] = Counter() + total_seconds = 0 + before_ids = { + item["mediaFileId"] + for item in all_scrobbles + if _int(item.get("submissionTime")) < window_start and item.get("mediaFileId") + } + + for item in week: + song = songs.get(item.get("mediaFileId")) + if not song: + continue + artist = song.get("artist") or "Unknown artist" + title = song.get("title") or "" + album = song.get("album") or "" + if not title: + continue + weight = _recency_weight(_int(item.get("submissionTime")), now) + artist_plays[artist] += 1 + artist_weight[artist] += weight + track_plays[(artist, title)] += 1 + track_weight[(artist, title)] += weight + if album: + album_plays[(album, artist)] += 1 + total_seconds += _duration_seconds(song.get("duration")) + day = datetime.fromtimestamp(_int(item.get("submissionTime")), timezone.utc) + day_plays[day.strftime("%Y-%m-%d")] += 1 + + history_keys = { + track_key(song.get("artist") or "", song.get("title") or "") + for song in songs.values() + if song.get("artist") and song.get("title") + } + history_artists = {normalize(song.get("artist") or "") for song in songs.values()} + + top_artist_rows = sorted( + artist_weight.items(), key=lambda item: item[1], reverse=True + )[: settings.seed_artists] + if not top_artist_rows: + raise RuntimeError("Could not determine top artists") + max_artist_weight = top_artist_rows[0][1] or 1.0 + seed_artists = [ + { + "name": name, + "plays": artist_plays[name], + "weight": weight / max_artist_weight, + } + for name, weight in top_artist_rows + ] + seed_artist_names = {seed["name"] for seed in seed_artists} + seed_artist_norm = {normalize(name) for name in seed_artist_names} + + top_track_rows = sorted( + track_weight.items(), key=lambda item: item[1], reverse=True + )[: settings.seed_tracks] + max_track_weight = top_track_rows[0][1] if top_track_rows else 1.0 + seed_tracks = [ + { + "artist": artist, + "title": title, + "plays": track_plays[(artist, title)], + "weight": weight / max_track_weight, + } + for (artist, title), weight in top_track_rows + if title + ] + + _log( + "seeds: " + + ", ".join(f"{seed['name']} ({seed['plays']})" for seed in seed_artists[:5]) + ) + + candidates: dict[str, dict] = {} + + def add_candidate( + *, + artist: str, + title: str, + source: str, + seed: dict, + similarity: float, + playcount: int = 0, + url: str = "", + image: str | None = None, + ) -> None: + artist = (artist or "").strip() + title = (title or "").strip() + if not artist or not title: + return + key = track_key(artist, title) + if key in history_keys: + return + base = max(0.0, min(1.0, similarity)) * seed["weight"] + entry = _candidate( + artist=artist, + title=title, + source=source, + seed=seed, + similarity=similarity, + playcount=playcount, + url=url, + image=image, + ) + entry["base"] = base + existing = candidates.get(key) + if existing: + existing["sources"].append(entry["sources"][0]) + if base > existing.get("base", 0): + entry["sources"] = existing["sources"] + candidates[key] = entry + return + candidates[key] = entry + + # Similar artists -> their top tracks + for index, seed in enumerate(seed_artists, start=1): + _log(f"artist seeds {index}/{len(seed_artists)}: {seed['name']}") + try: + similar = lastfm.artist_similar(seed["name"], limit=20) + except LastFMError as exc: + _log(f" skip {seed['name']}: {exc}") + continue + ranked = [ + item + for item in similar + if item.get("name") + and normalize(item.get("name")) != normalize(seed["name"]) + ] + ranked.sort(key=lambda item: lastfm.match(item.get("match")), reverse=True) + for similar_artist in ranked[: settings.similar_artists_per_seed]: + similar_name = similar_artist.get("name") or "" + similarity = lastfm.match(similar_artist.get("match")) + try: + tracks = lastfm.artist_top_tracks( + similar_name, limit=settings.top_tracks_per_artist + ) + except LastFMError: + continue + for track in tracks: + add_candidate( + artist=_artist_of(track) or similar_name, + title=track.get("name") or "", + source="artist", + seed={ + "type": "artist", + "artist": seed["name"], + "title": None, + "plays": seed["plays"], + "weight": seed["weight"], + }, + similarity=similarity, + playcount=_int(track.get("playcount")), + url=track.get("url") or "", + ) + + # Similar tracks + for index, seed in enumerate(seed_tracks, start=1): + _log(f"track seeds {index}/{len(seed_tracks)}: {seed['artist']} — {seed['title']}") + try: + similar = lastfm.track_similar( + seed["artist"], seed["title"], limit=settings.similar_tracks_per_seed + ) + except LastFMError as exc: + _log(f" skip: {exc}") + continue + for track in similar: + artist = _artist_of(track) + title = track.get("name") or "" + if not artist or not title: + continue + add_candidate( + artist=artist, + title=title, + source="track", + seed={ + "type": "track", + "artist": seed["artist"], + "title": seed["title"], + "plays": seed["plays"], + "weight": seed["weight"], + }, + similarity=lastfm.match(track.get("match")), + playcount=_int(track.get("playcount")), + url=track.get("url") or "", + image=LastFM.image_from_track(track), + ) + + if not candidates: + _log("Last.fm returned no new track candidates; using unplayed albums only") + + _log(f"{len(candidates)} candidates before ranking") + for candidate in candidates.values(): + artist_norm = normalize(candidate["artist"]) + novelty = 1.0 + if artist_norm not in history_artists: + novelty = 1.12 + elif artist_norm not in seed_artist_norm: + novelty = 1.05 + candidate["score"] = ( + candidate["base"] + * (1.0 + math.log1p(candidate["playcount"]) / 30.0) + * novelty + ) + + ranked = sorted(candidates.values(), key=lambda item: item["score"], reverse=True) + shortlist: list[dict] = [] + per_artist: Counter[str] = Counter() + for candidate in ranked: + artist_norm = normalize(candidate["artist"]) + if per_artist[artist_norm] >= 2: + continue + shortlist.append(candidate) + per_artist[artist_norm] += 1 + if len(shortlist) >= settings.feed_size + 18: + break + + _log(f"enriching {len(shortlist)} shortlisted tracks") + enriched: list[dict] = [] + for index, candidate in enumerate(shortlist, start=1): + info: dict = {} + try: + info = lastfm.track_info(candidate["artist"], candidate["title"]) + except LastFMError: + pass + + album = "" + image = candidate.get("image_hint") + lastfm_url = candidate.get("url") or "" + duration = 0 + if info: + album_obj = info.get("album") or {} + if isinstance(album_obj, dict): + album = album_obj.get("title") or "" + image = LastFM.image_from_track(info) or image + lastfm_url = info.get("url") or lastfm_url + duration = _duration_seconds(info.get("duration")) + + nav_match = None + try: + results = nav.search_songs( + f"{candidate['artist']} {candidate['title']}", limit=5 + ) + nav_match = best_match(results, candidate["artist"], candidate["title"]) + except Exception as exc: # noqa: BLE001 - one bad match must not kill the feed + _log(f" library search failed for {candidate['artist']}: {exc}") + + card = dict(candidate) + card["type"] = "track" + card["album"] = album + card["duration"] = duration + card["lastfm_url"] = lastfm_url or ( + "https://www.last.fm/music/" + + urllib.parse.quote(candidate["artist"], safe="") + + "/_/" + + urllib.parse.quote(candidate["title"], safe="") + ) + card["image"] = image + card["image_remote"] = image + card["playable"] = False + card["song_id"] = None + card["album_id"] = None + card["stream_url"] = None + card["navidrome_url"] = None + card["in_library"] = False + + if nav_match: + card["playable"] = True + card["in_library"] = True + card["song_id"] = nav_match.get("id") + card["album_id"] = nav_match.get("albumId") + card["album"] = nav_match.get("album") or album + card["duration"] = _duration_seconds(nav_match.get("duration")) or duration + cover_id = nav_match.get("coverArt") + if cover_id: + card["image"] = f"/api/cover/{urllib.parse.quote(str(cover_id), safe='')}?size=300" + if card["song_id"]: + card["stream_url"] = ( + f"/api/stream/{urllib.parse.quote(str(card['song_id']), safe='')}" + ) + card["navidrome_url"] = nav.page_url( + album_id=card["album_id"], song_id=card["song_id"] + ) + + card["similarity"] = round(card["similarity"], 4) + card["match_pct"] = max(1, min(99, round(card["similarity"] * 100))) + card["score"] = round(card["score"], 4) + if card["playable"]: + card["score"] = round(card["score"] * 1.18, 4) + card["is_new_artist"] = normalize(card["artist"]) not in history_artists + + seed = card["seed"] + if seed["type"] == "track": + card["reason"] = f"Similar to “{seed['title']}” by {seed['artist']}" + card["reason_kind"] = "similar_track" + if normalize(card["artist"]) == normalize(seed["artist"]): + card["reason"] = f"Another track near “{seed['title']}”" + else: + seed_norm = normalize(seed["artist"]) + card_norm = normalize(card["artist"]) + if card_norm == seed_norm: + card["reason"] = f"An unheard track from {card['artist']}" + card["reason_kind"] = "known_artist" + elif card_norm in seed_artist_norm: + card["reason"] = ( + f"More from {card['artist']}, an artist you played " + f"{artist_plays.get(card['artist'], 0)}×" + ) + card["reason_kind"] = "known_artist" + else: + card["reason"] = ( + f"Because you played {seed['artist']} {seed['plays']}× this week" + ) + card["reason_kind"] = "similar_artist" + + if card["is_new_artist"] and card["reason_kind"] == "similar_artist": + card["reason"] = f"New artist · because you played {seed['artist']}" + + # If several seeds point at the same track, say so — closer to the + # "Similar to X, Y and Z" explanations on Last.fm's own home page. + source_artists: list[str] = [] + source_tracks: list[str] = [] + for source in card.get("sources", []): + seed_info = source.get("seed") or {} + if seed_info.get("type") == "artist" and seed_info.get("artist"): + if seed_info["artist"] not in source_artists: + source_artists.append(seed_info["artist"]) + if seed_info.get("type") == "track" and seed_info.get("title"): + label = f"“{seed_info['title']}”" + if label not in source_tracks: + source_tracks.append(label) + if card["reason_kind"] == "similar_artist" and len(source_artists) >= 2: + names = source_artists[:3] + card["reason"] = "Similar to " + ", ".join(names[:-1]) + " and " + names[-1] + elif card["reason_kind"] == "similar_track" and len(source_tracks) >= 2: + card["reason"] = "Similar to " + ", ".join(source_tracks[:2]) + " and more" + + card["id"] = track_key(card["artist"], card["title"]) + enriched.append(card) + if index % 10 == 0: + _log(f" enriched {index}/{len(shortlist)}") + + # Unplayed albums from artists joren already listens to. This is the + # "you've scrobbled this artist before, but not this release" card. + history_album_ids = { + song.get("albumId") for song in songs.values() if song.get("albumId") + } + history_album_keys = { + (normalize(song.get("artist") or ""), normalize(song.get("album") or "")) + for song in songs.values() + if song.get("album") and song.get("artist") + } + artist_ids: dict[str, str] = {} + for item in week: + song = songs.get(item.get("mediaFileId")) + if song and song.get("artistId"): + artist_ids.setdefault(normalize(song.get("artist") or ""), song["artistId"]) + + album_cards: list[dict] = [] + for seed in seed_artists: + artist_id = artist_ids.get(normalize(seed["name"])) + if not artist_id: + continue + try: + data = nav.subsonic("getArtist", id=artist_id) + except Exception as exc: # noqa: BLE001 + _log(f" album lookup failed for {seed['name']}: {exc}") + continue + artist_data = data.get("artist", {}) or {} + albums = artist_data.get("album", []) + if isinstance(albums, dict): + albums = [albums] + unplayed = [] + for album in albums: + if not isinstance(album, dict): + continue + album_id = album.get("id") + album_name = album.get("name") or "" + if not album_id or not album_name: + continue + if album_id in history_album_ids: + continue + if (normalize(seed["name"]), normalize(album_name)) in history_album_keys: + continue + if _int(album.get("songCount")) < 3: + continue + unplayed.append(album) + if not unplayed: + continue + unplayed.sort( + key=lambda album: (_int(album.get("year")), str(album.get("created") or "")), + reverse=True, + ) + album = unplayed[0] + cover = album.get("coverArt") + album_cards.append( + { + "id": "album::" + track_key(seed["name"], album["name"]), + "type": "album", + "artist": seed["name"], + "title": album["name"], + "album": album["name"], + "track_count": _int(album.get("songCount")), + "duration": _int(album.get("duration")), + "image": ( + f"/api/cover/{urllib.parse.quote(str(cover), safe='')}?size=300" + if cover + else None + ), + "image_remote": None, + "playable": True, + "in_library": True, + "song_id": None, + "album_id": album["id"], + "stream_url": None, + "navidrome_url": nav.page_url(album_id=album["id"]), + "lastfm_url": ( + "https://www.last.fm/music/" + + urllib.parse.quote(seed["name"], safe="") + + "/" + + urllib.parse.quote(album["name"], safe="") + ), + "similarity": 1.0, + "match_pct": 100, + "score": round(0.66 + 0.28 * seed["weight"], 4), + "is_new_artist": False, + "reason": f"An album you haven't played from {seed['name']}", + "reason_kind": "unplayed_album", + "seed": { + "type": "artist", + "artist": seed["name"], + "title": None, + "plays": seed["plays"], + "weight": seed["weight"], + }, + } + ) + _log(f"added {len(album_cards)} unplayed album cards") + + if album_cards: + enriched.extend(album_cards) + enriched.sort(key=lambda card: card["score"], reverse=True) + + # Final diversity pass and trim. + final: list[dict] = [] + artist_count: Counter[str] = Counter() + album_count: Counter[tuple[str, str]] = Counter() + for card in enriched: + artist_norm = normalize(card["artist"]) + album_norm = normalize(card.get("album") or "") + if artist_count[artist_norm] >= 2: + continue + if album_norm and album_count[(artist_norm, album_norm)] >= 1: + continue + final.append(card) + artist_count[artist_norm] += 1 + if album_norm: + album_count[(artist_norm, album_norm)] += 1 + if len(final) >= settings.feed_size: + break + + if not final: + raise RuntimeError("No recommendations could be built for this window") + + stats = { + "plays": len(week), + "unique_tracks": len(week_ids), + "artists": len(artist_plays), + "albums": len(album_plays), + "hours": round(total_seconds / 3600.0, 1), + "first_time_tracks": len(week_ids - before_ids), + "top_artists": [ + {"name": name, "plays": plays} + for name, plays in artist_plays.most_common(12) + ], + "top_tracks": [ + {"title": title, "artist": artist, "plays": plays} + for (artist, title), plays in track_plays.most_common(10) + ], + "top_albums": [ + {"album": album, "artist": artist, "plays": plays} + for (album, artist), plays in album_plays.most_common(8) + ], + "days": [ + {"day": day, "plays": plays} + for day, plays in sorted(day_plays.items()) + ], + } + + feed = { + "generated_at": _iso(now), + "window": { + "days": settings.days, + "start": _iso(window_start), + "end": _iso(now), + }, + "stats": stats, + "cards": final, + } + save_json(feed_path, feed) + _log(f"feed ready: {len(final)} cards ({sum(1 for c in final if c['playable'])} playable)") + return feed diff --git a/lastrecc/server.py b/lastrecc/server.py new file mode 100644 index 0000000..7df0a5b --- /dev/null +++ b/lastrecc/server.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import hashlib +import json +import mimetypes +import sys +import threading +import traceback +import urllib.error +import urllib.parse +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from .cache import is_fresh, load_json, save_json +from .config import Settings +from .navidrome import Navidrome +from .net import HttpError +from .recommend import build_feed + + +class App: + def __init__(self, settings: Settings): + self.settings = settings + self.nav = Navidrome(settings) + self.build_lock = threading.Lock() + self.cover_dir = settings.cache_dir / "covers" + self.cover_dir.mkdir(parents=True, exist_ok=True) + + def feed(self, days: int | None = None, refresh: bool = False) -> dict: + settings = self.settings.with_days(days) if days else self.settings + with self.build_lock: + return build_feed(settings, force=refresh) + + +class Handler(BaseHTTPRequestHandler): + server_version = "LastRecc/0.1" + protocol_version = "HTTP/1.1" + + @property + def app(self) -> App: + return self.server.app # type: ignore[attr-defined] + + def log_message(self, fmt: str, *args) -> None: + sys.stderr.write(f"[http] {self.address_string()} {fmt % args}\n") + + # ------------------------------------------------------------------ helpers + def _json(self, status: int, data: dict) -> None: + payload = json.dumps(data, ensure_ascii=False).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(payload))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(payload) + + def _error(self, status: int, message: str) -> None: + self._json(status, {"error": message}) + + def _serve_file(self, path: Path) -> None: + if not path.is_file(): + self._error(HTTPStatus.NOT_FOUND, "Not found") + return + content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream" + payload = path.read_bytes() + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(payload))) + self.send_header("Cache-Control", "no-cache" if path.name.endswith(".html") else "public, max-age=300") + self.end_headers() + self.wfile.write(payload) + + # --------------------------------------------------------------------- GET + def do_GET(self) -> None: # noqa: N802 + parsed = urllib.parse.urlparse(self.path) + path = parsed.path + query = urllib.parse.parse_qs(parsed.query) + + if path in ("/", "/index.html"): + self._serve_file(self.app.settings.web_dir / "index.html") + return + if path.startswith("/static/"): + relative = path[len("/static/") :] + target = (self.app.settings.web_dir / relative).resolve() + web_root = self.app.settings.web_dir.resolve() + if web_root not in target.parents and target != web_root: + self._error(HTTPStatus.FORBIDDEN, "Forbidden") + return + self._serve_file(target) + return + if path == "/api/health": + cached = load_json(self.app.settings.cache_dir / "feed.json") + self._json( + HTTPStatus.OK, + { + "ok": True, + "user": self.app.settings.navidrome_user, + "cached_feed": bool(cached), + "generated_at": (cached or {}).get("generated_at"), + }, + ) + return + if path == "/api/feed": + days = None + if query.get("days"): + try: + days = int(query["days"][0]) + except ValueError: + self._error(HTTPStatus.BAD_REQUEST, "days must be an integer") + return + refresh = query.get("refresh", ["0"])[0].lower() in ("1", "true", "yes") + try: + feed = self.app.feed(days=days, refresh=refresh) + except Exception as exc: # noqa: BLE001 + traceback.print_exc() + self._error(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc)) + return + self._json(HTTPStatus.OK, feed) + return + if path.startswith("/api/cover/"): + cover_id = urllib.parse.unquote(path[len("/api/cover/") :]) + try: + size = int(query.get("size", ["300"])[0]) + except ValueError: + size = 300 + size = max(100, min(size, 600)) + self._cover(cover_id, size) + return + if path.startswith("/api/stream/"): + song_id = urllib.parse.unquote(path[len("/api/stream/") :]) + self._stream(song_id) + return + self._error(HTTPStatus.NOT_FOUND, "Not found") + + def do_HEAD(self) -> None: # noqa: N802 + # Good enough for browsers probing covers/audio. + parsed = urllib.parse.urlparse(self.path) + if parsed.path in ("/", "/index.html"): + path = self.app.settings.web_dir / "index.html" + elif parsed.path.startswith("/static/"): + web_root = self.app.settings.web_dir.resolve() + path = (web_root / parsed.path[len("/static/") :]).resolve() + if web_root not in path.parents and path != web_root: + self.send_response(HTTPStatus.FORBIDDEN) + self.send_header("Content-Length", "0") + self.end_headers() + return + else: + self.send_response(HTTPStatus.NOT_FOUND) + self.send_header("Content-Length", "0") + self.end_headers() + return + if not path.is_file(): + self.send_response(HTTPStatus.NOT_FOUND) + self.send_header("Content-Length", "0") + self.end_headers() + return + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", mimetypes.guess_type(str(path))[0] or "application/octet-stream") + self.send_header("Content-Length", str(path.stat().st_size)) + self.end_headers() + + def do_POST(self) -> None: # noqa: N802 + parsed = urllib.parse.urlparse(self.path) + if parsed.path == "/api/refresh": + try: + feed = self.app.feed(refresh=True) + except Exception as exc: # noqa: BLE001 + traceback.print_exc() + self._error(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc)) + return + self._json(HTTPStatus.OK, feed) + return + self._error(HTTPStatus.NOT_FOUND, "Not found") + + # ------------------------------------------------------------------- proxy + def _cover(self, cover_id: str, size: int) -> None: + if not cover_id: + self._error(HTTPStatus.BAD_REQUEST, "Missing cover id") + return + cache_key = hashlib.sha256(f"{cover_id}:{size}".encode()).hexdigest() + cache_path = self.app.cover_dir / f"{cache_key}.bin" + content_type = "image/jpeg" + if cache_path.exists() and is_fresh(cache_path, 7 * 24 * 3600): + meta_path = cache_path.with_suffix(".json") + meta = load_json(meta_path, {}) or {} + content_type = meta.get("content_type", content_type) + payload = cache_path.read_bytes() + else: + url = self.app.nav.cover_url(cover_id, size) + try: + _, headers, payload = self.app.nav.http.request(url) + except (HttpError, urllib.error.HTTPError, urllib.error.URLError, OSError) as exc: + self._error(HTTPStatus.BAD_GATEWAY, f"Cover fetch failed: {exc}") + return + content_type = headers.get("Content-Type", content_type) + cache_path.write_bytes(payload) + save_json(cache_path.with_suffix(".json"), {"content_type": content_type}) + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(payload))) + self.send_header("Cache-Control", "public, max-age=604800") + self.end_headers() + self.wfile.write(payload) + + def _stream(self, song_id: str) -> None: + if not song_id: + self._error(HTTPStatus.BAD_REQUEST, "Missing song id") + return + url = self.app.nav.stream_url(song_id) + headers = {} + range_header = self.headers.get("Range") + if range_header: + headers["Range"] = range_header + try: + upstream = self.app.nav.http.open(url, headers=headers) + except urllib.error.HTTPError as exc: + self._error(exc.code, f"Stream failed: {exc.reason}") + return + except (urllib.error.URLError, OSError) as exc: + self._error(HTTPStatus.BAD_GATEWAY, f"Stream failed: {exc}") + return + with upstream: + status = upstream.status + self.send_response(status) + content_length = upstream.headers.get("Content-Length") + for header in ( + "Content-Type", + "Content-Length", + "Content-Range", + "Accept-Ranges", + "ETag", + "Last-Modified", + ): + value = upstream.headers.get(header) + if value: + self.send_header(header, value) + self.send_header("Cache-Control", "no-store") + if not content_length: + self.send_header("Connection", "close") + self.close_connection = True + self.end_headers() + try: + while True: + chunk = upstream.read(64 * 1024) + if not chunk: + break + self.wfile.write(chunk) + except (BrokenPipeError, ConnectionResetError): + pass + + +class Server(ThreadingHTTPServer): + daemon_threads = True + allow_reuse_address = True + + def __init__(self, address, handler, app: App): + super().__init__(address, handler) + self.app = app + + +def serve(settings: Settings, host: str = "127.0.0.1", port: int = 8787) -> None: + app = App(settings) + server = Server((host, port), Handler, app) + print(f"LastRecc → http://{host}:{port}", file=sys.stderr) + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nbye", file=sys.stderr) + finally: + server.server_close() diff --git a/lastrecc/text.py b/lastrecc/text.py new file mode 100644 index 0000000..d16109e --- /dev/null +++ b/lastrecc/text.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import difflib +import re +import unicodedata + + +_PARENS = re.compile(r"\([^)]*\)|\[[^\]]*\]") +_FEAT = re.compile(r"\b(feat\.?|ft\.?|featuring|with)\b.*$", re.IGNORECASE) +_NON_WORD = re.compile(r"[^\w]+", re.UNICODE) + + +def normalize(value: str) -> str: + """Normalize artist/title strings while preserving non-Latin scripts.""" + if not value: + return "" + text = unicodedata.normalize("NFKC", value).casefold() + text = _PARENS.sub(" ", text) + text = _FEAT.sub(" ", text) + text = _NON_WORD.sub(" ", text) + return " ".join(text.split()) + + +def track_key(artist: str, title: str) -> str: + return f"{normalize(artist)}::{normalize(title)}" + + +def similarity(left: str, right: str) -> float: + if not left or not right: + return 0.0 + return difflib.SequenceMatcher(None, left, right).ratio() + + +def best_match(items: list[dict], artist: str, title: str) -> dict | None: + """Find the closest song in a small Navidrome search result.""" + want_artist = normalize(artist) + want_title = normalize(title) + best = None + best_score = 0.0 + for item in items: + got_artist = normalize(item.get("artist") or "") + got_title = normalize(item.get("title") or "") + if not got_artist or not got_title: + continue + if got_artist == want_artist and got_title == want_title: + return item + title_score = similarity(got_title, want_title) + artist_score = similarity(got_artist, want_artist) + score = title_score * 0.65 + artist_score * 0.35 + if score > best_score: + best_score = score + best = item + if best and best_score >= 0.86: + return best + return None + + +def human_duration(seconds: int | float | None) -> str: + if not seconds: + return "" + seconds = int(seconds) + return f"{seconds // 60}:{seconds % 60:02d}" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2951d25 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +# No third-party dependencies. Python 3.11+ standard library only. diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_scoring.py b/tests/test_scoring.py new file mode 100644 index 0000000..fd3f7af --- /dev/null +++ b/tests/test_scoring.py @@ -0,0 +1,22 @@ +import time +import unittest + +from lastrecc.recommend import _duration_seconds, _recency_weight + + +class ScoringTests(unittest.TestCase): + def test_recent_play_outweighs_old_play(self): + now = int(time.time()) + recent = _recency_weight(now - 86400, now) + old = _recency_weight(now - 60 * 86400, now) + self.assertGreater(recent, old) + self.assertAlmostEqual(_recency_weight(now, now), 1.0) + + def test_track_info_milliseconds(self): + self.assertEqual(_duration_seconds("197000"), 197) + self.assertEqual(_duration_seconds(203), 203) + self.assertEqual(_duration_seconds(None), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_text.py b/tests/test_text.py new file mode 100644 index 0000000..65f0886 --- /dev/null +++ b/tests/test_text.py @@ -0,0 +1,51 @@ +import unittest + +from lastrecc.text import best_match, human_duration, normalize, track_key + + +class NormalizeTests(unittest.TestCase): + def test_preserves_cyrillic(self): + self.assertEqual(normalize("Кино — Звезда по имени Солнце"), "кино звезда по имени солнце") + + def test_removes_parentheticals_and_features(self): + self.assertEqual( + normalize("Someday (Remastered 2011) [Live] feat. Someone"), + "someday", + ) + + def test_collapses_punctuation(self): + self.assertEqual(normalize("L'Impératrice — Danza Marilù!"), "l impératrice danza marilù") + + def test_track_key_is_stable(self): + self.assertEqual(track_key("Кино", "Звезда"), track_key("кино", "звезда")) + + +class MatchTests(unittest.TestCase): + def test_exact_match(self): + songs = [ + {"id": "1", "artist": "Кино", "title": "Звезда по имени Солнце"}, + {"id": "2", "artist": "Кино", "title": "Группа крови"}, + ] + match = best_match(songs, "Кино", "Звезда по имени Солнце") + self.assertIsNotNone(match) + self.assertEqual(match["id"], "1") + + def test_remastered_match(self): + songs = [{"id": "1", "artist": "The Strokes", "title": "Someday (Remastered)"}] + match = best_match(songs, "The Strokes", "Someday") + self.assertIsNotNone(match) + self.assertEqual(match["id"], "1") + + def test_no_match(self): + songs = [{"id": "1", "artist": "Кино", "title": "Группа крови"}] + self.assertIsNone(best_match(songs, "Кино", "Звезда по имени Солнце")) + + +class DurationTests(unittest.TestCase): + def test_human_duration(self): + self.assertEqual(human_duration(203), "3:23") + self.assertEqual(human_duration(0), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..443f585 --- /dev/null +++ b/web/app.js @@ -0,0 +1,388 @@ +const state = { + feed: null, + filter: "all", + days: Number(new URLSearchParams(location.search).get("days")) || 7, + loading: false, + audio: new Audio(), + currentId: null, + toastTimer: null, +}; + +const $ = (selector) => document.querySelector(selector); +const $$ = (selector) => Array.from(document.querySelectorAll(selector)); + +const esc = (value) => + String(value ?? "").replace(/[&<>"']/g, (char) => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + }[char])); + +const hueFor = (value) => { + let hash = 0; + for (const char of String(value || "")) hash = (hash * 31 + char.charCodeAt(0)) % 360; + return hash; +}; + +const initials = (value) => { + const words = String(value || "?").trim().split(/\s+/).slice(0, 2); + return words.map((word) => word[0] || "").join("").toUpperCase() || "?"; +}; + +const formatDuration = (seconds) => { + if (!seconds) return ""; + const total = Math.round(seconds); + return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`; +}; + +const formatClock = (seconds) => { + if (!Number.isFinite(seconds)) return "0:00"; + const total = Math.max(0, Math.round(seconds)); + return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`; +}; + +const playIcon = ``; +const pauseIcon = ``; +const sparkIcon = ``; + +function setStatus(text, busy = false) { + $("#status-text").textContent = text; + $("#status").classList.toggle("is-busy", busy); +} + +function showToast(message) { + const toast = $("#toast"); + toast.textContent = message; + toast.classList.remove("hidden"); + clearTimeout(state.toastTimer); + state.toastTimer = setTimeout(() => toast.classList.add("hidden"), 3200); +} + +function skeleton() { + $("#grid").innerHTML = Array.from({ length: 9 }) + .map( + () => ` +
+
+
+
+
+
+
+
+
` + ) + .join(""); + $("#empty").classList.add("hidden"); + $("#error").classList.add("hidden"); +} + +function showError(message) { + $("#grid").innerHTML = ""; + $("#empty").classList.add("hidden"); + const error = $("#error"); + error.textContent = `${message} — check the server console, then hit Refresh.`; + error.classList.remove("hidden"); + setStatus("error"); +} + +async function loadFeed(refresh = false) { + if (state.loading) return; + state.loading = true; + skeleton(); + setStatus(refresh ? "rebuilding feed" : "reading scrobbles", true); + const refreshButton = $("#refresh"); + refreshButton.disabled = true; + refreshButton.classList.add("is-loading"); + $("#days").disabled = true; + + try { + const response = await fetch( + `/api/feed?days=${state.days}${refresh ? "&refresh=1" : ""}`, + { cache: "no-store" } + ); + const data = await response.json(); + if (!response.ok) throw new Error(data.error || "Could not build the feed"); + state.feed = data; + state.filter = "all"; + history.replaceState(null, "", `?days=${state.days}`); + render(); + setStatus("ready"); + } catch (error) { + console.error(error); + showError(error.message || "Could not load the feed"); + } finally { + state.loading = false; + refreshButton.disabled = false; + refreshButton.classList.remove("is-loading"); + $("#days").disabled = false; + } +} + +function render() { + const feed = state.feed; + if (!feed) return; + const stats = feed.stats || {}; + const days = feed.window?.days || state.days; + $("#eyebrow").textContent = `LAST ${days} DAYS · NAVIDROME × LAST.FM`; + $("#lede").innerHTML = + `${stats.plays || 0} plays across ` + + `${stats.artists || 0} artists — ` + + `${stats.hours || 0}h of music. ` + + `Here's what Last.fm thinks you'll love next.`; + $("#stats").innerHTML = [ + [stats.plays || 0, "plays"], + [stats.unique_tracks || 0, "tracks"], + [stats.artists || 0, "artists"], + [`${stats.hours || 0}h`, "listened"], + ] + .map( + ([value, label]) => ` +
+ ${esc(value)} + ${esc(label)} +
` + ) + .join(""); + updateTabCounts(); + renderCards(); +} + +function tabCards() { + const cards = state.feed?.cards || []; + if (state.filter === "new") return cards.filter((card) => card.is_new_artist); + if (state.filter === "known") return cards.filter((card) => !card.is_new_artist); + if (state.filter === "playable") return cards.filter((card) => card.playable); + return cards; +} + +function updateTabCounts() { + const cards = state.feed?.cards || []; + const counts = { + all: cards.length, + new: cards.filter((card) => card.is_new_artist).length, + known: cards.filter((card) => !card.is_new_artist).length, + playable: cards.filter((card) => card.playable).length, + }; + $$("[data-count]").forEach((node) => { + node.textContent = counts[node.dataset.count] ?? 0; + }); +} + +function cardMarkup(card, index) { + const isAlbum = card.type === "album"; + const hue = hueFor(card.artist); + const image = card.image + ? `` + : ""; + const fallbackDisplay = card.image ? "none" : "flex"; + const subtitle = isAlbum + ? `${card.track_count || 0} tracks` + : card.album || ""; + const album = `

${esc(subtitle) || " "}

`; + const source = isAlbum + ? `Album · library` + : card.playable + ? `In library` + : `Last.fm`; + const badge = isAlbum ? "Album" : `${card.match_pct}% match`; + const actionLabel = isAlbum + ? "Open album" + : card.playable + ? "Play" + : "Open on Last.fm"; + return ` +
+
+ ${image} +
+ ${esc(initials(card.artist))} +
+
+ ${esc(badge)} + +
+
+

${esc(card.title)}

+

${esc(card.artist)}

+ ${album} +

${sparkIcon}${esc(card.reason)}

+
+ ${source} + ${esc(formatDuration(card.duration))} +
+
+
`; +} + +function renderCards() { + const cards = tabCards(); + $("#grid").innerHTML = cards.map(cardMarkup).join(""); + $("#empty").classList.toggle("hidden", cards.length > 0); + $("#error").classList.add("hidden"); + syncPlayingCards(); +} + +function setFilter(filter) { + state.filter = filter; + $$(".tab").forEach((tab) => { + const active = tab.dataset.filter === filter; + tab.classList.toggle("is-active", active); + tab.setAttribute("aria-selected", String(active)); + }); + renderCards(); +} + +function cardById(id) { + return (state.feed?.cards || []).find((card) => card.id === id); +} + +function syncPlayingCards() { + const paused = state.audio.paused; + $$(".card").forEach((card) => { + const active = card.dataset.id === state.currentId; + card.classList.toggle("is-current", active); + card.classList.toggle("is-playing", active && !paused); + const play = card.querySelector(".icon-play"); + const pause = card.querySelector(".icon-pause"); + if (play && pause) { + play.classList.toggle("hidden", active && !paused); + pause.classList.toggle("hidden", !(active && !paused)); + } + }); +} + +function showPlayer(card) { + const player = $("#player"); + player.classList.remove("hidden"); + $("#player-cover").innerHTML = card.image + ? `` + : `${esc(initials(card.artist))}`; + $("#player-title").textContent = card.title; + $("#player-artist").textContent = card.artist; +} + +function setupAudio() { + const audio = state.audio; + audio.preload = "metadata"; + + audio.addEventListener("play", () => { + $("#player-toggle .icon-play").classList.add("hidden"); + $("#player-toggle .icon-pause").classList.remove("hidden"); + syncPlayingCards(); + }); + audio.addEventListener("pause", () => { + $("#player-toggle .icon-play").classList.remove("hidden"); + $("#player-toggle .icon-pause").classList.add("hidden"); + syncPlayingCards(); + }); + audio.addEventListener("ended", () => { + state.currentId = null; + syncPlayingCards(); + }); + audio.addEventListener("loadedmetadata", () => { + $("#player-duration").textContent = formatClock(audio.duration); + }); + audio.addEventListener("timeupdate", () => { + const duration = audio.duration || 0; + $("#player-elapsed").textContent = formatClock(audio.currentTime); + if (duration) { + $("#player-seek").value = String(Math.round((audio.currentTime / duration) * 1000)); + } + }); +} + +function playById(id) { + const card = cardById(id); + if (!card) return; + if (card.type === "album") { + const target = card.navidrome_url || card.lastfm_url; + showToast("Opening album in Navidrome"); + window.open(target, "_blank", "noopener,noreferrer"); + return; + } + if (!card.playable || !card.stream_url) { + showToast("Not in your library — opening Last.fm"); + window.open(card.lastfm_url, "_blank", "noopener,noreferrer"); + return; + } + if (state.currentId === id) { + if (state.audio.paused) state.audio.play().catch(() => {}); + else state.audio.pause(); + return; + } + state.currentId = id; + state.audio.src = card.stream_url; + showPlayer(card); + state.audio.play().catch(() => { + showToast("Could not start playback"); + }); + syncPlayingCards(); +} + +function bind() { + $("#tabs").addEventListener("click", (event) => { + const tab = event.target.closest(".tab"); + if (tab) setFilter(tab.dataset.filter); + }); + + $("#grid").addEventListener("click", (event) => { + const button = event.target.closest('[data-action="play"]'); + if (button) { + event.stopPropagation(); + playById(button.dataset.id); + } + }); + + $("#refresh").addEventListener("click", () => loadFeed(true)); + + $("#days").addEventListener("change", (event) => { + state.days = Number(event.target.value); + loadFeed(); + }); + + $("#player-toggle").addEventListener("click", () => { + if (!state.currentId) return; + if (state.audio.paused) state.audio.play().catch(() => {}); + else state.audio.pause(); + }); + + $("#player-seek").addEventListener("input", (event) => { + const duration = state.audio.duration; + if (!duration) return; + state.audio.currentTime = (Number(event.target.value) / 1000) * duration; + }); + + $("#player-close").addEventListener("click", () => { + state.audio.pause(); + state.currentId = null; + $("#player").classList.add("hidden"); + syncPlayingCards(); + }); + + document.addEventListener("keydown", (event) => { + if (event.key === "Escape") { + state.audio.pause(); + $("#player").classList.add("hidden"); + } + }); +} + +function init() { + const daysSelect = $("#days"); + daysSelect.value = String(state.days); + if (!daysSelect.value) { + state.days = 7; + daysSelect.value = "7"; + } + setupAudio(); + bind(); + loadFeed(); +} + +init(); diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..0f8e2ea --- /dev/null +++ b/web/index.html @@ -0,0 +1,88 @@ + + + + + + + LastRecc — your week, recced + + + + +
+ + LR + LastRecc + beta + +
+ ready + + +
+
+ +
+
+

Navidrome × Last.fm

+

Your week,
recced.

+

Reading your scrobbles and finding the next things you'll love.

+
+
+ +
+
+
+

Picked for you

+

Fresh finds

+
+
+ + + + +
+
+ +
+ + +
+ +
+

Built from your Navidrome scrobbles. Similarity data by Last.fm.

+

Personal, non-commercial use. Cover art belongs to its respective owners.

+
+
+ + + + + + + diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..d0de6a1 --- /dev/null +++ b/web/style.css @@ -0,0 +1,1021 @@ +:root { + --bg: #f6f4ef; + --paper: #fffdf9; + --ink: #171717; + --muted: #706b63; + --muted-2: #98928a; + --line: #e5e0d7; + --accent: #e0362c; + --accent-soft: #fbe3df; + --violet: #5b5fd5; + --green: #1f7a4d; + --green-soft: #e2f3e9; + --shadow: 0 18px 50px -28px rgba(23, 23, 23, 0.35); + --radius: 18px; +} + +* { + box-sizing: border-box; +} + +html { + scroll-behavior: smooth; +} + +body { + margin: 0; + min-height: 100vh; + color: var(--ink); + background: + radial-gradient(1100px 500px at 82% -10%, rgba(224, 54, 44, 0.07), transparent 60%), + radial-gradient(900px 480px at -10% 5%, rgba(91, 95, 213, 0.06), transparent 55%), + var(--bg); + font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, Helvetica, Arial, sans-serif; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} + +a { + color: inherit; + text-decoration: none; +} + +button, +select, +input { + font: inherit; +} + +button { + cursor: pointer; +} + +.hidden { + display: none !important; +} + +/* ------------------------------------------------------------------ topbar */ +.topbar { + position: sticky; + top: 0; + z-index: 40; + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + padding: 14px clamp(18px, 4vw, 56px); + border-bottom: 1px solid rgba(229, 224, 215, 0.8); + background: rgba(246, 244, 239, 0.82); + backdrop-filter: blur(18px) saturate(1.2); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 10px; + min-width: 0; +} + +.brand-mark { + display: grid; + place-items: center; + width: 34px; + height: 34px; + border-radius: 10px; + background: var(--ink); + color: #fff; + font-size: 12px; + font-weight: 800; + letter-spacing: -0.04em; + position: relative; +} + +.brand-mark::after { + content: ""; + position: absolute; + top: -3px; + right: -3px; + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--accent); + border: 2px solid var(--bg); +} + +.brand-word { + font-size: 17px; + font-weight: 750; + letter-spacing: -0.035em; +} + +.brand-beta { + padding: 3px 7px; + border: 1px solid var(--line); + border-radius: 999px; + color: var(--muted); + font-size: 10px; + font-weight: 650; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.topbar-actions { + display: flex; + align-items: center; + gap: 14px; +} + +.status { + display: inline-flex; + align-items: center; + gap: 7px; + color: var(--muted); + font-size: 12px; + font-weight: 550; +} + +.status-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--green); + box-shadow: 0 0 0 4px rgba(31, 122, 77, 0.1); +} + +.status.is-busy .status-dot { + background: var(--accent); + box-shadow: 0 0 0 4px rgba(224, 54, 44, 0.12); + animation: pulse 1.3s ease-in-out infinite; +} + +@keyframes pulse { + 0%, 100% { opacity: 1; transform: scale(1); } + 50% { opacity: 0.45; transform: scale(0.8); } +} + +.days-picker { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--muted); + font-size: 11px; + font-weight: 650; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.days-picker select { + appearance: none; + border: 1px solid var(--line); + border-radius: 999px; + background: var(--paper); + color: var(--ink); + padding: 8px 28px 8px 12px; + font-size: 12px; + font-weight: 600; + letter-spacing: 0; + text-transform: none; + background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%); + background-position: calc(100% - 13px) 52%, calc(100% - 9px) 52%; + background-size: 4px 4px, 4px 4px; + background-repeat: no-repeat; + cursor: pointer; +} + +.btn { + display: inline-flex; + align-items: center; + gap: 8px; + border: 1px solid var(--line); + border-radius: 999px; + padding: 9px 15px; + background: var(--paper); + color: var(--ink); + font-size: 12.5px; + font-weight: 650; + transition: transform 0.18s ease, background 0.18s ease, border-color 0.18s ease; +} + +.btn svg { + width: 15px; + height: 15px; + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; +} + +.btn:hover { + transform: translateY(-1px); + border-color: #cfc8bd; +} + +.btn-dark { + background: var(--ink); + border-color: var(--ink); + color: #fff; +} + +.btn-dark:hover { + background: #2a2a2a; + border-color: #2a2a2a; +} + +.btn:disabled { + opacity: 0.6; + cursor: wait; + transform: none; +} + +.btn.is-loading svg { + animation: spin 0.9s linear infinite; +} + +@keyframes spin { + to { transform: rotate(360deg); } +} + +/* -------------------------------------------------------------------- layout */ +.wrap { + width: min(1240px, calc(100% - 36px)); + margin: 0 auto; +} + +.hero { + padding: clamp(52px, 8vw, 104px) 0 clamp(40px, 6vw, 64px); + border-bottom: 1px solid var(--line); +} + +.eyebrow { + margin: 0 0 14px; + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: 0.16em; + text-transform: uppercase; +} + +.hero h1 { + margin: 0; + max-width: 900px; + font-size: clamp(54px, 9.2vw, 112px); + font-weight: 760; + line-height: 0.88; + letter-spacing: -0.065em; +} + +.hero h1 em { + color: var(--accent); + font-family: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif; + font-weight: 500; + letter-spacing: -0.05em; +} + +.lede { + max-width: 590px; + margin: 26px 0 0; + color: var(--muted); + font-size: clamp(15px, 1.5vw, 18px); + line-height: 1.55; +} + +.lede strong { + color: var(--ink); + font-weight: 700; +} + +.stats { + display: flex; + flex-wrap: wrap; + gap: clamp(22px, 4vw, 48px); + margin-top: 36px; +} + +.stat { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 70px; +} + +.stat strong { + font-size: clamp(24px, 2.8vw, 34px); + font-weight: 720; + letter-spacing: -0.045em; +} + +.stat span { + color: var(--muted); + font-size: 11px; + font-weight: 650; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.feed-section { + padding: clamp(36px, 5vw, 60px) 0 40px; +} + +.section-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 24px; + margin-bottom: 24px; +} + +.section-head .eyebrow { + margin-bottom: 6px; +} + +.section-head h2 { + margin: 0; + font-size: clamp(28px, 3.5vw, 42px); + font-weight: 730; + letter-spacing: -0.05em; +} + +.tabs { + display: flex; + flex-wrap: wrap; + gap: 6px; + padding: 5px; + border: 1px solid var(--line); + border-radius: 999px; + background: rgba(255, 253, 249, 0.7); +} + +.tab { + display: inline-flex; + align-items: center; + gap: 7px; + border: 0; + border-radius: 999px; + padding: 8px 13px; + background: transparent; + color: var(--muted); + font-size: 12px; + font-weight: 620; + white-space: nowrap; + transition: color 0.18s ease, background 0.18s ease; +} + +.tab:hover { + color: var(--ink); +} + +.tab.is-active { + background: var(--ink); + color: #fff; +} + +.tab-count { + display: inline-grid; + place-items: center; + min-width: 19px; + height: 19px; + padding: 0 5px; + border-radius: 999px; + background: rgba(112, 107, 99, 0.1); + color: inherit; + font-size: 10px; + font-weight: 700; +} + +.tab.is-active .tab-count { + background: rgba(255, 255, 255, 0.16); +} + +/* --------------------------------------------------------------------- grid */ +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(248px, 1fr)); + gap: 22px; +} + +.card { + position: relative; + display: flex; + flex-direction: column; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--paper); + overflow: hidden; + box-shadow: 0 1px 0 rgba(23, 23, 23, 0.02); + animation: rise 0.55s cubic-bezier(0.22, 1, 0.36, 1) both; + animation-delay: var(--delay, 0ms); + transition: transform 0.24s ease, box-shadow 0.24s ease, border-color 0.24s ease; +} + +@keyframes rise { + from { opacity: 0; transform: translateY(14px); } + to { opacity: 1; transform: translateY(0); } +} + +.card:hover { + transform: translateY(-4px); + border-color: #d4cdc2; + box-shadow: var(--shadow); +} + +.card.is-current { + border-color: rgba(224, 54, 44, 0.55); +} + +.card.is-playing { + box-shadow: 0 0 0 2px rgba(224, 54, 44, 0.12), var(--shadow); +} + +.cover { + position: relative; + aspect-ratio: 1 / 1; + overflow: hidden; + background: hsl(var(--h, 20) 24% 88%); +} + +.cover img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + transition: transform 0.5s cubic-bezier(0.22, 1, 0.36, 1); +} + +.card:hover .cover img { + transform: scale(1.035); +} + +.cover-fallback { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: + radial-gradient(circle at 20% 20%, hsl(var(--h, 20) 62% 62% / 0.9), transparent 55%), + linear-gradient(145deg, hsl(var(--h, 20) 38% 44%), hsl(calc(var(--h, 20) + 45) 32% 24%)); + color: rgba(255, 255, 255, 0.9); +} + +.cover-fallback span { + font-family: "Iowan Old Style", Palatino, Georgia, serif; + font-size: clamp(48px, 6vw, 72px); + font-weight: 600; + letter-spacing: -0.05em; +} + +.cover-shade { + position: absolute; + inset: 0; + background: linear-gradient(to top, rgba(10, 8, 7, 0.42), transparent 38%); + pointer-events: none; +} + +.match { + position: absolute; + top: 12px; + left: 12px; + padding: 5px 8px; + border-radius: 999px; + background: rgba(20, 17, 15, 0.68); + color: rgba(255, 255, 255, 0.92); + font-size: 10px; + font-weight: 650; + letter-spacing: 0.04em; + backdrop-filter: blur(8px); +} + +.play-btn { + position: absolute; + right: 14px; + bottom: 14px; + display: grid; + place-items: center; + width: 48px; + height: 48px; + border: 0; + border-radius: 50%; + background: #fff; + color: var(--ink); + box-shadow: 0 8px 24px -8px rgba(0, 0, 0, 0.55); + opacity: 0; + transform: translateY(8px) scale(0.92); + transition: opacity 0.2s ease, transform 0.2s ease, background 0.2s ease; +} + +.card:hover .play-btn, +.card.is-current .play-btn, +.play-btn:focus-visible { + opacity: 1; + transform: translateY(0) scale(1); +} + +.play-btn:hover { + background: var(--accent); + color: #fff; +} + +.play-btn svg { + width: 22px; + height: 22px; + fill: currentColor; +} + +.card-body { + display: flex; + flex-direction: column; + flex: 1; + padding: 15px 16px 14px; +} + +.card-body h3 { + display: -webkit-box; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; + overflow: hidden; + margin: 0; + font-size: 16px; + font-weight: 700; + letter-spacing: -0.025em; + line-height: 1.3; +} + +.card-artist { + margin: 4px 0 0; + color: var(--ink); + font-size: 13px; + font-weight: 560; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.card-album { + margin: 2px 0 0; + color: var(--muted-2); + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.reason { + display: flex; + gap: 7px; + align-items: flex-start; + margin: 13px 0 0; + padding-top: 11px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 11.5px; + line-height: 1.4; +} + +.reason svg { + flex: 0 0 auto; + width: 13px; + height: 13px; + margin-top: 1px; + fill: var(--accent); +} + +.reason span { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.card-foot { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-top: auto; + padding-top: 11px; +} + +.source-pill { + display: inline-flex; + align-items: center; + padding: 3px 7px; + border-radius: 999px; + background: #f0ece5; + color: var(--muted); + font-size: 9.5px; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.source-pill.is-playable { + background: var(--green-soft); + color: var(--green); +} + +.duration { + color: var(--muted-2); + font-size: 11px; + font-variant-numeric: tabular-nums; +} + +/* ------------------------------------------------------------------ skeleton */ +.skeleton-card { + animation: none; +} + +.skeleton { + position: relative; + overflow: hidden; + background: #ece7df; +} + +.skeleton::after { + content: ""; + position: absolute; + inset: 0; + transform: translateX(-100%); + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.62), transparent); + animation: shimmer 1.4s infinite; +} + +@keyframes shimmer { + to { transform: translateX(100%); } +} + +.skeleton.line { + height: 11px; + border-radius: 6px; + margin-top: 9px; +} + +.skeleton.line.wide { width: 70%; height: 15px; } +.skeleton.line.short { width: 45%; } +.skeleton.line.reason-line { width: 90%; margin-top: 22px; height: 9px; } + +/* --------------------------------------------------------------- empty/error */ +.empty, +.error { + margin: 30px 0; + padding: 28px; + border: 1px dashed #d5cfc5; + border-radius: var(--radius); + color: var(--muted); + text-align: center; + font-size: 14px; +} + +.error { + border-color: rgba(224, 54, 44, 0.35); + background: var(--accent-soft); + color: #8e241d; + text-align: left; +} + +/* -------------------------------------------------------------------- footer */ +.footer { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 10px; + padding: 34px 0 120px; + border-top: 1px solid var(--line); + color: var(--muted-2); + font-size: 11.5px; +} + +.footer p { margin: 0; } + +.footer a { + color: var(--muted); + text-decoration: underline; + text-underline-offset: 2px; +} + +.footer a:hover { + color: var(--ink); +} + +/* -------------------------------------------------------------------- player */ +.player { + position: fixed; + right: 50%; + bottom: 18px; + z-index: 60; + display: flex; + align-items: center; + gap: 14px; + width: min(1040px, calc(100% - 28px)); + padding: 10px 14px 10px 10px; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 18px; + background: rgba(23, 23, 23, 0.96); + color: #fff; + box-shadow: 0 24px 70px -24px rgba(0, 0, 0, 0.65); + backdrop-filter: blur(18px); + transform: translateX(50%); + animation: player-in 0.28s ease both; +} + +@keyframes player-in { + from { opacity: 0; transform: translate(50%, 12px); } + to { opacity: 1; transform: translate(50%, 0); } +} + +.player-cover { + display: grid; + place-items: center; + flex: 0 0 auto; + width: 46px; + height: 46px; + overflow: hidden; + border-radius: 10px; + background: #333; +} + +.player-cover img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.player-cover span { + display: grid; + place-items: center; + width: 100%; + height: 100%; + background: linear-gradient(145deg, hsl(var(--h, 20) 40% 48%), hsl(calc(var(--h, 20) + 40) 35% 26%)); + font-family: Georgia, serif; + font-size: 15px; +} + +.player-meta { + display: flex; + flex-direction: column; + min-width: 0; + width: 190px; +} + +.player-meta strong, +.player-meta span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.player-meta strong { + font-size: 12.5px; + font-weight: 650; +} + +.player-meta span { + color: rgba(255, 255, 255, 0.55); + font-size: 11px; +} + +.player-toggle { + display: grid; + place-items: center; + flex: 0 0 auto; + width: 36px; + height: 36px; + border: 0; + border-radius: 50%; + background: #fff; + color: var(--ink); +} + +.player-toggle svg { + width: 18px; + height: 18px; + fill: currentColor; +} + +.player-progress { + flex: 1; + min-width: 0; +} + +.player-progress input[type="range"] { + width: 100%; + height: 14px; + margin: 0; + appearance: none; + background: transparent; + cursor: pointer; +} + +.player-progress input[type="range"]::-webkit-slider-runnable-track { + height: 3px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.2); +} + +.player-progress input[type="range"]::-moz-range-track { + height: 3px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.2); +} + +.player-progress input[type="range"]::-webkit-slider-thumb { + appearance: none; + width: 11px; + height: 11px; + margin-top: -4px; + border-radius: 50%; + background: #fff; +} + +.player-progress input[type="range"]::-moz-range-thumb { + width: 11px; + height: 11px; + border: 0; + border-radius: 50%; + background: #fff; +} + +.player-time { + display: flex; + justify-content: space-between; + margin-top: -2px; + color: rgba(255, 255, 255, 0.45); + font-size: 9.5px; + font-variant-numeric: tabular-nums; +} + +.player-close { + flex: 0 0 auto; + width: 28px; + height: 28px; + border: 0; + border-radius: 50%; + background: transparent; + color: rgba(255, 255, 255, 0.55); + font-size: 20px; + line-height: 1; +} + +.player-close:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; +} + +/* --------------------------------------------------------------------- toast */ +.toast { + position: fixed; + left: 50%; + bottom: 92px; + z-index: 70; + transform: translateX(-50%); + padding: 9px 14px; + border-radius: 999px; + background: rgba(23, 23, 23, 0.92); + color: #fff; + font-size: 12px; + font-weight: 550; + box-shadow: 0 10px 30px -12px rgba(0, 0, 0, 0.5); +} + +/* ----------------------------------------------------------------- responsive */ +@media (max-width: 900px) { + .section-head { + align-items: flex-start; + flex-direction: column; + } + + .tabs { + width: 100%; + } + + .tab { + flex: 1 1 auto; + justify-content: center; + } + + .grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .player-meta { + width: 140px; + } +} + +@media (max-width: 640px) { + .topbar { + flex-wrap: wrap; + gap: 10px; + padding: 12px 16px; + } + + .status, + .days-picker > span { + display: none; + } + + .topbar-actions { + gap: 8px; + } + + .btn { + padding: 8px 12px; + } + + .brand-beta { + display: none; + } + + .wrap { + width: min(100% - 28px, 1240px); + } + + .hero { + padding-top: 46px; + } + + .hero h1 { + font-size: clamp(48px, 17vw, 74px); + } + + .stats { + gap: 20px; + } + + .grid { + gap: 14px; + } + + .card-body { + padding: 12px 13px 12px; + } + + .card-body h3 { + font-size: 14px; + } + + .reason { + font-size: 10.5px; + } + + .play-btn { + width: 42px; + height: 42px; + opacity: 1; + transform: none; + } + + .player { + bottom: 10px; + gap: 9px; + width: calc(100% - 20px); + padding: 8px 10px 8px 8px; + } + + .player-meta { + width: auto; + flex: 1; + } + + .player-progress { + display: none; + } + + .player-close { + width: 24px; + } + + .footer { + flex-direction: column; + padding-bottom: 100px; + } +} + +@media (max-width: 430px) { + .grid { + grid-template-columns: 1fr; + } + + .tabs { + border-radius: 16px; + } + + .tab { + font-size: 11px; + padding: 7px 9px; + } + + .tab-count { + display: none; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +}