playlists.js 52 KB

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