songs.js 31 KB

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