songs.js 36 KB

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