songs.js 31 KB

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