This repository has been archived by the owner on May 30, 2022. It is now read-only.
/
scrobbler.js
108 lines (90 loc) · 2.34 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
Util = {
sortObject: function(o) {
var sorted = {}, key, a = [];
for(key in o) {
if(o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for(key = 0; key < a.length; key++) {
sorted[a[key]] = o[a[key]];
}
return sorted;
},
buildQuery: function(params) {
var query = [], paramName;
for(paramName in params) {
query.push(encodeURIComponent(paramName) + '=' + encodeURIComponent(params[paramName]));
}
return query.join('&');
}
};
Scrobbler = {
apiKey: "3782aa8b2bedec1020e87ba55411533f",
apiSecret: "0e9cdc350d10b96050b5cdfc68223418",
// please be kind and don't steal these
apiRoot: "http://ws.audioscrobbler.com/2.0/",
getToken: function(callback) {
var params = {method: "auth.getToken"};
Scrobbler.makeRequest(params, callback);
},
getSession: function(token, callback) {
var params = {
method: "auth.getSession",
token: token
};
Scrobbler.makeRequest(params, callback);
},
scrobble: function(artist, track, callback) {
var params = {
method: "track.scrobble",
artist: artist,
track: track,
sk: settings.sessionKey
};
Scrobbler.makeRequest(params, callback);
},
makeRequest: function(params, callback) {
params.api_key = Scrobbler.apiKey;
params.api_sig = Scrobbler.signRequest(params);
params.format = "json";
var xhr = new XMLHttpRequest();
xhr.open("POST", Scrobbler.apiRoot + '?' + Util.buildQuery(params), true);
xhr.onreadystatechange = function(data) {
if(xhr.readyState === 4 && xhr.status === 200) {
if(callback) {
callback(JSON.parse(xhr.responseText));
}
}
else if(xhr.readyState === 4) {
console.log("error");
console.log(xhr);
if(typeof callback === "function") {
callback({
error: "Last.fm appears to be unavailable.",
status: xhr.status
});
}
}
};
xhr.send();
},
signRequest: function(params) {
if(typeof params !== "object") {
params = [];
}
if(params.api_key === undefined) {
params.api_key = Scrobbler.apiKey;
}
if(params.timestamp === undefined) {
params.timestamp = Math.round((new Date()).getTime() / 1000);
}
var sortedParams = Util.sortObject(params);
var sigString = "", paramName;
for(paramName in sortedParams) {
sigString += paramName + sortedParams[paramName];
}
return hex_md5(sigString + Scrobbler.apiSecret);
}
};