playlists.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. cb({
  187. status: 'success',
  188. data: playlist
  189. });
  190. });
  191. }),
  192. //TODO Remove this
  193. /**
  194. * Updates a private playlist
  195. *
  196. * @param {Object} session - the session object automatically added by socket.io
  197. * @param {String} playlistId - the id of the playlist we are updating
  198. * @param {Object} playlist - the new private playlist object
  199. * @param {Function} cb - gets called with the result
  200. * @param {String} userId - the userId automatically added by hooks
  201. */
  202. update: hooks.loginRequired((session, playlistId, playlist, cb, userId) => {
  203. async.waterfall([
  204. (next) => {
  205. db.models.playlist.update({ _id: playlistId, createdBy: userId }, playlist, next);
  206. },
  207. (res, next) => {
  208. playlists.updatePlaylist(playlistId, next)
  209. }
  210. ], (err, playlist) => {
  211. if (err) {
  212. let error = 'An error occurred.';
  213. if (typeof err === "string") error = err;
  214. else if (err.message) error = err.message;
  215. logger.log("PLAYLIST_UPDATE", "ERROR", `Updating private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  216. return cb({ status: 'failure', message: error});
  217. }
  218. logger.log("PLAYLIST_UPDATE", "SUCCESS", `Successfully updated private playlist "${playlistId}" for user "${userId}".`);
  219. cb({
  220. status: 'success',
  221. data: playlist
  222. });
  223. });
  224. }),
  225. /**
  226. * Adds a song to a private playlist
  227. *
  228. * @param {Object} session - the session object automatically added by socket.io
  229. * @param {String} songId - the id of the song we are trying to add
  230. * @param {String} playlistId - the id of the playlist we are adding the song to
  231. * @param {Function} cb - gets called with the result
  232. * @param {String} userId - the userId automatically added by hooks
  233. */
  234. addSongToPlaylist: hooks.loginRequired((session, songId, playlistId, cb, userId) => {
  235. async.waterfall([
  236. (next) => {
  237. playlists.getPlaylist(playlistId, (err, playlist) => {
  238. if (err || !playlist || playlist.createdBy !== userId) return next('Something went wrong when trying to get the playlist');
  239. async.each(playlist.songs, (song, next) => {
  240. if (song._id === songId) return next('That song is already in the playlist');
  241. next();
  242. }, next);
  243. });
  244. },
  245. (next) => {
  246. songs.getSong(songId, (err, song) => {
  247. if (err) {
  248. utils.getSongFromYouTube(songId, (song) => {
  249. next(null, song);
  250. });
  251. } else {
  252. next(null, {
  253. _id: songId,
  254. title: song.title,
  255. duration: song.duration
  256. });
  257. }
  258. });
  259. },
  260. (newSong, next) => {
  261. db.models.playlist.update({ _id: playlistId }, { $push: { songs: newSong } }, (err) => {
  262. if (err) return next(err);
  263. playlists.updatePlaylist(playlistId, (err, playlist) => {
  264. next(err, playlist, newSong);
  265. });
  266. });
  267. }
  268. ],
  269. (err, playlist, newSong) => {
  270. if (err) {
  271. let error = 'An error occurred.';
  272. if (typeof err === "string") error = err;
  273. else if (err.message) error = err.message;
  274. logger.log("PLAYLIST_ADD_SONG", "ERROR", `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  275. return cb({ status: 'failure', message: error});
  276. }
  277. logger.log("PLAYLIST_ADD_SONG", "SUCCESS", `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${userId}".`);
  278. cache.pub('playlist.addSong', { playlistId: playlist._id, song: newSong, userId: userId });
  279. return cb({ status: 'success', message: 'Song has been successfully added to the playlist', data: playlist.songs });
  280. });
  281. }),
  282. /**
  283. * Adds a set of songs to a private playlist
  284. *
  285. * @param {Object} session - the session object automatically added by socket.io
  286. * @param {String} url - the url of the the YouTube playlist
  287. * @param {String} playlistId - the id of the playlist we are adding the set of songs to
  288. * @param {Function} cb - gets called with the result
  289. * @param {String} userId - the userId automatically added by hooks
  290. */
  291. addSetToPlaylist: hooks.loginRequired((session, url, playlistId, cb, userId) => {
  292. async.waterfall([
  293. (next) => {
  294. utils.getPlaylistFromYouTube(url, songs => {
  295. next(null, songs);
  296. });
  297. },
  298. (songs, next) => {
  299. let processed = 0;
  300. function checkDone() {
  301. if (processed === songs.length) next();
  302. }
  303. for (let s = 0; sif (playlist.song < songs.length; s++) {
  304. lib.addSongToPlaylist(session, songs[s].contentDetails.videoId, playlistId, () => {
  305. processed++;
  306. checkDone();
  307. });
  308. }
  309. },
  310. (next) => {
  311. playlists.getPlaylist(playlistId, next);
  312. },
  313. (playlist, next) => {
  314. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found.');
  315. next(null, playlist);
  316. }
  317. ], (err, playlist) => {
  318. if (err) {
  319. let error = 'An error occurred.';
  320. if (typeof err === "string") error = err;
  321. else if (err.message) error = err.message;
  322. logger.log("PLAYLIST_IMPORT", "ERROR", `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  323. return cb({ status: 'failure', message: error});
  324. }
  325. logger.log("PLAYLIST_IMPORT", "SUCCESS", `Successfully imported a YouTube playlist to private playlist "${playlistId}" for user "${userId}".`);
  326. cb({ status: 'success', message: 'Playlist has been successfully imported.', data: playlist.songs });
  327. });
  328. }),
  329. /**
  330. * Removes a song from a private playlist
  331. *
  332. * @param {Object} session - the session object automatically added by socket.io
  333. * @param {String} songId - the id of the song we are removing from the private playlist
  334. * @param {String} playlistId - the id of the playlist we are removing the song from
  335. * @param {Function} cb - gets called with the result
  336. * @param {String} userId - the userId automatically added by hooks
  337. */
  338. removeSongFromPlaylist: hooks.loginRequired((session, songId, playlistId, cb, userId) => {
  339. async.waterfall([
  340. (next) => {
  341. playlists.getPlaylist(playlistId, next);
  342. },
  343. (playlist, next) => {
  344. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  345. db.models.update({_id: playlistId}, {$pull: {songs: songId}}, next);
  346. },
  347. (res, next) => {
  348. playlists.updatePlaylist(playlistId, next);
  349. }
  350. ], (err, playlist) => {
  351. if (err) {
  352. let error = 'An error occurred.';
  353. if (typeof err === "string") error = err;
  354. else if (err.message) error = err.message;
  355. logger.log("PLAYLIST_REMOVE_SONG", "ERROR", `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  356. return cb({ status: 'failure', message: error});
  357. }
  358. logger.log("PLAYLIST_REMOVE_SONG", "SUCCESS", `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${userId}".`);
  359. cache.pub('playlist.removeSong', {playlistId: playlist._id, songId: songId, userId: userId});
  360. return cb({ status: 'success', message: 'Song has been successfully removed from playlist', data: playlist.songs });
  361. });
  362. }),
  363. /**
  364. * Updates the displayName of a private playlist
  365. *
  366. * @param {Object} session - the session object automatically added by socket.io
  367. * @param {String} playlistId - the id of the playlist we are updating the displayName for
  368. * @param {Function} cb - gets called with the result
  369. * @param {String} userId - the userId automatically added by hooks
  370. */
  371. updateDisplayName: hooks.loginRequired((session, playlistId, displayName, cb, userId) => {
  372. async.waterfall([
  373. (next) => {
  374. db.models.playlist.update({ _id: playlistId, createdBy: userId }, { $set: displayName }, next);
  375. },
  376. (res, next) => {
  377. playlists.updatePlaylist(playlistId, next);
  378. }
  379. ], (err, playlist) => {
  380. if (err) {
  381. let error = 'An error occurred.';
  382. if (typeof err === "string") error = err;
  383. else if (err.message) error = err.message;
  384. logger.log("PLAYLIST_UPDATE_DISPLAY_NAME", "ERROR", `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  385. return cb({ status: 'failure', message: error});
  386. }
  387. logger.log("PLAYLIST_UPDATE_DISPLAY_NAME", "SUCCESS", `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${userId}".`);
  388. cache.pub('playlist.updateDisplayName', {playlistId: playlistId, displayName: displayName, userId: userId});
  389. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  390. });
  391. }),
  392. /**
  393. * Moves a song to the top of the list in a private playlist
  394. *
  395. * @param {Object} session - the session object automatically added by socket.io
  396. * @param {String} playlistId - the id of the playlist we are moving the song to the top from
  397. * @param {String} songId - the id of the song we are moving to the top of the list
  398. * @param {Function} cb - gets called with the result
  399. * @param {String} userId - the userId automatically added by hooks
  400. */
  401. moveSongToTop: hooks.loginRequired((session, playlistId, songId, cb, userId) => {
  402. async.waterfall([
  403. (next) => {
  404. playlists.getPlaylist(playlistId, next);
  405. },
  406. (playlist, next) => {
  407. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  408. async.each(playlist.songs, (song) => {
  409. if (song._id === songId) return next(true, song);
  410. next();
  411. }, (err, song) => {
  412. if (err === true) return next(null, song);
  413. next('Song not found');
  414. });
  415. },
  416. (song, next) => {
  417. db.models.playlist.update({_id: playlistId}, {$pull: {songs: {_id: songId}}}, (err) => {
  418. if (err) return next(err);
  419. return next(null, song);
  420. });
  421. },
  422. (song, next) => {
  423. db.models.playlist.update({_id: playlistId}, {
  424. $push: {
  425. songs: {
  426. $each: [song],
  427. $position: 0
  428. }
  429. }
  430. }, next);
  431. },
  432. (res, next) => {
  433. playlists.updatePlaylist(playlistId, next);
  434. }
  435. ], (err, playlist) => {
  436. if (err) {
  437. let error = 'An error occurred.';
  438. if (typeof err === "string") error = err;
  439. else if (err.message) error = err.message;
  440. logger.log("PLAYLIST_MOVE_SONG_TO_TOP", "ERROR", `Moving song "${songId}" to the top for private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  441. return cb({ status: 'failure', message: error});
  442. }
  443. logger.log("PLAYLIST_MOVE_SONG_TO_TOP", "SUCCESS", `Successfully moved song "${songId}" to the top for private playlist "${playlistId}" for user "${userId}".`);
  444. cache.pub('playlist.moveSongToTop', {playlistId, songId, userId: userId});
  445. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  446. });
  447. }),
  448. /**
  449. * Moves a song to the bottom of the list in a private playlist
  450. *
  451. * @param {Object} session - the session object automatically added by socket.io
  452. * @param {String} playlistId - the id of the playlist we are moving the song to the bottom from
  453. * @param {String} songId - the id of the song we are moving to the bottom of the list
  454. * @param {Function} cb - gets called with the result
  455. * @param {String} userId - the userId automatically added by hooks
  456. */
  457. moveSongToBottom: hooks.loginRequired((session, playlistId, songId, cb, userId) => {
  458. async.waterfall([
  459. (next) => {
  460. playlists.getPlaylist(playlistId, next);
  461. },
  462. (playlist, next) => {
  463. if (!playlist || playlist.createdBy !== userId) return next('Playlist not found');
  464. async.each(playlist.songs, (song) => {
  465. if (song._id === songId) return next(true, song);
  466. next();
  467. }, (err, song) => {
  468. if (err === true) return next(null, song);
  469. next('Song not found');
  470. });
  471. },
  472. (song, next) => {
  473. db.models.playlist.update({_id: playlistId}, {$pull: {songs: {_id: songId}}}, (err) => {
  474. if (err) return next(err);
  475. return next(null, song);
  476. });
  477. },
  478. (song, next) => {
  479. db.models.playlist.update({_id: playlistId}, {
  480. $push: {
  481. songs: {
  482. song
  483. }
  484. }
  485. }, next);
  486. },
  487. (res, next) => {
  488. playlists.updatePlaylist(playlistId, next);
  489. }
  490. ], (err, playlist) => {
  491. if (err) {
  492. let error = 'An error occurred.';
  493. if (typeof err === "string") error = err;
  494. else if (err.message) error = err.message;
  495. logger.log("PLAYLIST_MOVE_SONG_TO_BOTTOM", "ERROR", `Moving song "${songId}" to the bottom for private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  496. return cb({ status: 'failure', message: error});
  497. }
  498. logger.log("PLAYLIST_MOVE_SONG_TO_BOTTOM", "SUCCESS", `Successfully moved song "${songId}" to the bottom for private playlist "${playlistId}" for user "${userId}".`);
  499. cache.pub('playlist.moveSongToBottom', {playlistId, songId, userId: userId});
  500. return cb({ status: 'success', message: 'Playlist has been successfully updated' });
  501. });
  502. }),
  503. /**
  504. * Removes a song from a private playlist
  505. *
  506. * @param {Object} session - the session object automatically added by socket.io
  507. * @param {String} playlistId - the id of the playlist we are moving the song to the top from
  508. * @param {Function} cb - gets called with the result
  509. * @param {String} userId - the userId automatically added by hooks
  510. */
  511. remove: hooks.loginRequired((session, playlistId, cb, userId) => {
  512. async.waterfall([
  513. (next) => {
  514. playlists.deletePlaylist(playlistId, next);
  515. }
  516. ], (err) => {
  517. if (err) {
  518. let error = 'An error occurred.';
  519. if (typeof err === "string") error = err;
  520. else if (err.message) error = err.message;
  521. logger.log("PLAYLIST_REMOVE", "ERROR", `Removing private playlist "${playlistId}" failed for user "${userId}". "${error}"`);
  522. return cb({ status: 'failure', message: error});
  523. }
  524. logger.log("PLAYLIST_REMOVE", "SUCCESS", `Successfully removed private playlist "${playlistId}" for user "${userId}".`);
  525. cache.pub('playlist.delete', {userId: userId, playlistId});
  526. return cb({ status: 'success', message: 'Playlist successfully removed' });
  527. });
  528. })
  529. };
  530. module.exports = lib;