songs.js 40 KB

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