-
Notifications
You must be signed in to change notification settings - Fork 0
/
lastfm.go
65 lines (54 loc) · 1.42 KB
/
lastfm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
type lastfmTrack struct {
Artist map[string]string `json:"artist"`
Name string `json:"name"`
Playcount string `json:"playcount"`
URL string `json:"url"`
}
func normalizeLastfmURL(url string) string {
x := strings.Replace(url, "(", "%28", -1)
return strings.Replace(x, ")", "%29", -1)
}
type lastfmChart map[string]map[string][]lastfmTrack
func getLastfmChart(username string, dateFrom, dateTo time.Time) (string, error) {
tsFrom := strconv.FormatInt(dateFrom.Unix(), 10)
tsTo := strconv.FormatInt(dateTo.Unix(), 10)
url := fmt.Sprintf(lastfmAPIUrl, username, tsFrom, tsTo)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
return buf.String(), nil
}
func getTopTrack(username string, from, to time.Time) (track, error) {
str, err := getLastfmChart(username, from, to)
if err != nil {
return track{}, err
}
var chart lastfmChart
json.Unmarshal([]byte(str), &chart)
top := chart["weeklytrackchart"]["track"][0]
playcount, err := strconv.ParseInt(top.Playcount, 10, 64)
if err != nil {
return track{}, err
}
return track{
Artist: top.Artist["#text"],
Name: top.Name,
Playcount: int(playcount),
URL: normalizeLastfmURL(top.URL),
username: username,
}, nil
}