songs.js 31 KB

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