playlists.js 43 KB

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