songs.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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.length", 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. "songs.getData",
  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.getSongFromId", 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 EditSongs
  285. *
  286. * @param {object} session - the session object automatically added by the websocket
  287. * @param {Array} youtubeIds - the song ids
  288. * @param {Function} cb
  289. */
  290. getSongsFromYoutubeIds: useHasPermission(
  291. "songs.getSongsFromYoutubeIds",
  292. function getSongsFromYoutubeIds(session, youtubeIds, cb) {
  293. async.waterfall(
  294. [
  295. next => {
  296. SongsModule.runJob(
  297. "GET_SONGS",
  298. {
  299. youtubeIds,
  300. properties: [
  301. "youtubeId",
  302. "title",
  303. "artists",
  304. "thumbnail",
  305. "duration",
  306. "verified",
  307. "_id",
  308. "youtubeVideoId"
  309. ]
  310. },
  311. this
  312. )
  313. .then(response => next(null, response.songs))
  314. .catch(err => next(err));
  315. }
  316. ],
  317. async (err, songs) => {
  318. if (err) {
  319. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  320. this.log("ERROR", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Failed to get songs. "${err}"`);
  321. return cb({ status: "error", message: err });
  322. }
  323. this.log("SUCCESS", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Got songs successfully.`);
  324. return cb({ status: "success", data: { songs } });
  325. }
  326. );
  327. }
  328. ),
  329. /**
  330. * Creates a song
  331. *
  332. * @param {object} session - the session object automatically added by the websocket
  333. * @param {object} newSong - the song object
  334. * @param {Function} cb
  335. */
  336. create: useHasPermission("songs.create", async function create(session, newSong, cb) {
  337. async.waterfall(
  338. [
  339. next => {
  340. SongsModule.runJob("CREATE_SONG", { song: newSong, userId: session.userId }, this)
  341. .then(song => next(null, song))
  342. .catch(next);
  343. }
  344. ],
  345. async (err, song) => {
  346. if (err) {
  347. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  348. this.log("ERROR", "SONGS_CREATE", `Failed to create song "${JSON.stringify(newSong)}". "${err}"`);
  349. return cb({ status: "error", message: err });
  350. }
  351. this.log("SUCCESS", "SONGS_CREATE", `Successfully created song "${song._id}".`);
  352. return cb({
  353. status: "success",
  354. message: "Song has been successfully created",
  355. data: { song }
  356. });
  357. }
  358. );
  359. }),
  360. /**
  361. * Updates a song
  362. *
  363. * @param {object} session - the session object automatically added by the websocket
  364. * @param {string} songId - the song id
  365. * @param {object} song - the updated song object
  366. * @param {Function} cb
  367. */
  368. update: useHasPermission("songs.update", async function update(session, songId, song, cb) {
  369. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  370. let existingSong = null;
  371. async.waterfall(
  372. [
  373. next => {
  374. songModel.findOne({ _id: songId }, next);
  375. },
  376. (_existingSong, next) => {
  377. existingSong = _existingSong;
  378. // Verify the song
  379. if (existingSong.verified === false && song.verified === true) {
  380. song.verifiedBy = session.userId;
  381. song.verifiedAt = Date.now();
  382. }
  383. // Unverify the song
  384. else if (existingSong.verified === true && song.verified === false) {
  385. song.verifiedBy = null;
  386. song.verifiedAt = null;
  387. }
  388. next();
  389. },
  390. next => {
  391. songModel.updateOne({ _id: songId }, song, { runValidators: true }, next);
  392. },
  393. (res, next) => {
  394. SongsModule.runJob("UPDATE_SONG", { songId }, this)
  395. .then(song => {
  396. existingSong.genres
  397. .concat(song.genres)
  398. .filter((value, index, self) => self.indexOf(value) === index)
  399. .forEach(genre => {
  400. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", {
  401. genre,
  402. createPlaylist: song.verified
  403. })
  404. .then(() => {})
  405. .catch(() => {});
  406. });
  407. next(null, song);
  408. })
  409. .catch(next);
  410. }
  411. ],
  412. async (err, song) => {
  413. if (err) {
  414. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  415. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  416. return cb({ status: "error", message: err });
  417. }
  418. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  419. return cb({
  420. status: "success",
  421. message: "Song has been successfully updated",
  422. data: { song }
  423. });
  424. }
  425. );
  426. }),
  427. /**
  428. * Removes a song
  429. *
  430. * @param session
  431. * @param songId - the song id
  432. * @param cb
  433. */
  434. remove: useHasPermission("songs.remove", async function remove(session, songId, cb) {
  435. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  436. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  437. async.waterfall(
  438. [
  439. next => {
  440. songModel.findOne({ _id: songId }, next);
  441. },
  442. (song, next) => {
  443. YouTubeModule.runJob("GET_VIDEO", { identifier: song.youtubeId, createMissing: true }, this)
  444. .then(res => next(null, song, res.video))
  445. .catch(() => next(null, song, false));
  446. },
  447. (song, youtubeVideo, next) => {
  448. PlaylistsModule.runJob("GET_PLAYLISTS_WITH_SONG", { songId }, this)
  449. .then(res =>
  450. next(
  451. null,
  452. song,
  453. youtubeVideo,
  454. res.playlists.map(playlist => playlist._id)
  455. )
  456. )
  457. .catch(next);
  458. },
  459. (song, youtubeVideo, playlistIds, next) => {
  460. if (!youtubeVideo) return next(null, song, youtubeVideo, playlistIds);
  461. return PlaylistsModule.playlistModel.updateMany(
  462. { "songs._id": songId },
  463. {
  464. $set: {
  465. "songs.$._id": null,
  466. "songs.$.title": youtubeVideo.title,
  467. "songs.$.artists": [youtubeVideo.author],
  468. "songs.$.duration": youtubeVideo.duration,
  469. "songs.$.skipDuration": 0,
  470. "songs.$.thumbnail": youtubeVideo.thumbnail,
  471. "songs.$.verified": false
  472. }
  473. },
  474. err => {
  475. if (err) next(err);
  476. next(null, song, youtubeVideo, playlistIds);
  477. }
  478. );
  479. },
  480. (song, youtubeVideo, playlistIds, next) => {
  481. async.eachLimit(
  482. playlistIds,
  483. 1,
  484. (playlistId, next) => {
  485. async.waterfall(
  486. [
  487. next => {
  488. if (youtubeVideo) next();
  489. else
  490. WSModule.runJob(
  491. "RUN_ACTION2",
  492. {
  493. session,
  494. namespace: "playlists",
  495. action: "removeSongFromPlaylist",
  496. args: [song.youtubeId, playlistId]
  497. },
  498. this
  499. )
  500. .then(res => {
  501. if (res.status === "error") next(res.message);
  502. else next();
  503. })
  504. .catch(err => {
  505. next(err);
  506. });
  507. },
  508. next => {
  509. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  510. .then(() => next())
  511. .catch(next);
  512. }
  513. ],
  514. next
  515. );
  516. },
  517. err => {
  518. if (err) next(err);
  519. else next(null, song, youtubeVideo);
  520. }
  521. );
  522. },
  523. (song, youtubeVideo, next) => {
  524. stationModel.find({ "queue._id": songId }, (err, stations) => {
  525. if (err) next(err);
  526. next(
  527. null,
  528. song,
  529. youtubeVideo,
  530. stations.map(station => station._id)
  531. );
  532. });
  533. },
  534. (song, youtubeVideo, stationIds, next) => {
  535. stationModel.find({ "currentSong._id": songId }, (err, stations) => {
  536. if (err) next(err);
  537. next(null, song, youtubeVideo, {
  538. queue: stationIds,
  539. current: stations.map(station => station._id)
  540. });
  541. });
  542. },
  543. (song, youtubeVideo, stationIds, next) => {
  544. if (!youtubeVideo) return next(null, song, youtubeVideo, stationIds);
  545. return stationModel.updateMany(
  546. { "queue._id": songId },
  547. {
  548. $set: {
  549. "queue.$._id": null,
  550. "queue.$.title": youtubeVideo.title,
  551. "queue.$.artists": [youtubeVideo.author],
  552. "queue.$.duration": youtubeVideo.duration,
  553. "queue.$.skipDuration": 0,
  554. "queue.$.thumbnail": youtubeVideo.thumbnail,
  555. "queue.$.verified": false
  556. }
  557. },
  558. err => {
  559. if (err) next(err);
  560. next(null, song, youtubeVideo, stationIds);
  561. }
  562. );
  563. },
  564. (song, youtubeVideo, stationIds, next) => {
  565. if (!youtubeVideo) return next(null, song, youtubeVideo, stationIds);
  566. return stationModel.updateMany(
  567. { "currentSong._id": songId },
  568. {
  569. $set: {
  570. "currentSong._id": null,
  571. "currentSong.title": youtubeVideo.title,
  572. "currentSong.artists": [youtubeVideo.author],
  573. // "currentSong.duration": youtubeVideo.duration,
  574. // "currentSong.skipDuration": 0,
  575. "currentSong.thumbnail": youtubeVideo.thumbnail,
  576. "currentSong.verified": false
  577. }
  578. },
  579. err => {
  580. if (err) next(err);
  581. next(null, song, youtubeVideo, stationIds);
  582. }
  583. );
  584. },
  585. (song, youtubeVideo, stationIds, next) => {
  586. async.eachLimit(
  587. stationIds.queue,
  588. 1,
  589. (stationId, next) => {
  590. if (!youtubeVideo)
  591. StationsModule.runJob(
  592. "REMOVE_FROM_QUEUE",
  593. { stationId, youtubeId: song.youtubeId },
  594. this
  595. )
  596. .then(() => next())
  597. .catch(err => {
  598. if (
  599. err === "Station not found" ||
  600. err === "Song is not currently in the queue."
  601. )
  602. next();
  603. else next(err);
  604. });
  605. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  606. .then(() => next())
  607. .catch(next);
  608. },
  609. err => {
  610. if (err) next(err);
  611. else next(null, youtubeVideo, stationIds);
  612. }
  613. );
  614. },
  615. (youtubeVideo, stationIds, next) => {
  616. async.eachLimit(
  617. stationIds.current,
  618. 1,
  619. (stationId, next) => {
  620. if (!youtubeVideo)
  621. StationsModule.runJob("SKIP_STATION", { stationId, natural: false }, this)
  622. .then(() => {
  623. next();
  624. })
  625. .catch(err => {
  626. if (err.message === "Station not found.") next();
  627. else next(err);
  628. });
  629. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  630. .then(() => next())
  631. .catch(next);
  632. },
  633. err => {
  634. if (err) next(err);
  635. else next();
  636. }
  637. );
  638. },
  639. next => {
  640. songModel.deleteOne({ _id: songId }, err => {
  641. if (err) next(err);
  642. else next();
  643. });
  644. },
  645. next => {
  646. CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  647. .then(() => {
  648. next();
  649. })
  650. .catch(next);
  651. }
  652. ],
  653. async err => {
  654. if (err) {
  655. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  656. this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  657. return cb({ status: "error", message: err });
  658. }
  659. this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  660. CacheModule.runJob("PUB", {
  661. channel: "song.removed",
  662. value: { songId }
  663. });
  664. return cb({
  665. status: "success",
  666. message: "Song has been successfully removed"
  667. });
  668. }
  669. );
  670. }),
  671. /**
  672. * Removes many songs
  673. *
  674. * @param session
  675. * @param songIds - array of song ids
  676. * @param cb
  677. */
  678. removeMany: useHasPermission("songs.removeMany", async function remove(session, songIds, cb) {
  679. const successful = [];
  680. const failed = [];
  681. this.keepLongJob();
  682. this.publishProgress({
  683. status: "started",
  684. title: "Bulk remove songs",
  685. message: "Removing songs.",
  686. id: this.toString()
  687. });
  688. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  689. await CacheModule.runJob(
  690. "PUB",
  691. {
  692. channel: "longJob.added",
  693. value: { jobId: this.toString(), userId: session.userId }
  694. },
  695. this
  696. );
  697. async.waterfall(
  698. [
  699. next => {
  700. async.eachLimit(
  701. songIds,
  702. 1,
  703. (songId, next) => {
  704. this.publishProgress({ status: "update", message: `Removing song "${songId}"` });
  705. WSModule.runJob(
  706. "RUN_ACTION2",
  707. {
  708. session,
  709. namespace: "songs",
  710. action: "remove",
  711. args: [songId]
  712. },
  713. this
  714. )
  715. .then(res => {
  716. if (res.status === "error") failed.push(songId);
  717. else successful.push(songId);
  718. next();
  719. })
  720. .catch(err => {
  721. next(err);
  722. });
  723. },
  724. err => {
  725. if (err) next(err);
  726. else next();
  727. }
  728. );
  729. }
  730. ],
  731. async err => {
  732. if (err) {
  733. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  734. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  735. this.publishProgress({
  736. status: "error",
  737. message: err
  738. });
  739. return cb({ status: "error", message: err });
  740. }
  741. let message = "";
  742. if (successful.length === 1) message += `1 song has been successfully removed`;
  743. else message += `${successful.length} songs have been successfully removed`;
  744. if (failed.length > 0) {
  745. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  746. if (failed.length === 1) message += `, failed to remove 1 song`;
  747. else message += `, failed to remove ${failed.length} songs`;
  748. }
  749. this.log("SUCCESS", "SONGS_REMOVE_MANY", `${message} "${successful.join(", ")}"`);
  750. this.publishProgress({
  751. status: "success",
  752. message
  753. });
  754. return cb({
  755. status: "success",
  756. message
  757. });
  758. }
  759. );
  760. }),
  761. /**
  762. * Searches through official songs
  763. *
  764. * @param {object} session - the session object automatically added by the websocket
  765. * @param {string} query - the query
  766. * @param {string} page - the page
  767. * @param {Function} cb - gets called with the result
  768. */
  769. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  770. async.waterfall(
  771. [
  772. next => {
  773. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  774. else next();
  775. },
  776. next => {
  777. SongsModule.runJob("SEARCH", {
  778. query,
  779. includeVerified: true,
  780. trimmed: true,
  781. page
  782. })
  783. .then(response => {
  784. next(null, response);
  785. })
  786. .catch(err => {
  787. next(err);
  788. });
  789. }
  790. ],
  791. async (err, data) => {
  792. if (err) {
  793. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  794. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  795. return cb({ status: "error", message: err });
  796. }
  797. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  798. return cb({ status: "success", data });
  799. }
  800. );
  801. }),
  802. /**
  803. * Verifies a song
  804. *
  805. * @param session
  806. * @param songId - the song id
  807. * @param cb
  808. */
  809. verify: useHasPermission("songs.verify", async function add(session, songId, cb) {
  810. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  811. async.waterfall(
  812. [
  813. next => {
  814. SongModel.findOne({ _id: songId }, next);
  815. },
  816. (song, next) => {
  817. if (!song) return next("This song is not in the database.");
  818. return next(null, song);
  819. },
  820. (song, next) => {
  821. const oldStatus = false;
  822. song.verifiedBy = session.userId;
  823. song.verifiedAt = Date.now();
  824. song.verified = true;
  825. song.save(err => next(err, song, oldStatus));
  826. },
  827. (song, oldStatus, next) => {
  828. song.genres.forEach(genre => {
  829. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true })
  830. .then(() => {})
  831. .catch(() => {});
  832. });
  833. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  834. next(null, song, oldStatus);
  835. }
  836. ],
  837. async err => {
  838. if (err) {
  839. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  840. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  841. return cb({ status: "error", message: err });
  842. }
  843. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  844. return cb({
  845. status: "success",
  846. message: "Song has been verified successfully."
  847. });
  848. }
  849. );
  850. // TODO Check if video is in queue and Add the song to the appropriate stations
  851. }),
  852. /**
  853. * Verify many songs
  854. *
  855. * @param session
  856. * @param songIds - array of song ids
  857. * @param cb
  858. */
  859. verifyMany: useHasPermission("songs.verifyMany", async function verifyMany(session, songIds, cb) {
  860. const successful = [];
  861. const failed = [];
  862. this.keepLongJob();
  863. this.publishProgress({
  864. status: "started",
  865. title: "Bulk verifying songs",
  866. message: "Verifying songs.",
  867. id: this.toString()
  868. });
  869. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  870. await CacheModule.runJob(
  871. "PUB",
  872. {
  873. channel: "longJob.added",
  874. value: { jobId: this.toString(), userId: session.userId }
  875. },
  876. this
  877. );
  878. async.waterfall(
  879. [
  880. next => {
  881. async.eachLimit(
  882. songIds,
  883. 1,
  884. (songId, next) => {
  885. this.publishProgress({ status: "update", message: `Verifying song "${songId}"` });
  886. WSModule.runJob(
  887. "RUN_ACTION2",
  888. {
  889. session,
  890. namespace: "songs",
  891. action: "verify",
  892. args: [songId]
  893. },
  894. this
  895. )
  896. .then(res => {
  897. if (res.status === "error") failed.push(songId);
  898. else successful.push(songId);
  899. next();
  900. })
  901. .catch(err => {
  902. next(err);
  903. });
  904. },
  905. err => {
  906. if (err) next(err);
  907. else next();
  908. }
  909. );
  910. }
  911. ],
  912. async err => {
  913. if (err) {
  914. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  915. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  916. this.publishProgress({
  917. status: "error",
  918. message: err
  919. });
  920. return cb({ status: "error", message: err });
  921. }
  922. let message = "";
  923. if (successful.length === 1) message += `1 song has been successfully verified`;
  924. else message += `${successful.length} songs have been successfully verified`;
  925. if (failed.length > 0) {
  926. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  927. if (failed.length === 1) message += `, failed to verify 1 song`;
  928. else message += `, failed to verify ${failed.length} songs`;
  929. }
  930. this.log("SUCCESS", "SONGS_VERIFY_MANY", `${message} "${successful.join(", ")}"`);
  931. this.publishProgress({
  932. status: "success",
  933. message
  934. });
  935. return cb({
  936. status: "success",
  937. message
  938. });
  939. }
  940. );
  941. }),
  942. /**
  943. * Un-verifies a song
  944. *
  945. * @param session
  946. * @param songId - the song id
  947. * @param cb
  948. */
  949. unverify: useHasPermission("songs.unverify", async function add(session, songId, cb) {
  950. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  951. async.waterfall(
  952. [
  953. next => {
  954. SongModel.findOne({ _id: songId }, next);
  955. },
  956. (song, next) => {
  957. if (!song) return next("This song is not in the database.");
  958. return next(null, song);
  959. },
  960. (song, next) => {
  961. song.verified = false;
  962. song.verifiedBy = null;
  963. song.verifiedAt = null;
  964. song.save(err => {
  965. next(err, song);
  966. });
  967. },
  968. (song, next) => {
  969. song.genres.forEach(genre => {
  970. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: false })
  971. .then(() => {})
  972. .catch(() => {});
  973. });
  974. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  975. next(null);
  976. }
  977. ],
  978. async err => {
  979. if (err) {
  980. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  981. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  982. return cb({ status: "error", message: err });
  983. }
  984. this.log(
  985. "SUCCESS",
  986. "SONGS_UNVERIFY",
  987. `User "${session.userId}" successfully unverified song "${songId}".`
  988. );
  989. return cb({
  990. status: "success",
  991. message: "Song has been unverified successfully."
  992. });
  993. }
  994. );
  995. // TODO Check if video is in queue and Add the song to the appropriate stations
  996. }),
  997. /**
  998. * Unverify many songs
  999. *
  1000. * @param session
  1001. * @param songIds - array of song ids
  1002. * @param cb
  1003. */
  1004. unverifyMany: useHasPermission("songs.unverifyMany", async function unverifyMany(session, songIds, cb) {
  1005. const successful = [];
  1006. const failed = [];
  1007. this.keepLongJob();
  1008. this.publishProgress({
  1009. status: "started",
  1010. title: "Bulk unverifying songs",
  1011. message: "Unverifying songs.",
  1012. id: this.toString()
  1013. });
  1014. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1015. await CacheModule.runJob(
  1016. "PUB",
  1017. {
  1018. channel: "longJob.added",
  1019. value: { jobId: this.toString(), userId: session.userId }
  1020. },
  1021. this
  1022. );
  1023. async.waterfall(
  1024. [
  1025. next => {
  1026. async.eachLimit(
  1027. songIds,
  1028. 1,
  1029. (songId, next) => {
  1030. this.publishProgress({ status: "update", message: `Unverifying song "${songId}"` });
  1031. WSModule.runJob(
  1032. "RUN_ACTION2",
  1033. {
  1034. session,
  1035. namespace: "songs",
  1036. action: "unverify",
  1037. args: [songId]
  1038. },
  1039. this
  1040. )
  1041. .then(res => {
  1042. if (res.status === "error") failed.push(songId);
  1043. else successful.push(songId);
  1044. next();
  1045. })
  1046. .catch(err => {
  1047. next(err);
  1048. });
  1049. },
  1050. err => {
  1051. if (err) next(err);
  1052. else next();
  1053. }
  1054. );
  1055. }
  1056. ],
  1057. async err => {
  1058. if (err) {
  1059. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1060. this.log(
  1061. "ERROR",
  1062. "SONGS_UNVERIFY_MANY",
  1063. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1064. );
  1065. this.publishProgress({
  1066. status: "error",
  1067. message: err
  1068. });
  1069. return cb({ status: "error", message: err });
  1070. }
  1071. let message = "";
  1072. if (successful.length === 1) message += `1 song has been successfully unverified`;
  1073. else message += `${successful.length} songs have been successfully unverified`;
  1074. if (failed.length > 0) {
  1075. this.log(
  1076. "ERROR",
  1077. "SONGS_UNVERIFY_MANY",
  1078. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1079. );
  1080. if (failed.length === 1) message += `, failed to unverify 1 song`;
  1081. else message += `, failed to unverify ${failed.length} songs`;
  1082. }
  1083. this.log("SUCCESS", "SONGS_UNVERIFY_MANY", `${message} "${successful.join(", ")}"`);
  1084. this.publishProgress({
  1085. status: "success",
  1086. message
  1087. });
  1088. return cb({
  1089. status: "success",
  1090. message
  1091. });
  1092. }
  1093. );
  1094. }),
  1095. /**
  1096. * Gets a list of all genres
  1097. *
  1098. * @param session
  1099. * @param cb
  1100. */
  1101. getGenres: useHasPermission("songs.getGenres", function getGenres(session, cb) {
  1102. async.waterfall(
  1103. [
  1104. next => {
  1105. SongsModule.runJob("GET_GENRES", this)
  1106. .then(res => {
  1107. next(null, res.genres);
  1108. })
  1109. .catch(next);
  1110. }
  1111. ],
  1112. async (err, genres) => {
  1113. if (err && err !== true) {
  1114. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1115. this.log("ERROR", "GET_GENRES", `User ${session.userId} failed to get genres. '${err}'`);
  1116. cb({ status: "error", message: err });
  1117. } else {
  1118. this.log("SUCCESS", "GET_GENRES", `User ${session.userId} has successfully got the genres.`);
  1119. cb({
  1120. status: "success",
  1121. message: "Successfully got genres.",
  1122. data: {
  1123. items: genres
  1124. }
  1125. });
  1126. }
  1127. }
  1128. );
  1129. }),
  1130. /**
  1131. * Bulk update genres for selected songs
  1132. *
  1133. * @param session
  1134. * @param method Whether to add, remove or replace genres
  1135. * @param genres Array of genres to apply
  1136. * @param songIds Array of songIds to apply genres to
  1137. * @param cb
  1138. */
  1139. editGenres: useHasPermission("songs.editGenres", async function editGenres(session, method, genres, songIds, cb) {
  1140. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1141. this.keepLongJob();
  1142. this.publishProgress({
  1143. status: "started",
  1144. title: "Bulk editing genres",
  1145. message: "Updating genres.",
  1146. id: this.toString()
  1147. });
  1148. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1149. await CacheModule.runJob(
  1150. "PUB",
  1151. {
  1152. channel: "longJob.added",
  1153. value: { jobId: this.toString(), userId: session.userId }
  1154. },
  1155. this
  1156. );
  1157. async.waterfall(
  1158. [
  1159. next => {
  1160. songModel.find({ _id: { $in: songIds } }, next);
  1161. },
  1162. (songs, next) => {
  1163. const songsFound = songs.map(song => song._id);
  1164. if (songsFound.length > 0) next(null, songsFound);
  1165. else next("None of the specified songs were found.");
  1166. },
  1167. (songsFound, next) => {
  1168. const query = {};
  1169. if (method === "add") {
  1170. query.$addToSet = { genres: { $each: genres } };
  1171. } else if (method === "remove") {
  1172. query.$pullAll = { genres };
  1173. } else if (method === "replace") {
  1174. query.$set = { genres };
  1175. } else {
  1176. next("Invalid method.");
  1177. return;
  1178. }
  1179. this.publishProgress({
  1180. status: "update",
  1181. message: "Updating genres in MongoDB."
  1182. });
  1183. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1184. if (err) {
  1185. next(err);
  1186. return;
  1187. }
  1188. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1189. next();
  1190. });
  1191. }
  1192. ],
  1193. async err => {
  1194. if (err && err !== true) {
  1195. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1196. this.log("ERROR", "EDIT_GENRES", `User ${session.userId} failed to edit genres. '${err}'`);
  1197. this.publishProgress({
  1198. status: "error",
  1199. message: err
  1200. });
  1201. cb({ status: "error", message: err });
  1202. } else {
  1203. this.log("SUCCESS", "EDIT_GENRES", `User ${session.userId} has successfully edited genres.`);
  1204. this.publishProgress({
  1205. status: "success",
  1206. message: "Successfully edited genres."
  1207. });
  1208. cb({
  1209. status: "success",
  1210. message: "Successfully edited genres."
  1211. });
  1212. }
  1213. }
  1214. );
  1215. }),
  1216. /**
  1217. * Gets a list of all artists
  1218. *
  1219. * @param session
  1220. * @param cb
  1221. */
  1222. getArtists: useHasPermission("songs.getArtists", function getArtists(session, cb) {
  1223. async.waterfall(
  1224. [
  1225. next => {
  1226. SongsModule.runJob("GET_ARTISTS", this)
  1227. .then(res => {
  1228. next(null, res.artists);
  1229. })
  1230. .catch(next);
  1231. }
  1232. ],
  1233. async (err, artists) => {
  1234. if (err && err !== true) {
  1235. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1236. this.log("ERROR", "GET_ARTISTS", `User ${session.userId} failed to get artists. '${err}'`);
  1237. cb({ status: "error", message: err });
  1238. } else {
  1239. this.log("SUCCESS", "GET_ARTISTS", `User ${session.userId} has successfully got the artists.`);
  1240. cb({
  1241. status: "success",
  1242. message: "Successfully got artists.",
  1243. data: {
  1244. items: artists
  1245. }
  1246. });
  1247. }
  1248. }
  1249. );
  1250. }),
  1251. /**
  1252. * Bulk update artists for selected songs
  1253. *
  1254. * @param session
  1255. * @param method Whether to add, remove or replace artists
  1256. * @param artists Array of artists to apply
  1257. * @param songIds Array of songIds to apply artists to
  1258. * @param cb
  1259. */
  1260. editArtists: useHasPermission(
  1261. "songs.editArtists",
  1262. async function editArtists(session, method, artists, songIds, cb) {
  1263. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1264. this.keepLongJob();
  1265. this.publishProgress({
  1266. status: "started",
  1267. title: "Bulk editing artists",
  1268. message: "Updating artists.",
  1269. id: this.toString()
  1270. });
  1271. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1272. await CacheModule.runJob(
  1273. "PUB",
  1274. {
  1275. channel: "longJob.added",
  1276. value: { jobId: this.toString(), userId: session.userId }
  1277. },
  1278. this
  1279. );
  1280. async.waterfall(
  1281. [
  1282. next => {
  1283. songModel.find({ _id: { $in: songIds } }, next);
  1284. },
  1285. (songs, next) => {
  1286. const songsFound = songs.map(song => song._id);
  1287. if (songsFound.length > 0) next(null, songsFound);
  1288. else next("None of the specified songs were found.");
  1289. },
  1290. (songsFound, next) => {
  1291. const query = {};
  1292. if (method === "add") {
  1293. query.$addToSet = { artists: { $each: artists } };
  1294. } else if (method === "remove") {
  1295. query.$pullAll = { artists };
  1296. } else if (method === "replace") {
  1297. query.$set = { artists };
  1298. } else {
  1299. next("Invalid method.");
  1300. return;
  1301. }
  1302. this.publishProgress({
  1303. status: "update",
  1304. message: "Updating artists in MongoDB."
  1305. });
  1306. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1307. if (err) {
  1308. next(err);
  1309. return;
  1310. }
  1311. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1312. next();
  1313. });
  1314. }
  1315. ],
  1316. async err => {
  1317. if (err && err !== true) {
  1318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1319. this.log("ERROR", "EDIT_ARTISTS", `User ${session.userId} failed to edit artists. '${err}'`);
  1320. this.publishProgress({
  1321. status: "error",
  1322. message: err
  1323. });
  1324. cb({ status: "error", message: err });
  1325. } else {
  1326. this.log("SUCCESS", "EDIT_ARTISTS", `User ${session.userId} has successfully edited artists.`);
  1327. this.publishProgress({
  1328. status: "success",
  1329. message: "Successfully edited artists."
  1330. });
  1331. cb({
  1332. status: "success",
  1333. message: "Successfully edited artists."
  1334. });
  1335. }
  1336. }
  1337. );
  1338. }
  1339. ),
  1340. /**
  1341. * Gets a list of all tags
  1342. *
  1343. * @param session
  1344. * @param cb
  1345. */
  1346. getTags: useHasPermission("songs.getTags", function getTags(session, cb) {
  1347. async.waterfall(
  1348. [
  1349. next => {
  1350. SongsModule.runJob("GET_TAGS", this)
  1351. .then(res => {
  1352. next(null, res.tags);
  1353. })
  1354. .catch(next);
  1355. }
  1356. ],
  1357. async (err, tags) => {
  1358. if (err && err !== true) {
  1359. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1360. this.log("ERROR", "GET_TAGS", `User ${session.userId} failed to get tags. '${err}'`);
  1361. cb({ status: "error", message: err });
  1362. } else {
  1363. this.log("SUCCESS", "GET_TAGS", `User ${session.userId} has successfully got the tags.`);
  1364. cb({
  1365. status: "success",
  1366. message: "Successfully got tags.",
  1367. data: {
  1368. items: tags
  1369. }
  1370. });
  1371. }
  1372. }
  1373. );
  1374. }),
  1375. /**
  1376. * Bulk update tags for selected songs
  1377. *
  1378. * @param session
  1379. * @param method Whether to add, remove or replace tags
  1380. * @param tags Array of tags to apply
  1381. * @param songIds Array of songIds to apply tags to
  1382. * @param cb
  1383. */
  1384. editTags: useHasPermission("songs.editTags", async function editTags(session, method, tags, songIds, cb) {
  1385. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1386. this.keepLongJob();
  1387. this.publishProgress({
  1388. status: "started",
  1389. title: "Bulk editing tags",
  1390. message: "Updating tags.",
  1391. id: this.toString()
  1392. });
  1393. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1394. await CacheModule.runJob(
  1395. "PUB",
  1396. {
  1397. channel: "longJob.added",
  1398. value: { jobId: this.toString(), userId: session.userId }
  1399. },
  1400. this
  1401. );
  1402. async.waterfall(
  1403. [
  1404. next => {
  1405. songModel.find({ _id: { $in: songIds } }, next);
  1406. },
  1407. (songs, next) => {
  1408. const songsFound = songs.map(song => song._id);
  1409. if (songsFound.length > 0) next(null, songsFound);
  1410. else next("None of the specified songs were found.");
  1411. },
  1412. (songsFound, next) => {
  1413. const query = {};
  1414. if (method === "add") {
  1415. query.$addToSet = { tags: { $each: tags } };
  1416. } else if (method === "remove") {
  1417. query.$pullAll = { tags };
  1418. } else if (method === "replace") {
  1419. query.$set = { tags };
  1420. } else {
  1421. next("Invalid method.");
  1422. return;
  1423. }
  1424. this.publishProgress({
  1425. status: "update",
  1426. message: "Updating tags in MongoDB."
  1427. });
  1428. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1429. if (err) {
  1430. next(err);
  1431. return;
  1432. }
  1433. SongsModule.runJob(
  1434. "UPDATE_SONGS",
  1435. {
  1436. songIds: songsFound
  1437. },
  1438. this
  1439. )
  1440. .then(() => {
  1441. next();
  1442. })
  1443. .catch(() => {
  1444. next();
  1445. });
  1446. });
  1447. }
  1448. ],
  1449. async err => {
  1450. if (err && err !== true) {
  1451. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1452. this.log("ERROR", "EDIT_TAGS", `User ${session.userId} failed to edit tags. '${err}'`);
  1453. this.publishProgress({
  1454. status: "error",
  1455. message: err
  1456. });
  1457. cb({ status: "error", message: err });
  1458. } else {
  1459. this.log("SUCCESS", "EDIT_TAGS", `User ${session.userId} has successfully edited tags.`);
  1460. this.publishProgress({
  1461. status: "success",
  1462. message: "Successfully edited tags."
  1463. });
  1464. cb({
  1465. status: "success",
  1466. message: "Successfully edited tags."
  1467. });
  1468. }
  1469. }
  1470. );
  1471. })
  1472. };