songs.js 32 KB

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