songs.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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 RatingsModule = moduleManager.modules.ratings;
  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} songIds - the song ids
  260. * @param {Function} cb
  261. */
  262. getSongsFromSongIds: isAdminRequired(function getSongFromSongId(session, songIds, cb) {
  263. async.waterfall(
  264. [
  265. next => {
  266. SongsModule.runJob(
  267. "GET_SONGS",
  268. {
  269. songIds,
  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. PlaylistsModule.runJob("GET_PLAYLISTS_WITH_SONG", { songId }, this)
  404. .then(res => {
  405. async.eachLimit(
  406. res.playlists,
  407. 1,
  408. (playlist, next) => {
  409. WSModule.runJob(
  410. "RUN_ACTION2",
  411. {
  412. session,
  413. namespace: "playlists",
  414. action: "removeSongFromPlaylist",
  415. args: [song.youtubeId, playlist._id]
  416. },
  417. this
  418. )
  419. .then(res => {
  420. if (res.status === "error") next(res.message);
  421. else next();
  422. })
  423. .catch(err => {
  424. next(err);
  425. });
  426. },
  427. err => {
  428. if (err) next(err);
  429. else next(null, song);
  430. }
  431. );
  432. })
  433. .catch(err => next(err));
  434. },
  435. (song, next) => {
  436. stationModel.find({ "queue._id": songId }, (err, stations) => {
  437. if (err) next(err);
  438. else {
  439. async.eachLimit(
  440. stations,
  441. 1,
  442. (station, next) => {
  443. WSModule.runJob(
  444. "RUN_ACTION2",
  445. {
  446. session,
  447. namespace: "stations",
  448. action: "removeFromQueue",
  449. args: [station._id, song.youtubeId]
  450. },
  451. this
  452. )
  453. .then(res => {
  454. if (
  455. res.status === "error" &&
  456. res.message !== "Station not found" &&
  457. res.message !== "Song is not currently in the queue."
  458. )
  459. next(res.message);
  460. else next();
  461. })
  462. .catch(err => {
  463. next(err);
  464. });
  465. },
  466. err => {
  467. if (err) next(err);
  468. else next(null, song);
  469. }
  470. );
  471. }
  472. });
  473. },
  474. (song, next) => {
  475. stationModel.find({ "currentSong._id": songId }, (err, stations) => {
  476. if (err) next(err);
  477. else {
  478. async.eachLimit(
  479. stations,
  480. 1,
  481. (station, next) => {
  482. StationsModule.runJob(
  483. "SKIP_STATION",
  484. { stationId: station._id, natural: false },
  485. this
  486. )
  487. .then(() => {
  488. next();
  489. })
  490. .catch(err => {
  491. if (err.message === "Station not found.") next();
  492. else next(err);
  493. });
  494. },
  495. err => {
  496. if (err) next(err);
  497. else next(null, song);
  498. }
  499. );
  500. }
  501. });
  502. },
  503. (song, next) => {
  504. RatingsModule.runJob("REMOVE_RATINGS", { youtubeIds: song.youtubeId }, this)
  505. .then(() => next())
  506. .catch(next);
  507. },
  508. next => {
  509. songModel.deleteOne({ _id: songId }, err => {
  510. if (err) next(err);
  511. else next();
  512. });
  513. },
  514. next => {
  515. CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  516. .then(() => {
  517. next();
  518. })
  519. .catch(next);
  520. }
  521. ],
  522. async err => {
  523. if (err) {
  524. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  525. this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  526. return cb({ status: "error", message: err });
  527. }
  528. this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  529. CacheModule.runJob("PUB", {
  530. channel: "song.removed",
  531. value: { songId }
  532. });
  533. return cb({
  534. status: "success",
  535. message: "Song has been successfully removed"
  536. });
  537. }
  538. );
  539. }),
  540. /**
  541. * Removes many songs
  542. *
  543. * @param session
  544. * @param songIds - array of song ids
  545. * @param cb
  546. */
  547. removeMany: isAdminRequired(async function remove(session, songIds, cb) {
  548. const successful = [];
  549. const failed = [];
  550. async.waterfall(
  551. [
  552. next => {
  553. async.eachLimit(
  554. songIds,
  555. 1,
  556. (songId, next) => {
  557. WSModule.runJob(
  558. "RUN_ACTION2",
  559. {
  560. session,
  561. namespace: "songs",
  562. action: "remove",
  563. args: [songId]
  564. },
  565. this
  566. )
  567. .then(res => {
  568. if (res.status === "error") failed.push(songId);
  569. else successful.push(songId);
  570. next();
  571. })
  572. .catch(err => {
  573. next(err);
  574. });
  575. },
  576. err => {
  577. if (err) next(err);
  578. else next();
  579. }
  580. );
  581. }
  582. ],
  583. async err => {
  584. if (err) {
  585. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  586. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  587. return cb({ status: "error", message: err });
  588. }
  589. let message = "";
  590. if (successful.length === 1) message += `1 song has been successfully removed`;
  591. else message += `${successful.length} songs have been successfully removed`;
  592. if (failed.length > 0) {
  593. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  594. if (failed.length === 1) message += `, failed to remove 1 song`;
  595. else message += `, failed to remove ${failed.length} songs`;
  596. }
  597. this.log("SUCCESS", "SONGS_REMOVE_MANY", `${message} "${successful.join(", ")}"`);
  598. return cb({
  599. status: "success",
  600. message
  601. });
  602. }
  603. );
  604. }),
  605. /**
  606. * Searches through official songs
  607. *
  608. * @param {object} session - the session object automatically added by the websocket
  609. * @param {string} query - the query
  610. * @param {string} page - the page
  611. * @param {Function} cb - gets called with the result
  612. */
  613. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  614. async.waterfall(
  615. [
  616. next => {
  617. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  618. else next();
  619. },
  620. next => {
  621. SongsModule.runJob("SEARCH", {
  622. query,
  623. includeVerified: true,
  624. trimmed: true,
  625. page
  626. })
  627. .then(response => {
  628. next(null, response);
  629. })
  630. .catch(err => {
  631. next(err);
  632. });
  633. }
  634. ],
  635. async (err, data) => {
  636. if (err) {
  637. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  638. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  639. return cb({ status: "error", message: err });
  640. }
  641. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  642. return cb({ status: "success", data });
  643. }
  644. );
  645. }),
  646. /**
  647. * Verifies a song
  648. *
  649. * @param session
  650. * @param songId - the song id
  651. * @param cb
  652. */
  653. verify: isAdminRequired(async function add(session, songId, cb) {
  654. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  655. async.waterfall(
  656. [
  657. next => {
  658. SongModel.findOne({ _id: songId }, next);
  659. },
  660. (song, next) => {
  661. if (!song) return next("This song is not in the database.");
  662. return next(null, song);
  663. },
  664. (song, next) => {
  665. const oldStatus = false;
  666. song.verifiedBy = session.userId;
  667. song.verifiedAt = Date.now();
  668. song.verified = true;
  669. song.save(err => next(err, song, oldStatus));
  670. },
  671. (song, oldStatus, next) => {
  672. song.genres.forEach(genre => {
  673. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true })
  674. .then(() => {})
  675. .catch(() => {});
  676. });
  677. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  678. next(null, song, oldStatus);
  679. }
  680. ],
  681. async err => {
  682. if (err) {
  683. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  684. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  685. return cb({ status: "error", message: err });
  686. }
  687. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  688. return cb({
  689. status: "success",
  690. message: "Song has been verified successfully."
  691. });
  692. }
  693. );
  694. // TODO Check if video is in queue and Add the song to the appropriate stations
  695. }),
  696. /**
  697. * Verify many songs
  698. *
  699. * @param session
  700. * @param songIds - array of song ids
  701. * @param cb
  702. */
  703. verifyMany: isAdminRequired(async function verifyMany(session, songIds, cb) {
  704. const successful = [];
  705. const failed = [];
  706. async.waterfall(
  707. [
  708. next => {
  709. async.eachLimit(
  710. songIds,
  711. 1,
  712. (songId, next) => {
  713. WSModule.runJob(
  714. "RUN_ACTION2",
  715. {
  716. session,
  717. namespace: "songs",
  718. action: "verify",
  719. args: [songId]
  720. },
  721. this
  722. )
  723. .then(res => {
  724. if (res.status === "error") failed.push(songId);
  725. else successful.push(songId);
  726. next();
  727. })
  728. .catch(err => {
  729. next(err);
  730. });
  731. },
  732. err => {
  733. if (err) next(err);
  734. else next();
  735. }
  736. );
  737. }
  738. ],
  739. async err => {
  740. if (err) {
  741. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  742. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  743. return cb({ status: "error", message: err });
  744. }
  745. let message = "";
  746. if (successful.length === 1) message += `1 song has been successfully verified`;
  747. else message += `${successful.length} songs have been successfully verified`;
  748. if (failed.length > 0) {
  749. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  750. if (failed.length === 1) message += `, failed to verify 1 song`;
  751. else message += `, failed to verify ${failed.length} songs`;
  752. }
  753. this.log("SUCCESS", "SONGS_VERIFY_MANY", `${message} "${successful.join(", ")}"`);
  754. return cb({
  755. status: "success",
  756. message
  757. });
  758. }
  759. );
  760. }),
  761. /**
  762. * Un-verifies a song
  763. *
  764. * @param session
  765. * @param songId - the song id
  766. * @param cb
  767. */
  768. unverify: isAdminRequired(async function add(session, songId, cb) {
  769. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  770. async.waterfall(
  771. [
  772. next => {
  773. SongModel.findOne({ _id: songId }, next);
  774. },
  775. (song, next) => {
  776. if (!song) return next("This song is not in the database.");
  777. return next(null, song);
  778. },
  779. (song, next) => {
  780. song.verified = false;
  781. song.verifiedBy = null;
  782. song.verifiedAt = null;
  783. song.save(err => {
  784. next(err, song);
  785. });
  786. },
  787. (song, next) => {
  788. song.genres.forEach(genre => {
  789. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: false })
  790. .then(() => {})
  791. .catch(() => {});
  792. });
  793. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  794. next(null);
  795. }
  796. ],
  797. async err => {
  798. if (err) {
  799. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  800. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  801. return cb({ status: "error", message: err });
  802. }
  803. this.log(
  804. "SUCCESS",
  805. "SONGS_UNVERIFY",
  806. `User "${session.userId}" successfully unverified song "${songId}".`
  807. );
  808. return cb({
  809. status: "success",
  810. message: "Song has been unverified successfully."
  811. });
  812. }
  813. );
  814. // TODO Check if video is in queue and Add the song to the appropriate stations
  815. }),
  816. /**
  817. * Unverify many songs
  818. *
  819. * @param session
  820. * @param songIds - array of song ids
  821. * @param cb
  822. */
  823. unverifyMany: isAdminRequired(async function unverifyMany(session, songIds, cb) {
  824. const successful = [];
  825. const failed = [];
  826. async.waterfall(
  827. [
  828. next => {
  829. async.eachLimit(
  830. songIds,
  831. 1,
  832. (songId, next) => {
  833. WSModule.runJob(
  834. "RUN_ACTION2",
  835. {
  836. session,
  837. namespace: "songs",
  838. action: "unverify",
  839. args: [songId]
  840. },
  841. this
  842. )
  843. .then(res => {
  844. if (res.status === "error") failed.push(songId);
  845. else successful.push(songId);
  846. next();
  847. })
  848. .catch(err => {
  849. next(err);
  850. });
  851. },
  852. err => {
  853. if (err) next(err);
  854. else next();
  855. }
  856. );
  857. }
  858. ],
  859. async err => {
  860. if (err) {
  861. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  862. this.log(
  863. "ERROR",
  864. "SONGS_UNVERIFY_MANY",
  865. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  866. );
  867. return cb({ status: "error", message: err });
  868. }
  869. let message = "";
  870. if (successful.length === 1) message += `1 song has been successfully unverified`;
  871. else message += `${successful.length} songs have been successfully unverified`;
  872. if (failed.length > 0) {
  873. this.log(
  874. "ERROR",
  875. "SONGS_UNVERIFY_MANY",
  876. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  877. );
  878. if (failed.length === 1) message += `, failed to unverify 1 song`;
  879. else message += `, failed to unverify ${failed.length} songs`;
  880. }
  881. this.log("SUCCESS", "SONGS_UNVERIFY_MANY", `${message} "${successful.join(", ")}"`);
  882. return cb({
  883. status: "success",
  884. message
  885. });
  886. }
  887. );
  888. }),
  889. /**
  890. * Gets a list of all genres
  891. *
  892. * @param session
  893. * @param cb
  894. */
  895. getGenres: isAdminRequired(function getGenres(session, cb) {
  896. async.waterfall(
  897. [
  898. next => {
  899. SongsModule.runJob("GET_GENRES", this)
  900. .then(res => {
  901. next(null, res.genres);
  902. })
  903. .catch(next);
  904. }
  905. ],
  906. async (err, genres) => {
  907. if (err && err !== true) {
  908. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  909. this.log("ERROR", "GET_GENRES", `User ${session.userId} failed to get genres. '${err}'`);
  910. cb({ status: "error", message: err });
  911. } else {
  912. this.log("SUCCESS", "GET_GENRES", `User ${session.userId} has successfully got the genres.`);
  913. cb({
  914. status: "success",
  915. message: "Successfully got genres.",
  916. data: {
  917. items: genres
  918. }
  919. });
  920. }
  921. }
  922. );
  923. }),
  924. /**
  925. * Bulk update genres for selected songs
  926. *
  927. * @param session
  928. * @param method Whether to add, remove or replace genres
  929. * @param genres Array of genres to apply
  930. * @param songIds Array of songIds to apply genres to
  931. * @param cb
  932. */
  933. editGenres: isAdminRequired(async function editGenres(session, method, genres, songIds, cb) {
  934. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  935. async.waterfall(
  936. [
  937. next => {
  938. songModel.find({ _id: { $in: songIds } }, next);
  939. },
  940. (songs, next) => {
  941. const songsFound = songs.map(song => song._id);
  942. if (songsFound.length > 0) next(null, songsFound);
  943. else next("None of the specified songs were found.");
  944. },
  945. (songsFound, next) => {
  946. const query = {};
  947. if (method === "add") {
  948. query.$addToSet = { genres: { $each: genres } };
  949. } else if (method === "remove") {
  950. query.$pullAll = { genres };
  951. } else if (method === "replace") {
  952. query.$set = { genres };
  953. } else {
  954. next("Invalid method.");
  955. return;
  956. }
  957. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  958. if (err) {
  959. next(err);
  960. return;
  961. }
  962. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  963. next();
  964. });
  965. }
  966. ],
  967. async err => {
  968. if (err && err !== true) {
  969. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  970. this.log("ERROR", "EDIT_GENRES", `User ${session.userId} failed to edit genres. '${err}'`);
  971. cb({ status: "error", message: err });
  972. } else {
  973. this.log("SUCCESS", "EDIT_GENRES", `User ${session.userId} has successfully edited genres.`);
  974. cb({
  975. status: "success",
  976. message: "Successfully edited genres."
  977. });
  978. }
  979. }
  980. );
  981. }),
  982. /**
  983. * Gets a list of all artists
  984. *
  985. * @param session
  986. * @param cb
  987. */
  988. getArtists: isAdminRequired(function getArtists(session, cb) {
  989. async.waterfall(
  990. [
  991. next => {
  992. SongsModule.runJob("GET_ARTISTS", this)
  993. .then(res => {
  994. next(null, res.artists);
  995. })
  996. .catch(next);
  997. }
  998. ],
  999. async (err, artists) => {
  1000. if (err && err !== true) {
  1001. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1002. this.log("ERROR", "GET_ARTISTS", `User ${session.userId} failed to get artists. '${err}'`);
  1003. cb({ status: "error", message: err });
  1004. } else {
  1005. this.log("SUCCESS", "GET_ARTISTS", `User ${session.userId} has successfully got the artists.`);
  1006. cb({
  1007. status: "success",
  1008. message: "Successfully got artists.",
  1009. data: {
  1010. items: artists
  1011. }
  1012. });
  1013. }
  1014. }
  1015. );
  1016. }),
  1017. /**
  1018. * Bulk update artists for selected songs
  1019. *
  1020. * @param session
  1021. * @param method Whether to add, remove or replace artists
  1022. * @param artists Array of artists to apply
  1023. * @param songIds Array of songIds to apply artists to
  1024. * @param cb
  1025. */
  1026. editArtists: isAdminRequired(async function editArtists(session, method, artists, songIds, cb) {
  1027. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1028. async.waterfall(
  1029. [
  1030. next => {
  1031. songModel.find({ _id: { $in: songIds } }, next);
  1032. },
  1033. (songs, next) => {
  1034. const songsFound = songs.map(song => song._id);
  1035. if (songsFound.length > 0) next(null, songsFound);
  1036. else next("None of the specified songs were found.");
  1037. },
  1038. (songsFound, next) => {
  1039. const query = {};
  1040. if (method === "add") {
  1041. query.$addToSet = { artists: { $each: artists } };
  1042. } else if (method === "remove") {
  1043. query.$pullAll = { artists };
  1044. } else if (method === "replace") {
  1045. query.$set = { artists };
  1046. } else {
  1047. next("Invalid method.");
  1048. return;
  1049. }
  1050. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1051. if (err) {
  1052. next(err);
  1053. return;
  1054. }
  1055. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1056. next();
  1057. });
  1058. }
  1059. ],
  1060. async err => {
  1061. if (err && err !== true) {
  1062. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1063. this.log("ERROR", "EDIT_ARTISTS", `User ${session.userId} failed to edit artists. '${err}'`);
  1064. cb({ status: "error", message: err });
  1065. } else {
  1066. this.log("SUCCESS", "EDIT_ARTISTS", `User ${session.userId} has successfully edited artists.`);
  1067. cb({
  1068. status: "success",
  1069. message: "Successfully edited artists."
  1070. });
  1071. }
  1072. }
  1073. );
  1074. }),
  1075. /**
  1076. * Gets a list of all tags
  1077. *
  1078. * @param session
  1079. * @param cb
  1080. */
  1081. getTags: isAdminRequired(function getTags(session, cb) {
  1082. async.waterfall(
  1083. [
  1084. next => {
  1085. SongsModule.runJob("GET_TAGS", this)
  1086. .then(res => {
  1087. next(null, res.tags);
  1088. })
  1089. .catch(next);
  1090. }
  1091. ],
  1092. async (err, tags) => {
  1093. if (err && err !== true) {
  1094. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1095. this.log("ERROR", "GET_TAGS", `User ${session.userId} failed to get tags. '${err}'`);
  1096. cb({ status: "error", message: err });
  1097. } else {
  1098. this.log("SUCCESS", "GET_TAGS", `User ${session.userId} has successfully got the tags.`);
  1099. cb({
  1100. status: "success",
  1101. message: "Successfully got tags.",
  1102. data: {
  1103. items: tags
  1104. }
  1105. });
  1106. }
  1107. }
  1108. );
  1109. }),
  1110. /**
  1111. * Bulk update tags for selected songs
  1112. *
  1113. * @param session
  1114. * @param method Whether to add, remove or replace tags
  1115. * @param tags Array of tags to apply
  1116. * @param songIds Array of songIds to apply tags to
  1117. * @param cb
  1118. */
  1119. editTags: isAdminRequired(async function editTags(session, method, tags, songIds, cb) {
  1120. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1121. async.waterfall(
  1122. [
  1123. next => {
  1124. songModel.find({ _id: { $in: songIds } }, next);
  1125. },
  1126. (songs, next) => {
  1127. const songsFound = songs.map(song => song._id);
  1128. if (songsFound.length > 0) next(null, songsFound);
  1129. else next("None of the specified songs were found.");
  1130. },
  1131. (songsFound, next) => {
  1132. const query = {};
  1133. if (method === "add") {
  1134. query.$addToSet = { tags: { $each: tags } };
  1135. } else if (method === "remove") {
  1136. query.$pullAll = { tags };
  1137. } else if (method === "replace") {
  1138. query.$set = { tags };
  1139. } else {
  1140. next("Invalid method.");
  1141. return;
  1142. }
  1143. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1144. if (err) {
  1145. next(err);
  1146. return;
  1147. }
  1148. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1149. next();
  1150. });
  1151. }
  1152. ],
  1153. async err => {
  1154. if (err && err !== true) {
  1155. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1156. this.log("ERROR", "EDIT_TAGS", `User ${session.userId} failed to edit tags. '${err}'`);
  1157. cb({ status: "error", message: err });
  1158. } else {
  1159. this.log("SUCCESS", "EDIT_TAGS", `User ${session.userId} has successfully edited tags.`);
  1160. cb({
  1161. status: "success",
  1162. message: "Successfully edited tags."
  1163. });
  1164. }
  1165. }
  1166. );
  1167. })
  1168. };