forked from web-scrobbler/web-scrobbler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrobbler.js
631 lines (505 loc) · 19.8 KB
/
scrobbler.js
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/**
* Last.fm Scrobbler for Chrome
* by David Sabata
*
* https://github.com/david-sabata/Chrome-Last.fm-Scrobbler
*
*
* TODOs
*
* - add second validation to nowPlaying request handler or trust the data to be valid?
*
*/
const APP_NAME = "Chrome Last.fm Scrobbler";
const APP_VERSION = "1.16";
// browser tab with actually scrobbled track
var nowPlayingTab = null;
// api url
var apiURL = "http://ws.audioscrobbler.com/2.0/?";
var apiKey = "d9bb1870d3269646f740544d9def2c95";
// song structure, filled in nowPlaying phase, (artist, track, duration, startTime)
var song = {};
// timer to submit the song
var scrobbleTimeout = null;
// is scrobbling disabled?
var disabled = false;
// set up page action handler; use dummy.html popup to override
chrome.pageAction.onClicked.addListener(pageActionClicked);
/**
* Notification
*/
const NOTIFICATION_TIMEOUT = 5000;
const NOTIFICATION_SEPARATOR = ':::';
/**
* Page action icons
*/
const ICON_UNKNOWN = 'icon_unknown.png'; // not recognized
const ICON_NOTE = 'icon_note.png'; // now playing
const ICON_NOTE_DISABLED = 'icon_note_gray.png'; // disabled
const ICON_TICK = 'icon_tick.png'; // scrobbled
const ICON_TICK_DISABLED = 'icon_tick_gray.png'; // disabled
const ICON_CONN_DISABLED = 'icon_cross_gray.png'; // connector is disabled
/**
* Icon - title - popup set identificators
*/
const ACTION_UNKNOWN = 1;
const ACTION_NOWPLAYING = 2;
const ACTION_SCROBBLED = 3;
const ACTION_UPDATED = 4;
const ACTION_DISABLED = 5;
const ACTION_REENABLED = 6;
const ACTION_CONN_DISABLED = 7;
/**
* Default settings & update notification
*/
{
// use notifications by default
if (localStorage.useNotifications == null)
localStorage.useNotifications = 1;
// now playing notifications
if (localStorage.useNotificationsNowPlaying == null)
localStorage.useNotificationsNowPlaying = 1;
// scrobbled notifications
if (localStorage.useNotificationsScrobbled == null)
localStorage.useNotificationsScrobbled = 1;
// don't use the YT statuses by default
if (localStorage.useYTInpage == null)
localStorage.useYTInpage = 0;
// show update popup - based on different version
if (localStorage.appVersion != APP_VERSION) {
localStorage.appVersion = APP_VERSION;
// introduce new options if not already set
if (typeof localStorage.useAutocorrect == 'undefined')
localStorage.useAutocorrect = 0;
}
}
function reset() {
console.log('reset called');
if (scrobbleTimeout != null) {
clearTimeout(scrobbleTimeout);
scrobbleTimeout = null;
}
nowPlayingTab = null;
song = {};
}
/**
* Calculates MD5 hash of the API request
* stored in k=v&k=v&... format
* @param params object
* @return md5 hash
*/
function apiCallSignature(params) {
var keys = new Array();
var o = '';
for (var x in params)
keys.push(x);
// params has to be ordered alphabetically
keys.sort();
for (i = 0; i < keys.length; i++) {
if (keys[i] == 'format' || keys[i] == 'callback')
continue;
o = o + keys[i] + params[keys[i]];
}
//console.log('hashing %s', o);
// append secret
return MD5(o + '2160733a567d4a1a69a73fad54c564b2');
}
/**
* Creates query string from object properties
*/
function createQueryString(params) {
var parts = new Array();
for (var x in params)
parts.push( x + '=' + encodeUtf8( params[x] ) );
return parts.join('&');
}
/**
* Encodes the utf8 string to use in parameter of API call
*/
function encodeUtf8(s) {
return encodeURIComponent( s );
}
/**
* Page action onclick handler. Switches scrobbling off and on
* and calls setActionIcon to re-set the icon accordingly
*/
function pageActionClicked(tabObj) {
// switch
disabled = !disabled;
// set up new icon
if (disabled) {
reset();
setActionIcon(ACTION_DISABLED, tabObj.id);
} else {
setActionIcon(ACTION_REENABLED, tabObj.id);
}
}
/**
* Sets up page action icon, including title and popup
* 'action' is one of the ACTION_ constants
*/
function setActionIcon(action, tabId) {
var tab = tabId ? tabId : nowPlayingTab;
chrome.pageAction.hide(tab);
console.log('set icon: ' + action);
switch(action) {
case ACTION_UNKNOWN:
chrome.pageAction.setIcon({tabId: tab, path: ICON_UNKNOWN});
chrome.pageAction.setTitle({tabId: tab, title: 'Song not recognized. Click the icon to correct its title'});
chrome.pageAction.setPopup({tabId: tab, popup: 'popup.html'});
break;
case ACTION_NOWPLAYING:
chrome.pageAction.setIcon({tabId: tab, path: ICON_NOTE});
chrome.pageAction.setTitle({tabId: tab, title: 'Now playing: ' + song.artist + ' - ' + song.track + '\nClick to disable scrobbling'});
chrome.pageAction.setPopup({tabId: tab, popup: ''});
break;
case ACTION_SCROBBLED:
chrome.pageAction.setIcon({tabId: tab, path: ICON_TICK});
chrome.pageAction.setTitle({tabId: tab, title: 'Song has been scrobbled\nClick to disable scrobbling'});
chrome.pageAction.setPopup({tabId: tab, popup: ''});
break;
case ACTION_DISABLED:
chrome.pageAction.setIcon({tabId: tab, path: ICON_NOTE_DISABLED});
chrome.pageAction.setTitle({tabId: tab, title: 'Scrobbling is disabled\nClick to enable'});
chrome.pageAction.setPopup({tabId: tab, popup: ''});
break;
case ACTION_REENABLED:
chrome.pageAction.setIcon({tabId: tab, path: ICON_TICK_DISABLED});
chrome.pageAction.setTitle({tabId: tab, title: 'Scrobbling will continue for the next song'});
chrome.pageAction.setPopup({tabId: tab, popup: ''});
break;
case ACTION_CONN_DISABLED:
chrome.pageAction.setIcon({tabId: tab, path: ICON_CONN_DISABLED});
chrome.pageAction.setTitle({tabId: tab, title: 'Scrobbling for this site is disabled, most likely because the site has changed its layout. Please contact the connector author.'});
chrome.pageAction.setPopup({tabId: tab, popup: ''});
break;
}
chrome.pageAction.show(tab);
}
/**
* Shows (or not) the notification, based on user settings
* Use 'force' to override settings and always show the notification (e.g. for errors)
*/
function scrobblerNotification(text, force) {
if (localStorage.useNotifications != 1 && !force)
return;
var title = 'Last.fm Scrobbler';
var body = '';
var boom = text.split(NOTIFICATION_SEPARATOR);
if (boom.length == 1)
body = boom[0];
else {
title = boom[0];
body = boom[1];
}
var notification = webkitNotifications.createNotification(
'icon128.png',
title,
body
);
notification.show();
setTimeout(function() {notification.cancel()}, NOTIFICATION_TIMEOUT);
}
/**
* Retrieves a token and opens a new window for user to authorize it
*/
function authorize() {
var http_request = new XMLHttpRequest();
http_request.open("GET", apiURL + 'method=auth.gettoken&api_key=' + apiKey, false); // synchronous
http_request.setRequestHeader("Content-Type", "application/xml");
http_request.send(null);
console.log('getToken response: %s', http_request.responseText);
var xmlDoc = $.parseXML(http_request.responseText);
var xml = $(xmlDoc);
var status = xml.find('lfm').attr('status');
if (status != 'ok') {
console.log('Error acquiring a token: %s', http_request.responseText);
localStorage.token = '';
} else {
localStorage.token = xml.find('token').text();
// open a tab with token authorization
var url = 'http://www.last.fm/api/auth/?api_key=' + apiKey + '&token=' + localStorage.token;
window.open(url);
}
}
/**
* Retrieve sessionID token if not already available
* Returns false if the sessionID cannot be retrieved (try again later - user has to authorize)
*/
function getSessionID() {
// check for a token first
if (!localStorage.token || localStorage.token == '') {
authorize();
return false;
}
// do we already have a session?
if (localStorage.sessionID && localStorage.sessionID != '')
return localStorage.sessionID;
var params = {
method: 'auth.getsession',
api_key: apiKey,
token: localStorage.token
};
var api_sig = apiCallSignature(params);
var url = apiURL + createQueryString(params) + '&api_sig=' + api_sig;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, false); // synchronous
http_request.setRequestHeader("Content-Type", "application/xml");
http_request.send(null);
console.log('getSession reponse: %s', http_request.responseText);
var xmlDoc = $.parseXML(http_request.responseText);
var xml = $(xmlDoc);
var status = xml.find('lfm').attr('status');
if (status != 'ok') {
console.log('getSession: the token probably hasn\'t been authorized');
localStorage.sessionID = '';
authorize();
} else {
localStorage.sessionID = xml.find('key').text();
return localStorage.sessionID;
}
return false;
}
/**
* Validate song info against last.fm and return valid song structure
* or false in case of failure
* @return object/false
*/
function validate(artist, track) {
var autocorrect = localStorage.useAutocorrect ? localStorage.useAutocorrect : 0;
var validationURL = apiURL + "method=track.getinfo&api_key=" + apiKey + "&autocorrect="+ autocorrect +"&artist=" + encodeUtf8(artist) + "&track=" + encodeUtf8(track);
console.log('validating %s - %s', artist, track);
var req = new XMLHttpRequest();
req.open('GET', validationURL, false);
req.send(null);
if(req.status == 200) {
if (req.responseText != "You must supply either an artist and track name OR a musicbrainz id.") {
// fill-in the song structure with validated data
var xmlDoc = $.parseXML(req.responseText);
var xml = $(xmlDoc);
// return the valid song info
return {artist : xml.find('artist > name').text(),
track : xml.find('track > name').text(),
duration : xml.find('track > duration').text()
};
} else {
console.log('validation failed: %s', req.responseText);
}
}
return false;
}
/**
* Tell server which song is playing right now (won't be scrobbled yet!)
*/
function nowPlaying() {
console.log('nowPlaying called for %s - %s', song.artist, song.track);
if (disabled) {
console.log('scrobbling disabled; exitting nowPlaying');
return;
}
// if the token/session is not authorized, wait for a while
var sessionID = getSessionID();
if (sessionID === false)
return;
var params = {
method: 'track.updatenowplaying',
track: song.track,
artist: song.artist,
api_key: apiKey,
sk: sessionID
};
var api_sig = apiCallSignature(params);
var url = apiURL + createQueryString(params) + '&api_sig=' + api_sig;
var notifText = 'Now playing' + NOTIFICATION_SEPARATOR + song.artist + " - " + song.track;
var http_request = new XMLHttpRequest();
http_request.open("POST", url, false); // synchronous
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(params);
console.log('nowPlaying response: %s', http_request.responseText);
var xmlDoc = $.parseXML(http_request.responseText);
var xml = $(xmlDoc);
if (xml.find('lfm').attr('status') == 'ok') {
console.log('now playing %s - %s', song.artist, song.track);
// Confirm the content_script, that the song is "now playing"
chrome.tabs.sendRequest(nowPlayingTab, {type: "nowPlayingOK"});
// Show notification
if (localStorage.useNotificationsNowPlaying == 1)
scrobblerNotification(notifText);
// Update page action icon
setActionIcon(ACTION_NOWPLAYING);
} else {
alert('Last.fm responded with unknown code on nowPlaying request');
}
}
/**
* Finally scrobble the song, but only if it has been playing long enough.
* Cleans global variables "song", "playingTab" and "scrobbleTimeout" on success.
*/
function submit() {
// bad function call
if (song == null || !song || song.artist == '' || song.track == '' || typeof(song.artist) == "undefined" || typeof(song.track) == "undefined" ) {
reset();
chrome.tabs.sendRequest(nowPlayingTab, {type: "submitFAIL", reason: "No song"});
return;
}
// if the token/session is not authorized, wait for a while
var sessionID = getSessionID();
if (sessionID === false)
return;
console.log('submit called for %s - %s', song.artist, song.track);
var params = {
method: 'track.scrobble',
'timestamp[0]': song.startTime,
'track[0]': song.track,
'artist[0]': song.artist,
api_key: apiKey,
sk: sessionID
};
var api_sig = apiCallSignature(params);
var url = apiURL + createQueryString(params) + '&api_sig=' + api_sig;
var http_request = new XMLHttpRequest();
http_request.open("POST", url, false); // synchronous
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(params);
if (http_request.status == 200) {
var notifText = 'Scrobbled' + NOTIFICATION_SEPARATOR + song.artist + " - " + song.track;
// notification
if (localStorage.useNotificationsScrobbled == 1)
scrobblerNotification(notifText);
// Update page action icon
setActionIcon(ACTION_SCROBBLED);
// stats
_gaq.push(['_trackEvent', 'Track scrobbled']);
console.log('submitted %s - %s (%s)', song.artist, song.track, http_request.responseText);
// Confirm the content script, that the song has been scrobbled
if (nowPlayingTab)
chrome.tabs.sendRequest(nowPlayingTab, {type: "submitOK", song: {artist:song.artist, track: song.track}});
}
else if (http_request.status == 503) {
console.log('submit failed %s - %s (%s)', song.artist, song.track, http_request.responseText);
alert('Unable to scrobble the track. Last.fm server is temporarily unavailable.');
}
else {
console.log('submit failed %s - %s (%s)', song.artist, song.track, http_request.responseText);
alert('An error occured while scrobbling the track. Please try again later.');
}
// clear the structures awaiting the next song
reset();
}
/**
* Extension inferface for content_script
* nowPlaying(artist, track, currentTime, duration) - send info to server which song is playing right now
* xhr(url) - send XHR GET request and return response text
* newSession() - start a new last.fm session (need to reauthenticate)
* validate(artist, track) - validate artist-track pair against last.fm and return false or the valid song
*/
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
switch(request.type) {
// Called when a new song has started playing. If the artist/track is filled,
// they have to be already validated! Otherwise they can be corrected from the popup.
// Also sets up a timout to trigger the scrobbling procedure (when all data are valid)
case "nowPlaying":
console.log('nowPlaying requested');
console.log($.dump(request));
// do the reset to be sure there is no other timer running
reset();
// remember the caller
nowPlayingTab = sender.tab.id;
// scrobbling disabled?
if (disabled) {
setActionIcon(ACTION_DISABLED, nowPlayingTab);
break;
}
// backward compatibility for connectors which dont use currentTime
if (typeof(request.currentTime) == 'undefined')
request.currentTime = 0;
// data missing, save only startTime and show the unknown icon
if (typeof(request.artist) == 'undefined' || typeof(request.track) == 'undefined') {
// fill only the startTime, so the popup knows how to set up the timer
song = {
startTime : parseInt(new Date().getTime() / 1000.0) // in seconds
};
// if we know something...
if (typeof(request.artist) != 'undefined')
song.artist = request.artist;
if (typeof(request.track) != 'undefined')
song.track = request.track;
if (typeof(request.currentTime) != 'undefined')
song.currentTime = request.currentTime;
if (typeof(request.duration) != 'undefined')
song.duration = request.duration;
// Update page action icon to 'unknown'
setActionIcon(ACTION_UNKNOWN, sender.tab.id);
}
// all data are avaliable and valid, set up the timer
else {
// fill the new playing song
song = {
artist : request.artist,
track : request.track,
currentTime : request.currentTime,
duration : request.duration,
startTime : ( parseInt (new Date().getTime() / 1000.0) - request.currentTime) // in seconds
}
// make the connection to last.fm service to notify
nowPlaying();
// The minimum time is 240 seconds or half the
// track's total length. Subtract the song's
// current time (for the case of unpausing).
var min_time = (Math.max(1, Math.min(240, song.duration / 2) - song.currentTime));
// Set up the timer
scrobbleTimeout = setTimeout(submit, min_time * 1000);
}
sendResponse({});
break;
// called when the window closes / unloads before the song can be scrobbled
case "reset":
// TEMP
//delete localStorage.sessionID;
//delete localStorage.token;
reset();
sendResponse({});
break;
case "trackStats":
_gaq.push(['_trackEvent', request.text]);
sendResponse({});
break;
// returns the options in key => value pseudomap
case "getOptions":
var opts = {};
for (var x in localStorage)
opts[x] = localStorage[x];
sendResponse({value: opts});
break;
// do we need this anymore? (content script can use ajax)
case "xhr":
var http_request = new XMLHttpRequest();
http_request.open("GET", request.url, true);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4 && http_request.status == 200)
sendResponse({text: http_request.responseText});
};
http_request.send(null);
break;
// for login
case "newSession":
sessionID = "";
break;
// connector tells us it is disabled
case "reportDisabled":
setActionIcon(ACTION_CONN_DISABLED, sender.tab.id);
break;
// Checks if the request.artist and request.track are valid and
// returns false if not or a song structure otherwise (may contain autocorrected values)
case "validate":
console.log('validate requested');
var res = validate(request.artist, request.track);
// res is false or a valid song structure
sendResponse( res );
break;
default:
console.log('Unknown request: %s', $.dump(request));
}
}
);