-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.js
394 lines (326 loc) · 9.82 KB
/
utils.js
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
var monk = require('monk');
var fs = require('fs');
var ObjectID = require('mongodb').ObjectID;
var SpotifyWebApi = require('spotify-web-api-node');
var transform = require('./query/transform')
var db = monk('localhost:27017/queueup');
var spotifyConfig = JSON.parse(fs.readFileSync(__dirname + '/spotify.key', {encoding: 'utf8'}));
exports.normalizeName = function (name) {
return name.replace(/[^\w]/gi,'').toLowerCase();
}
exports.getSpotifyApiForUser = function (user, callback) {
if (user) {
var spotifyApi = new SpotifyWebApi(spotifyConfig);
spotifyApi.setAccessToken(user.spotify.accessToken);
spotifyApi.setRefreshToken(user.spotify.refreshToken);
// If accessToken has expired
if (user.spotify.tokenExpiration < new Date().getTime()) {
spotifyApi.refreshAccessToken().then(function (data) {
user.spotify.accessToken = data.access_token;
user.spotify.tokenExpiration = (data.expires_in * 1000) + new Date().getTime();
spotifyApi.setAccessToken(data.access_token);
callback(null, spotifyApi, user);
}, function (err) {
callback(err);
});
} else {
callback(null, spotifyApi);
}
} else {
callback(new Error("Invalid user"));
}
}
exports.getUserPlaylistTracks = function (user, playlist, callback) {
if (user && playlist) {
getSpotifyApiForUser(user, playlist);
} else {
callback(new Error("User or playlist is undefined"));
}
}
exports.skipTrack = function (req, playlist, callback) {
transform.playlist(req, playlist, function (playlist) {
/* If there's anything in the queue */
if (playlist.tracks && playlist.tracks.length > 0) {
/* Store the first track */
var first = playlist.tracks[0];
console.log("Marking played: ", first.track.id);
/* Remove the first track from the DB, set the current as the stored track */
/* Mark the track as played and will not be displayed */
req.Playlists.findAndModify({
_id: playlist._id,
"tracks._id": first._id
}, {
$set: {
current: first.track,
current_addedBy: first.addedBy,
last_updated: new Date().getTime(),
"tracks.$.played": true
}
}, {
"new": true
}).success(function (playlist) {
transform.playlist(req, playlist, function (transformed) {
callback(transformed);
});
}).error(function (err) {
callback(null, err);
});
} else {
/* Reset the entire queue to not being played */
exports.resetPlaylist(req, playlist, callback);
}
});
}
exports.resetPlaylist = function (req, playlist, callback) {
console.log("Resetting playlist to initial state");
req.Playlists.findOne({
_id: playlist._id
}).success(function (p) {
p.tracks.forEach(function (track) {
track.played = false;
track.votes = 0;
track.voters = [];
});
req.Playlists.findAndModify({
_id: playlist._id
}, {
$set: {
current: null,
tracks: p.tracks
}
}, {
"new": true,
}).success(function (playlist) {
/* Moves the first track to current */
exports.skipTrack(req, playlist, callback);
}).error(function (err) {
callback(null, err);
});
}).error(function (err) {
callback(null, err);
});
}
exports.userIsPlaylistAdmin = function (user, playlist) {
if (!user || !playlist) {
return false;
}
return (user._id.equals(playlist.admin));
}
exports.updateUser = function (req, user, update, callback) {
req.Users.update({
_id: user._id
}, { $set: update }).error(function (err) {
if (callback) {
callback(err);
}
}).success(function(record) {
if (callback) {
callback(record);
}
});
}
exports.addTrackToPlaylist = function (req, trackId, playlist, callback) {
/* First get the track information from Spotify */
var apiUser = req.apiUser;
var user = (apiUser) ? {_id: apiUser._id, name: apiUser.name } : null;
req.spotify.getTrack(trackId).then(function(response) {
var track = response.body;
/* This keeps on the fields we want */
track = exports.objCopy(track, {"name": true,"duration_ms": true, "id": true, "uri": true, "artists": true, "album.id": true, "album.images": true, "album.name": true, "album.uri": true});
/* track should be defined if Spotify found a valid track */
if (track) {
/* If there isn't a current track, set this as the current, and mark as played so we can recover it later */
if (!playlist.current) {
/* Set the current track to the one just added */
req.Playlists.findAndModify(
{_id: playlist._id},
{
$set: {
current: track,
current_addedBy: user
},
$push: {
tracks: {
_id: new ObjectID(),
track: track,
dateAdded: new Date().getTime(),
addedBy: user,
played: true
}
}
}, { "new": true }
).success(function(playlist) {
/* playlist found in DB */
callback(null, playlist);
}).error(function (err) {
callback(err);
});
} else {
/* Add the track to the end of the queue */
req.Playlists.findAndModify(
{_id: playlist._id},
{
$push: {
tracks: {
_id: new ObjectID(),
track: track,
dateAdded: new Date().getTime(),
addedBy: user
}
}
}, {"new": true}
).success(function (playlist) {
/* Added successfully */
console.log("Added track: ", track.id);
callback(null, playlist);
}).error(function (err) {
callback(err);
console.log(err);
});
}
} else {
/* If the response from Spotify was undefined */
callback({
error: "Track not found",
message: "TrackID: " + req.params.trackid
});
}
});
}
exports.voteOnTrack = function (req, trackId, upvote, success, badRequest, error) {
var apiUserId = req.apiUser._id;
var playlistId = req.playlist._id;
var Playlists = req.Playlists;
/* First get playlist and track where the user is a voter */
Playlists.findOne({
_id: playlistId,
tracks: {
$elemMatch: {
_id: ObjectID(trackId),
voters: {
$elemMatch: {
_id: apiUserId
}
}
}
}
}).success(function (playlist) {
var updateQuery;
console.log("Voting", upvote);
/* If we are to add a vote and the user isn't already a voter on the track */
if (upvote && !playlist) {
/* Increments the votes and pushes the user to the list */
updateQuery = {
$inc: {
"tracks.$.votes": 1
},
$push: {
"tracks.$.voters": {
_id: apiUserId
}
}
};
/* If the user is a voter and we are removing the vote */
} else if (!upvote && playlist) {
/* Decrement and remove the voter */
updateQuery = {
$inc: {
"tracks.$.votes": -1
},
$pull: {
"tracks.$.voters": {
_id: apiUserId
}
}
};
} else {
if (upvote) {
badRequest("The user has already voted on this track");
} else {
badRequest("The user hasn't voted on this track yet");
}
}
/* If we have a valid scenario */
if (updateQuery) {
/* Do the update */
Playlists.findAndModify({
_id: playlistId,
"tracks._id": ObjectID(trackId)
}, updateQuery, {
"new": true
}).success(function (newPlaylist) {
/* If the track hasn't disappeared for some reason since last check*/
if (newPlaylist != null) {
success(newPlaylist);
} else {
console.log("No track found in playlist");
badRequest("No track found in playlist");
}
}).error(function (err) {
error(err);
});
}
}).error(function (err) {
error(err);
});
}
/* Broadcast to every listener in the 'room' */
exports.emitStateChange = function (req, playlist, proj, trigger) {
// TODO: IMPLEMENT PROJECTIONS
if (typeof (proj) == "string") {
trigger = proj;
}
// console.log("emitting state change: ", playlist);
/* Transform with the current state (playlist field is required) */
transform.playlist(req, playlist, function (playlist) {
/* Send update */
req.io.to(playlist._id).emit('state_change', {
play: playlist.play,
track: playlist.current,
queue: playlist.tracks,
trigger: trigger
});
});
}
/* Send to specific client */
exports.sendStateChange = function (req, socket, playlist, trigger) {
/* Transform with state */
transform.playlist(req, playlist, function (playlist) {
/* Send update */
socket.emit('state_change', {
play: playlist.play,
track: playlist.current,
queue: playlist.tracks,
trigger: trigger
});
});
}
exports.trackSimplify = function (track) {
return {
}
}
/**
This returns a copy of the object, but with the set of 'keep' fields retained.
Inner objects can be retained using "." between fields.
*/
exports.objCopy = function (object, keep) {
function copyObjField(object, fields, input) {
var o = (input) ? input : undefined;
if (fields.length >= 1) {
if (!o) { o = {} };
var top = fields.splice(0,1)[0];
var value = object[top];
if (value) {
o[top] = (fields.length == 0) ? value : copyObjField(value, fields, o[top]);
}
}
return o;
}
var result = {};
if (keep) {
for (key in keep) {
copyObjField(object, key.split('.'), result)
}
}
return result;
}