playlists.js 59 KB

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