songs.js 34 KB

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