playlists.js 73 KB

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