Fix google search

This commit is contained in:
Jonathan Cremin 2014-12-05 14:32:03 +00:00
parent 8802ffe959
commit d675ac4e9f

View file

@ -11,8 +11,11 @@ if (!process.env.GOOGLE_EMAIL || !process.env.GOOGLE_PASSWORD) {
return;
}
// It's probably ok to not wait for this to finish
pm.init({email: process.env.GOOGLE_EMAIL, password: process.env.GOOGLE_PASSWORD}, function() {});
var ready = Q.defer();
pm.init({email: process.env.GOOGLE_EMAIL, password: process.env.GOOGLE_PASSWORD}, function() {
ready.resolve();
});
module.exports.match = function(url, type) {
var parsed = parse(url);
@ -21,6 +24,7 @@ module.exports.match = function(url, type) {
module.exports.lookupId = function(id, type, next) {
var deferred = Q.defer();
ready.promise.then(function() {
if (type == "album") {
pm.getAlbum(id, true, function(album) {
deferred.resolve({
@ -55,12 +59,14 @@ module.exports.lookupId = function(id, type, next) {
});
});
}
});
return deferred.promise;
}
module.exports.search = function(data) {
var deferred = Q.defer();
var query = "";
ready.promise.then(function() {
var query, album;
var type = data.type;
if (type == "album") {
@ -73,16 +79,6 @@ module.exports.search = function(data) {
pm.search(query, 5, function(data) {
if (!data.entries) {
deferred.resolve({service: "googleplaymusic"});
return;
}
var result = data.entries.filter(function(result) {
return result[type];
}).sort(function(a, b) { // sort by match score
return a.score < b.score;
}).shift();
if (!result) {
var matches = album.match(/^[^\(\[]+/);
if (matches[0]) {
var cleanedData = JSON.parse(JSON.stringify(data));
@ -95,6 +91,16 @@ module.exports.search = function(data) {
} else {
deferred.resolve({service: "googleplaymusic"});
}
return;
}
var result = data.entries.filter(function(result) {
return result[type];
}).sort(function(a, b) { // sort by match score
return a.score < b.score;
}).shift();
if (!result) {
deferred.resolve({service: "googleplaymusic"});
} else {
var id;
if (type == "album") {
@ -106,11 +112,13 @@ module.exports.search = function(data) {
module.exports.lookupId(id, type).then(deferred.resolve);
}
});
});
return deferred.promise;
}
module.exports.parseUrl = function(url, next) {
var deferred = Q.defer();
ready.promise.then(function() {
var parsed = parse(url.replace(/\+/g, "%20"));
var path = parsed.path;
var hash = parsed.hash;
@ -131,5 +139,6 @@ module.exports.parseUrl = function(url, next) {
var type = matches[1][0] == "T" ? "track" : "album";
module.exports.lookupId(matches[1], type).then(deferred.resolve);
}
});
return deferred.promise;
}