combine.fm/routes/search.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-08-20 23:22:57 +01:00
import { parse } from 'url';
2017-10-23 17:58:23 +01:00
import kue from 'kue';
2017-10-23 22:47:14 +01:00
import debuglog from 'debug';
2018-04-08 16:31:46 +01:00
import { inspect } from 'util';
2015-06-03 21:45:54 -07:00
import lookup from '../lib/lookup';
import services from '../lib/services';
2017-10-23 19:26:49 +01:00
import { find, create } from '../lib/share';
2015-05-17 19:10:30 +01:00
2017-10-23 22:47:14 +01:00
const debug = debuglog('combine.fm:search');
2017-10-23 17:58:23 +01:00
const queue = kue.createQueue({
2017-10-23 19:26:49 +01:00
redis: process.env.REDIS_URL,
2017-10-23 17:58:23 +01:00
});
2015-08-21 18:33:50 +01:00
2018-04-13 21:44:31 +01:00
export default async function (ctx) {
2017-11-11 19:18:42 +00:00
try {
2018-04-13 21:44:31 +01:00
const url = parse(ctx.request.body.url);
2018-04-13 21:44:31 +01:00
ctx.assert(url.host, 400, { error: { message: 'You need to submit a url.' } });
2015-06-03 21:45:54 -07:00
2018-04-13 21:44:31 +01:00
const music = await lookup(ctx.request.body.url);
2018-04-14 00:18:48 +01:00
debug(music);
2018-04-13 21:44:31 +01:00
ctx.assert(music, 400, { error: { message: 'No supported music found at that link :(' } });
let share = await find(music);
2015-05-17 19:10:30 +01:00
2017-11-11 19:18:42 +00:00
if (!share) {
2018-04-13 21:44:31 +01:00
share = await create(music);
2017-10-23 17:58:23 +01:00
2017-11-11 19:18:42 +00:00
services.forEach((service) => {
if (service.id !== share.service) {
const job = queue.create('search', { title: `Matching ${share.name} on ${service.id}`, share, service })
.attempts(3)
.backoff({ type: 'exponential' })
.save((err) => {
debug(err || `JobID: ${job.id}`);
});
2017-11-11 19:18:42 +00:00
}
});
}
2015-06-03 21:45:54 -07:00
2017-11-11 19:18:42 +00:00
share = share.toJSON();
2017-11-11 19:18:42 +00:00
share.id = share.externalId;
2017-05-07 22:55:42 +01:00
2017-11-11 19:18:42 +00:00
const unmatched = services.filter(service =>
!share.matches.find(match => match.service === service.id));
2017-11-11 19:18:42 +00:00
share.matches = share.matches.concat(unmatched.map((service) => {
return {
service: service.id,
matching: true,
};
}));
2017-11-11 19:18:42 +00:00
share.matches = share.matches.sort(a => !!a.externalId);
2018-04-13 21:44:31 +01:00
ctx.body = share;
} catch (err) {
if (err.name === 'BadRequestError') {
throw err;
}
debug(inspect(err, {showHidden: false, depth: null}));
ctx.throw(400, { error: { message: 'Unexpected error looking up music. Please try again later.' } });
2017-11-11 19:18:42 +00:00
}
}