playlists.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  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)
  786. );
  787. })
  788. .catch(next);
  789. },
  790. next => {
  791. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  792. .then(UserModel => {
  793. UserModel.findOne(
  794. { _id: session.userId },
  795. { "preferences.anonymousSongRequests": 1 },
  796. next
  797. );
  798. })
  799. .catch(next);
  800. },
  801. (user, next) => {
  802. SongsModule.runJob(
  803. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  804. {
  805. songId,
  806. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  807. automaticallyRequested: true
  808. },
  809. this
  810. )
  811. .then(response => {
  812. const { song } = response;
  813. const { _id, title, thumbnail, duration, status } = song;
  814. next(null, {
  815. _id,
  816. songId,
  817. title,
  818. thumbnail,
  819. duration,
  820. status
  821. });
  822. })
  823. .catch(next);
  824. },
  825. (newSong, next) => {
  826. playlistModel.updateOne(
  827. { _id: playlistId },
  828. { $push: { songs: newSong } },
  829. { runValidators: true },
  830. err => {
  831. if (err) return next(err);
  832. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  833. .then(playlist => next(null, playlist, newSong))
  834. .catch(next);
  835. }
  836. );
  837. }
  838. ],
  839. async (err, playlist, newSong) => {
  840. if (err) {
  841. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  842. this.log(
  843. "ERROR",
  844. "PLAYLIST_ADD_SONG",
  845. `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  846. );
  847. return cb({ status: "failure", message: err });
  848. }
  849. this.log(
  850. "SUCCESS",
  851. "PLAYLIST_ADD_SONG",
  852. `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${session.userId}".`
  853. );
  854. if (!isSet && playlist.displayName !== "Liked Songs" && playlist.displayName !== "Disliked Songs") {
  855. const songName = newSong.artists
  856. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  857. : newSong.title;
  858. ActivitiesModule.runJob("ADD_ACTIVITY", {
  859. userId: session.userId,
  860. type: "playlist__add_song",
  861. payload: {
  862. message: `Added <songId>${songName}</songId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  863. thumbnail: newSong.thumbnail,
  864. playlistId,
  865. songId
  866. }
  867. });
  868. }
  869. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  870. .then(response => {
  871. response.stationIds.forEach(stationId => {
  872. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  873. });
  874. })
  875. .catch();
  876. CacheModule.runJob("PUB", {
  877. channel: "playlist.addSong",
  878. value: {
  879. playlistId: playlist._id,
  880. song: newSong,
  881. userId: session.userId,
  882. privacy: playlist.privacy
  883. }
  884. });
  885. return cb({
  886. status: "success",
  887. message: "Song has been successfully added to the playlist",
  888. data: playlist.songs
  889. });
  890. }
  891. );
  892. }),
  893. /**
  894. * Adds a set of songs to a private playlist
  895. *
  896. * @param {object} session - the session object automatically added by the websocket
  897. * @param {string} url - the url of the the YouTube playlist
  898. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  899. * @param {boolean} musicOnly - whether to only add music to the playlist
  900. * @param {Function} cb - gets called with the result
  901. */
  902. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  903. let videosInPlaylistTotal = 0;
  904. let songsInPlaylistTotal = 0;
  905. let addSongsStats = null;
  906. const addedSongs = [];
  907. async.waterfall(
  908. [
  909. next => {
  910. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  911. .then(res => {
  912. if (res.filteredSongs) {
  913. videosInPlaylistTotal = res.songs.length;
  914. songsInPlaylistTotal = res.filteredSongs.length;
  915. } else {
  916. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  917. }
  918. next(null, res.songs);
  919. })
  920. .catch(err => {
  921. next(err);
  922. });
  923. },
  924. (songIds, next) => {
  925. let successful = 0;
  926. let failed = 0;
  927. let alreadyInPlaylist = 0;
  928. if (songIds.length === 0) next();
  929. console.log(songIds);
  930. async.eachLimit(
  931. songIds,
  932. 1,
  933. (songId, next) => {
  934. WSModule.runJob(
  935. "RUN_ACTION2",
  936. {
  937. session,
  938. namespace: "playlists",
  939. action: "addSongToPlaylist",
  940. args: [true, songId, playlistId]
  941. },
  942. this
  943. )
  944. .then(res => {
  945. if (res.status === "success") {
  946. successful += 1;
  947. addedSongs.push(songId);
  948. } else failed += 1;
  949. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  950. })
  951. .catch(() => {
  952. failed += 1;
  953. })
  954. .finally(() => next());
  955. },
  956. () => {
  957. addSongsStats = { successful, failed, alreadyInPlaylist };
  958. next(null);
  959. }
  960. );
  961. },
  962. next => {
  963. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  964. .then(playlist => next(null, playlist))
  965. .catch(next);
  966. },
  967. (playlist, next) => {
  968. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  969. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  970. return next(null, playlist);
  971. }
  972. ],
  973. async (err, playlist) => {
  974. if (err) {
  975. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  976. this.log(
  977. "ERROR",
  978. "PLAYLIST_IMPORT",
  979. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  980. );
  981. return cb({ status: "failure", message: err });
  982. }
  983. ActivitiesModule.runJob("ADD_ACTIVITY", {
  984. userId: session.userId,
  985. type: "playlist__import_playlist",
  986. payload: {
  987. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  988. playlistId
  989. }
  990. });
  991. this.log(
  992. "SUCCESS",
  993. "PLAYLIST_IMPORT",
  994. `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}.`
  995. );
  996. return cb({
  997. status: "success",
  998. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  999. data: playlist.songs,
  1000. stats: {
  1001. videosInPlaylistTotal,
  1002. songsInPlaylistTotal
  1003. }
  1004. });
  1005. }
  1006. );
  1007. }),
  1008. /**
  1009. * Removes a song from a private playlist
  1010. *
  1011. * @param {object} session - the session object automatically added by the websocket
  1012. * @param {string} songId - the id of the song we are removing from the private playlist
  1013. * @param {string} playlistId - the id of the playlist we are removing the song from
  1014. * @param {Function} cb - gets called with the result
  1015. */
  1016. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, songId, playlistId, cb) {
  1017. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1018. async.waterfall(
  1019. [
  1020. next => {
  1021. if (!songId || typeof songId !== "string") return next("Invalid song id.");
  1022. if (!playlistId) return next("Invalid playlist id.");
  1023. return next();
  1024. },
  1025. next => {
  1026. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1027. .then(playlist => next(null, playlist))
  1028. .catch(next);
  1029. },
  1030. (playlist, next) => {
  1031. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  1032. // sort array by position
  1033. playlist.songs.sort((a, b) => a.position - b.position);
  1034. // find index of songId
  1035. playlist.songs.forEach((song, ind) => {
  1036. // remove song from array
  1037. if (song.songId === songId) playlist.songs.splice(ind, 1);
  1038. });
  1039. const songsBeingChanged = [];
  1040. playlist.songs.forEach((song, index) => {
  1041. // check if position needs updated based on index
  1042. if (song.position !== index + 1)
  1043. songsBeingChanged.push({
  1044. songId: song.songId,
  1045. position: index + 1
  1046. });
  1047. });
  1048. // update position property on songs that need to be changed
  1049. return WSModule.runJob(
  1050. "RUN_ACTION2",
  1051. {
  1052. session,
  1053. namespace: "playlists",
  1054. action: "repositionSongs",
  1055. args: [playlistId, songsBeingChanged]
  1056. },
  1057. this
  1058. )
  1059. .then(res => {
  1060. if (res.status === "success") return next();
  1061. return next("Unable to reposition song in playlist.");
  1062. })
  1063. .catch(next);
  1064. },
  1065. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { songId } } }, next),
  1066. (res, next) => {
  1067. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1068. .then(playlist => next(null, playlist))
  1069. .catch(next);
  1070. },
  1071. (playlist, next) => {
  1072. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  1073. .then(response => {
  1074. response.stationIds.forEach(stationId => {
  1075. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1076. });
  1077. })
  1078. .catch();
  1079. SongsModule.runJob("GET_SONG_FROM_ID", { songId }, this)
  1080. .then(res =>
  1081. next(null, playlist, {
  1082. title: res.song.title,
  1083. thumbnail: res.song.thumbnail,
  1084. artists: res.song.artists
  1085. })
  1086. )
  1087. .catch(() => {
  1088. YouTubeModule.runJob("GET_SONG", { songId }, this)
  1089. .then(response => next(null, playlist, response.song))
  1090. .catch(next);
  1091. });
  1092. },
  1093. (playlist, youtubeSong, next) => {
  1094. const songName = youtubeSong.artists
  1095. ? `${youtubeSong.title} by ${youtubeSong.artists.join(", ")}`
  1096. : youtubeSong.title;
  1097. if (playlist.displayName !== "Liked Songs" && playlist.displayName !== "Disliked Songs") {
  1098. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1099. userId: session.userId,
  1100. type: "playlist__remove_song",
  1101. payload: {
  1102. message: `Removed <songId>${songName}</songId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1103. thumbnail: youtubeSong.thumbnail,
  1104. playlistId,
  1105. songId
  1106. }
  1107. });
  1108. }
  1109. return next(null, playlist);
  1110. }
  1111. ],
  1112. async (err, playlist) => {
  1113. if (err) {
  1114. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1115. this.log(
  1116. "ERROR",
  1117. "PLAYLIST_REMOVE_SONG",
  1118. `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1119. );
  1120. return cb({ status: "failure", message: err });
  1121. }
  1122. this.log(
  1123. "SUCCESS",
  1124. "PLAYLIST_REMOVE_SONG",
  1125. `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1126. );
  1127. CacheModule.runJob("PUB", {
  1128. channel: "playlist.removeSong",
  1129. value: {
  1130. playlistId: playlist._id,
  1131. songId,
  1132. userId: session.userId,
  1133. privacy: playlist.privacy
  1134. }
  1135. });
  1136. return cb({
  1137. status: "success",
  1138. message: "Song has been successfully removed from playlist",
  1139. data: playlist.songs
  1140. });
  1141. }
  1142. );
  1143. }),
  1144. /**
  1145. * Updates the displayName of a private playlist
  1146. *
  1147. * @param {object} session - the session object automatically added by the websocket
  1148. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1149. * @param {Function} cb - gets called with the result
  1150. */
  1151. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1152. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1153. async.waterfall(
  1154. [
  1155. next => {
  1156. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1157. .then(playlist => next(null, playlist))
  1158. .catch(next);
  1159. },
  1160. (playlist, next) => {
  1161. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1162. return next(null);
  1163. },
  1164. next => {
  1165. playlistModel.updateOne(
  1166. { _id: playlistId, createdBy: session.userId },
  1167. { $set: { displayName } },
  1168. { runValidators: true },
  1169. next
  1170. );
  1171. },
  1172. (res, next) => {
  1173. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1174. .then(playlist => next(null, playlist))
  1175. .catch(next);
  1176. }
  1177. ],
  1178. async (err, playlist) => {
  1179. if (err) {
  1180. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1181. this.log(
  1182. "ERROR",
  1183. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1184. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1185. );
  1186. return cb({ status: "failure", message: err });
  1187. }
  1188. this.log(
  1189. "SUCCESS",
  1190. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1191. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1192. );
  1193. CacheModule.runJob("PUB", {
  1194. channel: "playlist.updateDisplayName",
  1195. value: {
  1196. playlistId,
  1197. displayName,
  1198. userId: session.userId,
  1199. privacy: playlist.privacy
  1200. }
  1201. });
  1202. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1203. userId: session.userId,
  1204. type: "playlist__edit_display_name",
  1205. payload: {
  1206. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1207. playlistId
  1208. }
  1209. });
  1210. return cb({
  1211. status: "success",
  1212. message: "Playlist has been successfully updated"
  1213. });
  1214. }
  1215. );
  1216. }),
  1217. /**
  1218. * Removes a private playlist
  1219. *
  1220. * @param {object} session - the session object automatically added by the websocket
  1221. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1222. * @param {Function} cb - gets called with the result
  1223. */
  1224. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1225. // const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1226. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1227. async.waterfall(
  1228. [
  1229. next => {
  1230. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1231. .then(playlist => next(null, playlist))
  1232. .catch(next);
  1233. },
  1234. (playlist, next) => {
  1235. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1236. return next(null, playlist);
  1237. },
  1238. (playlist, next) => {
  1239. userModel.updateOne(
  1240. { _id: playlist.createdBy },
  1241. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1242. err => next(err, playlist)
  1243. );
  1244. },
  1245. (playlist, next) => {
  1246. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1247. .then(() => next(null, playlist))
  1248. .catch(next);
  1249. }
  1250. // (playlist, next) => {
  1251. // stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1252. // next(err, playlist, res);
  1253. // });
  1254. // },
  1255. // (playlist, stations, next) => {
  1256. // async.each(
  1257. // stations,
  1258. // (station, next) => {
  1259. // async.waterfall(
  1260. // [
  1261. // next => {
  1262. // stationModel.updateOne(
  1263. // { _id: station._id },
  1264. // { $set: { privatePlaylist: null } },
  1265. // { runValidators: true },
  1266. // next
  1267. // );
  1268. // },
  1269. // (res, next) => {
  1270. // if (!station.partyMode) {
  1271. // moduleManager.modules.stations
  1272. // .runJob("UPDATE_STATION", { stationId: station._id }, this)
  1273. // .then(station => next(null, station))
  1274. // .catch(next);
  1275. // CacheModule.runJob("PUB", {
  1276. // channel: "privatePlaylist.selected",
  1277. // value: {
  1278. // playlistId: null,
  1279. // stationId: station._id
  1280. // }
  1281. // });
  1282. // } else next();
  1283. // }
  1284. // ],
  1285. // () => next()
  1286. // );
  1287. // },
  1288. // () => next(null, playlist)
  1289. // );
  1290. // }
  1291. ],
  1292. async (err, playlist) => {
  1293. if (err) {
  1294. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1295. this.log(
  1296. "ERROR",
  1297. "PLAYLIST_REMOVE",
  1298. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1299. );
  1300. return cb({ status: "failure", message: err });
  1301. }
  1302. this.log(
  1303. "SUCCESS",
  1304. "PLAYLIST_REMOVE",
  1305. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1306. );
  1307. CacheModule.runJob("PUB", {
  1308. channel: "playlist.delete",
  1309. value: {
  1310. userId: session.userId,
  1311. playlistId
  1312. }
  1313. });
  1314. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1315. userId: playlist.createdBy,
  1316. type: "playlist__remove",
  1317. payload: {
  1318. message: `Removed playlist ${playlist.displayName}`
  1319. }
  1320. });
  1321. return cb({
  1322. status: "success",
  1323. message: "Playlist successfully removed"
  1324. });
  1325. }
  1326. );
  1327. }),
  1328. /**
  1329. * Updates the privacy of a private playlist
  1330. *
  1331. * @param {object} session - the session object automatically added by the websocket
  1332. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1333. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1334. * @param {Function} cb - gets called with the result
  1335. */
  1336. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1337. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1338. async.waterfall(
  1339. [
  1340. next => {
  1341. playlistModel.updateOne(
  1342. { _id: playlistId, createdBy: session.userId },
  1343. { $set: { privacy } },
  1344. { runValidators: true },
  1345. next
  1346. );
  1347. },
  1348. (res, next) => {
  1349. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1350. .then(playlist => next(null, playlist))
  1351. .catch(next);
  1352. }
  1353. ],
  1354. async (err, playlist) => {
  1355. if (err) {
  1356. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1357. this.log(
  1358. "ERROR",
  1359. "PLAYLIST_UPDATE_PRIVACY",
  1360. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1361. );
  1362. return cb({ status: "failure", message: err });
  1363. }
  1364. this.log(
  1365. "SUCCESS",
  1366. "PLAYLIST_UPDATE_PRIVACY",
  1367. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1368. );
  1369. CacheModule.runJob("PUB", {
  1370. channel: "playlist.updatePrivacy",
  1371. value: {
  1372. userId: session.userId,
  1373. playlist
  1374. }
  1375. });
  1376. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1377. userId: session.userId,
  1378. type: "playlist__edit_privacy",
  1379. payload: {
  1380. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1381. playlistId
  1382. }
  1383. });
  1384. return cb({
  1385. status: "success",
  1386. message: "Playlist has been successfully updated"
  1387. });
  1388. }
  1389. );
  1390. }),
  1391. /**
  1392. * Deletes all orphaned station playlists
  1393. *
  1394. * @param {object} session - the session object automatically added by socket.io
  1395. * @param {Function} cb - gets called with the result
  1396. */
  1397. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1398. async.waterfall(
  1399. [
  1400. next => {
  1401. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1402. .then(() => next())
  1403. .catch(next);
  1404. }
  1405. ],
  1406. async err => {
  1407. if (err) {
  1408. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1409. this.log(
  1410. "ERROR",
  1411. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1412. `Deleting orphaned station playlists failed. "${err}"`
  1413. );
  1414. return cb({ status: "failure", message: err });
  1415. }
  1416. this.log(
  1417. "SUCCESS",
  1418. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1419. "Deleting orphaned station playlists successfull."
  1420. );
  1421. return cb({ status: "success", message: "Success" });
  1422. }
  1423. );
  1424. }),
  1425. /**
  1426. * Deletes all orphaned genre playlists
  1427. *
  1428. * @param {object} session - the session object automatically added by socket.io
  1429. * @param {Function} cb - gets called with the result
  1430. */
  1431. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1432. async.waterfall(
  1433. [
  1434. next => {
  1435. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1436. .then(() => next())
  1437. .catch(next);
  1438. }
  1439. ],
  1440. async err => {
  1441. if (err) {
  1442. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1443. this.log(
  1444. "ERROR",
  1445. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1446. `Deleting orphaned genre playlists failed. "${err}"`
  1447. );
  1448. return cb({ status: "failure", message: err });
  1449. }
  1450. this.log(
  1451. "SUCCESS",
  1452. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1453. "Deleting orphaned genre playlists successfull."
  1454. );
  1455. return cb({ status: "success", message: "Success" });
  1456. }
  1457. );
  1458. }),
  1459. /**
  1460. * Requests orpahned playlist songs
  1461. *
  1462. * @param {object} session - the session object automatically added by socket.io
  1463. * @param {Function} cb - gets called with the result
  1464. */
  1465. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1466. async.waterfall(
  1467. [
  1468. next => {
  1469. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1470. .then(() => next())
  1471. .catch(next);
  1472. }
  1473. ],
  1474. async err => {
  1475. if (err) {
  1476. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1477. this.log(
  1478. "ERROR",
  1479. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1480. `Requesting orphaned playlist songs failed. "${err}"`
  1481. );
  1482. return cb({ status: "failure", message: err });
  1483. }
  1484. this.log(
  1485. "SUCCESS",
  1486. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1487. "Requesting orphaned playlist songs was successfull."
  1488. );
  1489. return cb({ status: "success", message: "Success" });
  1490. }
  1491. );
  1492. }),
  1493. /**
  1494. * Clears and refills a station playlist
  1495. *
  1496. * @param {object} session - the session object automatically added by socket.io
  1497. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1498. * @param {Function} cb - gets called with the result
  1499. */
  1500. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1501. async.waterfall(
  1502. [
  1503. next => {
  1504. if (!playlistId) next("Please specify a playlist id");
  1505. else {
  1506. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1507. .then(() => {
  1508. next();
  1509. })
  1510. .catch(err => {
  1511. next(err);
  1512. });
  1513. }
  1514. }
  1515. ],
  1516. async err => {
  1517. if (err) {
  1518. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1519. this.log(
  1520. "ERROR",
  1521. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1522. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1523. );
  1524. return cb({ status: "failure", message: err });
  1525. }
  1526. this.log(
  1527. "SUCCESS",
  1528. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1529. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  1530. );
  1531. return cb({
  1532. status: "success",
  1533. message: "Playlist has been successfully cleared and refilled"
  1534. });
  1535. }
  1536. );
  1537. }),
  1538. /**
  1539. * Clears and refills a genre playlist
  1540. *
  1541. * @param {object} session - the session object automatically added by socket.io
  1542. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1543. * @param {Function} cb - gets called with the result
  1544. */
  1545. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1546. async.waterfall(
  1547. [
  1548. next => {
  1549. if (!playlistId) next("Please specify a playlist id");
  1550. else {
  1551. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  1552. .then(() => {
  1553. next();
  1554. })
  1555. .catch(err => {
  1556. next(err);
  1557. });
  1558. }
  1559. }
  1560. ],
  1561. async err => {
  1562. if (err) {
  1563. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1564. this.log(
  1565. "ERROR",
  1566. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1567. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1568. );
  1569. return cb({ status: "failure", message: err });
  1570. }
  1571. this.log(
  1572. "SUCCESS",
  1573. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1574. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  1575. );
  1576. return cb({
  1577. status: "success",
  1578. message: "Playlist has been successfully cleared and refilled"
  1579. });
  1580. }
  1581. );
  1582. }),
  1583. /**
  1584. * Clears and refills all station playlists
  1585. *
  1586. * @param {object} session - the session object automatically added by socket.io
  1587. * @param {Function} cb - gets called with the result
  1588. */
  1589. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  1590. async.waterfall(
  1591. [
  1592. next => {
  1593. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  1594. .then(response => {
  1595. next(null, response.playlists);
  1596. })
  1597. .catch(err => {
  1598. next(err);
  1599. });
  1600. },
  1601. (playlists, next) => {
  1602. async.eachLimit(
  1603. playlists,
  1604. 1,
  1605. (playlist, next) => {
  1606. PlaylistsModule.runJob(
  1607. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  1608. { playlistId: playlist._id },
  1609. this
  1610. )
  1611. .then(() => {
  1612. next();
  1613. })
  1614. .catch(err => {
  1615. next(err);
  1616. });
  1617. },
  1618. next
  1619. );
  1620. }
  1621. ],
  1622. async err => {
  1623. if (err) {
  1624. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1625. this.log(
  1626. "ERROR",
  1627. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1628. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  1629. );
  1630. return cb({ status: "failure", message: err });
  1631. }
  1632. this.log(
  1633. "SUCCESS",
  1634. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1635. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  1636. );
  1637. return cb({
  1638. status: "success",
  1639. message: "Playlists have been successfully cleared and refilled"
  1640. });
  1641. }
  1642. );
  1643. }),
  1644. /**
  1645. * Clears and refills all genre playlists
  1646. *
  1647. * @param {object} session - the session object automatically added by socket.io
  1648. * @param {Function} cb - gets called with the result
  1649. */
  1650. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1651. async.waterfall(
  1652. [
  1653. next => {
  1654. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  1655. .then(response => {
  1656. next(null, response.playlists);
  1657. })
  1658. .catch(err => {
  1659. next(err);
  1660. });
  1661. },
  1662. (playlists, next) => {
  1663. async.eachLimit(
  1664. playlists,
  1665. 1,
  1666. (playlist, next) => {
  1667. PlaylistsModule.runJob(
  1668. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1669. { playlistId: playlist._id },
  1670. this
  1671. )
  1672. .then(() => {
  1673. next();
  1674. })
  1675. .catch(err => {
  1676. next(err);
  1677. });
  1678. },
  1679. next
  1680. );
  1681. }
  1682. ],
  1683. async err => {
  1684. if (err) {
  1685. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1686. this.log(
  1687. "ERROR",
  1688. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1689. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  1690. );
  1691. return cb({ status: "failure", message: err });
  1692. }
  1693. this.log(
  1694. "SUCCESS",
  1695. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1696. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  1697. );
  1698. return cb({
  1699. status: "success",
  1700. message: "Playlists have been successfully cleared and refilled"
  1701. });
  1702. }
  1703. );
  1704. })
  1705. };