playlists.js 37 KB

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