1
0
mirror of https://github.com/tomahawk-player/tomahawk.git synced 2025-08-08 07:07:05 +02:00

Some style fixes in tomahawk.js

This commit is contained in:
Enno Gottschalk
2015-10-13 18:36:49 +02:00
parent ee8c687577
commit f89439a46a

View File

@@ -62,8 +62,12 @@ RSVP.on('error', function (reason) {
* (version1 > version2) == 1 * (version1 > version2) == 1
*/ */
Tomahawk.versionCompare = function (version1, version2) { Tomahawk.versionCompare = function (version1, version2) {
var v1 = version1.split('.').map(function (item) { return parseInt(item); }); var v1 = version1.split('.').map(function (item) {
var v2 = version2.split('.').map(function (item) { return parseInt(item); }); return parseInt(item);
});
var v2 = version2.split('.').map(function (item) {
return parseInt(item);
});
var length = Math.max(v1.length, v2.length); var length = Math.max(v1.length, v2.length);
var i = 0; var i = 0;
@@ -79,7 +83,7 @@ Tomahawk.versionCompare = function (version1, version2) {
return -1; return -1;
} }
} else if (typeof v2[i] == "undefined" || v2[i] === null) { } else if (typeof v2[i] == "undefined" || v2[i] === null) {
if ( v1[i] === 0 ) { if (v1[i] === 0) {
continue; continue;
} else { } else {
// v1 > v2 // v1 > v2
@@ -104,7 +108,6 @@ Tomahawk.atLeastVersion = function (version) {
return (Tomahawk.versionCompare(Tomahawk.apiVersion, version) >= 0); return (Tomahawk.versionCompare(Tomahawk.apiVersion, version) >= 0);
}; };
Tomahawk.resolver = { Tomahawk.resolver = {
scriptPath: Tomahawk.resolverData().scriptPath scriptPath: Tomahawk.resolverData().scriptPath
}; };
@@ -113,14 +116,14 @@ Tomahawk.timestamp = function () {
return Math.round(new Date() / 1000); return Math.round(new Date() / 1000);
}; };
Tomahawk.htmlDecode = (function() { Tomahawk.htmlDecode = (function () {
// this prevents any overhead from creating the object each time // this prevents any overhead from creating the object each time
var element = document.createElement('textarea'); var element = document.createElement('textarea');
function decodeHTMLEntities (str) { function decodeHTMLEntities(str) {
if(str && typeof str === 'string') { if (str && typeof str === 'string') {
str = str.replace(/</g,"&lt;"); str = str.replace(/</g, "&lt;");
str = str.replace(/>/g,"&gt;"); str = str.replace(/>/g, "&gt;");
element.innerHTML = str; element.innerHTML = str;
str = element.textContent; str = element.textContent;
element.textContent = ''; element.textContent = '';
@@ -133,10 +136,9 @@ Tomahawk.htmlDecode = (function() {
})(); })();
Tomahawk.dumpResult = function (result) { Tomahawk.dumpResult = function (result) {
var results = result.results, var results = result.results;
i = 0;
Tomahawk.log("Dumping " + results.length + " results for query " + result.qid + "..."); Tomahawk.log("Dumping " + results.length + " results for query " + result.qid + "...");
for (i = 0; i < results.length; i++) { for (var i = 0; i < results.length; i++) {
Tomahawk.log(results[i].artist + " - " + results[i].track + " | " + results[i].url); Tomahawk.log(results[i].artist + " - " + results[i].track + " | " + results[i].url);
} }
@@ -156,7 +158,6 @@ Tomahawk.extend = function (object, members) {
return newObject; return newObject;
}; };
var TomahawkResolverCapability = { var TomahawkResolverCapability = {
NullCapability: 0, NullCapability: 0,
Browsable: 1, Browsable: 1,
@@ -188,7 +189,7 @@ var TomahawkConfigTestResultType = {
* Resolver BaseObject, inherit it to implement your own resolver. * Resolver BaseObject, inherit it to implement your own resolver.
*/ */
var TomahawkResolver = { var TomahawkResolver = {
init: function() { init: function () {
}, },
scriptPath: function () { scriptPath: function () {
return Tomahawk.resolverData().scriptPath; return Tomahawk.resolverData().scriptPath;
@@ -201,7 +202,7 @@ var TomahawkResolver = {
}, },
saveUserConfig: function () { saveUserConfig: function () {
var configJson = JSON.stringify(Tomahawk.resolverData().config); var configJson = JSON.stringify(Tomahawk.resolverData().config);
window.localStorage[ this.scriptPath() ] = configJson; window.localStorage[this.scriptPath()] = configJson;
this.newConfigSaved(); this.newConfigSaved();
}, },
newConfigSaved: function () { newConfigSaved: function () {
@@ -212,7 +213,7 @@ var TomahawkResolver = {
}; };
}, },
search: function (qid, searchString) { search: function (qid, searchString) {
return this.resolve( qid, "", "", searchString ); return this.resolve(qid, "", "", searchString);
}, },
artists: function (qid) { artists: function (qid) {
return { return {
@@ -233,8 +234,8 @@ var TomahawkResolver = {
return {}; return {};
}, },
_testConfig: function (config) { _testConfig: function (config) {
return Promise.resolve(this.testConfig(config)).then(function() { return Promise.resolve(this.testConfig(config)).then(function () {
return { result: Tomahawk.ConfigTestResultType.Success }; return {result: Tomahawk.ConfigTestResultType.Success};
}); });
}, },
testConfig: function () { testConfig: function () {
@@ -267,10 +268,10 @@ Tomahawk.Resolver = {
return params; return params;
}, },
_convertUrls: function(results) { _convertUrls: function (results) {
var that = this; var that = this;
return results.map(function(r){ return results.map(function (r) {
if(r && r.url) { if (r && r.url) {
r.url = that._urlProtocol + '://' + r.url; r.url = that._urlProtocol + '://' + r.url;
} }
return r; return r;
@@ -280,15 +281,20 @@ Tomahawk.Resolver = {
_adapter_resolve: function (qid, artist, album, title) { _adapter_resolve: function (qid, artist, album, title) {
var that = this; var that = this;
var collectionPromises = []; var collectionPromises = [];
Tomahawk.collections.forEach(function(col) { Tomahawk.collections.forEach(function (col) {
if(col.resolve) if (col.resolve) {
collectionPromises.push(col.resolve({artist: artist, album: album, track:title})); collectionPromises.push(col.resolve({artist: artist, album: album, track: title}));
}
}); });
Promise.all(collectionPromises).then(function(collectionResults){ Promise.all(collectionPromises).then(function (collectionResults) {
var merged = []; var merged = [];
return merged.concat.apply(merged,collectionResults); return merged.concat.apply(merged, collectionResults);
}).then(function(collectionResults) { }).then(function (collectionResults) {
Promise.resolve(that.resolve({artist: artist, album: album, track:title})).then(function(results){ Promise.resolve(that.resolve({
artist: artist,
album: album,
track: title
})).then(function (results) {
Tomahawk.addTrackResults({ Tomahawk.addTrackResults({
'qid': qid, 'qid': qid,
'results': that._convertUrls(results.concat(collectionResults)) 'results': that._convertUrls(results.concat(collectionResults))
@@ -297,34 +303,33 @@ Tomahawk.Resolver = {
}); });
}, },
_adapter_init: function () _adapter_init: function () {
{
this._urlProtocol = this.settings.name.replace(/[^a-zA-Z]/g, '').toLowerCase(); this._urlProtocol = this.settings.name.replace(/[^a-zA-Z]/g, '').toLowerCase();
Tomahawk.addCustomUrlHandler( this._urlProtocol, 'getStreamUrl', true ); Tomahawk.addCustomUrlHandler(this._urlProtocol, 'getStreamUrl', true);
Tomahawk.log('Registered custom url handler for protocol "' + this._urlProtocol + '"'); Tomahawk.log('Registered custom url handler for protocol "' + this._urlProtocol + '"');
this.init(); this.init();
}, },
_adapter_getStreamUrl: function (params) { _adapter_getStreamUrl: function (params) {
params.url = params.url.slice(this._urlProtocol.length + 3); params.url = params.url.slice(this._urlProtocol.length + 3);
Promise.resolve(this.getStreamUrl(params)).then(function(result){ Promise.resolve(this.getStreamUrl(params)).then(function (result) {
Tomahawk.reportStreamUrl(params.qid, result.url, result.headers); Tomahawk.reportStreamUrl(params.qid, result.url, result.headers);
}); });
}, },
_adapter_search: function (qid, query) _adapter_search: function (qid, query) {
{
var that = this; var that = this;
var collectionPromises = []; var collectionPromises = [];
Tomahawk.collections.forEach(function(col) { Tomahawk.collections.forEach(function (col) {
if(col.search) if (col.search) {
collectionPromises.push(col.search({query: query})); collectionPromises.push(col.search({query: query}));
}
}); });
Promise.all(collectionPromises).then(function(collectionResults){ Promise.all(collectionPromises).then(function (collectionResults) {
var merged = []; var merged = [];
return merged.concat.apply(merged,collectionResults); return merged.concat.apply(merged, collectionResults);
}).then(function(collectionResults) { }).then(function (collectionResults) {
Promise.resolve(that.search({query:query})).then(function(results){ Promise.resolve(that.search({query: query})).then(function (results) {
Tomahawk.addTrackResults({ Tomahawk.addTrackResults({
'qid': qid, 'qid': qid,
'results': that._convertUrls(results.concat(collectionResults)) 'results': that._convertUrls(results.concat(collectionResults))
@@ -334,8 +339,8 @@ Tomahawk.Resolver = {
}, },
_adapter_testConfig: function (config) { _adapter_testConfig: function (config) {
return Promise.resolve(this.testConfig(config)).then(function() { return Promise.resolve(this.testConfig(config)).then(function () {
return { result: Tomahawk.ConfigTestResultType.Success }; return {result: Tomahawk.ConfigTestResultType.Success};
}); });
} }
}; };
@@ -469,7 +474,7 @@ Tomahawk.retrieveMetadata = function (url, mimetype, sizehint, options, callback
* *
* Internal use only! * Internal use only!
*/ */
Tomahawk.retrievedMetadata = function(metadataId, metadata, error) { Tomahawk.retrievedMetadata = function (metadataId, metadata, error) {
// Check that we have a matching callback stored. // Check that we have a matching callback stored.
if (!Tomahawk.retrieveMetadataCallbacks.hasOwnProperty(metadataId)) { if (!Tomahawk.retrieveMetadataCallbacks.hasOwnProperty(metadataId)) {
return; return;
@@ -558,7 +563,8 @@ Tomahawk.asyncRequest = function (url, callback, extraHeaders, options) {
} }
} }
xmlHttpRequest.onreadystatechange = function () { xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState == 4 && httpSuccessStatuses.indexOf(xmlHttpRequest.status) != -1) { if (xmlHttpRequest.readyState == 4
&& httpSuccessStatuses.indexOf(xmlHttpRequest.status) != -1) {
callback.call(window, xmlHttpRequest); callback.call(window, xmlHttpRequest);
} else if (xmlHttpRequest.readyState === 4) { } else if (xmlHttpRequest.readyState === 4) {
Tomahawk.log("Failed to do " + method + " request: to: " + url); Tomahawk.log("Failed to do " + method + " request: to: " + url);
@@ -585,7 +591,7 @@ var shouldDoNativeRequest = function (url, callback, extraHeaders, options) {
|| extraHeaders.hasOwnProperty("User-Agent"))); || extraHeaders.hasOwnProperty("User-Agent")));
}; };
Tomahawk.ajax = function(url, settings) { Tomahawk.ajax = function (url, settings) {
if (typeof url === "object") { if (typeof url === "object") {
settings = url; settings = url;
} else { } else {
@@ -598,10 +604,10 @@ Tomahawk.ajax = function(url, settings) {
settings.dataFormat = settings.dataFormat || 'form'; settings.dataFormat = settings.dataFormat || 'form';
if (settings.data) { if (settings.data) {
var formEncode = function(obj) { var formEncode = function (obj) {
var str = []; var str = [];
for(var p in obj) { for (var p in obj) {
if(obj[p] !== undefined) { if (obj[p] !== undefined) {
if (Array.isArray(obj[p])) { if (Array.isArray(obj[p])) {
for (var i = 0; i < obj[p].length; i++) { for (var i = 0; i < obj[p].length; i++) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i])); str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i]));
@@ -624,7 +630,8 @@ Tomahawk.ajax = function(url, settings) {
settings.data = JSON.stringify(settings.data); settings.data = JSON.stringify(settings.data);
settings.contentType = settings.contentType || 'application/json'; settings.contentType = settings.contentType || 'application/json';
} else { } else {
throw new Error("Tomahawk.ajax: unknown dataFormat requested: " + settings.dataFormat); throw new Error("Tomahawk.ajax: unknown dataFormat requested: "
+ settings.dataFormat);
} }
} else { } else {
throw new Error("Tomahawk.ajax: data should be either object or string"); throw new Error("Tomahawk.ajax: data should be either object or string");
@@ -644,7 +651,7 @@ Tomahawk.ajax = function(url, settings) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
settings.errorHandler = reject; settings.errorHandler = reject;
Tomahawk.asyncRequest(settings.url, resolve, settings.headers, settings); Tomahawk.asyncRequest(settings.url, resolve, settings.headers, settings);
}).then(function(xhr) { }).then(function (xhr) {
if (settings.rawResponse) { if (settings.rawResponse) {
return xhr; return xhr;
} }
@@ -675,7 +682,7 @@ Tomahawk.ajax = function(url, settings) {
}); });
}; };
Tomahawk.post = function(url, settings) { Tomahawk.post = function (url, settings) {
if (typeof url === "object") { if (typeof url === "object") {
settings = url; settings = url;
} else { } else {
@@ -688,7 +695,7 @@ Tomahawk.post = function(url, settings) {
return Tomahawk.ajax(settings); return Tomahawk.ajax(settings);
}; };
Tomahawk.get = function(url, settings) { Tomahawk.get = function (url, settings) {
return Tomahawk.ajax(url, settings); return Tomahawk.ajax(url, settings);
}; };
@@ -696,10 +703,10 @@ Tomahawk.assert = function (assertion, message) {
Tomahawk.nativeAssert(assertion, message); Tomahawk.nativeAssert(assertion, message);
}; };
Tomahawk.sha256 = Tomahawk.sha256 || function(message) { Tomahawk.sha256 = Tomahawk.sha256 || function (message) {
return CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex); return CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex);
}; };
Tomahawk.md5 = Tomahawk.md5 || function(message) { Tomahawk.md5 = Tomahawk.md5 || function (message) {
return CryptoJS.MD5(message).toString(CryptoJS.enc.Hex); return CryptoJS.MD5(message).toString(CryptoJS.enc.Hex);
}; };
// Return a HMAC (md5) signature of the input text with the desired key // Return a HMAC (md5) signature of the input text with the desired key
@@ -823,19 +830,19 @@ Tomahawk.hmac = function (key, message) {
})(); })();
Tomahawk.removeDiacritics = function (str) { Tomahawk.removeDiacritics = function (str) {
return str.replace(/[^\u0000-\u007E]/g, function(c) { return str.replace(/[^\u0000-\u007E]/g, function (c) {
return Tomahawk.diacriticsMap[c] || c; return Tomahawk.diacriticsMap[c] || c;
}); });
}; };
Tomahawk.localStorage = Tomahawk.localStorage || { Tomahawk.localStorage = Tomahawk.localStorage || {
setItem: function(key, value) { setItem: function (key, value) {
window.localStorage[key] = value; window.localStorage[key] = value;
}, },
getItem: function(key) { getItem: function (key) {
return window.localStorage[key]; return window.localStorage[key];
}, },
removeItem: function(key) { removeItem: function (key) {
delete window.localStorage[key]; delete window.localStorage[key];
} }
}; };
@@ -843,14 +850,18 @@ Tomahawk.localStorage = Tomahawk.localStorage || {
// some aliases // some aliases
Tomahawk.setTimeout = Tomahawk.setTimeout || window.setTimeout; Tomahawk.setTimeout = Tomahawk.setTimeout || window.setTimeout;
Tomahawk.setInterval = Tomahawk.setInterval || window.setInterval; Tomahawk.setInterval = Tomahawk.setInterval || window.setInterval;
Tomahawk.base64Decode = function(a) { return window.atob(a); }; Tomahawk.base64Decode = function (a) {
Tomahawk.base64Encode = function(b) { return window.btoa(b); }; return window.atob(a);
};
Tomahawk.base64Encode = function (b) {
return window.btoa(b);
};
Tomahawk.PluginManager = { Tomahawk.PluginManager = {
objects: {}, objects: {},
objectCounter: 0, objectCounter: 0,
identifyObject: function (object) { identifyObject: function (object) {
if( !object.hasOwnProperty('id') ) { if (!object.hasOwnProperty('id')) {
object.id = this.objectCounter++; object.id = this.objectCounter++;
} }
@@ -858,8 +869,7 @@ Tomahawk.PluginManager = {
}, },
registerPlugin: function (type, object) { registerPlugin: function (type, object) {
this.objects[this.identifyObject(object)] = object; this.objects[this.identifyObject(object)] = object;
if (type === 'collection') if (type === 'collection') {
{
Tomahawk.collections.push(object); Tomahawk.collections.push(object);
} }
@@ -867,7 +877,7 @@ Tomahawk.PluginManager = {
Tomahawk.registerScriptPlugin(type, object.id); Tomahawk.registerScriptPlugin(type, object.id);
}, },
unregisterPlugin: function(type, object) { unregisterPlugin: function (type, object) {
this.objects[this.identifyObject(object)] = object; this.objects[this.identifyObject(object)] = object;
Tomahawk.log("unregisterPlugin: " + type + " id: " + object.id); Tomahawk.log("unregisterPlugin: " + type + " id: " + object.id);
@@ -879,7 +889,7 @@ Tomahawk.PluginManager = {
if (!Tomahawk.resolver.instance.apiVersion || Tomahawk.resolver.instance.apiVersion < 0.9) { if (!Tomahawk.resolver.instance.apiVersion || Tomahawk.resolver.instance.apiVersion < 0.9) {
if (methodName === 'artistAlbums') { if (methodName === 'artistAlbums') {
methodName = 'albums'; methodName = 'albums';
} else if ( methodName === 'albumTracks' ) { } else if (methodName === 'albumTracks') {
methodName = 'tracks'; methodName = 'tracks';
} }
} }
@@ -894,7 +904,8 @@ Tomahawk.PluginManager = {
} }
if (typeof this.objects[objectId][methodName] === 'function') { if (typeof this.objects[objectId][methodName] === 'function') {
if (!Tomahawk.resolver.instance.apiVersion || Tomahawk.resolver.instance.apiVersion < 0.9) { if (!Tomahawk.resolver.instance.apiVersion
|| Tomahawk.resolver.instance.apiVersion < 0.9) {
if (methodName == 'artists') { if (methodName == 'artists') {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve; pluginManager.resolve[requestId] = resolve;
@@ -940,18 +951,19 @@ Tomahawk.PluginManager = {
return this.objects[objectId][methodName]; return this.objects[objectId][methodName];
}, },
invoke: function (requestId, objectId, methodName, params ) { invoke: function (requestId, objectId, methodName, params) {
Promise.resolve(this.invokeSync(requestId, objectId, methodName, params)).then(function (result) { Promise.resolve(this.invokeSync(requestId, objectId, methodName, params))
Tomahawk.reportScriptJobResults({ .then(function (result) {
requestId: requestId, Tomahawk.reportScriptJobResults({
data: result requestId: requestId,
data: result
});
}, function (error) {
Tomahawk.reportScriptJobResults({
requestId: requestId,
error: error
});
}); });
}, function (error) {
Tomahawk.reportScriptJobResults({
requestId: requestId,
error: error
});
});
} }
}; };
@@ -1257,8 +1269,6 @@ Tomahawk.Collection = {
Transaction: function (collection, id) { Transaction: function (collection, id) {
this.ensureDb = function () { this.ensureDb = function () {
var that = this;
return new RSVP.Promise(function (resolve, reject) { return new RSVP.Promise(function (resolve, reject) {
if (!collection.cachedDbs.hasOwnProperty(id)) { if (!collection.cachedDbs.hasOwnProperty(id)) {
Tomahawk.log("Opening database"); Tomahawk.log("Opening database");
@@ -1332,14 +1342,14 @@ Tomahawk.Collection = {
var that = this; var that = this;
that.stmtsToResolve = that.statements.length; that.stmtsToResolve = that.statements.length;
that.results = that.statements.slice(); that.results = that.statements.slice();
Tomahawk.log('Executing ' + that.stmtsToResolve + ' deffered SQL statements in transaction'); Tomahawk.log('Executing ' + that.stmtsToResolve
+ ' deferred SQL statements in transaction');
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
if (that.statements.length == 0) if (that.statements.length == 0) {
resolve([]); resolve([]);
else{ } else {
that.db.transaction(function (tx) { that.db.transaction(function (tx) {
for (var i = 0; i < that.statements.length; ++i) for (var i = 0; i < that.statements.length; ++i) {
{
var stmt = that.statements[i]; var stmt = that.statements[i];
tx.executeSql(stmt.statement, stmt.args, tx.executeSql(stmt.statement, stmt.args,
(function () { (function () {
@@ -1347,8 +1357,7 @@ Tomahawk.Collection = {
//capture value of i //capture value of i
var originalI = i; var originalI = i;
return function (tx, results) { return function (tx, results) {
if (typeof that.statements[originalI].map !== 'undefined') if (typeof that.statements[originalI].map !== 'undefined') {
{
var map = that.statements[originalI].map; var map = that.statements[originalI].map;
that.results[originalI] = []; that.results[originalI] = [];
for (var ii = 0; ii < results.rows.length; ii++) { for (var ii = 0; ii < results.rows.length; ii++) {
@@ -1357,11 +1366,11 @@ Tomahawk.Collection = {
)); ));
} }
} }
else else {
that.results[originalI] = results; that.results[originalI] = results;
}
that.stmtsToResolve--; that.stmtsToResolve--;
if(that.stmtsToResolve == 0) if (that.stmtsToResolve == 0) {
{
that.statements = []; that.statements = [];
resolve(that.results); resolve(that.results);
} }
@@ -1377,11 +1386,11 @@ Tomahawk.Collection = {
}); });
} }
}); });
}, };
this.sql = function (sqlStatement, sqlArgs, mapFunction) { this.sql = function (sqlStatement, sqlArgs, mapFunction) {
this.statements.push({statement: sqlStatement, args: sqlArgs, map: mapFunction}); this.statements.push({statement: sqlStatement, args: sqlArgs, map: mapFunction});
}; };
this.sqlSelect = function (table, mapResults, fields, where, join) { this.sqlSelect = function (table, mapResults, fields, where, join) {
var whereKeys = []; var whereKeys = [];
@@ -1435,6 +1444,7 @@ Tomahawk.Collection = {
}; };
}, },
addTracks: function (params) { addTracks: function (params) {
var that = this; var that = this;
var id = params.id; var id = params.id;
@@ -1474,14 +1484,14 @@ Tomahawk.Collection = {
return t.execDefferedStatements(); return t.execDefferedStatements();
}).then(function () { }).then(function () {
// Get all artists' and albumArtists' db ids // Get all artists' and albumArtists' db ids
t.sqlSelect("albumArtists", function(r) { t.sqlSelect("albumArtists", function (r) {
return { return {
albumArtist: r.albumArtist, albumArtist: r.albumArtist,
albumArtistDisambiguation: r.albumArtistDisambiguation, albumArtistDisambiguation: r.albumArtistDisambiguation,
_id: r._id _id: r._id
}; };
}); });
t.sqlSelect("artists", function(r) { t.sqlSelect("artists", function (r) {
return { return {
artist: r.artist, artist: r.artist,
artistDisambiguation: r.artistDisambiguation, artistDisambiguation: r.artistDisambiguation,
@@ -1524,7 +1534,6 @@ Tomahawk.Collection = {
} }
}).then(function () { }).then(function () {
// Insert all albums // Insert all albums
var promises = [];
for (var i = 0; i < tracks.length; i++) { for (var i = 0; i < tracks.length; i++) {
(function (track) { (function (track) {
var albumArtistId = cachedAlbumArtists[track.album].albumArtistId; var albumArtistId = cachedAlbumArtists[track.album].albumArtistId;
@@ -1537,7 +1546,7 @@ Tomahawk.Collection = {
return t.execDefferedStatements(); return t.execDefferedStatements();
}).then(function () { }).then(function () {
// Get the albums' db ids // Get the albums' db ids
t.sqlSelect("albums", function(r) { t.sqlSelect("albums", function (r) {
return { return {
album: r.album, album: r.album,
albumArtistId: r.albumArtistId, albumArtistId: r.albumArtistId,
@@ -1558,7 +1567,6 @@ Tomahawk.Collection = {
} }
}).then(function () { }).then(function () {
// Now we are ready to insert the tracks // Now we are ready to insert the tracks
var promises = [];
for (var i = 0; i < tracks.length; i++) { for (var i = 0; i < tracks.length; i++) {
(function (track) { (function (track) {
// Get all relevant ids that we stored in the previous steps // Get all relevant ids that we stored in the previous steps
@@ -1588,7 +1596,7 @@ Tomahawk.Collection = {
}).then(function () { }).then(function () {
var resultMap = function (r) { var resultMap = function (r) {
return { return {
_id : r._id, _id: r._id,
artistId: r.artistId, artistId: r.artistId,
albumId: r.albumId, albumId: r.albumId,
track: r.track track: r.track
@@ -1646,13 +1654,13 @@ Tomahawk.Collection = {
}); });
}, },
_fuzzyIndexIdsToTracks: function(resultIds, id) { _fuzzyIndexIdsToTracks: function (resultIds, id) {
var that = this; if (typeof id === 'undefined') {
if(typeof id === 'undefined')
id = this.settings.id; id = this.settings.id;
}
var t = new Tomahawk.Collection.Transaction(this, id); var t = new Tomahawk.Collection.Transaction(this, id);
return t.beginTransaction().then(function () { return t.beginTransaction().then(function () {
var mapFn = function(row) { var mapFn = function (row) {
return { return {
artist: row.artist, artist: row.artist,
artistDisambiguation: row.artistDisambiguation, artistDisambiguation: row.artistDisambiguation,
@@ -1668,8 +1676,8 @@ Tomahawk.Collection = {
}; };
for (var idx = 0; resultIds && idx < resultIds.length; idx++) { for (var idx = 0; resultIds && idx < resultIds.length; idx++) {
var trackid = resultIds[idx][0]; var trackid = resultIds[idx][0];
var where = { _id : trackid }; var where = {_id: trackid};
t.sqlSelect("tracks",mapFn, t.sqlSelect("tracks", mapFn,
[], [],
where, [ where, [
{ {
@@ -1690,25 +1698,19 @@ Tomahawk.Collection = {
}).then(function (results) { }).then(function (results) {
var merged = []; var merged = [];
return merged.concat.apply(merged, return merged.concat.apply(merged,
results.map(function(e){ results.map(function (e) {
//every result has one track //every result has one track
return e[0]; return e[0];
})); }));
}); });
}, },
resolve: function(params) { resolve: function (params) {
var id = params.id;
if(typeof id === 'undefined')
id = this.settings.id;
var resultIds = Tomahawk.resolveFromFuzzyIndex(params.artist, params.album, params.track); var resultIds = Tomahawk.resolveFromFuzzyIndex(params.artist, params.album, params.track);
return this._fuzzyIndexIdsToTracks(resultIds); return this._fuzzyIndexIdsToTracks(resultIds);
}, },
search: function(params) { search: function (params) {
var id = params.id;
if(typeof id === 'undefined')
id = this.settings.id;
var resultIds = Tomahawk.searchFuzzyIndex(params.query); var resultIds = Tomahawk.searchFuzzyIndex(params.query);
return this._fuzzyIndexIdsToTracks(resultIds); return this._fuzzyIndexIdsToTracks(resultIds);
}, },
@@ -1716,12 +1718,13 @@ Tomahawk.Collection = {
tracks: function (params, where) { tracks: function (params, where) {
//TODO filter/where support //TODO filter/where support
var id = params.id; var id = params.id;
if(typeof id === 'undefined') if (typeof id === 'undefined') {
id = this.settings.id; id = this.settings.id;
}
var t = new Tomahawk.Collection.Transaction(this, id); var t = new Tomahawk.Collection.Transaction(this, id);
return t.beginTransaction().then(function () { return t.beginTransaction().then(function () {
var mapFn = function(row) { var mapFn = function (row) {
return { return {
artist: row.artist, artist: row.artist,
artistDisambiguation: row.artistDisambiguation, artistDisambiguation: row.artistDisambiguation,
@@ -1735,7 +1738,7 @@ Tomahawk.Collection = {
albumpos: row.albumPos albumpos: row.albumPos
}; };
}; };
t.sqlSelect("tracks",mapFn, t.sqlSelect("tracks", mapFn,
[], [],
where, [ where, [
{ {
@@ -1760,19 +1763,20 @@ Tomahawk.Collection = {
albums: function (params, where) { albums: function (params, where) {
//TODO filter/where support //TODO filter/where support
var id = params.id; var id = params.id;
if(typeof id === 'undefined') if (typeof id === 'undefined') {
id = this.settings.id; id = this.settings.id;
}
var t = new Tomahawk.Collection.Transaction(this, id); var t = new Tomahawk.Collection.Transaction(this, id);
return t.beginTransaction().then(function () { return t.beginTransaction().then(function () {
var mapFn = function(row) { var mapFn = function (row) {
return { return {
albumArtist: row.artist, albumArtist: row.artist,
albumArtistDisambiguation: row.artistDisambiguation, albumArtistDisambiguation: row.artistDisambiguation,
album: row.album album: row.album
}; };
}; };
t.sqlSelect("albums",mapFn, t.sqlSelect("albums", mapFn,
["album", "artist", "artistDisambiguation"], ["album", "artist", "artistDisambiguation"],
where, [ where, [
{ {
@@ -1785,12 +1789,16 @@ Tomahawk.Collection = {
); );
return t.execDefferedStatements(); return t.execDefferedStatements();
}).then(function (results) { }).then(function (results) {
results = results[0].filter(function(e){ results = results[0].filter(function (e) {
return (e.albumArtist != '' && e.album != ''); return (e.albumArtist != '' && e.album != '');
}); });
return { return {
artists: results.map(function(i){ return i.albumArtist;}), artists: results.map(function (i) {
albums: results.map(function(i){ return i.album;}) return i.albumArtist;
}),
albums: results.map(function (i) {
return i.album;
})
}; };
}); });
}, },
@@ -1798,13 +1806,13 @@ Tomahawk.Collection = {
artists: function (params) { artists: function (params) {
//TODO filter/where support //TODO filter/where support
var id = params.id; var id = params.id;
if(typeof id === 'undefined') if (typeof id === 'undefined') {
id = this.settings.id; id = this.settings.id;
}
var t = new Tomahawk.Collection.Transaction(this, id); var t = new Tomahawk.Collection.Transaction(this, id);
return t.beginTransaction().then(function () { return t.beginTransaction().then(function () {
var mapFn = function(r) var mapFn = function (r) {
{
return r.artist; return r.artist;
}; };
t.sqlSelect("artists", mapFn, ["artist", "artistDisambiguation"]); t.sqlSelect("artists", mapFn, ["artist", "artistDisambiguation"]);
@@ -1836,26 +1844,29 @@ Tomahawk.Collection = {
artistAlbums: function (params) { artistAlbums: function (params) {
//TODO filter/where support //TODO filter/where support
var id = params.id; var id = params.id;
if(typeof id === 'undefined') if (typeof id === 'undefined') {
id = this.settings.id; id = this.settings.id;
}
var artist = params.artist; var artist = params.artist;
//var artistDisambiguation = params.artistDisambiguation; //var artistDisambiguation = params.artistDisambiguation;
var that = this;
var t = new Tomahawk.Collection.Transaction(this, id); var t = new Tomahawk.Collection.Transaction(this, id);
return t.beginTransaction().then(function () { return t.beginTransaction().then(function () {
t.sqlSelect("artists",function(r){return r._id;}, ["_id"], { t.sqlSelect("artists", function (r) {
return r._id;
}, ["_id"], {
artist: artist artist: artist
//artistDisambiguation: artistDisambiguation //artistDisambiguation: artistDisambiguation
}); });
return t.execDefferedStatements(); return t.execDefferedStatements();
}).then(function (results) { }).then(function (results) {
var artistId = results[0][0]; var artistId = results[0][0];
t.sqlSelect("artistAlbums",function(r){return r.album;}, ["albumId", 'album'], { t.sqlSelect("artistAlbums", function (r) {
return r.album;
}, ["albumId", 'album'], {
artistId: artistId artistId: artistId
},[ }, [
{ {
table: "albums", table: "albums",
conditions: { conditions: {
@@ -1875,8 +1886,9 @@ Tomahawk.Collection = {
albumTracks: function (params) { albumTracks: function (params) {
//TODO filter/where support //TODO filter/where support
var id = params.id; var id = params.id;
if(typeof id === 'undefined') if (typeof id === 'undefined') {
id = this.settings.id; id = this.settings.id;
}
var albumArtist = params.artist; var albumArtist = params.artist;
//var albumArtistDisambiguation = params.albumArtistDisambiguation; //var albumArtistDisambiguation = params.albumArtistDisambiguation;
var album = params.album; var album = params.album;
@@ -1885,14 +1897,18 @@ Tomahawk.Collection = {
var t = new Tomahawk.Collection.Transaction(this, id); var t = new Tomahawk.Collection.Transaction(this, id);
return t.beginTransaction().then(function () { return t.beginTransaction().then(function () {
t.sqlSelect("artists", function(r){return r._id;},["_id"], { t.sqlSelect("artists", function (r) {
artist: albumArtist, return r._id;
}, ["_id"], {
artist: albumArtist
//artistDisambiguation: albumArtistDisambiguation //artistDisambiguation: albumArtistDisambiguation
}); });
return t.execDefferedStatements(); return t.execDefferedStatements();
}).then(function (results) { }).then(function (results) {
var albumArtistId = results[0][0]; var albumArtistId = results[0][0];
t.sqlSelect("albums",function(r){return r._id;}, ["_id"], { t.sqlSelect("albums", function (r) {
return r._id;
}, ["_id"], {
album: album, album: album,
albumArtistId: albumArtistId albumArtistId: albumArtistId
}); });
@@ -1907,15 +1923,16 @@ Tomahawk.Collection = {
collection: function () { collection: function () {
this.settings.trackcount = this._trackCount; this.settings.trackcount = this._trackCount;
if(! this.settings.description) if (!this.settings.description) {
this.settings.description = this.settings.prettyname; this.settings.description = this.settings.prettyname;
}
this.settings.capabilities = [Tomahawk.Collection.BrowseCapability.Artists, this.settings.capabilities = [Tomahawk.Collection.BrowseCapability.Artists,
Tomahawk.Collection.BrowseCapability.Albums, Tomahawk.Collection.BrowseCapability.Tracks]; Tomahawk.Collection.BrowseCapability.Albums,
Tomahawk.Collection.BrowseCapability.Tracks];
return this.settings; return this.settings;
} }
}; };
// Legacy compability for 0.8 and before // Legacy compability for 0.8 and before
Tomahawk.reportCapabilities = function (capabilities) { Tomahawk.reportCapabilities = function (capabilities) {
if (capabilities & TomahawkResolverCapability.Browsable) { if (capabilities & TomahawkResolverCapability.Browsable) {
@@ -1925,7 +1942,8 @@ Tomahawk.reportCapabilities = function (capabilities) {
Tomahawk.nativeReportCapabilities(capabilities); Tomahawk.nativeReportCapabilities(capabilities);
}; };
Tomahawk.addArtistResults = Tomahawk.addAlbumResults = Tomahawk.addAlbumTrackResults = function (result) { Tomahawk.addArtistResults = Tomahawk.addAlbumResults = Tomahawk.addAlbumTrackResults
= function (result) {
Tomahawk.PluginManager.resolve[result.qid](result); Tomahawk.PluginManager.resolve[result.qid](result);
delete Tomahawk.PluginManager.resolve[result.qid]; delete Tomahawk.PluginManager.resolve[result.qid];
}; };
@@ -1943,7 +1961,7 @@ Tomahawk.reportStreamUrl = function (qid, streamUrl, headers) {
delete Tomahawk.PluginManager.resolve[qid]; delete Tomahawk.PluginManager.resolve[qid];
}; };
Tomahawk.addUrlResult = function(url, result) { Tomahawk.addUrlResult = function (url, result) {
/* Merge the whole mess into one consistent result which is independent of type /* Merge the whole mess into one consistent result which is independent of type
var cleanResult = { var cleanResult = {
type: result.type, type: result.type,