playlists.js 19 KB

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