songs.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import CoreClass from "../core";
  4. let SongsModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. let YouTubeModule;
  9. let StationsModule;
  10. let PlaylistsModule;
  11. class ErrorWithData extends Error {
  12. /**
  13. * @param {string} message - the error message
  14. * @param {object} data - the error data
  15. */
  16. constructor(message, data) {
  17. super(message);
  18. this.data = data;
  19. }
  20. }
  21. class _SongsModule extends CoreClass {
  22. // eslint-disable-next-line require-jsdoc
  23. constructor() {
  24. super("songs");
  25. SongsModule = this;
  26. }
  27. /**
  28. * Initialises the songs module
  29. *
  30. * @returns {Promise} - returns promise (reject, resolve)
  31. */
  32. async initialize() {
  33. this.setStage(1);
  34. CacheModule = this.moduleManager.modules.cache;
  35. DBModule = this.moduleManager.modules.db;
  36. UtilsModule = this.moduleManager.modules.utils;
  37. YouTubeModule = this.moduleManager.modules.youtube;
  38. StationsModule = this.moduleManager.modules.stations;
  39. PlaylistsModule = this.moduleManager.modules.playlists;
  40. this.SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" });
  41. this.SongSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "song" });
  42. this.setStage(2);
  43. return new Promise((resolve, reject) =>
  44. async.waterfall(
  45. [
  46. next => {
  47. this.setStage(2);
  48. CacheModule.runJob("HGETALL", { table: "songs" })
  49. .then(songs => {
  50. next(null, songs);
  51. })
  52. .catch(next);
  53. },
  54. (songs, next) => {
  55. this.setStage(3);
  56. if (!songs) return next();
  57. const youtubeIds = Object.keys(songs);
  58. return async.each(
  59. youtubeIds,
  60. (youtubeId, next) => {
  61. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => {
  62. if (err) next(err);
  63. else if (!song)
  64. CacheModule.runJob("HDEL", {
  65. table: "songs",
  66. key: youtubeId
  67. })
  68. .then(() => next())
  69. .catch(next);
  70. else next();
  71. });
  72. },
  73. next
  74. );
  75. },
  76. next => {
  77. this.setStage(4);
  78. SongsModule.SongModel.find({}, next);
  79. },
  80. (songs, next) => {
  81. this.setStage(5);
  82. async.each(
  83. songs,
  84. (song, next) => {
  85. CacheModule.runJob("HSET", {
  86. table: "songs",
  87. key: song.youtubeId,
  88. value: SongsModule.SongSchemaCache(song)
  89. })
  90. .then(() => next())
  91. .catch(next);
  92. },
  93. next
  94. );
  95. }
  96. ],
  97. async err => {
  98. if (err) {
  99. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  100. reject(new Error(err));
  101. } else resolve();
  102. }
  103. )
  104. );
  105. }
  106. /**
  107. * Gets a song by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  108. *
  109. * @param {object} payload - object containing the payload
  110. * @param {string} payload.songId - the id of the song we are trying to get
  111. * @returns {Promise} - returns a promise (resolve, reject)
  112. */
  113. GET_SONG(payload) {
  114. return new Promise((resolve, reject) =>
  115. async.waterfall(
  116. [
  117. next => {
  118. if (!mongoose.Types.ObjectId.isValid(payload.songId))
  119. return next("songId is not a valid ObjectId.");
  120. return CacheModule.runJob("HGET", { table: "songs", key: payload.songId }, this)
  121. .then(song => next(null, song))
  122. .catch(next);
  123. },
  124. (song, next) => {
  125. if (song) return next(true, song);
  126. return SongsModule.SongModel.findOne({ _id: payload.songId }, next);
  127. },
  128. (song, next) => {
  129. if (song) {
  130. CacheModule.runJob(
  131. "HSET",
  132. {
  133. table: "songs",
  134. key: payload.songId,
  135. value: song
  136. },
  137. this
  138. ).then(song => next(null, song));
  139. } else next("Song not found.");
  140. }
  141. ],
  142. (err, song) => {
  143. if (err && err !== true) return reject(new Error(err));
  144. return resolve({ song });
  145. }
  146. )
  147. );
  148. }
  149. /**
  150. * Gets songs by id from Mongo
  151. *
  152. * @param {object} payload - object containing the payload
  153. * @param {string} payload.songIds - the ids of the songs we are trying to get
  154. * @param {string} payload.properties - the properties to return
  155. * @returns {Promise} - returns a promise (resolve, reject)
  156. */
  157. GET_SONGS(payload) {
  158. return new Promise((resolve, reject) =>
  159. async.waterfall(
  160. [
  161. next => {
  162. if (!payload.songIds.every(songId => mongoose.Types.ObjectId.isValid(songId)))
  163. next("One or more songIds are not a valid ObjectId.");
  164. else next();
  165. },
  166. next => {
  167. const includeProperties = {};
  168. payload.properties.forEach(property => {
  169. includeProperties[property] = true;
  170. });
  171. return SongsModule.SongModel.find(
  172. {
  173. _id: { $in: payload.songIds }
  174. },
  175. includeProperties,
  176. next
  177. );
  178. }
  179. ],
  180. (err, songs) => {
  181. if (err && err !== true) return reject(new Error(err));
  182. return resolve({ songs });
  183. }
  184. )
  185. );
  186. }
  187. /**
  188. * Makes sure that if a song is not currently in the songs db, to add it
  189. *
  190. * @param {object} payload - an object containing the payload
  191. * @param {string} payload.youtubeId - the youtube song id of the song we are trying to ensure is in the songs db
  192. * @param {string} payload.userId - the youtube song id of the song we are trying to ensure is in the songs db
  193. * @param {string} payload.automaticallyRequested - whether the song was automatically requested or not
  194. * @returns {Promise} - returns a promise (resolve, reject)
  195. */
  196. ENSURE_SONG_EXISTS_BY_YOUTUBE_ID(payload) {
  197. return new Promise((resolve, reject) =>
  198. async.waterfall(
  199. [
  200. next => {
  201. SongsModule.SongModel.findOne({ youtubeId: payload.youtubeId }, next);
  202. },
  203. (song, next) => {
  204. if (song && song.duration > 0) next(true, song);
  205. else {
  206. YouTubeModule.runJob("GET_SONG", { youtubeId: payload.youtubeId }, this)
  207. .then(response => {
  208. next(null, song, response.song);
  209. })
  210. .catch(next);
  211. }
  212. },
  213. (song, youtubeSong, next) => {
  214. if (song && song.duration <= 0) {
  215. song.duration = youtubeSong.duration;
  216. song.save({ validateBeforeSave: true }, err => {
  217. if (err) return next(err, song);
  218. return next(null, song);
  219. });
  220. } else {
  221. const song = new SongsModule.SongModel({
  222. ...youtubeSong,
  223. requestedBy: payload.userId,
  224. requestedAt: Date.now()
  225. });
  226. song.save({ validateBeforeSave: true }, err => {
  227. if (err) return next(err, song);
  228. return next(null, song);
  229. });
  230. }
  231. }
  232. ],
  233. (err, song) => {
  234. if (err && err !== true) return reject(new Error(err));
  235. return resolve({ song });
  236. }
  237. )
  238. );
  239. }
  240. /**
  241. * Gets a song by youtube id
  242. *
  243. * @param {object} payload - an object containing the payload
  244. * @param {string} payload.youtubeId - the youtube id of the song we are trying to get
  245. * @returns {Promise} - returns a promise (resolve, reject)
  246. */
  247. GET_SONG_FROM_YOUTUBE_ID(payload) {
  248. return new Promise((resolve, reject) =>
  249. async.waterfall(
  250. [
  251. next => {
  252. SongsModule.SongModel.findOne({ youtubeId: payload.youtubeId }, next);
  253. }
  254. ],
  255. (err, song) => {
  256. if (err && err !== true) return reject(new Error(err));
  257. return resolve({ song });
  258. }
  259. )
  260. );
  261. }
  262. /**
  263. * Gets a song from id from Mongo and updates the cache with it
  264. *
  265. * @param {object} payload - an object containing the payload
  266. * @param {string} payload.songId - the id of the song we are trying to update
  267. * @param {string} payload.oldStatus - old status of song being updated (optional)
  268. * @returns {Promise} - returns a promise (resolve, reject)
  269. */
  270. UPDATE_SONG(payload) {
  271. return new Promise((resolve, reject) =>
  272. async.waterfall(
  273. [
  274. next => {
  275. SongsModule.SongModel.findOne({ _id: payload.songId }, next);
  276. },
  277. (song, next) => {
  278. if (!song) {
  279. CacheModule.runJob("HDEL", {
  280. table: "songs",
  281. key: payload.songId
  282. });
  283. return next("Song not found.");
  284. }
  285. return CacheModule.runJob(
  286. "HSET",
  287. {
  288. table: "songs",
  289. key: payload.songId,
  290. value: song
  291. },
  292. this
  293. )
  294. .then(song => {
  295. next(null, song);
  296. })
  297. .catch(next);
  298. },
  299. (song, next) => {
  300. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  301. const trimmedSong = {
  302. _id,
  303. youtubeId,
  304. title,
  305. artists,
  306. thumbnail,
  307. duration,
  308. verified
  309. };
  310. this.log("INFO", `Going to update playlists now for song ${_id}`);
  311. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this)
  312. .then(playlistModel => {
  313. playlistModel.updateMany(
  314. { "songs._id": song._id },
  315. { $set: { "songs.$": trimmedSong } },
  316. err => {
  317. if (err) next(err);
  318. else
  319. playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  320. if (err) next(err);
  321. else {
  322. async.eachLimit(
  323. playlists,
  324. 1,
  325. (playlist, next) => {
  326. PlaylistsModule.runJob(
  327. "UPDATE_PLAYLIST",
  328. {
  329. playlistId: playlist._id
  330. },
  331. this
  332. )
  333. .then(() => {
  334. next();
  335. })
  336. .catch(err => {
  337. next(err);
  338. });
  339. },
  340. err => {
  341. if (err) next(err);
  342. else next(null, song);
  343. }
  344. );
  345. }
  346. });
  347. }
  348. );
  349. })
  350. .catch(err => {
  351. next(err);
  352. });
  353. },
  354. (song, next) => {
  355. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  356. this.log("INFO", `Going to update stations now for song ${_id}`);
  357. DBModule.runJob("GET_MODEL", { modelName: "station" }, this)
  358. .then(stationModel => {
  359. stationModel.updateMany(
  360. { "queue._id": song._id },
  361. {
  362. $set: {
  363. "queue.$.youtubeId": youtubeId,
  364. "queue.$.title": title,
  365. "queue.$.artists": artists,
  366. "queue.$.thumbnail": thumbnail,
  367. "queue.$.duration": duration,
  368. "queue.$.verified": verified
  369. }
  370. },
  371. err => {
  372. if (err) this.log("ERROR", err);
  373. else
  374. stationModel.find({ "queue._id": song._id }, (err, stations) => {
  375. if (err) next(err);
  376. else {
  377. async.eachLimit(
  378. stations,
  379. 1,
  380. (station, next) => {
  381. StationsModule.runJob(
  382. "UPDATE_STATION",
  383. { stationId: station._id },
  384. this
  385. )
  386. .then(() => {
  387. next();
  388. })
  389. .catch(err => {
  390. next(err);
  391. });
  392. },
  393. err => {
  394. if (err) next(err);
  395. else next(null, song);
  396. }
  397. );
  398. }
  399. });
  400. }
  401. );
  402. })
  403. .catch(err => {
  404. next(err);
  405. });
  406. },
  407. (song, next) => {
  408. async.eachLimit(
  409. song.genres,
  410. 1,
  411. (genre, next) => {
  412. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  413. .then(() => {
  414. next();
  415. })
  416. .catch(err => next(err));
  417. },
  418. err => {
  419. next(err, song);
  420. }
  421. );
  422. }
  423. ],
  424. (err, song) => {
  425. if (err && err !== true) return reject(new Error(err));
  426. if (!payload.oldStatus) payload.oldStatus = null;
  427. CacheModule.runJob("PUB", {
  428. channel: "song.updated",
  429. value: { songId: song._id, oldStatus: payload.oldStatus }
  430. });
  431. return resolve(song);
  432. }
  433. )
  434. );
  435. }
  436. /**
  437. * Gets multiple songs from id from Mongo and updates the cache with it
  438. *
  439. * @param {object} payload - an object containing the payload
  440. * @param {Array} payload.songIds - the ids of the songs we are trying to update
  441. * @param {string} payload.oldStatus - old status of song being updated (optional)
  442. * @returns {Promise} - returns a promise (resolve, reject)
  443. */
  444. async UPDATE_SONGS(payload) {
  445. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  446. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  447. return new Promise((resolve, reject) =>
  448. async.waterfall(
  449. [
  450. // Get songs from Mongo
  451. next => {
  452. const { songIds } = payload;
  453. SongsModule.SongModel.find({ _id: songIds }, next);
  454. },
  455. // Any songs that were not in Mongo, remove from cache, if they're in the cache
  456. (songs, next) => {
  457. const { songIds } = payload;
  458. async.eachLimit(
  459. songIds,
  460. 1,
  461. (songId, next) => {
  462. if (songs.findIndex(song => song._id.toString() === songId) === -1) {
  463. // NOTE: could be made lower priority
  464. CacheModule.runJob("HDEL", {
  465. table: "songs",
  466. key: songId
  467. });
  468. next();
  469. } else next();
  470. },
  471. () => {
  472. next(null, songs);
  473. }
  474. );
  475. },
  476. // Adds/updates all songs in the cache
  477. (songs, next) => {
  478. async.eachLimit(
  479. songs,
  480. 1,
  481. (song, next) => {
  482. CacheModule.runJob(
  483. "HSET",
  484. {
  485. table: "songs",
  486. key: song._id,
  487. value: song
  488. },
  489. this
  490. )
  491. .then(() => {
  492. next();
  493. })
  494. .catch(next);
  495. },
  496. () => {
  497. next(null, songs);
  498. }
  499. );
  500. },
  501. // Updates all playlists that the songs are in by setting the new trimmed song
  502. (songs, next) => {
  503. const trimmedSongs = songs.map(song => {
  504. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  505. return {
  506. _id,
  507. youtubeId,
  508. title,
  509. artists,
  510. thumbnail,
  511. duration,
  512. verified
  513. };
  514. });
  515. const playlistsToUpdate = new Set();
  516. async.eachLimit(
  517. trimmedSongs,
  518. 1,
  519. (trimmedSong, next) => {
  520. async.waterfall(
  521. [
  522. next => {
  523. playlistModel.updateMany(
  524. { "songs._id": trimmedSong._id },
  525. { $set: { "songs.$": trimmedSong } },
  526. next
  527. );
  528. },
  529. (res, next) => {
  530. playlistModel.find({ "songs._id": trimmedSong._id }, next);
  531. },
  532. (playlists, next) => {
  533. playlists.forEach(playlist => {
  534. playlistsToUpdate.add(playlist._id.toString());
  535. });
  536. next();
  537. }
  538. ],
  539. next
  540. );
  541. },
  542. err => {
  543. next(err, songs, playlistsToUpdate);
  544. }
  545. );
  546. },
  547. // Updates all playlists that the songs are in
  548. (songs, playlistsToUpdate, next) => {
  549. async.eachLimit(
  550. playlistsToUpdate,
  551. 1,
  552. (playlistId, next) => {
  553. PlaylistsModule.runJob(
  554. "UPDATE_PLAYLIST",
  555. {
  556. playlistId
  557. },
  558. this
  559. )
  560. .then(() => {
  561. next();
  562. })
  563. .catch(err => {
  564. next(err);
  565. });
  566. },
  567. err => {
  568. next(err, songs);
  569. }
  570. );
  571. },
  572. // Updates all station queues that the songs are in by setting the new trimmed song
  573. (songs, next) => {
  574. const stationsToUpdate = new Set();
  575. async.eachLimit(
  576. songs,
  577. 1,
  578. (song, next) => {
  579. async.waterfall(
  580. [
  581. next => {
  582. const { youtubeId, title, artists, thumbnail, duration, verified } = song;
  583. stationModel.updateMany(
  584. { "queue._id": song._id },
  585. {
  586. $set: {
  587. "queue.$.youtubeId": youtubeId,
  588. "queue.$.title": title,
  589. "queue.$.artists": artists,
  590. "queue.$.thumbnail": thumbnail,
  591. "queue.$.duration": duration,
  592. "queue.$.verified": verified
  593. }
  594. },
  595. next
  596. );
  597. },
  598. (res, next) => {
  599. stationModel.find({ "queue._id": song._id }, next);
  600. },
  601. (stations, next) => {
  602. stations.forEach(station => {
  603. stationsToUpdate.add(station._id.toString());
  604. });
  605. next();
  606. }
  607. ],
  608. next
  609. );
  610. },
  611. err => {
  612. next(err, songs, stationsToUpdate);
  613. }
  614. );
  615. },
  616. // Updates all playlists that the songs are in
  617. (songs, stationsToUpdate, next) => {
  618. async.eachLimit(
  619. stationsToUpdate,
  620. 1,
  621. (stationId, next) => {
  622. StationsModule.runJob(
  623. "UPDATE_STATION",
  624. {
  625. stationId
  626. },
  627. this
  628. )
  629. .then(() => {
  630. next();
  631. })
  632. .catch(err => {
  633. next(err);
  634. });
  635. },
  636. err => {
  637. next(err, songs);
  638. }
  639. );
  640. },
  641. // Autofill the genre playlists of all genres of all songs
  642. (songs, next) => {
  643. const genresToAutofill = new Set();
  644. songs.forEach(song => {
  645. song.genres.forEach(genre => {
  646. genresToAutofill.add(genre);
  647. });
  648. });
  649. async.eachLimit(
  650. genresToAutofill,
  651. 1,
  652. (genre, next) => {
  653. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  654. .then(() => {
  655. next();
  656. })
  657. .catch(err => next(err));
  658. },
  659. err => {
  660. next(err, songs);
  661. }
  662. );
  663. },
  664. // Send event that the song was updated
  665. (songs, next) => {
  666. async.eachLimit(
  667. songs,
  668. 1,
  669. (song, next) => {
  670. CacheModule.runJob("PUB", {
  671. channel: "song.updated",
  672. value: { songId: song._id, oldStatus: null }
  673. });
  674. next();
  675. },
  676. () => {
  677. next();
  678. }
  679. );
  680. }
  681. ],
  682. err => {
  683. if (err && err !== true) return reject(new Error(err));
  684. return resolve();
  685. }
  686. )
  687. );
  688. }
  689. /**
  690. * Updates all songs
  691. *
  692. * @returns {Promise} - returns a promise (resolve, reject)
  693. */
  694. UPDATE_ALL_SONGS() {
  695. return new Promise((resolve, reject) =>
  696. async.waterfall(
  697. [
  698. next => {
  699. SongsModule.SongModel.find({}, next);
  700. },
  701. (songs, next) => {
  702. let index = 0;
  703. const { length } = songs;
  704. async.eachLimit(
  705. songs,
  706. 2,
  707. (song, next) => {
  708. index += 1;
  709. console.log(`Updating song #${index} out of ${length}: ${song._id}`);
  710. SongsModule.runJob("UPDATE_SONG", { songId: song._id }, this)
  711. .then(() => {
  712. next();
  713. })
  714. .catch(err => {
  715. next(err);
  716. });
  717. },
  718. err => {
  719. next(err);
  720. }
  721. );
  722. }
  723. ],
  724. err => {
  725. if (err && err !== true) return reject(new Error(err));
  726. return resolve();
  727. }
  728. )
  729. );
  730. }
  731. // /**
  732. // * Deletes song from id from Mongo and cache
  733. // *
  734. // * @param {object} payload - returns an object containing the payload
  735. // * @param {string} payload.songId - the song id of the song we are trying to delete
  736. // * @returns {Promise} - returns a promise (resolve, reject)
  737. // */
  738. // DELETE_SONG(payload) {
  739. // return new Promise((resolve, reject) =>
  740. // async.waterfall(
  741. // [
  742. // next => {
  743. // SongsModule.SongModel.deleteOne({ _id: payload.songId }, next);
  744. // },
  745. // next => {
  746. // CacheModule.runJob(
  747. // "HDEL",
  748. // {
  749. // table: "songs",
  750. // key: payload.songId
  751. // },
  752. // this
  753. // )
  754. // .then(() => next())
  755. // .catch(next);
  756. // },
  757. // next => {
  758. // this.log("INFO", `Going to update playlists and stations now for deleted song ${payload.songId}`);
  759. // DBModule.runJob("GET_MODEL", { modelName: "playlist" }).then(playlistModel => {
  760. // playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  761. // if (err) this.log("ERROR", err);
  762. // else {
  763. // playlistModel.updateMany(
  764. // { "songs._id": payload.songId },
  765. // { $pull: { "songs.$._id": payload.songId} },
  766. // err => {
  767. // if (err) this.log("ERROR", err);
  768. // else {
  769. // playlists.forEach(playlist => {
  770. // PlaylistsModule.runJob("UPDATE_PLAYLIST", {
  771. // playlistId: playlist._id
  772. // });
  773. // });
  774. // }
  775. // }
  776. // );
  777. // }
  778. // });
  779. // });
  780. // DBModule.runJob("GET_MODEL", { modelName: "station" }).then(stationModel => {
  781. // stationModel.find({ "queue._id": payload.songId }, (err, stations) => {
  782. // stationModel.updateMany(
  783. // { "queue._id": payload.songId },
  784. // {
  785. // $pull: { "queue._id": }
  786. // },
  787. // err => {
  788. // if (err) this.log("ERROR", err);
  789. // else {
  790. // stations.forEach(station => {
  791. // StationsModule.runJob("UPDATE_STATION", { stationId: station._id });
  792. // });
  793. // }
  794. // }
  795. // );
  796. // });
  797. // });
  798. // }
  799. // ],
  800. // err => {
  801. // if (err && err !== true) return reject(new Error(err));
  802. // return resolve();
  803. // }
  804. // )
  805. // );
  806. // }
  807. /**
  808. * Searches through songs
  809. *
  810. * @param {object} payload - object that contains the payload
  811. * @param {string} payload.query - the query
  812. * @param {string} payload.includeUnverified - include unverified songs
  813. * @param {string} payload.includeVerified - include verified songs
  814. * @param {string} payload.trimmed - include trimmed songs
  815. * @param {string} payload.page - page (default 1)
  816. * @returns {Promise} - returns promise (reject, resolve)
  817. */
  818. SEARCH(payload) {
  819. return new Promise((resolve, reject) =>
  820. async.waterfall(
  821. [
  822. next => {
  823. const isVerified = [];
  824. if (payload.includeUnverified) isVerified.push(false);
  825. if (payload.includeVerified) isVerified.push(true);
  826. if (isVerified.length === 0) return next("No verified status has been included.");
  827. let { query } = payload;
  828. const isRegex =
  829. query.length > 2 && query.indexOf("/") === 0 && query.lastIndexOf("/") === query.length - 1;
  830. if (isRegex) query = query.slice(1, query.length - 1);
  831. else query = query.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
  832. const filterArray = [
  833. {
  834. title: new RegExp(`${query}`, "i"),
  835. verified: { $in: isVerified }
  836. },
  837. {
  838. artists: new RegExp(`${query}`, "i"),
  839. verified: { $in: isVerified }
  840. }
  841. ];
  842. return next(null, filterArray);
  843. },
  844. (filterArray, next) => {
  845. const page = payload.page ? payload.page : 1;
  846. const pageSize = 15;
  847. const skipAmount = pageSize * (page - 1);
  848. SongsModule.SongModel.find({ $or: filterArray }).count((err, count) => {
  849. if (err) next(err);
  850. else {
  851. SongsModule.SongModel.find({ $or: filterArray })
  852. .skip(skipAmount)
  853. .limit(pageSize)
  854. .exec((err, songs) => {
  855. if (err) next(err);
  856. else {
  857. next(null, {
  858. songs,
  859. page,
  860. pageSize,
  861. skipAmount,
  862. count
  863. });
  864. }
  865. });
  866. }
  867. });
  868. },
  869. (data, next) => {
  870. if (data.songs.length === 0) next("No songs found");
  871. else if (payload.trimmed) {
  872. next(null, {
  873. songs: data.songs.map(song => {
  874. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  875. return {
  876. _id,
  877. youtubeId,
  878. title,
  879. artists,
  880. thumbnail,
  881. duration,
  882. verified
  883. };
  884. }),
  885. ...data
  886. });
  887. } else next(null, data);
  888. }
  889. ],
  890. (err, data) => {
  891. if (err && err !== true) return reject(new Error(err));
  892. return resolve(data);
  893. }
  894. )
  895. );
  896. }
  897. /**
  898. * Recalculates dislikes and likes for a song
  899. *
  900. * @param {object} payload - returns an object containing the payload
  901. * @param {string} payload.youtubeId - the youtube id of the song
  902. * @param {string} payload.songId - the song id of the song
  903. * @returns {Promise} - returns a promise (resolve, reject)
  904. */
  905. async RECALCULATE_SONG_RATINGS(payload) {
  906. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  907. return new Promise((resolve, reject) => {
  908. async.waterfall(
  909. [
  910. next => {
  911. playlistModel.countDocuments(
  912. { songs: { $elemMatch: { _id: payload.songId } }, type: "user-liked" },
  913. (err, likes) => {
  914. if (err) return next(err);
  915. return next(null, likes);
  916. }
  917. );
  918. },
  919. (likes, next) => {
  920. playlistModel.countDocuments(
  921. { songs: { $elemMatch: { _id: payload.songId } }, type: "user-disliked" },
  922. (err, dislikes) => {
  923. if (err) return next(err);
  924. return next(err, { likes, dislikes });
  925. }
  926. );
  927. },
  928. ({ likes, dislikes }, next) => {
  929. SongsModule.SongModel.updateOne(
  930. { _id: payload.songId },
  931. {
  932. $set: {
  933. likes,
  934. dislikes
  935. }
  936. },
  937. err => next(err, { likes, dislikes })
  938. );
  939. }
  940. ],
  941. (err, { likes, dislikes }) => {
  942. if (err) return reject(new Error(err));
  943. return resolve({ likes, dislikes });
  944. }
  945. );
  946. });
  947. }
  948. /**
  949. * Recalculates dislikes and likes for all songs
  950. *
  951. * @returns {Promise} - returns a promise (resolve, reject)
  952. */
  953. RECALCULATE_ALL_SONG_RATINGS() {
  954. return new Promise((resolve, reject) => {
  955. async.waterfall(
  956. [
  957. next => {
  958. SongsModule.SongModel.find({}, { _id: true }, next);
  959. },
  960. (songs, next) => {
  961. async.eachLimit(
  962. songs,
  963. 2,
  964. (song, next) => {
  965. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id }, this)
  966. .then(() => {
  967. next();
  968. })
  969. .catch(err => {
  970. next(err);
  971. });
  972. },
  973. err => {
  974. next(err);
  975. }
  976. );
  977. }
  978. ],
  979. err => {
  980. if (err) return reject(new Error(err));
  981. return resolve();
  982. }
  983. );
  984. });
  985. }
  986. /**
  987. * Gets an array of all genres
  988. *
  989. * @returns {Promise} - returns a promise (resolve, reject)
  990. */
  991. GET_ALL_GENRES() {
  992. return new Promise((resolve, reject) =>
  993. async.waterfall(
  994. [
  995. next => {
  996. SongsModule.SongModel.find({ verified: true }, { genres: 1, _id: false }, next);
  997. },
  998. (songs, next) => {
  999. let allGenres = [];
  1000. songs.forEach(song => {
  1001. allGenres = allGenres.concat(song.genres);
  1002. });
  1003. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  1004. const uniqueGenres = lowerCaseGenres.filter(
  1005. (value, index, self) => self.indexOf(value) === index
  1006. );
  1007. next(null, uniqueGenres);
  1008. }
  1009. ],
  1010. (err, genres) => {
  1011. if (err && err !== true) return reject(new Error(err));
  1012. return resolve({ genres });
  1013. }
  1014. )
  1015. );
  1016. }
  1017. /**
  1018. * Gets an array of all songs with a specific genre
  1019. *
  1020. * @param {object} payload - returns an object containing the payload
  1021. * @param {string} payload.genre - the genre
  1022. * @returns {Promise} - returns a promise (resolve, reject)
  1023. */
  1024. GET_ALL_SONGS_WITH_GENRE(payload) {
  1025. return new Promise((resolve, reject) =>
  1026. async.waterfall(
  1027. [
  1028. next => {
  1029. SongsModule.SongModel.find(
  1030. {
  1031. verified: true,
  1032. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  1033. },
  1034. next
  1035. );
  1036. }
  1037. ],
  1038. (err, songs) => {
  1039. if (err && err !== true) return reject(new Error(err));
  1040. return resolve({ songs });
  1041. }
  1042. )
  1043. );
  1044. }
  1045. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  1046. /**
  1047. * Gets a orphaned playlist songs
  1048. *
  1049. * @returns {Promise} - returns promise (reject, resolve)
  1050. */
  1051. GET_ORPHANED_PLAYLIST_SONGS() {
  1052. return new Promise((resolve, reject) => {
  1053. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  1054. playlistModel.find({}, (err, playlists) => {
  1055. if (err) reject(new Error(err));
  1056. else {
  1057. SongsModule.SongModel.find({}, { _id: true, youtubeId: true }, (err, songs) => {
  1058. if (err) reject(new Error(err));
  1059. else {
  1060. const songIds = songs.map(song => song._id.toString());
  1061. const orphanedYoutubeIds = new Set();
  1062. async.eachLimit(
  1063. playlists,
  1064. 1,
  1065. (playlist, next) => {
  1066. playlist.songs.forEach(song => {
  1067. if (
  1068. (!song._id || songIds.indexOf(song._id.toString() === -1)) &&
  1069. !orphanedYoutubeIds.has(song.youtubeId)
  1070. ) {
  1071. orphanedYoutubeIds.add(song.youtubeId);
  1072. }
  1073. });
  1074. next();
  1075. },
  1076. () => {
  1077. resolve({ youtubeIds: Array.from(orphanedYoutubeIds) });
  1078. }
  1079. );
  1080. }
  1081. });
  1082. }
  1083. });
  1084. });
  1085. });
  1086. }
  1087. /**
  1088. * Requests a song, adding it to the DB
  1089. *
  1090. * @param {object} payload - The payload
  1091. * @param {string} payload.youtubeId - The YouTube song id of the song
  1092. * @param {string} payload.userId - The user id of the person requesting the song
  1093. * @returns {Promise} - returns promise (reject, resolve)
  1094. */
  1095. REQUEST_SONG(payload) {
  1096. return new Promise((resolve, reject) => {
  1097. const { youtubeId, userId } = payload;
  1098. const requestedAt = Date.now();
  1099. async.waterfall(
  1100. [
  1101. next => {
  1102. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1103. .then(UserModel => {
  1104. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  1105. })
  1106. .catch(next);
  1107. },
  1108. (user, next) => {
  1109. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => next(err, user, song));
  1110. },
  1111. // Get YouTube data from id
  1112. (user, song, next) => {
  1113. if (song) return next("This song is already in the database.", song);
  1114. // TODO Add err object as first param of callback
  1115. return YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1116. .then(response => {
  1117. const { song } = response;
  1118. song.artists = [];
  1119. song.genres = [];
  1120. song.skipDuration = 0;
  1121. song.explicit = false;
  1122. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  1123. song.requestedAt = requestedAt;
  1124. song.verified = false;
  1125. next(null, song);
  1126. })
  1127. .catch(next);
  1128. },
  1129. (newSong, next) => {
  1130. const song = new SongsModule.SongModel(newSong);
  1131. song.save({ validateBeforeSave: false }, err => {
  1132. if (err) return next(err, song);
  1133. return next(null, song);
  1134. });
  1135. },
  1136. (song, next) => {
  1137. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1138. .then(UserModel => {
  1139. UserModel.findOne({ _id: userId }, (err, user) => {
  1140. if (err) return next(err);
  1141. if (!user) return next(null, song);
  1142. user.statistics.songsRequested += 1;
  1143. return user.save(err => {
  1144. if (err) return next(err);
  1145. return next(null, song);
  1146. });
  1147. });
  1148. })
  1149. .catch(next);
  1150. }
  1151. ],
  1152. async (err, song) => {
  1153. if (err && err !== "This song is already in the database.") return reject(err);
  1154. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  1155. const trimmedSong = {
  1156. _id,
  1157. youtubeId,
  1158. title,
  1159. artists,
  1160. thumbnail,
  1161. duration,
  1162. verified
  1163. };
  1164. if (err && err === "This song is already in the database.")
  1165. return reject(new ErrorWithData(err, { song: trimmedSong }));
  1166. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1167. return resolve({ song: trimmedSong });
  1168. }
  1169. );
  1170. });
  1171. }
  1172. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  1173. /**
  1174. * Requests all orphaned playlist songs, adding them to the database
  1175. *
  1176. * @returns {Promise} - returns promise (reject, resolve)
  1177. */
  1178. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  1179. return new Promise((resolve, reject) => {
  1180. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  1181. .then(playlistModel => {
  1182. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  1183. const { youtubeIds } = response;
  1184. const playlistsToUpdate = new Set();
  1185. async.eachLimit(
  1186. youtubeIds,
  1187. 1,
  1188. (youtubeId, next) => {
  1189. async.waterfall(
  1190. [
  1191. next => {
  1192. console.log(
  1193. youtubeId,
  1194. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  1195. );
  1196. setTimeout(next, 150);
  1197. },
  1198. next => {
  1199. SongsModule.runJob(
  1200. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  1201. { youtubeId, automaticallyRequested: true },
  1202. this
  1203. )
  1204. .then(() => next())
  1205. .catch(next);
  1206. },
  1207. next => {
  1208. console.log(444, youtubeId);
  1209. SongsModule.SongModel.findOne({ youtubeId }, next);
  1210. },
  1211. (song, next) => {
  1212. const { _id, title, artists, thumbnail, duration, verified } = song;
  1213. const trimmedSong = {
  1214. _id,
  1215. youtubeId,
  1216. title,
  1217. artists,
  1218. thumbnail,
  1219. duration,
  1220. verified
  1221. };
  1222. playlistModel.updateMany(
  1223. { "songs.youtubeId": song.youtubeId },
  1224. { $set: { "songs.$": trimmedSong } },
  1225. err => {
  1226. next(err, song);
  1227. }
  1228. );
  1229. },
  1230. (song, next) => {
  1231. playlistModel.find({ "songs._id": song._id }, next);
  1232. },
  1233. (playlists, next) => {
  1234. playlists.forEach(playlist => {
  1235. playlistsToUpdate.add(playlist._id.toString());
  1236. });
  1237. next();
  1238. }
  1239. ],
  1240. next
  1241. );
  1242. },
  1243. err => {
  1244. if (err) reject(err);
  1245. else {
  1246. async.eachLimit(
  1247. Array.from(playlistsToUpdate),
  1248. 1,
  1249. (playlistId, next) => {
  1250. PlaylistsModule.runJob(
  1251. "UPDATE_PLAYLIST",
  1252. {
  1253. playlistId
  1254. },
  1255. this
  1256. )
  1257. .then(() => {
  1258. next();
  1259. })
  1260. .catch(next);
  1261. },
  1262. err => {
  1263. if (err) reject(err);
  1264. else resolve();
  1265. }
  1266. );
  1267. }
  1268. }
  1269. );
  1270. });
  1271. })
  1272. .catch(reject);
  1273. });
  1274. }
  1275. /**
  1276. * Gets a list of all genres
  1277. *
  1278. * @returns {Promise} - returns promise (reject, resolve)
  1279. */
  1280. GET_GENRES() {
  1281. return new Promise((resolve, reject) => {
  1282. async.waterfall(
  1283. [
  1284. next => {
  1285. SongsModule.SongModel.distinct("genres", next);
  1286. }
  1287. ],
  1288. (err, genres) => {
  1289. if (err) reject(err);
  1290. resolve({ genres });
  1291. }
  1292. );
  1293. });
  1294. }
  1295. /**
  1296. * Gets a list of all artists
  1297. *
  1298. * @returns {Promise} - returns promise (reject, resolve)
  1299. */
  1300. GET_ARTISTS() {
  1301. return new Promise((resolve, reject) => {
  1302. async.waterfall(
  1303. [
  1304. next => {
  1305. SongsModule.SongModel.distinct("artists", next);
  1306. }
  1307. ],
  1308. (err, artists) => {
  1309. if (err) reject(err);
  1310. resolve({ artists });
  1311. }
  1312. );
  1313. });
  1314. }
  1315. /**
  1316. * Gets a list of all tags
  1317. *
  1318. * @returns {Promise} - returns promise (reject, resolve)
  1319. */
  1320. GET_TAGS() {
  1321. return new Promise((resolve, reject) => {
  1322. async.waterfall(
  1323. [
  1324. next => {
  1325. SongsModule.SongModel.distinct("tags", next);
  1326. }
  1327. ],
  1328. (err, tags) => {
  1329. if (err) reject(err);
  1330. resolve({ tags });
  1331. }
  1332. );
  1333. });
  1334. }
  1335. }
  1336. export default new _SongsModule();