playlists.js 61 KB

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