songs.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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. * Create song
  264. *
  265. * @param {object} payload - an object containing the payload
  266. * @param {string} payload.song - the song object
  267. * @param {string} payload.userId - the user id of the person requesting the song
  268. * @returns {Promise} - returns a promise (resolve, reject)
  269. */
  270. CREATE_SONG(payload) {
  271. return new Promise((resolve, reject) => {
  272. async.waterfall(
  273. [
  274. next => {
  275. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  276. .then(UserModel => {
  277. UserModel.findOne(
  278. { _id: payload.userId },
  279. { "preferences.anonymousSongRequests": 1 },
  280. next
  281. );
  282. })
  283. .catch(next);
  284. },
  285. (user, next) => {
  286. const song = new SongsModule.SongModel({
  287. ...payload.song,
  288. requestedBy: user.preferences.anonymousSongRequests ? null : payload.userId,
  289. requestedAt: Date.now()
  290. });
  291. if (song.verified) {
  292. song.verifiedBy = payload.userId;
  293. song.verifiedAt = Date.now();
  294. }
  295. song.save({ validateBeforeSave: true }, err => {
  296. if (err) return next(err, song);
  297. return next(null, song);
  298. });
  299. },
  300. (song, next) => {
  301. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  302. return next(null, song);
  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 from id from Mongo and updates the cache with it
  314. *
  315. * @param {object} payload - an object containing the payload
  316. * @param {string} payload.songId - the id of the song we are trying to update
  317. * @param {string} payload.oldStatus - old status of song being updated (optional)
  318. * @returns {Promise} - returns a promise (resolve, reject)
  319. */
  320. UPDATE_SONG(payload) {
  321. return new Promise((resolve, reject) => {
  322. async.waterfall(
  323. [
  324. next => {
  325. SongsModule.SongModel.findOne({ _id: payload.songId }, next);
  326. },
  327. (song, next) => {
  328. if (!song) {
  329. CacheModule.runJob("HDEL", {
  330. table: "songs",
  331. key: payload.songId
  332. });
  333. return next("Song not found.");
  334. }
  335. return CacheModule.runJob(
  336. "HSET",
  337. {
  338. table: "songs",
  339. key: payload.songId,
  340. value: song
  341. },
  342. this
  343. )
  344. .then(song => {
  345. next(null, song);
  346. })
  347. .catch(next);
  348. },
  349. (song, next) => {
  350. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  351. const trimmedSong = {
  352. _id,
  353. youtubeId,
  354. title,
  355. artists,
  356. thumbnail,
  357. duration,
  358. verified
  359. };
  360. this.log("INFO", `Going to update playlists now for song ${_id}`);
  361. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this)
  362. .then(playlistModel => {
  363. playlistModel.updateMany(
  364. { "songs._id": song._id },
  365. { $set: { "songs.$": trimmedSong } },
  366. err => {
  367. if (err) next(err);
  368. else
  369. playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  370. if (err) next(err);
  371. else {
  372. async.eachLimit(
  373. playlists,
  374. 1,
  375. (playlist, next) => {
  376. PlaylistsModule.runJob(
  377. "UPDATE_PLAYLIST",
  378. {
  379. playlistId: playlist._id
  380. },
  381. this
  382. )
  383. .then(() => {
  384. next();
  385. })
  386. .catch(err => {
  387. next(err);
  388. });
  389. },
  390. err => {
  391. if (err) next(err);
  392. else next(null, song);
  393. }
  394. );
  395. }
  396. });
  397. }
  398. );
  399. })
  400. .catch(err => {
  401. next(err);
  402. });
  403. },
  404. (song, next) => {
  405. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  406. this.log("INFO", `Going to update stations now for song ${_id}`);
  407. DBModule.runJob("GET_MODEL", { modelName: "station" }, this)
  408. .then(stationModel => {
  409. stationModel.updateMany(
  410. { "queue._id": song._id },
  411. {
  412. $set: {
  413. "queue.$.youtubeId": youtubeId,
  414. "queue.$.title": title,
  415. "queue.$.artists": artists,
  416. "queue.$.thumbnail": thumbnail,
  417. "queue.$.duration": duration,
  418. "queue.$.verified": verified
  419. }
  420. },
  421. err => {
  422. if (err) this.log("ERROR", err);
  423. else
  424. stationModel.find({ "queue._id": song._id }, (err, stations) => {
  425. if (err) next(err);
  426. else {
  427. async.eachLimit(
  428. stations,
  429. 1,
  430. (station, next) => {
  431. StationsModule.runJob(
  432. "UPDATE_STATION",
  433. { stationId: station._id },
  434. this
  435. )
  436. .then(() => {
  437. next();
  438. })
  439. .catch(err => {
  440. next(err);
  441. });
  442. },
  443. err => {
  444. if (err) next(err);
  445. else next(null, song);
  446. }
  447. );
  448. }
  449. });
  450. }
  451. );
  452. })
  453. .catch(err => {
  454. next(err);
  455. });
  456. },
  457. (song, next) => {
  458. async.eachLimit(
  459. song.genres,
  460. 1,
  461. (genre, next) => {
  462. PlaylistsModule.runJob(
  463. "AUTOFILL_GENRE_PLAYLIST",
  464. { genre, createPlaylist: song.verified },
  465. this
  466. )
  467. .then(() => {
  468. next();
  469. })
  470. .catch(err => next(err));
  471. },
  472. err => {
  473. next(err, song);
  474. }
  475. );
  476. }
  477. ],
  478. (err, song) => {
  479. if (err && err !== true) return reject(new Error(err));
  480. if (!payload.oldStatus) payload.oldStatus = null;
  481. CacheModule.runJob("PUB", {
  482. channel: "song.updated",
  483. value: { songId: song._id, oldStatus: payload.oldStatus }
  484. });
  485. return resolve(song);
  486. }
  487. );
  488. });
  489. }
  490. /**
  491. * Gets multiple songs from id from Mongo and updates the cache with it
  492. *
  493. * @param {object} payload - an object containing the payload
  494. * @param {Array} payload.songIds - the ids of the songs we are trying to update
  495. * @param {string} payload.oldStatus - old status of song being updated (optional)
  496. * @returns {Promise} - returns a promise (resolve, reject)
  497. */
  498. async UPDATE_SONGS(payload) {
  499. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  500. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  501. return new Promise((resolve, reject) => {
  502. async.waterfall(
  503. [
  504. // Get songs from Mongo
  505. next => {
  506. const { songIds } = payload;
  507. SongsModule.SongModel.find({ _id: songIds }, next);
  508. },
  509. // Any songs that were not in Mongo, remove from cache, if they're in the cache
  510. (songs, next) => {
  511. const { songIds } = payload;
  512. async.eachLimit(
  513. songIds,
  514. 1,
  515. (songId, next) => {
  516. if (songs.findIndex(song => song._id.toString() === songId) === -1) {
  517. // NOTE: could be made lower priority
  518. CacheModule.runJob("HDEL", {
  519. table: "songs",
  520. key: songId
  521. });
  522. next();
  523. } else next();
  524. },
  525. () => {
  526. next(null, songs);
  527. }
  528. );
  529. },
  530. // Adds/updates all songs in the cache
  531. (songs, next) => {
  532. async.eachLimit(
  533. songs,
  534. 1,
  535. (song, next) => {
  536. CacheModule.runJob(
  537. "HSET",
  538. {
  539. table: "songs",
  540. key: song._id,
  541. value: song
  542. },
  543. this
  544. )
  545. .then(() => {
  546. next();
  547. })
  548. .catch(next);
  549. },
  550. () => {
  551. next(null, songs);
  552. }
  553. );
  554. },
  555. // Updates all playlists that the songs are in by setting the new trimmed song
  556. (songs, next) => {
  557. const trimmedSongs = songs.map(song => {
  558. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  559. return {
  560. _id,
  561. youtubeId,
  562. title,
  563. artists,
  564. thumbnail,
  565. duration,
  566. verified
  567. };
  568. });
  569. const playlistsToUpdate = new Set();
  570. async.eachLimit(
  571. trimmedSongs,
  572. 1,
  573. (trimmedSong, next) => {
  574. async.waterfall(
  575. [
  576. next => {
  577. playlistModel.updateMany(
  578. { "songs._id": trimmedSong._id },
  579. { $set: { "songs.$": trimmedSong } },
  580. next
  581. );
  582. },
  583. (res, next) => {
  584. playlistModel.find({ "songs._id": trimmedSong._id }, next);
  585. },
  586. (playlists, next) => {
  587. playlists.forEach(playlist => {
  588. playlistsToUpdate.add(playlist._id.toString());
  589. });
  590. next();
  591. }
  592. ],
  593. next
  594. );
  595. },
  596. err => {
  597. next(err, songs, playlistsToUpdate);
  598. }
  599. );
  600. },
  601. // Updates all playlists that the songs are in
  602. (songs, playlistsToUpdate, next) => {
  603. async.eachLimit(
  604. playlistsToUpdate,
  605. 1,
  606. (playlistId, next) => {
  607. PlaylistsModule.runJob(
  608. "UPDATE_PLAYLIST",
  609. {
  610. playlistId
  611. },
  612. this
  613. )
  614. .then(() => {
  615. next();
  616. })
  617. .catch(err => {
  618. next(err);
  619. });
  620. },
  621. err => {
  622. next(err, songs);
  623. }
  624. );
  625. },
  626. // Updates all station queues that the songs are in by setting the new trimmed song
  627. (songs, next) => {
  628. const stationsToUpdate = new Set();
  629. async.eachLimit(
  630. songs,
  631. 1,
  632. (song, next) => {
  633. async.waterfall(
  634. [
  635. next => {
  636. const { youtubeId, title, artists, thumbnail, duration, verified } = song;
  637. stationModel.updateMany(
  638. { "queue._id": song._id },
  639. {
  640. $set: {
  641. "queue.$.youtubeId": youtubeId,
  642. "queue.$.title": title,
  643. "queue.$.artists": artists,
  644. "queue.$.thumbnail": thumbnail,
  645. "queue.$.duration": duration,
  646. "queue.$.verified": verified
  647. }
  648. },
  649. next
  650. );
  651. },
  652. (res, next) => {
  653. stationModel.find({ "queue._id": song._id }, next);
  654. },
  655. (stations, next) => {
  656. stations.forEach(station => {
  657. stationsToUpdate.add(station._id.toString());
  658. });
  659. next();
  660. }
  661. ],
  662. next
  663. );
  664. },
  665. err => {
  666. next(err, songs, stationsToUpdate);
  667. }
  668. );
  669. },
  670. // Updates all playlists that the songs are in
  671. (songs, stationsToUpdate, next) => {
  672. async.eachLimit(
  673. stationsToUpdate,
  674. 1,
  675. (stationId, next) => {
  676. StationsModule.runJob(
  677. "UPDATE_STATION",
  678. {
  679. stationId
  680. },
  681. this
  682. )
  683. .then(() => {
  684. next();
  685. })
  686. .catch(err => {
  687. next(err);
  688. });
  689. },
  690. err => {
  691. next(err, songs);
  692. }
  693. );
  694. },
  695. // Autofill the genre playlists of all genres of all songs
  696. (songs, next) => {
  697. const genresToAutofill = new Set();
  698. songs.forEach(song => {
  699. if (song.verified)
  700. song.genres.forEach(genre => {
  701. genresToAutofill.add(genre);
  702. });
  703. });
  704. async.eachLimit(
  705. genresToAutofill,
  706. 1,
  707. (genre, next) => {
  708. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true }, this)
  709. .then(() => {
  710. next();
  711. })
  712. .catch(err => next(err));
  713. },
  714. err => {
  715. next(err, songs);
  716. }
  717. );
  718. },
  719. // Send event that the song was updated
  720. (songs, next) => {
  721. async.eachLimit(
  722. songs,
  723. 1,
  724. (song, next) => {
  725. CacheModule.runJob("PUB", {
  726. channel: "song.updated",
  727. value: { songId: song._id, oldStatus: null }
  728. });
  729. next();
  730. },
  731. () => {
  732. next();
  733. }
  734. );
  735. }
  736. ],
  737. err => {
  738. if (err && err !== true) return reject(new Error(err));
  739. return resolve();
  740. }
  741. );
  742. });
  743. }
  744. /**
  745. * Updates all songs
  746. *
  747. * @returns {Promise} - returns a promise (resolve, reject)
  748. */
  749. UPDATE_ALL_SONGS() {
  750. return new Promise((resolve, reject) => {
  751. async.waterfall(
  752. [
  753. next => {
  754. SongsModule.SongModel.find({}, next);
  755. },
  756. (songs, next) => {
  757. let index = 0;
  758. const { length } = songs;
  759. async.eachLimit(
  760. songs,
  761. 2,
  762. (song, next) => {
  763. index += 1;
  764. console.log(`Updating song #${index} out of ${length}: ${song._id}`);
  765. SongsModule.runJob("UPDATE_SONG", { songId: song._id }, this)
  766. .then(() => {
  767. next();
  768. })
  769. .catch(err => {
  770. next(err);
  771. });
  772. },
  773. err => {
  774. next(err);
  775. }
  776. );
  777. }
  778. ],
  779. err => {
  780. if (err && err !== true) return reject(new Error(err));
  781. return resolve();
  782. }
  783. );
  784. });
  785. }
  786. // /**
  787. // * Deletes song from id from Mongo and cache
  788. // *
  789. // * @param {object} payload - returns an object containing the payload
  790. // * @param {string} payload.songId - the song id of the song we are trying to delete
  791. // * @returns {Promise} - returns a promise (resolve, reject)
  792. // */
  793. // DELETE_SONG(payload) {
  794. // return new Promise((resolve, reject) =>
  795. // async.waterfall(
  796. // [
  797. // next => {
  798. // SongsModule.SongModel.deleteOne({ _id: payload.songId }, next);
  799. // },
  800. // next => {
  801. // CacheModule.runJob(
  802. // "HDEL",
  803. // {
  804. // table: "songs",
  805. // key: payload.songId
  806. // },
  807. // this
  808. // )
  809. // .then(() => next())
  810. // .catch(next);
  811. // },
  812. // next => {
  813. // this.log("INFO", `Going to update playlists and stations now for deleted song ${payload.songId}`);
  814. // DBModule.runJob("GET_MODEL", { modelName: "playlist" }).then(playlistModel => {
  815. // playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  816. // if (err) this.log("ERROR", err);
  817. // else {
  818. // playlistModel.updateMany(
  819. // { "songs._id": payload.songId },
  820. // { $pull: { "songs.$._id": payload.songId} },
  821. // err => {
  822. // if (err) this.log("ERROR", err);
  823. // else {
  824. // playlists.forEach(playlist => {
  825. // PlaylistsModule.runJob("UPDATE_PLAYLIST", {
  826. // playlistId: playlist._id
  827. // });
  828. // });
  829. // }
  830. // }
  831. // );
  832. // }
  833. // });
  834. // });
  835. // DBModule.runJob("GET_MODEL", { modelName: "station" }).then(stationModel => {
  836. // stationModel.find({ "queue._id": payload.songId }, (err, stations) => {
  837. // stationModel.updateMany(
  838. // { "queue._id": payload.songId },
  839. // {
  840. // $pull: { "queue._id": }
  841. // },
  842. // err => {
  843. // if (err) this.log("ERROR", err);
  844. // else {
  845. // stations.forEach(station => {
  846. // StationsModule.runJob("UPDATE_STATION", { stationId: station._id });
  847. // });
  848. // }
  849. // }
  850. // );
  851. // });
  852. // });
  853. // }
  854. // ],
  855. // err => {
  856. // if (err && err !== true) return reject(new Error(err));
  857. // return resolve();
  858. // }
  859. // )
  860. // );
  861. // }
  862. /**
  863. * Searches through songs
  864. *
  865. * @param {object} payload - object that contains the payload
  866. * @param {string} payload.query - the query
  867. * @param {string} payload.includeUnverified - include unverified songs
  868. * @param {string} payload.includeVerified - include verified songs
  869. * @param {string} payload.trimmed - include trimmed songs
  870. * @param {string} payload.page - page (default 1)
  871. * @returns {Promise} - returns promise (reject, resolve)
  872. */
  873. SEARCH(payload) {
  874. return new Promise((resolve, reject) => {
  875. async.waterfall(
  876. [
  877. next => {
  878. const isVerified = [];
  879. if (payload.includeUnverified) isVerified.push(false);
  880. if (payload.includeVerified) isVerified.push(true);
  881. if (isVerified.length === 0) return next("No verified status has been included.");
  882. let { query } = payload;
  883. const isRegex =
  884. query.length > 2 && query.indexOf("/") === 0 && query.lastIndexOf("/") === query.length - 1;
  885. if (isRegex) query = query.slice(1, query.length - 1);
  886. else query = query.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
  887. const filterArray = [
  888. {
  889. title: new RegExp(`${query}`, "i"),
  890. verified: { $in: isVerified }
  891. },
  892. {
  893. artists: new RegExp(`${query}`, "i"),
  894. verified: { $in: isVerified }
  895. }
  896. ];
  897. return next(null, filterArray);
  898. },
  899. (filterArray, next) => {
  900. const page = payload.page ? payload.page : 1;
  901. const pageSize = 15;
  902. const skipAmount = pageSize * (page - 1);
  903. SongsModule.SongModel.find({ $or: filterArray }).count((err, count) => {
  904. if (err) next(err);
  905. else {
  906. SongsModule.SongModel.find({ $or: filterArray })
  907. .skip(skipAmount)
  908. .limit(pageSize)
  909. .exec((err, songs) => {
  910. if (err) next(err);
  911. else {
  912. next(null, {
  913. songs,
  914. page,
  915. pageSize,
  916. skipAmount,
  917. count
  918. });
  919. }
  920. });
  921. }
  922. });
  923. },
  924. (data, next) => {
  925. if (data.songs.length === 0) next("No songs found");
  926. else if (payload.trimmed) {
  927. next(null, {
  928. songs: data.songs.map(song => {
  929. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  930. return {
  931. _id,
  932. youtubeId,
  933. title,
  934. artists,
  935. thumbnail,
  936. duration,
  937. verified
  938. };
  939. }),
  940. ...data
  941. });
  942. } else next(null, data);
  943. }
  944. ],
  945. (err, data) => {
  946. if (err && err !== true) return reject(new Error(err));
  947. return resolve(data);
  948. }
  949. );
  950. });
  951. }
  952. /**
  953. * Recalculates dislikes and likes for a song
  954. *
  955. * @param {object} payload - returns an object containing the payload
  956. * @param {string} payload.youtubeId - the youtube id of the song
  957. * @param {string} payload.songId - the song id of the song
  958. * @returns {Promise} - returns a promise (resolve, reject)
  959. */
  960. async RECALCULATE_SONG_RATINGS(payload) {
  961. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  962. return new Promise((resolve, reject) => {
  963. async.waterfall(
  964. [
  965. next => {
  966. playlistModel.countDocuments(
  967. { songs: { $elemMatch: { _id: payload.songId } }, type: "user-liked" },
  968. (err, likes) => {
  969. if (err) return next(err);
  970. return next(null, likes);
  971. }
  972. );
  973. },
  974. (likes, next) => {
  975. playlistModel.countDocuments(
  976. { songs: { $elemMatch: { _id: payload.songId } }, type: "user-disliked" },
  977. (err, dislikes) => {
  978. if (err) return next(err);
  979. return next(err, { likes, dislikes });
  980. }
  981. );
  982. },
  983. ({ likes, dislikes }, next) => {
  984. SongsModule.SongModel.updateOne(
  985. { _id: payload.songId },
  986. {
  987. $set: {
  988. likes,
  989. dislikes
  990. }
  991. },
  992. err => next(err, { likes, dislikes })
  993. );
  994. }
  995. ],
  996. (err, { likes, dislikes }) => {
  997. if (err) return reject(new Error(err));
  998. return resolve({ likes, dislikes });
  999. }
  1000. );
  1001. });
  1002. }
  1003. /**
  1004. * Recalculates dislikes and likes for all songs
  1005. *
  1006. * @returns {Promise} - returns a promise (resolve, reject)
  1007. */
  1008. RECALCULATE_ALL_SONG_RATINGS() {
  1009. return new Promise((resolve, reject) => {
  1010. async.waterfall(
  1011. [
  1012. next => {
  1013. SongsModule.SongModel.find({}, { _id: true }, next);
  1014. },
  1015. (songs, next) => {
  1016. async.eachLimit(
  1017. songs,
  1018. 2,
  1019. (song, next) => {
  1020. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id }, this)
  1021. .then(() => {
  1022. next();
  1023. })
  1024. .catch(err => {
  1025. next(err);
  1026. });
  1027. },
  1028. err => {
  1029. next(err);
  1030. }
  1031. );
  1032. }
  1033. ],
  1034. err => {
  1035. if (err) return reject(new Error(err));
  1036. return resolve();
  1037. }
  1038. );
  1039. });
  1040. }
  1041. /**
  1042. * Gets an array of all genres
  1043. *
  1044. * @returns {Promise} - returns a promise (resolve, reject)
  1045. */
  1046. GET_ALL_GENRES() {
  1047. return new Promise((resolve, reject) => {
  1048. async.waterfall(
  1049. [
  1050. next => {
  1051. SongsModule.SongModel.find({ verified: true }, { genres: 1, _id: false }, next);
  1052. },
  1053. (songs, next) => {
  1054. let allGenres = [];
  1055. songs.forEach(song => {
  1056. allGenres = allGenres.concat(song.genres);
  1057. });
  1058. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  1059. const uniqueGenres = lowerCaseGenres.filter(
  1060. (value, index, self) => self.indexOf(value) === index
  1061. );
  1062. next(null, uniqueGenres);
  1063. }
  1064. ],
  1065. (err, genres) => {
  1066. if (err && err !== true) return reject(new Error(err));
  1067. return resolve({ genres });
  1068. }
  1069. );
  1070. });
  1071. }
  1072. /**
  1073. * Gets an array of all songs with a specific genre
  1074. *
  1075. * @param {object} payload - returns an object containing the payload
  1076. * @param {string} payload.genre - the genre
  1077. * @returns {Promise} - returns a promise (resolve, reject)
  1078. */
  1079. GET_ALL_SONGS_WITH_GENRE(payload) {
  1080. return new Promise((resolve, reject) => {
  1081. async.waterfall(
  1082. [
  1083. next => {
  1084. SongsModule.SongModel.find(
  1085. {
  1086. verified: true,
  1087. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  1088. },
  1089. next
  1090. );
  1091. }
  1092. ],
  1093. (err, songs) => {
  1094. if (err && err !== true) return reject(new Error(err));
  1095. return resolve({ songs });
  1096. }
  1097. );
  1098. });
  1099. }
  1100. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  1101. /**
  1102. * Gets a orphaned playlist songs
  1103. *
  1104. * @returns {Promise} - returns promise (reject, resolve)
  1105. */
  1106. GET_ORPHANED_PLAYLIST_SONGS() {
  1107. return new Promise((resolve, reject) => {
  1108. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  1109. playlistModel.find({}, (err, playlists) => {
  1110. if (err) reject(new Error(err));
  1111. else {
  1112. SongsModule.SongModel.find({}, { _id: true, youtubeId: true }, (err, songs) => {
  1113. if (err) reject(new Error(err));
  1114. else {
  1115. const songIds = songs.map(song => song._id.toString());
  1116. const orphanedYoutubeIds = new Set();
  1117. async.eachLimit(
  1118. playlists,
  1119. 1,
  1120. (playlist, next) => {
  1121. playlist.songs.forEach(song => {
  1122. if (
  1123. (!song._id || songIds.indexOf(song._id.toString() === -1)) &&
  1124. !orphanedYoutubeIds.has(song.youtubeId)
  1125. ) {
  1126. orphanedYoutubeIds.add(song.youtubeId);
  1127. }
  1128. });
  1129. next();
  1130. },
  1131. () => {
  1132. resolve({ youtubeIds: Array.from(orphanedYoutubeIds) });
  1133. }
  1134. );
  1135. }
  1136. });
  1137. }
  1138. });
  1139. });
  1140. });
  1141. }
  1142. /**
  1143. * Requests a song, adding it to the DB
  1144. *
  1145. * @param {object} payload - The payload
  1146. * @param {string} payload.youtubeId - The YouTube song id of the song
  1147. * @param {string} payload.userId - The user id of the person requesting the song
  1148. * @returns {Promise} - returns promise (reject, resolve)
  1149. */
  1150. REQUEST_SONG(payload) {
  1151. return new Promise((resolve, reject) => {
  1152. const { youtubeId, userId } = payload;
  1153. const requestedAt = Date.now();
  1154. async.waterfall(
  1155. [
  1156. next => {
  1157. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1158. .then(UserModel => {
  1159. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  1160. })
  1161. .catch(next);
  1162. },
  1163. (user, next) => {
  1164. SongsModule.SongModel.findOne({ youtubeId }, (err, song) => next(err, user, song));
  1165. },
  1166. // Get YouTube data from id
  1167. (user, song, next) => {
  1168. if (song) return next("This song is already in the database.", song);
  1169. // TODO Add err object as first param of callback
  1170. return YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1171. .then(response => next(null, user, response.song))
  1172. .catch(next);
  1173. },
  1174. (user, youtubeVideo, next) =>
  1175. YouTubeModule.runJob("CREATE_VIDEOS", { youtubeVideos: youtubeVideo }, this)
  1176. .then(() => {
  1177. const song = youtubeVideo;
  1178. delete song.author;
  1179. song.artists = [];
  1180. song.genres = [];
  1181. song.skipDuration = 0;
  1182. song.explicit = false;
  1183. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  1184. song.requestedAt = requestedAt;
  1185. song.verified = false;
  1186. next(null, song);
  1187. })
  1188. .catch(next),
  1189. (newSong, next) => {
  1190. const song = new SongsModule.SongModel(newSong);
  1191. song.save({ validateBeforeSave: false }, err => {
  1192. if (err) return next(err, song);
  1193. return next(null, song);
  1194. });
  1195. },
  1196. (song, next) => {
  1197. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1198. .then(UserModel => {
  1199. UserModel.findOne({ _id: userId }, (err, user) => {
  1200. if (err) return next(err);
  1201. if (!user) return next(null, song);
  1202. user.statistics.songsRequested += 1;
  1203. return user.save(err => {
  1204. if (err) return next(err);
  1205. return next(null, song);
  1206. });
  1207. });
  1208. })
  1209. .catch(next);
  1210. }
  1211. ],
  1212. async (err, song) => {
  1213. if (err && err !== "This song is already in the database.") return reject(err);
  1214. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  1215. const trimmedSong = {
  1216. _id,
  1217. youtubeId,
  1218. title,
  1219. artists,
  1220. thumbnail,
  1221. duration,
  1222. verified
  1223. };
  1224. if (err && err === "This song is already in the database.")
  1225. return reject(new ErrorWithData(err, { song: trimmedSong }));
  1226. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1227. return resolve({ song: trimmedSong });
  1228. }
  1229. );
  1230. });
  1231. }
  1232. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  1233. /**
  1234. * Requests all orphaned playlist songs, adding them to the database
  1235. *
  1236. * @returns {Promise} - returns promise (reject, resolve)
  1237. */
  1238. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  1239. return new Promise((resolve, reject) => {
  1240. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  1241. .then(playlistModel => {
  1242. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  1243. const { youtubeIds } = response;
  1244. const playlistsToUpdate = new Set();
  1245. async.eachLimit(
  1246. youtubeIds,
  1247. 1,
  1248. (youtubeId, next) => {
  1249. async.waterfall(
  1250. [
  1251. next => {
  1252. console.log(
  1253. youtubeId,
  1254. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  1255. );
  1256. setTimeout(next, 150);
  1257. },
  1258. next => {
  1259. SongsModule.runJob(
  1260. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  1261. { youtubeId, automaticallyRequested: true },
  1262. this
  1263. )
  1264. .then(() => next())
  1265. .catch(next);
  1266. },
  1267. next => {
  1268. console.log(444, youtubeId);
  1269. SongsModule.SongModel.findOne({ youtubeId }, next);
  1270. },
  1271. (song, next) => {
  1272. const { _id, title, artists, thumbnail, duration, verified } = song;
  1273. const trimmedSong = {
  1274. _id,
  1275. youtubeId,
  1276. title,
  1277. artists,
  1278. thumbnail,
  1279. duration,
  1280. verified
  1281. };
  1282. playlistModel.updateMany(
  1283. { "songs.youtubeId": song.youtubeId },
  1284. { $set: { "songs.$": trimmedSong } },
  1285. err => {
  1286. next(err, song);
  1287. }
  1288. );
  1289. },
  1290. (song, next) => {
  1291. playlistModel.find({ "songs._id": song._id }, next);
  1292. },
  1293. (playlists, next) => {
  1294. playlists.forEach(playlist => {
  1295. playlistsToUpdate.add(playlist._id.toString());
  1296. });
  1297. next();
  1298. }
  1299. ],
  1300. next
  1301. );
  1302. },
  1303. err => {
  1304. if (err) reject(err);
  1305. else {
  1306. async.eachLimit(
  1307. Array.from(playlistsToUpdate),
  1308. 1,
  1309. (playlistId, next) => {
  1310. PlaylistsModule.runJob(
  1311. "UPDATE_PLAYLIST",
  1312. {
  1313. playlistId
  1314. },
  1315. this
  1316. )
  1317. .then(() => {
  1318. next();
  1319. })
  1320. .catch(next);
  1321. },
  1322. err => {
  1323. if (err) reject(err);
  1324. else resolve();
  1325. }
  1326. );
  1327. }
  1328. }
  1329. );
  1330. });
  1331. })
  1332. .catch(reject);
  1333. });
  1334. }
  1335. /**
  1336. * Gets a list of all genres
  1337. *
  1338. * @returns {Promise} - returns promise (reject, resolve)
  1339. */
  1340. GET_GENRES() {
  1341. return new Promise((resolve, reject) => {
  1342. async.waterfall(
  1343. [
  1344. next => {
  1345. SongsModule.SongModel.distinct("genres", next);
  1346. }
  1347. ],
  1348. (err, genres) => {
  1349. if (err) reject(err);
  1350. resolve({ genres });
  1351. }
  1352. );
  1353. });
  1354. }
  1355. /**
  1356. * Gets a list of all artists
  1357. *
  1358. * @returns {Promise} - returns promise (reject, resolve)
  1359. */
  1360. GET_ARTISTS() {
  1361. return new Promise((resolve, reject) => {
  1362. async.waterfall(
  1363. [
  1364. next => {
  1365. SongsModule.SongModel.distinct("artists", next);
  1366. }
  1367. ],
  1368. (err, artists) => {
  1369. if (err) reject(err);
  1370. resolve({ artists });
  1371. }
  1372. );
  1373. });
  1374. }
  1375. /**
  1376. * Gets a list of all tags
  1377. *
  1378. * @returns {Promise} - returns promise (reject, resolve)
  1379. */
  1380. GET_TAGS() {
  1381. return new Promise((resolve, reject) => {
  1382. async.waterfall(
  1383. [
  1384. next => {
  1385. SongsModule.SongModel.distinct("tags", next);
  1386. }
  1387. ],
  1388. (err, tags) => {
  1389. if (err) reject(err);
  1390. resolve({ tags });
  1391. }
  1392. );
  1393. });
  1394. }
  1395. }
  1396. export default new _SongsModule();