playlists.js 53 KB

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