playlists.js 59 KB

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