playlists.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. 'use strict';
  2. const db = require('../db');
  3. const io = require('../io');
  4. const cache = require('../cache');
  5. const utils = require('../utils');
  6. const logger = require('../logger');
  7. const hooks = require('./hooks');
  8. const async = require('async');
  9. const playlists = require('../playlists');
  10. const songs = require('../songs');
  11. cache.sub('playlist.create', playlistId => {
  12. playlists.getPlaylist(playlistId, (err, playlist) => {
  13. if (!err) {
  14. utils.socketsFromUser(playlist.createdBy, (sockets) => {
  15. sockets.forEach((socket) => {
  16. socket.emit('event:playlist.create', playlist);
  17. });
  18. });
  19. }
  20. });
  21. });
  22. cache.sub('playlist.delete', res => {
  23. utils.socketsFromUser(res.userId, (sockets) => {
  24. sockets.forEach((socket) => {
  25. socket.emit('event:playlist.delete', res.playlistId);
  26. });
  27. });
  28. });
  29. cache.sub('playlist.moveSongToTop', res => {
  30. utils.socketsFromUser(res.userId, (sockets) => {
  31. sockets.forEach((socket) => {
  32. socket.emit('event:playlist.moveSongToTop', {playlistId: res.playlistId, songId: res.songId});
  33. });
  34. });
  35. });
  36. cache.sub('playlist.moveSongToBottom', res => {
  37. utils.socketsFromUser(res.userId, (sockets) => {
  38. sockets.forEach((socket) => {
  39. socket.emit('event:playlist.moveSongToBottom', {playlistId: res.playlistId, songId: res.songId});
  40. });
  41. });
  42. });
  43. cache.sub('playlist.addSong', res => {
  44. utils.socketsFromUser(res.userId, (sockets) => {
  45. sockets.forEach((socket) => {
  46. socket.emit('event:playlist.addSong', {playlistId: res.playlistId, song: res.song});
  47. });
  48. });
  49. });
  50. cache.sub('playlist.removeSong', res => {
  51. utils.socketsFromUser(res.userId, (sockets) => {
  52. sockets.forEach((socket) => {
  53. socket.emit('event:playlist.removeSong', {playlistId: res.playlistId, songId: res.songId});
  54. });
  55. });
  56. });
  57. cache.sub('playlist.updateDisplayName', res => {
  58. utils.socketsFromUser(res.userId, (sockets) => {
  59. sockets.forEach((socket) => {
  60. socket.emit('event:playlist.updateDisplayName', {playlistId: res.playlistId, displayName: res.displayName});
  61. });
  62. });
  63. });
  64. let lib = {
  65. /**
  66. * Gets the first song from a private playlist
  67. *
  68. * @param {Object} session - the session object automatically added by socket.io
  69. * @param {String} playlistId - the id of the playlist we are getting the first song from
  70. * @param {Function} cb - gets called with the result
  71. * @param {String} userId - the userId automatically added by hooks
  72. */
  73. getFirstSong: hooks.loginRequired((session, playlistId, cb, userId) => {
  74. async.waterfall([
  75. (next) => {
  76. playlists.getPlaylist(playlistId, next);
  77. },
  78. (playlist, next) => {
  79. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found.');
  80. next(null, playlist.songs[0]);
  81. }
  82. ], (err, song) => {
  83. if (err) {
  84. let error = 'An error occurred.';
  85. if (typeof err === "string") error = err;
  86. else if (err.message) error = err.message;
  87. logger.log("PLAYLIST_GET_FIRST_SONG", "ERROR", `Getting the first song of playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  88. return cb({ status: 'failure', message: 'Something went wrong when getting the playlist'});
  89. }
  90. logger.log("PLAYLIST_GET_FIRST_SONG", "SUCCESS", `Successfully got the first song of playlist "${playlistId}" for user "${userId}".`);
  91. cb({
  92. status: 'success',
  93. song: song
  94. });
  95. });
  96. }),
  97. /**
  98. * Gets all playlists for the user requesting it
  99. *
  100. * @param {Object} session - the session object automatically added by socket.io
  101. * @param {Function} cb - gets called with the result
  102. * @param {String} userId - the userId automatically added by hooks
  103. */
  104. indexForUser: hooks.loginRequired((session, cb, userId) => {
  105. async.waterfall([
  106. (next) => {
  107. db.models.playlist.find({ createdBy: userId }, next);
  108. }
  109. ], (err, playlists) => {
  110. if (err) {
  111. let error = 'An error occurred.';
  112. if (typeof err === "string") error = err;
  113. else if (err.message) error = err.message;
  114. logger.log("PLAYLIST_INDEX_FOR_USER", "ERROR", `Indexing playlists for user "${userId}" failed. "${error}"`);
  115. return cb({ status: 'failure', message: error});
  116. }
  117. logger.log("PLAYLIST_INDEX_FOR_USER", "SUCCESS", `Successfully indexed playlists for user "${userId}".`);
  118. cb({
  119. status: 'success',
  120. data: playlists
  121. });
  122. });
  123. }),
  124. /**
  125. * Creates a new private playlist
  126. *
  127. * @param {Object} session - the session object automatically added by socket.io
  128. * @param {Object} data - the data for the new private playlist
  129. * @param {Function} cb - gets called with the result
  130. * @param {String} userId - the userId automatically added by hooks
  131. */
  132. create: hooks.loginRequired((session, data, cb, userId) => {
  133. async.waterfall([
  134. (next) => {
  135. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  136. },
  137. (next) => {
  138. const { displayName, songs } = data;
  139. db.models.playlist.create({
  140. _id: utils.generateRandomString(17),//TODO Check if exists
  141. displayName,
  142. songs,
  143. createdBy: userId,
  144. createdAt: Date.now()
  145. }, next);
  146. }
  147. ], (err, playlist) => {
  148. if (err) {
  149. let error = 'An error occurred.';
  150. if (typeof err === "string") error = err;
  151. else if (err.message) error = err.message;
  152. logger.log("PLAYLIST_CREATE", "ERROR", `Creating private playlist failed for user "${userId}". "${error}"`);
  153. return cb({ status: 'failure', message: error});
  154. }
  155. cache.pub('playlist.create', playlist._id);
  156. logger.log("PLAYLIST_CREATE", "SUCCESS", `Successfully created private playlist for user "${userId}".`);
  157. cb({ 'status': 'success', 'message': 'Successfully created playlist' });
  158. });
  159. }),
  160. /**
  161. * Gets a playlist from id
  162. *
  163. * @param {Object} session - the session object automatically added by socket.io
  164. * @param {String} playlistId - the id of the playlist we are getting
  165. * @param {Function} cb - gets called with the result
  166. * @param {String} userId - the userId automatically added by hooks
  167. */
  168. getPlaylist: hooks.loginRequired((session, playlistId, cb, userId) => {
  169. async.waterfall([
  170. (next) => {
  171. playlists.getPlaylist(playlistId, next);
  172. },
  173. (playlist, next) => {
  174. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  175. next(null, playlist);
  176. }
  177. ], (err, playlist) => {
  178. if (err) {
  179. let error = 'An error occurred.';
  180. if (typeof err === "string") error = err;
  181. else if (err.message) error = err.message;
  182. logger.log("PLAYLIST_GET", "ERROR", `Getting private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  183. return cb({ status: 'failure', message: error});
  184. }
  185. logger.log("PLAYLIST_GET", "SUCCESS", `Successfully got private playlist "${playlistId}" for user "${userId}".`);
  186. console.log(playlist);
  187. cb({
  188. status: 'success',
  189. data: playlist
  190. });
  191. });
  192. }),
  193. //TODO Remove this
  194. /**
  195. * Updates a private playlist
  196. *
  197. * @param {Object} session - the session object automatically added by socket.io
  198. * @param {String} playlistId - the id of the playlist we are updating
  199. * @param {Object} playlist - the new private playlist object
  200. * @param {Function} cb - gets called with the result
  201. * @param {String} userId - the userId automatically added by hooks
  202. */
  203. update: hooks.loginRequired((session, playlistId, playlist, cb, userId) => {
  204. async.waterfall([
  205. (next) => {
  206. db.models.playlist.update({ _id: playlistId, createdBy: userId }, playlist, next);
  207. },
  208. (res, next) => {
  209. playlists.updatePlaylist(playlistId, next)
  210. }
  211. ], (err, playlist) => {
  212. if (err) {
  213. let error = 'An error occurred.';
  214. if (typeof err === "string") error = err;
  215. else if (err.message) error = err.message;
  216. logger.log("PLAYLIST_UPDATE", "ERROR", `Updating private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  217. return cb({ status: 'failure', message: error});
  218. }
  219. logger.log("PLAYLIST_UPDATE", "SUCCESS", `Successfully updated private playlist "${playlistId}" for user "${userId}".`);
  220. cb({
  221. status: 'success',
  222. data: playlist
  223. });
  224. });
  225. }),
  226. /**
  227. * Adds a song to a private playlist
  228. *
  229. * @param {Object} session - the session object automatically added by socket.io
  230. * @param {String} songId - the id of the song we are trying to add
  231. * @param {String} playlistId - the id of the playlist we are adding the song to
  232. * @param {Function} cb - gets called with the result
  233. * @param {String} userId - the userId automatically added by hooks
  234. */
  235. addSongToPlaylist: hooks.loginRequired((session, songId, playlistId, cb, userId) => {
  236. async.waterfall([
  237. (next) => {
  238. playlists.getPlaylist(playlistId, (err, playlist) => {
  239. if (err || !playlist || playlist.createdBy !== userId) return next('Something went wrong when trying to get the playlist');
  240. async.each(playlist.songs, (song, next) => {
  241. if (song._id === songId) return next('That song is already in the playlist');
  242. next();
  243. }, next);
  244. });
  245. },
  246. (next) => {
  247. songs.getSong(songId, (err, song) => {
  248. if (err) {
  249. utils.getSongFromYouTube(songId, (song) => {
  250. next(null, song);
  251. });
  252. } else {
  253. next(null, {
  254. _id: songId,
  255. title: song.title,
  256. duration: song.duration
  257. });
  258. }
  259. });
  260. },
  261. (newSong, next) => {
  262. db.models.playlist.update({ _id: playlistId }, { $push: { songs: newSong } }, (err) => {
  263. if (err) return next(err);
  264. playlists.updatePlaylist(playlistId, (err, playlist) => {
  265. next(err, playlist, newSong);
  266. });
  267. });
  268. }
  269. ],
  270. (err, playlist, newSong) => {
  271. if (err) {
  272. let error = 'An error occurred.';
  273. if (typeof err === "string") error = err;
  274. else if (err.message) error = err.message;
  275. logger.log("PLAYLIST_ADD_SONG", "ERROR", `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  276. return cb({ status: 'failure', message: error});
  277. }
  278. logger.log("PLAYLIST_ADD_SONG", "SUCCESS", `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${userId}".`);
  279. cache.pub('playlist.addSong', { playlistId: playlist._id, song: newSong, userId: userId });
  280. return cb({ status: 'success', message: 'Song has been successfully added to the playlist', data: playlist.songs });
  281. });
  282. }),
  283. /**
  284. * Adds a set of songs to a private playlist
  285. *
  286. * @param {Object} session - the session object automatically added by socket.io
  287. * @param {String} url - the url of the the YouTube playlist
  288. * @param {String} playlistId - the id of the playlist we are adding the set of songs to
  289. * @param {Function} cb - gets called with the result
  290. * @param {String} userId - the userId automatically added by hooks
  291. */
  292. addSetToPlaylist: hooks.loginRequired((session, url, playlistId, cb, userId) => {
  293. async.waterfall([
  294. (next) => {
  295. utils.getPlaylistFromYouTube(url, songs => {
  296. next(null, songs);
  297. });
  298. },
  299. (songs, next) => {
  300. let processed = 0;
  301. function checkDone() {
  302. if (processed === songs.length) next();
  303. }
  304. for (let s = 0; s < songs.length; s++) {
  305. lib.addSongToPlaylist(session, songs[s].contentDetails.videoId, playlistId, () => {
  306. processed++;
  307. checkDone();
  308. });
  309. }
  310. },
  311. (next) => {
  312. playlists.getPlaylist(playlistId, next);
  313. },
  314. (playlist, next) => {
  315. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found.');
  316. next(null, playlist);
  317. }
  318. ], (err, playlist) => {
  319. if (err) {
  320. let error = 'An error occurred.';
  321. if (typeof err === "string") error = err;
  322. else if (err.message) error = err.message;
  323. logger.log("PLAYLIST_IMPORT", "ERROR", `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  324. return cb({ status: 'failure', message: error});
  325. }
  326. logger.log("PLAYLIST_IMPORT", "SUCCESS", `Successfully imported a YouTube playlist to private playlist "${playlistId}" for user "${userId}".`);
  327. cb({ status: 'success', message: 'Playlist has been successfully imported.', data: playlist.songs });
  328. });
  329. }),
  330. /**
  331. * Removes a song from a private playlist
  332. *
  333. * @param {Object} session - the session object automatically added by socket.io
  334. * @param {String} songId - the id of the song we are removing from the private playlist
  335. * @param {String} playlistId - the id of the playlist we are removing the song from
  336. * @param {Function} cb - gets called with the result
  337. * @param {String} userId - the userId automatically added by hooks
  338. */
  339. removeSongFromPlaylist: hooks.loginRequired((session, songId, playlistId, cb, userId) => {
  340. async.waterfall([
  341. (next) => {
  342. playlists.getPlaylist(playlistId, next);
  343. },
  344. (playlist, next) => {
  345. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  346. db.models.playlist.update({_id: playlistId}, {$pull: {songs: songId}}, next);
  347. },
  348. (res, next) => {
  349. playlists.updatePlaylist(playlistId, next);
  350. }
  351. ], (err, playlist) => {
  352. if (err) {
  353. let error = 'An error occurred.';
  354. if (typeof err === "string") error = err;
  355. else if (err.message) error = err.message;
  356. logger.log("PLAYLIST_REMOVE_SONG", "ERROR", `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  357. return cb({ status: 'failure', message: error});
  358. }
  359. logger.log("PLAYLIST_REMOVE_SONG", "SUCCESS", `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${userId}".`);
  360. cache.pub('playlist.removeSong', {playlistId: playlist._id, songId: songId, userId: userId});
  361. return cb({ status: 'success', message: 'Song has been successfully removed from playlist', data: playlist.songs });
  362. });
  363. }),
  364. /**
  365. * Updates the displayName of a private playlist
  366. *
  367. * @param {Object} session - the session object automatically added by socket.io
  368. * @param {String} playlistId - the id of the playlist we are updating the displayName for
  369. * @param {Function} cb - gets called with the result
  370. * @param {String} userId - the userId automatically added by hooks
  371. */
  372. updateDisplayName: hooks.loginRequired((session, playlistId, displayName, cb, userId) => {
  373. async.waterfall([
  374. (next) => {
  375. db.models.playlist.update({ _id: playlistId, createdBy: userId }, { $set: { displayName } }, next);
  376. },
  377. (res, next) => {
  378. playlists.updatePlaylist(playlistId, next);
  379. }
  380. ], (err, playlist) => {
  381. if (err) {
  382. let error = 'An error occurred.';
  383. if (typeof err === "string") error = err;
  384. else if (err.message) error = err.message;
  385. logger.log("PLAYLIST_UPDATE_DISPLAY_NAME", "ERROR", `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  386. return cb({ status: 'failure', message: error});
  387. }
  388. logger.log("PLAYLIST_UPDATE_DISPLAY_NAME", "SUCCESS", `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${userId}".`);
  389. cache.pub('playlist.updateDisplayName', {playlistId: playlistId, displayName: displayName, userId: userId});
  390. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  391. });
  392. }),
  393. /**
  394. * Moves a song to the top of the list in a private playlist
  395. *
  396. * @param {Object} session - the session object automatically added by socket.io
  397. * @param {String} playlistId - the id of the playlist we are moving the song to the top from
  398. * @param {String} songId - the id of the song we are moving to the top of the list
  399. * @param {Function} cb - gets called with the result
  400. * @param {String} userId - the userId automatically added by hooks
  401. */
  402. moveSongToTop: hooks.loginRequired((session, playlistId, songId, cb, userId) => {
  403. async.waterfall([
  404. (next) => {
  405. playlists.getPlaylist(playlistId, next);
  406. },
  407. (playlist, next) => {
  408. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  409. async.each(playlist.songs, (song, next) => {
  410. if (song._id === songId) return next(song);
  411. next();
  412. }, (err) => {
  413. if (err && err._id) return next(null, err);
  414. next('Song not found');
  415. });
  416. },
  417. (song, next) => {
  418. db.models.playlist.update({_id: playlistId}, {$pull: {songs: {_id: songId}}}, (err) => {
  419. if (err) return next(err);
  420. return next(null, song);
  421. });
  422. },
  423. (song, next) => {
  424. db.models.playlist.update({_id: playlistId}, {
  425. $push: {
  426. songs: {
  427. $each: [song],
  428. $position: 0
  429. }
  430. }
  431. }, next);
  432. },
  433. (res, next) => {
  434. playlists.updatePlaylist(playlistId, next);
  435. }
  436. ], (err, playlist) => {
  437. if (err) {
  438. let error = 'An error occurred.';
  439. if (typeof err === "string") error = err;
  440. else if (err.message) error = err.message;
  441. logger.log("PLAYLIST_MOVE_SONG_TO_TOP", "ERROR", `Moving song "${songId}" to the top for private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  442. return cb({ status: 'failure', message: error});
  443. }
  444. logger.log("PLAYLIST_MOVE_SONG_TO_TOP", "SUCCESS", `Successfully moved song "${songId}" to the top for private playlist "${playlistId}" for user "${userId}".`);
  445. cache.pub('playlist.moveSongToTop', {playlistId, songId, userId: userId});
  446. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  447. });
  448. }),
  449. /**
  450. * Moves a song to the bottom of the list in a private playlist
  451. *
  452. * @param {Object} session - the session object automatically added by socket.io
  453. * @param {String} playlistId - the id of the playlist we are moving the song to the bottom from
  454. * @param {String} songId - the id of the song we are moving to the bottom of the list
  455. * @param {Function} cb - gets called with the result
  456. * @param {String} userId - the userId automatically added by hooks
  457. */
  458. moveSongToBottom: hooks.loginRequired((session, playlistId, songId, cb, userId) => {
  459. async.waterfall([
  460. (next) => {
  461. playlists.getPlaylist(playlistId, next);
  462. },
  463. (playlist, next) => {
  464. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  465. async.each(playlist.songs, (song, next) => {
  466. if (song._id === songId) return next(song);
  467. next();
  468. }, (err) => {
  469. if (err && err._id) return next(null, err);
  470. next('Song not found');
  471. });
  472. },
  473. (song, next) => {
  474. db.models.playlist.update({_id: playlistId}, {$pull: {songs: {_id: songId}}}, (err) => {
  475. if (err) return next(err);
  476. return next(null, song);
  477. });
  478. },
  479. (song, next) => {
  480. db.models.playlist.update({_id: playlistId}, {
  481. $push: {
  482. songs: song
  483. }
  484. }, next);
  485. },
  486. (res, next) => {
  487. playlists.updatePlaylist(playlistId, next);
  488. }
  489. ], (err, playlist) => {
  490. if (err) {
  491. let error = 'An error occurred.';
  492. if (typeof err === "string") error = err;
  493. else if (err.message) error = err.message;
  494. logger.log("PLAYLIST_MOVE_SONG_TO_BOTTOM", "ERROR", `Moving song "${songId}" to the bottom for private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  495. return cb({ status: 'failure', message: error});
  496. }
  497. logger.log("PLAYLIST_MOVE_SONG_TO_BOTTOM", "SUCCESS", `Successfully moved song "${songId}" to the bottom for private playlist "${playlistId}" for user "${userId}".`);
  498. cache.pub('playlist.moveSongToBottom', {playlistId, songId, userId: userId});
  499. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  500. });
  501. }),
  502. /**
  503. * Removes a song from a private playlist
  504. *
  505. * @param {Object} session - the session object automatically added by socket.io
  506. * @param {String} playlistId - the id of the playlist we are moving the song to the top from
  507. * @param {Function} cb - gets called with the result
  508. * @param {String} userId - the userId automatically added by hooks
  509. */
  510. remove: hooks.loginRequired((session, playlistId, cb, userId) => {
  511. async.waterfall([
  512. (next) => {
  513. playlists.deletePlaylist(playlistId, next);
  514. }
  515. ], (err) => {
  516. if (err) {
  517. let error = 'An error occurred.';
  518. if (typeof err === "string") error = err;
  519. else if (err.message) error = err.message;
  520. logger.log("PLAYLIST_REMOVE", "ERROR", `Removing private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  521. return cb({ status: 'failure', message: error});
  522. }
  523. logger.log("PLAYLIST_REMOVE", "SUCCESS", `Successfully removed private playlist "${playlistId}" for user "${userId}".`);
  524. cache.pub('playlist.delete', {userId: userId, playlistId});
  525. return cb({ status: 'success', message: 'Playlist successfully removed' });
  526. });
  527. })
  528. };
  529. module.exports = lib;