combine.fm/routes/share.js

73 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-06-03 21:45:54 -07:00
import React from 'react';
2016-01-09 15:10:28 +00:00
import { renderPage } from '../lib/react-handler';
2015-08-20 23:22:57 +01:00
import { routes } from '../views/app';
2015-06-03 21:45:54 -07:00
import services from '../lib/services';
import co from 'co';
2014-12-15 12:49:17 +00:00
2015-08-20 23:22:57 +01:00
function formatAndSort(matches, serviceId) {
2015-05-17 19:10:30 +01:00
matches = Object.keys(matches).map(function (key) {return matches[key]; });
matches.sort(function(a, b) {
return a.id && !b.id;
2015-05-17 19:10:30 +01:00
}).sort(function(a) {
return a.service !== serviceId;
});
return matches;
2015-05-17 19:10:30 +01:00
};
2015-08-20 23:22:57 +01:00
export default function* (serviceId, type, itemId, format, next) {
2015-06-03 21:45:54 -07:00
let matchedService;
2015-01-06 12:58:57 +00:00
services.some(function(service) {
2015-05-17 19:10:30 +01:00
matchedService = serviceId === service.id ? service : null;
2015-01-06 12:58:57 +00:00
return matchedService;
});
2014-12-05 17:40:07 +00:00
2015-06-03 21:45:54 -07:00
if (!matchedService || (type !== 'album' && type !== 'track')) {
return yield next;
2015-01-06 12:58:57 +00:00
}
let doc = yield this.db.matches.findOne({_id: serviceId + '$$' + itemId});
if (!doc) {
const item = yield matchedService.lookupId(itemId, type);
this.assert(item.id, 404);
item.matched_at = new Date(); // eslint-disable-line camelcase
const matches = {};
matches[item.service] = item;
2015-06-03 21:45:54 -07:00
for (let service of services) {
if (service.id === item.service) {
continue;
}
matches[service.id] = {service: service.id};
}
doc = {_id: item.service + '$$' + item.id, 'created_at': new Date(), services: matches};
yield this.db.matches.save(doc);
process.nextTick(() => {
for (let service of services) {
console.log(service.id);
if (service.id === item.service) {
continue;
}
matches[service.id] = {service: service.id};
co(function* (){
const match = yield service.search(item);
console.log(match.id);
match.matched_at = new Date(); // eslint-disable-line camelcase
const update = {};
update['services.' + match.service] = match;
yield this.db.matches.updateOne({_id: item.service + '$$' + item.id}, {'$set': update});
}.bind(this)).catch((err) => {
debug(err);
});
}
});
}
2015-01-06 12:58:57 +00:00
2015-08-20 23:22:57 +01:00
const shares = formatAndSort(doc.services, serviceId);
2015-06-03 21:45:54 -07:00
if (format === 'json') {
2015-08-21 18:33:50 +01:00
return this.body = {shares: shares};
}
2015-06-03 21:45:54 -07:00
2016-01-09 15:10:28 +00:00
this.body = yield renderPage(routes, this.request.url, {shares: shares});
};