playlists.js 65 KB

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