playlists.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. this.log(
  414. "SUCCESS",
  415. "PLAYLIST_GET",
  416. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  417. );
  418. return cb({
  419. status: "success",
  420. data: playlist
  421. });
  422. }
  423. );
  424. }),
  425. /**
  426. * Obtains basic metadata of a playlist in order to format an activity
  427. *
  428. * @param {object} session - the session object automatically added by socket.io
  429. * @param {string} playlistId - the playlist id
  430. * @param {Function} cb - callback
  431. */
  432. getPlaylistForActivity(session, playlistId, cb) {
  433. async.waterfall(
  434. [
  435. next => {
  436. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  437. .then(playlist => {
  438. next(null, playlist);
  439. })
  440. .catch(next);
  441. }
  442. ],
  443. async (err, playlist) => {
  444. if (err) {
  445. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  446. this.log(
  447. "ERROR",
  448. "PLAYLISTS_GET_PLAYLIST_FOR_ACTIVITY",
  449. `Failed to obtain metadata of playlist ${playlistId} for activity formatting. "${err}"`
  450. );
  451. return cb({ status: "failure", message: err });
  452. }
  453. this.log(
  454. "SUCCESS",
  455. "PLAYLISTS_GET_PLAYLIST_FOR_ACTIVITY",
  456. `Obtained metadata of playlist ${playlistId} for activity formatting successfully.`
  457. );
  458. return cb({
  459. status: "success",
  460. data: {
  461. title: playlist.displayName
  462. }
  463. });
  464. }
  465. );
  466. },
  467. // TODO Remove this
  468. /**
  469. * Updates a private playlist
  470. *
  471. * @param {object} session - the session object automatically added by socket.io
  472. * @param {string} playlistId - the id of the playlist we are updating
  473. * @param {object} playlist - the new private playlist object
  474. * @param {Function} cb - gets called with the result
  475. */
  476. update: isLoginRequired(async function update(session, playlistId, playlist, cb) {
  477. const playlistModel = await DBModule.runJob(
  478. "GET_MODEL",
  479. {
  480. modelName: "playlist"
  481. },
  482. this
  483. );
  484. async.waterfall(
  485. [
  486. next => {
  487. playlistModel.updateOne(
  488. { _id: playlistId, createdBy: session.userId },
  489. playlist,
  490. { runValidators: true },
  491. next
  492. );
  493. },
  494. (res, next) => {
  495. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  496. .then(playlist => {
  497. next(null, playlist);
  498. })
  499. .catch(next);
  500. }
  501. ],
  502. async (err, playlist) => {
  503. if (err) {
  504. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  505. this.log(
  506. "ERROR",
  507. "PLAYLIST_UPDATE",
  508. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  509. );
  510. return cb({ status: "failure", message: err });
  511. }
  512. this.log(
  513. "SUCCESS",
  514. "PLAYLIST_UPDATE",
  515. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  516. );
  517. return cb({
  518. status: "success",
  519. data: playlist
  520. });
  521. }
  522. );
  523. }),
  524. /**
  525. * Shuffles songs in a private playlist
  526. *
  527. * @param {object} session - the session object automatically added by socket.io
  528. * @param {string} playlistId - the id of the playlist we are updating
  529. * @param {Function} cb - gets called with the result
  530. */
  531. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  532. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  533. async.waterfall(
  534. [
  535. next => {
  536. if (!playlistId) return next("No playlist id.");
  537. return playlistModel.findById(playlistId, next);
  538. },
  539. (playlist, next) => {
  540. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  541. return UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  542. .then(result => next(null, result.array))
  543. .catch(next);
  544. },
  545. (songs, next) => {
  546. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  547. },
  548. (res, next) => {
  549. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  550. .then(playlist => next(null, playlist))
  551. .catch(next);
  552. }
  553. ],
  554. async (err, playlist) => {
  555. if (err) {
  556. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  557. this.log(
  558. "ERROR",
  559. "PLAYLIST_SHUFFLE",
  560. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  561. );
  562. return cb({ status: "failure", message: err });
  563. }
  564. this.log(
  565. "SUCCESS",
  566. "PLAYLIST_SHUFFLE",
  567. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  568. );
  569. return cb({
  570. status: "success",
  571. message: "Successfully shuffled playlist.",
  572. data: playlist
  573. });
  574. }
  575. );
  576. }),
  577. /**
  578. * Changes the order of song(s) in a private playlist
  579. *
  580. * @param {object} session - the session object automatically added by socket.io
  581. * @param {string} playlistId - the id of the playlist we are targeting
  582. * @param {Array} songsBeingChanged - the songs to be repositioned, each element contains "songId" and "position" properties
  583. * @param {Function} cb - gets called with the result
  584. */
  585. repositionSongs: isLoginRequired(async function repositionSongs(session, playlistId, songsBeingChanged, cb) {
  586. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  587. async.waterfall(
  588. [
  589. // update playlist object with each song's new position
  590. next =>
  591. async.each(
  592. songsBeingChanged,
  593. (song, nextSong) =>
  594. playlistModel.updateOne(
  595. { _id: playlistId, "songs.songId": song.songId },
  596. {
  597. $set: {
  598. "songs.$.position": song.position
  599. }
  600. },
  601. err => {
  602. if (err) return next(err);
  603. return nextSong();
  604. }
  605. ),
  606. next
  607. ),
  608. // update the cache with the new songs positioning
  609. next => {
  610. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  611. .then(playlist => next(null, playlist))
  612. .catch(next);
  613. }
  614. ],
  615. async err => {
  616. if (err) {
  617. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  618. this.log(
  619. "ERROR",
  620. "PLAYLIST_REPOSITION_SONGS",
  621. `Repositioning songs for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  622. );
  623. return cb({ status: "failure", message: err });
  624. }
  625. this.log(
  626. "SUCCESS",
  627. "PLAYLIST_REPOSITION_SONGS",
  628. `Successfully repositioned songs for private playlist "${playlistId}" for user "${session.userId}".`
  629. );
  630. CacheModule.runJob("PUB", {
  631. channel: "playlist.repositionSongs",
  632. value: {
  633. userId: session.userId,
  634. playlistId,
  635. songsBeingChanged
  636. }
  637. });
  638. return cb({
  639. status: "success",
  640. message: "Order of songs successfully updated"
  641. });
  642. }
  643. );
  644. }),
  645. /**
  646. * Moves a song to the bottom of the list in a private playlist
  647. *
  648. * @param {object} session - the session object automatically added by socket.io
  649. * @param {string} playlistId - the id of the playlist we are moving the song to the bottom from
  650. * @param {string} songId - the id of the song we are moving to the bottom of the list
  651. * @param {Function} cb - gets called with the result
  652. */
  653. moveSongToBottom: isLoginRequired(async function moveSongToBottom(session, playlistId, songId, cb) {
  654. async.waterfall(
  655. [
  656. next => {
  657. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  658. .then(playlist => next(null, playlist))
  659. .catch(next);
  660. },
  661. (playlist, next) => {
  662. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  663. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  664. // sort array by position
  665. playlist.songs.sort((a, b) => a.position - b.position);
  666. // find index of songId
  667. playlist.songs.forEach((song, index) => {
  668. // reorder array (simulates what would be done with a drag and drop interface)
  669. if (song.songId === songId)
  670. playlist.songs.splice(playlist.songs.length, 0, playlist.songs.splice(index, 1)[0]);
  671. });
  672. const songsBeingChanged = [];
  673. playlist.songs.forEach((song, index) => {
  674. // check if position needs updated based on index
  675. if (song.position !== index + 1)
  676. songsBeingChanged.push({
  677. songId: song.songId,
  678. position: index + 1
  679. });
  680. });
  681. // update position property on songs that need to be changed
  682. return IOModule.runJob(
  683. "RUN_ACTION2",
  684. {
  685. session,
  686. namespace: "playlists",
  687. action: "repositionSongs",
  688. args: [playlistId, songsBeingChanged]
  689. },
  690. this
  691. )
  692. .then(res => {
  693. if (res.status === "success") return next();
  694. return next("Unable to reposition song in playlist.");
  695. })
  696. .catch(next);
  697. }
  698. ],
  699. async err => {
  700. if (err) {
  701. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  702. this.log(
  703. "ERROR",
  704. "PLAYLIST_MOVE_SONG_TO_BOTTOM",
  705. `Moving song "${songId}" to the bottom for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  706. );
  707. return cb({ status: "failure", message: err });
  708. }
  709. this.log(
  710. "SUCCESS",
  711. "PLAYLIST_MOVE_SONG_TO_BOTTOM",
  712. `Successfully moved song "${songId}" to the bottom for private playlist "${playlistId}" for user "${session.userId}".`
  713. );
  714. return cb({
  715. status: "success",
  716. message: "Order of songs successfully updated"
  717. });
  718. }
  719. );
  720. }),
  721. /**
  722. * Adds a song to a private playlist
  723. *
  724. * @param {object} session - the session object automatically added by socket.io
  725. * @param {boolean} isSet - is the song part of a set of songs to be added
  726. * @param {string} songId - the id of the song we are trying to add
  727. * @param {string} playlistId - the id of the playlist we are adding the song to
  728. * @param {Function} cb - gets called with the result
  729. */
  730. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, songId, playlistId, cb) {
  731. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  732. async.waterfall(
  733. [
  734. next => {
  735. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  736. .then(playlist => {
  737. if (!playlist || playlist.createdBy !== session.userId)
  738. return next("Something went wrong when trying to get the playlist");
  739. return async.each(
  740. playlist.songs,
  741. (song, nextSong) => {
  742. if (song.songId === songId) return next("That song is already in the playlist");
  743. return nextSong();
  744. },
  745. err => next(err, playlist.songs.length + 1)
  746. );
  747. })
  748. .catch(next);
  749. },
  750. (position, next) => {
  751. SongsModule.runJob("GET_SONG", { id: songId }, this)
  752. .then(response => {
  753. const { song } = response;
  754. next(null, {
  755. _id: song._id,
  756. songId,
  757. title: song.title,
  758. duration: song.duration,
  759. position
  760. });
  761. })
  762. .catch(() => {
  763. YouTubeModule.runJob("GET_SONG", { songId }, this)
  764. .then(response => next(null, { ...response.song, position }))
  765. .catch(next);
  766. });
  767. },
  768. (newSong, next) => {
  769. playlistModel.updateOne(
  770. { _id: playlistId },
  771. { $push: { songs: newSong } },
  772. { runValidators: true },
  773. err => {
  774. if (err) return next(err);
  775. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  776. .then(playlist => next(null, playlist, newSong))
  777. .catch(next);
  778. }
  779. );
  780. }
  781. ],
  782. async (err, playlist, newSong) => {
  783. if (err) {
  784. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  785. this.log(
  786. "ERROR",
  787. "PLAYLIST_ADD_SONG",
  788. `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  789. );
  790. return cb({ status: "failure", message: err });
  791. }
  792. this.log(
  793. "SUCCESS",
  794. "PLAYLIST_ADD_SONG",
  795. `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${session.userId}".`
  796. );
  797. if (!isSet)
  798. ActivitiesModule.runJob("ADD_ACTIVITY", {
  799. userId: session.userId,
  800. activityType: "added_song_to_playlist",
  801. payload: [{ songId, playlistId }]
  802. });
  803. CacheModule.runJob("PUB", {
  804. channel: "playlist.addSong",
  805. value: {
  806. playlistId: playlist._id,
  807. song: newSong,
  808. userId: session.userId,
  809. privacy: playlist.privacy
  810. }
  811. });
  812. return cb({
  813. status: "success",
  814. message: "Song has been successfully added to the playlist",
  815. data: playlist.songs
  816. });
  817. }
  818. );
  819. }),
  820. /**
  821. * Adds a set of songs to a private playlist
  822. *
  823. * @param {object} session - the session object automatically added by socket.io
  824. * @param {string} url - the url of the the YouTube playlist
  825. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  826. * @param {boolean} musicOnly - whether to only add music to the playlist
  827. * @param {Function} cb - gets called with the result
  828. */
  829. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  830. let videosInPlaylistTotal = 0;
  831. let songsInPlaylistTotal = 0;
  832. let addSongsStats = null;
  833. const addedSongs = [];
  834. async.waterfall(
  835. [
  836. next => {
  837. YouTubeModule.runJob(
  838. "GET_PLAYLIST",
  839. {
  840. url,
  841. musicOnly
  842. },
  843. this
  844. ).then(response => {
  845. if (response.filteredSongs) {
  846. videosInPlaylistTotal = response.songs.length;
  847. songsInPlaylistTotal = response.filteredSongs.length;
  848. } else {
  849. songsInPlaylistTotal = videosInPlaylistTotal = response.songs.length;
  850. }
  851. next(null, response.songs);
  852. });
  853. },
  854. (songIds, next) => {
  855. let successful = 0;
  856. let failed = 0;
  857. let alreadyInPlaylist = 0;
  858. if (songIds.length === 0) next();
  859. async.eachLimit(
  860. songIds,
  861. 1,
  862. (songId, next) => {
  863. IOModule.runJob(
  864. "RUN_ACTION2",
  865. {
  866. session,
  867. namespace: "playlists",
  868. action: "addSongToPlaylist",
  869. args: [true, songId, playlistId]
  870. },
  871. this
  872. )
  873. .then(res => {
  874. if (res.status === "success") {
  875. successful += 1;
  876. addedSongs.push(songId);
  877. } else failed += 1;
  878. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  879. })
  880. .catch(() => {
  881. failed += 1;
  882. })
  883. .finally(() => {
  884. next();
  885. });
  886. },
  887. () => {
  888. addSongsStats = { successful, failed, alreadyInPlaylist };
  889. next(null);
  890. }
  891. );
  892. },
  893. next => {
  894. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  895. .then(playlist => {
  896. next(null, playlist);
  897. })
  898. .catch(next);
  899. },
  900. (playlist, next) => {
  901. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  902. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  903. return next(null, playlist);
  904. }
  905. ],
  906. async (err, playlist) => {
  907. if (err) {
  908. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  909. this.log(
  910. "ERROR",
  911. "PLAYLIST_IMPORT",
  912. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  913. );
  914. return cb({ status: "failure", message: err });
  915. }
  916. ActivitiesModule.runJob("ADD_ACTIVITY", {
  917. userId: session.userId,
  918. activityType: "added_songs_to_playlist",
  919. payload: addedSongs
  920. });
  921. this.log(
  922. "SUCCESS",
  923. "PLAYLIST_IMPORT",
  924. `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}.`
  925. );
  926. return cb({
  927. status: "success",
  928. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  929. data: playlist.songs,
  930. stats: {
  931. videosInPlaylistTotal,
  932. songsInPlaylistTotal
  933. }
  934. });
  935. }
  936. );
  937. }),
  938. /**
  939. * Removes a song from a private playlist
  940. *
  941. * @param {object} session - the session object automatically added by socket.io
  942. * @param {string} songId - the id of the song we are removing from the private playlist
  943. * @param {string} playlistId - the id of the playlist we are removing the song from
  944. * @param {Function} cb - gets called with the result
  945. */
  946. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, songId, playlistId, cb) {
  947. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  948. async.waterfall(
  949. [
  950. next => {
  951. if (!songId || typeof songId !== "string") return next("Invalid song id.");
  952. if (!playlistId) return next("Invalid playlist id.");
  953. return next();
  954. },
  955. next => {
  956. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  957. .then(playlist => next(null, playlist))
  958. .catch(next);
  959. },
  960. (playlist, next) => {
  961. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  962. // sort array by position
  963. playlist.songs.sort((a, b) => a.position - b.position);
  964. // find index of songId
  965. playlist.songs.forEach((song, ind) => {
  966. // remove song from array
  967. if (song.songId === songId) playlist.songs.splice(ind, 1);
  968. });
  969. const songsBeingChanged = [];
  970. playlist.songs.forEach((song, index) => {
  971. // check if position needs updated based on index
  972. if (song.position !== index + 1)
  973. songsBeingChanged.push({
  974. songId: song.songId,
  975. position: index + 1
  976. });
  977. });
  978. // update position property on songs that need to be changed
  979. return IOModule.runJob(
  980. "RUN_ACTION2",
  981. {
  982. session,
  983. namespace: "playlists",
  984. action: "repositionSongs",
  985. args: [playlistId, songsBeingChanged]
  986. },
  987. this
  988. )
  989. .then(res => {
  990. if (res.status === "success") return next();
  991. return next("Unable to reposition song in playlist.");
  992. })
  993. .catch(next);
  994. },
  995. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { songId } } }, next),
  996. (res, next) => {
  997. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  998. .then(playlist => next(null, playlist))
  999. .catch(next);
  1000. }
  1001. ],
  1002. async (err, playlist) => {
  1003. if (err) {
  1004. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1005. this.log(
  1006. "ERROR",
  1007. "PLAYLIST_REMOVE_SONG",
  1008. `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1009. );
  1010. return cb({ status: "failure", message: err });
  1011. }
  1012. this.log(
  1013. "SUCCESS",
  1014. "PLAYLIST_REMOVE_SONG",
  1015. `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1016. );
  1017. CacheModule.runJob("PUB", {
  1018. channel: "playlist.removeSong",
  1019. value: {
  1020. playlistId: playlist._id,
  1021. songId,
  1022. userId: session.userId,
  1023. privacy: playlist.privacy
  1024. }
  1025. });
  1026. return cb({
  1027. status: "success",
  1028. message: "Song has been successfully removed from playlist",
  1029. data: playlist.songs
  1030. });
  1031. }
  1032. );
  1033. }),
  1034. /**
  1035. * Updates the displayName of a private playlist
  1036. *
  1037. * @param {object} session - the session object automatically added by socket.io
  1038. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1039. * @param {Function} cb - gets called with the result
  1040. */
  1041. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1042. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1043. async.waterfall(
  1044. [
  1045. next => {
  1046. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1047. .then(playlist => next(null, playlist))
  1048. .catch(next);
  1049. },
  1050. (playlist, next) => {
  1051. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1052. return next(null);
  1053. },
  1054. next => {
  1055. playlistModel.updateOne(
  1056. { _id: playlistId, createdBy: session.userId },
  1057. { $set: { displayName } },
  1058. { runValidators: true },
  1059. next
  1060. );
  1061. },
  1062. (res, next) => {
  1063. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1064. .then(playlist => {
  1065. next(null, playlist);
  1066. })
  1067. .catch(next);
  1068. }
  1069. ],
  1070. async (err, playlist) => {
  1071. if (err) {
  1072. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1073. this.log(
  1074. "ERROR",
  1075. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1076. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1077. );
  1078. return cb({ status: "failure", message: err });
  1079. }
  1080. this.log(
  1081. "SUCCESS",
  1082. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1083. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1084. );
  1085. CacheModule.runJob("PUB", {
  1086. channel: "playlist.updateDisplayName",
  1087. value: {
  1088. playlistId,
  1089. displayName,
  1090. userId: session.userId,
  1091. privacy: playlist.privacy
  1092. }
  1093. });
  1094. return cb({
  1095. status: "success",
  1096. message: "Playlist has been successfully updated"
  1097. });
  1098. }
  1099. );
  1100. }),
  1101. /**
  1102. * Removes a private playlist
  1103. *
  1104. * @param {object} session - the session object automatically added by socket.io
  1105. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1106. * @param {Function} cb - gets called with the result
  1107. */
  1108. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1109. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1110. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1111. async.waterfall(
  1112. [
  1113. next => {
  1114. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1115. .then(playlist => next(null, playlist))
  1116. .catch(next);
  1117. },
  1118. (playlist, next) => {
  1119. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1120. return next(null, playlist);
  1121. },
  1122. (playlist, next) => {
  1123. userModel.updateOne(
  1124. { _id: playlist.createdBy },
  1125. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1126. err => {
  1127. if (err) return next(err);
  1128. return next(null);
  1129. }
  1130. );
  1131. },
  1132. next => {
  1133. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this).then(next).catch(next);
  1134. },
  1135. next => {
  1136. stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1137. next(err, res);
  1138. });
  1139. },
  1140. (stations, next) => {
  1141. async.each(
  1142. stations,
  1143. (station, next) => {
  1144. async.waterfall(
  1145. [
  1146. next => {
  1147. stationModel.updateOne(
  1148. { _id: station._id },
  1149. { $set: { privatePlaylist: null } },
  1150. { runValidators: true },
  1151. next
  1152. );
  1153. },
  1154. (res, next) => {
  1155. if (!station.partyMode) {
  1156. moduleManager.modules.stations
  1157. .runJob(
  1158. "UPDATE_STATION",
  1159. {
  1160. stationId: station._id
  1161. },
  1162. this
  1163. )
  1164. .then(station => next(null, station))
  1165. .catch(next);
  1166. CacheModule.runJob("PUB", {
  1167. channel: "privatePlaylist.selected",
  1168. value: {
  1169. playlistId: null,
  1170. stationId: station._id
  1171. }
  1172. });
  1173. } else next();
  1174. }
  1175. ],
  1176. () => {
  1177. next();
  1178. }
  1179. );
  1180. },
  1181. () => {
  1182. next();
  1183. }
  1184. );
  1185. }
  1186. ],
  1187. async err => {
  1188. if (err) {
  1189. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1190. this.log(
  1191. "ERROR",
  1192. "PLAYLIST_REMOVE",
  1193. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1194. );
  1195. return cb({ status: "failure", message: err });
  1196. }
  1197. this.log(
  1198. "SUCCESS",
  1199. "PLAYLIST_REMOVE",
  1200. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1201. );
  1202. CacheModule.runJob("PUB", {
  1203. channel: "playlist.delete",
  1204. value: {
  1205. userId: session.userId,
  1206. playlistId
  1207. }
  1208. });
  1209. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1210. userId: session.userId,
  1211. activityType: "deleted_playlist",
  1212. payload: [playlistId]
  1213. });
  1214. return cb({
  1215. status: "success",
  1216. message: "Playlist successfully removed"
  1217. });
  1218. }
  1219. );
  1220. }),
  1221. /**
  1222. * Updates the privacy of a private playlist
  1223. *
  1224. * @param {object} session - the session object automatically added by socket.io
  1225. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1226. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1227. * @param {Function} cb - gets called with the result
  1228. */
  1229. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1230. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1231. async.waterfall(
  1232. [
  1233. next => {
  1234. playlistModel.updateOne(
  1235. { _id: playlistId, createdBy: session.userId },
  1236. { $set: { privacy } },
  1237. { runValidators: true },
  1238. next
  1239. );
  1240. },
  1241. (res, next) => {
  1242. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1243. .then(playlist => {
  1244. next(null, playlist);
  1245. })
  1246. .catch(next);
  1247. }
  1248. ],
  1249. async (err, playlist) => {
  1250. if (err) {
  1251. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1252. this.log(
  1253. "ERROR",
  1254. "PLAYLIST_UPDATE_PRIVACY",
  1255. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1256. );
  1257. return cb({ status: "failure", message: err });
  1258. }
  1259. this.log(
  1260. "SUCCESS",
  1261. "PLAYLIST_UPDATE_PRIVACY",
  1262. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1263. );
  1264. CacheModule.runJob("PUB", {
  1265. channel: "playlist.updatePrivacy",
  1266. value: {
  1267. userId: session.userId,
  1268. playlist
  1269. }
  1270. });
  1271. return cb({
  1272. status: "success",
  1273. message: "Playlist has been successfully updated"
  1274. });
  1275. }
  1276. );
  1277. })
  1278. };