playlists.js 46 KB

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