songs.js 29 KB

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