songs.js 30 KB

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