package navidrome import ( "context" "encoding/json" "fmt" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "sync" "time" "lastrecc-go/internal/cache" "lastrecc-go/internal/config" "lastrecc-go/internal/httpclient" "lastrecc-go/internal/text" ) type Song struct { ID string `json:"id"` Title string `json:"title"` Artist string `json:"artist"` Album string `json:"album"` AlbumID string `json:"albumId"` ArtistID string `json:"artistId"` CoverArt string `json:"coverArt"` Duration float64 `json:"duration"` PlayCount int `json:"playCount"` Played string `json:"played"` } type Scrobble struct { ID int64 `json:"id"` MediaFileID string `json:"mediaFileId"` SubmissionTime int64 `json:"submissionTime"` } type Album struct { ID string `json:"id"` Name string `json:"name"` Artist string `json:"artist"` ArtistID string `json:"artistId"` CoverArt string `json:"coverArt"` SongCount int `json:"songCount"` Duration float64 `json:"duration"` PlayCount int `json:"playCount"` Played string `json:"played"` } type Artist struct { ID string `json:"id"` Name string `json:"name"` } type Playlist struct { ID string `json:"id"` Name string `json:"name"` SongCount int `json:"songCount"` } type ScanStatus struct { Scanning bool Count int LastScan string } type Client struct { cfg *config.Config http *httpclient.Client cacheDir string mu sync.Mutex token string salt string subToken string } type loginResponse struct { Token string `json:"token"` SubsonicSalt string `json:"subsonicSalt"` SubsonicToken string `json:"subsonicToken"` } func New(cfg *config.Config, cacheDir string) *Client { var basic *httpclient.BasicAuth if cfg.BasicUser != "" { basic = &httpclient.BasicAuth{User: cfg.BasicUser, Password: cfg.BasicPassword} } return &Client{ cfg: cfg, http: httpclient.New("LastRecc-Go/0.1", basic, httpclient.NewRateLimiter(8)), cacheDir: cacheDir, } } func (c *Client) Login(ctx context.Context) error { c.mu.Lock() defer c.mu.Unlock() body, _, err := c.http.PostJSON(ctx, c.cfg.NavidromeURL+"/auth/login", map[string]string{ "username": c.cfg.NavidromeUser, "password": c.cfg.NavidromePassword, }) if err != nil { return fmt.Errorf("navidrome login: %w", err) } var resp loginResponse if err := json.Unmarshal(body, &resp); err != nil { return fmt.Errorf("navidrome login response: %w", err) } if resp.Token == "" || resp.SubsonicSalt == "" || resp.SubsonicToken == "" { return fmt.Errorf("navidrome login: incomplete response") } c.token = resp.Token c.salt = resp.SubsonicSalt c.subToken = resp.SubsonicToken return nil } func (c *Client) ensureLogin(ctx context.Context) error { c.mu.Lock() ok := c.token != "" c.mu.Unlock() if ok { return nil } return c.Login(ctx) } func (c *Client) nativeGet(ctx context.Context, path string, params url.Values) ([]byte, http.Header, error) { if err := c.ensureLogin(ctx); err != nil { return nil, nil, err } for attempt := 0; attempt < 2; attempt++ { c.mu.Lock() token := c.token c.mu.Unlock() data, headers, err := c.http.GetWithHeaders(ctx, c.cfg.NavidromeURL+path, params, map[string]string{ "X-ND-Authorization": "Bearer " + token, }) if err != nil { if statusErr, ok := err.(*httpclient.StatusError); ok && statusErr.Status == http.StatusUnauthorized && attempt == 0 { if loginErr := c.Login(ctx); loginErr != nil { return nil, nil, loginErr } continue } return nil, nil, err } return data, headers, nil } return nil, nil, fmt.Errorf("navidrome request failed after re-authentication") } type scrobbleCache struct { FetchedAt int64 `json:"fetched_at"` Items []Scrobble `json:"items"` } func (c *Client) Scrobbles(ctx context.Context, force bool) ([]Scrobble, error) { cachePath := filepath.Join(c.cacheDir, "scrobbles.json") if !force && cache.Fresh(cachePath, 10*time.Minute) { var cached scrobbleCache if err := cache.LoadJSON(cachePath, &cached); err == nil && cached.Items != nil { return cached.Items, nil } } var items []Scrobble start := 0 for { params := url.Values{ "_end": {"5000"}, "_order": {"DESC"}, "_sort": {"submission_time"}, "_start": {strconv.Itoa(start)}, } data, headers, err := c.nativeGet(ctx, "/api/scrobble", params) if err != nil { return nil, err } var chunk []Scrobble if err := json.Unmarshal(data, &chunk); err != nil { return nil, fmt.Errorf("decode scrobbles: %w", err) } items = append(items, chunk...) total, _ := strconv.Atoi(headers.Get("X-Total-Count")) if len(chunk) == 0 || (total > 0 && len(items) >= total) { break } start += len(chunk) if start > 200000 { break } } if err := cache.SaveJSON(cachePath, scrobbleCache{FetchedAt: time.Now().Unix(), Items: items}); err != nil { fmt.Fprintf(os.Stderr, "warning: could not save scrobble cache: %v\n", err) } return items, nil } func (c *Client) Songs(ctx context.Context, ids []string, logf func(string, ...any)) (map[string]Song, error) { cachePath := filepath.Join(c.cacheDir, "navidrome_songs.json") all := map[string]Song{} if err := cache.LoadJSON(cachePath, &all); err != nil && !os.IsNotExist(err) { fmt.Fprintf(os.Stderr, "warning: could not read song cache: %v\n", err) } if all == nil { all = map[string]Song{} } var missing []string for _, id := range ids { if _, ok := all[id]; !ok { missing = append(missing, id) } } for offset := 0; offset < len(missing); offset += 80 { end := offset + 80 if end > len(missing) { end = len(missing) } params := url.Values{} for _, id := range missing[offset:end] { params.Add("id", id) } data, _, err := c.nativeGet(ctx, "/api/song", params) if err != nil { return nil, err } var songs []Song if err := json.Unmarshal(data, &songs); err != nil { return nil, fmt.Errorf("decode songs: %w", err) } for _, song := range songs { if song.ID != "" { all[song.ID] = song } } if logf != nil { logf("metadata %d/%d", min(end, len(missing)), len(missing)) } if err := cache.SaveJSON(cachePath, all); err != nil { fmt.Fprintf(os.Stderr, "warning: could not save song cache: %v\n", err) } } result := make(map[string]Song, len(ids)) for _, id := range ids { if song, ok := all[id]; ok { result[id] = song } } return result, nil } func (c *Client) subsonic(ctx context.Context, method string, params url.Values, post bool) (map[string]any, error) { if err := c.ensureLogin(ctx); err != nil { return nil, err } c.mu.Lock() salt, token := c.salt, c.subToken c.mu.Unlock() values := url.Values{ "u": {c.cfg.NavidromeUser}, "t": {token}, "s": {salt}, "v": {"1.16.1"}, "c": {"LastRecc-Go"}, "f": {"json"}, } for key, vals := range params { for _, value := range vals { values.Add(key, value) } } rawURL := c.cfg.NavidromeURL + "/rest/" + method + ".view" var data []byte var err error if post { data, _, err = c.http.PostForm(ctx, rawURL, values) } else { data, _, err = c.http.Get(ctx, rawURL, values) } if err != nil { return nil, err } var envelope map[string]any if err := json.Unmarshal(data, &envelope); err != nil { return nil, fmt.Errorf("decode subsonic %s: %w", method, err) } response, _ := envelope["subsonic-response"].(map[string]any) if response == nil { return nil, fmt.Errorf("subsonic %s: missing response", method) } if status, _ := response["status"].(string); status != "ok" { return nil, fmt.Errorf("subsonic %s: %v", method, response["error"]) } return response, nil } func (c *Client) SearchSongs(ctx context.Context, query string, limit int) ([]Song, error) { response, err := c.subsonic(ctx, "search3", url.Values{ "query": {query}, "songCount": {strconv.Itoa(limit)}, "albumCount": {"0"}, "artistCount": {"0"}, }, false) if err != nil { return nil, err } result, _ := response["searchResult3"].(map[string]any) if result == nil { return nil, nil } var songs []Song for _, raw := range asList(result["song"]) { if item, ok := raw.(map[string]any); ok { songs = append(songs, parseSong(item)) } } return songs, nil } func (c *Client) SearchAlbums(ctx context.Context, query string, limit int) ([]Album, error) { response, err := c.subsonic(ctx, "search3", url.Values{ "query": {query}, "songCount": {"0"}, "albumCount": {strconv.Itoa(limit)}, "artistCount": {"0"}, }, false) if err != nil { return nil, err } result, _ := response["searchResult3"].(map[string]any) if result == nil { return nil, nil } var albums []Album for _, raw := range asList(result["album"]) { if item, ok := raw.(map[string]any); ok { albums = append(albums, Album{ ID: asString(item["id"]), Name: asString(item["name"]), Artist: asString(item["artist"]), ArtistID: asString(item["artistId"]), CoverArt: asString(item["coverArt"]), SongCount: asInt(item["songCount"]), Duration: float64(asInt(item["duration"])), PlayCount: asInt(item["playCount"]), Played: asString(item["played"]), }) } } return albums, nil } func (c *Client) SearchArtists(ctx context.Context, query string, limit int) ([]Artist, error) { response, err := c.subsonic(ctx, "search3", url.Values{ "query": {query}, "songCount": {"0"}, "albumCount": {"0"}, "artistCount": {strconv.Itoa(limit)}, }, false) if err != nil { return nil, err } result, _ := response["searchResult3"].(map[string]any) if result == nil { return nil, nil } var artists []Artist for _, raw := range asList(result["artist"]) { if item, ok := raw.(map[string]any); ok { artists = append(artists, Artist{ID: asString(item["id"]), Name: asString(item["name"])}) } } return artists, nil } func (c *Client) GetAlbum(ctx context.Context, id string) (Album, []Song, error) { response, err := c.subsonic(ctx, "getAlbum", url.Values{"id": {id}}, false) if err != nil { return Album{}, nil, err } item, _ := response["album"].(map[string]any) if item == nil { return Album{}, nil, fmt.Errorf("album %s not found", id) } album := Album{ ID: asString(item["id"]), Name: asString(item["name"]), Artist: asString(item["artist"]), ArtistID: asString(item["artistId"]), CoverArt: asString(item["coverArt"]), SongCount: asInt(item["songCount"]), Duration: float64(asInt(item["duration"])), PlayCount: asInt(item["playCount"]), Played: asString(item["played"]), } var songs []Song for _, raw := range asList(item["song"]) { if rawMap, ok := raw.(map[string]any); ok { songs = append(songs, parseSong(rawMap)) } } return album, songs, nil } func (c *Client) GetPlaylists(ctx context.Context) ([]Playlist, error) { response, err := c.subsonic(ctx, "getPlaylists", nil, false) if err != nil { return nil, err } container, _ := response["playlists"].(map[string]any) if container == nil { return nil, nil } var playlists []Playlist for _, raw := range asList(container["playlist"]) { if item, ok := raw.(map[string]any); ok { playlists = append(playlists, Playlist{ ID: asString(item["id"]), Name: asString(item["name"]), SongCount: asInt(item["songCount"]), }) } } return playlists, nil } func (c *Client) CreatePlaylist(ctx context.Context, name string, songIDs []string) error { params := url.Values{"name": {name}} for _, id := range songIDs { params.Add("songId", id) } _, err := c.subsonic(ctx, "createPlaylist", params, true) return err } func (c *Client) DeletePlaylist(ctx context.Context, id string) error { _, err := c.subsonic(ctx, "deletePlaylist", url.Values{"id": {id}}, true) return err } func (c *Client) ScanStatus(ctx context.Context) (ScanStatus, error) { response, err := c.subsonic(ctx, "getScanStatus", nil, false) if err != nil { return ScanStatus{}, err } item, _ := response["scanStatus"].(map[string]any) if item == nil { return ScanStatus{}, nil } return ScanStatus{ Scanning: asBool(item["scanning"]), Count: asInt(item["count"]), LastScan: asString(item["lastScan"]), }, nil } func (c *Client) StartScan(ctx context.Context) error { _, err := c.subsonic(ctx, "startScan", nil, true) return err } func (c *Client) FindArtist(ctx context.Context, artist string) (Artist, bool, error) { artists, err := c.SearchArtists(ctx, artist, 5) if err != nil { return Artist{}, false, err } for _, candidate := range artists { if text.Similarity(candidate.Name, artist) >= 0.9 { return candidate, true, nil } } return Artist{}, false, nil } func (c *Client) FindSong(ctx context.Context, artist, title string) (Song, bool, error) { songs, err := c.SearchSongs(ctx, artist+" "+title, 5) if err != nil { return Song{}, false, err } best, bestScore := Song{}, 0.0 for _, song := range songs { score := text.Similarity(song.Title, title)*0.65 + text.Similarity(song.Artist, artist)*0.35 if score > bestScore { best, bestScore = song, score } } if bestScore >= 0.86 { return best, true, nil } return Song{}, false, nil } func (c *Client) FindAlbum(ctx context.Context, artist, album string) (Album, bool, error) { albums, err := c.SearchAlbums(ctx, artist+" "+album, 8) if err != nil { return Album{}, false, err } best, bestScore := Album{}, 0.0 for _, candidate := range albums { score := text.Similarity(candidate.Name, album)*0.65 + text.Similarity(candidate.Artist, artist)*0.35 if score > bestScore { best, bestScore = candidate, score } } if bestScore >= 0.86 { return best, true, nil } return Album{}, false, nil } func parseSong(item map[string]any) Song { return Song{ ID: asString(item["id"]), Title: asString(item["title"]), Artist: asString(item["artist"]), Album: asString(item["album"]), AlbumID: asString(item["albumId"]), ArtistID: asString(item["artistId"]), CoverArt: asString(item["coverArt"]), Duration: float64(asInt(item["duration"])), PlayCount: asInt(item["playCount"]), Played: asString(item["played"]), } } func asList(value any) []any { switch v := value.(type) { case []any: return v case map[string]any: return []any{v} default: return nil } } func asString(value any) string { switch v := value.(type) { case string: return v case float64: return strconv.FormatFloat(v, 'f', -1, 64) case json.Number: return v.String() default: return "" } } func asInt(value any) int { switch v := value.(type) { case float64: return int(v) case int: return v case string: parsed, _ := strconv.Atoi(v) return parsed case json.Number: parsed, _ := v.Int64() return int(parsed) default: return 0 } } func asBool(value any) bool { switch v := value.(type) { case bool: return v case string: return strings.EqualFold(v, "true") || v == "1" default: return false } }