Search additional markets for itunes and spotify

This commit is contained in:
Jonathan Cremin 2017-05-07 22:16:43 +01:00
parent 00ca82c851
commit 147ad4f3d2
4 changed files with 95 additions and 57 deletions

View file

@ -1,6 +1,8 @@
import { parse } from 'url';
import bluebird from 'bluebird';
import spotifyCB from 'spotify';
import request from 'superagent';
import 'superagent-bluebird-promise';
const spotify = bluebird.promisifyAll(spotifyCB);
import { match as urlMatch } from './url';
@ -64,8 +66,9 @@ export function* lookupId(id, type) {
}
}
export function* search(data) {
var cleanParam = function(str) {
export function* search(data, original={}) {
const markets = ['US', 'GB', 'JP', 'BR', 'DE', 'ES'];
const cleanParam = function(str) {
var chopChars = ['&', '[', '('];
chopChars.forEach(function(chr) {
if (data.artist.name.indexOf('&') > 0) {
@ -74,8 +77,8 @@ export function* search(data) {
})
return str.replace(/[\:\?]+/, "");
}
var query, album;
var type = data.type;
let query, album;
const type = data.type;
if (type == "album") {
query = "artist:" + cleanParam(data.artist.name) + " album:" + cleanParam(data.name);
@ -85,27 +88,50 @@ export function* search(data) {
album = data.albumName;
}
const results = yield spotify.searchAsync({query: query, type: type});
for (let market of markets) {
const response = yield request.get('https://api.spotify.com/v1/search?type=' + type + '&q=' + encodeURI(query) + '&market=' + market);
const items = response.body[type + 's'].items;
if (!results[type + "s"].items[0]) {
return {service: "spotify"};
} else {
let found;
const choppedAlbum = data.type == "album" ? cleanParam(data.name) : cleanParam(data.albumName);
if (!choppedAlbum.length) {
return yield lookupId(results[type + "s"].items[0].id, type);
const name = original.name || data.name;
let match;
if (!(match = exactMatch(name, items, type))) {
match = looseMatch(name, items, type);
}
results[type + "s"].items.forEach(function(item) {
const albumName = data.type == "album" ? item.name : item.album.name;
const matches = cleanParam(albumName).match(/^[^\(\[]+/);
if(choppedAlbum.indexOf(matches[0]) >= 0) {
found = item;
if (match) {
if (type === 'album') {
return yield lookupId(match.id, type);
} else if (type === 'track') {
return yield lookupId(match.id, type);
}
});
if (!found) {
return {service: "spotify"};
}
return yield lookupId(results[type + "s"].items[0].id, type);
}
return {service: "spotify"};
}
function exactMatch(needle, haystack, type) {
// try to find exact match
return haystack.find(function(entry) {
if (entry.type !== type) {
return false;
}
if (entry.name === needle) {
return entry;
}
});
}
function looseMatch(needle, haystack, type) {
// try to find exact match
return haystack.find(function(entry) {
if (entry.type !== type) {
return false;
}
if (entry.name.indexOf(needle) >= 0) {
return entry
}
});
}