songs.js 40 KB

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