playlists.js 63 KB

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