playlists.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245
  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. * Shuffles songs in a private 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 updating
  718. * @param {Function} cb - gets called with the result
  719. */
  720. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  721. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  722. async.waterfall(
  723. [
  724. next => {
  725. if (!playlistId) return next("No playlist id.");
  726. return playlistModel.findById(playlistId, next);
  727. },
  728. (playlist, next) => {
  729. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  730. return UtilsModule.runJob("SHUFFLE_SONG_POSITIONS", { array: playlist.songs }, this)
  731. .then(result => next(null, result.array))
  732. .catch(next);
  733. },
  734. (songs, next) => {
  735. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  736. },
  737. (res, next) => {
  738. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  739. .then(playlist => next(null, playlist))
  740. .catch(next);
  741. }
  742. ],
  743. async (err, playlist) => {
  744. if (err) {
  745. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  746. this.log(
  747. "ERROR",
  748. "PLAYLIST_SHUFFLE",
  749. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  750. );
  751. return cb({ status: "error", message: err });
  752. }
  753. this.log(
  754. "SUCCESS",
  755. "PLAYLIST_SHUFFLE",
  756. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  757. );
  758. return cb({
  759. status: "success",
  760. message: "Successfully shuffled playlist.",
  761. data: { playlist }
  762. });
  763. }
  764. );
  765. }),
  766. /**
  767. * Changes the order (position) of a song in a playlist
  768. *
  769. * @param {object} session - the session object automatically added by the websocket
  770. * @param {string} playlistId - the id of the playlist we are targeting
  771. * @param {object} song - the song to be repositioned
  772. * @param {string} song.youtubeId - the youtube id of the song being repositioned
  773. * @param {string} song.newIndex - the new position of the song in the playlist
  774. * @param {...any} song.args - any other elements that would be included with a song item in a playlist
  775. * @param {Function} cb - gets called with the result
  776. */
  777. repositionSong: isLoginRequired(async function repositionSong(session, playlistId, song, cb) {
  778. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  779. async.waterfall(
  780. [
  781. next => {
  782. if (!playlistId) return next("Please provide a playlist.");
  783. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  784. return next();
  785. },
  786. // remove song from playlist
  787. next => {
  788. playlistModel.updateOne(
  789. { _id: playlistId },
  790. { $pull: { songs: { youtubeId: song.youtubeId } } },
  791. next
  792. );
  793. },
  794. // add song back to playlist (in new position)
  795. (res, next) => {
  796. playlistModel.updateOne(
  797. { _id: playlistId },
  798. { $push: { songs: { $each: [song], $position: song.newIndex } } },
  799. err => next(err)
  800. );
  801. },
  802. // update the cache with the new songs positioning
  803. next => {
  804. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  805. .then(playlist => next(null, playlist))
  806. .catch(next);
  807. }
  808. ],
  809. async err => {
  810. if (err) {
  811. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  812. this.log(
  813. "ERROR",
  814. "PLAYLIST_REPOSITION_SONG",
  815. `Repositioning song ${song.youtubeId} for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  816. );
  817. return cb({ status: "error", message: err });
  818. }
  819. this.log(
  820. "SUCCESS",
  821. "PLAYLIST_REPOSITION_SONG",
  822. `Successfully repositioned song ${song.youtubeId} for private playlist "${playlistId}" for user "${session.userId}".`
  823. );
  824. CacheModule.runJob("PUB", {
  825. channel: "playlist.repositionSong",
  826. value: {
  827. userId: session.userId,
  828. playlistId,
  829. song
  830. }
  831. });
  832. return cb({
  833. status: "success",
  834. message: "Successfully repositioned song"
  835. });
  836. }
  837. );
  838. }),
  839. /**
  840. * Adds a song to a private playlist
  841. *
  842. * @param {object} session - the session object automatically added by the websocket
  843. * @param {boolean} isSet - is the song part of a set of songs to be added
  844. * @param {string} youtubeId - the youtube id of the song we are trying to add
  845. * @param {string} playlistId - the id of the playlist we are adding the song to
  846. * @param {Function} cb - gets called with the result
  847. */
  848. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, youtubeId, playlistId, cb) {
  849. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  850. async.waterfall(
  851. [
  852. next => {
  853. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  854. .then(playlist => {
  855. if (!playlist || playlist.createdBy !== session.userId)
  856. return next("Something went wrong when trying to get the playlist");
  857. return async.each(
  858. playlist.songs,
  859. (song, nextSong) => {
  860. if (song.youtubeId === youtubeId)
  861. return next("That song is already in the playlist");
  862. return nextSong();
  863. },
  864. err => next(err, playlist)
  865. );
  866. })
  867. .catch(next);
  868. },
  869. (playlist, next) => {
  870. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  871. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  872. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  873. playlistModel.count(
  874. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  875. (err, results) => {
  876. if (err) next(err);
  877. else if (results > 0)
  878. next(
  879. `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.`
  880. );
  881. else next();
  882. }
  883. );
  884. } else next();
  885. },
  886. next => {
  887. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  888. .then(UserModel => {
  889. UserModel.findOne(
  890. { _id: session.userId },
  891. { "preferences.anonymousSongRequests": 1 },
  892. next
  893. );
  894. })
  895. .catch(next);
  896. },
  897. (user, next) => {
  898. SongsModule.runJob(
  899. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  900. {
  901. youtubeId,
  902. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  903. automaticallyRequested: true
  904. },
  905. this
  906. )
  907. .then(response => {
  908. const { song } = response;
  909. const { _id, title, artists, thumbnail, duration, status } = song;
  910. next(null, {
  911. _id,
  912. youtubeId,
  913. title,
  914. artists,
  915. thumbnail,
  916. duration,
  917. status
  918. });
  919. })
  920. .catch(next);
  921. },
  922. (newSong, next) => {
  923. playlistModel.updateOne(
  924. { _id: playlistId },
  925. { $push: { songs: newSong } },
  926. { runValidators: true },
  927. err => {
  928. if (err) return next(err);
  929. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  930. .then(playlist => next(null, playlist, newSong))
  931. .catch(next);
  932. }
  933. );
  934. },
  935. (playlist, newSong, next) => {
  936. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  937. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  938. songId: newSong._id,
  939. youtubeId: newSong.youtubeId
  940. })
  941. .then(ratings => next(null, playlist, newSong, ratings))
  942. .catch(next);
  943. } else {
  944. next(null, playlist, newSong, null);
  945. }
  946. }
  947. ],
  948. async (err, playlist, newSong, ratings) => {
  949. if (err) {
  950. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  951. this.log(
  952. "ERROR",
  953. "PLAYLIST_ADD_SONG",
  954. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  955. );
  956. return cb({ status: "error", message: err });
  957. }
  958. this.log(
  959. "SUCCESS",
  960. "PLAYLIST_ADD_SONG",
  961. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  962. );
  963. if (!isSet && playlist.type !== "user-liked" && playlist.type !== "user-disliked") {
  964. const songName = newSong.artists
  965. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  966. : newSong.title;
  967. if (playlist.privacy === "public")
  968. ActivitiesModule.runJob("ADD_ACTIVITY", {
  969. userId: session.userId,
  970. type: "playlist__add_song",
  971. payload: {
  972. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  973. thumbnail: newSong.thumbnail,
  974. playlistId,
  975. youtubeId
  976. }
  977. });
  978. }
  979. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  980. .then(response => {
  981. response.stationIds.forEach(stationId => {
  982. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  983. });
  984. })
  985. .catch();
  986. CacheModule.runJob("PUB", {
  987. channel: "playlist.addSong",
  988. value: {
  989. playlistId: playlist._id,
  990. song: newSong,
  991. userId: session.userId,
  992. privacy: playlist.privacy
  993. }
  994. });
  995. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  996. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  997. const { likes, dislikes } = ratings;
  998. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  999. if (playlist.type === "user-liked") {
  1000. CacheModule.runJob("PUB", {
  1001. channel: "song.like",
  1002. value: JSON.stringify({
  1003. youtubeId,
  1004. userId: session.userId,
  1005. likes,
  1006. dislikes
  1007. })
  1008. });
  1009. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1010. userId: session.userId,
  1011. type: "song__like",
  1012. payload: {
  1013. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1014. youtubeId,
  1015. thumbnail
  1016. }
  1017. });
  1018. } else {
  1019. CacheModule.runJob("PUB", {
  1020. channel: "song.dislike",
  1021. value: JSON.stringify({
  1022. youtubeId,
  1023. userId: session.userId,
  1024. likes,
  1025. dislikes
  1026. })
  1027. });
  1028. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1029. userId: session.userId,
  1030. type: "song__dislike",
  1031. payload: {
  1032. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1033. youtubeId,
  1034. thumbnail
  1035. }
  1036. });
  1037. }
  1038. }
  1039. return cb({
  1040. status: "success",
  1041. message: "Song has been successfully added to the playlist",
  1042. data: { songs: playlist.songs }
  1043. });
  1044. }
  1045. );
  1046. }),
  1047. /**
  1048. * Adds a set of songs to a private playlist
  1049. *
  1050. * @param {object} session - the session object automatically added by the websocket
  1051. * @param {string} url - the url of the the YouTube playlist
  1052. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1053. * @param {boolean} musicOnly - whether to only add music to the playlist
  1054. * @param {Function} cb - gets called with the result
  1055. */
  1056. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1057. let videosInPlaylistTotal = 0;
  1058. let songsInPlaylistTotal = 0;
  1059. let addSongsStats = null;
  1060. const addedSongs = [];
  1061. async.waterfall(
  1062. [
  1063. next => {
  1064. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  1065. .then(res => {
  1066. if (res.filteredSongs) {
  1067. videosInPlaylistTotal = res.songs.length;
  1068. songsInPlaylistTotal = res.filteredSongs.length;
  1069. } else {
  1070. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1071. }
  1072. next(null, res.songs);
  1073. })
  1074. .catch(err => {
  1075. next(err);
  1076. });
  1077. },
  1078. (youtubeIds, next) => {
  1079. let successful = 0;
  1080. let failed = 0;
  1081. let alreadyInPlaylist = 0;
  1082. let alreadyInLikedPlaylist = 0;
  1083. let alreadyInDislikedPlaylist = 0;
  1084. if (youtubeIds.length === 0) next();
  1085. async.eachLimit(
  1086. youtubeIds,
  1087. 1,
  1088. (youtubeId, next) => {
  1089. WSModule.runJob(
  1090. "RUN_ACTION2",
  1091. {
  1092. session,
  1093. namespace: "playlists",
  1094. action: "addSongToPlaylist",
  1095. args: [true, youtubeId, playlistId]
  1096. },
  1097. this
  1098. )
  1099. .then(res => {
  1100. if (res.status === "success") {
  1101. successful += 1;
  1102. addedSongs.push(youtubeId);
  1103. } else failed += 1;
  1104. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1105. else if (
  1106. res.message ===
  1107. "That song is already in your Liked Songs playlist. " +
  1108. "A song cannot be in both the Liked Songs playlist" +
  1109. " and the Disliked Songs playlist at the same time."
  1110. )
  1111. alreadyInLikedPlaylist += 1;
  1112. else if (
  1113. res.message ===
  1114. "That song is already in your Disliked Songs playlist. " +
  1115. "A song cannot be in both the Liked Songs playlist " +
  1116. "and the Disliked Songs playlist at the same time."
  1117. )
  1118. alreadyInDislikedPlaylist += 1;
  1119. })
  1120. .catch(() => {
  1121. failed += 1;
  1122. })
  1123. .finally(() => next());
  1124. },
  1125. () => {
  1126. addSongsStats = {
  1127. successful,
  1128. failed,
  1129. alreadyInPlaylist,
  1130. alreadyInLikedPlaylist,
  1131. alreadyInDislikedPlaylist
  1132. };
  1133. next(null);
  1134. }
  1135. );
  1136. },
  1137. next => {
  1138. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1139. .then(playlist => next(null, playlist))
  1140. .catch(next);
  1141. },
  1142. (playlist, next) => {
  1143. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  1144. return next(null, playlist);
  1145. }
  1146. ],
  1147. async (err, playlist) => {
  1148. if (err) {
  1149. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1150. this.log(
  1151. "ERROR",
  1152. "PLAYLIST_IMPORT",
  1153. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1154. );
  1155. return cb({ status: "error", message: err });
  1156. }
  1157. if (playlist.privacy === "public")
  1158. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1159. userId: session.userId,
  1160. type: "playlist__import_playlist",
  1161. payload: {
  1162. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1163. playlistId
  1164. }
  1165. });
  1166. this.log(
  1167. "SUCCESS",
  1168. "PLAYLIST_IMPORT",
  1169. `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}.`
  1170. );
  1171. return cb({
  1172. status: "success",
  1173. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1174. data: {
  1175. songs: playlist.songs,
  1176. stats: {
  1177. videosInPlaylistTotal,
  1178. songsInPlaylistTotal,
  1179. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1180. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1181. }
  1182. }
  1183. });
  1184. }
  1185. );
  1186. }),
  1187. /**
  1188. * Removes a song from a private playlist
  1189. *
  1190. * @param {object} session - the session object automatically added by the websocket
  1191. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1192. * @param {string} playlistId - the id of the playlist we are removing the song from
  1193. * @param {Function} cb - gets called with the result
  1194. */
  1195. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1196. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1197. async.waterfall(
  1198. [
  1199. next => {
  1200. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1201. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1202. return next();
  1203. },
  1204. // remove song from playlist
  1205. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { youtubeId } } }, next),
  1206. // update cache representation of the playlist
  1207. (res, next) => {
  1208. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1209. .then(playlist => next(null, playlist))
  1210. .catch(next);
  1211. },
  1212. (playlist, next) => {
  1213. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  1214. .then(response => {
  1215. response.stationIds.forEach(stationId => {
  1216. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1217. });
  1218. })
  1219. .catch();
  1220. SongsModule.runJob("GET_SONG_FROM_YOUTUBE_ID", { youtubeId }, this)
  1221. .then(res =>
  1222. next(null, playlist, {
  1223. _id: res.song._id,
  1224. title: res.song.title,
  1225. thumbnail: res.song.thumbnail,
  1226. artists: res.song.artists,
  1227. youtubeId: res.song.youtubeId
  1228. })
  1229. )
  1230. .catch(() => {
  1231. YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1232. .then(response => next(null, playlist, response.song))
  1233. .catch(next);
  1234. });
  1235. },
  1236. (playlist, newSong, next) => {
  1237. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1238. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1239. songId: newSong._id,
  1240. youtubeId: newSong.youtubeId
  1241. })
  1242. .then(ratings => next(null, playlist, newSong, ratings))
  1243. .catch(next);
  1244. } else {
  1245. next(null, playlist, newSong, null);
  1246. }
  1247. },
  1248. (playlist, newSong, ratings, next) => {
  1249. const { _id, title, artists, thumbnail } = newSong;
  1250. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1251. if (
  1252. playlist.type !== "user-liked" &&
  1253. playlist.type !== "user-disliked" &&
  1254. playlist.privacy === "public"
  1255. ) {
  1256. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1257. userId: session.userId,
  1258. type: "playlist__remove_song",
  1259. payload: {
  1260. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1261. thumbnail,
  1262. playlistId,
  1263. youtubeId: newSong.youtubeId
  1264. }
  1265. });
  1266. }
  1267. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1268. const { likes, dislikes } = ratings;
  1269. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1270. if (playlist.type === "user-liked") {
  1271. CacheModule.runJob("PUB", {
  1272. channel: "song.unlike",
  1273. value: JSON.stringify({
  1274. youtubeId: newSong.youtubeId,
  1275. userId: session.userId,
  1276. likes,
  1277. dislikes
  1278. })
  1279. });
  1280. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1281. userId: session.userId,
  1282. type: "song__unlike",
  1283. payload: {
  1284. message: `Removed <youtubeId>${title} by ${artists.join(
  1285. ", "
  1286. )}</youtubeId> from your Liked Songs`,
  1287. youtubeId: newSong.youtubeId,
  1288. thumbnail
  1289. }
  1290. });
  1291. } else {
  1292. CacheModule.runJob("PUB", {
  1293. channel: "song.undislike",
  1294. value: JSON.stringify({
  1295. youtubeId: newSong.youtubeId,
  1296. userId: session.userId,
  1297. likes,
  1298. dislikes
  1299. })
  1300. });
  1301. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1302. userId: session.userId,
  1303. type: "song__undislike",
  1304. payload: {
  1305. message: `Removed <youtubeId>${title} by ${artists.join(
  1306. ", "
  1307. )}</youtubeId> from your Disliked Songs`,
  1308. youtubeId: newSong.youtubeId,
  1309. thumbnail
  1310. }
  1311. });
  1312. }
  1313. }
  1314. return next(null, playlist);
  1315. }
  1316. ],
  1317. async (err, playlist) => {
  1318. if (err) {
  1319. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1320. this.log(
  1321. "ERROR",
  1322. "PLAYLIST_REMOVE_SONG",
  1323. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1324. );
  1325. return cb({ status: "error", message: err });
  1326. }
  1327. this.log(
  1328. "SUCCESS",
  1329. "PLAYLIST_REMOVE_SONG",
  1330. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1331. );
  1332. CacheModule.runJob("PUB", {
  1333. channel: "playlist.removeSong",
  1334. value: {
  1335. playlistId: playlist._id,
  1336. youtubeId,
  1337. userId: session.userId,
  1338. privacy: playlist.privacy
  1339. }
  1340. });
  1341. return cb({
  1342. status: "success",
  1343. message: "Song has been successfully removed from playlist",
  1344. data: { songs: playlist.songs }
  1345. });
  1346. }
  1347. );
  1348. }),
  1349. /**
  1350. * Updates the displayName of a private playlist
  1351. *
  1352. * @param {object} session - the session object automatically added by the websocket
  1353. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1354. * @param {Function} cb - gets called with the result
  1355. */
  1356. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1357. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1358. async.waterfall(
  1359. [
  1360. next => {
  1361. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1362. .then(playlist => next(null, playlist))
  1363. .catch(next);
  1364. },
  1365. (playlist, next) => {
  1366. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1367. return next(null);
  1368. },
  1369. next => {
  1370. playlistModel.updateOne(
  1371. { _id: playlistId, createdBy: session.userId },
  1372. { $set: { displayName } },
  1373. { runValidators: true },
  1374. next
  1375. );
  1376. },
  1377. (res, next) => {
  1378. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1379. .then(playlist => next(null, playlist))
  1380. .catch(next);
  1381. }
  1382. ],
  1383. async (err, playlist) => {
  1384. if (err) {
  1385. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1386. this.log(
  1387. "ERROR",
  1388. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1389. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1390. );
  1391. return cb({ status: "error", message: err });
  1392. }
  1393. this.log(
  1394. "SUCCESS",
  1395. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1396. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1397. );
  1398. CacheModule.runJob("PUB", {
  1399. channel: "playlist.updateDisplayName",
  1400. value: {
  1401. playlistId,
  1402. displayName,
  1403. userId: session.userId,
  1404. privacy: playlist.privacy
  1405. }
  1406. });
  1407. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1408. userId: session.userId,
  1409. type: "playlist__edit_display_name",
  1410. payload: {
  1411. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1412. playlistId
  1413. }
  1414. });
  1415. return cb({
  1416. status: "success",
  1417. message: "Playlist has been successfully updated"
  1418. });
  1419. }
  1420. );
  1421. }),
  1422. /**
  1423. * Removes a user's own modifiable user playlist
  1424. *
  1425. * @param {object} session - the session object automatically added by the websocket
  1426. * @param {string} playlistId - the id of the playlist we are removing
  1427. * @param {Function} cb - gets called with the result
  1428. */
  1429. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1430. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1431. async.waterfall(
  1432. [
  1433. next => {
  1434. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1435. .then(playlist => next(null, playlist))
  1436. .catch(next);
  1437. },
  1438. (playlist, next) => {
  1439. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1440. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1441. return next(null, playlist);
  1442. },
  1443. (playlist, next) => {
  1444. userModel.updateOne(
  1445. { _id: playlist.createdBy },
  1446. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1447. err => next(err, playlist)
  1448. );
  1449. },
  1450. (playlist, next) => {
  1451. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1452. .then(() => next(null, playlist))
  1453. .catch(next);
  1454. }
  1455. ],
  1456. async (err, playlist) => {
  1457. if (err) {
  1458. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1459. this.log(
  1460. "ERROR",
  1461. "PLAYLIST_REMOVE",
  1462. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1463. );
  1464. return cb({ status: "error", message: err });
  1465. }
  1466. this.log(
  1467. "SUCCESS",
  1468. "PLAYLIST_REMOVE",
  1469. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1470. );
  1471. CacheModule.runJob("PUB", {
  1472. channel: "playlist.delete",
  1473. value: {
  1474. userId: session.userId,
  1475. playlistId
  1476. }
  1477. });
  1478. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1479. userId: playlist.createdBy,
  1480. type: "playlist__remove",
  1481. payload: {
  1482. message: `Removed playlist ${playlist.displayName}`
  1483. }
  1484. });
  1485. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1486. return cb({
  1487. status: "success",
  1488. message: "Playlist successfully removed"
  1489. });
  1490. }
  1491. );
  1492. }),
  1493. /**
  1494. * Removes a user's modifiable user playlist as an admin
  1495. *
  1496. * @param {object} session - the session object automatically added by the websocket
  1497. * @param {string} playlistId - the id of the playlist we are removing
  1498. * @param {Function} cb - gets called with the result
  1499. */
  1500. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1501. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1502. async.waterfall(
  1503. [
  1504. next => {
  1505. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1506. .then(playlist => next(null, playlist))
  1507. .catch(next);
  1508. },
  1509. (playlist, next) => {
  1510. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1511. return next(null, playlist);
  1512. },
  1513. (playlist, next) => {
  1514. userModel.updateOne(
  1515. { _id: playlist.createdBy },
  1516. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1517. err => next(err, playlist, playlist.createdBy)
  1518. );
  1519. },
  1520. (playlist, playlistCreator, next) => {
  1521. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1522. .then(() => next(null, playlistCreator))
  1523. .catch(next);
  1524. }
  1525. ],
  1526. async (err, playlistCreator) => {
  1527. if (err) {
  1528. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1529. this.log(
  1530. "ERROR",
  1531. "PLAYLIST_REMOVE_ADMIN",
  1532. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1533. );
  1534. return cb({ status: "error", message: err });
  1535. }
  1536. this.log(
  1537. "SUCCESS",
  1538. "PLAYLIST_REMOVE_ADMIN",
  1539. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1540. );
  1541. CacheModule.runJob("PUB", {
  1542. channel: "playlist.delete",
  1543. value: {
  1544. userId: playlistCreator,
  1545. playlistId
  1546. }
  1547. });
  1548. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1549. return cb({
  1550. status: "success",
  1551. message: "Playlist successfully removed"
  1552. });
  1553. }
  1554. );
  1555. }),
  1556. /**
  1557. * Updates the privacy of a private playlist
  1558. *
  1559. * @param {object} session - the session object automatically added by the websocket
  1560. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1561. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1562. * @param {Function} cb - gets called with the result
  1563. */
  1564. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1565. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1566. async.waterfall(
  1567. [
  1568. next => {
  1569. playlistModel.updateOne(
  1570. { _id: playlistId, createdBy: session.userId },
  1571. { $set: { privacy } },
  1572. { runValidators: true },
  1573. next
  1574. );
  1575. },
  1576. (res, next) => {
  1577. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1578. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1579. else {
  1580. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1581. .then(playlist => next(null, playlist))
  1582. .catch(next);
  1583. }
  1584. }
  1585. ],
  1586. async (err, playlist) => {
  1587. if (err) {
  1588. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1589. this.log(
  1590. "ERROR",
  1591. "PLAYLIST_UPDATE_PRIVACY",
  1592. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1593. );
  1594. return cb({ status: "error", message: err });
  1595. }
  1596. this.log(
  1597. "SUCCESS",
  1598. "PLAYLIST_UPDATE_PRIVACY",
  1599. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1600. );
  1601. CacheModule.runJob("PUB", {
  1602. channel: "playlist.updatePrivacy",
  1603. value: {
  1604. userId: session.userId,
  1605. playlist
  1606. }
  1607. });
  1608. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1609. userId: session.userId,
  1610. type: "playlist__edit_privacy",
  1611. payload: {
  1612. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1613. playlistId
  1614. }
  1615. });
  1616. return cb({
  1617. status: "success",
  1618. message: "Playlist has been successfully updated"
  1619. });
  1620. }
  1621. );
  1622. }),
  1623. /**
  1624. * Updates the privacy of a playlist
  1625. *
  1626. * @param {object} session - the session object automatically added by the websocket
  1627. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1628. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1629. * @param {Function} cb - gets called with the result
  1630. */
  1631. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1632. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1633. async.waterfall(
  1634. [
  1635. next => {
  1636. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1637. },
  1638. (res, next) => {
  1639. if (res.n === 0) next("No playlist found with that id.");
  1640. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1641. else {
  1642. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1643. .then(playlist => next(null, playlist))
  1644. .catch(next);
  1645. }
  1646. }
  1647. ],
  1648. async (err, playlist) => {
  1649. if (err) {
  1650. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1651. this.log(
  1652. "ERROR",
  1653. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1654. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1655. );
  1656. return cb({ status: "error", message: err });
  1657. }
  1658. this.log(
  1659. "SUCCESS",
  1660. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1661. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1662. );
  1663. if (playlist.type === "user") {
  1664. CacheModule.runJob("PUB", {
  1665. channel: "playlist.updatePrivacy",
  1666. value: {
  1667. userId: playlist.createdBy,
  1668. playlist
  1669. }
  1670. });
  1671. }
  1672. return cb({
  1673. status: "success",
  1674. message: "Playlist has been successfully updated"
  1675. });
  1676. }
  1677. );
  1678. }),
  1679. /**
  1680. * Deletes all orphaned station playlists
  1681. *
  1682. * @param {object} session - the session object automatically added by socket.io
  1683. * @param {Function} cb - gets called with the result
  1684. */
  1685. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1686. async.waterfall(
  1687. [
  1688. next => {
  1689. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1690. .then(() => next())
  1691. .catch(next);
  1692. }
  1693. ],
  1694. async err => {
  1695. if (err) {
  1696. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1697. this.log(
  1698. "ERROR",
  1699. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1700. `Deleting orphaned station playlists failed. "${err}"`
  1701. );
  1702. return cb({ status: "error", message: err });
  1703. }
  1704. this.log(
  1705. "SUCCESS",
  1706. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1707. "Deleting orphaned station playlists successful."
  1708. );
  1709. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1710. }
  1711. );
  1712. }),
  1713. /**
  1714. * Deletes all orphaned genre playlists
  1715. *
  1716. * @param {object} session - the session object automatically added by socket.io
  1717. * @param {Function} cb - gets called with the result
  1718. */
  1719. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1720. async.waterfall(
  1721. [
  1722. next => {
  1723. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1724. .then(() => next())
  1725. .catch(next);
  1726. }
  1727. ],
  1728. async err => {
  1729. if (err) {
  1730. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1731. this.log(
  1732. "ERROR",
  1733. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1734. `Deleting orphaned genre playlists failed. "${err}"`
  1735. );
  1736. return cb({ status: "error", message: err });
  1737. }
  1738. this.log(
  1739. "SUCCESS",
  1740. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1741. "Deleting orphaned genre playlists successful."
  1742. );
  1743. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1744. }
  1745. );
  1746. }),
  1747. /**
  1748. * Requests orpahned playlist songs
  1749. *
  1750. * @param {object} session - the session object automatically added by socket.io
  1751. * @param {Function} cb - gets called with the result
  1752. */
  1753. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1754. async.waterfall(
  1755. [
  1756. next => {
  1757. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1758. .then(() => next())
  1759. .catch(next);
  1760. }
  1761. ],
  1762. async err => {
  1763. if (err) {
  1764. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1765. this.log(
  1766. "ERROR",
  1767. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1768. `Requesting orphaned playlist songs failed. "${err}"`
  1769. );
  1770. return cb({ status: "error", message: err });
  1771. }
  1772. this.log(
  1773. "SUCCESS",
  1774. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1775. "Requesting orphaned playlist songs was successful."
  1776. );
  1777. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1778. }
  1779. );
  1780. }),
  1781. /**
  1782. * Clears and refills a station playlist
  1783. *
  1784. * @param {object} session - the session object automatically added by socket.io
  1785. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1786. * @param {Function} cb - gets called with the result
  1787. */
  1788. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1789. async.waterfall(
  1790. [
  1791. next => {
  1792. if (!playlistId) next("Please specify a playlist id");
  1793. else {
  1794. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1795. .then(() => {
  1796. next();
  1797. })
  1798. .catch(err => {
  1799. next(err);
  1800. });
  1801. }
  1802. }
  1803. ],
  1804. async err => {
  1805. if (err) {
  1806. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1807. this.log(
  1808. "ERROR",
  1809. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1810. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1811. );
  1812. return cb({ status: "error", message: err });
  1813. }
  1814. this.log(
  1815. "SUCCESS",
  1816. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1817. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  1818. );
  1819. return cb({
  1820. status: "success",
  1821. message: "Playlist has been successfully cleared and refilled"
  1822. });
  1823. }
  1824. );
  1825. }),
  1826. /**
  1827. * Clears and refills a genre playlist
  1828. *
  1829. * @param {object} session - the session object automatically added by socket.io
  1830. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1831. * @param {Function} cb - gets called with the result
  1832. */
  1833. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1834. async.waterfall(
  1835. [
  1836. next => {
  1837. if (!playlistId) next("Please specify a playlist id");
  1838. else {
  1839. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  1840. .then(() => {
  1841. next();
  1842. })
  1843. .catch(err => {
  1844. next(err);
  1845. });
  1846. }
  1847. }
  1848. ],
  1849. async err => {
  1850. if (err) {
  1851. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1852. this.log(
  1853. "ERROR",
  1854. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1855. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1856. );
  1857. return cb({ status: "error", message: err });
  1858. }
  1859. this.log(
  1860. "SUCCESS",
  1861. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1862. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  1863. );
  1864. return cb({
  1865. status: "success",
  1866. message: "Playlist has been successfully cleared and refilled"
  1867. });
  1868. }
  1869. );
  1870. }),
  1871. /**
  1872. * Clears and refills all station playlists
  1873. *
  1874. * @param {object} session - the session object automatically added by socket.io
  1875. * @param {Function} cb - gets called with the result
  1876. */
  1877. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  1878. async.waterfall(
  1879. [
  1880. next => {
  1881. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  1882. .then(response => {
  1883. next(null, response.playlists);
  1884. })
  1885. .catch(err => {
  1886. next(err);
  1887. });
  1888. },
  1889. (playlists, next) => {
  1890. async.eachLimit(
  1891. playlists,
  1892. 1,
  1893. (playlist, next) => {
  1894. PlaylistsModule.runJob(
  1895. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  1896. { playlistId: playlist._id },
  1897. this
  1898. )
  1899. .then(() => {
  1900. next();
  1901. })
  1902. .catch(err => {
  1903. next(err);
  1904. });
  1905. },
  1906. next
  1907. );
  1908. }
  1909. ],
  1910. async err => {
  1911. if (err) {
  1912. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1913. this.log(
  1914. "ERROR",
  1915. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1916. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  1917. );
  1918. return cb({ status: "error", message: err });
  1919. }
  1920. this.log(
  1921. "SUCCESS",
  1922. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1923. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  1924. );
  1925. return cb({
  1926. status: "success",
  1927. message: "Playlists have been successfully cleared and refilled"
  1928. });
  1929. }
  1930. );
  1931. }),
  1932. /**
  1933. * Clears and refills all genre playlists
  1934. *
  1935. * @param {object} session - the session object automatically added by socket.io
  1936. * @param {Function} cb - gets called with the result
  1937. */
  1938. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1939. async.waterfall(
  1940. [
  1941. next => {
  1942. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  1943. .then(response => {
  1944. next(null, response.playlists);
  1945. })
  1946. .catch(err => {
  1947. next(err);
  1948. });
  1949. },
  1950. (playlists, next) => {
  1951. async.eachLimit(
  1952. playlists,
  1953. 1,
  1954. (playlist, next) => {
  1955. PlaylistsModule.runJob(
  1956. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1957. { playlistId: playlist._id },
  1958. this
  1959. )
  1960. .then(() => {
  1961. next();
  1962. })
  1963. .catch(err => {
  1964. next(err);
  1965. });
  1966. },
  1967. next
  1968. );
  1969. }
  1970. ],
  1971. async err => {
  1972. if (err) {
  1973. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1974. this.log(
  1975. "ERROR",
  1976. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1977. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  1978. );
  1979. return cb({ status: "error", message: err });
  1980. }
  1981. this.log(
  1982. "SUCCESS",
  1983. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1984. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  1985. );
  1986. return cb({
  1987. status: "success",
  1988. message: "Playlists have been successfully cleared and refilled"
  1989. });
  1990. }
  1991. );
  1992. }),
  1993. /**
  1994. * Create missing genre playlists
  1995. *
  1996. * @param {object} session - the session object automatically added by socket.io
  1997. * @param {Function} cb - gets called with the result
  1998. */
  1999. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2000. async.waterfall(
  2001. [
  2002. next => {
  2003. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2004. .then(() => {
  2005. next();
  2006. })
  2007. .catch(err => {
  2008. next(err);
  2009. });
  2010. }
  2011. ],
  2012. async err => {
  2013. if (err) {
  2014. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2015. this.log(
  2016. "ERROR",
  2017. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2018. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2019. );
  2020. return cb({ status: "error", message: err });
  2021. }
  2022. this.log(
  2023. "SUCCESS",
  2024. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2025. `Successfully created missing genre playlists for user "${session.userId}".`
  2026. );
  2027. return cb({
  2028. status: "success",
  2029. message: "Missing genre playlists have been successfully created"
  2030. });
  2031. }
  2032. );
  2033. })
  2034. };