2014-12-04 22:50:30 +00:00
|
|
|
"use strict";
|
|
|
|
var parse = require('url').parse;
|
|
|
|
var path = require('path');
|
|
|
|
|
|
|
|
var services = {};
|
|
|
|
|
|
|
|
require("fs").readdirSync(path.join(__dirname, "..", "lib", "services")).forEach(function(file) {
|
|
|
|
var service = require("../lib/services/" + file);
|
|
|
|
if (service.search) {
|
|
|
|
services[service.id] = service;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2014-12-06 21:12:52 +00:00
|
|
|
module.exports = function(req, res, next) {
|
2014-12-04 22:50:30 +00:00
|
|
|
var url = parse(req.body.url);
|
2014-12-05 20:44:10 +00:00
|
|
|
var searching = false;
|
2014-12-04 22:50:30 +00:00
|
|
|
|
|
|
|
if (!url.host) {
|
2014-12-23 00:35:17 +00:00
|
|
|
res.json({error:{message:"You need to submit a url."}});
|
2014-12-06 18:16:31 +00:00
|
|
|
} else {
|
2014-12-13 15:56:52 +00:00
|
|
|
var items = {};
|
|
|
|
for (var id in services) {
|
|
|
|
items[id] = {service: id};
|
|
|
|
}
|
2014-12-06 18:16:31 +00:00
|
|
|
for (var id in services) {
|
|
|
|
var matched = services[id].match(req.body.url);
|
|
|
|
if (matched) {
|
|
|
|
searching = true;
|
2014-12-13 00:10:41 +00:00
|
|
|
services[id].parseUrl(req.body.url).timeout(10000).then(function(result) {
|
2014-12-06 18:16:31 +00:00
|
|
|
if (!result.id) {
|
2014-12-22 22:38:08 +00:00
|
|
|
res.json({error:{message:"No match found for url"}});
|
2014-12-06 18:16:31 +00:00
|
|
|
} else {
|
2014-12-13 15:56:52 +00:00
|
|
|
services[id].lookupId(result.id, result.type).then(function(item) {
|
|
|
|
items[id] = item;
|
|
|
|
req.db.matches.save({_id:id + "$$" + result.id, created_at: new Date(), services:items}).then(function() {
|
2014-12-23 00:35:17 +00:00
|
|
|
res.json(item);
|
2014-12-13 15:56:52 +00:00
|
|
|
});
|
|
|
|
});
|
2014-12-06 18:16:31 +00:00
|
|
|
}
|
|
|
|
}, function(error) {
|
|
|
|
if (error.code == "ETIMEDOUT") {
|
|
|
|
error = new Error("Error talking to music service");
|
2014-12-23 00:35:17 +00:00
|
|
|
error.status = 502;
|
2014-12-06 21:12:52 +00:00
|
|
|
next(error);
|
2014-12-11 19:53:12 +00:00
|
|
|
} else if (!error || !error.status) {
|
2014-12-06 18:16:31 +00:00
|
|
|
error = new Error("An unexpected error happenend");
|
|
|
|
error.status = 500;
|
2014-12-06 21:12:52 +00:00
|
|
|
next(error);
|
|
|
|
} else if (error.status == 404){
|
2014-12-22 22:38:08 +00:00
|
|
|
res.json({error:{message:"No match found for url"}});
|
2014-12-06 18:16:31 +00:00
|
|
|
}
|
2014-12-06 21:12:52 +00:00
|
|
|
});
|
2014-12-06 18:16:31 +00:00
|
|
|
break;
|
|
|
|
}
|
2014-12-04 22:50:30 +00:00
|
|
|
}
|
|
|
|
}
|
2014-12-07 16:15:50 +00:00
|
|
|
if (url.host && !searching) {
|
2014-12-22 22:38:08 +00:00
|
|
|
res.json({error:{message:"No match found for url"}});
|
2014-12-05 20:44:10 +00:00
|
|
|
}
|
2014-12-04 22:50:30 +00:00
|
|
|
};
|