playlists.js 68 KB

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