songs.js 30 KB

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