songs.js 32 KB

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