playlists.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450
  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(
  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. async.each(
  1017. playlist.songs,
  1018. (song, nextSong) => {
  1019. if (song.youtubeId === youtubeId) return next("That song is already in the playlist");
  1020. return nextSong();
  1021. },
  1022. err => next(err, playlist)
  1023. );
  1024. },
  1025. (playlist, next) => {
  1026. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1027. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1028. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1029. playlistModel.count(
  1030. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1031. (err, results) => {
  1032. if (err) next(err);
  1033. else if (results > 0)
  1034. next(
  1035. `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.`
  1036. );
  1037. else next();
  1038. }
  1039. );
  1040. } else next();
  1041. },
  1042. next => {
  1043. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1044. .then(UserModel => {
  1045. UserModel.findOne(
  1046. { _id: session.userId },
  1047. { "preferences.anonymousSongRequests": 1 },
  1048. next
  1049. );
  1050. })
  1051. .catch(next);
  1052. },
  1053. (user, next) => {
  1054. SongsModule.runJob(
  1055. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  1056. {
  1057. youtubeId,
  1058. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  1059. automaticallyRequested: true
  1060. },
  1061. this
  1062. )
  1063. .then(response => {
  1064. const { song } = response;
  1065. const { _id, title, artists, thumbnail, duration, status } = song;
  1066. next(null, {
  1067. _id,
  1068. youtubeId,
  1069. title,
  1070. artists,
  1071. thumbnail,
  1072. duration,
  1073. status
  1074. });
  1075. })
  1076. .catch(next);
  1077. },
  1078. (newSong, next) => {
  1079. playlistModel.updateOne(
  1080. { _id: playlistId },
  1081. { $push: { songs: newSong } },
  1082. { runValidators: true },
  1083. err => {
  1084. if (err) return next(err);
  1085. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1086. .then(playlist => next(null, playlist, newSong))
  1087. .catch(next);
  1088. }
  1089. );
  1090. },
  1091. (playlist, newSong, next) => {
  1092. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1093. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1094. songId: newSong._id,
  1095. youtubeId: newSong.youtubeId
  1096. })
  1097. .then(ratings => next(null, playlist, newSong, ratings))
  1098. .catch(next);
  1099. } else {
  1100. next(null, playlist, newSong, null);
  1101. }
  1102. }
  1103. ],
  1104. async (err, playlist, newSong, ratings) => {
  1105. if (err) {
  1106. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1107. this.log(
  1108. "ERROR",
  1109. "PLAYLIST_ADD_SONG",
  1110. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1111. );
  1112. return cb({ status: "error", message: err });
  1113. }
  1114. this.log(
  1115. "SUCCESS",
  1116. "PLAYLIST_ADD_SONG",
  1117. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1118. );
  1119. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1120. const songName = newSong.artists
  1121. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1122. : newSong.title;
  1123. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1124. userId: session.userId,
  1125. type: "playlist__add_song",
  1126. payload: {
  1127. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1128. thumbnail: newSong.thumbnail,
  1129. playlistId,
  1130. youtubeId
  1131. }
  1132. });
  1133. }
  1134. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  1135. .then(response => {
  1136. response.stationIds.forEach(stationId => {
  1137. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1138. });
  1139. })
  1140. .catch();
  1141. CacheModule.runJob("PUB", {
  1142. channel: "playlist.addSong",
  1143. value: {
  1144. playlistId: playlist._id,
  1145. song: newSong,
  1146. userId: session.userId,
  1147. privacy: playlist.privacy
  1148. }
  1149. });
  1150. CacheModule.runJob("PUB", {
  1151. channel: "playlist.updated",
  1152. value: { playlistId }
  1153. });
  1154. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1155. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  1156. const { likes, dislikes } = ratings;
  1157. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1158. if (playlist.type === "user-liked") {
  1159. CacheModule.runJob("PUB", {
  1160. channel: "song.like",
  1161. value: JSON.stringify({
  1162. youtubeId,
  1163. userId: session.userId,
  1164. likes,
  1165. dislikes
  1166. })
  1167. });
  1168. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1169. userId: session.userId,
  1170. type: "song__like",
  1171. payload: {
  1172. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1173. youtubeId,
  1174. thumbnail
  1175. }
  1176. });
  1177. } else {
  1178. CacheModule.runJob("PUB", {
  1179. channel: "song.dislike",
  1180. value: JSON.stringify({
  1181. youtubeId,
  1182. userId: session.userId,
  1183. likes,
  1184. dislikes
  1185. })
  1186. });
  1187. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1188. userId: session.userId,
  1189. type: "song__dislike",
  1190. payload: {
  1191. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1192. youtubeId,
  1193. thumbnail
  1194. }
  1195. });
  1196. }
  1197. }
  1198. return cb({
  1199. status: "success",
  1200. message: "Song has been successfully added to the playlist",
  1201. data: { songs: playlist.songs }
  1202. });
  1203. }
  1204. );
  1205. }),
  1206. /**
  1207. * Adds a set of songs to a private playlist
  1208. *
  1209. * @param {object} session - the session object automatically added by the websocket
  1210. * @param {string} url - the url of the the YouTube playlist
  1211. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1212. * @param {boolean} musicOnly - whether to only add music to the playlist
  1213. * @param {Function} cb - gets called with the result
  1214. */
  1215. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1216. let videosInPlaylistTotal = 0;
  1217. let songsInPlaylistTotal = 0;
  1218. let addSongsStats = null;
  1219. const addedSongs = [];
  1220. async.waterfall(
  1221. [
  1222. next => {
  1223. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  1224. .then(res => {
  1225. if (res.filteredSongs) {
  1226. videosInPlaylistTotal = res.songs.length;
  1227. songsInPlaylistTotal = res.filteredSongs.length;
  1228. } else {
  1229. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1230. }
  1231. next(null, res.songs);
  1232. })
  1233. .catch(err => {
  1234. next(err);
  1235. });
  1236. },
  1237. (youtubeIds, next) => {
  1238. let successful = 0;
  1239. let failed = 0;
  1240. let alreadyInPlaylist = 0;
  1241. let alreadyInLikedPlaylist = 0;
  1242. let alreadyInDislikedPlaylist = 0;
  1243. if (youtubeIds.length === 0) next();
  1244. async.eachLimit(
  1245. youtubeIds,
  1246. 1,
  1247. (youtubeId, next) => {
  1248. WSModule.runJob(
  1249. "RUN_ACTION2",
  1250. {
  1251. session,
  1252. namespace: "playlists",
  1253. action: "addSongToPlaylist",
  1254. args: [true, youtubeId, playlistId]
  1255. },
  1256. this
  1257. )
  1258. .then(res => {
  1259. if (res.status === "success") {
  1260. successful += 1;
  1261. addedSongs.push(youtubeId);
  1262. } else failed += 1;
  1263. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1264. else if (
  1265. res.message ===
  1266. "That song is already in your Liked Songs playlist. " +
  1267. "A song cannot be in both the Liked Songs playlist" +
  1268. " and the Disliked Songs playlist at the same time."
  1269. )
  1270. alreadyInLikedPlaylist += 1;
  1271. else if (
  1272. res.message ===
  1273. "That song is already in your Disliked Songs playlist. " +
  1274. "A song cannot be in both the Liked Songs playlist " +
  1275. "and the Disliked Songs playlist at the same time."
  1276. )
  1277. alreadyInDislikedPlaylist += 1;
  1278. })
  1279. .catch(() => {
  1280. failed += 1;
  1281. })
  1282. .finally(() => next());
  1283. },
  1284. () => {
  1285. addSongsStats = {
  1286. successful,
  1287. failed,
  1288. alreadyInPlaylist,
  1289. alreadyInLikedPlaylist,
  1290. alreadyInDislikedPlaylist
  1291. };
  1292. next(null);
  1293. }
  1294. );
  1295. },
  1296. next => {
  1297. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1298. .then(playlist => next(null, playlist))
  1299. .catch(next);
  1300. },
  1301. (playlist, next) => {
  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. ],
  1313. async (err, playlist) => {
  1314. if (err) {
  1315. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1316. this.log(
  1317. "ERROR",
  1318. "PLAYLIST_IMPORT",
  1319. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1320. );
  1321. return cb({ status: "error", message: err });
  1322. }
  1323. if (playlist.privacy === "public")
  1324. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1325. userId: session.userId,
  1326. type: "playlist__import_playlist",
  1327. payload: {
  1328. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1329. playlistId
  1330. }
  1331. });
  1332. this.log(
  1333. "SUCCESS",
  1334. "PLAYLIST_IMPORT",
  1335. `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}.`
  1336. );
  1337. return cb({
  1338. status: "success",
  1339. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1340. data: {
  1341. songs: playlist.songs,
  1342. stats: {
  1343. videosInPlaylistTotal,
  1344. songsInPlaylistTotal,
  1345. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1346. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1347. }
  1348. }
  1349. });
  1350. }
  1351. );
  1352. }),
  1353. /**
  1354. * Removes a song from a private playlist
  1355. *
  1356. * @param {object} session - the session object automatically added by the websocket
  1357. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1358. * @param {string} playlistId - the id of the playlist we are removing the song from
  1359. * @param {Function} cb - gets called with the result
  1360. */
  1361. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1362. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1363. async.waterfall(
  1364. [
  1365. next => {
  1366. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1367. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1368. return next();
  1369. },
  1370. next => {
  1371. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1372. .then(playlist => {
  1373. if (!playlist || playlist.createdBy !== session.userId) {
  1374. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1375. userModel.findOne({ _id: session.userId }, (err, user) => {
  1376. if (user && user.role === "admin") return next();
  1377. return next("Something went wrong when trying to get the playlist");
  1378. });
  1379. });
  1380. }
  1381. return next();
  1382. })
  1383. .catch(next);
  1384. },
  1385. // remove song from playlist
  1386. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { youtubeId } } }, next),
  1387. // update cache representation of the playlist
  1388. (res, next) => {
  1389. if (res.modifiedCount === 1)
  1390. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1391. .then(playlist => next(null, playlist))
  1392. .catch(next);
  1393. else next("Song wasn't in playlist.");
  1394. },
  1395. (playlist, next) => {
  1396. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  1397. .then(response => {
  1398. response.stationIds.forEach(stationId => {
  1399. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1400. });
  1401. })
  1402. .catch();
  1403. SongsModule.runJob("GET_SONG_FROM_YOUTUBE_ID", { youtubeId }, this)
  1404. .then(res =>
  1405. next(null, playlist, {
  1406. _id: res.song._id,
  1407. title: res.song.title,
  1408. thumbnail: res.song.thumbnail,
  1409. artists: res.song.artists,
  1410. youtubeId: res.song.youtubeId
  1411. })
  1412. )
  1413. .catch(() => {
  1414. YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1415. .then(response => next(null, playlist, response.song))
  1416. .catch(next);
  1417. });
  1418. },
  1419. (playlist, newSong, next) => {
  1420. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1421. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1422. songId: newSong._id,
  1423. youtubeId: newSong.youtubeId
  1424. })
  1425. .then(ratings => next(null, playlist, newSong, ratings))
  1426. .catch(next);
  1427. } else {
  1428. next(null, playlist, newSong, null);
  1429. }
  1430. },
  1431. (playlist, newSong, ratings, next) => {
  1432. const { _id, title, artists, thumbnail } = newSong;
  1433. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1434. if (playlist.type === "user" && playlist.privacy === "public") {
  1435. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1436. userId: session.userId,
  1437. type: "playlist__remove_song",
  1438. payload: {
  1439. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1440. thumbnail,
  1441. playlistId,
  1442. youtubeId: newSong.youtubeId
  1443. }
  1444. });
  1445. }
  1446. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1447. const { likes, dislikes } = ratings;
  1448. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1449. if (playlist.type === "user-liked") {
  1450. CacheModule.runJob("PUB", {
  1451. channel: "song.unlike",
  1452. value: JSON.stringify({
  1453. youtubeId: newSong.youtubeId,
  1454. userId: session.userId,
  1455. likes,
  1456. dislikes
  1457. })
  1458. });
  1459. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1460. userId: session.userId,
  1461. type: "song__unlike",
  1462. payload: {
  1463. message: `Removed <youtubeId>${title} by ${artists.join(
  1464. ", "
  1465. )}</youtubeId> from your Liked Songs`,
  1466. youtubeId: newSong.youtubeId,
  1467. thumbnail
  1468. }
  1469. });
  1470. } else {
  1471. CacheModule.runJob("PUB", {
  1472. channel: "song.undislike",
  1473. value: JSON.stringify({
  1474. youtubeId: newSong.youtubeId,
  1475. userId: session.userId,
  1476. likes,
  1477. dislikes
  1478. })
  1479. });
  1480. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1481. userId: session.userId,
  1482. type: "song__undislike",
  1483. payload: {
  1484. message: `Removed <youtubeId>${title} by ${artists.join(
  1485. ", "
  1486. )}</youtubeId> from your Disliked Songs`,
  1487. youtubeId: newSong.youtubeId,
  1488. thumbnail
  1489. }
  1490. });
  1491. }
  1492. }
  1493. return next(null, playlist);
  1494. }
  1495. ],
  1496. async (err, playlist) => {
  1497. if (err) {
  1498. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1499. this.log(
  1500. "ERROR",
  1501. "PLAYLIST_REMOVE_SONG",
  1502. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1503. );
  1504. return cb({ status: "error", message: err });
  1505. }
  1506. this.log(
  1507. "SUCCESS",
  1508. "PLAYLIST_REMOVE_SONG",
  1509. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1510. );
  1511. CacheModule.runJob("PUB", {
  1512. channel: "playlist.removeSong",
  1513. value: {
  1514. playlistId: playlist._id,
  1515. youtubeId,
  1516. userId: session.userId,
  1517. privacy: playlist.privacy
  1518. }
  1519. });
  1520. CacheModule.runJob("PUB", {
  1521. channel: "playlist.updated",
  1522. value: { playlistId }
  1523. });
  1524. return cb({
  1525. status: "success",
  1526. message: "Song has been successfully removed from playlist",
  1527. data: { songs: playlist.songs }
  1528. });
  1529. }
  1530. );
  1531. }),
  1532. /**
  1533. * Updates the displayName of a private playlist
  1534. *
  1535. * @param {object} session - the session object automatically added by the websocket
  1536. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1537. * @param {Function} cb - gets called with the result
  1538. */
  1539. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1540. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1541. async.waterfall(
  1542. [
  1543. next => {
  1544. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1545. .then(playlist => next(null, playlist))
  1546. .catch(next);
  1547. },
  1548. (playlist, next) => {
  1549. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1550. return next(null);
  1551. },
  1552. next => {
  1553. playlistModel.updateOne(
  1554. { _id: playlistId, createdBy: session.userId },
  1555. { $set: { displayName } },
  1556. { runValidators: true },
  1557. next
  1558. );
  1559. },
  1560. (res, next) => {
  1561. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1562. .then(playlist => next(null, playlist))
  1563. .catch(next);
  1564. }
  1565. ],
  1566. async (err, playlist) => {
  1567. if (err) {
  1568. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1569. this.log(
  1570. "ERROR",
  1571. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1572. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1573. );
  1574. return cb({ status: "error", message: err });
  1575. }
  1576. this.log(
  1577. "SUCCESS",
  1578. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1579. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1580. );
  1581. CacheModule.runJob("PUB", {
  1582. channel: "playlist.updateDisplayName",
  1583. value: {
  1584. playlistId,
  1585. displayName,
  1586. userId: session.userId,
  1587. privacy: playlist.privacy
  1588. }
  1589. });
  1590. CacheModule.runJob("PUB", {
  1591. channel: "playlist.updated",
  1592. value: { playlistId }
  1593. });
  1594. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1595. userId: session.userId,
  1596. type: "playlist__edit_display_name",
  1597. payload: {
  1598. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1599. playlistId
  1600. }
  1601. });
  1602. return cb({
  1603. status: "success",
  1604. message: "Playlist has been successfully updated"
  1605. });
  1606. }
  1607. );
  1608. }),
  1609. /**
  1610. * Removes a user's own modifiable user playlist
  1611. *
  1612. * @param {object} session - the session object automatically added by the websocket
  1613. * @param {string} playlistId - the id of the playlist we are removing
  1614. * @param {Function} cb - gets called with the result
  1615. */
  1616. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1617. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1618. async.waterfall(
  1619. [
  1620. next => {
  1621. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1622. .then(playlist => next(null, playlist))
  1623. .catch(next);
  1624. },
  1625. (playlist, next) => {
  1626. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1627. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1628. return next(null, playlist);
  1629. },
  1630. (playlist, next) => {
  1631. userModel.updateOne(
  1632. { _id: playlist.createdBy },
  1633. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1634. err => next(err, playlist)
  1635. );
  1636. },
  1637. (playlist, next) => {
  1638. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1639. .then(() => next(null, playlist))
  1640. .catch(next);
  1641. }
  1642. ],
  1643. async (err, playlist) => {
  1644. if (err) {
  1645. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1646. this.log(
  1647. "ERROR",
  1648. "PLAYLIST_REMOVE",
  1649. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1650. );
  1651. return cb({ status: "error", message: err });
  1652. }
  1653. this.log(
  1654. "SUCCESS",
  1655. "PLAYLIST_REMOVE",
  1656. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1657. );
  1658. CacheModule.runJob("PUB", {
  1659. channel: "playlist.delete",
  1660. value: {
  1661. userId: session.userId,
  1662. playlistId
  1663. }
  1664. });
  1665. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1666. userId: playlist.createdBy,
  1667. type: "playlist__remove",
  1668. payload: {
  1669. message: `Removed playlist ${playlist.displayName}`
  1670. }
  1671. });
  1672. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1673. return cb({
  1674. status: "success",
  1675. message: "Playlist successfully removed"
  1676. });
  1677. }
  1678. );
  1679. }),
  1680. /**
  1681. * Removes a user's modifiable user playlist as an admin
  1682. *
  1683. * @param {object} session - the session object automatically added by the websocket
  1684. * @param {string} playlistId - the id of the playlist we are removing
  1685. * @param {Function} cb - gets called with the result
  1686. */
  1687. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1688. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1689. async.waterfall(
  1690. [
  1691. next => {
  1692. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1693. .then(playlist => next(null, playlist))
  1694. .catch(next);
  1695. },
  1696. (playlist, next) => {
  1697. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1698. return next(null, playlist);
  1699. },
  1700. (playlist, next) => {
  1701. userModel.updateOne(
  1702. { _id: playlist.createdBy },
  1703. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1704. err => next(err, playlist, playlist.createdBy)
  1705. );
  1706. },
  1707. (playlist, playlistCreator, next) => {
  1708. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1709. .then(() => next(null, playlistCreator))
  1710. .catch(next);
  1711. }
  1712. ],
  1713. async (err, playlistCreator) => {
  1714. if (err) {
  1715. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1716. this.log(
  1717. "ERROR",
  1718. "PLAYLIST_REMOVE_ADMIN",
  1719. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1720. );
  1721. return cb({ status: "error", message: err });
  1722. }
  1723. this.log(
  1724. "SUCCESS",
  1725. "PLAYLIST_REMOVE_ADMIN",
  1726. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1727. );
  1728. CacheModule.runJob("PUB", {
  1729. channel: "playlist.delete",
  1730. value: {
  1731. userId: playlistCreator,
  1732. playlistId
  1733. }
  1734. });
  1735. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1736. return cb({
  1737. status: "success",
  1738. message: "Playlist successfully removed"
  1739. });
  1740. }
  1741. );
  1742. }),
  1743. /**
  1744. * Updates the privacy of a private playlist
  1745. *
  1746. * @param {object} session - the session object automatically added by the websocket
  1747. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1748. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1749. * @param {Function} cb - gets called with the result
  1750. */
  1751. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1752. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1753. async.waterfall(
  1754. [
  1755. next => {
  1756. playlistModel.updateOne(
  1757. { _id: playlistId, createdBy: session.userId },
  1758. { $set: { privacy } },
  1759. { runValidators: true },
  1760. next
  1761. );
  1762. },
  1763. (res, next) => {
  1764. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1765. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1766. else {
  1767. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1768. .then(playlist => next(null, playlist))
  1769. .catch(next);
  1770. }
  1771. }
  1772. ],
  1773. async (err, playlist) => {
  1774. if (err) {
  1775. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1776. this.log(
  1777. "ERROR",
  1778. "PLAYLIST_UPDATE_PRIVACY",
  1779. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1780. );
  1781. return cb({ status: "error", message: err });
  1782. }
  1783. this.log(
  1784. "SUCCESS",
  1785. "PLAYLIST_UPDATE_PRIVACY",
  1786. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1787. );
  1788. CacheModule.runJob("PUB", {
  1789. channel: "playlist.updatePrivacy",
  1790. value: {
  1791. userId: session.userId,
  1792. playlist
  1793. }
  1794. });
  1795. CacheModule.runJob("PUB", {
  1796. channel: "playlist.updated",
  1797. value: { playlistId }
  1798. });
  1799. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1800. userId: session.userId,
  1801. type: "playlist__edit_privacy",
  1802. payload: {
  1803. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1804. playlistId
  1805. }
  1806. });
  1807. return cb({
  1808. status: "success",
  1809. message: "Playlist has been successfully updated"
  1810. });
  1811. }
  1812. );
  1813. }),
  1814. /**
  1815. * Updates the privacy of a playlist
  1816. *
  1817. * @param {object} session - the session object automatically added by the websocket
  1818. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1819. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1820. * @param {Function} cb - gets called with the result
  1821. */
  1822. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1823. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1824. async.waterfall(
  1825. [
  1826. next => {
  1827. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1828. },
  1829. (res, next) => {
  1830. if (res.n === 0) next("No playlist found with that id.");
  1831. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1832. else {
  1833. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1834. .then(playlist => next(null, playlist))
  1835. .catch(next);
  1836. }
  1837. }
  1838. ],
  1839. async (err, playlist) => {
  1840. if (err) {
  1841. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1842. this.log(
  1843. "ERROR",
  1844. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1845. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1846. );
  1847. return cb({ status: "error", message: err });
  1848. }
  1849. this.log(
  1850. "SUCCESS",
  1851. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1852. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1853. );
  1854. if (playlist.type === "user") {
  1855. CacheModule.runJob("PUB", {
  1856. channel: "playlist.updatePrivacy",
  1857. value: {
  1858. userId: playlist.createdBy,
  1859. playlist
  1860. }
  1861. });
  1862. }
  1863. CacheModule.runJob("PUB", {
  1864. channel: "playlist.updated",
  1865. value: { playlistId }
  1866. });
  1867. return cb({
  1868. status: "success",
  1869. message: "Playlist has been successfully updated"
  1870. });
  1871. }
  1872. );
  1873. }),
  1874. /**
  1875. * Deletes all orphaned station playlists
  1876. *
  1877. * @param {object} session - the session object automatically added by socket.io
  1878. * @param {Function} cb - gets called with the result
  1879. */
  1880. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1881. async.waterfall(
  1882. [
  1883. next => {
  1884. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1885. .then(() => next())
  1886. .catch(next);
  1887. }
  1888. ],
  1889. async err => {
  1890. if (err) {
  1891. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1892. this.log(
  1893. "ERROR",
  1894. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1895. `Deleting orphaned station playlists failed. "${err}"`
  1896. );
  1897. return cb({ status: "error", message: err });
  1898. }
  1899. this.log(
  1900. "SUCCESS",
  1901. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1902. "Deleting orphaned station playlists successful."
  1903. );
  1904. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1905. }
  1906. );
  1907. }),
  1908. /**
  1909. * Deletes all orphaned genre playlists
  1910. *
  1911. * @param {object} session - the session object automatically added by socket.io
  1912. * @param {Function} cb - gets called with the result
  1913. */
  1914. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1915. async.waterfall(
  1916. [
  1917. next => {
  1918. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1919. .then(() => next())
  1920. .catch(next);
  1921. }
  1922. ],
  1923. async err => {
  1924. if (err) {
  1925. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1926. this.log(
  1927. "ERROR",
  1928. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1929. `Deleting orphaned genre playlists failed. "${err}"`
  1930. );
  1931. return cb({ status: "error", message: err });
  1932. }
  1933. this.log(
  1934. "SUCCESS",
  1935. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1936. "Deleting orphaned genre playlists successful."
  1937. );
  1938. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1939. }
  1940. );
  1941. }),
  1942. /**
  1943. * Requests orpahned playlist songs
  1944. *
  1945. * @param {object} session - the session object automatically added by socket.io
  1946. * @param {Function} cb - gets called with the result
  1947. */
  1948. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1949. async.waterfall(
  1950. [
  1951. next => {
  1952. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1953. .then(() => next())
  1954. .catch(next);
  1955. }
  1956. ],
  1957. async err => {
  1958. if (err) {
  1959. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1960. this.log(
  1961. "ERROR",
  1962. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1963. `Requesting orphaned playlist songs failed. "${err}"`
  1964. );
  1965. return cb({ status: "error", message: err });
  1966. }
  1967. this.log(
  1968. "SUCCESS",
  1969. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1970. "Requesting orphaned playlist songs was successful."
  1971. );
  1972. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1973. }
  1974. );
  1975. }),
  1976. /**
  1977. * Clears and refills a station playlist
  1978. *
  1979. * @param {object} session - the session object automatically added by socket.io
  1980. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1981. * @param {Function} cb - gets called with the result
  1982. */
  1983. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1984. async.waterfall(
  1985. [
  1986. next => {
  1987. if (!playlistId) next("Please specify a playlist id");
  1988. else {
  1989. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1990. .then(() => {
  1991. next();
  1992. })
  1993. .catch(err => {
  1994. next(err);
  1995. });
  1996. }
  1997. }
  1998. ],
  1999. async err => {
  2000. if (err) {
  2001. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2002. this.log(
  2003. "ERROR",
  2004. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2005. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2006. );
  2007. return cb({ status: "error", message: err });
  2008. }
  2009. this.log(
  2010. "SUCCESS",
  2011. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2012. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2013. );
  2014. return cb({
  2015. status: "success",
  2016. message: "Playlist has been successfully cleared and refilled"
  2017. });
  2018. }
  2019. );
  2020. }),
  2021. /**
  2022. * Clears and refills a genre playlist
  2023. *
  2024. * @param {object} session - the session object automatically added by socket.io
  2025. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2026. * @param {Function} cb - gets called with the result
  2027. */
  2028. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2029. async.waterfall(
  2030. [
  2031. next => {
  2032. if (!playlistId) next("Please specify a playlist id");
  2033. else {
  2034. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2035. .then(() => {
  2036. next();
  2037. })
  2038. .catch(err => {
  2039. next(err);
  2040. });
  2041. }
  2042. }
  2043. ],
  2044. async err => {
  2045. if (err) {
  2046. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2047. this.log(
  2048. "ERROR",
  2049. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2050. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2051. );
  2052. return cb({ status: "error", message: err });
  2053. }
  2054. this.log(
  2055. "SUCCESS",
  2056. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2057. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2058. );
  2059. return cb({
  2060. status: "success",
  2061. message: "Playlist has been successfully cleared and refilled"
  2062. });
  2063. }
  2064. );
  2065. }),
  2066. /**
  2067. * Clears and refills all station playlists
  2068. *
  2069. * @param {object} session - the session object automatically added by socket.io
  2070. * @param {Function} cb - gets called with the result
  2071. */
  2072. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  2073. async.waterfall(
  2074. [
  2075. next => {
  2076. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2077. .then(response => {
  2078. next(null, response.playlists);
  2079. })
  2080. .catch(err => {
  2081. next(err);
  2082. });
  2083. },
  2084. (playlists, next) => {
  2085. async.eachLimit(
  2086. playlists,
  2087. 1,
  2088. (playlist, next) => {
  2089. PlaylistsModule.runJob(
  2090. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2091. { playlistId: playlist._id },
  2092. this
  2093. )
  2094. .then(() => {
  2095. next();
  2096. })
  2097. .catch(err => {
  2098. next(err);
  2099. });
  2100. },
  2101. next
  2102. );
  2103. }
  2104. ],
  2105. async err => {
  2106. if (err) {
  2107. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2108. this.log(
  2109. "ERROR",
  2110. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2111. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2112. );
  2113. return cb({ status: "error", message: err });
  2114. }
  2115. this.log(
  2116. "SUCCESS",
  2117. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2118. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2119. );
  2120. return cb({
  2121. status: "success",
  2122. message: "Playlists have been successfully cleared and refilled"
  2123. });
  2124. }
  2125. );
  2126. }),
  2127. /**
  2128. * Clears and refills all genre playlists
  2129. *
  2130. * @param {object} session - the session object automatically added by socket.io
  2131. * @param {Function} cb - gets called with the result
  2132. */
  2133. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2134. async.waterfall(
  2135. [
  2136. next => {
  2137. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2138. .then(response => {
  2139. next(null, response.playlists);
  2140. })
  2141. .catch(err => {
  2142. next(err);
  2143. });
  2144. },
  2145. (playlists, next) => {
  2146. async.eachLimit(
  2147. playlists,
  2148. 1,
  2149. (playlist, next) => {
  2150. PlaylistsModule.runJob(
  2151. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2152. { playlistId: playlist._id },
  2153. this
  2154. )
  2155. .then(() => {
  2156. next();
  2157. })
  2158. .catch(err => {
  2159. next(err);
  2160. });
  2161. },
  2162. next
  2163. );
  2164. }
  2165. ],
  2166. async err => {
  2167. if (err) {
  2168. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2169. this.log(
  2170. "ERROR",
  2171. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2172. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2173. );
  2174. return cb({ status: "error", message: err });
  2175. }
  2176. this.log(
  2177. "SUCCESS",
  2178. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2179. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2180. );
  2181. return cb({
  2182. status: "success",
  2183. message: "Playlists have been successfully cleared and refilled"
  2184. });
  2185. }
  2186. );
  2187. }),
  2188. /**
  2189. * Create missing genre playlists
  2190. *
  2191. * @param {object} session - the session object automatically added by socket.io
  2192. * @param {Function} cb - gets called with the result
  2193. */
  2194. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2195. async.waterfall(
  2196. [
  2197. next => {
  2198. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2199. .then(() => {
  2200. next();
  2201. })
  2202. .catch(err => {
  2203. next(err);
  2204. });
  2205. }
  2206. ],
  2207. async err => {
  2208. if (err) {
  2209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2210. this.log(
  2211. "ERROR",
  2212. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2213. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2214. );
  2215. return cb({ status: "error", message: err });
  2216. }
  2217. this.log(
  2218. "SUCCESS",
  2219. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2220. `Successfully created missing genre playlists for user "${session.userId}".`
  2221. );
  2222. return cb({
  2223. status: "success",
  2224. message: "Missing genre playlists have been successfully created"
  2225. });
  2226. }
  2227. );
  2228. })
  2229. };