songs.js 30 KB

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