songs.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. next(null, song);
  268. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  269. const trimmedSong = {
  270. _id,
  271. youtubeId,
  272. title,
  273. artists,
  274. thumbnail,
  275. duration,
  276. status
  277. };
  278. this.log("INFO", `Going to update playlists and stations now for song ${_id}`);
  279. DBModule.runJob("GET_MODEL", { modelName: "playlist" }).then(playlistModel => {
  280. playlistModel.updateMany(
  281. { "songs._id": song._id },
  282. { $set: { "songs.$": trimmedSong } },
  283. err => {
  284. if (err) this.log("ERROR", err);
  285. else
  286. playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  287. playlists.forEach(playlist => {
  288. PlaylistsModule.runJob("UPDATE_PLAYLIST", {
  289. playlistId: playlist._id
  290. });
  291. });
  292. });
  293. }
  294. );
  295. });
  296. DBModule.runJob("GET_MODEL", { modelName: "station" }).then(stationModel => {
  297. stationModel.updateMany(
  298. { "queue._id": song._id },
  299. {
  300. $set: {
  301. "queue.$.youtubeId": youtubeId,
  302. "queue.$.title": title,
  303. "queue.$.artists": artists,
  304. "queue.$.thumbnail": thumbnail,
  305. "queue.$.duration": duration,
  306. "queue.$.status": status
  307. }
  308. },
  309. err => {
  310. if (err) this.log("ERROR", err);
  311. else
  312. stationModel.find({ "queue._id": song._id }, (err, stations) => {
  313. stations.forEach(station => {
  314. StationsModule.runJob("UPDATE_STATION", { stationId: station._id });
  315. });
  316. });
  317. }
  318. );
  319. });
  320. },
  321. (song, next) => {
  322. async.eachLimit(
  323. song.genres,
  324. 1,
  325. (genre, next) => {
  326. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  327. .then(() => {
  328. next();
  329. })
  330. .catch(err => next(err));
  331. },
  332. err => {
  333. next(err, song);
  334. }
  335. );
  336. }
  337. ],
  338. (err, song) => {
  339. if (err && err !== true) return reject(new Error(err));
  340. return resolve(song);
  341. }
  342. )
  343. );
  344. }
  345. /**
  346. * Deletes song from id from Mongo and cache
  347. *
  348. * @param {object} payload - returns an object containing the payload
  349. * @param {string} payload.youtubeId - the youtube id of the song we are trying to delete
  350. * @returns {Promise} - returns a promise (resolve, reject)
  351. */
  352. DELETE_SONG(payload) {
  353. return new Promise((resolve, reject) =>
  354. async.waterfall(
  355. [
  356. next => {
  357. SongsModule.SongModel.deleteOne({ youtubeId: payload.youtubeId }, next);
  358. },
  359. next => {
  360. CacheModule.runJob(
  361. "HDEL",
  362. {
  363. table: "songs",
  364. key: payload.youtubeId
  365. },
  366. this
  367. )
  368. .then(() => next())
  369. .catch(next);
  370. }
  371. ],
  372. err => {
  373. if (err && err !== true) return reject(new Error(err));
  374. return resolve();
  375. }
  376. )
  377. );
  378. }
  379. /**
  380. * Searches through songs
  381. *
  382. * @param {object} payload - object that contains the payload
  383. * @param {string} payload.query - the query
  384. * @param {string} payload.includeHidden - include hidden songs
  385. * @param {string} payload.includeUnverified - include unverified songs
  386. * @param {string} payload.includeVerified - include verified songs
  387. * @param {string} payload.trimmed - include trimmed songs
  388. * @param {string} payload.page - page (default 1)
  389. * @returns {Promise} - returns promise (reject, resolve)
  390. */
  391. SEARCH(payload) {
  392. return new Promise((resolve, reject) =>
  393. async.waterfall(
  394. [
  395. next => {
  396. const statuses = [];
  397. if (payload.includeHidden) statuses.push("hidden");
  398. if (payload.includeUnverified) statuses.push("unverified");
  399. if (payload.includeVerified) statuses.push("verified");
  400. if (statuses.length === 0) return next("No statuses have been included.");
  401. const filterArray = [
  402. {
  403. title: new RegExp(`${payload.query}`, "i"),
  404. status: { $in: statuses }
  405. },
  406. {
  407. artists: new RegExp(`${payload.query}`, "i"),
  408. status: { $in: statuses }
  409. }
  410. ];
  411. return next(null, filterArray);
  412. },
  413. (filterArray, next) => {
  414. const page = payload.page ? payload.page : 1;
  415. const pageSize = 15;
  416. const skipAmount = pageSize * (page - 1);
  417. SongsModule.SongModel.find({ $or: filterArray }).count((err, count) => {
  418. if (err) next(err);
  419. else {
  420. SongsModule.SongModel.find({ $or: filterArray })
  421. .skip(skipAmount)
  422. .limit(pageSize)
  423. .exec((err, songs) => {
  424. if (err) next(err);
  425. else {
  426. next(null, {
  427. songs,
  428. page,
  429. pageSize,
  430. skipAmount,
  431. count
  432. });
  433. }
  434. });
  435. }
  436. });
  437. },
  438. (data, next) => {
  439. if (data.songs.length === 0) next("No songs found");
  440. else if (payload.trimmed) {
  441. next(null, {
  442. songs: data.songs.map(song => {
  443. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  444. return {
  445. _id,
  446. youtubeId,
  447. title,
  448. artists,
  449. thumbnail,
  450. duration,
  451. status
  452. };
  453. }),
  454. ...data
  455. });
  456. } else next(null, data);
  457. }
  458. ],
  459. (err, data) => {
  460. if (err && err !== true) return reject(new Error(err));
  461. return resolve(data);
  462. }
  463. )
  464. );
  465. }
  466. /**
  467. * Recalculates dislikes and likes for a song
  468. *
  469. * @param {object} payload - returns an object containing the payload
  470. * @param {string} payload.youtubeId - the youtube id of the song
  471. * @param {string} payload.songId - the song id of the song
  472. * @returns {Promise} - returns a promise (resolve, reject)
  473. */
  474. async RECALCULATE_SONG_RATINGS(payload) {
  475. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  476. return new Promise((resolve, reject) => {
  477. async.waterfall(
  478. [
  479. next => {
  480. playlistModel.countDocuments(
  481. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, displayName: "Liked Songs" },
  482. (err, likes) => {
  483. if (err) return next(err);
  484. return next(null, likes);
  485. }
  486. );
  487. },
  488. (likes, next) => {
  489. playlistModel.countDocuments(
  490. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, displayName: "Disliked Songs" },
  491. (err, dislikes) => {
  492. if (err) return next(err);
  493. return next(err, { likes, dislikes });
  494. }
  495. );
  496. },
  497. ({ likes, dislikes }, next) => {
  498. SongsModule.SongModel.updateOne(
  499. { _id: payload.songId },
  500. {
  501. $set: {
  502. likes,
  503. dislikes
  504. }
  505. },
  506. err => next(err, { likes, dislikes })
  507. );
  508. }
  509. ],
  510. (err, { likes, dislikes }) => {
  511. if (err) return reject(new Error(err));
  512. return resolve({ likes, dislikes });
  513. }
  514. );
  515. });
  516. }
  517. /**
  518. * Gets an array of all genres
  519. *
  520. * @returns {Promise} - returns a promise (resolve, reject)
  521. */
  522. GET_ALL_GENRES() {
  523. return new Promise((resolve, reject) =>
  524. async.waterfall(
  525. [
  526. next => {
  527. SongsModule.SongModel.find({ status: "verified" }, { genres: 1, _id: false }, next);
  528. },
  529. (songs, next) => {
  530. let allGenres = [];
  531. songs.forEach(song => {
  532. allGenres = allGenres.concat(song.genres);
  533. });
  534. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  535. const uniqueGenres = lowerCaseGenres.filter(
  536. (value, index, self) => self.indexOf(value) === index
  537. );
  538. next(null, uniqueGenres);
  539. }
  540. ],
  541. (err, genres) => {
  542. if (err && err !== true) return reject(new Error(err));
  543. return resolve({ genres });
  544. }
  545. )
  546. );
  547. }
  548. /**
  549. * Gets an array of all songs with a specific genre
  550. *
  551. * @param {object} payload - returns an object containing the payload
  552. * @param {string} payload.genre - the genre
  553. * @returns {Promise} - returns a promise (resolve, reject)
  554. */
  555. GET_ALL_SONGS_WITH_GENRE(payload) {
  556. return new Promise((resolve, reject) =>
  557. async.waterfall(
  558. [
  559. next => {
  560. SongsModule.SongModel.find(
  561. {
  562. status: "verified",
  563. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  564. },
  565. next
  566. );
  567. }
  568. ],
  569. (err, songs) => {
  570. if (err && err !== true) return reject(new Error(err));
  571. return resolve({ songs });
  572. }
  573. )
  574. );
  575. }
  576. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  577. /**
  578. * Gets a orphaned playlist songs
  579. *
  580. * @returns {Promise} - returns promise (reject, resolve)
  581. */
  582. GET_ORPHANED_PLAYLIST_SONGS() {
  583. return new Promise((resolve, reject) => {
  584. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  585. playlistModel.find({}, (err, playlists) => {
  586. if (err) reject(new Error(err));
  587. else {
  588. SongsModule.SongModel.find({}, { _id: true, youtubeId: true }, (err, songs) => {
  589. if (err) reject(new Error(err));
  590. else {
  591. const songIds = songs.map(song => song._id.toString());
  592. const orphanedYoutubeIds = new Set();
  593. async.eachLimit(
  594. playlists,
  595. 1,
  596. (playlist, next) => {
  597. playlist.songs.forEach(song => {
  598. if (
  599. (!song._id || songIds.indexOf(song._id.toString() === -1)) &&
  600. !orphanedYoutubeIds.has(song.youtubeId)
  601. ) {
  602. orphanedYoutubeIds.add(song.youtubeId);
  603. }
  604. });
  605. next();
  606. },
  607. () => {
  608. resolve({ youtubeIds: Array.from(orphanedYoutubeIds) });
  609. }
  610. );
  611. }
  612. });
  613. }
  614. });
  615. });
  616. });
  617. }
  618. /**
  619. * Requests a song, adding it to the DB
  620. *
  621. * @param {object} payload - The payload
  622. * @param {string} payload.youtubeId - The YouTube song id of the song
  623. * @param {string} payload.userId - The user id of the person requesting the song
  624. * @returns {Promise} - returns promise (reject, resolve)
  625. */
  626. REQUEST_SONG(payload) {
  627. return new Promise((resolve, reject) => {
  628. const { youtubeId, userId } = payload;
  629. const requestedAt = Date.now();
  630. async.waterfall(
  631. [
  632. next => {
  633. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  634. .then(UserModel => {
  635. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  636. })
  637. .catch(next);
  638. },
  639. (user, next) => {
  640. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => next(err, user, song));
  641. },
  642. // Get YouTube data from id
  643. (user, song, next) => {
  644. if (song) return next("This song is already in the database.");
  645. // TODO Add err object as first param of callback
  646. const requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  647. const status = !requestedBy && config.get("hideAnonymousSongs") ? "hidden" : "unverified";
  648. return YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  649. .then(response => {
  650. const { song } = response;
  651. song.artists = [];
  652. song.genres = [];
  653. song.skipDuration = 0;
  654. song.explicit = false;
  655. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  656. song.requestedAt = requestedAt;
  657. song.status = status;
  658. next(null, song);
  659. })
  660. .catch(next);
  661. },
  662. (newSong, next) => {
  663. const song = new SongsModule.SongModel(newSong);
  664. song.save({ validateBeforeSave: false }, err => {
  665. if (err) return next(err, song);
  666. return next(null, song);
  667. });
  668. },
  669. (song, next) => {
  670. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  671. .then(UserModel => {
  672. UserModel.findOne({ _id: userId }, (err, user) => {
  673. if (err) return next(err);
  674. if (!user) return next(null, song);
  675. user.statistics.songsRequested += 1;
  676. return user.save(err => {
  677. if (err) return next(err);
  678. return next(null, song);
  679. });
  680. });
  681. })
  682. .catch(next);
  683. }
  684. ],
  685. async (err, song) => {
  686. if (err) reject(err);
  687. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  688. CacheModule.runJob("PUB", {
  689. channel: "song.newUnverifiedSong",
  690. value: song._id
  691. });
  692. resolve();
  693. }
  694. );
  695. });
  696. }
  697. /**
  698. * Hides a song
  699. *
  700. * @param {object} payload - The payload
  701. * @param {string} payload.songId - The song id of the song
  702. * @returns {Promise} - returns promise (reject, resolve)
  703. */
  704. HIDE_SONG(payload) {
  705. return new Promise((resolve, reject) => {
  706. const { songId } = payload;
  707. async.waterfall(
  708. [
  709. next => {
  710. SongsModule.SongModel.findOne({ _id: songId }, next);
  711. },
  712. // Get YouTube data from id
  713. (song, next) => {
  714. if (!song) return next("This song does not exist.");
  715. if (song.status === "hidden") return next("This song is already hidden.");
  716. if (song.status === "verified") return next("Verified songs cannot be hidden.");
  717. // TODO Add err object as first param of callback
  718. return next();
  719. },
  720. next => {
  721. SongsModule.SongModel.updateOne({ _id: songId }, { status: "hidden" }, next);
  722. },
  723. (res, next) => {
  724. SongsModule.runJob("UPDATE_SONG", { songId });
  725. next();
  726. }
  727. ],
  728. async err => {
  729. if (err) reject(err);
  730. CacheModule.runJob("PUB", {
  731. channel: "song.newHiddenSong",
  732. value: songId
  733. });
  734. CacheModule.runJob("PUB", {
  735. channel: "song.removedUnverifiedSong",
  736. value: songId
  737. });
  738. resolve();
  739. }
  740. );
  741. });
  742. }
  743. /**
  744. * Unhides a song
  745. *
  746. * @param {object} payload - The payload
  747. * @param {string} payload.songId - The song id of the song
  748. * @returns {Promise} - returns promise (reject, resolve)
  749. */
  750. UNHIDE_SONG(payload) {
  751. return new Promise((resolve, reject) => {
  752. const { songId } = payload;
  753. async.waterfall(
  754. [
  755. next => {
  756. SongsModule.SongModel.findOne({ _id: songId }, next);
  757. },
  758. // Get YouTube data from id
  759. (song, next) => {
  760. if (!song) return next("This song does not exist.");
  761. if (song.status !== "hidden") return next("This song is not hidden.");
  762. // TODO Add err object as first param of callback
  763. return next();
  764. },
  765. next => {
  766. SongsModule.SongModel.updateOne({ _id: songId }, { status: "unverified" }, next);
  767. },
  768. (res, next) => {
  769. SongsModule.runJob("UPDATE_SONG", { songId });
  770. next();
  771. }
  772. ],
  773. async err => {
  774. if (err) reject(err);
  775. CacheModule.runJob("PUB", {
  776. channel: "song.newUnverifiedSong",
  777. value: songId
  778. });
  779. CacheModule.runJob("PUB", {
  780. channel: "song.removedHiddenSong",
  781. value: songId
  782. });
  783. resolve();
  784. }
  785. );
  786. });
  787. }
  788. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  789. /**
  790. * Requests all orphaned playlist songs, adding them to the database
  791. *
  792. * @returns {Promise} - returns promise (reject, resolve)
  793. */
  794. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  795. return new Promise((resolve, reject) => {
  796. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  797. .then(playlistModel => {
  798. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  799. const { youtubeIds } = response;
  800. const playlistsToUpdate = new Set();
  801. async.eachLimit(
  802. youtubeIds,
  803. 1,
  804. (youtubeId, next) => {
  805. async.waterfall(
  806. [
  807. next => {
  808. console.log(
  809. youtubeId,
  810. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  811. );
  812. setTimeout(next, 150);
  813. },
  814. next => {
  815. SongsModule.runJob(
  816. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  817. { youtubeId, automaticallyRequested: true },
  818. this
  819. )
  820. .then(() => next())
  821. .catch(next);
  822. // SongsModule.runJob("REQUEST_SONG", { youtubeId, userId: null }, this)
  823. // .then(() => {
  824. // next();
  825. // })
  826. // .catch(next);
  827. },
  828. next => {
  829. console.log(444, youtubeId);
  830. SongsModule.SongModel.findOne({ youtubeId }, next);
  831. },
  832. (song, next) => {
  833. const { _id, title, artists, thumbnail, duration, status } = song;
  834. const trimmedSong = {
  835. _id,
  836. youtubeId,
  837. title,
  838. artists,
  839. thumbnail,
  840. duration,
  841. status
  842. };
  843. playlistModel.updateMany(
  844. { "songs.youtubeId": song.youtubeId },
  845. { $set: { "songs.$": trimmedSong } },
  846. err => {
  847. next(err, song);
  848. }
  849. );
  850. },
  851. (song, next) => {
  852. playlistModel.find({ "songs._id": song._id }, next);
  853. },
  854. (playlists, next) => {
  855. playlists.forEach(playlist => {
  856. playlistsToUpdate.add(playlist._id.toString());
  857. });
  858. next();
  859. }
  860. ],
  861. next
  862. );
  863. },
  864. err => {
  865. if (err) reject(err);
  866. else {
  867. async.eachLimit(
  868. Array.from(playlistsToUpdate),
  869. 1,
  870. (playlistId, next) => {
  871. PlaylistsModule.runJob(
  872. "UPDATE_PLAYLIST",
  873. {
  874. playlistId
  875. },
  876. this
  877. )
  878. .then(() => {
  879. next();
  880. })
  881. .catch(next);
  882. },
  883. err => {
  884. if (err) reject(err);
  885. else resolve();
  886. }
  887. );
  888. }
  889. }
  890. );
  891. });
  892. })
  893. .catch(reject);
  894. });
  895. }
  896. }
  897. export default new _SongsModule();