songs.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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 => {
  1172. const { song } = response;
  1173. song.artists = [];
  1174. song.genres = [];
  1175. song.skipDuration = 0;
  1176. song.explicit = false;
  1177. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  1178. song.requestedAt = requestedAt;
  1179. song.verified = false;
  1180. next(null, song);
  1181. })
  1182. .catch(next);
  1183. },
  1184. (newSong, next) => {
  1185. const song = new SongsModule.SongModel(newSong);
  1186. song.save({ validateBeforeSave: false }, err => {
  1187. if (err) return next(err, song);
  1188. return next(null, song);
  1189. });
  1190. },
  1191. (song, next) => {
  1192. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1193. .then(UserModel => {
  1194. UserModel.findOne({ _id: userId }, (err, user) => {
  1195. if (err) return next(err);
  1196. if (!user) return next(null, song);
  1197. user.statistics.songsRequested += 1;
  1198. return user.save(err => {
  1199. if (err) return next(err);
  1200. return next(null, song);
  1201. });
  1202. });
  1203. })
  1204. .catch(next);
  1205. }
  1206. ],
  1207. async (err, song) => {
  1208. if (err && err !== "This song is already in the database.") return reject(err);
  1209. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  1210. const trimmedSong = {
  1211. _id,
  1212. youtubeId,
  1213. title,
  1214. artists,
  1215. thumbnail,
  1216. duration,
  1217. verified
  1218. };
  1219. if (err && err === "This song is already in the database.")
  1220. return reject(new ErrorWithData(err, { song: trimmedSong }));
  1221. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1222. return resolve({ song: trimmedSong });
  1223. }
  1224. );
  1225. });
  1226. }
  1227. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  1228. /**
  1229. * Requests all orphaned playlist songs, adding them to the database
  1230. *
  1231. * @returns {Promise} - returns promise (reject, resolve)
  1232. */
  1233. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  1234. return new Promise((resolve, reject) => {
  1235. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  1236. .then(playlistModel => {
  1237. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  1238. const { youtubeIds } = response;
  1239. const playlistsToUpdate = new Set();
  1240. async.eachLimit(
  1241. youtubeIds,
  1242. 1,
  1243. (youtubeId, next) => {
  1244. async.waterfall(
  1245. [
  1246. next => {
  1247. console.log(
  1248. youtubeId,
  1249. `this is song ${youtubeIds.indexOf(youtubeId) + 1}/${youtubeIds.length}`
  1250. );
  1251. setTimeout(next, 150);
  1252. },
  1253. next => {
  1254. SongsModule.runJob(
  1255. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  1256. { youtubeId, automaticallyRequested: true },
  1257. this
  1258. )
  1259. .then(() => next())
  1260. .catch(next);
  1261. },
  1262. next => {
  1263. console.log(444, youtubeId);
  1264. SongsModule.SongModel.findOne({ youtubeId }, next);
  1265. },
  1266. (song, next) => {
  1267. const { _id, title, artists, thumbnail, duration, verified } = song;
  1268. const trimmedSong = {
  1269. _id,
  1270. youtubeId,
  1271. title,
  1272. artists,
  1273. thumbnail,
  1274. duration,
  1275. verified
  1276. };
  1277. playlistModel.updateMany(
  1278. { "songs.youtubeId": song.youtubeId },
  1279. { $set: { "songs.$": trimmedSong } },
  1280. err => {
  1281. next(err, song);
  1282. }
  1283. );
  1284. },
  1285. (song, next) => {
  1286. playlistModel.find({ "songs._id": song._id }, next);
  1287. },
  1288. (playlists, next) => {
  1289. playlists.forEach(playlist => {
  1290. playlistsToUpdate.add(playlist._id.toString());
  1291. });
  1292. next();
  1293. }
  1294. ],
  1295. next
  1296. );
  1297. },
  1298. err => {
  1299. if (err) reject(err);
  1300. else {
  1301. async.eachLimit(
  1302. Array.from(playlistsToUpdate),
  1303. 1,
  1304. (playlistId, next) => {
  1305. PlaylistsModule.runJob(
  1306. "UPDATE_PLAYLIST",
  1307. {
  1308. playlistId
  1309. },
  1310. this
  1311. )
  1312. .then(() => {
  1313. next();
  1314. })
  1315. .catch(next);
  1316. },
  1317. err => {
  1318. if (err) reject(err);
  1319. else resolve();
  1320. }
  1321. );
  1322. }
  1323. }
  1324. );
  1325. });
  1326. })
  1327. .catch(reject);
  1328. });
  1329. }
  1330. /**
  1331. * Gets a list of all genres
  1332. *
  1333. * @returns {Promise} - returns promise (reject, resolve)
  1334. */
  1335. GET_GENRES() {
  1336. return new Promise((resolve, reject) => {
  1337. async.waterfall(
  1338. [
  1339. next => {
  1340. SongsModule.SongModel.distinct("genres", next);
  1341. }
  1342. ],
  1343. (err, genres) => {
  1344. if (err) reject(err);
  1345. resolve({ genres });
  1346. }
  1347. );
  1348. });
  1349. }
  1350. /**
  1351. * Gets a list of all artists
  1352. *
  1353. * @returns {Promise} - returns promise (reject, resolve)
  1354. */
  1355. GET_ARTISTS() {
  1356. return new Promise((resolve, reject) => {
  1357. async.waterfall(
  1358. [
  1359. next => {
  1360. SongsModule.SongModel.distinct("artists", next);
  1361. }
  1362. ],
  1363. (err, artists) => {
  1364. if (err) reject(err);
  1365. resolve({ artists });
  1366. }
  1367. );
  1368. });
  1369. }
  1370. /**
  1371. * Gets a list of all tags
  1372. *
  1373. * @returns {Promise} - returns promise (reject, resolve)
  1374. */
  1375. GET_TAGS() {
  1376. return new Promise((resolve, reject) => {
  1377. async.waterfall(
  1378. [
  1379. next => {
  1380. SongsModule.SongModel.distinct("tags", next);
  1381. }
  1382. ],
  1383. (err, tags) => {
  1384. if (err) reject(err);
  1385. resolve({ tags });
  1386. }
  1387. );
  1388. });
  1389. }
  1390. }
  1391. export default new _SongsModule();