-
Notifications
You must be signed in to change notification settings - Fork 22
/
audioscrobbler.cpp
327 lines (272 loc) · 8.57 KB
/
audioscrobbler.cpp
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#include "mpdas.h"
#define APIKEY "a0ed2629d3d28606f67d7214c916788d"
#define SECRET "295f31c5d28215215b1503fb0327cc01"
#define CURL_MAX_RETRIES 3
#define CURL_RETRY_DELAY 3 // Seconds
CAudioScrobbler* AudioScrobbler = 0;
#define CLEANUP() _response.clear()
size_t writecb(void* ptr, size_t size, size_t nmemb, void *stream)
{
AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);
return size*nmemb;
}
CAudioScrobbler::CAudioScrobbler(CConfig *cfg)
{
_cfg = cfg;
_failcount = 0;
_authed = false;
_response = "";
_handle = curl_easy_init();
if(!_handle) {
eprintf("%s", "Could not initialize CURL.");
exit(EXIT_FAILURE);
}
}
CAudioScrobbler::~CAudioScrobbler()
{
curl_easy_cleanup(_handle);
curl_global_cleanup();
}
std::string CAudioScrobbler::GetServiceURL()
{
if(_cfg->getService() == LibreFm) {
return "https://libre.fm/2.0/";
}
return "https://ws.audioscrobbler.com/2.0/";
}
void CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)
{
curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);
curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10);
if(postfields) {
curl_easy_setopt(_handle, CURLOPT_POST, 1);
curl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);
}
else
curl_easy_setopt(_handle, CURLOPT_POST, 0);
if(errbuf)
curl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);
curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());
CURLcode res = curl_easy_perform(_handle);
// Sometimes last.fm likes to just timeout for no reason, leaving us hanging.
// If this happens, retry a few times with a small delay.
if (res != CURLE_OK) {
eprintf("libcurl error (%d): %s", res, curl_easy_strerror(res));
eprintf("Will retry %d times with a %d second delay.", CURL_MAX_RETRIES, CURL_RETRY_DELAY);
int retries = 0;
do {
sleep(CURL_RETRY_DELAY);
retries++;
eprintf("Retry %d/%d", retries, CURL_MAX_RETRIES);
res = curl_easy_perform(_handle);
if (res != CURLE_OK) {
eprintf("Failed: %s", curl_easy_strerror(res));
}
} while (res != CURLE_OK && retries < CURL_MAX_RETRIES);
}
}
void CAudioScrobbler::ReportResponse(char* buf, size_t size)
{
_response.append(buf);
}
std::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry)
{
const Song& song = entry.getSong();
CLastFMMessage msg(_handle);
msg.AddField("method", "track.Scrobble");
msg.AddField("artist", song.getArtist());
msg.AddField("track", song.getTitle());
msg.AddField("duration", song.getDuration());
msg.AddField("timestamp", entry.getStartTime());
msg.AddField("sk", _sessionid);
msg.AddField("api_key", APIKEY);
if(!song.getAlbum().empty()) {
msg.AddField("album", song.getAlbum());
}
if(!song.getAlbumArtist().empty()) {
msg.AddField("albumArtist", song.getAlbumArtist());
}
return msg.GetMessage();
}
void CAudioScrobbler::Failure()
{
_failcount += 1;
if(_failcount >= 3) {
eprintf("%s", "Re-Handshaking!");
_failcount = 0;
Handshake();
}
}
bool CAudioScrobbler::CheckFailure(std::string response)
{
bool retval = false;
size_t start, end;
start = _response.find("<error code=\"")+13;
end = _response.find(">", start)-1;
std::string errorcode = _response.substr(start, end-start);
int code = strtol(errorcode.c_str(), 0, 10);
eprintf("%s%i", "Code: ", code);
switch(code) {
case 3:
eprintf("Invalid Method. This should not happen.");
retval = true;
break;
case 4:
eprintf("Authentication failed. Please check your login data.");
exit(EXIT_FAILURE);
case 9:
eprintf("Invalid session key. Re-authenticating.");
retval = true;
_failcount = 3;
break;
case 10:
eprintf("Invalid API-Key. Let's bugger off.");
exit(EXIT_FAILURE);
case 13:
eprintf("Invalid method signature.");
exit(EXIT_FAILURE);
case 16:
eprintf("The service is temporarily unavailable, we will try again later..");
retval = true;
break;
case 26:
eprintf("Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm");
exit(EXIT_FAILURE);
}
return retval;
}
bool CAudioScrobbler::Scrobble(const CacheEntry& entry)
{
bool retval = false;
if(!_authed) {
eprintf("Handshake hasn't been done yet.");
Handshake();
return retval;
}
iprintf("Scrobbling: %s - %s", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str());
OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str());
if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
iprintf("%s", "Scrobbled successfully.");
retval = true;
}
else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
eprintf("%s%s", "Last.fm returned an error while scrobbling:\n", _response.c_str());
if(CheckFailure(_response))
Failure();
}
CLEANUP();
return retval;
}
bool CAudioScrobbler::LoveTrack(const Song& song, bool unlove)
{
bool retval = false;
CLastFMMessage msg(_handle);
msg.AddField("method", unlove ? "track.unlove" : "track.love");
msg.AddField("artist", song.getArtist());
msg.AddField("track", song.getTitle());
msg.AddField("api_key", APIKEY);
msg.AddField("sk", _sessionid);
OpenURL(GetServiceURL(), msg.GetMessage().c_str());
if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
iprintf("%s", "(Un)loved track successfully.");
retval = true;
}
else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
eprintf("%s%s", "Last.fm returned an error while (un)loving the currently playing track:\n", _response.c_str());
if(CheckFailure(_response))
Failure();
}
CLEANUP();
return retval;
}
bool CAudioScrobbler::SendNowPlaying(const Song& song)
{
bool retval = false;
CLastFMMessage msg(_handle);
msg.AddField("method", "track.updateNowPlaying");
msg.AddField("artist", song.getArtist());
msg.AddField("track", song.getTitle());
msg.AddField("duration", song.getDuration());
msg.AddField("sk", _sessionid);
msg.AddField("api_key", APIKEY);
if(!song.getAlbum().empty()) {
msg.AddField("album", song.getAlbum());
}
if(!song.getAlbumArtist().empty()) {
msg.AddField("albumArtist", song.getAlbumArtist());
}
OpenURL(GetServiceURL(), msg.GetMessage().c_str());
if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
iprintf("%s", "Updated \"Now Playing\" status successfully.");
retval = true;
}
else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str());
if(CheckFailure(_response))
Failure();
}
CLEANUP();
return retval;
}
void CAudioScrobbler::Handshake()
{
std::string username = "";
for(unsigned int i = 0; i < _cfg->Get("username").length(); i++) {
username.append(1, tolower(_cfg->Get("username").c_str()[i]));
}
std::string password = _cfg->Get("password");
CLastFMMessage msg(_handle);
msg.AddField("method", "auth.getMobileSession");
msg.AddField("username", username);
if(_cfg->getService() == LastFm) {
msg.AddField("password", password);
}
else {
std::string password_hashed(md5sum((char*)"%s", password.c_str()));
std::string authtoken(md5sum((char*)"%s%s", username.c_str(), password_hashed.c_str()));
msg.AddField("authToken", authtoken);
msg.AddField("password", password_hashed);
}
msg.AddField("api_key", APIKEY);
OpenURL(GetServiceURL(), msg.GetMessage().c_str());
if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
size_t start, end;
start = _response.find("<key>") + 5;
end = _response.find("</key>");
_sessionid = _response.substr(start, end-start);
iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str());
_authed = true;
}
else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
CheckFailure(_response);
exit(EXIT_FAILURE);
}
CLEANUP();
}
std::string CLastFMMessage::GetMessage()
{
std::ostringstream strstream;
for(std::map<std::string, std::string>::iterator it = valueMap.begin(); it != valueMap.end(); ++it) {
if(it != valueMap.begin()) {
strstream << "&";
}
char* escaped = curl_easy_escape(curl_handle, it->second.c_str(), it->second.length());
strstream << it->first << "=" << escaped;
curl_free(escaped);
}
// append signature hash
strstream << "&api_sig=" << GetSignatureHash();
return strstream.str();
}
std::string CLastFMMessage::GetSignatureHash()
{
std::ostringstream strstream;
for(std::map<std::string, std::string>::iterator it = valueMap.begin(); it != valueMap.end(); ++it) {
strstream << it->first << it->second;
}
// append secret key
strstream << SECRET;
return std::string(md5sum((char*)"%s", strstream.str().c_str()));
}