playlists.js 64 KB

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