songs.js 30 KB

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