62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package models
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
type LastFMTrack struct {
|
|
Name string `json:"name"`
|
|
Artist struct {
|
|
Name string `json:"#text"`
|
|
} `json:"artist"`
|
|
Album struct {
|
|
Name string `json:"#text"`
|
|
} `json:"album"`
|
|
Date struct {
|
|
Unix string `json:"#text"`
|
|
} `json:"date"`
|
|
}
|
|
|
|
type LastFMResponse struct {
|
|
RecentTracks struct {
|
|
Tracks []LastFMTrack `json:"track"`
|
|
} `json:"recenttracks"`
|
|
}
|
|
|
|
func LastFMGetRecentTracks(username, apiKey string) (*LastFMResponse, error) {
|
|
url := fmt.Sprintf("https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json", username, apiKey)
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("lastfm get resp err: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("lastfm read resp body err: %v", err)
|
|
}
|
|
var lastFMResponse LastFMResponse
|
|
if err := json.Unmarshal(body, &lastFMResponse); err != nil {
|
|
return nil, fmt.Errorf("lastfm unmarshal err: %v", err)
|
|
}
|
|
|
|
return &lastFMResponse, nil
|
|
}
|
|
|
|
func LastFMGetLastTrack(username, apiKey string) (string, error) {
|
|
resp, err := LastFMGetRecentTracks(username, apiKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var data string
|
|
if len(resp.RecentTracks.Tracks) > 0 {
|
|
track := resp.RecentTracks.Tracks[0]
|
|
data = fmt.Sprintf("%s - %s", track.Name, track.Artist.Name)
|
|
} else {
|
|
return "", fmt.Errorf("len(resp.RecentTracks.Tracks) <= 0")
|
|
}
|
|
return data, nil
|
|
}
|