playlists.js 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542
  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. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1158. userModel.findOne({ _id: session.userId }, (err, user) => {
  1159. if (user && user.role === "admin") return next(null, true);
  1160. return next(null, false);
  1161. });
  1162. });
  1163. },
  1164. (isAdmin, next) => {
  1165. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 1)` });
  1166. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1167. const channelRegex =
  1168. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1169. if (playlistRegex.exec(url) || channelRegex.exec(url))
  1170. YouTubeModule.runJob(
  1171. playlistRegex.exec(url) ? "GET_PLAYLIST" : "GET_CHANNEL",
  1172. {
  1173. url,
  1174. musicOnly,
  1175. disableSearch: !isAdmin
  1176. },
  1177. this
  1178. )
  1179. .then(res => {
  1180. if (res.filteredSongs) {
  1181. videosInPlaylistTotal = res.songs.length;
  1182. songsInPlaylistTotal = res.filteredSongs.length;
  1183. } else {
  1184. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1185. }
  1186. next(null, res.songs);
  1187. })
  1188. .catch(next);
  1189. else next("Invalid YouTube URL.");
  1190. },
  1191. (youtubeIds, next) => {
  1192. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 2)` });
  1193. let successful = 0;
  1194. let failed = 0;
  1195. let alreadyInPlaylist = 0;
  1196. let alreadyInLikedPlaylist = 0;
  1197. let alreadyInDislikedPlaylist = 0;
  1198. if (youtubeIds.length === 0) next();
  1199. async.eachLimit(
  1200. youtubeIds,
  1201. 1,
  1202. (youtubeId, next) => {
  1203. WSModule.runJob(
  1204. "RUN_ACTION2",
  1205. {
  1206. session,
  1207. namespace: "playlists",
  1208. action: "addSongToPlaylist",
  1209. args: [true, youtubeId, playlistId]
  1210. },
  1211. this
  1212. )
  1213. .then(res => {
  1214. if (res.status === "success") {
  1215. successful += 1;
  1216. addedSongs.push(youtubeId);
  1217. } else failed += 1;
  1218. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1219. else if (
  1220. res.message ===
  1221. "That song is already in your Liked Songs playlist. " +
  1222. "A song cannot be in both the Liked Songs playlist" +
  1223. " and the Disliked Songs playlist at the same time."
  1224. )
  1225. alreadyInLikedPlaylist += 1;
  1226. else if (
  1227. res.message ===
  1228. "That song is already in your Disliked Songs playlist. " +
  1229. "A song cannot be in both the Liked Songs playlist " +
  1230. "and the Disliked Songs playlist at the same time."
  1231. )
  1232. alreadyInDislikedPlaylist += 1;
  1233. })
  1234. .catch(() => {
  1235. failed += 1;
  1236. })
  1237. .finally(() => next());
  1238. },
  1239. () => {
  1240. addSongsStats = {
  1241. successful,
  1242. failed,
  1243. alreadyInPlaylist,
  1244. alreadyInLikedPlaylist,
  1245. alreadyInDislikedPlaylist
  1246. };
  1247. next(null);
  1248. }
  1249. );
  1250. },
  1251. next => {
  1252. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 3)` });
  1253. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1254. .then(playlist => next(null, playlist))
  1255. .catch(next);
  1256. },
  1257. (playlist, next) => {
  1258. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 4)` });
  1259. if (!playlist) return next("Playlist not found.");
  1260. if (playlist.createdBy !== session.userId)
  1261. return hasPermission("playlists.songs.add", session)
  1262. .then(() => next(null, playlist))
  1263. .catch(() => next("Invalid permissions."));
  1264. return next(null, playlist);
  1265. }
  1266. ],
  1267. async (err, playlist) => {
  1268. if (err) {
  1269. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1270. this.log(
  1271. "ERROR",
  1272. "PLAYLIST_IMPORT",
  1273. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1274. );
  1275. this.publishProgress({
  1276. status: "error",
  1277. message: err
  1278. });
  1279. return cb({ status: "error", message: err });
  1280. }
  1281. if (playlist.privacy === "public")
  1282. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1283. userId: session.userId,
  1284. type: "playlist__import_playlist",
  1285. payload: {
  1286. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1287. playlistId
  1288. }
  1289. });
  1290. this.log(
  1291. "SUCCESS",
  1292. "PLAYLIST_IMPORT",
  1293. `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}.`
  1294. );
  1295. this.publishProgress({
  1296. status: "success",
  1297. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1298. });
  1299. return cb({
  1300. status: "success",
  1301. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1302. data: {
  1303. songs: playlist.songs,
  1304. stats: {
  1305. videosInPlaylistTotal,
  1306. songsInPlaylistTotal,
  1307. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1308. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1309. }
  1310. }
  1311. });
  1312. }
  1313. );
  1314. }),
  1315. /**
  1316. * Removes a song from a private playlist
  1317. *
  1318. * @param {object} session - the session object automatically added by the websocket
  1319. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1320. * @param {string} playlistId - the id of the playlist we are removing the song from
  1321. * @param {Function} cb - gets called with the result
  1322. */
  1323. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1324. async.waterfall(
  1325. [
  1326. next => {
  1327. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1328. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1329. return next();
  1330. },
  1331. next => {
  1332. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1333. .then(playlist => {
  1334. if (!playlist) return next("Playlist not found.");
  1335. if (playlist.createdBy !== session.userId)
  1336. return hasPermission("playlists.songs.remove", session)
  1337. .then(() => next(null, playlist))
  1338. .catch(() => next("Invalid permissions."));
  1339. return next(null, playlist);
  1340. })
  1341. .catch(next);
  1342. },
  1343. (playlist, next) => {
  1344. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1345. .then(res =>
  1346. next(null, playlist, {
  1347. _id: res.song._id,
  1348. title: res.song.title,
  1349. thumbnail: res.song.thumbnail,
  1350. artists: res.song.artists,
  1351. youtubeId: res.song.youtubeId
  1352. })
  1353. )
  1354. .catch(next);
  1355. },
  1356. (playlist, newSong, next) => {
  1357. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, youtubeId }, this)
  1358. .then(res => {
  1359. const { ratings } = res;
  1360. next(null, playlist, newSong, ratings);
  1361. })
  1362. .catch(next);
  1363. },
  1364. (playlist, newSong, ratings, next) => {
  1365. const { _id, title, artists, thumbnail } = newSong;
  1366. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1367. if (playlist.type === "user" && playlist.privacy === "public") {
  1368. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1369. userId: session.userId,
  1370. type: "playlist__remove_song",
  1371. payload: {
  1372. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1373. thumbnail,
  1374. playlistId,
  1375. youtubeId: newSong.youtubeId
  1376. }
  1377. });
  1378. }
  1379. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1380. const { likes, dislikes } = ratings;
  1381. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1382. if (playlist.type === "user-liked") {
  1383. CacheModule.runJob("PUB", {
  1384. channel: "ratings.unlike",
  1385. value: JSON.stringify({
  1386. youtubeId: newSong.youtubeId,
  1387. userId: session.userId,
  1388. likes,
  1389. dislikes
  1390. })
  1391. });
  1392. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1393. userId: session.userId,
  1394. type: "song__unlike",
  1395. payload: {
  1396. message: `Removed <youtubeId>${title} by ${artists.join(
  1397. ", "
  1398. )}</youtubeId> from your Liked Songs`,
  1399. youtubeId: newSong.youtubeId,
  1400. thumbnail
  1401. }
  1402. });
  1403. } else {
  1404. CacheModule.runJob("PUB", {
  1405. channel: "song.undislike",
  1406. value: JSON.stringify({
  1407. youtubeId: newSong.youtubeId,
  1408. userId: session.userId,
  1409. likes,
  1410. dislikes
  1411. })
  1412. });
  1413. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1414. userId: session.userId,
  1415. type: "song__undislike",
  1416. payload: {
  1417. message: `Removed <youtubeId>${title} by ${artists.join(
  1418. ", "
  1419. )}</youtubeId> from your Disliked Songs`,
  1420. youtubeId: newSong.youtubeId,
  1421. thumbnail
  1422. }
  1423. });
  1424. }
  1425. }
  1426. return next(null, playlist);
  1427. }
  1428. ],
  1429. async (err, playlist) => {
  1430. if (err) {
  1431. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1432. this.log(
  1433. "ERROR",
  1434. "PLAYLIST_REMOVE_SONG",
  1435. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1436. );
  1437. return cb({ status: "error", message: err });
  1438. }
  1439. this.log(
  1440. "SUCCESS",
  1441. "PLAYLIST_REMOVE_SONG",
  1442. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1443. );
  1444. CacheModule.runJob("PUB", {
  1445. channel: "playlist.removeSong",
  1446. value: {
  1447. playlistId: playlist._id,
  1448. youtubeId,
  1449. userId: session.userId,
  1450. privacy: playlist.privacy
  1451. }
  1452. });
  1453. return cb({
  1454. status: "success",
  1455. message: "Song has been successfully removed from playlist",
  1456. data: { songs: playlist.songs }
  1457. });
  1458. }
  1459. );
  1460. }),
  1461. /**
  1462. * Updates the displayName of a private playlist
  1463. *
  1464. * @param {object} session - the session object automatically added by the websocket
  1465. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1466. * @param {Function} cb - gets called with the result
  1467. */
  1468. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1469. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1470. async.waterfall(
  1471. [
  1472. next => {
  1473. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1474. .then(playlist => next(null, playlist))
  1475. .catch(next);
  1476. },
  1477. (playlist, next) => {
  1478. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1479. return next(null);
  1480. },
  1481. next => {
  1482. playlistModel.updateOne(
  1483. { _id: playlistId, createdBy: session.userId },
  1484. { $set: { displayName } },
  1485. { runValidators: true },
  1486. next
  1487. );
  1488. },
  1489. (res, next) => {
  1490. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1491. .then(playlist => next(null, playlist))
  1492. .catch(next);
  1493. }
  1494. ],
  1495. async (err, playlist) => {
  1496. if (err) {
  1497. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1498. this.log(
  1499. "ERROR",
  1500. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1501. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1502. );
  1503. return cb({ status: "error", message: err });
  1504. }
  1505. this.log(
  1506. "SUCCESS",
  1507. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1508. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1509. );
  1510. CacheModule.runJob("PUB", {
  1511. channel: "playlist.updateDisplayName",
  1512. value: {
  1513. playlistId,
  1514. displayName,
  1515. userId: session.userId,
  1516. privacy: playlist.privacy
  1517. }
  1518. });
  1519. CacheModule.runJob("PUB", {
  1520. channel: "playlist.updated",
  1521. value: { playlistId }
  1522. });
  1523. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1524. userId: session.userId,
  1525. type: "playlist__edit_display_name",
  1526. payload: {
  1527. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1528. playlistId
  1529. }
  1530. });
  1531. return cb({
  1532. status: "success",
  1533. message: "Playlist has been successfully updated"
  1534. });
  1535. }
  1536. );
  1537. }),
  1538. /**
  1539. * Removes a user's own modifiable user playlist
  1540. *
  1541. * @param {object} session - the session object automatically added by the websocket
  1542. * @param {string} playlistId - the id of the playlist we are removing
  1543. * @param {Function} cb - gets called with the result
  1544. */
  1545. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1546. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1547. async.waterfall(
  1548. [
  1549. next => {
  1550. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1551. .then(playlist => next(null, playlist))
  1552. .catch(next);
  1553. },
  1554. (playlist, next) => {
  1555. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1556. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1557. return next(null, playlist);
  1558. },
  1559. (playlist, next) => {
  1560. userModel.updateOne(
  1561. { _id: playlist.createdBy },
  1562. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1563. err => next(err, playlist)
  1564. );
  1565. },
  1566. (playlist, next) => {
  1567. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1568. .then(() => next(null, playlist))
  1569. .catch(next);
  1570. }
  1571. ],
  1572. async (err, playlist) => {
  1573. if (err) {
  1574. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1575. this.log(
  1576. "ERROR",
  1577. "PLAYLIST_REMOVE",
  1578. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1579. );
  1580. return cb({ status: "error", message: err });
  1581. }
  1582. this.log(
  1583. "SUCCESS",
  1584. "PLAYLIST_REMOVE",
  1585. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1586. );
  1587. CacheModule.runJob("PUB", {
  1588. channel: "playlist.delete",
  1589. value: {
  1590. userId: session.userId,
  1591. playlistId
  1592. }
  1593. });
  1594. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1595. userId: playlist.createdBy,
  1596. type: "playlist__remove",
  1597. payload: {
  1598. message: `Removed playlist ${playlist.displayName}`
  1599. }
  1600. });
  1601. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1602. return cb({
  1603. status: "success",
  1604. message: "Playlist successfully removed"
  1605. });
  1606. }
  1607. );
  1608. }),
  1609. /**
  1610. * Removes a user's modifiable user playlist as an admin
  1611. *
  1612. * @param {object} session - the session object automatically added by the websocket
  1613. * @param {string} playlistId - the id of the playlist we are removing
  1614. * @param {Function} cb - gets called with the result
  1615. */
  1616. removeAdmin: useHasPermission("playlists.removeAdmin", async function removeAdmin(session, playlistId, cb) {
  1617. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1618. async.waterfall(
  1619. [
  1620. next => {
  1621. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1622. .then(playlist => next(null, playlist))
  1623. .catch(next);
  1624. },
  1625. (playlist, next) => {
  1626. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1627. return next(null, playlist);
  1628. },
  1629. (playlist, next) => {
  1630. userModel.updateOne(
  1631. { _id: playlist.createdBy },
  1632. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1633. err => next(err, playlist, playlist.createdBy)
  1634. );
  1635. },
  1636. (playlist, playlistCreator, next) => {
  1637. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1638. .then(() => next(null, playlistCreator))
  1639. .catch(next);
  1640. }
  1641. ],
  1642. async (err, playlistCreator) => {
  1643. if (err) {
  1644. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1645. this.log(
  1646. "ERROR",
  1647. "PLAYLIST_REMOVE_ADMIN",
  1648. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1649. );
  1650. return cb({ status: "error", message: err });
  1651. }
  1652. this.log(
  1653. "SUCCESS",
  1654. "PLAYLIST_REMOVE_ADMIN",
  1655. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1656. );
  1657. CacheModule.runJob("PUB", {
  1658. channel: "playlist.delete",
  1659. value: {
  1660. userId: playlistCreator,
  1661. playlistId
  1662. }
  1663. });
  1664. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1665. return cb({
  1666. status: "success",
  1667. message: "Playlist successfully removed"
  1668. });
  1669. }
  1670. );
  1671. }),
  1672. /**
  1673. * Updates the privacy of a private playlist
  1674. *
  1675. * @param {object} session - the session object automatically added by the websocket
  1676. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1677. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1678. * @param {Function} cb - gets called with the result
  1679. */
  1680. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1681. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1682. async.waterfall(
  1683. [
  1684. next => {
  1685. playlistModel.updateOne(
  1686. { _id: playlistId, createdBy: session.userId },
  1687. { $set: { privacy } },
  1688. { runValidators: true },
  1689. next
  1690. );
  1691. },
  1692. (res, next) => {
  1693. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1694. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1695. else {
  1696. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1697. .then(playlist => next(null, playlist))
  1698. .catch(next);
  1699. }
  1700. }
  1701. ],
  1702. async (err, playlist) => {
  1703. if (err) {
  1704. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1705. this.log(
  1706. "ERROR",
  1707. "PLAYLIST_UPDATE_PRIVACY",
  1708. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1709. );
  1710. return cb({ status: "error", message: err });
  1711. }
  1712. this.log(
  1713. "SUCCESS",
  1714. "PLAYLIST_UPDATE_PRIVACY",
  1715. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1716. );
  1717. CacheModule.runJob("PUB", {
  1718. channel: "playlist.updatePrivacy",
  1719. value: {
  1720. userId: session.userId,
  1721. playlist
  1722. }
  1723. });
  1724. CacheModule.runJob("PUB", {
  1725. channel: "playlist.updated",
  1726. value: { playlistId }
  1727. });
  1728. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1729. userId: session.userId,
  1730. type: "playlist__edit_privacy",
  1731. payload: {
  1732. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1733. playlistId
  1734. }
  1735. });
  1736. return cb({
  1737. status: "success",
  1738. message: "Playlist has been successfully updated"
  1739. });
  1740. }
  1741. );
  1742. }),
  1743. /**
  1744. * Updates the privacy of a playlist
  1745. *
  1746. * @param {object} session - the session object automatically added by the websocket
  1747. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1748. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1749. * @param {Function} cb - gets called with the result
  1750. */
  1751. updatePrivacyAdmin: useHasPermission(
  1752. "playlists.update.privacy",
  1753. async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1754. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1755. async.waterfall(
  1756. [
  1757. next => {
  1758. playlistModel.updateOne(
  1759. { _id: playlistId },
  1760. { $set: { privacy } },
  1761. { runValidators: true },
  1762. next
  1763. );
  1764. },
  1765. (res, next) => {
  1766. if (res.n === 0) next("No playlist found with that id.");
  1767. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1768. else {
  1769. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1770. .then(playlist => next(null, playlist))
  1771. .catch(next);
  1772. }
  1773. }
  1774. ],
  1775. async (err, playlist) => {
  1776. if (err) {
  1777. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1778. this.log(
  1779. "ERROR",
  1780. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1781. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1782. );
  1783. return cb({ status: "error", message: err });
  1784. }
  1785. this.log(
  1786. "SUCCESS",
  1787. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1788. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1789. );
  1790. if (playlist.type === "user") {
  1791. CacheModule.runJob("PUB", {
  1792. channel: "playlist.updatePrivacy",
  1793. value: {
  1794. userId: playlist.createdBy,
  1795. playlist
  1796. }
  1797. });
  1798. }
  1799. CacheModule.runJob("PUB", {
  1800. channel: "playlist.updated",
  1801. value: { playlistId }
  1802. });
  1803. return cb({
  1804. status: "success",
  1805. message: "Playlist has been successfully updated"
  1806. });
  1807. }
  1808. );
  1809. }
  1810. ),
  1811. /**
  1812. * Deletes all orphaned station playlists
  1813. *
  1814. * @param {object} session - the session object automatically added by socket.io
  1815. * @param {Function} cb - gets called with the result
  1816. */
  1817. deleteOrphanedStationPlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  1818. this.keepLongJob();
  1819. this.publishProgress({
  1820. status: "started",
  1821. title: "Delete orphaned station playlists",
  1822. message: "Deleting orphaned station playlists.",
  1823. id: this.toString()
  1824. });
  1825. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1826. await CacheModule.runJob(
  1827. "PUB",
  1828. {
  1829. channel: "longJob.added",
  1830. value: { jobId: this.toString(), userId: session.userId }
  1831. },
  1832. this
  1833. );
  1834. async.waterfall(
  1835. [
  1836. next => {
  1837. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1838. .then(() => next())
  1839. .catch(next);
  1840. }
  1841. ],
  1842. async err => {
  1843. if (err) {
  1844. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1845. this.log(
  1846. "ERROR",
  1847. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1848. `Deleting orphaned station playlists failed. "${err}"`
  1849. );
  1850. this.publishProgress({
  1851. status: "error",
  1852. message: err
  1853. });
  1854. return cb({ status: "error", message: err });
  1855. }
  1856. this.log(
  1857. "SUCCESS",
  1858. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1859. "Deleting orphaned station playlists successful."
  1860. );
  1861. this.publishProgress({
  1862. status: "success",
  1863. message: "Successfully deleted orphaned station playlists."
  1864. });
  1865. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1866. }
  1867. );
  1868. }),
  1869. /**
  1870. * Deletes all orphaned genre playlists
  1871. *
  1872. * @param {object} session - the session object automatically added by socket.io
  1873. * @param {Function} cb - gets called with the result
  1874. */
  1875. deleteOrphanedGenrePlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  1876. this.keepLongJob();
  1877. this.publishProgress({
  1878. status: "started",
  1879. title: "Delete orphaned genre playlists",
  1880. message: "Deleting orphaned genre playlists.",
  1881. id: this.toString()
  1882. });
  1883. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1884. await CacheModule.runJob(
  1885. "PUB",
  1886. {
  1887. channel: "longJob.added",
  1888. value: { jobId: this.toString(), userId: session.userId }
  1889. },
  1890. this
  1891. );
  1892. async.waterfall(
  1893. [
  1894. next => {
  1895. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1896. .then(() => next())
  1897. .catch(next);
  1898. }
  1899. ],
  1900. async err => {
  1901. if (err) {
  1902. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1903. this.log(
  1904. "ERROR",
  1905. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1906. `Deleting orphaned genre playlists failed. "${err}"`
  1907. );
  1908. this.publishProgress({
  1909. status: "error",
  1910. message: err
  1911. });
  1912. return cb({ status: "error", message: err });
  1913. }
  1914. this.log(
  1915. "SUCCESS",
  1916. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1917. "Deleting orphaned genre playlists successful."
  1918. );
  1919. this.publishProgress({
  1920. status: "success",
  1921. message: "Successfully deleted orphaned genre playlists."
  1922. });
  1923. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1924. }
  1925. );
  1926. }),
  1927. /**
  1928. * Requests orpahned playlist songs
  1929. *
  1930. * @param {object} session - the session object automatically added by socket.io
  1931. * @param {Function} cb - gets called with the result
  1932. */
  1933. requestOrphanedPlaylistSongs: useHasPermission(
  1934. "playlists.requestOrphanedPlaylistSongs",
  1935. async function index(session, cb) {
  1936. this.keepLongJob();
  1937. this.publishProgress({
  1938. status: "started",
  1939. title: "Request orphaned playlist songs",
  1940. message: "Requesting orphaned playlist songs.",
  1941. id: this.toString()
  1942. });
  1943. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1944. await CacheModule.runJob(
  1945. "PUB",
  1946. {
  1947. channel: "longJob.added",
  1948. value: { jobId: this.toString(), userId: session.userId }
  1949. },
  1950. this
  1951. );
  1952. async.waterfall(
  1953. [
  1954. next => {
  1955. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1956. .then(() => next())
  1957. .catch(next);
  1958. }
  1959. ],
  1960. async err => {
  1961. if (err) {
  1962. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1963. this.log(
  1964. "ERROR",
  1965. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1966. `Requesting orphaned playlist songs failed. "${err}"`
  1967. );
  1968. this.publishProgress({
  1969. status: "error",
  1970. message: err
  1971. });
  1972. return cb({ status: "error", message: err });
  1973. }
  1974. this.log(
  1975. "SUCCESS",
  1976. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1977. "Requesting orphaned playlist songs was successful."
  1978. );
  1979. this.publishProgress({
  1980. status: "success",
  1981. message: "Successfully requested orphaned playlist songs."
  1982. });
  1983. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1984. }
  1985. );
  1986. }
  1987. ),
  1988. /**
  1989. * Clears and refills a station playlist
  1990. *
  1991. * @param {object} session - the session object automatically added by socket.io
  1992. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1993. * @param {Function} cb - gets called with the result
  1994. */
  1995. clearAndRefillStationPlaylist: useHasPermission(
  1996. "playlists.clearAndRefill",
  1997. async function index(session, playlistId, cb) {
  1998. async.waterfall(
  1999. [
  2000. next => {
  2001. if (!playlistId) next("Please specify a playlist id");
  2002. else {
  2003. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  2004. .then(() => {
  2005. next();
  2006. })
  2007. .catch(err => {
  2008. next(err);
  2009. });
  2010. }
  2011. }
  2012. ],
  2013. async err => {
  2014. if (err) {
  2015. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2016. this.log(
  2017. "ERROR",
  2018. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2019. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2020. );
  2021. return cb({ status: "error", message: err });
  2022. }
  2023. this.log(
  2024. "SUCCESS",
  2025. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2026. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2027. );
  2028. return cb({
  2029. status: "success",
  2030. message: "Playlist has been successfully cleared and refilled"
  2031. });
  2032. }
  2033. );
  2034. }
  2035. ),
  2036. /**
  2037. * Clears and refills a genre playlist
  2038. *
  2039. * @param {object} session - the session object automatically added by socket.io
  2040. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2041. * @param {Function} cb - gets called with the result
  2042. */
  2043. clearAndRefillGenrePlaylist: useHasPermission(
  2044. "playlists.clearAndRefill",
  2045. async function index(session, playlistId, cb) {
  2046. async.waterfall(
  2047. [
  2048. next => {
  2049. if (!playlistId) next("Please specify a playlist id");
  2050. else {
  2051. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2052. .then(() => {
  2053. next();
  2054. })
  2055. .catch(err => {
  2056. next(err);
  2057. });
  2058. }
  2059. }
  2060. ],
  2061. async err => {
  2062. if (err) {
  2063. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2064. this.log(
  2065. "ERROR",
  2066. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2067. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2068. );
  2069. return cb({ status: "error", message: err });
  2070. }
  2071. this.log(
  2072. "SUCCESS",
  2073. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2074. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2075. );
  2076. return cb({
  2077. status: "success",
  2078. message: "Playlist has been successfully cleared and refilled"
  2079. });
  2080. }
  2081. );
  2082. }
  2083. ),
  2084. /**
  2085. * Clears and refills all station playlists
  2086. *
  2087. * @param {object} session - the session object automatically added by socket.io
  2088. * @param {Function} cb - gets called with the result
  2089. */
  2090. clearAndRefillAllStationPlaylists: useHasPermission(
  2091. "playlists.clearAndRefillAll",
  2092. async function index(session, cb) {
  2093. this.keepLongJob();
  2094. this.publishProgress({
  2095. status: "started",
  2096. title: "Clear and refill all station playlists",
  2097. message: "Clearing and refilling all station playlists.",
  2098. id: this.toString()
  2099. });
  2100. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2101. await CacheModule.runJob(
  2102. "PUB",
  2103. {
  2104. channel: "longJob.added",
  2105. value: { jobId: this.toString(), userId: session.userId }
  2106. },
  2107. this
  2108. );
  2109. async.waterfall(
  2110. [
  2111. next => {
  2112. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2113. .then(response => {
  2114. next(null, response.playlists);
  2115. })
  2116. .catch(err => {
  2117. next(err);
  2118. });
  2119. },
  2120. (playlists, next) => {
  2121. async.eachLimit(
  2122. playlists,
  2123. 1,
  2124. (playlist, next) => {
  2125. this.publishProgress({
  2126. status: "update",
  2127. message: `Clearing and refilling "${playlist._id}"`
  2128. });
  2129. PlaylistsModule.runJob(
  2130. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2131. { playlistId: playlist._id },
  2132. this
  2133. )
  2134. .then(() => {
  2135. next();
  2136. })
  2137. .catch(err => {
  2138. next(err);
  2139. });
  2140. },
  2141. next
  2142. );
  2143. }
  2144. ],
  2145. async err => {
  2146. if (err) {
  2147. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2148. this.log(
  2149. "ERROR",
  2150. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2151. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2152. );
  2153. this.publishProgress({
  2154. status: "error",
  2155. message: err
  2156. });
  2157. return cb({ status: "error", message: err });
  2158. }
  2159. this.log(
  2160. "SUCCESS",
  2161. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2162. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2163. );
  2164. this.publishProgress({
  2165. status: "success",
  2166. message: "Playlists have been successfully cleared and refilled."
  2167. });
  2168. return cb({
  2169. status: "success",
  2170. message: "Playlists have been successfully cleared and refilled"
  2171. });
  2172. }
  2173. );
  2174. }
  2175. ),
  2176. /**
  2177. * Clears and refills all genre playlists
  2178. *
  2179. * @param {object} session - the session object automatically added by socket.io
  2180. * @param {Function} cb - gets called with the result
  2181. */
  2182. clearAndRefillAllGenrePlaylists: useHasPermission("playlists.clearAndRefillAll", async function index(session, cb) {
  2183. this.keepLongJob();
  2184. this.publishProgress({
  2185. status: "started",
  2186. title: "Clear and refill all genre playlists",
  2187. message: "Clearing and refilling all genre playlists.",
  2188. id: this.toString()
  2189. });
  2190. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2191. await CacheModule.runJob(
  2192. "PUB",
  2193. {
  2194. channel: "longJob.added",
  2195. value: { jobId: this.toString(), userId: session.userId }
  2196. },
  2197. this
  2198. );
  2199. async.waterfall(
  2200. [
  2201. next => {
  2202. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2203. .then(response => {
  2204. next(null, response.playlists);
  2205. })
  2206. .catch(err => {
  2207. next(err);
  2208. });
  2209. },
  2210. (playlists, next) => {
  2211. async.eachLimit(
  2212. playlists,
  2213. 1,
  2214. (playlist, next) => {
  2215. this.publishProgress({
  2216. status: "update",
  2217. message: `Clearing and refilling "${playlist._id}"`
  2218. });
  2219. PlaylistsModule.runJob(
  2220. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2221. { playlistId: playlist._id },
  2222. this
  2223. )
  2224. .then(() => {
  2225. next();
  2226. })
  2227. .catch(err => {
  2228. next(err);
  2229. });
  2230. },
  2231. next
  2232. );
  2233. }
  2234. ],
  2235. async err => {
  2236. if (err) {
  2237. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2238. this.log(
  2239. "ERROR",
  2240. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2241. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2242. );
  2243. this.publishProgress({
  2244. status: "error",
  2245. message: err
  2246. });
  2247. return cb({ status: "error", message: err });
  2248. }
  2249. this.log(
  2250. "SUCCESS",
  2251. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2252. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2253. );
  2254. this.publishProgress({
  2255. status: "success",
  2256. message: "Playlists have been successfully cleared and refilled."
  2257. });
  2258. return cb({
  2259. status: "success",
  2260. message: "Playlists have been successfully cleared and refilled"
  2261. });
  2262. }
  2263. );
  2264. }),
  2265. /**
  2266. * Create missing genre playlists
  2267. *
  2268. * @param {object} session - the session object automatically added by socket.io
  2269. * @param {Function} cb - gets called with the result
  2270. */
  2271. createMissingGenrePlaylists: useHasPermission("playlists.createMissing", async function index(session, cb) {
  2272. this.keepLongJob();
  2273. this.publishProgress({
  2274. status: "started",
  2275. title: "Create missing genre playlists",
  2276. message: "Creating missing genre playlists.",
  2277. id: this.toString()
  2278. });
  2279. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2280. await CacheModule.runJob(
  2281. "PUB",
  2282. {
  2283. channel: "longJob.added",
  2284. value: { jobId: this.toString(), userId: session.userId }
  2285. },
  2286. this
  2287. );
  2288. async.waterfall(
  2289. [
  2290. next => {
  2291. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2292. .then(() => {
  2293. next();
  2294. })
  2295. .catch(err => {
  2296. next(err);
  2297. });
  2298. }
  2299. ],
  2300. async err => {
  2301. if (err) {
  2302. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2303. this.log(
  2304. "ERROR",
  2305. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2306. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2307. );
  2308. this.publishProgress({
  2309. status: "error",
  2310. message: err
  2311. });
  2312. return cb({ status: "error", message: err });
  2313. }
  2314. this.log(
  2315. "SUCCESS",
  2316. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2317. `Successfully created missing genre playlists for user "${session.userId}".`
  2318. );
  2319. this.publishProgress({
  2320. status: "success",
  2321. message: "Missing genre playlists have been successfully created."
  2322. });
  2323. return cb({
  2324. status: "success",
  2325. message: "Missing genre playlists have been successfully created"
  2326. });
  2327. }
  2328. );
  2329. })
  2330. };