songs.js 30 KB

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