media.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let MediaModule;
  4. let CacheModule;
  5. let DBModule;
  6. let UtilsModule;
  7. let YouTubeModule;
  8. let SoundCloudModule;
  9. let SpotifyModule;
  10. let SongsModule;
  11. let WSModule;
  12. class _MediaModule extends CoreClass {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor() {
  15. super("media");
  16. MediaModule = this;
  17. }
  18. /**
  19. * Initialises the media module
  20. *
  21. * @returns {Promise} - returns promise (reject, resolve)
  22. */
  23. async initialize() {
  24. this.setStage(1);
  25. CacheModule = this.moduleManager.modules.cache;
  26. DBModule = this.moduleManager.modules.db;
  27. UtilsModule = this.moduleManager.modules.utils;
  28. YouTubeModule = this.moduleManager.modules.youtube;
  29. SoundCloudModule = this.moduleManager.modules.soundcloud;
  30. SpotifyModule = this.moduleManager.modules.spotify;
  31. SongsModule = this.moduleManager.modules.songs;
  32. WSModule = this.moduleManager.modules.ws;
  33. this.RatingsModel = await DBModule.runJob("GET_MODEL", { modelName: "ratings" });
  34. this.RatingsSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "ratings" });
  35. this.ImportJobModel = await DBModule.runJob("GET_MODEL", { modelName: "importJob" });
  36. this.setStage(2);
  37. return new Promise((resolve, reject) => {
  38. CacheModule.runJob("SUB", {
  39. channel: "importJob.updated",
  40. cb: importJob => {
  41. WSModule.runJob("EMIT_TO_ROOM", {
  42. room: "admin.import",
  43. args: ["event:admin.importJob.updated", { data: { importJob } }]
  44. });
  45. }
  46. });
  47. CacheModule.runJob("SUB", {
  48. channel: "importJob.removed",
  49. cb: jobId => {
  50. WSModule.runJob("EMIT_TO_ROOM", {
  51. room: "admin.import",
  52. args: ["event:admin.importJob.removed", { data: { jobId } }]
  53. });
  54. }
  55. });
  56. async.waterfall(
  57. [
  58. next => {
  59. this.setStage(2);
  60. CacheModule.runJob("HGETALL", { table: "ratings" })
  61. .then(ratings => {
  62. next(null, ratings);
  63. })
  64. .catch(next);
  65. },
  66. (ratings, next) => {
  67. this.setStage(3);
  68. if (!ratings) return next();
  69. const mediaSources = Object.keys(ratings);
  70. return async.each(
  71. mediaSources,
  72. (mediaSource, next) => {
  73. MediaModule.RatingsModel.findOne({ mediaSource }, (err, rating) => {
  74. if (err) next(err);
  75. else if (!rating)
  76. CacheModule.runJob("HDEL", {
  77. table: "ratings",
  78. key: mediaSource
  79. })
  80. .then(() => next())
  81. .catch(next);
  82. else next();
  83. });
  84. },
  85. next
  86. );
  87. },
  88. next => {
  89. this.setStage(4);
  90. MediaModule.RatingsModel.find({}, next);
  91. },
  92. (ratings, next) => {
  93. this.setStage(5);
  94. async.each(
  95. ratings,
  96. (rating, next) => {
  97. CacheModule.runJob("HSET", {
  98. table: "ratings",
  99. key: rating.mediaSource,
  100. value: MediaModule.RatingsSchemaCache(rating)
  101. })
  102. .then(() => next())
  103. .catch(next);
  104. },
  105. next
  106. );
  107. }
  108. ],
  109. async err => {
  110. if (err) {
  111. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  112. reject(new Error(err));
  113. } else resolve();
  114. }
  115. );
  116. });
  117. }
  118. /**
  119. * Recalculates dislikes and likes
  120. *
  121. * @param {object} payload - returns an object containing the payload
  122. * @param {string} payload.mediaSource - the media source
  123. * @returns {Promise} - returns a promise (resolve, reject)
  124. */
  125. async RECALCULATE_RATINGS(payload) {
  126. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  127. return new Promise((resolve, reject) => {
  128. async.waterfall(
  129. [
  130. next => {
  131. playlistModel.countDocuments(
  132. { songs: { $elemMatch: { mediaSource: payload.mediaSource } }, type: "user-liked" },
  133. (err, likes) => {
  134. if (err) return next(err);
  135. return next(null, likes);
  136. }
  137. );
  138. },
  139. (likes, next) => {
  140. playlistModel.countDocuments(
  141. { songs: { $elemMatch: { mediaSource: payload.mediaSource } }, type: "user-disliked" },
  142. (err, dislikes) => {
  143. if (err) return next(err);
  144. return next(err, { likes, dislikes });
  145. }
  146. );
  147. },
  148. ({ likes, dislikes }, next) => {
  149. MediaModule.RatingsModel.findOneAndUpdate(
  150. { mediaSource: payload.mediaSource },
  151. {
  152. $set: {
  153. likes,
  154. dislikes
  155. }
  156. },
  157. { new: true, upsert: true },
  158. next
  159. );
  160. },
  161. (ratings, next) => {
  162. CacheModule.runJob(
  163. "HSET",
  164. {
  165. table: "ratings",
  166. key: payload.mediaSource,
  167. value: ratings
  168. },
  169. this
  170. )
  171. .then(ratings => next(null, ratings))
  172. .catch(next);
  173. }
  174. ],
  175. (err, { likes, dislikes }) => {
  176. if (err) return reject(new Error(err));
  177. return resolve({ likes, dislikes });
  178. }
  179. );
  180. });
  181. }
  182. /**
  183. * Recalculates all dislikes and likes
  184. *
  185. * @returns {Promise} - returns a promise (resolve, reject)
  186. */
  187. RECALCULATE_ALL_RATINGS() {
  188. return new Promise((resolve, reject) => {
  189. async.waterfall(
  190. [
  191. next => {
  192. SongsModule.SongModel.find({}, { mediaSource: true }, next);
  193. },
  194. (songs, next) => {
  195. // TODO support spotify
  196. YouTubeModule.youtubeVideoModel.find({}, { youtubeId: true }, (err, videos) => {
  197. if (err) next(err);
  198. else
  199. next(null, [
  200. ...songs.map(song => song.mediaSource),
  201. ...videos.map(video => `youtube:${video.youtubeId}`)
  202. ]);
  203. });
  204. },
  205. (mediaSources, next) => {
  206. async.eachLimit(
  207. mediaSources,
  208. 2,
  209. (mediaSource, next) => {
  210. this.publishProgress({
  211. status: "update",
  212. message: `Recalculating ratings for ${mediaSource}`
  213. });
  214. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  215. .then(() => {
  216. next();
  217. })
  218. .catch(err => {
  219. next(err);
  220. });
  221. },
  222. err => {
  223. next(err);
  224. }
  225. );
  226. }
  227. ],
  228. err => {
  229. if (err) return reject(new Error(err));
  230. return resolve();
  231. }
  232. );
  233. });
  234. }
  235. /**
  236. * Gets ratings by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  237. *
  238. * @param {object} payload - object containing the payload
  239. * @param {string} payload.mediaSource - the media source
  240. * @param {string} payload.createMissing - whether to create missing ratings
  241. * @returns {Promise} - returns a promise (resolve, reject)
  242. */
  243. GET_RATINGS(payload) {
  244. return new Promise((resolve, reject) => {
  245. async.waterfall(
  246. [
  247. next =>
  248. CacheModule.runJob("HGET", { table: "ratings", key: payload.mediaSource }, this)
  249. .then(ratings => next(null, ratings))
  250. .catch(next),
  251. (ratings, next) => {
  252. if (ratings) return next(true, ratings);
  253. return MediaModule.RatingsModel.findOne({ mediaSource: payload.mediaSource }, next);
  254. },
  255. (ratings, next) => {
  256. if (ratings)
  257. return CacheModule.runJob(
  258. "HSET",
  259. {
  260. table: "ratings",
  261. key: payload.mediaSource,
  262. value: ratings
  263. },
  264. this
  265. ).then(ratings => next(true, ratings));
  266. if (!payload.createMissing) return next("Ratings not found.");
  267. return MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource: payload.mediaSource }, this)
  268. .then(() => next())
  269. .catch(next);
  270. },
  271. next =>
  272. MediaModule.runJob("GET_RATINGS", { mediaSource: payload.mediaSource }, this)
  273. .then(res => next(null, res.ratings))
  274. .catch(next)
  275. ],
  276. (err, ratings) => {
  277. if (err && err !== true) return reject(new Error(err));
  278. return resolve({ ratings });
  279. }
  280. );
  281. });
  282. }
  283. /**
  284. * Remove ratings by id from the cache and Mongo
  285. *
  286. * @param {object} payload - object containing the payload
  287. * @param {string} payload.mediaSources - the media source
  288. * @returns {Promise} - returns a promise (resolve, reject)
  289. */
  290. REMOVE_RATINGS(payload) {
  291. return new Promise((resolve, reject) => {
  292. let { mediaSources } = payload;
  293. if (!Array.isArray(mediaSources)) mediaSources = [mediaSources];
  294. async.eachLimit(
  295. mediaSources,
  296. 1,
  297. (mediaSource, next) => {
  298. async.waterfall(
  299. [
  300. next => {
  301. MediaModule.RatingsModel.deleteOne({ mediaSource }, err => {
  302. if (err) next(err);
  303. else next();
  304. });
  305. },
  306. next => {
  307. CacheModule.runJob("HDEL", { table: "ratings", key: mediaSource }, this)
  308. .then(() => {
  309. next();
  310. })
  311. .catch(next);
  312. }
  313. ],
  314. next
  315. );
  316. },
  317. err => {
  318. if (err && err !== true) return reject(new Error(err));
  319. return resolve();
  320. }
  321. );
  322. });
  323. }
  324. /**
  325. * Get song or youtube video by mediaSource
  326. *
  327. * @param {object} payload - an object containing the payload
  328. * @param {string} payload.mediaSource - the media source of the song/video
  329. * @param {string} payload.userId - the user id
  330. * @returns {Promise} - returns a promise (resolve, reject)
  331. */
  332. GET_MEDIA(payload) {
  333. return new Promise((resolve, reject) => {
  334. async.waterfall(
  335. [
  336. next => {
  337. SongsModule.SongModel.findOne({ mediaSource: payload.mediaSource }, next);
  338. },
  339. (song, next) => {
  340. if (song && song.duration > 0) return next(true, song);
  341. console.log(123, payload);
  342. if (payload.mediaSource.startsWith("youtube:")) {
  343. const youtubeId = payload.mediaSource.split(":")[1];
  344. return YouTubeModule.runJob(
  345. "GET_VIDEOS",
  346. { identifiers: [youtubeId], createMissing: true },
  347. this
  348. )
  349. .then(response => {
  350. const { youtubeId, title, author, duration } = response.videos[0];
  351. next(null, song, {
  352. mediaSource: `youtube:${youtubeId}`,
  353. title,
  354. artists: [author],
  355. duration
  356. });
  357. })
  358. .catch(next);
  359. }
  360. if (payload.mediaSource.startsWith("soundcloud:")) {
  361. const trackId = payload.mediaSource.split(":")[1];
  362. return SoundCloudModule.runJob(
  363. "GET_TRACK",
  364. { identifier: trackId, createMissing: true },
  365. this
  366. )
  367. .then(response => {
  368. const { trackId, title, username, artworkUrl, duration } = response.track;
  369. next(null, song, {
  370. mediaSource: `soundcloud:${trackId}`,
  371. title,
  372. artists: [username],
  373. thumbnail: artworkUrl,
  374. duration
  375. });
  376. })
  377. .catch(next);
  378. }
  379. if (payload.mediaSource.indexOf("soundcloud.com") !== -1) {
  380. return SoundCloudModule.runJob(
  381. "GET_TRACK_FROM_URL",
  382. { identifier: payload.mediaSource, createMissing: true },
  383. this
  384. )
  385. .then(response => {
  386. const { trackId, title, username, artworkUrl, duration } = response.track;
  387. next(null, song, {
  388. mediaSource: `soundcloud:${trackId}`,
  389. title,
  390. artists: [username],
  391. thumbnail: artworkUrl,
  392. duration
  393. });
  394. })
  395. .catch(next);
  396. }
  397. if (payload.mediaSource.startsWith("spotify:")) {
  398. const trackId = payload.mediaSource.split(":")[1];
  399. return SpotifyModule.runJob("GET_TRACK", { identifier: trackId, createMissing: true }, this)
  400. .then(response => {
  401. const { trackId, name, artists, albumImageUrl, duration } = response.track;
  402. next(null, song, {
  403. mediaSource: `spotify:${trackId}`,
  404. title: name,
  405. artists,
  406. thumbnail: albumImageUrl,
  407. duration
  408. });
  409. })
  410. .catch(next);
  411. }
  412. return next("Invalid media source provided.");
  413. },
  414. (song, youtubeVideo, next) => {
  415. if (song && song.duration <= 0) {
  416. song.duration = youtubeVideo.duration;
  417. song.save({ validateBeforeSave: true }, err => {
  418. if (err) next(err, song);
  419. next(null, song);
  420. });
  421. } else {
  422. next(null, {
  423. ...youtubeVideo,
  424. skipDuration: 0,
  425. requestedBy: payload.userId,
  426. requestedAt: Date.now(),
  427. verified: false
  428. });
  429. }
  430. }
  431. ],
  432. (err, song) => {
  433. if (err && err !== true) return reject(new Error(err));
  434. return resolve({ song });
  435. }
  436. );
  437. });
  438. }
  439. /**
  440. * Gets media from media sources
  441. *
  442. * @param {object} payload - an object containing the payload
  443. * @param {string} payload.mediaSources - the media sources
  444. * @returns {Promise} - returns a promise (resolve, reject)
  445. */
  446. GET_MEDIA_FROM_MEDIA_SOURCES(payload) {
  447. return new Promise((resolve, reject) => {
  448. const songMap = {};
  449. const youtubeMediaSources = payload.mediaSources.filter(mediaSource => mediaSource.startsWith("youtube:"));
  450. const soundcloudMediaSources = payload.mediaSources.filter(mediaSource =>
  451. mediaSource.startsWith("soundcloud:")
  452. );
  453. async.waterfall(
  454. [
  455. next => {
  456. const allPromises = [];
  457. youtubeMediaSources.forEach(mediaSource => {
  458. const youtubeId = mediaSource.split(":")[1];
  459. const promise = YouTubeModule.runJob(
  460. "GET_VIDEOS",
  461. { identifiers: [youtubeId], createMissing: true },
  462. this
  463. )
  464. .then(response => {
  465. const { youtubeId, title, author, duration } = response.videos[0];
  466. songMap[mediaSource] = {
  467. mediaSource: `youtube:${youtubeId}`,
  468. title,
  469. artists: [author],
  470. duration
  471. };
  472. })
  473. .catch(err => {
  474. MediaModule.log(
  475. "ERROR",
  476. `Failed to get media in GET_MEDIA_FROM_MEDIA_SOURCES with mediaSource ${mediaSource} and error`,
  477. typeof err === "string" ? err : err.message
  478. );
  479. });
  480. allPromises.push(promise);
  481. });
  482. soundcloudMediaSources.forEach(mediaSource => {
  483. const trackId = mediaSource.split(":")[1];
  484. const promise = SoundCloudModule.runJob(
  485. "GET_TRACK",
  486. { identifier: trackId, createMissing: true },
  487. this
  488. )
  489. .then(response => {
  490. const { trackId, title, username, artworkUrl, duration } = response.track;
  491. songMap[mediaSource] = {
  492. mediaSource: `soundcloud:${trackId}`,
  493. title,
  494. artists: [username],
  495. thumbnail: artworkUrl,
  496. duration
  497. };
  498. })
  499. .catch(err => {
  500. MediaModule.log(
  501. "ERROR",
  502. `Failed to get media in GET_MEDIA_FROM_MEDIA_SOURCES with mediaSource ${mediaSource} and error`,
  503. typeof err === "string" ? err : err.message
  504. );
  505. });
  506. allPromises.push(promise);
  507. });
  508. Promise.allSettled(allPromises).then(() => {
  509. next();
  510. });
  511. }
  512. ],
  513. err => {
  514. if (err && err !== true) return reject(new Error(err));
  515. return resolve(songMap);
  516. }
  517. );
  518. });
  519. }
  520. /**
  521. * Remove import job by id from Mongo
  522. *
  523. * @param {object} payload - object containing the payload
  524. * @param {string} payload.jobIds - the job ids
  525. * @returns {Promise} - returns a promise (resolve, reject)
  526. */
  527. UPDATE_IMPORT_JOBS(payload) {
  528. return new Promise((resolve, reject) => {
  529. let { jobIds } = payload;
  530. if (!Array.isArray(jobIds)) jobIds = [jobIds];
  531. async.waterfall(
  532. [
  533. next => {
  534. MediaModule.ImportJobModel.find({ _id: { $in: jobIds } }, next);
  535. },
  536. (importJobs, next) => {
  537. async.eachLimit(
  538. importJobs,
  539. 1,
  540. (importJob, next) => {
  541. CacheModule.runJob("PUB", {
  542. channel: "importJob.updated",
  543. value: importJob
  544. })
  545. .then(() => next())
  546. .catch(next);
  547. },
  548. err => {
  549. if (err) next(err);
  550. else next(null, importJobs);
  551. }
  552. );
  553. }
  554. ],
  555. (err, importJobs) => {
  556. if (err && err !== true) return reject(new Error(err));
  557. return resolve({ importJobs });
  558. }
  559. );
  560. });
  561. }
  562. /**
  563. * Remove import job by id from Mongo
  564. *
  565. * @param {object} payload - object containing the payload
  566. * @param {string} payload.jobIds - the job ids
  567. * @returns {Promise} - returns a promise (resolve, reject)
  568. */
  569. REMOVE_IMPORT_JOBS(payload) {
  570. return new Promise((resolve, reject) => {
  571. let { jobIds } = payload;
  572. if (!Array.isArray(jobIds)) jobIds = [jobIds];
  573. async.waterfall(
  574. [
  575. next => {
  576. MediaModule.ImportJobModel.deleteMany({ _id: { $in: jobIds } }, err => {
  577. if (err) next(err);
  578. else next();
  579. });
  580. },
  581. next => {
  582. async.eachLimit(
  583. jobIds,
  584. 1,
  585. (jobId, next) => {
  586. CacheModule.runJob("PUB", {
  587. channel: "importJob.removed",
  588. value: jobId
  589. })
  590. .then(() => next())
  591. .catch(next);
  592. },
  593. next
  594. );
  595. }
  596. ],
  597. err => {
  598. if (err && err !== true) return reject(new Error(err));
  599. return resolve();
  600. }
  601. );
  602. });
  603. }
  604. }
  605. export default new _MediaModule();