playlists.js 70 KB

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