Switch to async/await

This commit is contained in:
Jonathan Cremin 2018-04-14 00:18:48 +01:00
parent 87459b2acc
commit 18021e0ef8
10 changed files with 53 additions and 8837 deletions

1
.gitignore vendored
View file

@ -5,4 +5,5 @@ public/**/*.gz
.DS_Store .DS_Store
.env .env
npm-debug.log npm-debug.log
yarn-error.log
stats.json stats.json

View file

@ -10,13 +10,13 @@ fs.readdirSync(path.join(__dirname, 'services')).forEach(function(file) {
} }
}); });
export default function* (url) { export default async function (url) {
let matchedService; let matchedService;
for (let service of services) { for (let service of services) {
matchedService = service.match(url); matchedService = service.match(url);
if (matchedService) { if (matchedService) {
const result = yield service.parseUrl(url); const result = await service.parseUrl(url);
return yield service.lookupId(result.id, result.type); return await service.lookupId(result.id, result.type);
} }
} }
}; };

View file

@ -13,9 +13,9 @@ const client = amazon.createClient({
awsTag: process.env.AWS_TAG, awsTag: process.env.AWS_TAG,
}); });
export function* lookupId(id, type) { export async function lookupId(id, type) {
try { try {
const results = yield client.itemLookup({ const results = await client.itemLookup({
itemId: id, itemId: id,
responseGroup: 'ItemAttributes,Images,ItemIds', responseGroup: 'ItemAttributes,Images,ItemIds',
}); });
@ -63,15 +63,15 @@ export function* lookupId(id, type) {
}; };
} }
} catch (err) { } catch (err) {
debug(inspect(err, { depth: 4 })); debug(inspect(err, { depth: null }));
} }
return { service: 'amazon' }; return { service: 'amazon' };
} }
export function* search(data) { export async function search(data) {
try { try {
const type = data.type; const type = data.type;
const results = yield client.itemSearch({ const results = await client.itemSearch({
author: data.artist.name.replace(':', ' '), author: data.artist.name.replace(':', ' '),
title: data.name.replace(':', ' '), title: data.name.replace(':', ' '),
searchIndex: 'MP3Downloads', searchIndex: 'MP3Downloads',
@ -130,7 +130,7 @@ export function* search(data) {
return { service: 'amazon' }; return { service: 'amazon' };
} }
export function* parseUrl(url) { export function parseUrl(url) {
const matches = parse(url).path.match(/\/(albums|tracks)[/]+([^?]+)/); const matches = parse(url).path.match(/\/(albums|tracks)[/]+([^?]+)/);
if (matches && matches[2]) { if (matches && matches[2]) {

View file

@ -45,10 +45,10 @@ function looseMatch(needle, haystack, type, various) {
} }
export function* lookupId(id, type) { export async function lookupId(id, type) {
const path = `/${type}/${id}?size=xl`; const path = `/${type}/${id}?size=xl`;
const { body } = yield request.get(apiRoot + path); const { body } = await request.get(apiRoot + path);
if (!body || body.error) { if (!body || body.error) {
const error = new Error('Not Found'); const error = new Error('Not Found');
error.status = 404; error.status = 404;
@ -94,7 +94,7 @@ export function* lookupId(id, type) {
return Promise.reject(new Error()); return Promise.reject(new Error());
} }
export function* search(data, original = {}) { export async function search(data, original = {}) {
function cleanParam(str) { function cleanParam(str) {
return str.replace(/[:?&]+/, ''); return str.replace(/[:?&]+/, '');
} }
@ -119,7 +119,7 @@ export function* search(data, original = {}) {
const path = `/search/${type}?q=${encodeURIComponent(query)}`; const path = `/search/${type}?q=${encodeURIComponent(query)}`;
const response = yield request.get(apiRoot + path); const response = await request.get(apiRoot + path);
const name = original.name || data.name; const name = original.name || data.name;
@ -129,7 +129,7 @@ export function* search(data, original = {}) {
match = looseMatch(name, response.body.data, data.type, various); match = looseMatch(name, response.body.data, data.type, various);
} }
return yield module.exports.lookupId(response.body.data[0].id, type); return await module.exports.lookupId(response.body.data[0].id, type);
} }
const matches = album.match(/^[^([]+/); const matches = album.match(/^[^([]+/);
if (matches && matches[0] && matches[0] !== album) { if (matches && matches[0] && matches[0] !== album) {
@ -139,7 +139,7 @@ export function* search(data, original = {}) {
} else if (type === 'track') { } else if (type === 'track') {
cleanedData.albumName = matches[0].trim(); cleanedData.albumName = matches[0].trim();
} }
return yield module.exports.search(cleanedData, data); return await module.exports.search(cleanedData, data);
} }
return Promise.resolve({ service: 'deezer' }); return Promise.resolve({ service: 'deezer' });
} }

View file

@ -15,16 +15,16 @@ if (!(process.env.GOOGLE_EMAIL && process.env.GOOGLE_PASSWORD) && !(process.env.
const creds = { const creds = {
androidId: process.env.GOOGLE_ANDROID_ID, androidId: process.env.GOOGLE_ANDROID_ID,
masterToken: process.env.GOOGLE_MASTER_TOKEN, masterToken: process.env.GOOGLE_MASTER_TOKEN,
} };
let ready = pm.initAsync(creds).catch(function(err) { let ready = pm.initAsync(creds).catch(function(err) {
debug(err); debug(err);
}); });
export function* lookupId(id, type) { export async function lookupId(id, type) {
yield ready; await ready;
if (type === 'album') { if (type === 'album') {
const album = yield pm.getAlbumAsync(id, false); const album = await pm.getAlbumAsync(id, false);
return { return {
service: 'google', service: 'google',
type: 'album', type: 'album',
@ -41,7 +41,7 @@ export function* lookupId(id, type) {
}, },
}; };
} else if (type === 'track') { } else if (type === 'track') {
const track = yield pm.getAllAccessTrackAsync(id); const track = await pm.getAllAccessTrackAsync(id);
return { return {
service: 'google', service: 'google',
type: 'track', type: 'track',
@ -92,8 +92,8 @@ function looseMatch(needle, haystack, type) {
}); });
} }
export function* search(data, original = {}, cleaned = false) { export async function search(data, original = {}, cleaned = false) {
yield ready; await ready;
let query; let query;
let album; let album;
const type = data.type; const type = data.type;
@ -106,7 +106,7 @@ export function* search(data, original = {}, cleaned = false) {
album = data.albumName; album = data.albumName;
} }
const result = yield pm.searchAsync(query, 5); const result = await pm.searchAsync(query, 5);
if (!result.entries) { if (!result.entries) {
if (cleaned) { if (cleaned) {
@ -121,7 +121,7 @@ export function* search(data, original = {}, cleaned = false) {
cleanedData.albumName = data.albumName.match(/^[^([]+/)[0].trim(); cleanedData.albumName = data.albumName.match(/^[^([]+/)[0].trim();
cleanedData.name = data.name.match(/^[^([]+/)[0].trim(); cleanedData.name = data.name.match(/^[^([]+/)[0].trim();
} }
return yield search(cleanedData, data, true); return await search(cleanedData, data, true);
} }
return { service: 'google' }; return { service: 'google' };
} }
@ -137,15 +137,15 @@ export function* search(data, original = {}, cleaned = false) {
return { service: 'google' }; return { service: 'google' };
} }
if (type === 'album') { if (type === 'album') {
return yield lookupId(match.album.albumId, type); return await lookupId(match.album.albumId, type);
} else if (type === 'track') { } else if (type === 'track') {
return yield lookupId(match.track.storeId, type); return await lookupId(match.track.storeId, type);
} }
return { service: 'google' }; return { service: 'google' };
} }
export function* parseUrl(url) { export async function parseUrl(url) {
yield ready; await ready;
const parsed = parse(url.replace(/\+/g, '%20')); const parsed = parse(url.replace(/\+/g, '%20'));
const path = parsed.path; const path = parsed.path;
const hash = parsed.hash; const hash = parsed.hash;
@ -163,11 +163,11 @@ export function* parseUrl(url) {
if (id.length > 0) { if (id.length > 0) {
return { id, type }; return { id, type };
} }
return yield search({ type, name: album, artist: { name: artist } }); return await search({ type, name: album, artist: { name: artist } });
} else if (path) { } else if (path) {
const matches = path.match(/\/music\/m\/([\w]+)/); const matches = path.match(/\/music\/m\/([\w]+)/);
const type = matches[1][0] === 'T' ? 'track' : 'album'; const type = matches[1][0] === 'T' ? 'track' : 'album';
return yield lookupId(matches[1], type); return await lookupId(matches[1], type);
} }
return false; return false;
} }

View file

@ -5,7 +5,7 @@ import urlMatch from './url';
const apiRoot = 'https://itunes.apple.com'; const apiRoot = 'https://itunes.apple.com';
export function* parseUrl(url) { export async function parseUrl(url) {
const parsed = parse(url); const parsed = parse(url);
const matches = parsed.path.match(/[/]?([/]?[a-z]{2}?)?[/]+album[/]+([^/]+)[/]+([^?]+)/); const matches = parsed.path.match(/[/]?([/]?[a-z]{2}?)?[/]+album[/]+([^/]+)[/]+([^?]+)/);
const query = querystring.parse(parsed.query); const query = querystring.parse(parsed.query);
@ -22,12 +22,12 @@ export function* parseUrl(url) {
} }
} }
return yield module.exports.lookupId(itunesId, type, matches[1] || 'us'); return await module.exports.lookupId(itunesId, type, matches[1] || 'us');
} }
throw new Error(); throw new Error();
} }
export function* lookupId(possibleId, type, countrycode) { export async function lookupId(possibleId, type, countrycode) {
let cc = countrycode; let cc = countrycode;
let id = possibleId; let id = possibleId;
if (String(possibleId).match(/^[a-z]{2}/)) { if (String(possibleId).match(/^[a-z]{2}/)) {
@ -39,7 +39,7 @@ export function* lookupId(possibleId, type, countrycode) {
if (cc) { if (cc) {
path = `/${cc}${path}`; path = `/${cc}${path}`;
} }
const response = yield request.get(apiRoot + path); const response = await request.get(apiRoot + path);
let result = JSON.parse(response.text); let result = JSON.parse(response.text);
if (!result.results || result.resultCount === 0 || !result.results[0].collectionId) { if (!result.results || result.resultCount === 0 || !result.results[0].collectionId) {
@ -75,7 +75,7 @@ export function* lookupId(possibleId, type, countrycode) {
} }
} }
export function* search(data) { export async function search(data) {
const markets = ['us', 'gb', 'jp', 'br', 'de', 'es']; const markets = ['us', 'gb', 'jp', 'br', 'de', 'es'];
let query; let query;
let album; let album;
@ -94,7 +94,7 @@ export function* search(data) {
for (const market of markets) { // eslint-disable-line for (const market of markets) { // eslint-disable-line
const path = `/${market}/search?term=${encodeURIComponent(query)}&media=music&entity=${entity}`; const path = `/${market}/search?term=${encodeURIComponent(query)}&media=music&entity=${entity}`;
const response = yield request.get(apiRoot + path); const response = await request.get(apiRoot + path);
let result = JSON.parse(response.text); let result = JSON.parse(response.text);
if (!result.results[0]) { if (!result.results[0]) {
@ -106,7 +106,7 @@ export function* search(data) {
} else if (type === 'track') { } else if (type === 'track') {
cleanedData.albumName = matches[0].trim(); cleanedData.albumName = matches[0].trim();
} }
return yield search(cleanedData); return await search(cleanedData);
} }
} else { } else {
result = result.results[0]; result = result.results[0];

View file

@ -37,10 +37,10 @@ function looseMatch(needle, haystack, type) {
}); });
} }
export function* lookupId(id, type) { export async function lookupId(id, type) {
const token = yield spotify.clientCredentialsGrant(); const token = await spotify.clientCredentialsGrant();
spotify.setAccessToken(token.body.access_token); spotify.setAccessToken(token.body.access_token);
let data = yield spotify[`get${type.charAt(0).toUpperCase()}${type.slice(1)}s`]([id]); let data = await spotify[`get${type.charAt(0).toUpperCase()}${type.slice(1)}s`]([id]);
data = data.body[`${type}s`][0]; data = data.body[`${type}s`][0];
@ -85,8 +85,8 @@ export function* lookupId(id, type) {
return { service: 'spotify' }; return { service: 'spotify' };
} }
export function* search(data, original = {}) { export async function search(data, original = {}) {
const token = yield spotify.clientCredentialsGrant(); const token = await spotify.clientCredentialsGrant();
spotify.setAccessToken(token.body.access_token); spotify.setAccessToken(token.body.access_token);
const markets = ['US', 'GB', 'JP', 'BR', 'DE', 'ES']; const markets = ['US', 'GB', 'JP', 'BR', 'DE', 'ES'];
@ -109,7 +109,7 @@ export function* search(data, original = {}) {
} }
for (const market of markets) { // eslint-disable-line for (const market of markets) { // eslint-disable-line
const response = yield spotify[`search${type.charAt(0).toUpperCase()}${type.slice(1)}s`](query, { market }); const response = await spotify[`search${type.charAt(0).toUpperCase()}${type.slice(1)}s`](query, { market });
const items = response.body[`${type}s`].items; const items = response.body[`${type}s`].items;
@ -122,20 +122,20 @@ export function* search(data, original = {}) {
if (match) { if (match) {
if (type === 'album') { if (type === 'album') {
return yield lookupId(match.id, type); return await lookupId(match.id, type);
} else if (type === 'track') { } else if (type === 'track') {
return yield lookupId(match.id, type); return await lookupId(match.id, type);
} }
} }
} }
return { service: 'spotify' }; return { service: 'spotify' };
} }
export function* parseUrl(url) { export async function parseUrl(url) {
const matches = parse(url).path.match(/\/(album|track)[/]+([A-Za-z0-9]+)/); const matches = parse(url).path.match(/\/(album|track)[/]+([A-Za-z0-9]+)/);
if (matches && matches[2]) { if (matches && matches[2]) {
return yield lookupId(matches[2], matches[1]); return await lookupId(matches[2], matches[1]);
} }
throw new Error(); throw new Error();
} }

View file

@ -26,10 +26,10 @@ const apiRoot = 'https://www.googleapis.com/youtube/v3';
// retryCount: 10, // retryCount: 10,
// }); // });
export function* lookupId(id) { export async function lookupId(id) {
const path = `/videos?part=snippet%2CcontentDetails&id=${id}&key=${credentials.key}`; const path = `/videos?part=snippet%2CcontentDetails&id=${id}&key=${credentials.key}`;
try { try {
const result = yield request.get(apiRoot + path); const result = await request.get(apiRoot + path);
const item = result.body.items[0].snippet; const item = result.body.items[0].snippet;
const duration = toSeconds(ptParse(result.body.items[0].contentDetails.duration)); const duration = toSeconds(ptParse(result.body.items[0].contentDetails.duration));
@ -73,7 +73,7 @@ export function* lookupId(id) {
} }
} }
export function* search(data) { export async function search(data) {
let query; let query;
const type = data.type; const type = data.type;
@ -84,7 +84,7 @@ export function* search(data) {
} }
const path = `/search?part=snippet&q=${encodeURIComponent(query)}&type=video&videoCaption=any&videoCategoryId=10&key=${credentials.key}`; const path = `/search?part=snippet&q=${encodeURIComponent(query)}&type=video&videoCaption=any&videoCategoryId=10&key=${credentials.key}`;
const result = yield request.get(apiRoot + path); const result = await request.get(apiRoot + path);
const item = result.body.items[0]; const item = result.body.items[0];
if (!item) { if (!item) {

View file

@ -20,7 +20,7 @@ export default async function (ctx) {
ctx.assert(url.host, 400, { error: { message: 'You need to submit a url.' } }); ctx.assert(url.host, 400, { error: { message: 'You need to submit a url.' } });
const music = await lookup(ctx.request.body.url); const music = await lookup(ctx.request.body.url);
debug(music);
ctx.assert(music, 400, { error: { message: 'No supported music found at that link :(' } }); ctx.assert(music, 400, { error: { message: 'No supported music found at that link :(' } });
let share = await find(music); let share = await find(music);

File diff suppressed because it is too large Load diff