media.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. import async from "async";
  2. import config from "config";
  3. import CoreClass from "../core";
  4. let MediaModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. let YouTubeModule;
  9. let SoundCloudModule;
  10. let SpotifyModule;
  11. let SongsModule;
  12. let WSModule;
  13. class _MediaModule extends CoreClass {
  14. // eslint-disable-next-line require-jsdoc
  15. constructor() {
  16. super("media");
  17. MediaModule = this;
  18. }
  19. /**
  20. * Initialises the media module
  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. * @param {object} payload - returns an object containing the payload
  121. * @param {string} payload.mediaSource - the media source
  122. * @returns {Promise} - returns a promise (resolve, reject)
  123. */
  124. async RECALCULATE_RATINGS(payload) {
  125. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  126. return new Promise((resolve, reject) => {
  127. async.waterfall(
  128. [
  129. next => {
  130. playlistModel.countDocuments(
  131. { songs: { $elemMatch: { mediaSource: payload.mediaSource } }, type: "user-liked" },
  132. (err, likes) => {
  133. if (err) return next(err);
  134. return next(null, likes);
  135. }
  136. );
  137. },
  138. (likes, next) => {
  139. playlistModel.countDocuments(
  140. { songs: { $elemMatch: { mediaSource: payload.mediaSource } }, type: "user-disliked" },
  141. (err, dislikes) => {
  142. if (err) return next(err);
  143. return next(err, { likes, dislikes });
  144. }
  145. );
  146. },
  147. ({ likes, dislikes }, next) => {
  148. MediaModule.RatingsModel.findOneAndUpdate(
  149. { mediaSource: payload.mediaSource },
  150. {
  151. $set: {
  152. likes,
  153. dislikes
  154. }
  155. },
  156. { new: true, upsert: true },
  157. next
  158. );
  159. },
  160. (ratings, next) => {
  161. CacheModule.runJob(
  162. "HSET",
  163. {
  164. table: "ratings",
  165. key: payload.mediaSource,
  166. value: ratings
  167. },
  168. this
  169. )
  170. .then(ratings => next(null, ratings))
  171. .catch(next);
  172. }
  173. ],
  174. (err, { likes, dislikes }) => {
  175. if (err) return reject(new Error(err));
  176. return resolve({ likes, dislikes });
  177. }
  178. );
  179. });
  180. }
  181. /**
  182. * Recalculates all dislikes and likes
  183. * @returns {Promise} - returns a promise (resolve, reject)
  184. */
  185. RECALCULATE_ALL_RATINGS() {
  186. return new Promise((resolve, reject) => {
  187. async.waterfall(
  188. [
  189. next => {
  190. SongsModule.SongModel.find({}, { mediaSource: true }, next);
  191. },
  192. (songs, next) => {
  193. // TODO support spotify
  194. YouTubeModule.youtubeVideoModel.find({}, { youtubeId: true }, (err, videos) => {
  195. if (err) next(err);
  196. else
  197. next(null, [
  198. ...songs.map(song => song.mediaSource),
  199. ...videos.map(video => `youtube:${video.youtubeId}`)
  200. ]);
  201. });
  202. },
  203. (mediaSources, next) => {
  204. async.eachLimit(
  205. mediaSources,
  206. 2,
  207. (mediaSource, next) => {
  208. this.publishProgress({
  209. status: "update",
  210. message: `Recalculating ratings for ${mediaSource}`
  211. });
  212. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  213. .then(() => {
  214. next();
  215. })
  216. .catch(err => {
  217. next(err);
  218. });
  219. },
  220. err => {
  221. next(err);
  222. }
  223. );
  224. }
  225. ],
  226. err => {
  227. if (err) return reject(new Error(err));
  228. return resolve();
  229. }
  230. );
  231. });
  232. }
  233. /**
  234. * Gets ratings by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  235. * @param {object} payload - object containing the payload
  236. * @param {string} payload.mediaSource - the media source
  237. * @param {string} payload.createMissing - whether to create missing ratings
  238. * @returns {Promise} - returns a promise (resolve, reject)
  239. */
  240. GET_RATINGS(payload) {
  241. return new Promise((resolve, reject) => {
  242. async.waterfall(
  243. [
  244. next =>
  245. CacheModule.runJob("HGET", { table: "ratings", key: payload.mediaSource }, this)
  246. .then(ratings => next(null, ratings))
  247. .catch(next),
  248. (ratings, next) => {
  249. if (ratings) return next(true, ratings);
  250. return MediaModule.RatingsModel.findOne({ mediaSource: payload.mediaSource }, next);
  251. },
  252. (ratings, next) => {
  253. if (ratings)
  254. return CacheModule.runJob(
  255. "HSET",
  256. {
  257. table: "ratings",
  258. key: payload.mediaSource,
  259. value: ratings
  260. },
  261. this
  262. ).then(ratings => next(true, ratings));
  263. if (!payload.createMissing) return next("Ratings not found.");
  264. return MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource: payload.mediaSource }, this)
  265. .then(() => next())
  266. .catch(next);
  267. },
  268. next =>
  269. MediaModule.runJob("GET_RATINGS", { mediaSource: payload.mediaSource }, this)
  270. .then(res => next(null, res.ratings))
  271. .catch(next)
  272. ],
  273. (err, ratings) => {
  274. if (err && err !== true) return reject(new Error(err));
  275. return resolve({ ratings });
  276. }
  277. );
  278. });
  279. }
  280. /**
  281. * Remove ratings by id from the cache and Mongo
  282. * @param {object} payload - object containing the payload
  283. * @param {string} payload.mediaSources - the media source
  284. * @returns {Promise} - returns a promise (resolve, reject)
  285. */
  286. REMOVE_RATINGS(payload) {
  287. return new Promise((resolve, reject) => {
  288. let { mediaSources } = payload;
  289. if (!Array.isArray(mediaSources)) mediaSources = [mediaSources];
  290. async.eachLimit(
  291. mediaSources,
  292. 1,
  293. (mediaSource, next) => {
  294. async.waterfall(
  295. [
  296. next => {
  297. MediaModule.RatingsModel.deleteOne({ mediaSource }, err => {
  298. if (err) next(err);
  299. else next();
  300. });
  301. },
  302. next => {
  303. CacheModule.runJob("HDEL", { table: "ratings", key: mediaSource }, this)
  304. .then(() => {
  305. next();
  306. })
  307. .catch(next);
  308. }
  309. ],
  310. next
  311. );
  312. },
  313. err => {
  314. if (err && err !== true) return reject(new Error(err));
  315. return resolve();
  316. }
  317. );
  318. });
  319. }
  320. /**
  321. * Get song or youtube video by mediaSource
  322. * @param {object} payload - an object containing the payload
  323. * @param {string} payload.mediaSource - the media source of the song/video
  324. * @param {string} payload.userId - the user id
  325. * @returns {Promise} - returns a promise (resolve, reject)
  326. */
  327. GET_MEDIA(payload) {
  328. return new Promise((resolve, reject) => {
  329. async.waterfall(
  330. [
  331. next => {
  332. SongsModule.SongModel.findOne({ mediaSource: payload.mediaSource }, next);
  333. },
  334. (song, next) => {
  335. if (song && song.duration > 0) return next(true, song);
  336. if (payload.mediaSource.startsWith("youtube:")) {
  337. const youtubeId = payload.mediaSource.split(":")[1];
  338. return YouTubeModule.runJob(
  339. "GET_VIDEOS",
  340. { identifiers: [youtubeId], createMissing: true },
  341. this
  342. )
  343. .then(response => {
  344. if (response.videos.length === 0) {
  345. next("Media not found.");
  346. return;
  347. }
  348. const { youtubeId, title, author, duration } = response.videos[0];
  349. next(null, song, {
  350. mediaSource: `youtube:${youtubeId}`,
  351. title,
  352. artists: [author],
  353. duration
  354. });
  355. })
  356. .catch(next);
  357. }
  358. if (config.get("experimental.soundcloud")) {
  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. }
  397. if (config.get("experimental.spotify") && 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. * @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_VIDEOS",
  460. { identifiers: [youtubeId], createMissing: true },
  461. this
  462. )
  463. .then(response => {
  464. const { youtubeId, title, author, duration } = response.videos[0];
  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. if (config.get("experimental.soundcloud"))
  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. * @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. * @param {object} payload - object containing the payload
  564. * @param {string} payload.jobIds - the job ids
  565. * @returns {Promise} - returns a promise (resolve, reject)
  566. */
  567. REMOVE_IMPORT_JOBS(payload) {
  568. return new Promise((resolve, reject) => {
  569. let { jobIds } = payload;
  570. if (!Array.isArray(jobIds)) jobIds = [jobIds];
  571. async.waterfall(
  572. [
  573. next => {
  574. MediaModule.ImportJobModel.deleteMany({ _id: { $in: jobIds } }, err => {
  575. if (err) next(err);
  576. else next();
  577. });
  578. },
  579. next => {
  580. async.eachLimit(
  581. jobIds,
  582. 1,
  583. (jobId, next) => {
  584. CacheModule.runJob("PUB", {
  585. channel: "importJob.removed",
  586. value: jobId
  587. })
  588. .then(() => next())
  589. .catch(next);
  590. },
  591. next
  592. );
  593. }
  594. ],
  595. err => {
  596. if (err && err !== true) return reject(new Error(err));
  597. return resolve();
  598. }
  599. );
  600. });
  601. }
  602. }
  603. export default new _MediaModule();