playlists.js 74 KB

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