songs.js 33 KB

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