1
0

songs.js 33 KB

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