songs.js 31 KB

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