playlists.js 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536
  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. "playlists.getData",
  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(
  411. "playlists.searchOfficial",
  412. async function searchOfficial(session, query, page, cb) {
  413. async.waterfall(
  414. [
  415. next => {
  416. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  417. else next();
  418. },
  419. next => {
  420. PlaylistsModule.runJob("SEARCH", {
  421. query,
  422. includeGenre: true,
  423. includePrivate: true,
  424. includeSongs: true,
  425. page
  426. })
  427. .then(response => {
  428. next(null, response);
  429. })
  430. .catch(err => {
  431. next(err);
  432. });
  433. }
  434. ],
  435. async (err, data) => {
  436. if (err) {
  437. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  438. this.log("ERROR", "PLAYLISTS_SEARCH_OFFICIAL", `Searching playlists failed. "${err}"`);
  439. return cb({ status: "error", message: err });
  440. }
  441. this.log("SUCCESS", "PLAYLISTS_SEARCH_OFFICIAL", "Searching playlists successful.");
  442. return cb({ status: "success", data });
  443. }
  444. );
  445. }
  446. ),
  447. /**
  448. * Gets the first song from a private playlist
  449. *
  450. * @param {object} session - the session object automatically added by the websocket
  451. * @param {string} playlistId - the id of the playlist we are getting the first song from
  452. * @param {Function} cb - gets called with the result
  453. */
  454. getFirstSong: isLoginRequired(function getFirstSong(session, playlistId, cb) {
  455. async.waterfall(
  456. [
  457. next => {
  458. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  459. .then(playlist => next(null, playlist))
  460. .catch(next);
  461. },
  462. (playlist, next) => {
  463. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  464. playlist.songs.sort((a, b) => a.position - b.position);
  465. return next(null, playlist.songs[0]);
  466. }
  467. ],
  468. async (err, song) => {
  469. if (err) {
  470. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  471. this.log(
  472. "ERROR",
  473. "PLAYLIST_GET_FIRST_SONG",
  474. `Getting the first song of playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  475. );
  476. return cb({ status: "error", message: err });
  477. }
  478. this.log(
  479. "SUCCESS",
  480. "PLAYLIST_GET_FIRST_SONG",
  481. `Successfully got the first song of playlist "${playlistId}" for user "${session.userId}".`
  482. );
  483. return cb({
  484. status: "success",
  485. data: { song }
  486. });
  487. }
  488. );
  489. }),
  490. /**
  491. * Gets a list of all the playlists for a specific user
  492. *
  493. * @param {object} session - the session object automatically added by the websocket
  494. * @param {string} userId - the user id in question
  495. * @param {Function} cb - gets called with the result
  496. */
  497. indexForUser: async function indexForUser(session, userId, cb) {
  498. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  499. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  500. async.waterfall(
  501. [
  502. next => {
  503. userModel.findById(userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  504. },
  505. (user, next) => {
  506. if (!user) next("User not found");
  507. else {
  508. const { preferences } = user;
  509. const { orderOfPlaylists } = preferences;
  510. const match = {
  511. createdBy: userId,
  512. type: { $in: ["user", "user-liked", "user-disliked"] }
  513. };
  514. // if a playlist order exists
  515. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  516. playlistModel
  517. .aggregate()
  518. .match(match)
  519. .addFields({
  520. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  521. })
  522. .sort({ weight: 1 })
  523. .exec(next);
  524. }
  525. },
  526. (playlists, next) => {
  527. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  528. const filteredPlaylists = [];
  529. return async.each(
  530. playlists,
  531. (playlist, nextPlaylist) => {
  532. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  533. return nextPlaylist();
  534. },
  535. () => next(null, filteredPlaylists)
  536. );
  537. }
  538. ],
  539. async (err, playlists) => {
  540. if (err) {
  541. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  542. this.log(
  543. "ERROR",
  544. "PLAYLIST_INDEX_FOR_USER",
  545. `Indexing playlists for user "${userId}" failed. "${err}"`
  546. );
  547. return cb({ status: "error", message: err });
  548. }
  549. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  550. return cb({
  551. status: "success",
  552. data: { playlists }
  553. });
  554. }
  555. );
  556. },
  557. /**
  558. * Gets all playlists for the user requesting it
  559. *
  560. * @param {object} session - the session object automatically added by the websocket
  561. * @param {Function} cb - gets called with the result
  562. */
  563. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  564. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  565. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  566. async.waterfall(
  567. [
  568. next => {
  569. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  570. },
  571. (user, next) => {
  572. if (!user) next("User not found");
  573. else {
  574. const { preferences } = user;
  575. const { orderOfPlaylists } = preferences;
  576. const match = {
  577. createdBy: session.userId,
  578. type: { $in: ["user", "user-liked", "user-disliked"] }
  579. };
  580. // if a playlist order exists
  581. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  582. playlistModel
  583. .aggregate()
  584. .match(match)
  585. .addFields({
  586. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  587. })
  588. .sort({ weight: 1 })
  589. .exec(next);
  590. }
  591. }
  592. ],
  593. async (err, playlists) => {
  594. if (err) {
  595. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  596. this.log(
  597. "ERROR",
  598. "PLAYLIST_INDEX_FOR_ME",
  599. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  600. );
  601. return cb({ status: "error", message: err });
  602. }
  603. this.log(
  604. "SUCCESS",
  605. "PLAYLIST_INDEX_FOR_ME",
  606. `Successfully indexed playlists for user "${session.userId}".`
  607. );
  608. return cb({
  609. status: "success",
  610. data: { playlists }
  611. });
  612. }
  613. );
  614. }),
  615. /**
  616. * Gets all playlists playlists
  617. *
  618. * @param {object} session - the session object automatically added by the websocket
  619. * @param {Function} cb - gets called with the result
  620. */
  621. indexFeaturedPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  622. async.waterfall(
  623. [
  624. next => {
  625. const featuredPlaylistIds = config.get("featuredPlaylists");
  626. if (featuredPlaylistIds.length === 0) next(true, []);
  627. else next(null, featuredPlaylistIds);
  628. },
  629. (featuredPlaylistIds, next) => {
  630. const featuredPlaylists = [];
  631. async.eachLimit(
  632. featuredPlaylistIds,
  633. 1,
  634. (playlistId, next) => {
  635. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  636. .then(playlist => {
  637. if (playlist.privacy === "public") featuredPlaylists.push(playlist);
  638. next();
  639. })
  640. .catch(next);
  641. },
  642. err => {
  643. next(err, featuredPlaylists);
  644. }
  645. );
  646. }
  647. ],
  648. async (err, playlists) => {
  649. if (err && err !== true) {
  650. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  651. this.log("ERROR", "PLAYLIST_INDEX_FEATURED", `Indexing featured playlists failed. "${err}"`);
  652. return cb({ status: "error", message: err });
  653. }
  654. this.log("SUCCESS", "PLAYLIST_INDEX_FEATURED", `Successfully indexed featured playlists.`);
  655. return cb({
  656. status: "success",
  657. data: { playlists }
  658. });
  659. }
  660. );
  661. }),
  662. /**
  663. * Creates a new private playlist
  664. *
  665. * @param {object} session - the session object automatically added by the websocket
  666. * @param {object} data - the data for the new private playlist
  667. * @param {Function} cb - gets called with the result
  668. */
  669. create: isLoginRequired(async function create(session, data, cb) {
  670. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  671. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  672. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  673. async.waterfall(
  674. [
  675. next => (data ? next() : cb({ status: "error", message: "Invalid data" })),
  676. next => {
  677. const { displayName, songs, privacy } = data;
  678. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  679. return next("That playlist name is blacklisted. Please use a different name.");
  680. return playlistModel.create(
  681. {
  682. displayName,
  683. songs,
  684. privacy,
  685. createdBy: session.userId,
  686. createdAt: Date.now(),
  687. createdFor: null,
  688. type: "user"
  689. },
  690. next
  691. );
  692. },
  693. (playlist, next) => {
  694. userModel.updateOne(
  695. { _id: session.userId },
  696. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  697. err => {
  698. if (err) return next(err);
  699. return next(null, playlist);
  700. }
  701. );
  702. }
  703. ],
  704. async (err, playlist) => {
  705. if (err) {
  706. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  707. this.log(
  708. "ERROR",
  709. "PLAYLIST_CREATE",
  710. `Creating private playlist failed for user "${session.userId}". "${err}"`
  711. );
  712. return cb({ status: "error", message: err });
  713. }
  714. CacheModule.runJob("PUB", {
  715. channel: "playlist.create",
  716. value: playlist
  717. });
  718. ActivitiesModule.runJob("ADD_ACTIVITY", {
  719. userId: playlist.createdBy,
  720. type: "playlist__create",
  721. payload: {
  722. message: `Created playlist <playlistId>${playlist.displayName}</playlistId>`,
  723. playlistId: playlist._id
  724. }
  725. });
  726. this.log(
  727. "SUCCESS",
  728. "PLAYLIST_CREATE",
  729. `Successfully created private playlist for user "${session.userId}".`
  730. );
  731. return cb({
  732. status: "success",
  733. message: "Successfully created playlist",
  734. data: {
  735. playlistId: playlist._id
  736. }
  737. });
  738. }
  739. );
  740. }),
  741. /**
  742. * Gets a playlist from id
  743. *
  744. * @param {object} session - the session object automatically added by the websocket
  745. * @param {string} playlistId - the id of the playlist we are getting
  746. * @param {Function} cb - gets called with the result
  747. */
  748. getPlaylist: function getPlaylist(session, playlistId, cb) {
  749. async.waterfall(
  750. [
  751. next => {
  752. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  753. .then(playlist => next(null, playlist))
  754. .catch(next);
  755. },
  756. (playlist, next) => {
  757. if (!playlist) return next("Playlist not found");
  758. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId)
  759. return hasPermission("playlists.getPlaylist", session)
  760. .then(() => next(null, playlist))
  761. .catch(() => next("User unauthorised to view playlist."));
  762. return next(null, playlist);
  763. }
  764. ],
  765. async (err, playlist) => {
  766. if (err) {
  767. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  768. this.log(
  769. "ERROR",
  770. "PLAYLIST_GET",
  771. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  772. );
  773. return cb({ status: "error", message: err });
  774. }
  775. this.log(
  776. "SUCCESS",
  777. "PLAYLIST_GET",
  778. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  779. );
  780. return cb({
  781. status: "success",
  782. data: { playlist }
  783. });
  784. }
  785. );
  786. },
  787. /**
  788. * Gets a playlist from station id
  789. *
  790. * @param {object} session - the session object automatically added by the websocket
  791. * @param {string} stationId - the id of the station we are getting
  792. * @param {string} includeSongs - include songs
  793. * @param {Function} cb - gets called with the result
  794. */
  795. getPlaylistForStation: function getPlaylist(session, stationId, includeSongs, cb) {
  796. async.waterfall(
  797. [
  798. next => {
  799. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs }, this)
  800. .then(response => next(null, response.playlist))
  801. .catch(next);
  802. },
  803. (playlist, next) => {
  804. if (!playlist) return next("Playlist not found");
  805. if (playlist.privacy !== "public")
  806. return hasPermission("stations.getPlaylist", session, stationId)
  807. .then(() => next(null, playlist))
  808. .catch(() => next("User unauthorised to view playlist."));
  809. return next(null, playlist);
  810. }
  811. ],
  812. async (err, playlist) => {
  813. if (err) {
  814. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  815. this.log(
  816. "ERROR",
  817. "PLAYLIST_GET",
  818. `Getting playlist for station "${stationId}" failed for user "${session.userId}". "${err}"`
  819. );
  820. return cb({ status: "error", message: err });
  821. }
  822. this.log(
  823. "SUCCESS",
  824. "PLAYLIST_GET",
  825. `Successfully got playlist for station "${stationId}" for user "${session.userId}".`
  826. );
  827. return cb({
  828. status: "success",
  829. data: { playlist }
  830. });
  831. }
  832. );
  833. },
  834. /**
  835. * Shuffles songs in a private playlist
  836. *
  837. * @param {object} session - the session object automatically added by the websocket
  838. * @param {string} playlistId - the id of the playlist we are updating
  839. * @param {Function} cb - gets called with the result
  840. */
  841. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  842. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  843. async.waterfall(
  844. [
  845. next => {
  846. if (!playlistId) return next("No playlist id.");
  847. return next();
  848. },
  849. next => {
  850. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  851. .then(playlist => {
  852. if (!playlist || playlist.createdBy !== session.userId)
  853. return next("Something went wrong when trying to get the playlist");
  854. return next(null, playlist);
  855. })
  856. .catch(next);
  857. },
  858. (playlist, next) => {
  859. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  860. return UtilsModule.runJob("SHUFFLE_SONG_POSITIONS", { array: playlist.songs }, this)
  861. .then(result => next(null, result.array))
  862. .catch(next);
  863. },
  864. (songs, next) => {
  865. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  866. },
  867. (res, next) => {
  868. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  869. .then(playlist => next(null, playlist))
  870. .catch(next);
  871. }
  872. ],
  873. async (err, playlist) => {
  874. if (err) {
  875. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  876. this.log(
  877. "ERROR",
  878. "PLAYLIST_SHUFFLE",
  879. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  880. );
  881. return cb({ status: "error", message: err });
  882. }
  883. this.log(
  884. "SUCCESS",
  885. "PLAYLIST_SHUFFLE",
  886. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  887. );
  888. return cb({
  889. status: "success",
  890. message: "Successfully shuffled playlist.",
  891. data: { playlist }
  892. });
  893. }
  894. );
  895. }),
  896. /**
  897. * Changes the order (position) of a song in a playlist
  898. *
  899. * @param {object} session - the session object automatically added by the websocket
  900. * @param {string} playlistId - the id of the playlist we are targeting
  901. * @param {object} song - the song to be repositioned
  902. * @param {string} song.youtubeId - the youtube id of the song being repositioned
  903. * @param {string} song.newIndex - the new position of the song in the playlist
  904. * @param {...any} song.args - any other elements that would be included with a song item in a playlist
  905. * @param {Function} cb - gets called with the result
  906. */
  907. repositionSong: isLoginRequired(async function repositionSong(session, playlistId, song, cb) {
  908. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  909. async.waterfall(
  910. [
  911. next => {
  912. if (!playlistId) return next("Please provide a playlist.");
  913. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  914. return next();
  915. },
  916. next => {
  917. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  918. .then(playlist => {
  919. if (!playlist) return next("Playlist not found.");
  920. if (playlist.createdBy !== session.userId)
  921. return hasPermission("playlists.repositionSong", session)
  922. .then(() => next())
  923. .catch(() => next("Invalid permissions."));
  924. return next();
  925. })
  926. .catch(next);
  927. },
  928. // remove song from playlist
  929. next => {
  930. playlistModel.updateOne(
  931. { _id: playlistId },
  932. { $pull: { songs: { youtubeId: song.youtubeId } } },
  933. next
  934. );
  935. },
  936. // add song back to playlist (in new position)
  937. (res, next) => {
  938. playlistModel.updateOne(
  939. { _id: playlistId },
  940. { $push: { songs: { $each: [song], $position: song.newIndex } } },
  941. err => next(err)
  942. );
  943. },
  944. // update the cache with the new songs positioning
  945. next => {
  946. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  947. .then(playlist => next(null, playlist))
  948. .catch(next);
  949. }
  950. ],
  951. async err => {
  952. if (err) {
  953. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  954. this.log(
  955. "ERROR",
  956. "PLAYLIST_REPOSITION_SONG",
  957. `Repositioning song ${song.youtubeId} for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  958. );
  959. return cb({ status: "error", message: err });
  960. }
  961. this.log(
  962. "SUCCESS",
  963. "PLAYLIST_REPOSITION_SONG",
  964. `Successfully repositioned song ${song.youtubeId} for private playlist "${playlistId}" for user "${session.userId}".`
  965. );
  966. CacheModule.runJob("PUB", {
  967. channel: "playlist.repositionSong",
  968. value: {
  969. userId: session.userId,
  970. playlistId,
  971. song
  972. }
  973. });
  974. return cb({
  975. status: "success",
  976. message: "Successfully repositioned song"
  977. });
  978. }
  979. );
  980. }),
  981. /**
  982. * Adds a song to a private playlist
  983. *
  984. * @param {object} session - the session object automatically added by the websocket
  985. * @param {boolean} isSet - is the song part of a set of songs to be added
  986. * @param {string} youtubeId - the youtube id of the song we are trying to add
  987. * @param {string} playlistId - the id of the playlist we are adding the song to
  988. * @param {Function} cb - gets called with the result
  989. */
  990. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, youtubeId, playlistId, cb) {
  991. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  992. async.waterfall(
  993. [
  994. next => {
  995. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  996. .then(playlist => {
  997. if (!playlist) return next("Playlist not found.");
  998. if (playlist.createdBy !== session.userId)
  999. return hasPermission("playlists.addSongToPlaylist", session)
  1000. .then(() => next(null, playlist))
  1001. .catch(() => next("Invalid permissions."));
  1002. return next(null, playlist);
  1003. })
  1004. .catch(next);
  1005. },
  1006. (playlist, next) => {
  1007. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1008. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1009. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1010. playlistModel.count(
  1011. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1012. (err, results) => {
  1013. if (err) next(err);
  1014. else if (results > 0)
  1015. next(
  1016. `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.`
  1017. );
  1018. else next();
  1019. }
  1020. );
  1021. } else next();
  1022. },
  1023. next => {
  1024. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, youtubeId }, this)
  1025. .then(res => {
  1026. const { playlist, song, ratings } = res;
  1027. next(null, playlist, song, ratings);
  1028. })
  1029. .catch(next);
  1030. }
  1031. ],
  1032. async (err, playlist, newSong, ratings) => {
  1033. if (err) {
  1034. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1035. this.log(
  1036. "ERROR",
  1037. "PLAYLIST_ADD_SONG",
  1038. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1039. );
  1040. return cb({ status: "error", message: err });
  1041. }
  1042. this.log(
  1043. "SUCCESS",
  1044. "PLAYLIST_ADD_SONG",
  1045. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1046. );
  1047. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1048. const songName = newSong.artists
  1049. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1050. : newSong.title;
  1051. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1052. userId: session.userId,
  1053. type: "playlist__add_song",
  1054. payload: {
  1055. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1056. thumbnail: newSong.thumbnail,
  1057. playlistId,
  1058. youtubeId
  1059. }
  1060. });
  1061. }
  1062. CacheModule.runJob("PUB", {
  1063. channel: "playlist.addSong",
  1064. value: {
  1065. playlistId: playlist._id,
  1066. song: newSong,
  1067. userId: session.userId,
  1068. privacy: playlist.privacy
  1069. }
  1070. });
  1071. CacheModule.runJob("PUB", {
  1072. channel: "playlist.updated",
  1073. value: { playlistId }
  1074. });
  1075. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1076. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  1077. const { likes, dislikes } = ratings;
  1078. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1079. if (playlist.type === "user-liked") {
  1080. CacheModule.runJob("PUB", {
  1081. channel: "song.like",
  1082. value: JSON.stringify({
  1083. youtubeId,
  1084. userId: session.userId,
  1085. likes,
  1086. dislikes
  1087. })
  1088. });
  1089. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1090. userId: session.userId,
  1091. type: "song__like",
  1092. payload: {
  1093. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1094. youtubeId,
  1095. thumbnail
  1096. }
  1097. });
  1098. } else {
  1099. CacheModule.runJob("PUB", {
  1100. channel: "song.dislike",
  1101. value: JSON.stringify({
  1102. youtubeId,
  1103. userId: session.userId,
  1104. likes,
  1105. dislikes
  1106. })
  1107. });
  1108. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1109. userId: session.userId,
  1110. type: "song__dislike",
  1111. payload: {
  1112. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1113. youtubeId,
  1114. thumbnail
  1115. }
  1116. });
  1117. }
  1118. }
  1119. return cb({
  1120. status: "success",
  1121. message: "Song has been successfully added to the playlist",
  1122. data: { songs: playlist.songs }
  1123. });
  1124. }
  1125. );
  1126. }),
  1127. /**
  1128. * Adds a set of songs to a private playlist
  1129. *
  1130. * @param {object} session - the session object automatically added by the websocket
  1131. * @param {string} url - the url of the the YouTube playlist
  1132. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1133. * @param {boolean} musicOnly - whether to only add music to the playlist
  1134. * @param {Function} cb - gets called with the result
  1135. */
  1136. addSetToPlaylist: isLoginRequired(async function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1137. let videosInPlaylistTotal = 0;
  1138. let songsInPlaylistTotal = 0;
  1139. let addSongsStats = null;
  1140. const addedSongs = [];
  1141. this.keepLongJob();
  1142. this.publishProgress({
  1143. status: "started",
  1144. title: "Import YouTube playlist",
  1145. message: "Importing YouTube playlist.",
  1146. id: this.toString()
  1147. });
  1148. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1149. await CacheModule.runJob(
  1150. "PUB",
  1151. {
  1152. channel: "longJob.added",
  1153. value: { jobId: this.toString(), userId: session.userId }
  1154. },
  1155. this
  1156. );
  1157. async.waterfall(
  1158. [
  1159. next => {
  1160. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 1)` });
  1161. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  1162. .then(res => {
  1163. if (res.filteredSongs) {
  1164. videosInPlaylistTotal = res.songs.length;
  1165. songsInPlaylistTotal = res.filteredSongs.length;
  1166. } else {
  1167. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1168. }
  1169. next(null, res.songs);
  1170. })
  1171. .catch(err => {
  1172. next(err);
  1173. });
  1174. },
  1175. (youtubeIds, next) => {
  1176. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 2)` });
  1177. let successful = 0;
  1178. let failed = 0;
  1179. let alreadyInPlaylist = 0;
  1180. let alreadyInLikedPlaylist = 0;
  1181. let alreadyInDislikedPlaylist = 0;
  1182. if (youtubeIds.length === 0) next();
  1183. async.eachLimit(
  1184. youtubeIds,
  1185. 1,
  1186. (youtubeId, next) => {
  1187. WSModule.runJob(
  1188. "RUN_ACTION2",
  1189. {
  1190. session,
  1191. namespace: "playlists",
  1192. action: "addSongToPlaylist",
  1193. args: [true, youtubeId, playlistId]
  1194. },
  1195. this
  1196. )
  1197. .then(res => {
  1198. if (res.status === "success") {
  1199. successful += 1;
  1200. addedSongs.push(youtubeId);
  1201. } else failed += 1;
  1202. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1203. else if (
  1204. res.message ===
  1205. "That song is already in your Liked Songs playlist. " +
  1206. "A song cannot be in both the Liked Songs playlist" +
  1207. " and the Disliked Songs playlist at the same time."
  1208. )
  1209. alreadyInLikedPlaylist += 1;
  1210. else if (
  1211. res.message ===
  1212. "That song is already in your Disliked Songs playlist. " +
  1213. "A song cannot be in both the Liked Songs playlist " +
  1214. "and the Disliked Songs playlist at the same time."
  1215. )
  1216. alreadyInDislikedPlaylist += 1;
  1217. })
  1218. .catch(() => {
  1219. failed += 1;
  1220. })
  1221. .finally(() => next());
  1222. },
  1223. () => {
  1224. addSongsStats = {
  1225. successful,
  1226. failed,
  1227. alreadyInPlaylist,
  1228. alreadyInLikedPlaylist,
  1229. alreadyInDislikedPlaylist
  1230. };
  1231. next(null);
  1232. }
  1233. );
  1234. },
  1235. next => {
  1236. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 3)` });
  1237. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1238. .then(playlist => next(null, playlist))
  1239. .catch(next);
  1240. },
  1241. (playlist, next) => {
  1242. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 4)` });
  1243. if (!playlist) return next("Playlist not found.");
  1244. if (playlist.createdBy !== session.userId)
  1245. return hasPermission("playlists.addSetToPlaylist", session)
  1246. .then(() => next(null, playlist))
  1247. .catch(() => next("Invalid permissions."));
  1248. return next(null, playlist);
  1249. }
  1250. ],
  1251. async (err, playlist) => {
  1252. if (err) {
  1253. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1254. this.log(
  1255. "ERROR",
  1256. "PLAYLIST_IMPORT",
  1257. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1258. );
  1259. this.publishProgress({
  1260. status: "error",
  1261. message: err
  1262. });
  1263. return cb({ status: "error", message: err });
  1264. }
  1265. if (playlist.privacy === "public")
  1266. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1267. userId: session.userId,
  1268. type: "playlist__import_playlist",
  1269. payload: {
  1270. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1271. playlistId
  1272. }
  1273. });
  1274. this.log(
  1275. "SUCCESS",
  1276. "PLAYLIST_IMPORT",
  1277. `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}.`
  1278. );
  1279. this.publishProgress({
  1280. status: "success",
  1281. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1282. });
  1283. return cb({
  1284. status: "success",
  1285. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1286. data: {
  1287. songs: playlist.songs,
  1288. stats: {
  1289. videosInPlaylistTotal,
  1290. songsInPlaylistTotal,
  1291. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1292. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1293. }
  1294. }
  1295. });
  1296. }
  1297. );
  1298. }),
  1299. /**
  1300. * Removes a song from a private playlist
  1301. *
  1302. * @param {object} session - the session object automatically added by the websocket
  1303. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1304. * @param {string} playlistId - the id of the playlist we are removing the song from
  1305. * @param {Function} cb - gets called with the result
  1306. */
  1307. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1308. async.waterfall(
  1309. [
  1310. next => {
  1311. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1312. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1313. return next();
  1314. },
  1315. next => {
  1316. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1317. .then(playlist => {
  1318. if (!playlist) return next("Playlist not found.");
  1319. if (playlist.createdBy !== session.userId)
  1320. return hasPermission("playlists.removeSongFromPlaylist", session)
  1321. .then(() => next(null, playlist))
  1322. .catch(() => next("Invalid permissions."));
  1323. return next(null, playlist);
  1324. })
  1325. .catch(next);
  1326. },
  1327. (playlist, next) => {
  1328. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1329. .then(res =>
  1330. next(null, playlist, {
  1331. _id: res.song._id,
  1332. title: res.song.title,
  1333. thumbnail: res.song.thumbnail,
  1334. artists: res.song.artists,
  1335. youtubeId: res.song.youtubeId
  1336. })
  1337. )
  1338. .catch(next);
  1339. },
  1340. (playlist, newSong, next) => {
  1341. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, youtubeId }, this)
  1342. .then(res => {
  1343. const { ratings } = res;
  1344. next(null, playlist, newSong, ratings);
  1345. })
  1346. .catch(next);
  1347. },
  1348. (playlist, newSong, ratings, next) => {
  1349. const { _id, title, artists, thumbnail } = newSong;
  1350. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1351. if (playlist.type === "user" && playlist.privacy === "public") {
  1352. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1353. userId: session.userId,
  1354. type: "playlist__remove_song",
  1355. payload: {
  1356. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1357. thumbnail,
  1358. playlistId,
  1359. youtubeId: newSong.youtubeId
  1360. }
  1361. });
  1362. }
  1363. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1364. const { likes, dislikes } = ratings;
  1365. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1366. if (playlist.type === "user-liked") {
  1367. CacheModule.runJob("PUB", {
  1368. channel: "ratings.unlike",
  1369. value: JSON.stringify({
  1370. youtubeId: newSong.youtubeId,
  1371. userId: session.userId,
  1372. likes,
  1373. dislikes
  1374. })
  1375. });
  1376. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1377. userId: session.userId,
  1378. type: "song__unlike",
  1379. payload: {
  1380. message: `Removed <youtubeId>${title} by ${artists.join(
  1381. ", "
  1382. )}</youtubeId> from your Liked Songs`,
  1383. youtubeId: newSong.youtubeId,
  1384. thumbnail
  1385. }
  1386. });
  1387. } else {
  1388. CacheModule.runJob("PUB", {
  1389. channel: "song.undislike",
  1390. value: JSON.stringify({
  1391. youtubeId: newSong.youtubeId,
  1392. userId: session.userId,
  1393. likes,
  1394. dislikes
  1395. })
  1396. });
  1397. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1398. userId: session.userId,
  1399. type: "song__undislike",
  1400. payload: {
  1401. message: `Removed <youtubeId>${title} by ${artists.join(
  1402. ", "
  1403. )}</youtubeId> from your Disliked Songs`,
  1404. youtubeId: newSong.youtubeId,
  1405. thumbnail
  1406. }
  1407. });
  1408. }
  1409. }
  1410. return next(null, playlist);
  1411. }
  1412. ],
  1413. async (err, playlist) => {
  1414. if (err) {
  1415. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1416. this.log(
  1417. "ERROR",
  1418. "PLAYLIST_REMOVE_SONG",
  1419. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1420. );
  1421. return cb({ status: "error", message: err });
  1422. }
  1423. this.log(
  1424. "SUCCESS",
  1425. "PLAYLIST_REMOVE_SONG",
  1426. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1427. );
  1428. CacheModule.runJob("PUB", {
  1429. channel: "playlist.removeSong",
  1430. value: {
  1431. playlistId: playlist._id,
  1432. youtubeId,
  1433. userId: session.userId,
  1434. privacy: playlist.privacy
  1435. }
  1436. });
  1437. return cb({
  1438. status: "success",
  1439. message: "Song has been successfully removed from playlist",
  1440. data: { songs: playlist.songs }
  1441. });
  1442. }
  1443. );
  1444. }),
  1445. /**
  1446. * Updates the displayName of a private playlist
  1447. *
  1448. * @param {object} session - the session object automatically added by the websocket
  1449. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1450. * @param {Function} cb - gets called with the result
  1451. */
  1452. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1453. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1454. async.waterfall(
  1455. [
  1456. next => {
  1457. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1458. .then(playlist => next(null, playlist))
  1459. .catch(next);
  1460. },
  1461. (playlist, next) => {
  1462. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1463. return next(null);
  1464. },
  1465. next => {
  1466. playlistModel.updateOne(
  1467. { _id: playlistId, createdBy: session.userId },
  1468. { $set: { displayName } },
  1469. { runValidators: true },
  1470. next
  1471. );
  1472. },
  1473. (res, next) => {
  1474. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1475. .then(playlist => next(null, playlist))
  1476. .catch(next);
  1477. }
  1478. ],
  1479. async (err, playlist) => {
  1480. if (err) {
  1481. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1482. this.log(
  1483. "ERROR",
  1484. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1485. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1486. );
  1487. return cb({ status: "error", message: err });
  1488. }
  1489. this.log(
  1490. "SUCCESS",
  1491. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1492. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1493. );
  1494. CacheModule.runJob("PUB", {
  1495. channel: "playlist.updateDisplayName",
  1496. value: {
  1497. playlistId,
  1498. displayName,
  1499. userId: session.userId,
  1500. privacy: playlist.privacy
  1501. }
  1502. });
  1503. CacheModule.runJob("PUB", {
  1504. channel: "playlist.updated",
  1505. value: { playlistId }
  1506. });
  1507. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1508. userId: session.userId,
  1509. type: "playlist__edit_display_name",
  1510. payload: {
  1511. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1512. playlistId
  1513. }
  1514. });
  1515. return cb({
  1516. status: "success",
  1517. message: "Playlist has been successfully updated"
  1518. });
  1519. }
  1520. );
  1521. }),
  1522. /**
  1523. * Removes a user's own modifiable user playlist
  1524. *
  1525. * @param {object} session - the session object automatically added by the websocket
  1526. * @param {string} playlistId - the id of the playlist we are removing
  1527. * @param {Function} cb - gets called with the result
  1528. */
  1529. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1530. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1531. async.waterfall(
  1532. [
  1533. next => {
  1534. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1535. .then(playlist => next(null, playlist))
  1536. .catch(next);
  1537. },
  1538. (playlist, next) => {
  1539. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1540. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1541. return next(null, playlist);
  1542. },
  1543. (playlist, next) => {
  1544. userModel.updateOne(
  1545. { _id: playlist.createdBy },
  1546. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1547. err => next(err, playlist)
  1548. );
  1549. },
  1550. (playlist, next) => {
  1551. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1552. .then(() => next(null, playlist))
  1553. .catch(next);
  1554. }
  1555. ],
  1556. async (err, playlist) => {
  1557. if (err) {
  1558. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1559. this.log(
  1560. "ERROR",
  1561. "PLAYLIST_REMOVE",
  1562. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1563. );
  1564. return cb({ status: "error", message: err });
  1565. }
  1566. this.log(
  1567. "SUCCESS",
  1568. "PLAYLIST_REMOVE",
  1569. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1570. );
  1571. CacheModule.runJob("PUB", {
  1572. channel: "playlist.delete",
  1573. value: {
  1574. userId: session.userId,
  1575. playlistId
  1576. }
  1577. });
  1578. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1579. userId: playlist.createdBy,
  1580. type: "playlist__remove",
  1581. payload: {
  1582. message: `Removed playlist ${playlist.displayName}`
  1583. }
  1584. });
  1585. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1586. return cb({
  1587. status: "success",
  1588. message: "Playlist successfully removed"
  1589. });
  1590. }
  1591. );
  1592. }),
  1593. /**
  1594. * Removes a user's modifiable user playlist as an admin
  1595. *
  1596. * @param {object} session - the session object automatically added by the websocket
  1597. * @param {string} playlistId - the id of the playlist we are removing
  1598. * @param {Function} cb - gets called with the result
  1599. */
  1600. removeAdmin: useHasPermission("playlists.removeAdmin", async function removeAdmin(session, playlistId, cb) {
  1601. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1602. async.waterfall(
  1603. [
  1604. next => {
  1605. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1606. .then(playlist => next(null, playlist))
  1607. .catch(next);
  1608. },
  1609. (playlist, next) => {
  1610. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1611. return next(null, playlist);
  1612. },
  1613. (playlist, next) => {
  1614. userModel.updateOne(
  1615. { _id: playlist.createdBy },
  1616. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1617. err => next(err, playlist, playlist.createdBy)
  1618. );
  1619. },
  1620. (playlist, playlistCreator, next) => {
  1621. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1622. .then(() => next(null, playlistCreator))
  1623. .catch(next);
  1624. }
  1625. ],
  1626. async (err, playlistCreator) => {
  1627. if (err) {
  1628. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1629. this.log(
  1630. "ERROR",
  1631. "PLAYLIST_REMOVE_ADMIN",
  1632. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1633. );
  1634. return cb({ status: "error", message: err });
  1635. }
  1636. this.log(
  1637. "SUCCESS",
  1638. "PLAYLIST_REMOVE_ADMIN",
  1639. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1640. );
  1641. CacheModule.runJob("PUB", {
  1642. channel: "playlist.delete",
  1643. value: {
  1644. userId: playlistCreator,
  1645. playlistId
  1646. }
  1647. });
  1648. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1649. return cb({
  1650. status: "success",
  1651. message: "Playlist successfully removed"
  1652. });
  1653. }
  1654. );
  1655. }),
  1656. /**
  1657. * Updates the privacy of a private playlist
  1658. *
  1659. * @param {object} session - the session object automatically added by the websocket
  1660. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1661. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1662. * @param {Function} cb - gets called with the result
  1663. */
  1664. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1665. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1666. async.waterfall(
  1667. [
  1668. next => {
  1669. playlistModel.updateOne(
  1670. { _id: playlistId, createdBy: session.userId },
  1671. { $set: { privacy } },
  1672. { runValidators: true },
  1673. next
  1674. );
  1675. },
  1676. (res, next) => {
  1677. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1678. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1679. else {
  1680. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1681. .then(playlist => next(null, playlist))
  1682. .catch(next);
  1683. }
  1684. }
  1685. ],
  1686. async (err, playlist) => {
  1687. if (err) {
  1688. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1689. this.log(
  1690. "ERROR",
  1691. "PLAYLIST_UPDATE_PRIVACY",
  1692. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1693. );
  1694. return cb({ status: "error", message: err });
  1695. }
  1696. this.log(
  1697. "SUCCESS",
  1698. "PLAYLIST_UPDATE_PRIVACY",
  1699. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1700. );
  1701. CacheModule.runJob("PUB", {
  1702. channel: "playlist.updatePrivacy",
  1703. value: {
  1704. userId: session.userId,
  1705. playlist
  1706. }
  1707. });
  1708. CacheModule.runJob("PUB", {
  1709. channel: "playlist.updated",
  1710. value: { playlistId }
  1711. });
  1712. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1713. userId: session.userId,
  1714. type: "playlist__edit_privacy",
  1715. payload: {
  1716. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1717. playlistId
  1718. }
  1719. });
  1720. return cb({
  1721. status: "success",
  1722. message: "Playlist has been successfully updated"
  1723. });
  1724. }
  1725. );
  1726. }),
  1727. /**
  1728. * Updates the privacy of a playlist
  1729. *
  1730. * @param {object} session - the session object automatically added by the websocket
  1731. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1732. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1733. * @param {Function} cb - gets called with the result
  1734. */
  1735. updatePrivacyAdmin: useHasPermission(
  1736. "playlists.updatePrivacy",
  1737. async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1738. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1739. async.waterfall(
  1740. [
  1741. next => {
  1742. playlistModel.updateOne(
  1743. { _id: playlistId },
  1744. { $set: { privacy } },
  1745. { runValidators: true },
  1746. next
  1747. );
  1748. },
  1749. (res, next) => {
  1750. if (res.n === 0) next("No playlist found with that id.");
  1751. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1752. else {
  1753. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1754. .then(playlist => next(null, playlist))
  1755. .catch(next);
  1756. }
  1757. }
  1758. ],
  1759. async (err, playlist) => {
  1760. if (err) {
  1761. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1762. this.log(
  1763. "ERROR",
  1764. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1765. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1766. );
  1767. return cb({ status: "error", message: err });
  1768. }
  1769. this.log(
  1770. "SUCCESS",
  1771. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1772. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1773. );
  1774. if (playlist.type === "user") {
  1775. CacheModule.runJob("PUB", {
  1776. channel: "playlist.updatePrivacy",
  1777. value: {
  1778. userId: playlist.createdBy,
  1779. playlist
  1780. }
  1781. });
  1782. }
  1783. CacheModule.runJob("PUB", {
  1784. channel: "playlist.updated",
  1785. value: { playlistId }
  1786. });
  1787. return cb({
  1788. status: "success",
  1789. message: "Playlist has been successfully updated"
  1790. });
  1791. }
  1792. );
  1793. }
  1794. ),
  1795. /**
  1796. * Deletes all orphaned station playlists
  1797. *
  1798. * @param {object} session - the session object automatically added by socket.io
  1799. * @param {Function} cb - gets called with the result
  1800. */
  1801. deleteOrphanedStationPlaylists: useHasPermission(
  1802. "playlists.deleteOrphanedStationPlaylists",
  1803. async function index(session, cb) {
  1804. this.keepLongJob();
  1805. this.publishProgress({
  1806. status: "started",
  1807. title: "Delete orphaned station playlists",
  1808. message: "Deleting orphaned station playlists.",
  1809. id: this.toString()
  1810. });
  1811. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1812. await CacheModule.runJob(
  1813. "PUB",
  1814. {
  1815. channel: "longJob.added",
  1816. value: { jobId: this.toString(), userId: session.userId }
  1817. },
  1818. this
  1819. );
  1820. async.waterfall(
  1821. [
  1822. next => {
  1823. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1824. .then(() => next())
  1825. .catch(next);
  1826. }
  1827. ],
  1828. async err => {
  1829. if (err) {
  1830. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1831. this.log(
  1832. "ERROR",
  1833. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1834. `Deleting orphaned station playlists failed. "${err}"`
  1835. );
  1836. this.publishProgress({
  1837. status: "error",
  1838. message: err
  1839. });
  1840. return cb({ status: "error", message: err });
  1841. }
  1842. this.log(
  1843. "SUCCESS",
  1844. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1845. "Deleting orphaned station playlists successful."
  1846. );
  1847. this.publishProgress({
  1848. status: "success",
  1849. message: "Successfully deleted orphaned station playlists."
  1850. });
  1851. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1852. }
  1853. );
  1854. }
  1855. ),
  1856. /**
  1857. * Deletes all orphaned genre playlists
  1858. *
  1859. * @param {object} session - the session object automatically added by socket.io
  1860. * @param {Function} cb - gets called with the result
  1861. */
  1862. deleteOrphanedGenrePlaylists: useHasPermission(
  1863. "playlists.deleteOrphanedGenrePlaylists",
  1864. async function index(session, cb) {
  1865. this.keepLongJob();
  1866. this.publishProgress({
  1867. status: "started",
  1868. title: "Delete orphaned genre playlists",
  1869. message: "Deleting orphaned genre playlists.",
  1870. id: this.toString()
  1871. });
  1872. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1873. await CacheModule.runJob(
  1874. "PUB",
  1875. {
  1876. channel: "longJob.added",
  1877. value: { jobId: this.toString(), userId: session.userId }
  1878. },
  1879. this
  1880. );
  1881. async.waterfall(
  1882. [
  1883. next => {
  1884. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1885. .then(() => next())
  1886. .catch(next);
  1887. }
  1888. ],
  1889. async err => {
  1890. if (err) {
  1891. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1892. this.log(
  1893. "ERROR",
  1894. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1895. `Deleting orphaned genre playlists failed. "${err}"`
  1896. );
  1897. this.publishProgress({
  1898. status: "error",
  1899. message: err
  1900. });
  1901. return cb({ status: "error", message: err });
  1902. }
  1903. this.log(
  1904. "SUCCESS",
  1905. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1906. "Deleting orphaned genre playlists successful."
  1907. );
  1908. this.publishProgress({
  1909. status: "success",
  1910. message: "Successfully deleted orphaned genre playlists."
  1911. });
  1912. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1913. }
  1914. );
  1915. }
  1916. ),
  1917. /**
  1918. * Requests orpahned playlist songs
  1919. *
  1920. * @param {object} session - the session object automatically added by socket.io
  1921. * @param {Function} cb - gets called with the result
  1922. */
  1923. requestOrphanedPlaylistSongs: useHasPermission(
  1924. "playlists.requestOrphanedPlaylistSongs",
  1925. async function index(session, cb) {
  1926. this.keepLongJob();
  1927. this.publishProgress({
  1928. status: "started",
  1929. title: "Request orphaned playlist songs",
  1930. message: "Requesting orphaned playlist songs.",
  1931. id: this.toString()
  1932. });
  1933. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1934. await CacheModule.runJob(
  1935. "PUB",
  1936. {
  1937. channel: "longJob.added",
  1938. value: { jobId: this.toString(), userId: session.userId }
  1939. },
  1940. this
  1941. );
  1942. async.waterfall(
  1943. [
  1944. next => {
  1945. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, 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. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1956. `Requesting orphaned playlist songs failed. "${err}"`
  1957. );
  1958. this.publishProgress({
  1959. status: "error",
  1960. message: err
  1961. });
  1962. return cb({ status: "error", message: err });
  1963. }
  1964. this.log(
  1965. "SUCCESS",
  1966. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1967. "Requesting orphaned playlist songs was successful."
  1968. );
  1969. this.publishProgress({
  1970. status: "success",
  1971. message: "Successfully requested orphaned playlist songs."
  1972. });
  1973. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1974. }
  1975. );
  1976. }
  1977. ),
  1978. /**
  1979. * Clears and refills a station playlist
  1980. *
  1981. * @param {object} session - the session object automatically added by socket.io
  1982. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1983. * @param {Function} cb - gets called with the result
  1984. */
  1985. clearAndRefillStationPlaylist: useHasPermission(
  1986. "playlists.clearAndRefillStationPlaylist",
  1987. async function index(session, playlistId, cb) {
  1988. async.waterfall(
  1989. [
  1990. next => {
  1991. if (!playlistId) next("Please specify a playlist id");
  1992. else {
  1993. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1994. .then(() => {
  1995. next();
  1996. })
  1997. .catch(err => {
  1998. next(err);
  1999. });
  2000. }
  2001. }
  2002. ],
  2003. async err => {
  2004. if (err) {
  2005. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2006. this.log(
  2007. "ERROR",
  2008. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2009. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2010. );
  2011. return cb({ status: "error", message: err });
  2012. }
  2013. this.log(
  2014. "SUCCESS",
  2015. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2016. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2017. );
  2018. return cb({
  2019. status: "success",
  2020. message: "Playlist has been successfully cleared and refilled"
  2021. });
  2022. }
  2023. );
  2024. }
  2025. ),
  2026. /**
  2027. * Clears and refills a genre playlist
  2028. *
  2029. * @param {object} session - the session object automatically added by socket.io
  2030. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2031. * @param {Function} cb - gets called with the result
  2032. */
  2033. clearAndRefillGenrePlaylist: useHasPermission(
  2034. "playlists.clearAndRefillGenrePlaylist",
  2035. async function index(session, playlistId, cb) {
  2036. async.waterfall(
  2037. [
  2038. next => {
  2039. if (!playlistId) next("Please specify a playlist id");
  2040. else {
  2041. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2042. .then(() => {
  2043. next();
  2044. })
  2045. .catch(err => {
  2046. next(err);
  2047. });
  2048. }
  2049. }
  2050. ],
  2051. async err => {
  2052. if (err) {
  2053. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2054. this.log(
  2055. "ERROR",
  2056. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2057. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2058. );
  2059. return cb({ status: "error", message: err });
  2060. }
  2061. this.log(
  2062. "SUCCESS",
  2063. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2064. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2065. );
  2066. return cb({
  2067. status: "success",
  2068. message: "Playlist has been successfully cleared and refilled"
  2069. });
  2070. }
  2071. );
  2072. }
  2073. ),
  2074. /**
  2075. * Clears and refills all station playlists
  2076. *
  2077. * @param {object} session - the session object automatically added by socket.io
  2078. * @param {Function} cb - gets called with the result
  2079. */
  2080. clearAndRefillAllStationPlaylists: useHasPermission(
  2081. "playlists.clearAndRefillAllStationPlaylists",
  2082. async function index(session, cb) {
  2083. this.keepLongJob();
  2084. this.publishProgress({
  2085. status: "started",
  2086. title: "Clear and refill all station playlists",
  2087. message: "Clearing and refilling all station playlists.",
  2088. id: this.toString()
  2089. });
  2090. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2091. await CacheModule.runJob(
  2092. "PUB",
  2093. {
  2094. channel: "longJob.added",
  2095. value: { jobId: this.toString(), userId: session.userId }
  2096. },
  2097. this
  2098. );
  2099. async.waterfall(
  2100. [
  2101. next => {
  2102. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2103. .then(response => {
  2104. next(null, response.playlists);
  2105. })
  2106. .catch(err => {
  2107. next(err);
  2108. });
  2109. },
  2110. (playlists, next) => {
  2111. async.eachLimit(
  2112. playlists,
  2113. 1,
  2114. (playlist, next) => {
  2115. this.publishProgress({
  2116. status: "update",
  2117. message: `Clearing and refilling "${playlist._id}"`
  2118. });
  2119. PlaylistsModule.runJob(
  2120. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2121. { playlistId: playlist._id },
  2122. this
  2123. )
  2124. .then(() => {
  2125. next();
  2126. })
  2127. .catch(err => {
  2128. next(err);
  2129. });
  2130. },
  2131. next
  2132. );
  2133. }
  2134. ],
  2135. async err => {
  2136. if (err) {
  2137. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2138. this.log(
  2139. "ERROR",
  2140. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2141. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2142. );
  2143. this.publishProgress({
  2144. status: "error",
  2145. message: err
  2146. });
  2147. return cb({ status: "error", message: err });
  2148. }
  2149. this.log(
  2150. "SUCCESS",
  2151. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2152. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2153. );
  2154. this.publishProgress({
  2155. status: "success",
  2156. message: "Playlists have been successfully cleared and refilled."
  2157. });
  2158. return cb({
  2159. status: "success",
  2160. message: "Playlists have been successfully cleared and refilled"
  2161. });
  2162. }
  2163. );
  2164. }
  2165. ),
  2166. /**
  2167. * Clears and refills all genre playlists
  2168. *
  2169. * @param {object} session - the session object automatically added by socket.io
  2170. * @param {Function} cb - gets called with the result
  2171. */
  2172. clearAndRefillAllGenrePlaylists: useHasPermission(
  2173. "playlists.clearAndRefillAllGenrePlaylists",
  2174. async function index(session, cb) {
  2175. this.keepLongJob();
  2176. this.publishProgress({
  2177. status: "started",
  2178. title: "Clear and refill all genre playlists",
  2179. message: "Clearing and refilling all genre playlists.",
  2180. id: this.toString()
  2181. });
  2182. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2183. await CacheModule.runJob(
  2184. "PUB",
  2185. {
  2186. channel: "longJob.added",
  2187. value: { jobId: this.toString(), userId: session.userId }
  2188. },
  2189. this
  2190. );
  2191. async.waterfall(
  2192. [
  2193. next => {
  2194. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2195. .then(response => {
  2196. next(null, response.playlists);
  2197. })
  2198. .catch(err => {
  2199. next(err);
  2200. });
  2201. },
  2202. (playlists, next) => {
  2203. async.eachLimit(
  2204. playlists,
  2205. 1,
  2206. (playlist, next) => {
  2207. this.publishProgress({
  2208. status: "update",
  2209. message: `Clearing and refilling "${playlist._id}"`
  2210. });
  2211. PlaylistsModule.runJob(
  2212. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2213. { playlistId: playlist._id },
  2214. this
  2215. )
  2216. .then(() => {
  2217. next();
  2218. })
  2219. .catch(err => {
  2220. next(err);
  2221. });
  2222. },
  2223. next
  2224. );
  2225. }
  2226. ],
  2227. async err => {
  2228. if (err) {
  2229. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2230. this.log(
  2231. "ERROR",
  2232. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2233. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2234. );
  2235. this.publishProgress({
  2236. status: "error",
  2237. message: err
  2238. });
  2239. return cb({ status: "error", message: err });
  2240. }
  2241. this.log(
  2242. "SUCCESS",
  2243. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2244. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2245. );
  2246. this.publishProgress({
  2247. status: "success",
  2248. message: "Playlists have been successfully cleared and refilled."
  2249. });
  2250. return cb({
  2251. status: "success",
  2252. message: "Playlists have been successfully cleared and refilled"
  2253. });
  2254. }
  2255. );
  2256. }
  2257. ),
  2258. /**
  2259. * Create missing genre playlists
  2260. *
  2261. * @param {object} session - the session object automatically added by socket.io
  2262. * @param {Function} cb - gets called with the result
  2263. */
  2264. createMissingGenrePlaylists: useHasPermission(
  2265. "playlists.createMissingGenrePlaylists",
  2266. async function index(session, cb) {
  2267. this.keepLongJob();
  2268. this.publishProgress({
  2269. status: "started",
  2270. title: "Create missing genre playlists",
  2271. message: "Creating missing genre playlists.",
  2272. id: this.toString()
  2273. });
  2274. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2275. await CacheModule.runJob(
  2276. "PUB",
  2277. {
  2278. channel: "longJob.added",
  2279. value: { jobId: this.toString(), userId: session.userId }
  2280. },
  2281. this
  2282. );
  2283. async.waterfall(
  2284. [
  2285. next => {
  2286. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2287. .then(() => {
  2288. next();
  2289. })
  2290. .catch(err => {
  2291. next(err);
  2292. });
  2293. }
  2294. ],
  2295. async err => {
  2296. if (err) {
  2297. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2298. this.log(
  2299. "ERROR",
  2300. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2301. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2302. );
  2303. this.publishProgress({
  2304. status: "error",
  2305. message: err
  2306. });
  2307. return cb({ status: "error", message: err });
  2308. }
  2309. this.log(
  2310. "SUCCESS",
  2311. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2312. `Successfully created missing genre playlists for user "${session.userId}".`
  2313. );
  2314. this.publishProgress({
  2315. status: "success",
  2316. message: "Missing genre playlists have been successfully created."
  2317. });
  2318. return cb({
  2319. status: "success",
  2320. message: "Missing genre playlists have been successfully created"
  2321. });
  2322. }
  2323. );
  2324. }
  2325. )
  2326. };