playlists.js 64 KB

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