forked from mertdogar/node-acoustid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (61 loc) · 1.67 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* jshint node:true */
"use strict";
var fpcalc = require("fpcalc");
module.exports = function(file, options, callback) {
// Get fingerprint of file
fpcalc(file, function(err, result) {
if (err) return callback(err);
// Return track info
getinfo(result, options, callback);
});
};
// -- Get track information given fingerprint
var querystring = require("querystring"),
concat = require("concat-stream");
var META_DEFAULT = "recordings releases releasegroups tracks usermeta sources";
function getinfo(fp, options, callback) {
// Create request to http service
var req = request({
format: "json",
meta: options.meta || META_DEFAULT,
client: options.key,
duration: fp.duration,
fingerprint: fp.fingerprint,
});
req.on("error", callback);
req.on("response", function(res) {
res.pipe(concat(function(data) {
var results;
// Expect 200 response
if (res.statusCode !== 200) {
return callback(new Error(data));
}
// Expect valid JSON response body
try {
results = JSON.parse(data);
}
catch (err) {
return callback(err);
}
// Expect "ok" status in json object
if (results.status !== "ok") {
return callback(new Error(data));
}
// Return results
callback(null, results.results);
}));
});
}
// -- Create HTTP request object
var API_URL = "http://api.acoustid.org/v2/lookup",
hyperquest = require("hyperquest");
function request(params) {
var req = hyperquest.post(API_URL),
query = querystring.stringify(params),
buf = new Buffer(query);
req.setHeader("Content-Type", "application/x-www-form-urlencoded");
req.setHeader("Content-Length", buf.length);
// @TODO GZip the request body
req.end(buf);
return req;
}