songs.js 31 KB

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