songs.js 40 KB

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