1
0

songs.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  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 bulk EditSong
  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. existingSong.artists
  401. .concat(song.artists)
  402. .filter((value, index, self) => self.indexOf(value) === index)
  403. .forEach(artist => {
  404. PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist })
  405. .then(() => {})
  406. .catch(() => {});
  407. });
  408. next(null, song);
  409. })
  410. .catch(next);
  411. }
  412. ],
  413. async (err, song) => {
  414. if (err) {
  415. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  416. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  417. return cb({ status: "error", message: err });
  418. }
  419. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  420. return cb({
  421. status: "success",
  422. message: "Song has been successfully updated",
  423. data: { song }
  424. });
  425. }
  426. );
  427. }),
  428. /**
  429. * Removes a song
  430. *
  431. * @param session
  432. * @param songId - the song id
  433. * @param cb
  434. */
  435. remove: isAdminRequired(async function remove(session, songId, cb) {
  436. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  437. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  438. async.waterfall(
  439. [
  440. next => {
  441. songModel.findOne({ _id: songId }, next);
  442. },
  443. (song, next) => {
  444. YouTubeModule.runJob("GET_VIDEO", { identifier: song.youtubeId, createMissing: true }, this)
  445. .then(res => next(null, song, res.video))
  446. .catch(() => next(null, song, false));
  447. },
  448. (song, youtubeVideo, next) => {
  449. PlaylistsModule.runJob("GET_PLAYLISTS_WITH_SONG", { songId }, this)
  450. .then(res =>
  451. next(
  452. null,
  453. song,
  454. youtubeVideo,
  455. res.playlists.map(playlist => playlist._id)
  456. )
  457. )
  458. .catch(next);
  459. },
  460. (song, youtubeVideo, playlistIds, next) => {
  461. if (!youtubeVideo) return next(null, song, youtubeVideo, playlistIds);
  462. return PlaylistsModule.playlistModel.updateMany(
  463. { "songs._id": songId },
  464. {
  465. $set: {
  466. "songs.$._id": null,
  467. "songs.$.title": youtubeVideo.title,
  468. "songs.$.artists": [youtubeVideo.author],
  469. "songs.$.duration": youtubeVideo.duration,
  470. "songs.$.skipDuration": 0,
  471. "songs.$.thumbnail": youtubeVideo.thumbnail,
  472. "songs.$.verified": false
  473. }
  474. },
  475. err => {
  476. if (err) next(err);
  477. next(null, song, youtubeVideo, playlistIds);
  478. }
  479. );
  480. },
  481. (song, youtubeVideo, playlistIds, next) => {
  482. async.eachLimit(
  483. playlistIds,
  484. 1,
  485. (playlistId, next) => {
  486. async.waterfall(
  487. [
  488. next => {
  489. if (youtubeVideo) next();
  490. else
  491. WSModule.runJob(
  492. "RUN_ACTION2",
  493. {
  494. session,
  495. namespace: "playlists",
  496. action: "removeSongFromPlaylist",
  497. args: [song.youtubeId, playlistId]
  498. },
  499. this
  500. )
  501. .then(res => {
  502. if (res.status === "error") next(res.message);
  503. else next();
  504. })
  505. .catch(err => {
  506. next(err);
  507. });
  508. },
  509. next => {
  510. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  511. .then(() => next())
  512. .catch(next);
  513. }
  514. ],
  515. next
  516. );
  517. },
  518. err => {
  519. if (err) next(err);
  520. else next(null, song, youtubeVideo);
  521. }
  522. );
  523. },
  524. (song, youtubeVideo, next) => {
  525. stationModel.find({ "queue._id": songId }, (err, stations) => {
  526. if (err) next(err);
  527. next(
  528. null,
  529. song,
  530. youtubeVideo,
  531. stations.map(station => station._id)
  532. );
  533. });
  534. },
  535. (song, youtubeVideo, stationIds, next) => {
  536. stationModel.find({ "currentSong._id": songId }, (err, stations) => {
  537. if (err) next(err);
  538. next(null, song, youtubeVideo, {
  539. queue: stationIds,
  540. current: stations.map(station => station._id)
  541. });
  542. });
  543. },
  544. (song, youtubeVideo, stationIds, next) => {
  545. if (!youtubeVideo) return next(null, song, youtubeVideo, stationIds);
  546. return stationModel.updateMany(
  547. { "queue._id": songId },
  548. {
  549. $set: {
  550. "queue.$._id": null,
  551. "queue.$.title": youtubeVideo.title,
  552. "queue.$.artists": [youtubeVideo.author],
  553. "queue.$.duration": youtubeVideo.duration,
  554. "queue.$.skipDuration": 0,
  555. "queue.$.thumbnail": youtubeVideo.thumbnail,
  556. "queue.$.verified": false
  557. }
  558. },
  559. err => {
  560. if (err) next(err);
  561. next(null, song, youtubeVideo, stationIds);
  562. }
  563. );
  564. },
  565. (song, youtubeVideo, stationIds, next) => {
  566. if (!youtubeVideo) return next(null, song, youtubeVideo, stationIds);
  567. return stationModel.updateMany(
  568. { "currentSong._id": songId },
  569. {
  570. $set: {
  571. "currentSong._id": null,
  572. "currentSong.title": youtubeVideo.title,
  573. "currentSong.artists": [youtubeVideo.author],
  574. // "currentSong.duration": youtubeVideo.duration,
  575. // "currentSong.skipDuration": 0,
  576. "currentSong.thumbnail": youtubeVideo.thumbnail,
  577. "currentSong.verified": false
  578. }
  579. },
  580. err => {
  581. if (err) next(err);
  582. next(null, song, youtubeVideo, stationIds);
  583. }
  584. );
  585. },
  586. (song, youtubeVideo, stationIds, next) => {
  587. async.eachLimit(
  588. stationIds.queue,
  589. 1,
  590. (stationId, next) => {
  591. if (!youtubeVideo)
  592. StationsModule.runJob(
  593. "REMOVE_FROM_QUEUE",
  594. { stationId, youtubeId: song.youtubeId },
  595. this
  596. )
  597. .then(() => next())
  598. .catch(err => {
  599. if (
  600. err === "Station not found" ||
  601. err === "Song is not currently in the queue."
  602. )
  603. next();
  604. else next(err);
  605. });
  606. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  607. .then(() => next())
  608. .catch(next);
  609. },
  610. err => {
  611. if (err) next(err);
  612. else next(null, youtubeVideo, stationIds);
  613. }
  614. );
  615. },
  616. (youtubeVideo, stationIds, next) => {
  617. async.eachLimit(
  618. stationIds.current,
  619. 1,
  620. (stationId, next) => {
  621. if (!youtubeVideo)
  622. StationsModule.runJob("SKIP_STATION", { stationId, natural: false }, this)
  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: isAdminRequired(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: isAdminRequired(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. song.artists.forEach(artist => {
  835. PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist })
  836. .then(() => {})
  837. .catch(() => {});
  838. });
  839. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  840. next(null, song, oldStatus);
  841. }
  842. ],
  843. async err => {
  844. if (err) {
  845. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  846. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  847. return cb({ status: "error", message: err });
  848. }
  849. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  850. return cb({
  851. status: "success",
  852. message: "Song has been verified successfully."
  853. });
  854. }
  855. );
  856. // TODO Check if video is in queue and Add the song to the appropriate stations
  857. }),
  858. /**
  859. * Verify many songs
  860. *
  861. * @param session
  862. * @param songIds - array of song ids
  863. * @param cb
  864. */
  865. verifyMany: isAdminRequired(async function verifyMany(session, songIds, cb) {
  866. const successful = [];
  867. const failed = [];
  868. this.keepLongJob();
  869. this.publishProgress({
  870. status: "started",
  871. title: "Bulk verifying songs",
  872. message: "Verifying songs.",
  873. id: this.toString()
  874. });
  875. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  876. await CacheModule.runJob(
  877. "PUB",
  878. {
  879. channel: "longJob.added",
  880. value: { jobId: this.toString(), userId: session.userId }
  881. },
  882. this
  883. );
  884. async.waterfall(
  885. [
  886. next => {
  887. async.eachLimit(
  888. songIds,
  889. 1,
  890. (songId, next) => {
  891. this.publishProgress({ status: "update", message: `Verifying song "${songId}"` });
  892. WSModule.runJob(
  893. "RUN_ACTION2",
  894. {
  895. session,
  896. namespace: "songs",
  897. action: "verify",
  898. args: [songId]
  899. },
  900. this
  901. )
  902. .then(res => {
  903. if (res.status === "error") failed.push(songId);
  904. else successful.push(songId);
  905. next();
  906. })
  907. .catch(err => {
  908. next(err);
  909. });
  910. },
  911. err => {
  912. if (err) next(err);
  913. else next();
  914. }
  915. );
  916. }
  917. ],
  918. async err => {
  919. if (err) {
  920. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  921. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  922. this.publishProgress({
  923. status: "error",
  924. message: err
  925. });
  926. return cb({ status: "error", message: err });
  927. }
  928. let message = "";
  929. if (successful.length === 1) message += `1 song has been successfully verified`;
  930. else message += `${successful.length} songs have been successfully verified`;
  931. if (failed.length > 0) {
  932. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  933. if (failed.length === 1) message += `, failed to verify 1 song`;
  934. else message += `, failed to verify ${failed.length} songs`;
  935. }
  936. this.log("SUCCESS", "SONGS_VERIFY_MANY", `${message} "${successful.join(", ")}"`);
  937. this.publishProgress({
  938. status: "success",
  939. message
  940. });
  941. return cb({
  942. status: "success",
  943. message
  944. });
  945. }
  946. );
  947. }),
  948. /**
  949. * Un-verifies a song
  950. *
  951. * @param session
  952. * @param songId - the song id
  953. * @param cb
  954. */
  955. unverify: isAdminRequired(async function add(session, songId, cb) {
  956. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  957. async.waterfall(
  958. [
  959. next => {
  960. SongModel.findOne({ _id: songId }, next);
  961. },
  962. (song, next) => {
  963. if (!song) return next("This song is not in the database.");
  964. return next(null, song);
  965. },
  966. (song, next) => {
  967. song.verified = false;
  968. song.verifiedBy = null;
  969. song.verifiedAt = null;
  970. song.save(err => {
  971. next(err, song);
  972. });
  973. },
  974. (song, next) => {
  975. song.genres.forEach(genre => {
  976. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: false })
  977. .then(() => {})
  978. .catch(() => {});
  979. });
  980. song.artists.forEach(artist => {
  981. PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist })
  982. .then(() => {})
  983. .catch(() => {});
  984. });
  985. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  986. next(null);
  987. }
  988. ],
  989. async err => {
  990. if (err) {
  991. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  992. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  993. return cb({ status: "error", message: err });
  994. }
  995. this.log(
  996. "SUCCESS",
  997. "SONGS_UNVERIFY",
  998. `User "${session.userId}" successfully unverified song "${songId}".`
  999. );
  1000. return cb({
  1001. status: "success",
  1002. message: "Song has been unverified successfully."
  1003. });
  1004. }
  1005. );
  1006. // TODO Check if video is in queue and Add the song to the appropriate stations
  1007. }),
  1008. /**
  1009. * Unverify many songs
  1010. *
  1011. * @param session
  1012. * @param songIds - array of song ids
  1013. * @param cb
  1014. */
  1015. unverifyMany: isAdminRequired(async function unverifyMany(session, songIds, cb) {
  1016. const successful = [];
  1017. const failed = [];
  1018. this.keepLongJob();
  1019. this.publishProgress({
  1020. status: "started",
  1021. title: "Bulk unverifying songs",
  1022. message: "Unverifying songs.",
  1023. id: this.toString()
  1024. });
  1025. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1026. await CacheModule.runJob(
  1027. "PUB",
  1028. {
  1029. channel: "longJob.added",
  1030. value: { jobId: this.toString(), userId: session.userId }
  1031. },
  1032. this
  1033. );
  1034. async.waterfall(
  1035. [
  1036. next => {
  1037. async.eachLimit(
  1038. songIds,
  1039. 1,
  1040. (songId, next) => {
  1041. this.publishProgress({ status: "update", message: `Unverifying song "${songId}"` });
  1042. WSModule.runJob(
  1043. "RUN_ACTION2",
  1044. {
  1045. session,
  1046. namespace: "songs",
  1047. action: "unverify",
  1048. args: [songId]
  1049. },
  1050. this
  1051. )
  1052. .then(res => {
  1053. if (res.status === "error") failed.push(songId);
  1054. else successful.push(songId);
  1055. next();
  1056. })
  1057. .catch(err => {
  1058. next(err);
  1059. });
  1060. },
  1061. err => {
  1062. if (err) next(err);
  1063. else next();
  1064. }
  1065. );
  1066. }
  1067. ],
  1068. async err => {
  1069. if (err) {
  1070. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1071. this.log(
  1072. "ERROR",
  1073. "SONGS_UNVERIFY_MANY",
  1074. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1075. );
  1076. this.publishProgress({
  1077. status: "error",
  1078. message: err
  1079. });
  1080. return cb({ status: "error", message: err });
  1081. }
  1082. let message = "";
  1083. if (successful.length === 1) message += `1 song has been successfully unverified`;
  1084. else message += `${successful.length} songs have been successfully unverified`;
  1085. if (failed.length > 0) {
  1086. this.log(
  1087. "ERROR",
  1088. "SONGS_UNVERIFY_MANY",
  1089. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1090. );
  1091. if (failed.length === 1) message += `, failed to unverify 1 song`;
  1092. else message += `, failed to unverify ${failed.length} songs`;
  1093. }
  1094. this.log("SUCCESS", "SONGS_UNVERIFY_MANY", `${message} "${successful.join(", ")}"`);
  1095. this.publishProgress({
  1096. status: "success",
  1097. message
  1098. });
  1099. return cb({
  1100. status: "success",
  1101. message
  1102. });
  1103. }
  1104. );
  1105. }),
  1106. /**
  1107. * Gets a list of all genres
  1108. *
  1109. * @param session
  1110. * @param cb
  1111. */
  1112. getGenres: isAdminRequired(function getGenres(session, cb) {
  1113. async.waterfall(
  1114. [
  1115. next => {
  1116. SongsModule.runJob("GET_GENRES", this)
  1117. .then(res => {
  1118. next(null, res.genres);
  1119. })
  1120. .catch(next);
  1121. }
  1122. ],
  1123. async (err, genres) => {
  1124. if (err && err !== true) {
  1125. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1126. this.log("ERROR", "GET_GENRES", `User ${session.userId} failed to get genres. '${err}'`);
  1127. cb({ status: "error", message: err });
  1128. } else {
  1129. this.log("SUCCESS", "GET_GENRES", `User ${session.userId} has successfully got the genres.`);
  1130. cb({
  1131. status: "success",
  1132. message: "Successfully got genres.",
  1133. data: {
  1134. items: genres
  1135. }
  1136. });
  1137. }
  1138. }
  1139. );
  1140. }),
  1141. /**
  1142. * Bulk update genres for selected songs
  1143. *
  1144. * @param session
  1145. * @param method Whether to add, remove or replace genres
  1146. * @param genres Array of genres to apply
  1147. * @param songIds Array of songIds to apply genres to
  1148. * @param cb
  1149. */
  1150. editGenres: isAdminRequired(async function editGenres(session, method, genres, songIds, cb) {
  1151. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1152. this.keepLongJob();
  1153. this.publishProgress({
  1154. status: "started",
  1155. title: "Bulk editing genres",
  1156. message: "Updating genres.",
  1157. id: this.toString()
  1158. });
  1159. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1160. await CacheModule.runJob(
  1161. "PUB",
  1162. {
  1163. channel: "longJob.added",
  1164. value: { jobId: this.toString(), userId: session.userId }
  1165. },
  1166. this
  1167. );
  1168. async.waterfall(
  1169. [
  1170. next => {
  1171. songModel.find({ _id: { $in: songIds } }, next);
  1172. },
  1173. (songs, next) => {
  1174. const songsFound = songs.map(song => song._id);
  1175. if (songsFound.length > 0) next(null, songsFound);
  1176. else next("None of the specified songs were found.");
  1177. },
  1178. (songsFound, next) => {
  1179. const query = {};
  1180. if (method === "add") {
  1181. query.$addToSet = { genres: { $each: genres } };
  1182. } else if (method === "remove") {
  1183. query.$pullAll = { genres };
  1184. } else if (method === "replace") {
  1185. query.$set = { genres };
  1186. } else {
  1187. next("Invalid method.");
  1188. return;
  1189. }
  1190. this.publishProgress({
  1191. status: "update",
  1192. message: "Updating genres in MongoDB."
  1193. });
  1194. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1195. if (err) {
  1196. next(err);
  1197. return;
  1198. }
  1199. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1200. next();
  1201. });
  1202. }
  1203. ],
  1204. async err => {
  1205. if (err && err !== true) {
  1206. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1207. this.log("ERROR", "EDIT_GENRES", `User ${session.userId} failed to edit genres. '${err}'`);
  1208. this.publishProgress({
  1209. status: "error",
  1210. message: err
  1211. });
  1212. cb({ status: "error", message: err });
  1213. } else {
  1214. this.log("SUCCESS", "EDIT_GENRES", `User ${session.userId} has successfully edited genres.`);
  1215. this.publishProgress({
  1216. status: "success",
  1217. message: "Successfully edited genres."
  1218. });
  1219. cb({
  1220. status: "success",
  1221. message: "Successfully edited genres."
  1222. });
  1223. }
  1224. }
  1225. );
  1226. }),
  1227. /**
  1228. * Gets a list of all artists
  1229. *
  1230. * @param session
  1231. * @param cb
  1232. */
  1233. getArtists: isAdminRequired(function getArtists(session, cb) {
  1234. async.waterfall(
  1235. [
  1236. next => {
  1237. SongsModule.runJob("GET_ARTISTS", this)
  1238. .then(res => {
  1239. next(null, res.artists);
  1240. })
  1241. .catch(next);
  1242. }
  1243. ],
  1244. async (err, artists) => {
  1245. if (err && err !== true) {
  1246. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1247. this.log("ERROR", "GET_ARTISTS", `User ${session.userId} failed to get artists. '${err}'`);
  1248. cb({ status: "error", message: err });
  1249. } else {
  1250. this.log("SUCCESS", "GET_ARTISTS", `User ${session.userId} has successfully got the artists.`);
  1251. cb({
  1252. status: "success",
  1253. message: "Successfully got artists.",
  1254. data: {
  1255. items: artists
  1256. }
  1257. });
  1258. }
  1259. }
  1260. );
  1261. }),
  1262. /**
  1263. * Bulk update artists for selected songs
  1264. *
  1265. * @param session
  1266. * @param method Whether to add, remove or replace artists
  1267. * @param artists Array of artists to apply
  1268. * @param songIds Array of songIds to apply artists to
  1269. * @param cb
  1270. */
  1271. editArtists: isAdminRequired(async function editArtists(session, method, artists, songIds, cb) {
  1272. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1273. this.keepLongJob();
  1274. this.publishProgress({
  1275. status: "started",
  1276. title: "Bulk editing artists",
  1277. message: "Updating artists.",
  1278. id: this.toString()
  1279. });
  1280. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1281. await CacheModule.runJob(
  1282. "PUB",
  1283. {
  1284. channel: "longJob.added",
  1285. value: { jobId: this.toString(), userId: session.userId }
  1286. },
  1287. this
  1288. );
  1289. async.waterfall(
  1290. [
  1291. next => {
  1292. songModel.find({ _id: { $in: songIds } }, next);
  1293. },
  1294. (songs, next) => {
  1295. const songsFound = songs.map(song => song._id);
  1296. if (songsFound.length > 0) next(null, songsFound);
  1297. else next("None of the specified songs were found.");
  1298. },
  1299. (songsFound, next) => {
  1300. const query = {};
  1301. if (method === "add") {
  1302. query.$addToSet = { artists: { $each: artists } };
  1303. } else if (method === "remove") {
  1304. query.$pullAll = { artists };
  1305. } else if (method === "replace") {
  1306. query.$set = { artists };
  1307. } else {
  1308. next("Invalid method.");
  1309. return;
  1310. }
  1311. this.publishProgress({
  1312. status: "update",
  1313. message: "Updating artists in MongoDB."
  1314. });
  1315. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1316. if (err) {
  1317. next(err);
  1318. return;
  1319. }
  1320. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1321. next();
  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: isAdminRequired(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: isAdminRequired(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. };