1
0
mirror of https://github.com/tomahawk-player/tomahawk.git synced 2025-08-19 20:34:22 +02:00

Merge pull request #333 from mrmaffen/master

Merge tomahawk.js from tomahawk-android + some fixes
This commit is contained in:
Dominik Schmidt
2015-10-14 10:09:26 +02:00

View File

@@ -42,17 +42,18 @@ Tomahawk.apiVersion = "0.2.2";
//Statuses considered a success for HTTP request //Statuses considered a success for HTTP request
var httpSuccessStatuses = [200, 201]; var httpSuccessStatuses = [200, 201];
// install RSVP.Promise as global Promise // install RSVP error handler for uncaught(!) errors
if(window.Promise === undefined) { RSVP.on('error', function (reason) {
window.Promise = window.RSVP.Promise; var resolverName = "";
window.RSVP.on('error', function(reason) { if (Tomahawk.resolver.instance) {
resolverName = Tomahawk.resolver.instance.settings.name + " - ";
}
if (reason) { if (reason) {
console.error(reason.message, reason); console.error(resolverName + 'Uncaught error:' + JSON.stringify(reason));
} else { } else {
console.error('Error: error thrown from RSVP but it was empty'); console.error(resolverName + 'Uncaught error: error thrown from RSVP but it was empty');
} }
}); });
}
/** /**
* Compares versions strings * Compares versions strings
@@ -61,8 +62,12 @@ if(window.Promise === undefined) {
* (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;
@@ -103,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
}; };
@@ -132,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);
} }
@@ -155,7 +158,7 @@ Tomahawk.extend = function (object, members) {
return newObject; return newObject;
}; };
//Deprecated for 0.9 resolvers. Reporting resolver capabilities is no longer necessary.
var TomahawkResolverCapability = { var TomahawkResolverCapability = {
NullCapability: 0, NullCapability: 0,
Browsable: 1, Browsable: 1,
@@ -164,6 +167,7 @@ var TomahawkResolverCapability = {
UrlLookup: 8 UrlLookup: 8
}; };
//Deprecated for 0.9 resolvers. Use Tomahawk.UrlType instead.
var TomahawkUrlType = { var TomahawkUrlType = {
Any: 0, Any: 0,
Playlist: 1, Playlist: 1,
@@ -172,6 +176,7 @@ var TomahawkUrlType = {
Artist: 8 Artist: 8
}; };
//Deprecated for 0.9 resolvers. Use Tomahawk.ConfigTestResultType instead.
var TomahawkConfigTestResultType = { var TomahawkConfigTestResultType = {
Other: 0, Other: 0,
Success: 1, Success: 1,
@@ -231,24 +236,40 @@ var TomahawkResolver = {
collection: function () { collection: function () {
return {}; return {};
}, },
getStreamUrl: function(params) {
Tomahawk.reportStreamUrl(params.qid, params.url);
},
_testConfig: function (config) { _testConfig: function (config) {
return Promise.resolve(this.testConfig(config)).then(function() { return RSVP.Promise.resolve(this.testConfig(config)).then(function () {
return {result: Tomahawk.ConfigTestResultType.Success}; return {result: Tomahawk.ConfigTestResultType.Success};
}); });
}, },
testConfig: function () { testConfig: function () {
this.configTest();
},
getStreamUrl: function (qid, url) {
Tomahawk.reportStreamUrl(qid, url);
} }
}; };
Tomahawk.Resolver = {
Tomahawk.Resolver = Tomahawk.extend(TomahawkResolver, { init: function () {
},
scriptPath: function () {
return Tomahawk.resolverData().scriptPath;
},
getConfigUi: function () {
return {};
},
getUserConfig: function () {
return JSON.parse(window.localStorage[this.scriptPath()] || "{}");
},
saveUserConfig: function () { saveUserConfig: function () {
window.localStorage[this.scriptPath()] = JSON.stringify(Tomahawk.resolverData().config); window.localStorage[this.scriptPath()] = JSON.stringify(Tomahawk.resolverData().config);
this.newConfigSaved(Tomahawk.resolverData().config); this.newConfigSaved(Tomahawk.resolverData().config);
}, },
newConfigSaved: function () {
},
getStreamUrl: function (params) {
return params;
},
_convertUrls: function (results) { _convertUrls: function (results) {
var that = this; var that = this;
@@ -264,14 +285,19 @@ Tomahawk.Resolver = Tomahawk.extend(TomahawkResolver, {
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){ RSVP.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){ RSVP.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))
@@ -280,8 +306,7 @@ Tomahawk.Resolver = Tomahawk.extend(TomahawkResolver, {
}); });
}, },
_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 + '"');
@@ -290,24 +315,24 @@ Tomahawk.Resolver = Tomahawk.extend(TomahawkResolver, {
_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){ RSVP.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){ RSVP.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){ RSVP.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))
@@ -317,56 +342,11 @@ Tomahawk.Resolver = Tomahawk.extend(TomahawkResolver, {
}, },
_adapter_testConfig: function (config) { _adapter_testConfig: function (config) {
return Promise.resolve(this.testConfig(config)).then(function() { return RSVP.Promise.resolve(this.testConfig(config)).then(function () {
return {result: Tomahawk.ConfigTestResultType.Success}; return {result: Tomahawk.ConfigTestResultType.Success};
}); });
} }
});
/**** begin example implementation of a resolver ****/
// implement the resolver
/*
* var DemoResolver = Tomahawk.extend(TomahawkResolver,
* {
* getSettings: function()
* {
* return {
* name: "Demo Resolver",
* weigth: 95,
* timeout: 5,
* limit: 10
}; };
},
resolve: function( qid, artist, album, track )
{
return {
qid: qid,
results: [
{
artist: "Mokele",
album: "You Yourself are Me Myself and I am in Love",
track: "Hiding In Your Insides (php)",
source: "Mokele.co.uk",
url: "http://play.mokele.co.uk/music/Hiding%20In%20Your%20Insides.mp3",
bitrate: 160,
duration: 248,
size: 4971780,
score: 1.0,
extension: "mp3",
mimetype: "audio/mpeg"
}
]
};
}
}
);
// register the resolver
Tomahawk.resolver.instance = DemoResolver;*/
/**** end example implementation of a resolver ****/
// help functions // help functions
@@ -478,7 +458,7 @@ Tomahawk.asyncRequestIdCounter = 0;
Tomahawk.asyncRequestCallbacks = {}; Tomahawk.asyncRequestCallbacks = {};
/** /**
* Pass the natively retrived reply back to the javascript callback * Pass the natively retrieved reply back to the javascript callback
* and augment the fake XMLHttpRequest object. * and augment the fake XMLHttpRequest object.
* *
* Internal use only! * Internal use only!
@@ -541,7 +521,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,9 +566,15 @@ Tomahawk.ajax = function(url, settings) {
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])) {
for (var i = 0; i < obj[p].length; i++) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i]));
}
} else {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
} }
} }
}
str.sort(); str.sort();
@@ -601,7 +588,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");
@@ -618,7 +606,7 @@ Tomahawk.ajax = function(url, settings) {
} }
} }
return new Promise(function (resolve, reject) { return new RSVP.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) {
@@ -629,7 +617,7 @@ Tomahawk.ajax = function(url, settings) {
var contentType; var contentType;
if (settings.dataType === 'json') { if (settings.dataType === 'json') {
contentType = 'application/json'; contentType = 'application/json';
} else if (contentType === 'xml') { } else if (settings.dataType === 'xml') {
contentType = 'text/xml'; contentType = 'text/xml';
} else if (typeof xhr.getResponseHeader !== 'undefined') { } else if (typeof xhr.getResponseHeader !== 'undefined') {
contentType = xhr.getResponseHeader('Content-Type'); contentType = xhr.getResponseHeader('Content-Type');
@@ -820,8 +808,12 @@ 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: {},
@@ -835,8 +827,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);
} }
@@ -871,22 +862,44 @@ 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 RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve; pluginManager.resolve[requestId] = resolve;
Tomahawk.resolver.instance.artists(requestId); Tomahawk.resolver.instance.artists(requestId);
}); });
} else if (methodName == 'albums') { } else if (methodName == 'albums') {
return new Promise(function (resolve, reject) { return new RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve; pluginManager.resolve[requestId] = resolve;
Tomahawk.resolver.instance.albums(requestId, params.artist); Tomahawk.resolver.instance.albums(requestId, params.artist);
}); });
} else if (methodName == 'tracks') { } else if (methodName == 'tracks') {
return new Promise(function (resolve, reject) { return new RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve; pluginManager.resolve[requestId] = resolve;
Tomahawk.resolver.instance.tracks(requestId, params.artist, params.album); Tomahawk.resolver.instance.tracks(requestId, params.artist, params.album);
}); });
} else if (methodName == 'lookupUrl') {
return new RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[params.url] = resolve;
Tomahawk.resolver.instance.lookupUrl(params.url);
});
} else if (methodName == 'getStreamUrl') {
return new RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve;
Tomahawk.resolver.instance.getStreamUrl(requestId, params.url);
});
} else if (methodName == 'resolve') {
return new RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve;
Tomahawk.resolver.instance.resolve(requestId, params.artist,
params.album, params.track);
});
} else if (methodName == 'search') {
return new RSVP.Promise(function (resolve, reject) {
pluginManager.resolve[requestId] = resolve;
Tomahawk.resolver.instance.search(requestId, params.query);
});
} }
} }
@@ -897,18 +910,12 @@ Tomahawk.PluginManager = {
}, },
invoke: function (requestId, objectId, methodName, params) { invoke: function (requestId, objectId, methodName, params) {
Promise.resolve(this.invokeSync(requestId, objectId, methodName, params)).then(function (result) { RSVP.Promise.resolve(this.invokeSync(requestId, objectId, methodName, params))
if (typeof result === 'object') { .then(function (result) {
Tomahawk.reportScriptJobResults({ Tomahawk.reportScriptJobResults({
requestId: requestId, requestId: requestId,
data: result data: result
}); });
} else {
Tomahawk.reportScriptJobResults({
requestId: requestId,
error: "Scripts need to return objects for requests: methodName: " + methodName + " params: " + JSON.stringify(params)
});
}
}, function (error) { }, function (error) {
Tomahawk.reportScriptJobResults({ Tomahawk.reportScriptJobResults({
requestId: requestId, requestId: requestId,
@@ -918,6 +925,32 @@ Tomahawk.PluginManager = {
} }
}; };
Tomahawk.NativeScriptJobManager = {
idCounter: 0,
deferreds: {},
invoke: function (methodName, params) {
var requestId = this.idCounter++;
Tomahawk.invokeNativeScriptJob(requestId, methodName, JSON.stringify(params));
this.deferreds[requestId] = RSVP.defer();
return this.deferreds[requestId].promise;
},
reportNativeScriptJobResult: function (requestId, result) {
var deferred = this.deferreds[requestId];
if (!deferred) {
Tomahawk.log("Deferred object with the given requestId is not present!");
}
deferred.resolve(result);
}
};
Tomahawk.UrlType = {
Any: 0,
Playlist: 1,
Track: 2,
Album: 3,
Artist: 4,
XspfPlaylist: 5
};
Tomahawk.ConfigTestResultType = { Tomahawk.ConfigTestResultType = {
Other: 0, Other: 0,
@@ -1194,8 +1227,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");
@@ -1244,7 +1275,11 @@ Tomahawk.Collection = {
"FOREIGN KEY(artistId) REFERENCES artists(_id)," + "FOREIGN KEY(artistId) REFERENCES artists(_id)," +
"FOREIGN KEY(albumId) REFERENCES albums(_id))", []); "FOREIGN KEY(albumId) REFERENCES albums(_id))", []);
}); });
//m.migration(2, function (tx) {
// //Tomahawk.log("Migrating to db version 2");
//});
m.execute();
} }
resolve(collection.cachedDbs[id]); resolve(collection.cachedDbs[id]);
}); });
@@ -1261,18 +1296,18 @@ Tomahawk.Collection = {
}); });
}; };
this.execDefferedStatements = function (resolve, reject) { this.execDeferredStatements = function (resolve, reject) {
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
return new Promise(function (resolve, reject) { + ' deferred SQL statements in transaction');
if (that.statements.length == 0) return new RSVP.Promise(function (resolve, reject) {
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 () {
@@ -1280,8 +1315,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++) {
@@ -1290,11 +1324,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);
} }
@@ -1310,7 +1344,7 @@ 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});
@@ -1368,6 +1402,7 @@ Tomahawk.Collection = {
}; };
}, },
addTracks: function (params) { addTracks: function (params) {
var that = this; var that = this;
var id = params.id; var id = params.id;
@@ -1404,7 +1439,7 @@ Tomahawk.Collection = {
}); });
})(tracks[i]); })(tracks[i]);
} }
return t.execDefferedStatements(); return t.execDeferredStatements();
}).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) {
@@ -1421,7 +1456,7 @@ Tomahawk.Collection = {
_id: r._id _id: r._id
}; };
}); });
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (resultsArray) { }).then(function (resultsArray) {
// Store the db ids in a map // Store the db ids in a map
var i, row, albumArtists = {}; var i, row, albumArtists = {};
@@ -1457,7 +1492,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;
@@ -1467,7 +1501,7 @@ Tomahawk.Collection = {
}); });
})(tracks[i]); })(tracks[i]);
} }
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function () { }).then(function () {
// Get the albums' db ids // Get the albums' db ids
t.sqlSelect("albums", function (r) { t.sqlSelect("albums", function (r) {
@@ -1477,7 +1511,7 @@ Tomahawk.Collection = {
_id: r._id _id: r._id
}; };
}); });
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (results) { }).then(function (results) {
// Store the db ids in a map // Store the db ids in a map
results = results[0]; results = results[0];
@@ -1491,7 +1525,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
@@ -1517,7 +1550,7 @@ Tomahawk.Collection = {
}); });
})(tracks[i]); })(tracks[i]);
} }
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function () { }).then(function () {
var resultMap = function (r) { var resultMap = function (r) {
return { return {
@@ -1529,7 +1562,7 @@ Tomahawk.Collection = {
}; };
// Get the tracks' db ids // Get the tracks' db ids
t.sqlSelect("tracks", resultMap, ["_id", "artistId", "albumId", "track"]); t.sqlSelect("tracks", resultMap, ["_id", "artistId", "albumId", "track"]);
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (results) { }).then(function (results) {
that._trackCount = results[0].length; that._trackCount = results[0].length;
Tomahawk.log("Added " + results[0].length + " tracks to collection '" + id + "'"); Tomahawk.log("Added " + results[0].length + " tracks to collection '" + id + "'");
@@ -1560,9 +1593,9 @@ Tomahawk.Collection = {
t.sqlDrop("albums"); t.sqlDrop("albums");
t.sqlDrop("artistAlbums"); t.sqlDrop("artistAlbums");
t.sqlDrop("tracks"); t.sqlDrop("tracks");
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function () { }).then(function () {
return new Promise(function (resolve, reject) { return new RSVP.Promise(function (resolve, reject) {
that.cachedDbs[id].changeVersion(that.cachedDbs[id].version, "", null, that.cachedDbs[id].changeVersion(that.cachedDbs[id].version, "", null,
function (err) { function (err) {
if (console.error) { if (console.error) {
@@ -1580,9 +1613,9 @@ 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) {
@@ -1619,7 +1652,7 @@ Tomahawk.Collection = {
] ]
); );
} }
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (results) { }).then(function (results) {
var merged = []; var merged = [];
return merged.concat.apply(merged, return merged.concat.apply(merged,
@@ -1631,17 +1664,11 @@ Tomahawk.Collection = {
}, },
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);
}, },
@@ -1649,8 +1676,9 @@ 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 () {
@@ -1684,7 +1712,7 @@ Tomahawk.Collection = {
} }
] ]
); );
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (results) { }).then(function (results) {
return {results: Tomahawk.resolver.instance._convertUrls(results[0])}; return {results: Tomahawk.resolver.instance._convertUrls(results[0])};
}); });
@@ -1693,8 +1721,9 @@ 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 () {
@@ -1716,14 +1745,18 @@ Tomahawk.Collection = {
} }
] ]
); );
return t.execDefferedStatements(); return t.execDeferredStatements();
}).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;
})
}; };
}); });
}, },
@@ -1731,17 +1764,17 @@ 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"]);
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (artists) { }).then(function (artists) {
return {artists: artists[0]}; return {artists: artists[0]};
}); });
@@ -1760,7 +1793,7 @@ Tomahawk.Collection = {
//}; //};
//}; //};
//t.sqlSelect("albumArtists", ["albumArtist", "albumArtistDisambiguation"]); //t.sqlSelect("albumArtists", ["albumArtist", "albumArtistDisambiguation"]);
//return t.execDefferedStatements(); //return t.execDeferredStatements();
//}).then(function (results) { //}).then(function (results) {
//return results[0]; //return results[0];
//}); //});
@@ -1769,24 +1802,27 @@ 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.execDeferredStatements();
}).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
}, [ }, [
{ {
@@ -1796,7 +1832,7 @@ Tomahawk.Collection = {
} }
} }
]); ]);
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (results) { }).then(function (results) {
return { return {
artist: artist, artist: artist,
@@ -1808,8 +1844,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;
@@ -1818,18 +1855,22 @@ 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.execDeferredStatements();
}).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
}); });
return t.execDefferedStatements(); return t.execDeferredStatements();
}).then(function (results) { }).then(function (results) {
var albumId = results[0][0]; var albumId = results[0][0];
return that.tracks(params, { return that.tracks(params, {
@@ -1840,15 +1881,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) {
@@ -1858,7 +1900,59 @@ 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];
}; };
Tomahawk.addTrackResults = function (result) {
Tomahawk.PluginManager.resolve[result.qid](result.results);
delete Tomahawk.PluginManager.resolve[result.qid];
};
Tomahawk.reportStreamUrl = function (qid, streamUrl, headers) {
Tomahawk.PluginManager.resolve[qid]({
url: streamUrl,
headers: headers
});
delete Tomahawk.PluginManager.resolve[qid];
};
Tomahawk.addUrlResult = function (url, result) {
/* Merge the whole mess into one consistent result which is independent of type
var cleanResult = {
type: result.type,
guid: result.guid,
info: result.info,
creator: result.creator,
linkUrl: result.url
};
if (cleanResult.type == "track") {
cleanResult.track = result.title;
cleanResult.artist = result.artist;
} else if (cleanResult.type == "artist") {
cleanResult.artist = result.name;
} else if (cleanResult.type == "album") {
cleanResult.album = result.name;
cleanResult.artist = result.artist;
} else if (cleanResult.type == "playlist") {
cleanResult.title = result.title;
} else if (cleanResult.type == "xspf-url") {
cleanResult.url = result.url;
}
if (result.tracks) {
cleanResult.tracks = [];
var i;
for (i=0;i<result.tracks.length;i++) {
var cleanTrack = {
track: result.tracks[i].title,
artist: result.tracks[i].artist
};
cleanResult.push(cleanTrack)
}
Tomahawk.PluginManager.resolve[url](cleanResult);
*/
Tomahawk.PluginManager.resolve[url](result);
delete Tomahawk.PluginManager.resolve[url];
};