songs.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. let { query } = payload;
  578. const isRegex = query.length > 2 && query.indexOf("/") === 0 && query.lastIndexOf("/") === query.length - 1;
  579. if (isRegex) query = query.slice(1, query.length - 1);
  580. else query = query.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
  581. const filterArray = [
  582. {
  583. title: new RegExp(`${query}`, "i"),
  584. status: { $in: statuses }
  585. },
  586. {
  587. artists: new RegExp(`${query}`, "i"),
  588. status: { $in: statuses }
  589. }
  590. ];
  591. return next(null, filterArray);
  592. },
  593. (filterArray, next) => {
  594. const page = payload.page ? payload.page : 1;
  595. const pageSize = 15;
  596. const skipAmount = pageSize * (page - 1);
  597. SongsModule.SongModel.find({ $or: filterArray }).count((err, count) => {
  598. if (err) next(err);
  599. else {
  600. SongsModule.SongModel.find({ $or: filterArray })
  601. .skip(skipAmount)
  602. .limit(pageSize)
  603. .exec((err, songs) => {
  604. if (err) next(err);
  605. else {
  606. next(null, {
  607. songs,
  608. page,
  609. pageSize,
  610. skipAmount,
  611. count
  612. });
  613. }
  614. });
  615. }
  616. });
  617. },
  618. (data, next) => {
  619. if (data.songs.length === 0) next("No songs found");
  620. else if (payload.trimmed) {
  621. next(null, {
  622. songs: data.songs.map(song => {
  623. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  624. return {
  625. _id,
  626. youtubeId,
  627. title,
  628. artists,
  629. thumbnail,
  630. duration,
  631. status
  632. };
  633. }),
  634. ...data
  635. });
  636. } else next(null, data);
  637. }
  638. ],
  639. (err, data) => {
  640. if (err && err !== true) return reject(new Error(err));
  641. return resolve(data);
  642. }
  643. )
  644. );
  645. }
  646. /**
  647. * Recalculates dislikes and likes for a song
  648. *
  649. * @param {object} payload - returns an object containing the payload
  650. * @param {string} payload.youtubeId - the youtube id of the song
  651. * @param {string} payload.songId - the song id of the song
  652. * @returns {Promise} - returns a promise (resolve, reject)
  653. */
  654. async RECALCULATE_SONG_RATINGS(payload) {
  655. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  656. return new Promise((resolve, reject) => {
  657. async.waterfall(
  658. [
  659. next => {
  660. playlistModel.countDocuments(
  661. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, displayName: "Liked Songs" },
  662. (err, likes) => {
  663. if (err) return next(err);
  664. return next(null, likes);
  665. }
  666. );
  667. },
  668. (likes, next) => {
  669. playlistModel.countDocuments(
  670. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, displayName: "Disliked Songs" },
  671. (err, dislikes) => {
  672. if (err) return next(err);
  673. return next(err, { likes, dislikes });
  674. }
  675. );
  676. },
  677. ({ likes, dislikes }, next) => {
  678. SongsModule.SongModel.updateOne(
  679. { _id: payload.songId },
  680. {
  681. $set: {
  682. likes,
  683. dislikes
  684. }
  685. },
  686. err => next(err, { likes, dislikes })
  687. );
  688. }
  689. ],
  690. (err, { likes, dislikes }) => {
  691. if (err) return reject(new Error(err));
  692. return resolve({ likes, dislikes });
  693. }
  694. );
  695. });
  696. }
  697. /**
  698. * Gets an array of all genres
  699. *
  700. * @returns {Promise} - returns a promise (resolve, reject)
  701. */
  702. GET_ALL_GENRES() {
  703. return new Promise((resolve, reject) =>
  704. async.waterfall(
  705. [
  706. next => {
  707. SongsModule.SongModel.find({ status: "verified" }, { genres: 1, _id: false }, next);
  708. },
  709. (songs, next) => {
  710. let allGenres = [];
  711. songs.forEach(song => {
  712. allGenres = allGenres.concat(song.genres);
  713. });
  714. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  715. const uniqueGenres = lowerCaseGenres.filter(
  716. (value, index, self) => self.indexOf(value) === index
  717. );
  718. next(null, uniqueGenres);
  719. }
  720. ],
  721. (err, genres) => {
  722. if (err && err !== true) return reject(new Error(err));
  723. return resolve({ genres });
  724. }
  725. )
  726. );
  727. }
  728. /**
  729. * Gets an array of all songs with a specific genre
  730. *
  731. * @param {object} payload - returns an object containing the payload
  732. * @param {string} payload.genre - the genre
  733. * @returns {Promise} - returns a promise (resolve, reject)
  734. */
  735. GET_ALL_SONGS_WITH_GENRE(payload) {
  736. return new Promise((resolve, reject) =>
  737. async.waterfall(
  738. [
  739. next => {
  740. SongsModule.SongModel.find(
  741. {
  742. status: "verified",
  743. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  744. },
  745. next
  746. );
  747. }
  748. ],
  749. (err, songs) => {
  750. if (err && err !== true) return reject(new Error(err));
  751. return resolve({ songs });
  752. }
  753. )
  754. );
  755. }
  756. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  757. /**
  758. * Gets a orphaned playlist songs
  759. *
  760. * @returns {Promise} - returns promise (reject, resolve)
  761. */
  762. GET_ORPHANED_PLAYLIST_SONGS() {
  763. return new Promise((resolve, reject) => {
  764. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  765. playlistModel.find({}, (err, playlists) => {
  766. if (err) reject(new Error(err));
  767. else {
  768. SongsModule.SongModel.find({}, { _id: true, youtubeId: true }, (err, songs) => {
  769. if (err) reject(new Error(err));
  770. else {
  771. const songIds = songs.map(song => song._id.toString());
  772. const orphanedYoutubeIds = new Set();
  773. async.eachLimit(
  774. playlists,
  775. 1,
  776. (playlist, next) => {
  777. playlist.songs.forEach(song => {
  778. if (
  779. (!song._id || songIds.indexOf(song._id.toString() === -1)) &&
  780. !orphanedYoutubeIds.has(song.youtubeId)
  781. ) {
  782. orphanedYoutubeIds.add(song.youtubeId);
  783. }
  784. });
  785. next();
  786. },
  787. () => {
  788. resolve({ youtubeIds: Array.from(orphanedYoutubeIds) });
  789. }
  790. );
  791. }
  792. });
  793. }
  794. });
  795. });
  796. });
  797. }
  798. /**
  799. * Requests a song, adding it to the DB
  800. *
  801. * @param {object} payload - The payload
  802. * @param {string} payload.youtubeId - The YouTube song id of the song
  803. * @param {string} payload.userId - The user id of the person requesting the song
  804. * @returns {Promise} - returns promise (reject, resolve)
  805. */
  806. REQUEST_SONG(payload) {
  807. return new Promise((resolve, reject) => {
  808. const { youtubeId, userId } = payload;
  809. const requestedAt = Date.now();
  810. async.waterfall(
  811. [
  812. next => {
  813. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  814. .then(UserModel => {
  815. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  816. })
  817. .catch(next);
  818. },
  819. (user, next) => {
  820. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => next(err, user, song));
  821. },
  822. // Get YouTube data from id
  823. (user, song, next) => {
  824. if (song) return next("This song is already in the database.", song);
  825. // TODO Add err object as first param of callback
  826. const requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  827. const status = !requestedBy && config.get("hideAnonymousSongs") ? "hidden" : "unverified";
  828. return YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  829. .then(response => {
  830. const { song } = response;
  831. song.artists = [];
  832. song.genres = [];
  833. song.skipDuration = 0;
  834. song.explicit = false;
  835. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  836. song.requestedAt = requestedAt;
  837. song.status = status;
  838. next(null, song);
  839. })
  840. .catch(next);
  841. },
  842. (newSong, next) => {
  843. const song = new SongsModule.SongModel(newSong);
  844. song.save({ validateBeforeSave: false }, err => {
  845. if (err) return next(err, song);
  846. return next(null, song);
  847. });
  848. },
  849. (song, next) => {
  850. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  851. .then(UserModel => {
  852. UserModel.findOne({ _id: userId }, (err, user) => {
  853. if (err) return next(err);
  854. if (!user) return next(null, song);
  855. user.statistics.songsRequested += 1;
  856. return user.save(err => {
  857. if (err) return next(err);
  858. return next(null, song);
  859. });
  860. });
  861. })
  862. .catch(next);
  863. }
  864. ],
  865. async (err, song) => {
  866. if (err && err !== "This song is already in the database.") return reject(err);
  867. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  868. const trimmedSong = {
  869. _id,
  870. youtubeId,
  871. title,
  872. artists,
  873. thumbnail,
  874. duration,
  875. status
  876. };
  877. if (err && err === "This song is already in the database.")
  878. return reject(new ErrorWithData(err, { song: trimmedSong }));
  879. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  880. CacheModule.runJob("PUB", {
  881. channel: "song.newUnverifiedSong",
  882. value: song._id
  883. });
  884. return resolve({ song: trimmedSong });
  885. }
  886. );
  887. });
  888. }
  889. /**
  890. * Hides a song
  891. *
  892. * @param {object} payload - The payload
  893. * @param {string} payload.songId - The song id of the song
  894. * @returns {Promise} - returns promise (reject, resolve)
  895. */
  896. HIDE_SONG(payload) {
  897. return new Promise((resolve, reject) => {
  898. const { songId } = payload;
  899. async.waterfall(
  900. [
  901. next => {
  902. SongsModule.SongModel.findOne({ _id: songId }, next);
  903. },
  904. // Get YouTube data from id
  905. (song, next) => {
  906. if (!song) return next("This song does not exist.");
  907. if (song.status === "hidden") return next("This song is already hidden.");
  908. // TODO Add err object as first param of callback
  909. return next();
  910. },
  911. next => {
  912. SongsModule.SongModel.updateOne({ _id: songId }, { status: "hidden" }, next);
  913. },
  914. (res, next) => {
  915. SongsModule.runJob("UPDATE_SONG", { songId });
  916. next();
  917. }
  918. ],
  919. async err => {
  920. if (err) reject(err);
  921. CacheModule.runJob("PUB", {
  922. channel: "song.newHiddenSong",
  923. value: songId
  924. });
  925. CacheModule.runJob("PUB", {
  926. channel: "song.removedUnverifiedSong",
  927. value: songId
  928. });
  929. CacheModule.runJob("PUB", {
  930. channel: "song.removedVerifiedSong",
  931. value: songId
  932. });
  933. resolve();
  934. }
  935. );
  936. });
  937. }
  938. /**
  939. * Unhides a song
  940. *
  941. * @param {object} payload - The payload
  942. * @param {string} payload.songId - The song id of the song
  943. * @returns {Promise} - returns promise (reject, resolve)
  944. */
  945. UNHIDE_SONG(payload) {
  946. return new Promise((resolve, reject) => {
  947. const { songId } = payload;
  948. async.waterfall(
  949. [
  950. next => {
  951. SongsModule.SongModel.findOne({ _id: songId }, next);
  952. },
  953. // Get YouTube data from id
  954. (song, next) => {
  955. if (!song) return next("This song does not exist.");
  956. if (song.status !== "hidden") return next("This song is not hidden.");
  957. // TODO Add err object as first param of callback
  958. return next();
  959. },
  960. next => {
  961. SongsModule.SongModel.updateOne({ _id: songId }, { status: "unverified" }, next);
  962. },
  963. (res, next) => {
  964. SongsModule.runJob("UPDATE_SONG", { songId });
  965. next();
  966. }
  967. ],
  968. async err => {
  969. if (err) reject(err);
  970. CacheModule.runJob("PUB", {
  971. channel: "song.newUnverifiedSong",
  972. value: songId
  973. });
  974. CacheModule.runJob("PUB", {
  975. channel: "song.removedHiddenSong",
  976. value: songId
  977. });
  978. resolve();
  979. }
  980. );
  981. });
  982. }
  983. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  984. /**
  985. * Requests all orphaned playlist songs, adding them to the database
  986. *
  987. * @returns {Promise} - returns promise (reject, resolve)
  988. */
  989. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  990. return new Promise((resolve, reject) => {
  991. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  992. .then(playlistModel => {
  993. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  994. const { youtubeIds } = response;
  995. const playlistsToUpdate = new Set();
  996. async.eachLimit(
  997. youtubeIds,
  998. 1,
  999. (youtubeId, next) => {
  1000. async.waterfall(
  1001. [
  1002. next => {
  1003. console.log(
  1004. youtubeId,
  1005. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  1006. );
  1007. setTimeout(next, 150);
  1008. },
  1009. next => {
  1010. SongsModule.runJob(
  1011. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  1012. { youtubeId, automaticallyRequested: true },
  1013. this
  1014. )
  1015. .then(() => next())
  1016. .catch(next);
  1017. },
  1018. next => {
  1019. console.log(444, youtubeId);
  1020. SongsModule.SongModel.findOne({ youtubeId }, next);
  1021. },
  1022. (song, next) => {
  1023. const { _id, title, artists, thumbnail, duration, status } = song;
  1024. const trimmedSong = {
  1025. _id,
  1026. youtubeId,
  1027. title,
  1028. artists,
  1029. thumbnail,
  1030. duration,
  1031. status
  1032. };
  1033. playlistModel.updateMany(
  1034. { "songs.youtubeId": song.youtubeId },
  1035. { $set: { "songs.$": trimmedSong } },
  1036. err => {
  1037. next(err, song);
  1038. }
  1039. );
  1040. },
  1041. (song, next) => {
  1042. playlistModel.find({ "songs._id": song._id }, next);
  1043. },
  1044. (playlists, next) => {
  1045. playlists.forEach(playlist => {
  1046. playlistsToUpdate.add(playlist._id.toString());
  1047. });
  1048. next();
  1049. }
  1050. ],
  1051. next
  1052. );
  1053. },
  1054. err => {
  1055. if (err) reject(err);
  1056. else {
  1057. async.eachLimit(
  1058. Array.from(playlistsToUpdate),
  1059. 1,
  1060. (playlistId, next) => {
  1061. PlaylistsModule.runJob(
  1062. "UPDATE_PLAYLIST",
  1063. {
  1064. playlistId
  1065. },
  1066. this
  1067. )
  1068. .then(() => {
  1069. next();
  1070. })
  1071. .catch(next);
  1072. },
  1073. err => {
  1074. if (err) reject(err);
  1075. else resolve();
  1076. }
  1077. );
  1078. }
  1079. }
  1080. );
  1081. });
  1082. })
  1083. .catch(reject);
  1084. });
  1085. }
  1086. }
  1087. export default new _SongsModule();