-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSearch.js
More file actions
102 lines (85 loc) · 2.73 KB
/
Search.js
File metadata and controls
102 lines (85 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var b = require('bindings')('spotify.node');
var Session = require('./Session');
var Track = require('./Track');
var Album = require('./Album');
var Artist = require('./Artist');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var format = require('format').format;
/**
* This class allows to run searches on the spotify database
* You can either create it from a string or specify single fields
* with the adequate methods
* @constructor
* @param {Session} session, the session to attach this search to (optional)
* @param {String} search, a query to run (optional)
*/
function Search (session, query) {
if(session && session instanceof Session) {
this._session = session;
}
else {
this._session = Session.currentSession;
}
this._query = query || (typeof session == 'string') ? session : null;
this.trackOffset = 0,
this.trackCount = 10,
this.albumOffset = 0,
this.albumCount = 0,
this.artistOffset = 0,
this.artistCount = 0,
this.playlistOffset = 0,
this.playlistCount = 0;
this._sp_search = null;
}
util.inherits(Search, EventEmitter);
/**
* actually run the search. When the search is complete
* the event 'ready' is triggered
*/
Search.prototype.execute = function execute(cb) {
this._sp_search = b.search_create(
this._session._sp_session,
this._query,
this.trackOffset || 0,
this.trackCount || 0,
this.albumOffset || 0,
this.albumCount || 0,
this.artistOffset || 0,
this.artistCount || 0,
this.playlistOffset || 0,
this.playlistCount || 0
);
var self = this;
this._sp_search.on_search_complete = function(err, search) {
if(err) {
self.emit('error', err);
return;
}
if(search != self._sp_search) {
return;
}
self._processResults(search);
self.emit('ready', self);
};
if(typeof cb == 'function') {
this.once('ready', cb);
}
};
Search.prototype._processResults = function _processResults(search) {
var i;
this.tracks = new Array(b.search_num_tracks(this._sp_search));
this.albums = new Array(b.search_num_albums(this._sp_search));
this.artists = new Array(b.search_num_artists(this._sp_search));
for (i = 0; i < this.tracks.length; ++i) {
this.tracks[i] = new Track(b.search_track(this._sp_search, i));
}
for (i = 0; i < this.albums.length; ++i) {
this.albums[i] = new Album(b.search_album(this._sp_search, i));
}
for (i = 0; i < this.artists.length; ++i) {
this.artists[i] = new Artist(b.search_artist(this._sp_search, i));
}
this.playlists = [];
};
module.exports = Search;