songs.js 30 KB

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