songs.js 33 KB

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