playlists.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437
  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(null, playlist);
  997. return next("Something went wrong when trying to get the playlist");
  998. });
  999. });
  1000. } else next(null, playlist);
  1001. })
  1002. .catch(next);
  1003. },
  1004. (playlist, next) => {
  1005. async.each(
  1006. playlist.songs,
  1007. (song, nextSong) => {
  1008. if (song.youtubeId === youtubeId) return next("That song is already in the playlist");
  1009. return nextSong();
  1010. },
  1011. err => next(err, playlist)
  1012. );
  1013. },
  1014. (playlist, next) => {
  1015. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1016. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1017. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1018. playlistModel.count(
  1019. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1020. (err, results) => {
  1021. if (err) next(err);
  1022. else if (results > 0)
  1023. next(
  1024. `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.`
  1025. );
  1026. else next();
  1027. }
  1028. );
  1029. } else next();
  1030. },
  1031. next => {
  1032. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1033. .then(UserModel => {
  1034. UserModel.findOne(
  1035. { _id: session.userId },
  1036. { "preferences.anonymousSongRequests": 1 },
  1037. next
  1038. );
  1039. })
  1040. .catch(next);
  1041. },
  1042. (user, next) => {
  1043. SongsModule.runJob(
  1044. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  1045. {
  1046. youtubeId,
  1047. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  1048. automaticallyRequested: true
  1049. },
  1050. this
  1051. )
  1052. .then(response => {
  1053. const { song } = response;
  1054. const { _id, title, artists, thumbnail, duration, status } = song;
  1055. next(null, {
  1056. _id,
  1057. youtubeId,
  1058. title,
  1059. artists,
  1060. thumbnail,
  1061. duration,
  1062. status
  1063. });
  1064. })
  1065. .catch(next);
  1066. },
  1067. (newSong, next) => {
  1068. playlistModel.updateOne(
  1069. { _id: playlistId },
  1070. { $push: { songs: newSong } },
  1071. { runValidators: true },
  1072. err => {
  1073. if (err) return next(err);
  1074. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1075. .then(playlist => next(null, playlist, newSong))
  1076. .catch(next);
  1077. }
  1078. );
  1079. },
  1080. (playlist, newSong, next) => {
  1081. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1082. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1083. songId: newSong._id,
  1084. youtubeId: newSong.youtubeId
  1085. })
  1086. .then(ratings => next(null, playlist, newSong, ratings))
  1087. .catch(next);
  1088. } else {
  1089. next(null, playlist, newSong, null);
  1090. }
  1091. }
  1092. ],
  1093. async (err, playlist, newSong, ratings) => {
  1094. if (err) {
  1095. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1096. this.log(
  1097. "ERROR",
  1098. "PLAYLIST_ADD_SONG",
  1099. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1100. );
  1101. return cb({ status: "error", message: err });
  1102. }
  1103. this.log(
  1104. "SUCCESS",
  1105. "PLAYLIST_ADD_SONG",
  1106. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1107. );
  1108. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1109. const songName = newSong.artists
  1110. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1111. : newSong.title;
  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 (playlist.type === "user" && playlist.privacy === "public") {
  1422. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1423. userId: session.userId,
  1424. type: "playlist__remove_song",
  1425. payload: {
  1426. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1427. thumbnail,
  1428. playlistId,
  1429. youtubeId: newSong.youtubeId
  1430. }
  1431. });
  1432. }
  1433. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1434. const { likes, dislikes } = ratings;
  1435. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1436. if (playlist.type === "user-liked") {
  1437. CacheModule.runJob("PUB", {
  1438. channel: "song.unlike",
  1439. value: JSON.stringify({
  1440. youtubeId: newSong.youtubeId,
  1441. userId: session.userId,
  1442. likes,
  1443. dislikes
  1444. })
  1445. });
  1446. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1447. userId: session.userId,
  1448. type: "song__unlike",
  1449. payload: {
  1450. message: `Removed <youtubeId>${title} by ${artists.join(
  1451. ", "
  1452. )}</youtubeId> from your Liked Songs`,
  1453. youtubeId: newSong.youtubeId,
  1454. thumbnail
  1455. }
  1456. });
  1457. } else {
  1458. CacheModule.runJob("PUB", {
  1459. channel: "song.undislike",
  1460. value: JSON.stringify({
  1461. youtubeId: newSong.youtubeId,
  1462. userId: session.userId,
  1463. likes,
  1464. dislikes
  1465. })
  1466. });
  1467. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1468. userId: session.userId,
  1469. type: "song__undislike",
  1470. payload: {
  1471. message: `Removed <youtubeId>${title} by ${artists.join(
  1472. ", "
  1473. )}</youtubeId> from your Disliked Songs`,
  1474. youtubeId: newSong.youtubeId,
  1475. thumbnail
  1476. }
  1477. });
  1478. }
  1479. }
  1480. return next(null, playlist);
  1481. }
  1482. ],
  1483. async (err, playlist) => {
  1484. if (err) {
  1485. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1486. this.log(
  1487. "ERROR",
  1488. "PLAYLIST_REMOVE_SONG",
  1489. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1490. );
  1491. return cb({ status: "error", message: err });
  1492. }
  1493. this.log(
  1494. "SUCCESS",
  1495. "PLAYLIST_REMOVE_SONG",
  1496. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1497. );
  1498. CacheModule.runJob("PUB", {
  1499. channel: "playlist.removeSong",
  1500. value: {
  1501. playlistId: playlist._id,
  1502. youtubeId,
  1503. userId: session.userId,
  1504. privacy: playlist.privacy
  1505. }
  1506. });
  1507. CacheModule.runJob("PUB", {
  1508. channel: "playlist.updated",
  1509. value: { playlistId }
  1510. });
  1511. return cb({
  1512. status: "success",
  1513. message: "Song has been successfully removed from playlist",
  1514. data: { songs: playlist.songs }
  1515. });
  1516. }
  1517. );
  1518. }),
  1519. /**
  1520. * Updates the displayName of a private playlist
  1521. *
  1522. * @param {object} session - the session object automatically added by the websocket
  1523. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1524. * @param {Function} cb - gets called with the result
  1525. */
  1526. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1527. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1528. async.waterfall(
  1529. [
  1530. next => {
  1531. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1532. .then(playlist => next(null, playlist))
  1533. .catch(next);
  1534. },
  1535. (playlist, next) => {
  1536. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1537. return next(null);
  1538. },
  1539. next => {
  1540. playlistModel.updateOne(
  1541. { _id: playlistId, createdBy: session.userId },
  1542. { $set: { displayName } },
  1543. { runValidators: true },
  1544. next
  1545. );
  1546. },
  1547. (res, next) => {
  1548. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1549. .then(playlist => next(null, playlist))
  1550. .catch(next);
  1551. }
  1552. ],
  1553. async (err, playlist) => {
  1554. if (err) {
  1555. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1556. this.log(
  1557. "ERROR",
  1558. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1559. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1560. );
  1561. return cb({ status: "error", message: err });
  1562. }
  1563. this.log(
  1564. "SUCCESS",
  1565. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1566. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1567. );
  1568. CacheModule.runJob("PUB", {
  1569. channel: "playlist.updateDisplayName",
  1570. value: {
  1571. playlistId,
  1572. displayName,
  1573. userId: session.userId,
  1574. privacy: playlist.privacy
  1575. }
  1576. });
  1577. CacheModule.runJob("PUB", {
  1578. channel: "playlist.updated",
  1579. value: { playlistId }
  1580. });
  1581. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1582. userId: session.userId,
  1583. type: "playlist__edit_display_name",
  1584. payload: {
  1585. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1586. playlistId
  1587. }
  1588. });
  1589. return cb({
  1590. status: "success",
  1591. message: "Playlist has been successfully updated"
  1592. });
  1593. }
  1594. );
  1595. }),
  1596. /**
  1597. * Removes a user's own modifiable user playlist
  1598. *
  1599. * @param {object} session - the session object automatically added by the websocket
  1600. * @param {string} playlistId - the id of the playlist we are removing
  1601. * @param {Function} cb - gets called with the result
  1602. */
  1603. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1604. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1605. async.waterfall(
  1606. [
  1607. next => {
  1608. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1609. .then(playlist => next(null, playlist))
  1610. .catch(next);
  1611. },
  1612. (playlist, next) => {
  1613. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1614. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1615. return next(null, playlist);
  1616. },
  1617. (playlist, next) => {
  1618. userModel.updateOne(
  1619. { _id: playlist.createdBy },
  1620. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1621. err => next(err, playlist)
  1622. );
  1623. },
  1624. (playlist, next) => {
  1625. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1626. .then(() => next(null, playlist))
  1627. .catch(next);
  1628. }
  1629. ],
  1630. async (err, playlist) => {
  1631. if (err) {
  1632. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1633. this.log(
  1634. "ERROR",
  1635. "PLAYLIST_REMOVE",
  1636. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1637. );
  1638. return cb({ status: "error", message: err });
  1639. }
  1640. this.log(
  1641. "SUCCESS",
  1642. "PLAYLIST_REMOVE",
  1643. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1644. );
  1645. CacheModule.runJob("PUB", {
  1646. channel: "playlist.delete",
  1647. value: {
  1648. userId: session.userId,
  1649. playlistId
  1650. }
  1651. });
  1652. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1653. userId: playlist.createdBy,
  1654. type: "playlist__remove",
  1655. payload: {
  1656. message: `Removed playlist ${playlist.displayName}`
  1657. }
  1658. });
  1659. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1660. return cb({
  1661. status: "success",
  1662. message: "Playlist successfully removed"
  1663. });
  1664. }
  1665. );
  1666. }),
  1667. /**
  1668. * Removes a user's modifiable user playlist as an admin
  1669. *
  1670. * @param {object} session - the session object automatically added by the websocket
  1671. * @param {string} playlistId - the id of the playlist we are removing
  1672. * @param {Function} cb - gets called with the result
  1673. */
  1674. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1675. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1676. async.waterfall(
  1677. [
  1678. next => {
  1679. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1680. .then(playlist => next(null, playlist))
  1681. .catch(next);
  1682. },
  1683. (playlist, next) => {
  1684. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1685. return next(null, playlist);
  1686. },
  1687. (playlist, next) => {
  1688. userModel.updateOne(
  1689. { _id: playlist.createdBy },
  1690. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1691. err => next(err, playlist, playlist.createdBy)
  1692. );
  1693. },
  1694. (playlist, playlistCreator, next) => {
  1695. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1696. .then(() => next(null, playlistCreator))
  1697. .catch(next);
  1698. }
  1699. ],
  1700. async (err, playlistCreator) => {
  1701. if (err) {
  1702. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1703. this.log(
  1704. "ERROR",
  1705. "PLAYLIST_REMOVE_ADMIN",
  1706. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1707. );
  1708. return cb({ status: "error", message: err });
  1709. }
  1710. this.log(
  1711. "SUCCESS",
  1712. "PLAYLIST_REMOVE_ADMIN",
  1713. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1714. );
  1715. CacheModule.runJob("PUB", {
  1716. channel: "playlist.delete",
  1717. value: {
  1718. userId: playlistCreator,
  1719. playlistId
  1720. }
  1721. });
  1722. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1723. return cb({
  1724. status: "success",
  1725. message: "Playlist successfully removed"
  1726. });
  1727. }
  1728. );
  1729. }),
  1730. /**
  1731. * Updates the privacy of a private playlist
  1732. *
  1733. * @param {object} session - the session object automatically added by the websocket
  1734. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1735. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1736. * @param {Function} cb - gets called with the result
  1737. */
  1738. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1739. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1740. async.waterfall(
  1741. [
  1742. next => {
  1743. playlistModel.updateOne(
  1744. { _id: playlistId, createdBy: session.userId },
  1745. { $set: { privacy } },
  1746. { runValidators: true },
  1747. next
  1748. );
  1749. },
  1750. (res, next) => {
  1751. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1752. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1753. else {
  1754. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1755. .then(playlist => next(null, playlist))
  1756. .catch(next);
  1757. }
  1758. }
  1759. ],
  1760. async (err, playlist) => {
  1761. if (err) {
  1762. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1763. this.log(
  1764. "ERROR",
  1765. "PLAYLIST_UPDATE_PRIVACY",
  1766. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1767. );
  1768. return cb({ status: "error", message: err });
  1769. }
  1770. this.log(
  1771. "SUCCESS",
  1772. "PLAYLIST_UPDATE_PRIVACY",
  1773. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1774. );
  1775. CacheModule.runJob("PUB", {
  1776. channel: "playlist.updatePrivacy",
  1777. value: {
  1778. userId: session.userId,
  1779. playlist
  1780. }
  1781. });
  1782. CacheModule.runJob("PUB", {
  1783. channel: "playlist.updated",
  1784. value: { playlistId }
  1785. });
  1786. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1787. userId: session.userId,
  1788. type: "playlist__edit_privacy",
  1789. payload: {
  1790. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1791. playlistId
  1792. }
  1793. });
  1794. return cb({
  1795. status: "success",
  1796. message: "Playlist has been successfully updated"
  1797. });
  1798. }
  1799. );
  1800. }),
  1801. /**
  1802. * Updates the privacy of a playlist
  1803. *
  1804. * @param {object} session - the session object automatically added by the websocket
  1805. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1806. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1807. * @param {Function} cb - gets called with the result
  1808. */
  1809. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1810. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1811. async.waterfall(
  1812. [
  1813. next => {
  1814. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1815. },
  1816. (res, next) => {
  1817. if (res.n === 0) next("No playlist found with that id.");
  1818. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1819. else {
  1820. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1821. .then(playlist => next(null, playlist))
  1822. .catch(next);
  1823. }
  1824. }
  1825. ],
  1826. async (err, playlist) => {
  1827. if (err) {
  1828. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1829. this.log(
  1830. "ERROR",
  1831. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1832. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1833. );
  1834. return cb({ status: "error", message: err });
  1835. }
  1836. this.log(
  1837. "SUCCESS",
  1838. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1839. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1840. );
  1841. if (playlist.type === "user") {
  1842. CacheModule.runJob("PUB", {
  1843. channel: "playlist.updatePrivacy",
  1844. value: {
  1845. userId: playlist.createdBy,
  1846. playlist
  1847. }
  1848. });
  1849. }
  1850. CacheModule.runJob("PUB", {
  1851. channel: "playlist.updated",
  1852. value: { playlistId }
  1853. });
  1854. return cb({
  1855. status: "success",
  1856. message: "Playlist has been successfully updated"
  1857. });
  1858. }
  1859. );
  1860. }),
  1861. /**
  1862. * Deletes all orphaned station playlists
  1863. *
  1864. * @param {object} session - the session object automatically added by socket.io
  1865. * @param {Function} cb - gets called with the result
  1866. */
  1867. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1868. async.waterfall(
  1869. [
  1870. next => {
  1871. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1872. .then(() => next())
  1873. .catch(next);
  1874. }
  1875. ],
  1876. async err => {
  1877. if (err) {
  1878. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1879. this.log(
  1880. "ERROR",
  1881. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1882. `Deleting orphaned station playlists failed. "${err}"`
  1883. );
  1884. return cb({ status: "error", message: err });
  1885. }
  1886. this.log(
  1887. "SUCCESS",
  1888. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1889. "Deleting orphaned station playlists successful."
  1890. );
  1891. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1892. }
  1893. );
  1894. }),
  1895. /**
  1896. * Deletes all orphaned genre playlists
  1897. *
  1898. * @param {object} session - the session object automatically added by socket.io
  1899. * @param {Function} cb - gets called with the result
  1900. */
  1901. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1902. async.waterfall(
  1903. [
  1904. next => {
  1905. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1906. .then(() => next())
  1907. .catch(next);
  1908. }
  1909. ],
  1910. async err => {
  1911. if (err) {
  1912. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1913. this.log(
  1914. "ERROR",
  1915. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1916. `Deleting orphaned genre playlists failed. "${err}"`
  1917. );
  1918. return cb({ status: "error", message: err });
  1919. }
  1920. this.log(
  1921. "SUCCESS",
  1922. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1923. "Deleting orphaned genre playlists successful."
  1924. );
  1925. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1926. }
  1927. );
  1928. }),
  1929. /**
  1930. * Requests orpahned playlist songs
  1931. *
  1932. * @param {object} session - the session object automatically added by socket.io
  1933. * @param {Function} cb - gets called with the result
  1934. */
  1935. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1936. async.waterfall(
  1937. [
  1938. next => {
  1939. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1940. .then(() => next())
  1941. .catch(next);
  1942. }
  1943. ],
  1944. async err => {
  1945. if (err) {
  1946. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1947. this.log(
  1948. "ERROR",
  1949. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1950. `Requesting orphaned playlist songs failed. "${err}"`
  1951. );
  1952. return cb({ status: "error", message: err });
  1953. }
  1954. this.log(
  1955. "SUCCESS",
  1956. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1957. "Requesting orphaned playlist songs was successful."
  1958. );
  1959. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1960. }
  1961. );
  1962. }),
  1963. /**
  1964. * Clears and refills a station playlist
  1965. *
  1966. * @param {object} session - the session object automatically added by socket.io
  1967. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1968. * @param {Function} cb - gets called with the result
  1969. */
  1970. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1971. async.waterfall(
  1972. [
  1973. next => {
  1974. if (!playlistId) next("Please specify a playlist id");
  1975. else {
  1976. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1977. .then(() => {
  1978. next();
  1979. })
  1980. .catch(err => {
  1981. next(err);
  1982. });
  1983. }
  1984. }
  1985. ],
  1986. async err => {
  1987. if (err) {
  1988. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1989. this.log(
  1990. "ERROR",
  1991. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1992. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1993. );
  1994. return cb({ status: "error", message: err });
  1995. }
  1996. this.log(
  1997. "SUCCESS",
  1998. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1999. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2000. );
  2001. return cb({
  2002. status: "success",
  2003. message: "Playlist has been successfully cleared and refilled"
  2004. });
  2005. }
  2006. );
  2007. }),
  2008. /**
  2009. * Clears and refills a genre playlist
  2010. *
  2011. * @param {object} session - the session object automatically added by socket.io
  2012. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2013. * @param {Function} cb - gets called with the result
  2014. */
  2015. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2016. async.waterfall(
  2017. [
  2018. next => {
  2019. if (!playlistId) next("Please specify a playlist id");
  2020. else {
  2021. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2022. .then(() => {
  2023. next();
  2024. })
  2025. .catch(err => {
  2026. next(err);
  2027. });
  2028. }
  2029. }
  2030. ],
  2031. async err => {
  2032. if (err) {
  2033. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2034. this.log(
  2035. "ERROR",
  2036. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2037. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2038. );
  2039. return cb({ status: "error", message: err });
  2040. }
  2041. this.log(
  2042. "SUCCESS",
  2043. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2044. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2045. );
  2046. return cb({
  2047. status: "success",
  2048. message: "Playlist has been successfully cleared and refilled"
  2049. });
  2050. }
  2051. );
  2052. }),
  2053. /**
  2054. * Clears and refills all station playlists
  2055. *
  2056. * @param {object} session - the session object automatically added by socket.io
  2057. * @param {Function} cb - gets called with the result
  2058. */
  2059. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  2060. async.waterfall(
  2061. [
  2062. next => {
  2063. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2064. .then(response => {
  2065. next(null, response.playlists);
  2066. })
  2067. .catch(err => {
  2068. next(err);
  2069. });
  2070. },
  2071. (playlists, next) => {
  2072. async.eachLimit(
  2073. playlists,
  2074. 1,
  2075. (playlist, next) => {
  2076. PlaylistsModule.runJob(
  2077. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2078. { playlistId: playlist._id },
  2079. this
  2080. )
  2081. .then(() => {
  2082. next();
  2083. })
  2084. .catch(err => {
  2085. next(err);
  2086. });
  2087. },
  2088. next
  2089. );
  2090. }
  2091. ],
  2092. async err => {
  2093. if (err) {
  2094. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2095. this.log(
  2096. "ERROR",
  2097. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2098. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2099. );
  2100. return cb({ status: "error", message: err });
  2101. }
  2102. this.log(
  2103. "SUCCESS",
  2104. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2105. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2106. );
  2107. return cb({
  2108. status: "success",
  2109. message: "Playlists have been successfully cleared and refilled"
  2110. });
  2111. }
  2112. );
  2113. }),
  2114. /**
  2115. * Clears and refills all genre playlists
  2116. *
  2117. * @param {object} session - the session object automatically added by socket.io
  2118. * @param {Function} cb - gets called with the result
  2119. */
  2120. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2121. async.waterfall(
  2122. [
  2123. next => {
  2124. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2125. .then(response => {
  2126. next(null, response.playlists);
  2127. })
  2128. .catch(err => {
  2129. next(err);
  2130. });
  2131. },
  2132. (playlists, next) => {
  2133. async.eachLimit(
  2134. playlists,
  2135. 1,
  2136. (playlist, next) => {
  2137. PlaylistsModule.runJob(
  2138. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2139. { playlistId: playlist._id },
  2140. this
  2141. )
  2142. .then(() => {
  2143. next();
  2144. })
  2145. .catch(err => {
  2146. next(err);
  2147. });
  2148. },
  2149. next
  2150. );
  2151. }
  2152. ],
  2153. async err => {
  2154. if (err) {
  2155. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2156. this.log(
  2157. "ERROR",
  2158. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2159. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2160. );
  2161. return cb({ status: "error", message: err });
  2162. }
  2163. this.log(
  2164. "SUCCESS",
  2165. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2166. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2167. );
  2168. return cb({
  2169. status: "success",
  2170. message: "Playlists have been successfully cleared and refilled"
  2171. });
  2172. }
  2173. );
  2174. }),
  2175. /**
  2176. * Create missing genre playlists
  2177. *
  2178. * @param {object} session - the session object automatically added by socket.io
  2179. * @param {Function} cb - gets called with the result
  2180. */
  2181. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2182. async.waterfall(
  2183. [
  2184. next => {
  2185. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2186. .then(() => {
  2187. next();
  2188. })
  2189. .catch(err => {
  2190. next(err);
  2191. });
  2192. }
  2193. ],
  2194. async err => {
  2195. if (err) {
  2196. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2197. this.log(
  2198. "ERROR",
  2199. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2200. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2201. );
  2202. return cb({ status: "error", message: err });
  2203. }
  2204. this.log(
  2205. "SUCCESS",
  2206. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2207. `Successfully created missing genre playlists for user "${session.userId}".`
  2208. );
  2209. return cb({
  2210. status: "success",
  2211. message: "Missing genre playlists have been successfully created"
  2212. });
  2213. }
  2214. );
  2215. })
  2216. };