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