forked from lacymorrow/album-art
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (52 loc) · 1.59 KB
/
index.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
'use strict';
module.exports = function (artist, album, size, cb) {
if (typeof artist !== 'string') {
throw new Error('Expected a string');
}
if (typeof album === 'function') {
cb = album;
album = size = null;
} else if (typeof size === 'function') {
cb = size;
size = null;
}
var data = '';
var sizes = ['small', 'medium', 'large', 'extralarge', 'mega'];
var method = (album === null) ? 'artist' : 'album';
var apiKey = '4cb074e4b8ec4ee9ad3eb37d6f7eb240';
var http = require('http');
var artist = artist.replace ("&", "and");
var options = {
host: 'ws.audioscrobbler.com',
port: 80,
path: encodeURI('/2.0/?format=json&api_key=' + apiKey + '&method=' + method + '.getinfo&artist=' + artist + '&album=' + album)
};
http.get(options, function(resp){
resp.on('data', function(chunk){
data += chunk;
});
resp.on('end', function(){
var json = JSON.parse(data);
if (typeof(json.error) !== 'undefined'){
// Error
return cb('JSON Error: ' + json.message, '');
} else if (sizes.indexOf(size) !== -1 && json[method] && json[method].image){
// Return image in specific size
json[method].image.forEach(function(e, i) {
if (e.size === size){
cb(null, e['#text']);
}
});
} else if (json[method] && json[method].image) {
// Return largest image
var i = json[method].image.length - 2;
cb(null, json[method].image[i]['#text']);
} else {
// No image art found
cb('Error: No image found.', '');
}
});
}).on("error", function(e){
return cb('Got error: ' + e.message);
});
};