playlists.js 73 KB

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