media.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 SongsModule;
  9. class _MediaModule extends CoreClass {
  10. // eslint-disable-next-line require-jsdoc
  11. constructor() {
  12. super("media");
  13. MediaModule = this;
  14. }
  15. /**
  16. * Initialises the media module
  17. *
  18. * @returns {Promise} - returns promise (reject, resolve)
  19. */
  20. async initialize() {
  21. this.setStage(1);
  22. CacheModule = this.moduleManager.modules.cache;
  23. DBModule = this.moduleManager.modules.db;
  24. UtilsModule = this.moduleManager.modules.utils;
  25. YouTubeModule = this.moduleManager.modules.youtube;
  26. SongsModule = this.moduleManager.modules.songs;
  27. this.RatingsModel = await DBModule.runJob("GET_MODEL", { modelName: "ratings" });
  28. this.RatingsSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "ratings" });
  29. this.setStage(2);
  30. return new Promise((resolve, reject) => {
  31. async.waterfall(
  32. [
  33. next => {
  34. this.setStage(2);
  35. CacheModule.runJob("HGETALL", { table: "ratings" })
  36. .then(ratings => {
  37. next(null, ratings);
  38. })
  39. .catch(next);
  40. },
  41. (ratings, next) => {
  42. this.setStage(3);
  43. if (!ratings) return next();
  44. const youtubeIds = Object.keys(ratings);
  45. return async.each(
  46. youtubeIds,
  47. (youtubeId, next) => {
  48. MediaModule.RatingsModel.findOne({ youtubeId }, (err, rating) => {
  49. if (err) next(err);
  50. else if (!rating)
  51. CacheModule.runJob("HDEL", {
  52. table: "ratings",
  53. key: youtubeId
  54. })
  55. .then(() => next())
  56. .catch(next);
  57. else next();
  58. });
  59. },
  60. next
  61. );
  62. },
  63. next => {
  64. this.setStage(4);
  65. MediaModule.RatingsModel.find({}, next);
  66. },
  67. (ratings, next) => {
  68. this.setStage(5);
  69. async.each(
  70. ratings,
  71. (rating, next) => {
  72. CacheModule.runJob("HSET", {
  73. table: "ratings",
  74. key: rating.youtubeId,
  75. value: MediaModule.RatingsSchemaCache(rating)
  76. })
  77. .then(() => next())
  78. .catch(next);
  79. },
  80. next
  81. );
  82. }
  83. ],
  84. async err => {
  85. if (err) {
  86. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  87. reject(new Error(err));
  88. } else resolve();
  89. }
  90. );
  91. });
  92. }
  93. /**
  94. * Recalculates dislikes and likes
  95. *
  96. * @param {object} payload - returns an object containing the payload
  97. * @param {string} payload.youtubeId - the youtube id
  98. * @returns {Promise} - returns a promise (resolve, reject)
  99. */
  100. async RECALCULATE_RATINGS(payload) {
  101. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  102. return new Promise((resolve, reject) => {
  103. async.waterfall(
  104. [
  105. next => {
  106. playlistModel.countDocuments(
  107. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, type: "user-liked" },
  108. (err, likes) => {
  109. if (err) return next(err);
  110. return next(null, likes);
  111. }
  112. );
  113. },
  114. (likes, next) => {
  115. playlistModel.countDocuments(
  116. { songs: { $elemMatch: { youtubeId: payload.youtubeId } }, type: "user-disliked" },
  117. (err, dislikes) => {
  118. if (err) return next(err);
  119. return next(err, { likes, dislikes });
  120. }
  121. );
  122. },
  123. ({ likes, dislikes }, next) => {
  124. MediaModule.RatingsModel.findOneAndUpdate(
  125. { youtubeId: payload.youtubeId },
  126. {
  127. $set: {
  128. likes,
  129. dislikes
  130. }
  131. },
  132. { new: true, upsert: true },
  133. next
  134. );
  135. },
  136. (ratings, next) => {
  137. CacheModule.runJob(
  138. "HSET",
  139. {
  140. table: "ratings",
  141. key: payload.youtubeId,
  142. value: ratings
  143. },
  144. this
  145. )
  146. .then(ratings => next(null, ratings))
  147. .catch(next);
  148. }
  149. ],
  150. (err, { likes, dislikes }) => {
  151. if (err) return reject(new Error(err));
  152. return resolve({ likes, dislikes });
  153. }
  154. );
  155. });
  156. }
  157. /**
  158. * Recalculates all dislikes and likes
  159. *
  160. * @returns {Promise} - returns a promise (resolve, reject)
  161. */
  162. RECALCULATE_ALL_RATINGS() {
  163. return new Promise((resolve, reject) => {
  164. async.waterfall(
  165. [
  166. next => {
  167. SongsModule.SongModel.find({}, { youtubeId: true }, next);
  168. },
  169. (songs, next) => {
  170. YouTubeModule.youtubeVideoModel.find({}, { youtubeId: true }, (err, videos) => {
  171. if (err) next(err);
  172. else
  173. next(null, [
  174. ...songs.map(song => song.youtubeId),
  175. ...videos.map(video => video.youtubeId)
  176. ]);
  177. });
  178. },
  179. (youtubeIds, next) => {
  180. async.eachLimit(
  181. youtubeIds,
  182. 2,
  183. (youtubeId, next) => {
  184. MediaModule.runJob("RECALCULATE_RATINGS", { youtubeId }, this)
  185. .then(() => {
  186. next();
  187. })
  188. .catch(err => {
  189. next(err);
  190. });
  191. },
  192. err => {
  193. next(err);
  194. }
  195. );
  196. }
  197. ],
  198. err => {
  199. if (err) return reject(new Error(err));
  200. return resolve();
  201. }
  202. );
  203. });
  204. }
  205. /**
  206. * Gets ratings by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  207. *
  208. * @param {object} payload - object containing the payload
  209. * @param {string} payload.youtubeId - the youtube id
  210. * @param {string} payload.createMissing - whether to create missing ratings
  211. * @returns {Promise} - returns a promise (resolve, reject)
  212. */
  213. GET_RATINGS(payload) {
  214. return new Promise((resolve, reject) => {
  215. async.waterfall(
  216. [
  217. next =>
  218. CacheModule.runJob("HGET", { table: "ratings", key: payload.youtubeId }, this)
  219. .then(ratings => next(null, ratings))
  220. .catch(next),
  221. (ratings, next) => {
  222. if (ratings) return next(true, ratings);
  223. return MediaModule.RatingsModel.findOne({ youtubeId: payload.youtubeId }, next);
  224. },
  225. (ratings, next) => {
  226. if (ratings)
  227. return CacheModule.runJob(
  228. "HSET",
  229. {
  230. table: "ratings",
  231. key: payload.youtubeId,
  232. value: ratings
  233. },
  234. this
  235. ).then(ratings => next(true, ratings));
  236. if (!payload.createMissing) return next("Ratings not found.");
  237. return MediaModule.runJob("RECALCULATE_RATINGS", { youtubeId: payload.youtubeId }, this)
  238. .then(() => next())
  239. .catch(next);
  240. },
  241. next =>
  242. MediaModule.runJob("GET_RATINGS", { youtubeId: payload.youtubeId }, this)
  243. .then(res => next(null, res.ratings))
  244. .catch(next)
  245. ],
  246. (err, ratings) => {
  247. if (err && err !== true) return reject(new Error(err));
  248. return resolve({ ratings });
  249. }
  250. );
  251. });
  252. }
  253. /**
  254. * Remove ratings by id from the cache and Mongo
  255. *
  256. * @param {object} payload - object containing the payload
  257. * @param {string} payload.youtubeIds - the youtube id
  258. * @returns {Promise} - returns a promise (resolve, reject)
  259. */
  260. REMOVE_RATINGS(payload) {
  261. return new Promise((resolve, reject) => {
  262. let { youtubeIds } = payload;
  263. if (!Array.isArray(youtubeIds)) youtubeIds = [youtubeIds];
  264. async.eachLimit(
  265. youtubeIds,
  266. 1,
  267. (youtubeId, next) => {
  268. async.waterfall(
  269. [
  270. next => {
  271. MediaModule.RatingsModel.deleteOne({ youtubeId }, err => {
  272. if (err) next(err);
  273. else next();
  274. });
  275. },
  276. next => {
  277. CacheModule.runJob("HDEL", { table: "ratings", key: youtubeId }, this)
  278. .then(() => {
  279. next();
  280. })
  281. .catch(next);
  282. }
  283. ],
  284. next
  285. );
  286. },
  287. err => {
  288. if (err && err !== true) return reject(new Error(err));
  289. return resolve();
  290. }
  291. );
  292. });
  293. }
  294. /**
  295. * Get song or youtube video by youtubeId
  296. *
  297. * @param {object} payload - an object containing the payload
  298. * @param {string} payload.youtubeId - the youtube id of the song/video
  299. * @param {string} payload.userId - the user id
  300. * @returns {Promise} - returns a promise (resolve, reject)
  301. */
  302. GET_MEDIA(payload) {
  303. return new Promise((resolve, reject) => {
  304. async.waterfall(
  305. [
  306. next => {
  307. SongsModule.SongModel.findOne({ youtubeId: payload.youtubeId }, next);
  308. },
  309. (song, next) => {
  310. if (song && song.duration > 0) next(true, song);
  311. else {
  312. YouTubeModule.runJob(
  313. "GET_VIDEO",
  314. { identifier: payload.youtubeId, createMissing: true },
  315. this
  316. )
  317. .then(response => {
  318. const { youtubeId, title, author, duration } = response.video;
  319. next(null, song, { youtubeId, title, artists: [author], duration });
  320. })
  321. .catch(next);
  322. }
  323. },
  324. (song, youtubeVideo, next) => {
  325. if (song && song.duration <= 0) {
  326. song.duration = youtubeVideo.duration;
  327. song.save({ validateBeforeSave: true }, err => {
  328. if (err) next(err, song);
  329. next(null, song);
  330. });
  331. } else {
  332. next(null, {
  333. ...youtubeVideo,
  334. skipDuration: 0,
  335. requestedBy: payload.userId,
  336. requestedAt: Date.now(),
  337. verified: false
  338. });
  339. }
  340. }
  341. ],
  342. (err, song) => {
  343. if (err && err !== true) return reject(new Error(err));
  344. return resolve({ song });
  345. }
  346. );
  347. });
  348. }
  349. }
  350. export default new _MediaModule();