playlists.js 73 KB

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