playlists.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. import async from "async";
  2. import { isLoginRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const IOModule = moduleManager.modules.io;
  7. const SongsModule = moduleManager.modules.songs;
  8. const CacheModule = moduleManager.modules.cache;
  9. const PlaylistsModule = moduleManager.modules.playlists;
  10. const YouTubeModule = moduleManager.modules.youtube;
  11. const ActivitiesModule = moduleManager.modules.activities;
  12. CacheModule.runJob("SUB", {
  13. channel: "playlist.create",
  14. cb: playlist => {
  15. IOModule.runJob("SOCKETS_FROM_USER", { userId: playlist.createdBy }, this).then(response => {
  16. response.sockets.forEach(socket => {
  17. socket.emit("event:playlist.create", playlist);
  18. });
  19. });
  20. if (playlist.privacy === "public")
  21. IOModule.runJob("EMIT_TO_ROOM", {
  22. room: `profile-${playlist.createdBy}`,
  23. args: ["event:playlist.create", playlist]
  24. });
  25. }
  26. });
  27. CacheModule.runJob("SUB", {
  28. channel: "playlist.delete",
  29. cb: res => {
  30. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  31. response.sockets.forEach(socket => {
  32. socket.emit("event:playlist.delete", res.playlistId);
  33. });
  34. });
  35. IOModule.runJob("EMIT_TO_ROOM", {
  36. room: `profile-${res.userId}`,
  37. args: ["event:playlist.delete", res.playlistId]
  38. });
  39. }
  40. });
  41. CacheModule.runJob("SUB", {
  42. channel: "playlist.repositionSongs",
  43. cb: res => {
  44. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response =>
  45. response.sockets.forEach(socket =>
  46. socket.emit("event:playlist.repositionSongs", {
  47. playlistId: res.playlistId,
  48. songsBeingChanged: res.songsBeingChanged
  49. })
  50. )
  51. );
  52. }
  53. });
  54. CacheModule.runJob("SUB", {
  55. channel: "playlist.addSong",
  56. cb: res => {
  57. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  58. response.sockets.forEach(socket => {
  59. socket.emit("event:playlist.addSong", {
  60. playlistId: res.playlistId,
  61. song: res.song
  62. });
  63. });
  64. });
  65. if (res.privacy === "public")
  66. IOModule.runJob("EMIT_TO_ROOM", {
  67. room: `profile-${res.userId}`,
  68. args: [
  69. "event:playlist.addSong",
  70. {
  71. playlistId: res.playlistId,
  72. song: res.song
  73. }
  74. ]
  75. });
  76. }
  77. });
  78. CacheModule.runJob("SUB", {
  79. channel: "playlist.removeSong",
  80. cb: res => {
  81. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  82. response.sockets.forEach(socket => {
  83. socket.emit("event:playlist.removeSong", {
  84. playlistId: res.playlistId,
  85. songId: res.songId
  86. });
  87. });
  88. });
  89. if (res.privacy === "public")
  90. IOModule.runJob("EMIT_TO_ROOM", {
  91. room: `profile-${res.userId}`,
  92. args: [
  93. "event:playlist.removeSong",
  94. {
  95. playlistId: res.playlistId,
  96. songId: res.songId
  97. }
  98. ]
  99. });
  100. }
  101. });
  102. CacheModule.runJob("SUB", {
  103. channel: "playlist.updateDisplayName",
  104. cb: res => {
  105. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  106. response.sockets.forEach(socket => {
  107. socket.emit("event:playlist.updateDisplayName", {
  108. playlistId: res.playlistId,
  109. displayName: res.displayName
  110. });
  111. });
  112. });
  113. if (res.privacy === "public")
  114. IOModule.runJob("EMIT_TO_ROOM", {
  115. room: `profile-${res.userId}`,
  116. args: [
  117. "event:playlist.updateDisplayName",
  118. {
  119. playlistId: res.playlistId,
  120. displayName: res.displayName
  121. }
  122. ]
  123. });
  124. }
  125. });
  126. CacheModule.runJob("SUB", {
  127. channel: "playlist.updatePrivacy",
  128. cb: res => {
  129. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  130. response.sockets.forEach(socket => {
  131. socket.emit("event:playlist.updatePrivacy");
  132. });
  133. });
  134. if (res.playlist.privacy === "public")
  135. return IOModule.runJob("EMIT_TO_ROOM", {
  136. room: `profile-${res.userId}`,
  137. args: ["event:playlist.create", res.playlist]
  138. });
  139. return IOModule.runJob("EMIT_TO_ROOM", {
  140. room: `profile-${res.userId}`,
  141. args: ["event:playlist.delete", res.playlist._id]
  142. });
  143. }
  144. });
  145. export default {
  146. /**
  147. * Gets the first song from a private playlist
  148. *
  149. * @param {object} session - the session object automatically added by socket.io
  150. * @param {string} playlistId - the id of the playlist we are getting the first song from
  151. * @param {Function} cb - gets called with the result
  152. */
  153. getFirstSong: isLoginRequired(function getFirstSong(session, playlistId, cb) {
  154. async.waterfall(
  155. [
  156. next => {
  157. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  158. .then(playlist => {
  159. next(null, playlist);
  160. })
  161. .catch(next);
  162. },
  163. (playlist, next) => {
  164. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  165. return next(null, playlist.songs[0]);
  166. }
  167. ],
  168. async (err, song) => {
  169. if (err) {
  170. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  171. this.log(
  172. "ERROR",
  173. "PLAYLIST_GET_FIRST_SONG",
  174. `Getting the first song of playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  175. );
  176. return cb({ status: "failure", message: err });
  177. }
  178. this.log(
  179. "SUCCESS",
  180. "PLAYLIST_GET_FIRST_SONG",
  181. `Successfully got the first song of playlist "${playlistId}" for user "${session.userId}".`
  182. );
  183. return cb({
  184. status: "success",
  185. song
  186. });
  187. }
  188. );
  189. }),
  190. /**
  191. * Gets a list of all the playlists for a specific user
  192. *
  193. * @param {object} session - the session object automatically added by socket.io
  194. * @param {string} userId - the user id in question
  195. * @param {Function} cb - gets called with the result
  196. */
  197. indexForUser: async function indexForUser(session, userId, cb) {
  198. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  199. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  200. async.waterfall(
  201. [
  202. next => {
  203. userModel.findById(userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  204. },
  205. ({ preferences }, next) => {
  206. const { orderOfPlaylists } = preferences;
  207. const match = {
  208. createdBy: userId
  209. };
  210. // if a playlist order exists
  211. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  212. playlistModel
  213. .aggregate()
  214. .match(match)
  215. .addFields({
  216. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  217. })
  218. .sort({ weight: 1 })
  219. .exec(next);
  220. },
  221. (playlists, next) => {
  222. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  223. const filteredPlaylists = [];
  224. return async.each(
  225. playlists,
  226. (playlist, nextPlaylist) => {
  227. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  228. return nextPlaylist();
  229. },
  230. () => next(null, filteredPlaylists)
  231. );
  232. }
  233. ],
  234. async (err, playlists) => {
  235. if (err) {
  236. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  237. this.log(
  238. "ERROR",
  239. "PLAYLIST_INDEX_FOR_USER",
  240. `Indexing playlists for user "${userId}" failed. "${err}"`
  241. );
  242. return cb({ status: "failure", message: err });
  243. }
  244. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  245. return cb({
  246. status: "success",
  247. data: playlists
  248. });
  249. }
  250. );
  251. },
  252. /**
  253. * Gets all playlists for the user requesting it
  254. *
  255. * @param {object} session - the session object automatically added by socket.io
  256. * @param {boolean} showNonModifiablePlaylists - whether or not to show non modifiable playlists e.g. liked songs
  257. * @param {Function} cb - gets called with the result
  258. */
  259. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, showNonModifiablePlaylists, cb) {
  260. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  261. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  262. async.waterfall(
  263. [
  264. next => {
  265. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  266. },
  267. ({ preferences }, next) => {
  268. const { orderOfPlaylists } = preferences;
  269. const match = {
  270. createdBy: session.userId
  271. };
  272. // if non modifiable playlists should be shown as well
  273. if (!showNonModifiablePlaylists) match.isUserModifiable = true;
  274. // if a playlist order exists
  275. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  276. playlistModel
  277. .aggregate()
  278. .match(match)
  279. .addFields({
  280. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  281. })
  282. .sort({ weight: 1 })
  283. .exec(next);
  284. }
  285. ],
  286. async (err, playlists) => {
  287. if (err) {
  288. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  289. this.log(
  290. "ERROR",
  291. "PLAYLIST_INDEX_FOR_ME",
  292. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  293. );
  294. return cb({ status: "failure", message: err });
  295. }
  296. this.log(
  297. "SUCCESS",
  298. "PLAYLIST_INDEX_FOR_ME",
  299. `Successfully indexed playlists for user "${session.userId}".`
  300. );
  301. return cb({
  302. status: "success",
  303. data: playlists
  304. });
  305. }
  306. );
  307. }),
  308. /**
  309. * Creates a new private playlist
  310. *
  311. * @param {object} session - the session object automatically added by socket.io
  312. * @param {object} data - the data for the new private playlist
  313. * @param {Function} cb - gets called with the result
  314. */
  315. create: isLoginRequired(async function create(session, data, cb) {
  316. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  317. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  318. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  319. async.waterfall(
  320. [
  321. next => (data ? next() : cb({ status: "failure", message: "Invalid data" })),
  322. next => {
  323. const { displayName, songs } = data;
  324. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  325. return next("That playlist name is blacklisted. Please use a different name.");
  326. return playlistModel.create(
  327. {
  328. displayName,
  329. songs,
  330. createdBy: session.userId,
  331. createdAt: Date.now()
  332. },
  333. next
  334. );
  335. },
  336. (playlist, next) => {
  337. userModel.updateOne(
  338. { _id: session.userId },
  339. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  340. err => {
  341. if (err) return next(err);
  342. return next(null, playlist);
  343. }
  344. );
  345. }
  346. ],
  347. async (err, playlist) => {
  348. if (err) {
  349. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  350. this.log(
  351. "ERROR",
  352. "PLAYLIST_CREATE",
  353. `Creating private playlist failed for user "${session.userId}". "${err}"`
  354. );
  355. return cb({ status: "failure", message: err });
  356. }
  357. CacheModule.runJob("PUB", {
  358. channel: "playlist.create",
  359. value: playlist
  360. });
  361. ActivitiesModule.runJob("ADD_ACTIVITY", {
  362. userId: session.userId,
  363. activityType: "created_playlist",
  364. payload: [playlist._id]
  365. });
  366. this.log(
  367. "SUCCESS",
  368. "PLAYLIST_CREATE",
  369. `Successfully created private playlist for user "${session.userId}".`
  370. );
  371. return cb({
  372. status: "success",
  373. message: "Successfully created playlist",
  374. data: {
  375. _id: playlist._id
  376. }
  377. });
  378. }
  379. );
  380. }),
  381. /**
  382. * Gets a playlist from id
  383. *
  384. * @param {object} session - the session object automatically added by socket.io
  385. * @param {string} playlistId - the id of the playlist we are getting
  386. * @param {Function} cb - gets called with the result
  387. */
  388. getPlaylist: isLoginRequired(function getPlaylist(session, playlistId, cb) {
  389. async.waterfall(
  390. [
  391. next => {
  392. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  393. .then(playlist => {
  394. next(null, playlist);
  395. })
  396. .catch(next);
  397. },
  398. (playlist, next) => {
  399. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  400. return next(null, playlist);
  401. }
  402. ],
  403. async (err, playlist) => {
  404. if (err) {
  405. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  406. this.log(
  407. "ERROR",
  408. "PLAYLIST_GET",
  409. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  410. );
  411. return cb({ status: "failure", message: err });
  412. }
  413. const sortedSongs = playlist.songs.sort((a, b) => a.position - b.position);
  414. playlist.songs = sortedSongs;
  415. this.log(
  416. "SUCCESS",
  417. "PLAYLIST_GET",
  418. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  419. );
  420. return cb({
  421. status: "success",
  422. data: playlist
  423. });
  424. }
  425. );
  426. }),
  427. /**
  428. * Obtains basic metadata of a playlist in order to format an activity
  429. *
  430. * @param {object} session - the session object automatically added by socket.io
  431. * @param {string} playlistId - the playlist id
  432. * @param {Function} cb - callback
  433. */
  434. getPlaylistForActivity(session, playlistId, cb) {
  435. async.waterfall(
  436. [
  437. next => {
  438. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  439. .then(playlist => {
  440. next(null, playlist);
  441. })
  442. .catch(next);
  443. }
  444. ],
  445. async (err, playlist) => {
  446. if (err) {
  447. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  448. this.log(
  449. "ERROR",
  450. "PLAYLISTS_GET_PLAYLIST_FOR_ACTIVITY",
  451. `Failed to obtain metadata of playlist ${playlistId} for activity formatting. "${err}"`
  452. );
  453. return cb({ status: "failure", message: err });
  454. }
  455. this.log(
  456. "SUCCESS",
  457. "PLAYLISTS_GET_PLAYLIST_FOR_ACTIVITY",
  458. `Obtained metadata of playlist ${playlistId} for activity formatting successfully.`
  459. );
  460. return cb({
  461. status: "success",
  462. data: {
  463. title: playlist.displayName
  464. }
  465. });
  466. }
  467. );
  468. },
  469. // TODO Remove this
  470. /**
  471. * Updates a private playlist
  472. *
  473. * @param {object} session - the session object automatically added by socket.io
  474. * @param {string} playlistId - the id of the playlist we are updating
  475. * @param {object} playlist - the new private playlist object
  476. * @param {Function} cb - gets called with the result
  477. */
  478. update: isLoginRequired(async function update(session, playlistId, playlist, cb) {
  479. const playlistModel = await DBModule.runJob(
  480. "GET_MODEL",
  481. {
  482. modelName: "playlist"
  483. },
  484. this
  485. );
  486. async.waterfall(
  487. [
  488. next => {
  489. playlistModel.updateOne(
  490. { _id: playlistId, createdBy: session.userId },
  491. playlist,
  492. { runValidators: true },
  493. next
  494. );
  495. },
  496. (res, next) => {
  497. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  498. .then(playlist => {
  499. next(null, playlist);
  500. })
  501. .catch(next);
  502. }
  503. ],
  504. async (err, playlist) => {
  505. if (err) {
  506. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  507. this.log(
  508. "ERROR",
  509. "PLAYLIST_UPDATE",
  510. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  511. );
  512. return cb({ status: "failure", message: err });
  513. }
  514. this.log(
  515. "SUCCESS",
  516. "PLAYLIST_UPDATE",
  517. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  518. );
  519. return cb({
  520. status: "success",
  521. data: playlist
  522. });
  523. }
  524. );
  525. }),
  526. /**
  527. * Shuffles songs in a private playlist
  528. *
  529. * @param {object} session - the session object automatically added by socket.io
  530. * @param {string} playlistId - the id of the playlist we are updating
  531. * @param {Function} cb - gets called with the result
  532. */
  533. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  534. const playlistModel = await DBModule.runJob(
  535. "GET_MODEL",
  536. {
  537. modelName: "playlist"
  538. },
  539. this
  540. );
  541. async.waterfall(
  542. [
  543. next => {
  544. if (!playlistId) return next("No playlist id.");
  545. return playlistModel.findById(playlistId, next);
  546. },
  547. (playlist, next) => {
  548. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  549. return UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  550. .then(result => next(null, result.array))
  551. .catch(next);
  552. },
  553. (songs, next) => {
  554. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  555. },
  556. (res, next) => {
  557. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  558. .then(playlist => {
  559. next(null, playlist);
  560. })
  561. .catch(next);
  562. }
  563. ],
  564. async (err, playlist) => {
  565. if (err) {
  566. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  567. this.log(
  568. "ERROR",
  569. "PLAYLIST_SHUFFLE",
  570. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  571. );
  572. return cb({ status: "failure", message: err });
  573. }
  574. this.log(
  575. "SUCCESS",
  576. "PLAYLIST_SHUFFLE",
  577. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  578. );
  579. return cb({
  580. status: "success",
  581. message: "Successfully shuffled playlist.",
  582. data: playlist
  583. });
  584. }
  585. );
  586. }),
  587. /**
  588. * Changes the order of song(s) in a private playlist
  589. *
  590. * @param {object} session - the session object automatically added by socket.io
  591. * @param {string} playlistId - the id of the playlist we are targeting
  592. * @param {Array} songsBeingChanged - the songs to be repositioned, each element contains "songId" and "position" properties
  593. * @param {Function} cb - gets called with the result
  594. */
  595. repositionSongs: isLoginRequired(async function repositionSongs(session, playlistId, songsBeingChanged, cb) {
  596. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  597. async.waterfall(
  598. [
  599. // get current playlist object (before changes)
  600. next =>
  601. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  602. .then(playlist => next(null, playlist))
  603. .catch(next),
  604. (playlist, next) => {
  605. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  606. return next(null);
  607. },
  608. // update playlist object with each song's new position
  609. next =>
  610. async.each(
  611. songsBeingChanged,
  612. (song, nextSong) =>
  613. playlistModel.updateOne(
  614. { _id: playlistId, "songs.songId": song.songId },
  615. {
  616. $set: {
  617. "songs.$.position": song.position
  618. }
  619. },
  620. err => {
  621. if (err) return next(err);
  622. return nextSong();
  623. }
  624. ),
  625. next
  626. ),
  627. // update the cache with the new songs positioning
  628. next => {
  629. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  630. .then(playlist => next(null, playlist))
  631. .catch(next);
  632. }
  633. ],
  634. async err => {
  635. if (err) {
  636. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  637. this.log(
  638. "ERROR",
  639. "PLAYLIST_REPOSITION_SONGS",
  640. `Repositioning songs for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  641. );
  642. return cb({ status: "failure", message: err });
  643. }
  644. this.log(
  645. "SUCCESS",
  646. "PLAYLIST_REPOSITION_SONGS",
  647. `Successfully repositioned songs for private playlist "${playlistId}" for user "${session.userId}".`
  648. );
  649. CacheModule.runJob("PUB", {
  650. channel: "playlist.repositionSongs",
  651. value: {
  652. userId: session.userId,
  653. playlistId,
  654. songsBeingChanged
  655. }
  656. });
  657. return cb({
  658. status: "success",
  659. message: "Order of songs successfully updated"
  660. });
  661. }
  662. );
  663. }),
  664. /**
  665. * Moves a song to the bottom of the list in a private playlist
  666. *
  667. * @param {object} session - the session object automatically added by socket.io
  668. * @param {string} playlistId - the id of the playlist we are moving the song to the bottom from
  669. * @param {string} songId - the id of the song we are moving to the bottom of the list
  670. * @param {Function} cb - gets called with the result
  671. */
  672. moveSongToBottom: isLoginRequired(async function moveSongToBottom(session, playlistId, songId, cb) {
  673. async.waterfall(
  674. [
  675. next => {
  676. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  677. .then(playlist => next(null, playlist))
  678. .catch(next);
  679. },
  680. (playlist, next) => {
  681. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  682. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  683. // sort array by position
  684. playlist.songs.sort((a, b) => a.position - b.position);
  685. // find index of songId
  686. playlist.songs.forEach((song, index) => {
  687. // reorder array (simulates what would be done with a drag and drop interface)
  688. if (song.songId === songId)
  689. playlist.songs.splice(playlist.songs.length, 0, playlist.songs.splice(index, 1)[0]);
  690. });
  691. const songsBeingChanged = [];
  692. playlist.songs.forEach((song, index) => {
  693. // check if position needs updated based on index
  694. if (song.position !== index + 1)
  695. songsBeingChanged.push({
  696. songId: song.songId,
  697. position: index + 1
  698. });
  699. });
  700. // update position property on songs that need to be changed
  701. return IOModule.runJob(
  702. "RUN_ACTION2",
  703. {
  704. session,
  705. namespace: "playlists",
  706. action: "repositionSongs",
  707. args: [playlistId, songsBeingChanged]
  708. },
  709. this
  710. )
  711. .then(res => {
  712. if (res.status === "success") return next();
  713. return next("Unable to reposition song in playlist.");
  714. })
  715. .catch(next);
  716. }
  717. ],
  718. async err => {
  719. if (err) {
  720. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  721. this.log(
  722. "ERROR",
  723. "PLAYLIST_MOVE_SONG_TO_BOTTOM",
  724. `Moving song "${songId}" to the bottom for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  725. );
  726. return cb({ status: "failure", message: err });
  727. }
  728. this.log(
  729. "SUCCESS",
  730. "PLAYLIST_MOVE_SONG_TO_BOTTOM",
  731. `Successfully moved song "${songId}" to the bottom for private playlist "${playlistId}" for user "${session.userId}".`
  732. );
  733. return cb({
  734. status: "success",
  735. message: "Order of songs successfully updated"
  736. });
  737. }
  738. );
  739. }),
  740. /**
  741. * Adds a song to a private playlist
  742. *
  743. * @param {object} session - the session object automatically added by socket.io
  744. * @param {boolean} isSet - is the song part of a set of songs to be added
  745. * @param {string} songId - the id of the song we are trying to add
  746. * @param {string} playlistId - the id of the playlist we are adding the song to
  747. * @param {Function} cb - gets called with the result
  748. */
  749. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, songId, playlistId, cb) {
  750. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  751. async.waterfall(
  752. [
  753. next => {
  754. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  755. .then(playlist => {
  756. if (!playlist || playlist.createdBy !== session.userId)
  757. return next("Something went wrong when trying to get the playlist");
  758. return async.each(
  759. playlist.songs,
  760. (song, nextSong) => {
  761. if (song.songId === songId) return next("That song is already in the playlist");
  762. return nextSong();
  763. },
  764. err => next(err, playlist.songs.length + 1)
  765. );
  766. })
  767. .catch(next);
  768. },
  769. (position, next) => {
  770. SongsModule.runJob("GET_SONG", { id: songId }, this)
  771. .then(response => {
  772. const { song } = response;
  773. next(null, {
  774. _id: song._id,
  775. songId,
  776. title: song.title,
  777. duration: song.duration,
  778. position
  779. });
  780. })
  781. .catch(() => {
  782. YouTubeModule.runJob("GET_SONG", { songId }, this)
  783. .then(response => next(null, { ...response.song, position }))
  784. .catch(next);
  785. });
  786. },
  787. (newSong, next) => {
  788. playlistModel.updateOne(
  789. { _id: playlistId },
  790. { $push: { songs: newSong } },
  791. { runValidators: true },
  792. err => {
  793. if (err) return next(err);
  794. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  795. .then(playlist => next(null, playlist, newSong))
  796. .catch(next);
  797. }
  798. );
  799. }
  800. ],
  801. async (err, playlist, newSong) => {
  802. if (err) {
  803. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  804. this.log(
  805. "ERROR",
  806. "PLAYLIST_ADD_SONG",
  807. `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  808. );
  809. return cb({ status: "failure", message: err });
  810. }
  811. this.log(
  812. "SUCCESS",
  813. "PLAYLIST_ADD_SONG",
  814. `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${session.userId}".`
  815. );
  816. if (!isSet)
  817. ActivitiesModule.runJob("ADD_ACTIVITY", {
  818. userId: session.userId,
  819. activityType: "added_song_to_playlist",
  820. payload: [{ songId, playlistId }]
  821. });
  822. CacheModule.runJob("PUB", {
  823. channel: "playlist.addSong",
  824. value: {
  825. playlistId: playlist._id,
  826. song: newSong,
  827. userId: session.userId,
  828. privacy: playlist.privacy
  829. }
  830. });
  831. return cb({
  832. status: "success",
  833. message: "Song has been successfully added to the playlist",
  834. data: playlist.songs
  835. });
  836. }
  837. );
  838. }),
  839. /**
  840. * Adds a set of songs to a private playlist
  841. *
  842. * @param {object} session - the session object automatically added by socket.io
  843. * @param {string} url - the url of the the YouTube playlist
  844. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  845. * @param {boolean} musicOnly - whether to only add music to the playlist
  846. * @param {Function} cb - gets called with the result
  847. */
  848. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  849. let videosInPlaylistTotal = 0;
  850. let songsInPlaylistTotal = 0;
  851. let addSongsStats = null;
  852. const addedSongs = [];
  853. async.waterfall(
  854. [
  855. next => {
  856. YouTubeModule.runJob(
  857. "GET_PLAYLIST",
  858. {
  859. url,
  860. musicOnly
  861. },
  862. this
  863. ).then(response => {
  864. if (response.filteredSongs) {
  865. videosInPlaylistTotal = response.songs.length;
  866. songsInPlaylistTotal = response.filteredSongs.length;
  867. } else {
  868. songsInPlaylistTotal = videosInPlaylistTotal = response.songs.length;
  869. }
  870. next(null, response.songs);
  871. });
  872. },
  873. (songIds, next) => {
  874. let successful = 0;
  875. let failed = 0;
  876. let alreadyInPlaylist = 0;
  877. if (songIds.length === 0) next();
  878. async.eachLimit(
  879. songIds,
  880. 1,
  881. (songId, next) => {
  882. IOModule.runJob(
  883. "RUN_ACTION2",
  884. {
  885. session,
  886. namespace: "playlists",
  887. action: "addSongToPlaylist",
  888. args: [true, songId, playlistId]
  889. },
  890. this
  891. )
  892. .then(res => {
  893. if (res.status === "success") {
  894. successful += 1;
  895. addedSongs.push(songId);
  896. } else failed += 1;
  897. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  898. })
  899. .catch(() => {
  900. failed += 1;
  901. })
  902. .finally(() => {
  903. next();
  904. });
  905. },
  906. () => {
  907. addSongsStats = { successful, failed, alreadyInPlaylist };
  908. next(null);
  909. }
  910. );
  911. },
  912. next => {
  913. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  914. .then(playlist => {
  915. next(null, playlist);
  916. })
  917. .catch(next);
  918. },
  919. (playlist, next) => {
  920. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  921. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  922. return next(null, playlist);
  923. }
  924. ],
  925. async (err, playlist) => {
  926. if (err) {
  927. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  928. this.log(
  929. "ERROR",
  930. "PLAYLIST_IMPORT",
  931. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  932. );
  933. return cb({ status: "failure", message: err });
  934. }
  935. ActivitiesModule.runJob("ADD_ACTIVITY", {
  936. userId: session.userId,
  937. activityType: "added_songs_to_playlist",
  938. payload: addedSongs
  939. });
  940. this.log(
  941. "SUCCESS",
  942. "PLAYLIST_IMPORT",
  943. `Successfully imported a YouTube playlist to private playlist "${playlistId}" for user "${session.userId}". Videos in playlist: ${videosInPlaylistTotal}, songs in playlist: ${songsInPlaylistTotal}, songs successfully added: ${addSongsStats.successful}, songs failed: ${addSongsStats.failed}, already in playlist: ${addSongsStats.alreadyInPlaylist}.`
  944. );
  945. return cb({
  946. status: "success",
  947. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  948. data: playlist.songs,
  949. stats: {
  950. videosInPlaylistTotal,
  951. songsInPlaylistTotal
  952. }
  953. });
  954. }
  955. );
  956. }),
  957. /**
  958. * Removes a song from a private playlist
  959. *
  960. * @param {object} session - the session object automatically added by socket.io
  961. * @param {string} songId - the id of the song we are removing from the private playlist
  962. * @param {string} playlistId - the id of the playlist we are removing the song from
  963. * @param {Function} cb - gets called with the result
  964. */
  965. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, songId, playlistId, cb) {
  966. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  967. async.waterfall(
  968. [
  969. next => {
  970. if (!songId || typeof songId !== "string") return next("Invalid song id.");
  971. if (!playlistId) return next("Invalid playlist id.");
  972. return next();
  973. },
  974. next => {
  975. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  976. .then(playlist => next(null, playlist))
  977. .catch(next);
  978. },
  979. (playlist, next) => {
  980. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  981. // sort array by position
  982. playlist.songs.sort((a, b) => a.position - b.position);
  983. // find index of songId
  984. playlist.songs.forEach((song, ind) => {
  985. // remove song from array
  986. if (song.songId === songId) playlist.songs.splice(ind, 1);
  987. });
  988. const songsBeingChanged = [];
  989. playlist.songs.forEach((song, index) => {
  990. // check if position needs updated based on index
  991. if (song.position !== index + 1)
  992. songsBeingChanged.push({
  993. songId: song.songId,
  994. position: index + 1
  995. });
  996. });
  997. // update position property on songs that need to be changed
  998. return IOModule.runJob(
  999. "RUN_ACTION2",
  1000. {
  1001. session,
  1002. namespace: "playlists",
  1003. action: "repositionSongs",
  1004. args: [playlistId, songsBeingChanged]
  1005. },
  1006. this
  1007. )
  1008. .then(res => {
  1009. if (res.status === "success") return next();
  1010. return next("Unable to reposition song in playlist.");
  1011. })
  1012. .catch(next);
  1013. },
  1014. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { songId } } }, next),
  1015. (res, next) => {
  1016. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1017. .then(playlist => next(null, playlist))
  1018. .catch(next);
  1019. }
  1020. ],
  1021. async (err, playlist) => {
  1022. if (err) {
  1023. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1024. this.log(
  1025. "ERROR",
  1026. "PLAYLIST_REMOVE_SONG",
  1027. `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1028. );
  1029. return cb({ status: "failure", message: err });
  1030. }
  1031. this.log(
  1032. "SUCCESS",
  1033. "PLAYLIST_REMOVE_SONG",
  1034. `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1035. );
  1036. CacheModule.runJob("PUB", {
  1037. channel: "playlist.removeSong",
  1038. value: {
  1039. playlistId: playlist._id,
  1040. songId,
  1041. userId: session.userId,
  1042. privacy: playlist.privacy
  1043. }
  1044. });
  1045. return cb({
  1046. status: "success",
  1047. message: "Song has been successfully removed from playlist",
  1048. data: playlist.songs
  1049. });
  1050. }
  1051. );
  1052. }),
  1053. /**
  1054. * Updates the displayName of a private playlist
  1055. *
  1056. * @param {object} session - the session object automatically added by socket.io
  1057. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1058. * @param {Function} cb - gets called with the result
  1059. */
  1060. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1061. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1062. async.waterfall(
  1063. [
  1064. next => {
  1065. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1066. .then(playlist => next(null, playlist))
  1067. .catch(next);
  1068. },
  1069. (playlist, next) => {
  1070. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1071. return next(null);
  1072. },
  1073. next => {
  1074. playlistModel.updateOne(
  1075. { _id: playlistId, createdBy: session.userId },
  1076. { $set: { displayName } },
  1077. { runValidators: true },
  1078. next
  1079. );
  1080. },
  1081. (res, next) => {
  1082. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1083. .then(playlist => {
  1084. next(null, playlist);
  1085. })
  1086. .catch(next);
  1087. }
  1088. ],
  1089. async (err, playlist) => {
  1090. if (err) {
  1091. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1092. this.log(
  1093. "ERROR",
  1094. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1095. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1096. );
  1097. return cb({ status: "failure", message: err });
  1098. }
  1099. this.log(
  1100. "SUCCESS",
  1101. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1102. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1103. );
  1104. CacheModule.runJob("PUB", {
  1105. channel: "playlist.updateDisplayName",
  1106. value: {
  1107. playlistId,
  1108. displayName,
  1109. userId: session.userId,
  1110. privacy: playlist.privacy
  1111. }
  1112. });
  1113. return cb({
  1114. status: "success",
  1115. message: "Playlist has been successfully updated"
  1116. });
  1117. }
  1118. );
  1119. }),
  1120. /**
  1121. * Removes a private playlist
  1122. *
  1123. * @param {object} session - the session object automatically added by socket.io
  1124. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1125. * @param {Function} cb - gets called with the result
  1126. */
  1127. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1128. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1129. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1130. async.waterfall(
  1131. [
  1132. next => {
  1133. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1134. .then(playlist => next(null, playlist))
  1135. .catch(next);
  1136. },
  1137. (playlist, next) => {
  1138. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1139. return next(null, playlist);
  1140. },
  1141. (playlist, next) => {
  1142. userModel.updateOne(
  1143. { _id: playlist.createdBy },
  1144. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1145. err => {
  1146. if (err) return next(err);
  1147. return next(null);
  1148. }
  1149. );
  1150. },
  1151. next => {
  1152. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this).then(next).catch(next);
  1153. },
  1154. next => {
  1155. stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1156. next(err, res);
  1157. });
  1158. },
  1159. (stations, next) => {
  1160. async.each(
  1161. stations,
  1162. (station, next) => {
  1163. async.waterfall(
  1164. [
  1165. next => {
  1166. stationModel.updateOne(
  1167. { _id: station._id },
  1168. { $set: { privatePlaylist: null } },
  1169. { runValidators: true },
  1170. next
  1171. );
  1172. },
  1173. (res, next) => {
  1174. if (!station.partyMode) {
  1175. moduleManager.modules.stations
  1176. .runJob(
  1177. "UPDATE_STATION",
  1178. {
  1179. stationId: station._id
  1180. },
  1181. this
  1182. )
  1183. .then(station => next(null, station))
  1184. .catch(next);
  1185. CacheModule.runJob("PUB", {
  1186. channel: "privatePlaylist.selected",
  1187. value: {
  1188. playlistId: null,
  1189. stationId: station._id
  1190. }
  1191. });
  1192. } else next();
  1193. }
  1194. ],
  1195. () => {
  1196. next();
  1197. }
  1198. );
  1199. },
  1200. () => {
  1201. next();
  1202. }
  1203. );
  1204. }
  1205. ],
  1206. async err => {
  1207. if (err) {
  1208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1209. this.log(
  1210. "ERROR",
  1211. "PLAYLIST_REMOVE",
  1212. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1213. );
  1214. return cb({ status: "failure", message: err });
  1215. }
  1216. this.log(
  1217. "SUCCESS",
  1218. "PLAYLIST_REMOVE",
  1219. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1220. );
  1221. CacheModule.runJob("PUB", {
  1222. channel: "playlist.delete",
  1223. value: {
  1224. userId: session.userId,
  1225. playlistId
  1226. }
  1227. });
  1228. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1229. userId: session.userId,
  1230. activityType: "deleted_playlist",
  1231. payload: [playlistId]
  1232. });
  1233. return cb({
  1234. status: "success",
  1235. message: "Playlist successfully removed"
  1236. });
  1237. }
  1238. );
  1239. }),
  1240. /**
  1241. * Updates the privacy of a private playlist
  1242. *
  1243. * @param {object} session - the session object automatically added by socket.io
  1244. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1245. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1246. * @param {Function} cb - gets called with the result
  1247. */
  1248. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1249. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1250. async.waterfall(
  1251. [
  1252. next => {
  1253. playlistModel.updateOne(
  1254. { _id: playlistId, createdBy: session.userId },
  1255. { $set: { privacy } },
  1256. { runValidators: true },
  1257. next
  1258. );
  1259. },
  1260. (res, next) => {
  1261. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1262. .then(playlist => {
  1263. next(null, playlist);
  1264. })
  1265. .catch(next);
  1266. }
  1267. ],
  1268. async (err, playlist) => {
  1269. if (err) {
  1270. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1271. this.log(
  1272. "ERROR",
  1273. "PLAYLIST_UPDATE_PRIVACY",
  1274. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1275. );
  1276. return cb({ status: "failure", message: err });
  1277. }
  1278. this.log(
  1279. "SUCCESS",
  1280. "PLAYLIST_UPDATE_PRIVACY",
  1281. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1282. );
  1283. CacheModule.runJob("PUB", {
  1284. channel: "playlist.updatePrivacy",
  1285. value: {
  1286. userId: session.userId,
  1287. playlist
  1288. }
  1289. });
  1290. return cb({
  1291. status: "success",
  1292. message: "Playlist has been successfully updated"
  1293. });
  1294. }
  1295. );
  1296. })
  1297. };