songs.js 41 KB

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