songs.js 33 KB

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