Files
LastRecc/lastrecc-go/internal/lastfm/client.go
T

243 lines
5.5 KiB
Go

package lastfm
import (
"context"
"encoding/json"
"fmt"
"net/url"
"path/filepath"
"strconv"
"time"
"lastrecc-go/internal/cache"
"lastrecc-go/internal/httpclient"
)
const apiRoot = "https://ws.audioscrobbler.com/2.0/"
type FlexFloat float64
func (f *FlexFloat) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == "null" {
*f = 0
return nil
}
if data[0] == '"' {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
v, _ := strconv.ParseFloat(s, 64)
*f = FlexFloat(v)
return nil
}
var v float64
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*f = FlexFloat(v)
return nil
}
type FlexInt int
func (f *FlexInt) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == "null" {
*f = 0
return nil
}
if data[0] == '"' {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
v, _ := strconv.Atoi(s)
*f = FlexInt(v)
return nil
}
var v int
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*f = FlexInt(v)
return nil
}
type List[T any] []T
func (l *List[T]) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == "null" {
*l = nil
return nil
}
if data[0] == '[' {
var items []T
if err := json.Unmarshal(data, &items); err != nil {
return err
}
*l = items
return nil
}
var one T
if err := json.Unmarshal(data, &one); err != nil {
return err
}
*l = []T{one}
return nil
}
type Artist struct {
Name string `json:"name"`
MBID string `json:"mbid"`
URL string `json:"url"`
Match FlexFloat `json:"match"`
}
type Track struct {
Name string `json:"name"`
Artist Artist `json:"artist"`
Match FlexFloat `json:"match"`
Playcount FlexInt `json:"playcount"`
URL string `json:"url"`
Duration FlexInt `json:"duration"`
}
type Album struct {
Name string `json:"name"`
MBID string `json:"mbid"`
URL string `json:"url"`
Artist Artist `json:"artist"`
Playcount FlexInt `json:"playcount"`
}
type AlbumInfo struct {
Name string `json:"name"`
MBID string `json:"mbid"`
URL string `json:"url"`
Playcount FlexInt `json:"playcount"`
ReleaseDate string `json:"releaseDate"`
Tracks struct {
Track List[Track] `json:"track"`
} `json:"tracks"`
}
type Client struct {
key string
http *httpclient.Client
cache cache.JSONCache
}
func New(apiKey string, cacheDir string) *Client {
return &Client{
key: apiKey,
http: httpclient.New("LastRecc-Go/0.1", nil, httpclient.NewRateLimiter(4)),
cache: cache.JSONCache{Dir: filepath.Join(cacheDir, "lastfm"), TTL: 14 * 24 * time.Hour},
}
}
type apiError struct {
Error int `json:"error"`
Message string `json:"message"`
}
func (c *Client) call(ctx context.Context, method string, params url.Values, out any) error {
values := url.Values{
"method": {method},
"api_key": {c.key},
"format": {"json"},
}
for key, vals := range params {
for _, value := range vals {
values.Add(key, value)
}
}
cacheKey := method + "::" + values.Encode()
if raw, ok := c.cache.GetBytes(cacheKey); ok {
if err := json.Unmarshal(raw, out); err == nil {
return nil
}
}
raw, _, err := c.http.Get(ctx, apiRoot, values)
if err != nil {
return fmt.Errorf("lastfm %s: %w", method, err)
}
var apiErr apiError
if err := json.Unmarshal(raw, &apiErr); err == nil && apiErr.Error != 0 {
return fmt.Errorf("lastfm %s: %s", method, apiErr.Message)
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("lastfm %s decode: %w", method, err)
}
_ = c.cache.SetBytes(cacheKey, raw)
return nil
}
func (c *Client) SimilarArtists(ctx context.Context, artist string, limit int) ([]Artist, error) {
var response struct {
Similar struct {
Artist List[Artist] `json:"artist"`
} `json:"similarartists"`
}
err := c.call(ctx, "artist.getSimilar", url.Values{
"artist": {artist},
"limit": {strconv.Itoa(limit)},
"autocorrect": {"1"},
}, &response)
return response.Similar.Artist, err
}
func (c *Client) SimilarTracks(ctx context.Context, artist, track string, limit int) ([]Track, error) {
var response struct {
Similar struct {
Track List[Track] `json:"track"`
} `json:"similartracks"`
}
err := c.call(ctx, "track.getSimilar", url.Values{
"artist": {artist},
"track": {track},
"limit": {strconv.Itoa(limit)},
"autocorrect": {"1"},
}, &response)
return response.Similar.Track, err
}
func (c *Client) ArtistTopTracks(ctx context.Context, artist string, limit int) ([]Track, error) {
var response struct {
Top struct {
Track List[Track] `json:"track"`
} `json:"toptracks"`
}
err := c.call(ctx, "artist.getTopTracks", url.Values{
"artist": {artist},
"limit": {strconv.Itoa(limit)},
"autocorrect": {"1"},
}, &response)
return response.Top.Track, err
}
func (c *Client) ArtistTopAlbums(ctx context.Context, artist string, limit int) ([]Album, error) {
var response struct {
Top struct {
Album List[Album] `json:"album"`
} `json:"topalbums"`
}
err := c.call(ctx, "artist.getTopAlbums", url.Values{
"artist": {artist},
"limit": {strconv.Itoa(limit)},
"autocorrect": {"1"},
}, &response)
return response.Top.Album, err
}
func (c *Client) AlbumInfo(ctx context.Context, artist, album string) (AlbumInfo, error) {
var response struct {
Album AlbumInfo `json:"album"`
}
err := c.call(ctx, "album.getInfo", url.Values{
"artist": {artist},
"album": {album},
"autocorrect": {"1"},
}, &response)
return response.Album, err
}