songs.js 36 KB

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