songs.js 41 KB

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