quintodrome/utils/lastfm/client.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

114 lines
2.4 KiB
Go
Raw Normal View History

package lastfm
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
2020-10-20 09:38:44 -08:00
"strconv"
)
const (
apiBaseUrl = "https://ws.audioscrobbler.com/2.0/"
)
type Error struct {
Code int
Message string
}
func (e *Error) Error() string {
return fmt.Sprintf("last.fm error(%d): %s", e.Code, e.Message)
}
2021-02-07 19:26:05 -09:00
type httpDoer interface {
Do(req *http.Request) (*http.Response, error)
}
2021-02-07 19:26:05 -09:00
func NewClient(apiKey string, lang string, hc httpDoer) *Client {
return &Client{apiKey, lang, hc}
}
type Client struct {
apiKey string
lang string
2021-02-07 19:26:05 -09:00
hc httpDoer
}
2020-10-20 09:38:44 -08:00
func (c *Client) makeRequest(params url.Values) (*Response, error) {
params.Add("format", "json")
params.Add("api_key", c.apiKey)
2020-10-20 09:38:44 -08:00
req, _ := http.NewRequest("GET", apiBaseUrl, nil)
req.URL.RawQuery = params.Encode()
resp, err := c.hc.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var response Response
jsonErr := json.Unmarshal(data, &response)
if resp.StatusCode != 200 && jsonErr != nil {
return nil, fmt.Errorf("last.fm http status: (%d)", resp.StatusCode)
}
if jsonErr != nil {
return nil, jsonErr
}
if response.Error != 0 {
return &response, &Error{Code: response.Error, Message: response.Message}
}
2020-10-20 09:38:44 -08:00
return &response, nil
2020-10-20 09:38:44 -08:00
}
func (c *Client) ArtistGetInfo(ctx context.Context, name string, mbid string) (*Artist, error) {
2020-10-20 09:38:44 -08:00
params := url.Values{}
params.Add("method", "artist.getInfo")
params.Add("artist", name)
params.Add("mbid", mbid)
2020-10-20 09:38:44 -08:00
params.Add("lang", c.lang)
response, err := c.makeRequest(params)
if err != nil {
return nil, err
}
return &response.Artist, nil
}
func (c *Client) ArtistGetSimilar(ctx context.Context, name string, mbid string, limit int) (*SimilarArtists, error) {
2020-10-20 09:38:44 -08:00
params := url.Values{}
params.Add("method", "artist.getSimilar")
params.Add("artist", name)
params.Add("mbid", mbid)
2020-10-20 09:38:44 -08:00
params.Add("limit", strconv.Itoa(limit))
response, err := c.makeRequest(params)
if err != nil {
return nil, err
}
return &response.SimilarArtists, nil
}
func (c *Client) ArtistGetTopTracks(ctx context.Context, name string, mbid string, limit int) (*TopTracks, error) {
2020-10-20 18:53:52 -08:00
params := url.Values{}
params.Add("method", "artist.getTopTracks")
params.Add("artist", name)
params.Add("mbid", mbid)
2020-10-20 18:53:52 -08:00
params.Add("limit", strconv.Itoa(limit))
response, err := c.makeRequest(params)
if err != nil {
return nil, err
}
return &response.TopTracks, nil
}