songs.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. import async from "async";
  2. import config from "config";
  3. import mongoose from "mongoose";
  4. import CoreClass from "../core";
  5. let SongsModule;
  6. let CacheModule;
  7. let DBModule;
  8. let UtilsModule;
  9. let YouTubeModule;
  10. let StationsModule;
  11. let PlaylistsModule;
  12. class ErrorWithData extends Error {
  13. /**
  14. * @param {string} message - the error message
  15. * @param {object} data - the error data
  16. */
  17. constructor(message, data) {
  18. super(message);
  19. this.data = data;
  20. }
  21. }
  22. class _SongsModule extends CoreClass {
  23. // eslint-disable-next-line require-jsdoc
  24. constructor() {
  25. super("songs");
  26. SongsModule = this;
  27. }
  28. /**
  29. * Initialises the songs module
  30. *
  31. * @returns {Promise} - returns promise (reject, resolve)
  32. */
  33. async initialize() {
  34. this.setStage(1);
  35. CacheModule = this.moduleManager.modules.cache;
  36. DBModule = this.moduleManager.modules.db;
  37. UtilsModule = this.moduleManager.modules.utils;
  38. YouTubeModule = this.moduleManager.modules.youtube;
  39. StationsModule = this.moduleManager.modules.stations;
  40. PlaylistsModule = this.moduleManager.modules.playlists;
  41. this.SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" });
  42. this.SongSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "song" });
  43. this.setStage(2);
  44. return new Promise((resolve, reject) =>
  45. async.waterfall(
  46. [
  47. next => {
  48. this.setStage(2);
  49. CacheModule.runJob("HGETALL", { table: "songs" })
  50. .then(songs => {
  51. next(null, songs);
  52. })
  53. .catch(next);
  54. },
  55. (songs, next) => {
  56. this.setStage(3);
  57. if (!songs) return next();
  58. const youtubeIds = Object.keys(songs);
  59. return async.each(
  60. youtubeIds,
  61. (youtubeId, next) => {
  62. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => {
  63. if (err) next(err);
  64. else if (!song)
  65. CacheModule.runJob("HDEL", {
  66. table: "songs",
  67. key: youtubeId
  68. })
  69. .then(() => next())
  70. .catch(next);
  71. else next();
  72. });
  73. },
  74. next
  75. );
  76. },
  77. next => {
  78. this.setStage(4);
  79. SongsModule.SongModel.find({}, next);
  80. },
  81. (songs, next) => {
  82. this.setStage(5);
  83. async.each(
  84. songs,
  85. (song, next) => {
  86. CacheModule.runJob("HSET", {
  87. table: "songs",
  88. key: song.youtubeId,
  89. value: SongsModule.SongSchemaCache(song)
  90. })
  91. .then(() => next())
  92. .catch(next);
  93. },
  94. next
  95. );
  96. }
  97. ],
  98. async err => {
  99. if (err) {
  100. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  101. reject(new Error(err));
  102. } else resolve();
  103. }
  104. )
  105. );
  106. }
  107. /**
  108. * Gets a song by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  109. *
  110. * @param {object} payload - object containing the payload
  111. * @param {string} payload.songId - the id of the song we are trying to get
  112. * @returns {Promise} - returns a promise (resolve, reject)
  113. */
  114. GET_SONG(payload) {
  115. return new Promise((resolve, reject) =>
  116. async.waterfall(
  117. [
  118. next => {
  119. if (!mongoose.Types.ObjectId.isValid(payload.songId))
  120. return next("songId is not a valid ObjectId.");
  121. return CacheModule.runJob("HGET", { table: "songs", key: payload.songId }, this)
  122. .then(song => next(null, song))
  123. .catch(next);
  124. },
  125. (song, next) => {
  126. if (song) return next(true, song);
  127. return SongsModule.SongModel.findOne({ _id: payload.songId }, next);
  128. },
  129. (song, next) => {
  130. if (song) {
  131. CacheModule.runJob(
  132. "HSET",
  133. {
  134. table: "songs",
  135. key: payload.songId,
  136. value: song
  137. },
  138. this
  139. ).then(song => next(null, song));
  140. } else next("Song not found.");
  141. }
  142. ],
  143. (err, song) => {
  144. if (err && err !== true) return reject(new Error(err));
  145. return resolve({ song });
  146. }
  147. )
  148. );
  149. }
  150. /**
  151. * Gets songs by id from Mongo
  152. *
  153. * @param {object} payload - object containing the payload
  154. * @param {string} payload.songIds - the ids of the songs we are trying to get
  155. * @param {string} payload.properties - the properties to return
  156. * @returns {Promise} - returns a promise (resolve, reject)
  157. */
  158. GET_SONGS(payload) {
  159. return new Promise((resolve, reject) =>
  160. async.waterfall(
  161. [
  162. next => {
  163. if (!payload.songIds.every(songId => mongoose.Types.ObjectId.isValid(songId)))
  164. next("One or more songIds are not a valid ObjectId.");
  165. else next();
  166. },
  167. next => {
  168. const includeProperties = {};
  169. payload.properties.forEach(property => {
  170. includeProperties[property] = true;
  171. });
  172. return SongsModule.SongModel.find(
  173. {
  174. _id: { $in: payload.songIds }
  175. },
  176. includeProperties,
  177. next
  178. );
  179. }
  180. ],
  181. (err, songs) => {
  182. if (err && err !== true) return reject(new Error(err));
  183. return resolve({ songs });
  184. }
  185. )
  186. );
  187. }
  188. /**
  189. * Makes sure that if a song is not currently in the songs db, to add it
  190. *
  191. * @param {object} payload - an object containing the payload
  192. * @param {string} payload.youtubeId - the youtube song id of the song we are trying to ensure is in the songs db
  193. * @param {string} payload.userId - the youtube song id of the song we are trying to ensure is in the songs db
  194. * @param {string} payload.automaticallyRequested - whether the song was automatically requested or not
  195. * @returns {Promise} - returns a promise (resolve, reject)
  196. */
  197. ENSURE_SONG_EXISTS_BY_YOUTUBE_ID(payload) {
  198. return new Promise((resolve, reject) =>
  199. async.waterfall(
  200. [
  201. next => {
  202. SongsModule.SongModel.findOne({ youtubeId: payload.youtubeId }, next);
  203. },
  204. (song, next) => {
  205. if (song && song.duration > 0) next(true, song);
  206. else {
  207. YouTubeModule.runJob("GET_SONG", { youtubeId: payload.youtubeId }, this)
  208. .then(response => {
  209. next(null, song, response.song);
  210. })
  211. .catch(next);
  212. }
  213. },
  214. (song, youtubeSong, next) => {
  215. if (song && song.duration <= 0) {
  216. song.duration = youtubeSong.duration;
  217. song.save({ validateBeforeSave: true }, err => {
  218. if (err) return next(err, song);
  219. return next(null, song);
  220. });
  221. } else {
  222. const status =
  223. (!payload.userId && config.get("hideAnonymousSongs")) ||
  224. (payload.automaticallyRequested && config.get("hideAutomaticallyRequestedSongs"))
  225. ? "hidden"
  226. : "unverified";
  227. const song = new SongsModule.SongModel({
  228. ...youtubeSong,
  229. status,
  230. requestedBy: payload.userId,
  231. requestedAt: Date.now()
  232. });
  233. song.save({ validateBeforeSave: true }, err => {
  234. if (err) return next(err, song);
  235. return next(null, song);
  236. });
  237. }
  238. }
  239. ],
  240. (err, song) => {
  241. if (err && err !== true) return reject(new Error(err));
  242. return resolve({ song });
  243. }
  244. )
  245. );
  246. }
  247. /**
  248. * Gets a song by youtube id
  249. *
  250. * @param {object} payload - an object containing the payload
  251. * @param {string} payload.youtubeId - the youtube id of the song we are trying to get
  252. * @returns {Promise} - returns a promise (resolve, reject)
  253. */
  254. GET_SONG_FROM_YOUTUBE_ID(payload) {
  255. return new Promise((resolve, reject) =>
  256. async.waterfall(
  257. [
  258. next => {
  259. SongsModule.SongModel.findOne({ youtubeId: payload.youtubeId }, next);
  260. }
  261. ],
  262. (err, song) => {
  263. if (err && err !== true) return reject(new Error(err));
  264. return resolve({ song });
  265. }
  266. )
  267. );
  268. }
  269. /**
  270. * Gets a song from id from Mongo and updates the cache with it
  271. *
  272. * @param {object} payload - an object containing the payload
  273. * @param {string} payload.songId - the id of the song we are trying to update
  274. * @param {string} payload.oldStatus - old status of song being updated (optional)
  275. * @returns {Promise} - returns a promise (resolve, reject)
  276. */
  277. UPDATE_SONG(payload) {
  278. return new Promise((resolve, reject) =>
  279. async.waterfall(
  280. [
  281. next => {
  282. SongsModule.SongModel.findOne({ _id: payload.songId }, next);
  283. },
  284. (song, next) => {
  285. if (!song) {
  286. CacheModule.runJob("HDEL", {
  287. table: "songs",
  288. key: payload.songId
  289. });
  290. return next("Song not found.");
  291. }
  292. return CacheModule.runJob(
  293. "HSET",
  294. {
  295. table: "songs",
  296. key: payload.songId,
  297. value: song
  298. },
  299. this
  300. )
  301. .then(song => {
  302. next(null, song);
  303. })
  304. .catch(next);
  305. },
  306. (song, next) => {
  307. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  308. const trimmedSong = {
  309. _id,
  310. youtubeId,
  311. title,
  312. artists,
  313. thumbnail,
  314. duration,
  315. status
  316. };
  317. this.log("INFO", `Going to update playlists now for song ${_id}`);
  318. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this)
  319. .then(playlistModel => {
  320. playlistModel.updateMany(
  321. { "songs._id": song._id },
  322. { $set: { "songs.$": trimmedSong } },
  323. err => {
  324. if (err) next(err);
  325. else
  326. playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  327. if (err) next(err);
  328. else {
  329. async.eachLimit(
  330. playlists,
  331. 1,
  332. (playlist, next) => {
  333. PlaylistsModule.runJob(
  334. "UPDATE_PLAYLIST",
  335. {
  336. playlistId: playlist._id
  337. },
  338. this
  339. )
  340. .then(() => {
  341. next();
  342. })
  343. .catch(err => {
  344. next(err);
  345. });
  346. },
  347. err => {
  348. if (err) next(err);
  349. else next(null, song);
  350. }
  351. );
  352. }
  353. });
  354. }
  355. );
  356. })
  357. .catch(err => {
  358. next(err);
  359. });
  360. },
  361. (song, next) => {
  362. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  363. this.log("INFO", `Going to update stations now for song ${_id}`);
  364. DBModule.runJob("GET_MODEL", { modelName: "station" }, this)
  365. .then(stationModel => {
  366. stationModel.updateMany(
  367. { "queue._id": song._id },
  368. {
  369. $set: {
  370. "queue.$.youtubeId": youtubeId,
  371. "queue.$.title": title,
  372. "queue.$.artists": artists,
  373. "queue.$.thumbnail": thumbnail,
  374. "queue.$.duration": duration,
  375. "queue.$.status": status
  376. }
  377. },
  378. err => {
  379. if (err) this.log("ERROR", err);
  380. else
  381. stationModel.find({ "queue._id": song._id }, (err, stations) => {
  382. if (err) next(err);
  383. else {
  384. async.eachLimit(
  385. stations,
  386. 1,
  387. (station, next) => {
  388. StationsModule.runJob(
  389. "UPDATE_STATION",
  390. { stationId: station._id },
  391. this
  392. )
  393. .then(() => {
  394. next();
  395. })
  396. .catch(err => {
  397. next(err);
  398. });
  399. },
  400. err => {
  401. if (err) next(err);
  402. else next(null, song);
  403. }
  404. );
  405. }
  406. });
  407. }
  408. );
  409. })
  410. .catch(err => {
  411. next(err);
  412. });
  413. },
  414. (song, next) => {
  415. async.eachLimit(
  416. song.genres,
  417. 1,
  418. (genre, next) => {
  419. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  420. .then(() => {
  421. next();
  422. })
  423. .catch(err => next(err));
  424. },
  425. err => {
  426. next(err, song);
  427. }
  428. );
  429. }
  430. ],
  431. (err, song) => {
  432. if (err && err !== true) return reject(new Error(err));
  433. if (!payload.oldStatus) payload.oldStatus = null;
  434. CacheModule.runJob("PUB", {
  435. channel: "song.updated",
  436. value: { songId: song._id, oldStatus: payload.oldStatus }
  437. });
  438. return resolve(song);
  439. }
  440. )
  441. );
  442. }
  443. /**
  444. * Updates all songs
  445. *
  446. * @returns {Promise} - returns a promise (resolve, reject)
  447. */
  448. UPDATE_ALL_SONGS() {
  449. return new Promise((resolve, reject) =>
  450. async.waterfall(
  451. [
  452. next => {
  453. SongsModule.SongModel.find({}, next);
  454. },
  455. (songs, next) => {
  456. let index = 0;
  457. const { length } = songs;
  458. async.eachLimit(
  459. songs,
  460. 2,
  461. (song, next) => {
  462. index += 1;
  463. console.log(`Updating song #${index} out of ${length}: ${song._id}`);
  464. SongsModule.runJob("UPDATE_SONG", { songId: song._id }, this)
  465. .then(() => {
  466. next();
  467. })
  468. .catch(err => {
  469. next(err);
  470. });
  471. },
  472. err => {
  473. next(err);
  474. }
  475. );
  476. }
  477. ],
  478. err => {
  479. if (err && err !== true) return reject(new Error(err));
  480. return resolve();
  481. }
  482. )
  483. );
  484. }
  485. // /**
  486. // * Deletes song from id from Mongo and cache
  487. // *
  488. // * @param {object} payload - returns an object containing the payload
  489. // * @param {string} payload.songId - the song id of the song we are trying to delete
  490. // * @returns {Promise} - returns a promise (resolve, reject)
  491. // */
  492. // DELETE_SONG(payload) {
  493. // return new Promise((resolve, reject) =>
  494. // async.waterfall(
  495. // [
  496. // next => {
  497. // SongsModule.SongModel.deleteOne({ _id: payload.songId }, next);
  498. // },
  499. // next => {
  500. // CacheModule.runJob(
  501. // "HDEL",
  502. // {
  503. // table: "songs",
  504. // key: payload.songId
  505. // },
  506. // this
  507. // )
  508. // .then(() => next())
  509. // .catch(next);
  510. // },
  511. // next => {
  512. // this.log("INFO", `Going to update playlists and stations now for deleted song ${payload.songId}`);
  513. // DBModule.runJob("GET_MODEL", { modelName: "playlist" }).then(playlistModel => {
  514. // playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  515. // if (err) this.log("ERROR", err);
  516. // else {
  517. // playlistModel.updateMany(
  518. // { "songs._id": payload.songId },
  519. // { $pull: { "songs.$._id": payload.songId} },
  520. // err => {
  521. // if (err) this.log("ERROR", err);
  522. // else {
  523. // playlists.forEach(playlist => {
  524. // PlaylistsModule.runJob("UPDATE_PLAYLIST", {
  525. // playlistId: playlist._id
  526. // });
  527. // });
  528. // }
  529. // }
  530. // );
  531. // }
  532. // });
  533. // });
  534. // DBModule.runJob("GET_MODEL", { modelName: "station" }).then(stationModel => {
  535. // stationModel.find({ "queue._id": payload.songId }, (err, stations) => {
  536. // stationModel.updateMany(
  537. // { "queue._id": payload.songId },
  538. // {
  539. // $pull: { "queue._id": }
  540. // },
  541. // err => {
  542. // if (err) this.log("ERROR", err);
  543. // else {
  544. // stations.forEach(station => {
  545. // StationsModule.runJob("UPDATE_STATION", { stationId: station._id });
  546. // });
  547. // }
  548. // }
  549. // );
  550. // });
  551. // });
  552. // }
  553. // ],
  554. // err => {
  555. // if (err && err !== true) return reject(new Error(err));
  556. // return resolve();
  557. // }
  558. // )
  559. // );
  560. // }
  561. /**
  562. * Searches through songs
  563. *
  564. * @param {object} payload - object that contains the payload
  565. * @param {string} payload.query - the query
  566. * @param {string} payload.includeHidden - include hidden songs
  567. * @param {string} payload.includeUnverified - include unverified songs
  568. * @param {string} payload.includeVerified - include verified songs
  569. * @param {string} payload.trimmed - include trimmed songs
  570. * @param {string} payload.page - page (default 1)
  571. * @returns {Promise} - returns promise (reject, resolve)
  572. */
  573. SEARCH(payload) {
  574. return new Promise((resolve, reject) =>
  575. async.waterfall(
  576. [
  577. next => {
  578. const statuses = [];
  579. if (payload.includeHidden) statuses.push("hidden");
  580. if (payload.includeUnverified) statuses.push("unverified");
  581. if (payload.includeVerified) statuses.push("verified");
  582. if (statuses.length === 0) return next("No statuses have been included.");
  583. let { query } = payload;
  584. const isRegex =
  585. query.length > 2 && query.indexOf("/") === 0 && query.lastIndexOf("/") === query.length - 1;
  586. if (isRegex) query = query.slice(1, query.length - 1);
  587. else query = query.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
  588. const filterArray = [
  589. {
  590. title: new RegExp(`${query}`, "i"),
  591. status: { $in: statuses }
  592. },
  593. {
  594. artists: new RegExp(`${query}`, "i"),
  595. status: { $in: statuses }
  596. }
  597. ];
  598. return next(null, filterArray);
  599. },
  600. (filterArray, next) => {
  601. const page = payload.page ? payload.page : 1;
  602. const pageSize = 15;
  603. const skipAmount = pageSize * (page - 1);
  604. SongsModule.SongModel.find({ $or: filterArray }).count((err, count) => {
  605. if (err) next(err);
  606. else {
  607. SongsModule.SongModel.find({ $or: filterArray })
  608. .skip(skipAmount)
  609. .limit(pageSize)
  610. .exec((err, songs) => {
  611. if (err) next(err);
  612. else {
  613. next(null, {
  614. songs,
  615. page,
  616. pageSize,
  617. skipAmount,
  618. count
  619. });
  620. }
  621. });
  622. }
  623. });
  624. },
  625. (data, next) => {
  626. if (data.songs.length === 0) next("No songs found");
  627. else if (payload.trimmed) {
  628. next(null, {
  629. songs: data.songs.map(song => {
  630. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  631. return {
  632. _id,
  633. youtubeId,
  634. title,
  635. artists,
  636. thumbnail,
  637. duration,
  638. status
  639. };
  640. }),
  641. ...data
  642. });
  643. } else next(null, data);
  644. }
  645. ],
  646. (err, data) => {
  647. if (err && err !== true) return reject(new Error(err));
  648. return resolve(data);
  649. }
  650. )
  651. );
  652. }
  653. /**
  654. * Recalculates dislikes and likes for a song
  655. *
  656. * @param {object} payload - returns an object containing the payload
  657. * @param {string} payload.youtubeId - the youtube id of the song
  658. * @param {string} payload.songId - the song id of the song
  659. * @returns {Promise} - returns a promise (resolve, reject)
  660. */
  661. async RECALCULATE_SONG_RATINGS(payload) {
  662. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  663. return new Promise((resolve, reject) => {
  664. async.waterfall(
  665. [
  666. next => {
  667. playlistModel.countDocuments(
  668. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, type: "user-liked" },
  669. (err, likes) => {
  670. if (err) return next(err);
  671. return next(null, likes);
  672. }
  673. );
  674. },
  675. (likes, next) => {
  676. playlistModel.countDocuments(
  677. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, type: "user-disliked" },
  678. (err, dislikes) => {
  679. if (err) return next(err);
  680. return next(err, { likes, dislikes });
  681. }
  682. );
  683. },
  684. ({ likes, dislikes }, next) => {
  685. SongsModule.SongModel.updateOne(
  686. { _id: payload.songId },
  687. {
  688. $set: {
  689. likes,
  690. dislikes
  691. }
  692. },
  693. err => next(err, { likes, dislikes })
  694. );
  695. }
  696. ],
  697. (err, { likes, dislikes }) => {
  698. if (err) return reject(new Error(err));
  699. return resolve({ likes, dislikes });
  700. }
  701. );
  702. });
  703. }
  704. /**
  705. * Recalculates dislikes and likes for all songs
  706. *
  707. * @returns {Promise} - returns a promise (resolve, reject)
  708. */
  709. RECALCULATE_ALL_SONG_RATINGS() {
  710. return new Promise((resolve, reject) => {
  711. async.waterfall(
  712. [
  713. next => {
  714. SongsModule.SongModel.find({}, { _id: true }, next);
  715. },
  716. (songs, next) => {
  717. let index = 0;
  718. const { length } = songs;
  719. async.eachLimit(
  720. songs,
  721. 2,
  722. (song, next) => {
  723. index += 1;
  724. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id }, this)
  725. .then(() => {
  726. next();
  727. })
  728. .catch(err => {
  729. next(err);
  730. });
  731. },
  732. err => {
  733. next(err);
  734. }
  735. );
  736. }
  737. ],
  738. err => {
  739. if (err) return reject(new Error(err));
  740. return resolve();
  741. }
  742. );
  743. });
  744. }
  745. /**
  746. * Gets an array of all genres
  747. *
  748. * @returns {Promise} - returns a promise (resolve, reject)
  749. */
  750. GET_ALL_GENRES() {
  751. return new Promise((resolve, reject) =>
  752. async.waterfall(
  753. [
  754. next => {
  755. SongsModule.SongModel.find({ status: "verified" }, { genres: 1, _id: false }, next);
  756. },
  757. (songs, next) => {
  758. let allGenres = [];
  759. songs.forEach(song => {
  760. allGenres = allGenres.concat(song.genres);
  761. });
  762. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  763. const uniqueGenres = lowerCaseGenres.filter(
  764. (value, index, self) => self.indexOf(value) === index
  765. );
  766. next(null, uniqueGenres);
  767. }
  768. ],
  769. (err, genres) => {
  770. if (err && err !== true) return reject(new Error(err));
  771. return resolve({ genres });
  772. }
  773. )
  774. );
  775. }
  776. /**
  777. * Gets an array of all songs with a specific genre
  778. *
  779. * @param {object} payload - returns an object containing the payload
  780. * @param {string} payload.genre - the genre
  781. * @returns {Promise} - returns a promise (resolve, reject)
  782. */
  783. GET_ALL_SONGS_WITH_GENRE(payload) {
  784. return new Promise((resolve, reject) =>
  785. async.waterfall(
  786. [
  787. next => {
  788. SongsModule.SongModel.find(
  789. {
  790. status: "verified",
  791. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  792. },
  793. next
  794. );
  795. }
  796. ],
  797. (err, songs) => {
  798. if (err && err !== true) return reject(new Error(err));
  799. return resolve({ songs });
  800. }
  801. )
  802. );
  803. }
  804. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  805. /**
  806. * Gets a orphaned playlist songs
  807. *
  808. * @returns {Promise} - returns promise (reject, resolve)
  809. */
  810. GET_ORPHANED_PLAYLIST_SONGS() {
  811. return new Promise((resolve, reject) => {
  812. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  813. playlistModel.find({}, (err, playlists) => {
  814. if (err) reject(new Error(err));
  815. else {
  816. SongsModule.SongModel.find({}, { _id: true, youtubeId: true }, (err, songs) => {
  817. if (err) reject(new Error(err));
  818. else {
  819. const songIds = songs.map(song => song._id.toString());
  820. const orphanedYoutubeIds = new Set();
  821. async.eachLimit(
  822. playlists,
  823. 1,
  824. (playlist, next) => {
  825. playlist.songs.forEach(song => {
  826. if (
  827. (!song._id || songIds.indexOf(song._id.toString() === -1)) &&
  828. !orphanedYoutubeIds.has(song.youtubeId)
  829. ) {
  830. orphanedYoutubeIds.add(song.youtubeId);
  831. }
  832. });
  833. next();
  834. },
  835. () => {
  836. resolve({ youtubeIds: Array.from(orphanedYoutubeIds) });
  837. }
  838. );
  839. }
  840. });
  841. }
  842. });
  843. });
  844. });
  845. }
  846. /**
  847. * Requests a song, adding it to the DB
  848. *
  849. * @param {object} payload - The payload
  850. * @param {string} payload.youtubeId - The YouTube song id of the song
  851. * @param {string} payload.userId - The user id of the person requesting the song
  852. * @returns {Promise} - returns promise (reject, resolve)
  853. */
  854. REQUEST_SONG(payload) {
  855. return new Promise((resolve, reject) => {
  856. const { youtubeId, userId } = payload;
  857. const requestedAt = Date.now();
  858. async.waterfall(
  859. [
  860. next => {
  861. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  862. .then(UserModel => {
  863. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  864. })
  865. .catch(next);
  866. },
  867. (user, next) => {
  868. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => next(err, user, song));
  869. },
  870. // Get YouTube data from id
  871. (user, song, next) => {
  872. if (song) return next("This song is already in the database.", song);
  873. // TODO Add err object as first param of callback
  874. const requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  875. const status = !requestedBy && config.get("hideAnonymousSongs") ? "hidden" : "unverified";
  876. return YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  877. .then(response => {
  878. const { song } = response;
  879. song.artists = [];
  880. song.genres = [];
  881. song.skipDuration = 0;
  882. song.explicit = false;
  883. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  884. song.requestedAt = requestedAt;
  885. song.status = status;
  886. next(null, song);
  887. })
  888. .catch(next);
  889. },
  890. (newSong, next) => {
  891. const song = new SongsModule.SongModel(newSong);
  892. song.save({ validateBeforeSave: false }, err => {
  893. if (err) return next(err, song);
  894. return next(null, song);
  895. });
  896. },
  897. (song, next) => {
  898. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  899. .then(UserModel => {
  900. UserModel.findOne({ _id: userId }, (err, user) => {
  901. if (err) return next(err);
  902. if (!user) return next(null, song);
  903. user.statistics.songsRequested += 1;
  904. return user.save(err => {
  905. if (err) return next(err);
  906. return next(null, song);
  907. });
  908. });
  909. })
  910. .catch(next);
  911. }
  912. ],
  913. async (err, song) => {
  914. if (err && err !== "This song is already in the database.") return reject(err);
  915. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  916. const trimmedSong = {
  917. _id,
  918. youtubeId,
  919. title,
  920. artists,
  921. thumbnail,
  922. duration,
  923. status
  924. };
  925. if (err && err === "This song is already in the database.")
  926. return reject(new ErrorWithData(err, { song: trimmedSong }));
  927. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  928. return resolve({ song: trimmedSong });
  929. }
  930. );
  931. });
  932. }
  933. /**
  934. * Hides a song
  935. *
  936. * @param {object} payload - The payload
  937. * @param {string} payload.songId - The song id of the song
  938. * @returns {Promise} - returns promise (reject, resolve)
  939. */
  940. HIDE_SONG(payload) {
  941. return new Promise((resolve, reject) => {
  942. const { songId } = payload;
  943. async.waterfall(
  944. [
  945. next => {
  946. SongsModule.SongModel.findOne({ _id: songId }, next);
  947. },
  948. // Get YouTube data from id
  949. (song, next) => {
  950. if (!song) return next("This song does not exist.");
  951. if (song.status === "hidden") return next("This song is already hidden.");
  952. // TODO Add err object as first param of callback
  953. return next(null, song.status);
  954. },
  955. (oldStatus, next) => {
  956. SongsModule.SongModel.updateOne({ _id: songId }, { status: "hidden" }, res =>
  957. next(null, res, oldStatus)
  958. );
  959. },
  960. (res, oldStatus, next) => {
  961. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus });
  962. next();
  963. }
  964. ],
  965. async err => {
  966. if (err) reject(err);
  967. resolve();
  968. }
  969. );
  970. });
  971. }
  972. /**
  973. * Unhides a song
  974. *
  975. * @param {object} payload - The payload
  976. * @param {string} payload.songId - The song id of the song
  977. * @returns {Promise} - returns promise (reject, resolve)
  978. */
  979. UNHIDE_SONG(payload) {
  980. return new Promise((resolve, reject) => {
  981. const { songId } = payload;
  982. async.waterfall(
  983. [
  984. next => {
  985. SongsModule.SongModel.findOne({ _id: songId }, next);
  986. },
  987. // Get YouTube data from id
  988. (song, next) => {
  989. if (!song) return next("This song does not exist.");
  990. if (song.status !== "hidden") return next("This song is not hidden.");
  991. // TODO Add err object as first param of callback
  992. return next();
  993. },
  994. next => {
  995. SongsModule.SongModel.updateOne({ _id: songId }, { status: "unverified" }, next);
  996. },
  997. (res, next) => {
  998. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: "hidden" });
  999. next();
  1000. }
  1001. ],
  1002. async err => {
  1003. if (err) reject(err);
  1004. resolve();
  1005. }
  1006. );
  1007. });
  1008. }
  1009. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  1010. /**
  1011. * Requests all orphaned playlist songs, adding them to the database
  1012. *
  1013. * @returns {Promise} - returns promise (reject, resolve)
  1014. */
  1015. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  1016. return new Promise((resolve, reject) => {
  1017. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  1018. .then(playlistModel => {
  1019. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  1020. const { youtubeIds } = response;
  1021. const playlistsToUpdate = new Set();
  1022. async.eachLimit(
  1023. youtubeIds,
  1024. 1,
  1025. (youtubeId, next) => {
  1026. async.waterfall(
  1027. [
  1028. next => {
  1029. console.log(
  1030. youtubeId,
  1031. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  1032. );
  1033. setTimeout(next, 150);
  1034. },
  1035. next => {
  1036. SongsModule.runJob(
  1037. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  1038. { youtubeId, automaticallyRequested: true },
  1039. this
  1040. )
  1041. .then(() => next())
  1042. .catch(next);
  1043. },
  1044. next => {
  1045. console.log(444, youtubeId);
  1046. SongsModule.SongModel.findOne({ youtubeId }, next);
  1047. },
  1048. (song, next) => {
  1049. const { _id, title, artists, thumbnail, duration, status } = song;
  1050. const trimmedSong = {
  1051. _id,
  1052. youtubeId,
  1053. title,
  1054. artists,
  1055. thumbnail,
  1056. duration,
  1057. status
  1058. };
  1059. playlistModel.updateMany(
  1060. { "songs.youtubeId": song.youtubeId },
  1061. { $set: { "songs.$": trimmedSong } },
  1062. err => {
  1063. next(err, song);
  1064. }
  1065. );
  1066. },
  1067. (song, next) => {
  1068. playlistModel.find({ "songs._id": song._id }, next);
  1069. },
  1070. (playlists, next) => {
  1071. playlists.forEach(playlist => {
  1072. playlistsToUpdate.add(playlist._id.toString());
  1073. });
  1074. next();
  1075. }
  1076. ],
  1077. next
  1078. );
  1079. },
  1080. err => {
  1081. if (err) reject(err);
  1082. else {
  1083. async.eachLimit(
  1084. Array.from(playlistsToUpdate),
  1085. 1,
  1086. (playlistId, next) => {
  1087. PlaylistsModule.runJob(
  1088. "UPDATE_PLAYLIST",
  1089. {
  1090. playlistId
  1091. },
  1092. this
  1093. )
  1094. .then(() => {
  1095. next();
  1096. })
  1097. .catch(next);
  1098. },
  1099. err => {
  1100. if (err) reject(err);
  1101. else resolve();
  1102. }
  1103. );
  1104. }
  1105. }
  1106. );
  1107. });
  1108. })
  1109. .catch(reject);
  1110. });
  1111. }
  1112. }
  1113. export default new _SongsModule();