playlists.js 43 KB

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