songs.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  1. import async from "async";
  2. import isLoginRequired from "../hooks/loginRequired";
  3. import { useHasPermission } from "../hooks/hasPermission";
  4. // eslint-disable-next-line
  5. import moduleManager from "../../index";
  6. const DBModule = moduleManager.modules.db;
  7. const UtilsModule = moduleManager.modules.utils;
  8. const WSModule = moduleManager.modules.ws;
  9. const CacheModule = moduleManager.modules.cache;
  10. const SongsModule = moduleManager.modules.songs;
  11. const PlaylistsModule = moduleManager.modules.playlists;
  12. const StationsModule = moduleManager.modules.stations;
  13. const YouTubeModule = moduleManager.modules.youtube;
  14. CacheModule.runJob("SUB", {
  15. channel: "song.updated",
  16. cb: async data => {
  17. const songModel = await DBModule.runJob("GET_MODEL", {
  18. modelName: "song"
  19. });
  20. songModel.findOne({ _id: data.songId }, (err, song) => {
  21. WSModule.runJob("EMIT_TO_ROOMS", {
  22. rooms: ["import-album", "admin.songs", `edit-song.${data.songId}`, "edit-songs"],
  23. args: ["event:admin.song.updated", { data: { song, oldStatus: data.oldStatus } }]
  24. });
  25. });
  26. }
  27. });
  28. CacheModule.runJob("SUB", {
  29. channel: "song.removed",
  30. cb: async data => {
  31. WSModule.runJob("EMIT_TO_ROOMS", {
  32. rooms: ["import-album", "admin.songs", `edit-song.${data.songId}`, "edit-songs"],
  33. args: ["event:admin.song.removed", { data }]
  34. });
  35. }
  36. });
  37. export default {
  38. /**
  39. * Returns the length of the songs list
  40. *
  41. * @param {object} session - the session object automatically added by the websocket
  42. * @param cb
  43. */
  44. length: useHasPermission("songs.get", async function length(session, cb) {
  45. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  46. async.waterfall(
  47. [
  48. next => {
  49. songModel.countDocuments({}, next);
  50. }
  51. ],
  52. async (err, count) => {
  53. if (err) {
  54. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  55. this.log("ERROR", "SONGS_LENGTH", `Failed to get length from songs. "${err}"`);
  56. return cb({ status: "error", message: err });
  57. }
  58. this.log("SUCCESS", "SONGS_LENGTH", `Got length from songs successfully.`);
  59. return cb({ status: "success", message: "Successfully got length of songs.", data: { length: count } });
  60. }
  61. );
  62. }),
  63. /**
  64. * Gets songs, used in the admin songs page by the AdvancedTable component
  65. *
  66. * @param {object} session - the session object automatically added by the websocket
  67. * @param page - the page
  68. * @param pageSize - the size per page
  69. * @param properties - the properties to return for each song
  70. * @param sort - the sort object
  71. * @param queries - the queries array
  72. * @param operator - the operator for queries
  73. * @param cb
  74. */
  75. getData: useHasPermission(
  76. "admin.view.songs",
  77. async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  78. async.waterfall(
  79. [
  80. next => {
  81. DBModule.runJob(
  82. "GET_DATA",
  83. {
  84. page,
  85. pageSize,
  86. properties,
  87. sort,
  88. queries,
  89. operator,
  90. modelName: "song",
  91. blacklistedProperties: [],
  92. specialProperties: {
  93. requestedBy: [
  94. {
  95. $addFields: {
  96. requestedByOID: {
  97. $convert: {
  98. input: "$requestedBy",
  99. to: "objectId",
  100. onError: "unknown",
  101. onNull: "unknown"
  102. }
  103. }
  104. }
  105. },
  106. {
  107. $lookup: {
  108. from: "users",
  109. localField: "requestedByOID",
  110. foreignField: "_id",
  111. as: "requestedByUser"
  112. }
  113. },
  114. {
  115. $addFields: {
  116. requestedByUsername: {
  117. $ifNull: ["$requestedByUser.username", "unknown"]
  118. }
  119. }
  120. },
  121. {
  122. $project: {
  123. requestedByOID: 0,
  124. requestedByUser: 0
  125. }
  126. }
  127. ],
  128. verifiedBy: [
  129. {
  130. $addFields: {
  131. verifiedByOID: {
  132. $convert: {
  133. input: "$verifiedBy",
  134. to: "objectId",
  135. onError: "unknown",
  136. onNull: "unknown"
  137. }
  138. }
  139. }
  140. },
  141. {
  142. $lookup: {
  143. from: "users",
  144. localField: "verifiedByOID",
  145. foreignField: "_id",
  146. as: "verifiedByUser"
  147. }
  148. },
  149. {
  150. $unwind: {
  151. path: "$verifiedByUser",
  152. preserveNullAndEmptyArrays: true
  153. }
  154. },
  155. {
  156. $addFields: {
  157. verifiedByUsername: {
  158. $ifNull: ["$verifiedByUser.username", "unknown"]
  159. }
  160. }
  161. },
  162. {
  163. $project: {
  164. verifiedByOID: 0,
  165. verifiedByUser: 0
  166. }
  167. }
  168. ]
  169. },
  170. specialQueries: {
  171. requestedBy: newQuery => ({
  172. $or: [newQuery, { requestedByUsername: newQuery.requestedBy }]
  173. }),
  174. verifiedBy: newQuery => ({
  175. $or: [newQuery, { verifiedByUsername: newQuery.verifiedBy }]
  176. })
  177. }
  178. },
  179. this
  180. )
  181. .then(response => {
  182. next(null, response);
  183. })
  184. .catch(err => {
  185. next(err);
  186. });
  187. }
  188. ],
  189. async (err, response) => {
  190. if (err) {
  191. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  192. this.log("ERROR", "SONGS_GET_DATA", `Failed to get data from songs. "${err}"`);
  193. return cb({ status: "error", message: err });
  194. }
  195. this.log("SUCCESS", "SONGS_GET_DATA", `Got data from songs successfully.`);
  196. return cb({ status: "success", message: "Successfully got data from songs.", data: response });
  197. }
  198. );
  199. }
  200. ),
  201. /**
  202. * Updates all songs
  203. *
  204. * @param {object} session - the session object automatically added by the websocket
  205. * @param cb
  206. */
  207. updateAll: useHasPermission("songs.updateAll", async function updateAll(session, cb) {
  208. this.keepLongJob();
  209. this.publishProgress({
  210. status: "started",
  211. title: "Update all songs",
  212. message: "Updating all songs.",
  213. id: this.toString()
  214. });
  215. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  216. await CacheModule.runJob(
  217. "PUB",
  218. {
  219. channel: "longJob.added",
  220. value: { jobId: this.toString(), userId: session.userId }
  221. },
  222. this
  223. );
  224. async.waterfall(
  225. [
  226. next => {
  227. SongsModule.runJob("UPDATE_ALL_SONGS", {}, this)
  228. .then(() => {
  229. next();
  230. })
  231. .catch(err => {
  232. next(err);
  233. });
  234. }
  235. ],
  236. async err => {
  237. if (err) {
  238. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  239. this.log("ERROR", "SONGS_UPDATE_ALL", `Failed to update all songs. "${err}"`);
  240. this.publishProgress({
  241. status: "error",
  242. message: err
  243. });
  244. return cb({ status: "error", message: err });
  245. }
  246. this.log("SUCCESS", "SONGS_UPDATE_ALL", `Updated all songs successfully.`);
  247. this.publishProgress({
  248. status: "success",
  249. message: "Successfully updated all songs."
  250. });
  251. return cb({ status: "success", message: "Successfully updated all songs." });
  252. }
  253. );
  254. }),
  255. /**
  256. * Gets a song from the Musare song id
  257. *
  258. * @param {object} session - the session object automatically added by the websocket
  259. * @param {string} songId - the song id
  260. * @param {Function} cb
  261. */
  262. getSongFromSongId: useHasPermission("songs.get", function getSongFromSongId(session, songId, cb) {
  263. async.waterfall(
  264. [
  265. next => {
  266. SongsModule.runJob("GET_SONG", { songId }, this)
  267. .then(response => next(null, response.song))
  268. .catch(err => next(err));
  269. }
  270. ],
  271. async (err, song) => {
  272. if (err) {
  273. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  274. this.log("ERROR", "SONGS_GET_SONG_FROM_MUSARE_ID", `Failed to get song ${songId}. "${err}"`);
  275. return cb({ status: "error", message: err });
  276. }
  277. this.log("SUCCESS", "SONGS_GET_SONG_FROM_MUSARE_ID", `Got song ${songId} successfully.`);
  278. return cb({ status: "success", data: { song } });
  279. }
  280. );
  281. }),
  282. /**
  283. * Gets multiple songs from the Musare song ids
  284. * At this time only used in bulk EditSong
  285. *
  286. * @param {object} session - the session object automatically added by the websocket
  287. * @param {Array} mediaSources - the song media sources
  288. * @param {Function} cb
  289. */
  290. getSongsFromMediaSources: useHasPermission(
  291. "songs.get",
  292. function getSongsFromMediaSources(session, mediaSources, cb) {
  293. async.waterfall(
  294. [
  295. next => {
  296. console.log(687889, mediaSources);
  297. SongsModule.runJob(
  298. "GET_SONGS",
  299. {
  300. mediaSources,
  301. properties: [
  302. "mediaSource",
  303. "title",
  304. "artists",
  305. "thumbnail",
  306. "duration",
  307. "verified",
  308. "_id",
  309. "youtubeVideoId"
  310. ]
  311. },
  312. this
  313. )
  314. .then(response => next(null, response.songs))
  315. .catch(err => next(err));
  316. }
  317. ],
  318. async (err, songs) => {
  319. if (err) {
  320. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  321. this.log("ERROR", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Failed to get songs. "${err}"`);
  322. return cb({ status: "error", message: err });
  323. }
  324. this.log("SUCCESS", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Got songs successfully.`);
  325. return cb({ status: "success", data: { songs } });
  326. }
  327. );
  328. }
  329. ),
  330. /**
  331. * Creates a song
  332. *
  333. * @param {object} session - the session object automatically added by the websocket
  334. * @param {object} newSong - the song object
  335. * @param {Function} cb
  336. */
  337. create: useHasPermission("songs.create", async function create(session, newSong, cb) {
  338. async.waterfall(
  339. [
  340. next => {
  341. SongsModule.runJob("CREATE_SONG", { song: newSong, userId: session.userId }, this)
  342. .then(song => next(null, song))
  343. .catch(next);
  344. }
  345. ],
  346. async (err, song) => {
  347. if (err) {
  348. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  349. this.log("ERROR", "SONGS_CREATE", `Failed to create song "${JSON.stringify(newSong)}". "${err}"`);
  350. return cb({ status: "error", message: err });
  351. }
  352. this.log("SUCCESS", "SONGS_CREATE", `Successfully created song "${song._id}".`);
  353. return cb({
  354. status: "success",
  355. message: "Song has been successfully created",
  356. data: { song }
  357. });
  358. }
  359. );
  360. }),
  361. /**
  362. * Updates a song
  363. *
  364. * @param {object} session - the session object automatically added by the websocket
  365. * @param {string} songId - the song id
  366. * @param {object} song - the updated song object
  367. * @param {Function} cb
  368. */
  369. update: useHasPermission("songs.update", async function update(session, songId, song, cb) {
  370. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  371. let existingSong = null;
  372. async.waterfall(
  373. [
  374. next => {
  375. songModel.findOne({ _id: songId }, next);
  376. },
  377. (_existingSong, next) => {
  378. existingSong = _existingSong;
  379. // Verify the song
  380. if (existingSong.verified === false && song.verified === true) {
  381. song.verifiedBy = session.userId;
  382. song.verifiedAt = Date.now();
  383. }
  384. // Unverify the song
  385. else if (existingSong.verified === true && song.verified === false) {
  386. song.verifiedBy = null;
  387. song.verifiedAt = null;
  388. }
  389. next();
  390. },
  391. next => {
  392. songModel.updateOne({ _id: songId }, song, { runValidators: true }, next);
  393. },
  394. (res, next) => {
  395. SongsModule.runJob("UPDATE_SONG", { songId }, this)
  396. .then(song => {
  397. existingSong.genres
  398. .concat(song.genres)
  399. .filter((value, index, self) => self.indexOf(value) === index)
  400. .forEach(genre => {
  401. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", {
  402. genre,
  403. createPlaylist: song.verified
  404. })
  405. .then(() => {})
  406. .catch(() => {});
  407. });
  408. next(null, song);
  409. })
  410. .catch(next);
  411. }
  412. ],
  413. async (err, song) => {
  414. if (err) {
  415. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  416. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  417. return cb({ status: "error", message: err });
  418. }
  419. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  420. return cb({
  421. status: "success",
  422. message: "Song has been successfully updated",
  423. data: { song }
  424. });
  425. }
  426. );
  427. }),
  428. /**
  429. * Removes a song
  430. *
  431. * @param session
  432. * @param songId - the song id
  433. * @param cb
  434. */
  435. remove: useHasPermission("songs.remove", async function remove(session, songId, cb) {
  436. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  437. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  438. async.waterfall(
  439. [
  440. next => {
  441. songModel.findOne({ _id: songId }, next);
  442. },
  443. (song, next) => {
  444. // TODO replace for spotify support
  445. YouTubeModule.runJob(
  446. "GET_VIDEO",
  447. { identifier: song.mediaSource.split(":")[1], createMissing: true },
  448. this
  449. )
  450. .then(res => next(null, song, res.video))
  451. .catch(() => next(null, song, false));
  452. },
  453. (song, youtubeVideo, next) => {
  454. PlaylistsModule.runJob("GET_PLAYLISTS_WITH_SONG", { songId }, this)
  455. .then(res =>
  456. next(
  457. null,
  458. song,
  459. youtubeVideo,
  460. res.playlists.map(playlist => playlist._id)
  461. )
  462. )
  463. .catch(next);
  464. },
  465. (song, youtubeVideo, playlistIds, next) => {
  466. if (!youtubeVideo) return next(null, song, youtubeVideo, playlistIds);
  467. return PlaylistsModule.playlistModel.updateMany(
  468. { "songs._id": songId },
  469. {
  470. $set: {
  471. "songs.$._id": null,
  472. "songs.$.title": youtubeVideo.title,
  473. "songs.$.artists": [youtubeVideo.author],
  474. "songs.$.duration": youtubeVideo.duration,
  475. "songs.$.skipDuration": 0,
  476. "songs.$.thumbnail": youtubeVideo.thumbnail,
  477. "songs.$.verified": false
  478. }
  479. },
  480. err => {
  481. if (err) next(err);
  482. next(null, song, youtubeVideo, playlistIds);
  483. }
  484. );
  485. },
  486. (song, youtubeVideo, playlistIds, next) => {
  487. async.eachLimit(
  488. playlistIds,
  489. 1,
  490. (playlistId, next) => {
  491. async.waterfall(
  492. [
  493. next => {
  494. if (youtubeVideo) next();
  495. else
  496. WSModule.runJob(
  497. "RUN_ACTION2",
  498. {
  499. session,
  500. namespace: "playlists",
  501. action: "removeSongFromPlaylist",
  502. args: [song.mediaSource, playlistId]
  503. },
  504. this
  505. )
  506. .then(res => {
  507. if (res.status === "error") next(res.message);
  508. else next();
  509. })
  510. .catch(err => {
  511. next(err);
  512. });
  513. },
  514. next => {
  515. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  516. .then(() => next())
  517. .catch(next);
  518. }
  519. ],
  520. next
  521. );
  522. },
  523. err => {
  524. if (err) next(err);
  525. else next(null, song, youtubeVideo);
  526. }
  527. );
  528. },
  529. (song, youtubeVideo, next) => {
  530. stationModel.find({ "queue._id": songId }, (err, stations) => {
  531. if (err) next(err);
  532. next(
  533. null,
  534. song,
  535. youtubeVideo,
  536. stations.map(station => station._id)
  537. );
  538. });
  539. },
  540. (song, youtubeVideo, stationIds, next) => {
  541. stationModel.find({ "currentSong._id": songId }, (err, stations) => {
  542. if (err) next(err);
  543. next(null, song, youtubeVideo, {
  544. queue: stationIds,
  545. current: stations.map(station => station._id)
  546. });
  547. });
  548. },
  549. (song, youtubeVideo, stationIds, next) => {
  550. if (!youtubeVideo) return next(null, song, youtubeVideo, stationIds);
  551. return stationModel.updateMany(
  552. { "queue._id": songId },
  553. {
  554. $set: {
  555. "queue.$._id": null,
  556. "queue.$.title": youtubeVideo.title,
  557. "queue.$.artists": [youtubeVideo.author],
  558. "queue.$.duration": youtubeVideo.duration,
  559. "queue.$.skipDuration": 0,
  560. "queue.$.thumbnail": youtubeVideo.thumbnail,
  561. "queue.$.verified": false
  562. }
  563. },
  564. err => {
  565. if (err) next(err);
  566. next(null, song, youtubeVideo, stationIds);
  567. }
  568. );
  569. },
  570. (song, youtubeVideo, stationIds, next) => {
  571. if (!youtubeVideo) return next(null, song, youtubeVideo, stationIds);
  572. return stationModel.updateMany(
  573. { "currentSong._id": songId },
  574. {
  575. $set: {
  576. "currentSong._id": null,
  577. "currentSong.title": youtubeVideo.title,
  578. "currentSong.artists": [youtubeVideo.author],
  579. // "currentSong.duration": youtubeVideo.duration,
  580. // "currentSong.skipDuration": 0,
  581. "currentSong.thumbnail": youtubeVideo.thumbnail,
  582. "currentSong.verified": false
  583. }
  584. },
  585. err => {
  586. if (err) next(err);
  587. next(null, song, youtubeVideo, stationIds);
  588. }
  589. );
  590. },
  591. (song, youtubeVideo, stationIds, next) => {
  592. async.eachLimit(
  593. stationIds.queue,
  594. 1,
  595. (stationId, next) => {
  596. if (!youtubeVideo)
  597. StationsModule.runJob(
  598. "REMOVE_FROM_QUEUE",
  599. { stationId, mediaSource: song.mediaSource },
  600. this
  601. )
  602. .then(() => next())
  603. .catch(err => {
  604. if (
  605. err === "Station not found" ||
  606. err === "Song is not currently in the queue."
  607. )
  608. next();
  609. else next(err);
  610. });
  611. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  612. .then(() => next())
  613. .catch(next);
  614. },
  615. err => {
  616. if (err) next(err);
  617. else next(null, youtubeVideo, stationIds);
  618. }
  619. );
  620. },
  621. (youtubeVideo, stationIds, next) => {
  622. async.eachLimit(
  623. stationIds.current,
  624. 1,
  625. (stationId, next) => {
  626. if (!youtubeVideo)
  627. StationsModule.runJob(
  628. "SKIP_STATION",
  629. { stationId, natural: false, skipReason: "other" },
  630. this
  631. )
  632. .then(() => {
  633. next();
  634. })
  635. .catch(err => {
  636. if (err.message === "Station not found.") next();
  637. else next(err);
  638. });
  639. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  640. .then(() => next())
  641. .catch(next);
  642. },
  643. err => {
  644. if (err) next(err);
  645. else next();
  646. }
  647. );
  648. },
  649. next => {
  650. songModel.deleteOne({ _id: songId }, err => {
  651. if (err) next(err);
  652. else next();
  653. });
  654. },
  655. next => {
  656. CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  657. .then(() => {
  658. next();
  659. })
  660. .catch(next);
  661. }
  662. ],
  663. async err => {
  664. if (err) {
  665. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  666. this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  667. return cb({ status: "error", message: err });
  668. }
  669. this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  670. CacheModule.runJob("PUB", {
  671. channel: "song.removed",
  672. value: { songId }
  673. });
  674. return cb({
  675. status: "success",
  676. message: "Song has been successfully removed"
  677. });
  678. }
  679. );
  680. }),
  681. /**
  682. * Removes many songs
  683. *
  684. * @param session
  685. * @param songIds - array of song ids
  686. * @param cb
  687. */
  688. removeMany: useHasPermission("songs.remove", async function remove(session, songIds, cb) {
  689. const successful = [];
  690. const failed = [];
  691. this.keepLongJob();
  692. this.publishProgress({
  693. status: "started",
  694. title: "Bulk remove songs",
  695. message: "Removing songs.",
  696. id: this.toString()
  697. });
  698. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  699. await CacheModule.runJob(
  700. "PUB",
  701. {
  702. channel: "longJob.added",
  703. value: { jobId: this.toString(), userId: session.userId }
  704. },
  705. this
  706. );
  707. async.waterfall(
  708. [
  709. next => {
  710. async.eachLimit(
  711. songIds,
  712. 1,
  713. (songId, next) => {
  714. this.publishProgress({ status: "update", message: `Removing song "${songId}"` });
  715. WSModule.runJob(
  716. "RUN_ACTION2",
  717. {
  718. session,
  719. namespace: "songs",
  720. action: "remove",
  721. args: [songId]
  722. },
  723. this
  724. )
  725. .then(res => {
  726. if (res.status === "error") failed.push(songId);
  727. else successful.push(songId);
  728. next();
  729. })
  730. .catch(err => {
  731. next(err);
  732. });
  733. },
  734. err => {
  735. if (err) next(err);
  736. else next();
  737. }
  738. );
  739. }
  740. ],
  741. async err => {
  742. if (err) {
  743. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  744. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  745. this.publishProgress({
  746. status: "error",
  747. message: err
  748. });
  749. return cb({ status: "error", message: err });
  750. }
  751. let message = "";
  752. if (successful.length === 1) message += `1 song has been successfully removed`;
  753. else message += `${successful.length} songs have been successfully removed`;
  754. if (failed.length > 0) {
  755. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  756. if (failed.length === 1) message += `, failed to remove 1 song`;
  757. else message += `, failed to remove ${failed.length} songs`;
  758. }
  759. this.log("SUCCESS", "SONGS_REMOVE_MANY", `${message} "${successful.join(", ")}"`);
  760. this.publishProgress({
  761. status: "success",
  762. message
  763. });
  764. return cb({
  765. status: "success",
  766. message
  767. });
  768. }
  769. );
  770. }),
  771. /**
  772. * Searches through official songs
  773. *
  774. * @param {object} session - the session object automatically added by the websocket
  775. * @param {string} query - the query
  776. * @param {string} page - the page
  777. * @param {Function} cb - gets called with the result
  778. */
  779. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  780. async.waterfall(
  781. [
  782. next => {
  783. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  784. else next();
  785. },
  786. next => {
  787. SongsModule.runJob("SEARCH", {
  788. query,
  789. includeVerified: true,
  790. trimmed: true,
  791. page
  792. })
  793. .then(response => {
  794. next(null, response);
  795. })
  796. .catch(err => {
  797. next(err);
  798. });
  799. }
  800. ],
  801. async (err, data) => {
  802. if (err) {
  803. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  804. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  805. return cb({ status: "error", message: err });
  806. }
  807. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  808. return cb({ status: "success", data });
  809. }
  810. );
  811. }),
  812. /**
  813. * Verifies a song
  814. *
  815. * @param session
  816. * @param songId - the song id
  817. * @param cb
  818. */
  819. verify: useHasPermission("songs.verify", async function add(session, songId, cb) {
  820. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  821. async.waterfall(
  822. [
  823. next => {
  824. SongModel.findOne({ _id: songId }, next);
  825. },
  826. (song, next) => {
  827. if (!song) return next("This song is not in the database.");
  828. return next(null, song);
  829. },
  830. (song, next) => {
  831. const oldStatus = false;
  832. song.verifiedBy = session.userId;
  833. song.verifiedAt = Date.now();
  834. song.verified = true;
  835. song.save(err => next(err, song, oldStatus));
  836. },
  837. (song, oldStatus, next) => {
  838. song.genres.forEach(genre => {
  839. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true })
  840. .then(() => {})
  841. .catch(() => {});
  842. });
  843. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  844. next(null, song, oldStatus);
  845. }
  846. ],
  847. async err => {
  848. if (err) {
  849. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  850. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  851. return cb({ status: "error", message: err });
  852. }
  853. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  854. return cb({
  855. status: "success",
  856. message: "Song has been verified successfully."
  857. });
  858. }
  859. );
  860. // TODO Check if video is in queue and Add the song to the appropriate stations
  861. }),
  862. /**
  863. * Verify many songs
  864. *
  865. * @param session
  866. * @param songIds - array of song ids
  867. * @param cb
  868. */
  869. verifyMany: useHasPermission("songs.verify", async function verifyMany(session, songIds, cb) {
  870. const successful = [];
  871. const failed = [];
  872. this.keepLongJob();
  873. this.publishProgress({
  874. status: "started",
  875. title: "Bulk verifying songs",
  876. message: "Verifying songs.",
  877. id: this.toString()
  878. });
  879. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  880. await CacheModule.runJob(
  881. "PUB",
  882. {
  883. channel: "longJob.added",
  884. value: { jobId: this.toString(), userId: session.userId }
  885. },
  886. this
  887. );
  888. async.waterfall(
  889. [
  890. next => {
  891. async.eachLimit(
  892. songIds,
  893. 1,
  894. (songId, next) => {
  895. this.publishProgress({ status: "update", message: `Verifying song "${songId}"` });
  896. WSModule.runJob(
  897. "RUN_ACTION2",
  898. {
  899. session,
  900. namespace: "songs",
  901. action: "verify",
  902. args: [songId]
  903. },
  904. this
  905. )
  906. .then(res => {
  907. if (res.status === "error") failed.push(songId);
  908. else successful.push(songId);
  909. next();
  910. })
  911. .catch(err => {
  912. next(err);
  913. });
  914. },
  915. err => {
  916. if (err) next(err);
  917. else next();
  918. }
  919. );
  920. }
  921. ],
  922. async err => {
  923. if (err) {
  924. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  925. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  926. this.publishProgress({
  927. status: "error",
  928. message: err
  929. });
  930. return cb({ status: "error", message: err });
  931. }
  932. let message = "";
  933. if (successful.length === 1) message += `1 song has been successfully verified`;
  934. else message += `${successful.length} songs have been successfully verified`;
  935. if (failed.length > 0) {
  936. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  937. if (failed.length === 1) message += `, failed to verify 1 song`;
  938. else message += `, failed to verify ${failed.length} songs`;
  939. }
  940. this.log("SUCCESS", "SONGS_VERIFY_MANY", `${message} "${successful.join(", ")}"`);
  941. this.publishProgress({
  942. status: "success",
  943. message
  944. });
  945. return cb({
  946. status: "success",
  947. message
  948. });
  949. }
  950. );
  951. }),
  952. /**
  953. * Un-verifies a song
  954. *
  955. * @param session
  956. * @param songId - the song id
  957. * @param cb
  958. */
  959. unverify: useHasPermission("songs.verify", async function add(session, songId, cb) {
  960. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  961. async.waterfall(
  962. [
  963. next => {
  964. SongModel.findOne({ _id: songId }, next);
  965. },
  966. (song, next) => {
  967. if (!song) return next("This song is not in the database.");
  968. return next(null, song);
  969. },
  970. (song, next) => {
  971. song.verified = false;
  972. song.verifiedBy = null;
  973. song.verifiedAt = null;
  974. song.save(err => {
  975. next(err, song);
  976. });
  977. },
  978. (song, next) => {
  979. song.genres.forEach(genre => {
  980. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: false })
  981. .then(() => {})
  982. .catch(() => {});
  983. });
  984. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  985. next(null);
  986. }
  987. ],
  988. async err => {
  989. if (err) {
  990. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  991. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  992. return cb({ status: "error", message: err });
  993. }
  994. this.log(
  995. "SUCCESS",
  996. "SONGS_UNVERIFY",
  997. `User "${session.userId}" successfully unverified song "${songId}".`
  998. );
  999. return cb({
  1000. status: "success",
  1001. message: "Song has been unverified successfully."
  1002. });
  1003. }
  1004. );
  1005. // TODO Check if video is in queue and Add the song to the appropriate stations
  1006. }),
  1007. /**
  1008. * Unverify many songs
  1009. *
  1010. * @param session
  1011. * @param songIds - array of song ids
  1012. * @param cb
  1013. */
  1014. unverifyMany: useHasPermission("songs.verify", async function unverifyMany(session, songIds, cb) {
  1015. const successful = [];
  1016. const failed = [];
  1017. this.keepLongJob();
  1018. this.publishProgress({
  1019. status: "started",
  1020. title: "Bulk unverifying songs",
  1021. message: "Unverifying songs.",
  1022. id: this.toString()
  1023. });
  1024. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1025. await CacheModule.runJob(
  1026. "PUB",
  1027. {
  1028. channel: "longJob.added",
  1029. value: { jobId: this.toString(), userId: session.userId }
  1030. },
  1031. this
  1032. );
  1033. async.waterfall(
  1034. [
  1035. next => {
  1036. async.eachLimit(
  1037. songIds,
  1038. 1,
  1039. (songId, next) => {
  1040. this.publishProgress({ status: "update", message: `Unverifying song "${songId}"` });
  1041. WSModule.runJob(
  1042. "RUN_ACTION2",
  1043. {
  1044. session,
  1045. namespace: "songs",
  1046. action: "unverify",
  1047. args: [songId]
  1048. },
  1049. this
  1050. )
  1051. .then(res => {
  1052. if (res.status === "error") failed.push(songId);
  1053. else successful.push(songId);
  1054. next();
  1055. })
  1056. .catch(err => {
  1057. next(err);
  1058. });
  1059. },
  1060. err => {
  1061. if (err) next(err);
  1062. else next();
  1063. }
  1064. );
  1065. }
  1066. ],
  1067. async err => {
  1068. if (err) {
  1069. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1070. this.log(
  1071. "ERROR",
  1072. "SONGS_UNVERIFY_MANY",
  1073. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1074. );
  1075. this.publishProgress({
  1076. status: "error",
  1077. message: err
  1078. });
  1079. return cb({ status: "error", message: err });
  1080. }
  1081. let message = "";
  1082. if (successful.length === 1) message += `1 song has been successfully unverified`;
  1083. else message += `${successful.length} songs have been successfully unverified`;
  1084. if (failed.length > 0) {
  1085. this.log(
  1086. "ERROR",
  1087. "SONGS_UNVERIFY_MANY",
  1088. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1089. );
  1090. if (failed.length === 1) message += `, failed to unverify 1 song`;
  1091. else message += `, failed to unverify ${failed.length} songs`;
  1092. }
  1093. this.log("SUCCESS", "SONGS_UNVERIFY_MANY", `${message} "${successful.join(", ")}"`);
  1094. this.publishProgress({
  1095. status: "success",
  1096. message
  1097. });
  1098. return cb({
  1099. status: "success",
  1100. message
  1101. });
  1102. }
  1103. );
  1104. }),
  1105. /**
  1106. * Gets a list of all genres
  1107. *
  1108. * @param session
  1109. * @param cb
  1110. */
  1111. getGenres: useHasPermission("songs.get", function getGenres(session, cb) {
  1112. async.waterfall(
  1113. [
  1114. next => {
  1115. SongsModule.runJob("GET_GENRES", this)
  1116. .then(res => {
  1117. next(null, res.genres);
  1118. })
  1119. .catch(next);
  1120. }
  1121. ],
  1122. async (err, genres) => {
  1123. if (err && err !== true) {
  1124. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1125. this.log("ERROR", "GET_GENRES", `User ${session.userId} failed to get genres. '${err}'`);
  1126. cb({ status: "error", message: err });
  1127. } else {
  1128. this.log("SUCCESS", "GET_GENRES", `User ${session.userId} has successfully got the genres.`);
  1129. cb({
  1130. status: "success",
  1131. message: "Successfully got genres.",
  1132. data: {
  1133. items: genres
  1134. }
  1135. });
  1136. }
  1137. }
  1138. );
  1139. }),
  1140. /**
  1141. * Bulk update genres for selected songs
  1142. *
  1143. * @param session
  1144. * @param method Whether to add, remove or replace genres
  1145. * @param genres Array of genres to apply
  1146. * @param songIds Array of songIds to apply genres to
  1147. * @param cb
  1148. */
  1149. editGenres: useHasPermission("songs.update", async function editGenres(session, method, genres, songIds, cb) {
  1150. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1151. this.keepLongJob();
  1152. this.publishProgress({
  1153. status: "started",
  1154. title: "Bulk editing genres",
  1155. message: "Updating genres.",
  1156. id: this.toString()
  1157. });
  1158. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1159. await CacheModule.runJob(
  1160. "PUB",
  1161. {
  1162. channel: "longJob.added",
  1163. value: { jobId: this.toString(), userId: session.userId }
  1164. },
  1165. this
  1166. );
  1167. async.waterfall(
  1168. [
  1169. next => {
  1170. songModel.find({ _id: { $in: songIds } }, next);
  1171. },
  1172. (songs, next) => {
  1173. const songsFound = songs.map(song => song._id);
  1174. if (songsFound.length > 0) next(null, songsFound);
  1175. else next("None of the specified songs were found.");
  1176. },
  1177. (songsFound, next) => {
  1178. const query = {};
  1179. if (method === "add") {
  1180. query.$addToSet = { genres: { $each: genres } };
  1181. } else if (method === "remove") {
  1182. query.$pullAll = { genres };
  1183. } else if (method === "replace") {
  1184. query.$set = { genres };
  1185. } else {
  1186. next("Invalid method.");
  1187. return;
  1188. }
  1189. this.publishProgress({
  1190. status: "update",
  1191. message: "Updating genres in MongoDB."
  1192. });
  1193. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1194. if (err) {
  1195. next(err);
  1196. return;
  1197. }
  1198. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound }, this)
  1199. .then(() => {
  1200. next();
  1201. })
  1202. .catch(err => {
  1203. next(err);
  1204. });
  1205. });
  1206. }
  1207. ],
  1208. async err => {
  1209. if (err && err !== true) {
  1210. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1211. this.log("ERROR", "EDIT_GENRES", `User ${session.userId} failed to edit genres. '${err}'`);
  1212. this.publishProgress({
  1213. status: "error",
  1214. message: err
  1215. });
  1216. cb({ status: "error", message: err });
  1217. } else {
  1218. this.log("SUCCESS", "EDIT_GENRES", `User ${session.userId} has successfully edited genres.`);
  1219. this.publishProgress({
  1220. status: "success",
  1221. message: "Successfully edited genres."
  1222. });
  1223. cb({
  1224. status: "success",
  1225. message: "Successfully edited genres."
  1226. });
  1227. }
  1228. }
  1229. );
  1230. }),
  1231. /**
  1232. * Gets a list of all artists
  1233. *
  1234. * @param session
  1235. * @param cb
  1236. */
  1237. getArtists: useHasPermission("songs.get", function getArtists(session, cb) {
  1238. async.waterfall(
  1239. [
  1240. next => {
  1241. SongsModule.runJob("GET_ARTISTS", this)
  1242. .then(res => {
  1243. next(null, res.artists);
  1244. })
  1245. .catch(next);
  1246. }
  1247. ],
  1248. async (err, artists) => {
  1249. if (err && err !== true) {
  1250. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1251. this.log("ERROR", "GET_ARTISTS", `User ${session.userId} failed to get artists. '${err}'`);
  1252. cb({ status: "error", message: err });
  1253. } else {
  1254. this.log("SUCCESS", "GET_ARTISTS", `User ${session.userId} has successfully got the artists.`);
  1255. cb({
  1256. status: "success",
  1257. message: "Successfully got artists.",
  1258. data: {
  1259. items: artists
  1260. }
  1261. });
  1262. }
  1263. }
  1264. );
  1265. }),
  1266. /**
  1267. * Bulk update artists for selected songs
  1268. *
  1269. * @param session
  1270. * @param method Whether to add, remove or replace artists
  1271. * @param artists Array of artists to apply
  1272. * @param songIds Array of songIds to apply artists to
  1273. * @param cb
  1274. */
  1275. editArtists: useHasPermission("songs.update", async function editArtists(session, method, artists, songIds, cb) {
  1276. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1277. this.keepLongJob();
  1278. this.publishProgress({
  1279. status: "started",
  1280. title: "Bulk editing artists",
  1281. message: "Updating artists.",
  1282. id: this.toString()
  1283. });
  1284. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1285. await CacheModule.runJob(
  1286. "PUB",
  1287. {
  1288. channel: "longJob.added",
  1289. value: { jobId: this.toString(), userId: session.userId }
  1290. },
  1291. this
  1292. );
  1293. async.waterfall(
  1294. [
  1295. next => {
  1296. songModel.find({ _id: { $in: songIds } }, next);
  1297. },
  1298. (songs, next) => {
  1299. const songsFound = songs.map(song => song._id);
  1300. if (songsFound.length > 0) next(null, songsFound);
  1301. else next("None of the specified songs were found.");
  1302. },
  1303. (songsFound, next) => {
  1304. const query = {};
  1305. if (method === "add") {
  1306. query.$addToSet = { artists: { $each: artists } };
  1307. } else if (method === "remove") {
  1308. query.$pullAll = { artists };
  1309. } else if (method === "replace") {
  1310. query.$set = { artists };
  1311. } else {
  1312. next("Invalid method.");
  1313. return;
  1314. }
  1315. this.publishProgress({
  1316. status: "update",
  1317. message: "Updating artists in MongoDB."
  1318. });
  1319. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1320. if (err) {
  1321. next(err);
  1322. return;
  1323. }
  1324. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound })
  1325. .then(() => {
  1326. next();
  1327. })
  1328. .catch(err => {
  1329. next(err);
  1330. });
  1331. });
  1332. }
  1333. ],
  1334. async err => {
  1335. if (err && err !== true) {
  1336. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1337. this.log("ERROR", "EDIT_ARTISTS", `User ${session.userId} failed to edit artists. '${err}'`);
  1338. this.publishProgress({
  1339. status: "error",
  1340. message: err
  1341. });
  1342. cb({ status: "error", message: err });
  1343. } else {
  1344. this.log("SUCCESS", "EDIT_ARTISTS", `User ${session.userId} has successfully edited artists.`);
  1345. this.publishProgress({
  1346. status: "success",
  1347. message: "Successfully edited artists."
  1348. });
  1349. cb({
  1350. status: "success",
  1351. message: "Successfully edited artists."
  1352. });
  1353. }
  1354. }
  1355. );
  1356. }),
  1357. /**
  1358. * Gets a list of all tags
  1359. *
  1360. * @param session
  1361. * @param cb
  1362. */
  1363. getTags: useHasPermission("songs.get", function getTags(session, cb) {
  1364. async.waterfall(
  1365. [
  1366. next => {
  1367. SongsModule.runJob("GET_TAGS", this)
  1368. .then(res => {
  1369. next(null, res.tags);
  1370. })
  1371. .catch(next);
  1372. }
  1373. ],
  1374. async (err, tags) => {
  1375. if (err && err !== true) {
  1376. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1377. this.log("ERROR", "GET_TAGS", `User ${session.userId} failed to get tags. '${err}'`);
  1378. cb({ status: "error", message: err });
  1379. } else {
  1380. this.log("SUCCESS", "GET_TAGS", `User ${session.userId} has successfully got the tags.`);
  1381. cb({
  1382. status: "success",
  1383. message: "Successfully got tags.",
  1384. data: {
  1385. items: tags
  1386. }
  1387. });
  1388. }
  1389. }
  1390. );
  1391. }),
  1392. /**
  1393. * Bulk update tags for selected songs
  1394. *
  1395. * @param session
  1396. * @param method Whether to add, remove or replace tags
  1397. * @param tags Array of tags to apply
  1398. * @param songIds Array of songIds to apply tags to
  1399. * @param cb
  1400. */
  1401. editTags: useHasPermission("songs.update", async function editTags(session, method, tags, songIds, cb) {
  1402. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1403. this.keepLongJob();
  1404. this.publishProgress({
  1405. status: "started",
  1406. title: "Bulk editing tags",
  1407. message: "Updating tags.",
  1408. id: this.toString()
  1409. });
  1410. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1411. await CacheModule.runJob(
  1412. "PUB",
  1413. {
  1414. channel: "longJob.added",
  1415. value: { jobId: this.toString(), userId: session.userId }
  1416. },
  1417. this
  1418. );
  1419. async.waterfall(
  1420. [
  1421. next => {
  1422. songModel.find({ _id: { $in: songIds } }, next);
  1423. },
  1424. (songs, next) => {
  1425. const songsFound = songs.map(song => song._id);
  1426. if (songsFound.length > 0) next(null, songsFound);
  1427. else next("None of the specified songs were found.");
  1428. },
  1429. (songsFound, next) => {
  1430. const query = {};
  1431. if (method === "add") {
  1432. query.$addToSet = { tags: { $each: tags } };
  1433. } else if (method === "remove") {
  1434. query.$pullAll = { tags };
  1435. } else if (method === "replace") {
  1436. query.$set = { tags };
  1437. } else {
  1438. next("Invalid method.");
  1439. return;
  1440. }
  1441. this.publishProgress({
  1442. status: "update",
  1443. message: "Updating tags in MongoDB."
  1444. });
  1445. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1446. if (err) {
  1447. next(err);
  1448. return;
  1449. }
  1450. SongsModule.runJob(
  1451. "UPDATE_SONGS",
  1452. {
  1453. songIds: songsFound
  1454. },
  1455. this
  1456. )
  1457. .then(() => {
  1458. next();
  1459. })
  1460. .catch(() => {
  1461. next();
  1462. });
  1463. });
  1464. }
  1465. ],
  1466. async err => {
  1467. if (err && err !== true) {
  1468. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1469. this.log("ERROR", "EDIT_TAGS", `User ${session.userId} failed to edit tags. '${err}'`);
  1470. this.publishProgress({
  1471. status: "error",
  1472. message: err
  1473. });
  1474. cb({ status: "error", message: err });
  1475. } else {
  1476. this.log("SUCCESS", "EDIT_TAGS", `User ${session.userId} has successfully edited tags.`);
  1477. this.publishProgress({
  1478. status: "success",
  1479. message: "Successfully edited tags."
  1480. });
  1481. cb({
  1482. status: "success",
  1483. message: "Successfully edited tags."
  1484. });
  1485. }
  1486. }
  1487. );
  1488. })
  1489. };