songs.js 33 KB

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