playlists.js 52 KB

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