songs.js 40 KB

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