media.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. if (payload.mediaSource.startsWith("youtube:")) {
  342. const youtubeId = payload.mediaSource.split(":")[1];
  343. return YouTubeModule.runJob(
  344. "GET_VIDEO",
  345. { identifier: youtubeId, createMissing: true },
  346. this
  347. )
  348. .then(response => {
  349. const { youtubeId, title, author, duration } = response.video;
  350. next(null, song, {
  351. mediaSource: `youtube:${youtubeId}`,
  352. title,
  353. artists: [author],
  354. duration
  355. });
  356. })
  357. .catch(next);
  358. }
  359. if (payload.mediaSource.startsWith("soundcloud:")) {
  360. const trackId = payload.mediaSource.split(":")[1];
  361. return SoundCloudModule.runJob(
  362. "GET_TRACK",
  363. { identifier: trackId, createMissing: true },
  364. this
  365. )
  366. .then(response => {
  367. const { trackId, title, username, artworkUrl, duration } = response.track;
  368. next(null, song, {
  369. mediaSource: `soundcloud:${trackId}`,
  370. title,
  371. artists: [username],
  372. thumbnail: artworkUrl,
  373. duration
  374. });
  375. })
  376. .catch(next);
  377. }
  378. if (payload.mediaSource.indexOf("soundcloud.com") !== -1) {
  379. return SoundCloudModule.runJob(
  380. "GET_TRACK_FROM_URL",
  381. { identifier: payload.mediaSource, createMissing: true },
  382. this
  383. )
  384. .then(response => {
  385. const { trackId, title, username, artworkUrl, duration } = response.track;
  386. next(null, song, {
  387. mediaSource: `soundcloud:${trackId}`,
  388. title,
  389. artists: [username],
  390. thumbnail: artworkUrl,
  391. duration
  392. });
  393. })
  394. .catch(next);
  395. }
  396. if (payload.mediaSource.startsWith("spotify:")) {
  397. const trackId = payload.mediaSource.split(":")[1];
  398. return SpotifyModule.runJob("GET_TRACK", { identifier: trackId, createMissing: true }, this)
  399. .then(response => {
  400. const { trackId, name, artists, albumImageUrl, duration } = response.track;
  401. next(null, song, {
  402. mediaSource: `spotify:${trackId}`,
  403. title: name,
  404. artists,
  405. thumbnail: albumImageUrl,
  406. duration
  407. });
  408. })
  409. .catch(next);
  410. }
  411. return next("Invalid media source provided.");
  412. },
  413. (song, youtubeVideo, next) => {
  414. if (song && song.duration <= 0) {
  415. song.duration = youtubeVideo.duration;
  416. song.save({ validateBeforeSave: true }, err => {
  417. if (err) next(err, song);
  418. next(null, song);
  419. });
  420. } else {
  421. next(null, {
  422. ...youtubeVideo,
  423. skipDuration: 0,
  424. requestedBy: payload.userId,
  425. requestedAt: Date.now(),
  426. verified: false
  427. });
  428. }
  429. }
  430. ],
  431. (err, song) => {
  432. if (err && err !== true) return reject(new Error(err));
  433. return resolve({ song });
  434. }
  435. );
  436. });
  437. }
  438. /**
  439. * Gets media from media sources
  440. *
  441. * @param {object} payload - an object containing the payload
  442. * @param {string} payload.mediaSources - the media sources
  443. * @returns {Promise} - returns a promise (resolve, reject)
  444. */
  445. GET_MEDIA_FROM_MEDIA_SOURCES(payload) {
  446. return new Promise((resolve, reject) => {
  447. const songMap = {};
  448. const youtubeMediaSources = payload.mediaSources.filter(mediaSource => mediaSource.startsWith("youtube:"));
  449. const soundcloudMediaSources = payload.mediaSources.filter(mediaSource =>
  450. mediaSource.startsWith("soundcloud:")
  451. );
  452. async.waterfall(
  453. [
  454. next => {
  455. const allPromises = [];
  456. youtubeMediaSources.forEach(mediaSource => {
  457. const youtubeId = mediaSource.split(":")[1];
  458. const promise = YouTubeModule.runJob(
  459. "GET_VIDEO",
  460. { identifier: youtubeId, createMissing: true },
  461. this
  462. )
  463. .then(response => {
  464. const { youtubeId, title, author, duration } = response.video;
  465. songMap[mediaSource] = {
  466. mediaSource: `youtube:${youtubeId}`,
  467. title,
  468. artists: [author],
  469. duration
  470. };
  471. })
  472. .catch(err => {
  473. MediaModule.log(
  474. "ERROR",
  475. `Failed to get media in GET_MEDIA_FROM_MEDIA_SOURCES with mediaSource ${mediaSource} and error`,
  476. typeof err === "string" ? err : err.message
  477. );
  478. });
  479. allPromises.push(promise);
  480. });
  481. soundcloudMediaSources.forEach(mediaSource => {
  482. const trackId = mediaSource.split(":")[1];
  483. const promise = SoundCloudModule.runJob(
  484. "GET_TRACK",
  485. { identifier: trackId, createMissing: true },
  486. this
  487. )
  488. .then(response => {
  489. const { trackId, title, username, artworkUrl, duration } = response.track;
  490. songMap[mediaSource] = {
  491. mediaSource: `soundcloud:${trackId}`,
  492. title,
  493. artists: [username],
  494. thumbnail: artworkUrl,
  495. duration
  496. };
  497. })
  498. .catch(err => {
  499. MediaModule.log(
  500. "ERROR",
  501. `Failed to get media in GET_MEDIA_FROM_MEDIA_SOURCES with mediaSource ${mediaSource} and error`,
  502. typeof err === "string" ? err : err.message
  503. );
  504. });
  505. allPromises.push(promise);
  506. });
  507. Promise.allSettled(allPromises).then(() => {
  508. next();
  509. });
  510. }
  511. ],
  512. err => {
  513. if (err && err !== true) return reject(new Error(err));
  514. return resolve(songMap);
  515. }
  516. );
  517. });
  518. }
  519. /**
  520. * Remove import job by id from Mongo
  521. *
  522. * @param {object} payload - object containing the payload
  523. * @param {string} payload.jobIds - the job ids
  524. * @returns {Promise} - returns a promise (resolve, reject)
  525. */
  526. UPDATE_IMPORT_JOBS(payload) {
  527. return new Promise((resolve, reject) => {
  528. let { jobIds } = payload;
  529. if (!Array.isArray(jobIds)) jobIds = [jobIds];
  530. async.waterfall(
  531. [
  532. next => {
  533. MediaModule.ImportJobModel.find({ _id: { $in: jobIds } }, next);
  534. },
  535. (importJobs, next) => {
  536. async.eachLimit(
  537. importJobs,
  538. 1,
  539. (importJob, next) => {
  540. CacheModule.runJob("PUB", {
  541. channel: "importJob.updated",
  542. value: importJob
  543. })
  544. .then(() => next())
  545. .catch(next);
  546. },
  547. err => {
  548. if (err) next(err);
  549. else next(null, importJobs);
  550. }
  551. );
  552. }
  553. ],
  554. (err, importJobs) => {
  555. if (err && err !== true) return reject(new Error(err));
  556. return resolve({ importJobs });
  557. }
  558. );
  559. });
  560. }
  561. /**
  562. * Remove import job by id from Mongo
  563. *
  564. * @param {object} payload - object containing the payload
  565. * @param {string} payload.jobIds - the job ids
  566. * @returns {Promise} - returns a promise (resolve, reject)
  567. */
  568. REMOVE_IMPORT_JOBS(payload) {
  569. return new Promise((resolve, reject) => {
  570. let { jobIds } = payload;
  571. if (!Array.isArray(jobIds)) jobIds = [jobIds];
  572. async.waterfall(
  573. [
  574. next => {
  575. MediaModule.ImportJobModel.deleteMany({ _id: { $in: jobIds } }, err => {
  576. if (err) next(err);
  577. else next();
  578. });
  579. },
  580. next => {
  581. async.eachLimit(
  582. jobIds,
  583. 1,
  584. (jobId, next) => {
  585. CacheModule.runJob("PUB", {
  586. channel: "importJob.removed",
  587. value: jobId
  588. })
  589. .then(() => next())
  590. .catch(next);
  591. },
  592. next
  593. );
  594. }
  595. ],
  596. err => {
  597. if (err && err !== true) return reject(new Error(err));
  598. return resolve();
  599. }
  600. );
  601. });
  602. }
  603. }
  604. export default new _MediaModule();