aboutsummaryrefslogtreecommitdiffstats
path: root/lfmclient.go
blob: 1b39ce9598db28e09d3ab3f97092da06c3cdb66a (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"time"
)

type Image struct {
	Size string `json:"size"`
	Href string `json:"#text"`
}

type AlbumInfo struct {
	Images   []Image `json:"image"`
	Mbid     string
	Name     string `json:"title"`
	Url      string
	Position `json:"@attr"`
	Artist   string
}

type Date struct {
	Date string `json:"#text"`
	Uts  string
}

type PageAttrs struct {
	TotalPages string
	Total      string
	Page       string
	User       string
}

type ArtistInfo struct {
	Name string
	Mbid string
	Url  string
}

type Position struct {
	TrackNumber string `json:"position"`
}

type TrackInfo struct {
	Name      string
	Mbid      string
	Duration  string
	Artist    ArtistInfo
	Album     AlbumInfo
	PlayCount string
	Listeners string
}

type RecentTrack struct {
	Name   string
	Mbid   string
	Url    string
	Artist struct {
		Name string `json:"#text"`
		Mbid string
	}
	Album struct {
		Name string `json:"#text"`
		Mbid string
	}
	Images []Image `json:"image"`
	Date   Date
}

func (app *App) LfmQuery(payload map[string]string) []byte {
	r, _ := http.NewRequest("GET", "http://ws.audioscrobbler.com/2.0/", nil)
	values := r.URL.Query()
	values.Add("api_key", app.Config.Lfm.ApiKey)
	values.Add("format", "json")
	for key, value := range payload {
		values.Add(key, value)
	}
	r.URL.RawQuery = values.Encode()
	resp, _ := http.DefaultClient.Do(r)
	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	return body
}

func GetImage(images []Image, size string) string {
	for _, image := range images {
		if image.Size == size {
			return image.Href
		}
	}
	return "https://lastfm-img2.akamaized.net/i/u/64s/4128a6eb29f94943c9d206c08e625904.png"
}

func (app *App) AlbumInfo(artist, album string) AlbumInfo {
	r := app.LfmQuery(map[string]string{
		"method": "album.getInfo",
		"artist": artist,
		"album":  album,
	})
	var dst map[string]AlbumInfo
	json.Unmarshal(r, &dst)
	return dst["album"]
}

func (app *App) TrackInfo(artist, name string) TrackInfo {
	r := app.LfmQuery(map[string]string{
		"method":      "track.getInfo",
		"artist":      artist,
		"track":       name,
		"autocorrect": "1",
	})
	var dst map[string]TrackInfo
	json.Unmarshal(r, &dst)
	return dst["track"]
}

func (app *App) ImportRecentTracks(user *User) {
	s := &Session{
		UserId:        user.Id,
		Client:        "import",
		ClientVersion: "",
		Key:           randomToken(16),
		Protocol:      "1.2.1",
	}
	app.PutSession(s)
	i := app.NewImport(user.LfmName)
	payload := map[string]string{
		"method": "user.getRecentTracks",
		"limit":  "200",
		"user":   user.LfmName,
		"to":     strconv.Itoa(int(i.To.Unix())),
	}
	if i.From.IsZero() {
		payload["from"] = "0"
	} else {
		payload["from"] = strconv.Itoa(int(i.From.Unix()))
	}
	var dst map[string]struct {
		Attrs  PageAttrs     `json:"@attr"`
		Tracks []RecentTrack `json:"track"`
	}
	scrobbles := make([]Scrobble, 0, 200)
	var st time.Time
	for {
		scrobbles = scrobbles[:0]
		if !i.LastFetch.IsZero() {
			payload["to"] = strconv.Itoa(int(i.LastFetch.Unix()))
		}
		r := app.LfmQuery(payload)
		json.Unmarshal(r, &dst)
		tracks := dst["recenttracks"].Tracks
		if len(tracks) == 0 {
			i.Done = true
			break
		}
		for _, t := range tracks {
			ts, _ := strconv.Atoi(t.Date.Uts)
			if ts == 0 {
				continue
			}
			st = time.Unix(int64(ts), 0)
			scrobble := Scrobble{
				Artist:     NewCorrectable(t.Artist.Name),
				Album:      NewCorrectable(t.Album.Name),
				TrackName:  NewCorrectable(t.Name),
				Mbid:       t.Mbid,
				Time:       st,
				UserId:     user.Id,
				SessionKey: s.Key,
				Image:      GetImage(t.Images, "medium"),
			}
			app.GetScrobbleSong(&scrobble)
			scrobbles = append(scrobbles, scrobble)
		}
		if err := app.PutScrobbles(scrobbles); err != nil {
			log.Println(err)
		}
		i.LastFetch = st
		if err := app.SaveImport(i); err != nil {
			log.Println(err)
		}
	}
	if err := app.SaveImport(i); err != nil {
		log.Println(err)
	}
}

func (app *App) LovedTracks(user string) []TrackInfo {
	r := app.LfmQuery(map[string]string{
		"method": "user.getLovedTracks",
		"limit":  "100",
		"user":   user,
	})
	var dst map[string]struct {
		Attrs  PageAttrs   `json:"@attr"`
		Tracks []TrackInfo `json:"track"`
	}
	json.Unmarshal(r, &dst)
	root := dst["lovedtracks"]
	tracks := root.Tracks
	return tracks
}

func (app *App) GetSong(s *Song) {
	if s.Album != "" || s.Mbid != "" {
		if app.GetSongId(s) != nil {
			if s.Image == "" {
				s.Image = GetImage(app.AlbumInfo(s.Artist, s.Album).Images,
					"medium")
			}
			if err := app.InsertSong(s); err != nil {
				log.Println(err)
			}
		}
	} else {
		t := app.TrackInfo(s.Artist, s.Name)
		s.Album = t.Album.Name
		s.Mbid = t.Mbid
		s.Image = GetImage(t.Album.Images, "medium")
		if app.GetSongId(s) != nil {
			app.InsertSong(s)
		}
	}
}