songs.js 31 KB

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