playlists.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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 {Boolean} musicOnly - whether to only add music to the playlist
  274. * @param {Function} cb - gets called with the result
  275. */
  276. addSetToPlaylist: hooks.loginRequired((session, url, playlistId, musicOnly, cb) => {
  277. let videosInPlaylistTotal = 0;
  278. let songsInPlaylistTotal = 0;
  279. let songsSuccess = 0;
  280. let songsFail = 0;
  281. async.waterfall([
  282. (next) => {
  283. utils.getPlaylistFromYouTube(url, musicOnly, (songIds, otherSongIds) => {
  284. if (otherSongIds) {
  285. videosInPlaylistTotal = songIds.length;
  286. songsInPlaylistTotal = otherSongIds.length;
  287. } else {
  288. songsInPlaylistTotal = videosInPlaylistTotal = songIds.length;
  289. }
  290. next(null, songIds);
  291. });
  292. },
  293. (songIds, next) => {
  294. let processed = 0;
  295. function checkDone() {
  296. if (processed === songIds.length) next();
  297. }
  298. for (let s = 0; s < songIds.length; s++) {
  299. lib.addSongToPlaylist(session, songIds[s], playlistId, (res) => {
  300. processed++;
  301. if (res.status === "success") songsSuccess++;
  302. else songsFail++;
  303. checkDone();
  304. });
  305. }
  306. },
  307. (next) => {
  308. playlists.getPlaylist(playlistId, next);
  309. },
  310. (playlist, next) => {
  311. if (!playlist || playlist.createdBy !== session.userId) return next('Playlist not found.');
  312. next(null, playlist);
  313. }
  314. ], async (err, playlist) => {
  315. if (err) {
  316. err = await utils.getError(err);
  317. logger.error("PLAYLIST_IMPORT", `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`);
  318. return cb({ status: 'failure', message: err});
  319. } else {
  320. logger.success("PLAYLIST_IMPORT", `Successfully imported a YouTube playlist to private playlist "${playlistId}" for user "${session.userId}". Videos in playlist: ${videosInPlaylistTotal}, songs in playlist: ${songsInPlaylistTotal}, songs successfully added: ${songsSuccess}, songs failed: ${songsFail}.`);
  321. cb({
  322. status: 'success',
  323. message: 'Playlist has been successfully imported.',
  324. data: playlist.songs,
  325. stats: {
  326. videosInPlaylistTotal,
  327. songsInPlaylistTotal,
  328. songsAddedSuccessfully: songsSuccess,
  329. songsFailedToAdd: songsFail
  330. }
  331. });
  332. }
  333. });
  334. }),
  335. /**
  336. * Removes a song from a private playlist
  337. *
  338. * @param {Object} session - the session object automatically added by socket.io
  339. * @param {String} songId - the id of the song we are removing from the private playlist
  340. * @param {String} playlistId - the id of the playlist we are removing the song from
  341. * @param {Function} cb - gets called with the result
  342. */
  343. removeSongFromPlaylist: hooks.loginRequired((session, songId, playlistId, cb) => {
  344. async.waterfall([
  345. (next) => {
  346. if (!songId || typeof songId !== 'string') return next('Invalid song id.');
  347. if (!playlistId || typeof playlistId !== 'string') return next('Invalid playlist id.');
  348. next();
  349. },
  350. (next) => {
  351. playlists.getPlaylist(playlistId, next);
  352. },
  353. (playlist, next) => {
  354. if (!playlist || playlist.createdBy !== session.userId) return next('Playlist not found');
  355. db.models.playlist.updateOne({_id: playlistId}, {$pull: {songs: {songId: songId}}}, next);
  356. },
  357. (res, next) => {
  358. playlists.updatePlaylist(playlistId, next);
  359. }
  360. ], async (err, playlist) => {
  361. if (err) {
  362. err = await utils.getError(err);
  363. logger.error("PLAYLIST_REMOVE_SONG", `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`);
  364. return cb({ status: 'failure', message: err});
  365. } else {
  366. logger.success("PLAYLIST_REMOVE_SONG", `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${session.userId}".`);
  367. cache.pub('playlist.removeSong', { playlistId: playlist._id, songId: songId, userId: session.userId });
  368. return cb({ status: 'success', message: 'Song has been successfully removed from playlist', data: playlist.songs });
  369. }
  370. });
  371. }),
  372. /**
  373. * Updates the displayName of a private playlist
  374. *
  375. * @param {Object} session - the session object automatically added by socket.io
  376. * @param {String} playlistId - the id of the playlist we are updating the displayName for
  377. * @param {Function} cb - gets called with the result
  378. */
  379. updateDisplayName: hooks.loginRequired((session, playlistId, displayName, cb) => {
  380. async.waterfall([
  381. (next) => {
  382. db.models.playlist.updateOne({ _id: playlistId, createdBy: session.userId }, { $set: { displayName } }, {runValidators: true}, next);
  383. },
  384. (res, next) => {
  385. playlists.updatePlaylist(playlistId, next);
  386. }
  387. ], async (err, playlist) => {
  388. if (err) {
  389. err = await utils.getError(err);
  390. logger.error("PLAYLIST_UPDATE_DISPLAY_NAME", `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`);
  391. return cb({ status: 'failure', message: err});
  392. }
  393. logger.success("PLAYLIST_UPDATE_DISPLAY_NAME", `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`);
  394. cache.pub('playlist.updateDisplayName', {playlistId: playlistId, displayName: displayName, userId: session.userId});
  395. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  396. });
  397. }),
  398. /**
  399. * Moves a song to the top of the list in a private playlist
  400. *
  401. * @param {Object} session - the session object automatically added by socket.io
  402. * @param {String} playlistId - the id of the playlist we are moving the song to the top from
  403. * @param {String} songId - the id of the song we are moving to the top of the list
  404. * @param {Function} cb - gets called with the result
  405. */
  406. moveSongToTop: hooks.loginRequired((session, playlistId, songId, cb) => {
  407. async.waterfall([
  408. (next) => {
  409. playlists.getPlaylist(playlistId, next);
  410. },
  411. (playlist, next) => {
  412. if (!playlist || playlist.createdBy !== session.userId) return next('Playlist not found');
  413. async.each(playlist.songs, (song, next) => {
  414. if (song.songId === songId) return next(song);
  415. next();
  416. }, (err) => {
  417. if (err && err.songId) return next(null, err);
  418. next('Song not found');
  419. });
  420. },
  421. (song, next) => {
  422. db.models.playlist.updateOne({_id: playlistId}, {$pull: {songs: {songId}}}, (err) => {
  423. if (err) return next(err);
  424. return next(null, song);
  425. });
  426. },
  427. (song, next) => {
  428. db.models.playlist.updateOne({_id: playlistId}, {
  429. $push: {
  430. songs: {
  431. $each: [song],
  432. $position: 0
  433. }
  434. }
  435. }, next);
  436. },
  437. (res, next) => {
  438. playlists.updatePlaylist(playlistId, next);
  439. }
  440. ], async (err, playlist) => {
  441. if (err) {
  442. err = await utils.getError(err);
  443. logger.error("PLAYLIST_MOVE_SONG_TO_TOP", `Moving song "${songId}" to the top for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`);
  444. return cb({ status: 'failure', message: err});
  445. }
  446. logger.success("PLAYLIST_MOVE_SONG_TO_TOP", `Successfully moved song "${songId}" to the top for private playlist "${playlistId}" for user "${session.userId}".`);
  447. cache.pub('playlist.moveSongToTop', {playlistId, songId, userId: session.userId});
  448. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  449. });
  450. }),
  451. /**
  452. * Moves a song to the bottom of the list in a private playlist
  453. *
  454. * @param {Object} session - the session object automatically added by socket.io
  455. * @param {String} playlistId - the id of the playlist we are moving the song to the bottom from
  456. * @param {String} songId - the id of the song we are moving to the bottom of the list
  457. * @param {Function} cb - gets called with the result
  458. */
  459. moveSongToBottom: hooks.loginRequired((session, playlistId, songId, cb) => {
  460. async.waterfall([
  461. (next) => {
  462. playlists.getPlaylist(playlistId, next);
  463. },
  464. (playlist, next) => {
  465. if (!playlist || playlist.createdBy !== session.userId) return next('Playlist not found');
  466. async.each(playlist.songs, (song, next) => {
  467. if (song.songId === songId) return next(song);
  468. next();
  469. }, (err) => {
  470. if (err && err.songId) return next(null, err);
  471. next('Song not found');
  472. });
  473. },
  474. (song, next) => {
  475. db.models.playlist.updateOne({_id: playlistId}, {$pull: {songs: {songId}}}, (err) => {
  476. if (err) return next(err);
  477. return next(null, song);
  478. });
  479. },
  480. (song, next) => {
  481. db.models.playlist.updateOne({_id: playlistId}, {
  482. $push: {
  483. songs: song
  484. }
  485. }, next);
  486. },
  487. (res, next) => {
  488. playlists.updatePlaylist(playlistId, next);
  489. }
  490. ], async (err, playlist) => {
  491. if (err) {
  492. err = await utils.getError(err);
  493. logger.error("PLAYLIST_MOVE_SONG_TO_BOTTOM", `Moving song "${songId}" to the bottom for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`);
  494. return cb({ status: 'failure', message: err});
  495. }
  496. logger.success("PLAYLIST_MOVE_SONG_TO_BOTTOM", `Successfully moved song "${songId}" to the bottom for private playlist "${playlistId}" for user "${session.userId}".`);
  497. cache.pub('playlist.moveSongToBottom', {playlistId, songId, userId: session.userId});
  498. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  499. });
  500. }),
  501. /**
  502. * Removes a private playlist
  503. *
  504. * @param {Object} session - the session object automatically added by socket.io
  505. * @param {String} playlistId - the id of the playlist we are moving the song to the top from
  506. * @param {Function} cb - gets called with the result
  507. */
  508. remove: hooks.loginRequired((session, playlistId, cb) => {
  509. async.waterfall([
  510. (next) => {
  511. playlists.deletePlaylist(playlistId, next);
  512. }
  513. ], async (err) => {
  514. if (err) {
  515. err = await utils.getError(err);
  516. logger.error("PLAYLIST_REMOVE", `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`);
  517. return cb({ status: 'failure', message: err});
  518. }
  519. logger.success("PLAYLIST_REMOVE", `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`);
  520. cache.pub('playlist.delete', {userId: session.userId, playlistId});
  521. return cb({ status: 'success', message: 'Playlist successfully removed' });
  522. });
  523. })
  524. };
  525. module.exports = lib;