playlists.js 19 KB

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