playlists.js 68 KB

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