songs.js 31 KB

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