songs.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. async.eachLimit(
  718. songs,
  719. 2,
  720. (song, next) => {
  721. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id }, this)
  722. .then(() => {
  723. next();
  724. })
  725. .catch(err => {
  726. next(err);
  727. });
  728. },
  729. err => {
  730. next(err);
  731. }
  732. );
  733. }
  734. ],
  735. err => {
  736. if (err) return reject(new Error(err));
  737. return resolve();
  738. }
  739. );
  740. });
  741. }
  742. /**
  743. * Gets an array of all genres
  744. *
  745. * @returns {Promise} - returns a promise (resolve, reject)
  746. */
  747. GET_ALL_GENRES() {
  748. return new Promise((resolve, reject) =>
  749. async.waterfall(
  750. [
  751. next => {
  752. SongsModule.SongModel.find({ status: "verified" }, { genres: 1, _id: false }, next);
  753. },
  754. (songs, next) => {
  755. let allGenres = [];
  756. songs.forEach(song => {
  757. allGenres = allGenres.concat(song.genres);
  758. });
  759. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  760. const uniqueGenres = lowerCaseGenres.filter(
  761. (value, index, self) => self.indexOf(value) === index
  762. );
  763. next(null, uniqueGenres);
  764. }
  765. ],
  766. (err, genres) => {
  767. if (err && err !== true) return reject(new Error(err));
  768. return resolve({ genres });
  769. }
  770. )
  771. );
  772. }
  773. /**
  774. * Gets an array of all songs with a specific genre
  775. *
  776. * @param {object} payload - returns an object containing the payload
  777. * @param {string} payload.genre - the genre
  778. * @returns {Promise} - returns a promise (resolve, reject)
  779. */
  780. GET_ALL_SONGS_WITH_GENRE(payload) {
  781. return new Promise((resolve, reject) =>
  782. async.waterfall(
  783. [
  784. next => {
  785. SongsModule.SongModel.find(
  786. {
  787. status: "verified",
  788. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  789. },
  790. next
  791. );
  792. }
  793. ],
  794. (err, songs) => {
  795. if (err && err !== true) return reject(new Error(err));
  796. return resolve({ songs });
  797. }
  798. )
  799. );
  800. }
  801. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  802. /**
  803. * Gets a orphaned playlist songs
  804. *
  805. * @returns {Promise} - returns promise (reject, resolve)
  806. */
  807. GET_ORPHANED_PLAYLIST_SONGS() {
  808. return new Promise((resolve, reject) => {
  809. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  810. playlistModel.find({}, (err, playlists) => {
  811. if (err) reject(new Error(err));
  812. else {
  813. SongsModule.SongModel.find({}, { _id: true, youtubeId: true }, (err, songs) => {
  814. if (err) reject(new Error(err));
  815. else {
  816. const songIds = songs.map(song => song._id.toString());
  817. const orphanedYoutubeIds = new Set();
  818. async.eachLimit(
  819. playlists,
  820. 1,
  821. (playlist, next) => {
  822. playlist.songs.forEach(song => {
  823. if (
  824. (!song._id || songIds.indexOf(song._id.toString() === -1)) &&
  825. !orphanedYoutubeIds.has(song.youtubeId)
  826. ) {
  827. orphanedYoutubeIds.add(song.youtubeId);
  828. }
  829. });
  830. next();
  831. },
  832. () => {
  833. resolve({ youtubeIds: Array.from(orphanedYoutubeIds) });
  834. }
  835. );
  836. }
  837. });
  838. }
  839. });
  840. });
  841. });
  842. }
  843. /**
  844. * Requests a song, adding it to the DB
  845. *
  846. * @param {object} payload - The payload
  847. * @param {string} payload.youtubeId - The YouTube song id of the song
  848. * @param {string} payload.userId - The user id of the person requesting the song
  849. * @returns {Promise} - returns promise (reject, resolve)
  850. */
  851. REQUEST_SONG(payload) {
  852. return new Promise((resolve, reject) => {
  853. const { youtubeId, userId } = payload;
  854. const requestedAt = Date.now();
  855. async.waterfall(
  856. [
  857. next => {
  858. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  859. .then(UserModel => {
  860. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  861. })
  862. .catch(next);
  863. },
  864. (user, next) => {
  865. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => next(err, user, song));
  866. },
  867. // Get YouTube data from id
  868. (user, song, next) => {
  869. if (song) return next("This song is already in the database.", song);
  870. // TODO Add err object as first param of callback
  871. const requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  872. const status = !requestedBy && config.get("hideAnonymousSongs") ? "hidden" : "unverified";
  873. return YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  874. .then(response => {
  875. const { song } = response;
  876. song.artists = [];
  877. song.genres = [];
  878. song.skipDuration = 0;
  879. song.explicit = false;
  880. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  881. song.requestedAt = requestedAt;
  882. song.status = status;
  883. next(null, song);
  884. })
  885. .catch(next);
  886. },
  887. (newSong, next) => {
  888. const song = new SongsModule.SongModel(newSong);
  889. song.save({ validateBeforeSave: false }, err => {
  890. if (err) return next(err, song);
  891. return next(null, song);
  892. });
  893. },
  894. (song, next) => {
  895. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  896. .then(UserModel => {
  897. UserModel.findOne({ _id: userId }, (err, user) => {
  898. if (err) return next(err);
  899. if (!user) return next(null, song);
  900. user.statistics.songsRequested += 1;
  901. return user.save(err => {
  902. if (err) return next(err);
  903. return next(null, song);
  904. });
  905. });
  906. })
  907. .catch(next);
  908. }
  909. ],
  910. async (err, song) => {
  911. if (err && err !== "This song is already in the database.") return reject(err);
  912. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  913. const trimmedSong = {
  914. _id,
  915. youtubeId,
  916. title,
  917. artists,
  918. thumbnail,
  919. duration,
  920. status
  921. };
  922. if (err && err === "This song is already in the database.")
  923. return reject(new ErrorWithData(err, { song: trimmedSong }));
  924. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  925. return resolve({ song: trimmedSong });
  926. }
  927. );
  928. });
  929. }
  930. /**
  931. * Hides a song
  932. *
  933. * @param {object} payload - The payload
  934. * @param {string} payload.songId - The song id of the song
  935. * @returns {Promise} - returns promise (reject, resolve)
  936. */
  937. HIDE_SONG(payload) {
  938. return new Promise((resolve, reject) => {
  939. const { songId } = payload;
  940. async.waterfall(
  941. [
  942. next => {
  943. SongsModule.SongModel.findOne({ _id: songId }, next);
  944. },
  945. // Get YouTube data from id
  946. (song, next) => {
  947. if (!song) return next("This song does not exist.");
  948. if (song.status === "hidden") return next("This song is already hidden.");
  949. // TODO Add err object as first param of callback
  950. return next(null, song.status);
  951. },
  952. (oldStatus, next) => {
  953. SongsModule.SongModel.updateOne({ _id: songId }, { status: "hidden" }, res =>
  954. next(null, res, oldStatus)
  955. );
  956. },
  957. (res, oldStatus, next) => {
  958. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus });
  959. next();
  960. }
  961. ],
  962. async err => {
  963. if (err) reject(err);
  964. resolve();
  965. }
  966. );
  967. });
  968. }
  969. /**
  970. * Unhides a song
  971. *
  972. * @param {object} payload - The payload
  973. * @param {string} payload.songId - The song id of the song
  974. * @returns {Promise} - returns promise (reject, resolve)
  975. */
  976. UNHIDE_SONG(payload) {
  977. return new Promise((resolve, reject) => {
  978. const { songId } = payload;
  979. async.waterfall(
  980. [
  981. next => {
  982. SongsModule.SongModel.findOne({ _id: songId }, next);
  983. },
  984. // Get YouTube data from id
  985. (song, next) => {
  986. if (!song) return next("This song does not exist.");
  987. if (song.status !== "hidden") return next("This song is not hidden.");
  988. // TODO Add err object as first param of callback
  989. return next();
  990. },
  991. next => {
  992. SongsModule.SongModel.updateOne({ _id: songId }, { status: "unverified" }, next);
  993. },
  994. (res, next) => {
  995. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: "hidden" });
  996. next();
  997. }
  998. ],
  999. async err => {
  1000. if (err) reject(err);
  1001. resolve();
  1002. }
  1003. );
  1004. });
  1005. }
  1006. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  1007. /**
  1008. * Requests all orphaned playlist songs, adding them to the database
  1009. *
  1010. * @returns {Promise} - returns promise (reject, resolve)
  1011. */
  1012. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  1013. return new Promise((resolve, reject) => {
  1014. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  1015. .then(playlistModel => {
  1016. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  1017. const { youtubeIds } = response;
  1018. const playlistsToUpdate = new Set();
  1019. async.eachLimit(
  1020. youtubeIds,
  1021. 1,
  1022. (youtubeId, next) => {
  1023. async.waterfall(
  1024. [
  1025. next => {
  1026. console.log(
  1027. youtubeId,
  1028. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  1029. );
  1030. setTimeout(next, 150);
  1031. },
  1032. next => {
  1033. SongsModule.runJob(
  1034. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  1035. { youtubeId, automaticallyRequested: true },
  1036. this
  1037. )
  1038. .then(() => next())
  1039. .catch(next);
  1040. },
  1041. next => {
  1042. console.log(444, youtubeId);
  1043. SongsModule.SongModel.findOne({ youtubeId }, next);
  1044. },
  1045. (song, next) => {
  1046. const { _id, title, artists, thumbnail, duration, status } = song;
  1047. const trimmedSong = {
  1048. _id,
  1049. youtubeId,
  1050. title,
  1051. artists,
  1052. thumbnail,
  1053. duration,
  1054. status
  1055. };
  1056. playlistModel.updateMany(
  1057. { "songs.youtubeId": song.youtubeId },
  1058. { $set: { "songs.$": trimmedSong } },
  1059. err => {
  1060. next(err, song);
  1061. }
  1062. );
  1063. },
  1064. (song, next) => {
  1065. playlistModel.find({ "songs._id": song._id }, next);
  1066. },
  1067. (playlists, next) => {
  1068. playlists.forEach(playlist => {
  1069. playlistsToUpdate.add(playlist._id.toString());
  1070. });
  1071. next();
  1072. }
  1073. ],
  1074. next
  1075. );
  1076. },
  1077. err => {
  1078. if (err) reject(err);
  1079. else {
  1080. async.eachLimit(
  1081. Array.from(playlistsToUpdate),
  1082. 1,
  1083. (playlistId, next) => {
  1084. PlaylistsModule.runJob(
  1085. "UPDATE_PLAYLIST",
  1086. {
  1087. playlistId
  1088. },
  1089. this
  1090. )
  1091. .then(() => {
  1092. next();
  1093. })
  1094. .catch(next);
  1095. },
  1096. err => {
  1097. if (err) reject(err);
  1098. else resolve();
  1099. }
  1100. );
  1101. }
  1102. }
  1103. );
  1104. });
  1105. })
  1106. .catch(reject);
  1107. });
  1108. }
  1109. }
  1110. export default new _SongsModule();