youtube.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. import mongoose from "mongoose";
  2. import async from "async";
  3. import { isAdminRequired, isLoginRequired } from "./hooks";
  4. // eslint-disable-next-line
  5. import moduleManager from "../../index";
  6. const DBModule = moduleManager.modules.db;
  7. const CacheModule = moduleManager.modules.cache;
  8. const UtilsModule = moduleManager.modules.utils;
  9. const YouTubeModule = moduleManager.modules.youtube;
  10. export default {
  11. /**
  12. * Returns details about the YouTube quota usage
  13. *
  14. * @returns {{status: string, data: object}}
  15. */
  16. getQuotaStatus: isAdminRequired(function getQuotaStatus(session, fromDate, cb) {
  17. YouTubeModule.runJob("GET_QUOTA_STATUS", { fromDate }, this)
  18. .then(response => {
  19. this.log("SUCCESS", "YOUTUBE_GET_QUOTA_STATUS", `Getting quota status was successful.`);
  20. return cb({ status: "success", data: { status: response.status } });
  21. })
  22. .catch(async err => {
  23. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  24. this.log("ERROR", "YOUTUBE_GET_QUOTA_STATUS", `Getting quota status failed. "${err}"`);
  25. return cb({ status: "error", message: err });
  26. });
  27. }),
  28. /**
  29. * Returns YouTube quota chart data
  30. *
  31. * @param {object} session - the session object automatically added by the websocket
  32. * @param timePeriod - either hours or days
  33. * @param startDate - beginning date
  34. * @param endDate - end date
  35. * @param dataType - either usage or count
  36. * @returns {{status: string, data: object}}
  37. */
  38. getQuotaChartData: isAdminRequired(function getQuotaChartData(
  39. session,
  40. timePeriod,
  41. startDate,
  42. endDate,
  43. dataType,
  44. cb
  45. ) {
  46. YouTubeModule.runJob(
  47. "GET_QUOTA_CHART_DATA",
  48. { timePeriod, startDate: new Date(startDate), endDate: new Date(endDate), dataType },
  49. this
  50. )
  51. .then(data => {
  52. this.log("SUCCESS", "YOUTUBE_GET_QUOTA_CHART_DATA", `Getting quota chart data was successful.`);
  53. return cb({ status: "success", data });
  54. })
  55. .catch(async err => {
  56. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  57. this.log("ERROR", "YOUTUBE_GET_QUOTA_CHART_DATA", `Getting quota chart data failed. "${err}"`);
  58. return cb({ status: "error", message: err });
  59. });
  60. }),
  61. /**
  62. * Gets api requests, used in the admin youtube page by the AdvancedTable component
  63. *
  64. * @param {object} session - the session object automatically added by the websocket
  65. * @param page - the page
  66. * @param pageSize - the size per page
  67. * @param properties - the properties to return for each news item
  68. * @param sort - the sort object
  69. * @param queries - the queries array
  70. * @param operator - the operator for queries
  71. * @param cb
  72. */
  73. getApiRequests: isAdminRequired(async function getApiRequests(
  74. session,
  75. page,
  76. pageSize,
  77. properties,
  78. sort,
  79. queries,
  80. operator,
  81. cb
  82. ) {
  83. async.waterfall(
  84. [
  85. next => {
  86. DBModule.runJob(
  87. "GET_DATA",
  88. {
  89. page,
  90. pageSize,
  91. properties,
  92. sort,
  93. queries,
  94. operator,
  95. modelName: "youtubeApiRequest",
  96. blacklistedProperties: [],
  97. specialProperties: {},
  98. specialQueries: {}
  99. },
  100. this
  101. )
  102. .then(response => {
  103. next(null, response);
  104. })
  105. .catch(err => {
  106. next(err);
  107. });
  108. }
  109. ],
  110. async (err, response) => {
  111. if (err && err !== true) {
  112. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  113. this.log("ERROR", "YOUTUBE_GET_API_REQUESTS", `Failed to get YouTube api requests. "${err}"`);
  114. return cb({ status: "error", message: err });
  115. }
  116. this.log("SUCCESS", "YOUTUBE_GET_API_REQUESTS", `Fetched YouTube api requests successfully.`);
  117. return cb({
  118. status: "success",
  119. message: "Successfully fetched YouTube api requests.",
  120. data: response
  121. });
  122. }
  123. );
  124. }),
  125. /**
  126. * Returns a specific api request
  127. *
  128. * @returns {{status: string, data: object}}
  129. */
  130. getApiRequest: isAdminRequired(function getApiRequest(session, apiRequestId, cb) {
  131. if (!mongoose.Types.ObjectId.isValid(apiRequestId))
  132. return cb({ status: "error", message: "Api request id is not a valid ObjectId." });
  133. return YouTubeModule.runJob("GET_API_REQUEST", { apiRequestId }, this)
  134. .then(response => {
  135. this.log(
  136. "SUCCESS",
  137. "YOUTUBE_GET_API_REQUEST",
  138. `Getting api request with id ${apiRequestId} was successful.`
  139. );
  140. return cb({ status: "success", data: { apiRequest: response.apiRequest } });
  141. })
  142. .catch(async err => {
  143. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  144. this.log(
  145. "ERROR",
  146. "YOUTUBE_GET_API_REQUEST",
  147. `Getting api request with id ${apiRequestId} failed. "${err}"`
  148. );
  149. return cb({ status: "error", message: err });
  150. });
  151. }),
  152. /**
  153. * Reset stored API requests
  154. *
  155. * @returns {{status: string, data: object}}
  156. */
  157. resetStoredApiRequests: isAdminRequired(async function resetStoredApiRequests(session, cb) {
  158. YouTubeModule.runJob("RESET_STORED_API_REQUESTS", {}, this)
  159. .then(() => {
  160. this.log(
  161. "SUCCESS",
  162. "YOUTUBE_RESET_STORED_API_REQUESTS",
  163. `Resetting stored API requests was successful.`
  164. );
  165. return cb({ status: "success", message: "Successfully reset stored YouTube API requests" });
  166. })
  167. .catch(async err => {
  168. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  169. this.log(
  170. "ERROR",
  171. "YOUTUBE_RESET_STORED_API_REQUESTS",
  172. `Resetting stored API requests failed. "${err}"`
  173. );
  174. return cb({ status: "error", message: err });
  175. });
  176. }),
  177. /**
  178. * Remove stored API requests
  179. *
  180. * @returns {{status: string, data: object}}
  181. */
  182. removeStoredApiRequest: isAdminRequired(function removeStoredApiRequest(session, requestId, cb) {
  183. YouTubeModule.runJob("REMOVE_STORED_API_REQUEST", { requestId }, this)
  184. .then(() => {
  185. this.log(
  186. "SUCCESS",
  187. "YOUTUBE_REMOVE_STORED_API_REQUEST",
  188. `Removing stored API request "${requestId}" was successful.`
  189. );
  190. return cb({ status: "success", message: "Successfully removed stored YouTube API request" });
  191. })
  192. .catch(async err => {
  193. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  194. this.log(
  195. "ERROR",
  196. "YOUTUBE_REMOVE_STORED_API_REQUEST",
  197. `Removing stored API request "${requestId}" failed. "${err}"`
  198. );
  199. return cb({ status: "error", message: err });
  200. });
  201. }),
  202. /**
  203. * Gets videos, used in the admin youtube page by the AdvancedTable component
  204. *
  205. * @param {object} session - the session object automatically added by the websocket
  206. * @param page - the page
  207. * @param pageSize - the size per page
  208. * @param properties - the properties to return for each news item
  209. * @param sort - the sort object
  210. * @param queries - the queries array
  211. * @param operator - the operator for queries
  212. * @param cb
  213. */
  214. getVideos: isAdminRequired(async function getVideos(
  215. session,
  216. page,
  217. pageSize,
  218. properties,
  219. sort,
  220. queries,
  221. operator,
  222. cb
  223. ) {
  224. async.waterfall(
  225. [
  226. next => {
  227. DBModule.runJob(
  228. "GET_DATA",
  229. {
  230. page,
  231. pageSize,
  232. properties,
  233. sort,
  234. queries,
  235. operator,
  236. modelName: "youtubeVideo",
  237. blacklistedProperties: [],
  238. specialProperties: {},
  239. specialQueries: {},
  240. specialFilters: {
  241. importJob: importJobId => [
  242. {
  243. $lookup: {
  244. from: "importjobs",
  245. let: { youtubeId: "$youtubeId" },
  246. pipeline: [
  247. {
  248. $match: {
  249. _id: mongoose.Types.ObjectId(importJobId)
  250. }
  251. },
  252. {
  253. $addFields: {
  254. importJob: {
  255. $in: ["$$youtubeId", "$response.successfulVideoIds"]
  256. }
  257. }
  258. },
  259. {
  260. $project: {
  261. importJob: 1,
  262. _id: 0
  263. }
  264. }
  265. ],
  266. as: "importJob"
  267. }
  268. },
  269. {
  270. $unwind: "$importJob"
  271. },
  272. {
  273. $set: {
  274. importJob: "$importJob.importJob"
  275. }
  276. }
  277. ]
  278. }
  279. },
  280. this
  281. )
  282. .then(response => {
  283. next(null, response);
  284. })
  285. .catch(err => {
  286. next(err);
  287. });
  288. }
  289. ],
  290. async (err, response) => {
  291. if (err && err !== true) {
  292. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  293. this.log("ERROR", "YOUTUBE_GET_VIDEOS", `Failed to get YouTube videos. "${err}"`);
  294. return cb({ status: "error", message: err });
  295. }
  296. this.log("SUCCESS", "YOUTUBE_GET_VIDEOS", `Fetched YouTube videos successfully.`);
  297. return cb({
  298. status: "success",
  299. message: "Successfully fetched YouTube videos.",
  300. data: response
  301. });
  302. }
  303. );
  304. }),
  305. /**
  306. * Get a YouTube video
  307. *
  308. * @returns {{status: string, data: object}}
  309. */
  310. getVideo: isLoginRequired(function getVideo(session, identifier, createMissing, cb) {
  311. YouTubeModule.runJob("GET_VIDEO", { identifier, createMissing }, this)
  312. .then(res => {
  313. this.log("SUCCESS", "YOUTUBE_GET_VIDEO", `Fetching video was successful.`);
  314. return cb({ status: "success", message: "Successfully fetched YouTube video", data: res.video });
  315. })
  316. .catch(async err => {
  317. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  318. this.log("ERROR", "YOUTUBE_GET_VIDEO", `Fetching video failed. "${err}"`);
  319. return cb({ status: "error", message: err });
  320. });
  321. }),
  322. /**
  323. * Remove YouTube videos
  324. *
  325. * @returns {{status: string, data: object}}
  326. */
  327. removeVideos: isAdminRequired(function removeVideos(session, videoIds, cb) {
  328. YouTubeModule.runJob("REMOVE_VIDEOS", { videoIds }, this)
  329. .then(() => {
  330. this.log("SUCCESS", "YOUTUBE_REMOVE_VIDEOS", `Removing videos was successful.`);
  331. return cb({ status: "success", message: "Successfully removed YouTube videos" });
  332. })
  333. .catch(async err => {
  334. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  335. this.log("ERROR", "YOUTUBE_REMOVE_VIDEOS", `Removing videos failed. "${err}"`);
  336. return cb({ status: "error", message: err });
  337. });
  338. }),
  339. /**
  340. * Requests a set of YouTube videos
  341. *
  342. * @param {object} session - the session object automatically added by the websocket
  343. * @param {string} url - the url of the the YouTube playlist
  344. * @param {boolean} musicOnly - whether to only get music from the playlist
  345. * @param {boolean} musicOnly - whether to return videos
  346. * @param {Function} cb - gets called with the result
  347. */
  348. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnVideos, cb) {
  349. YouTubeModule.runJob("REQUEST_SET", { url, musicOnly, returnVideos }, this)
  350. .then(response => {
  351. this.log(
  352. "SUCCESS",
  353. "REQUEST_SET",
  354. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  355. );
  356. return cb({
  357. status: "success",
  358. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  359. videos: returnVideos ? response.videos : null
  360. });
  361. })
  362. .catch(async err => {
  363. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  364. this.log(
  365. "ERROR",
  366. "REQUEST_SET",
  367. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  368. );
  369. return cb({ status: "error", message: err });
  370. });
  371. }),
  372. /**
  373. * Requests a set of YouTube videos as an admin
  374. *
  375. * @param {object} session - the session object automatically added by the websocket
  376. * @param {string} url - the url of the the YouTube playlist
  377. * @param {boolean} musicOnly - whether to only get music from the playlist
  378. * @param {boolean} musicOnly - whether to return videos
  379. * @param {Function} cb - gets called with the result
  380. */
  381. requestSetAdmin: isAdminRequired(async function requestSetAdmin(session, url, musicOnly, returnVideos, cb) {
  382. const importJobModel = await DBModule.runJob("GET_MODEL", { modelName: "importJob" }, this);
  383. this.keepLongJob();
  384. this.publishProgress({
  385. status: "started",
  386. title: "Import playlist",
  387. message: "Importing playlist.",
  388. id: this.toString()
  389. });
  390. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  391. await CacheModule.runJob(
  392. "PUB",
  393. {
  394. channel: "longJob.added",
  395. value: { jobId: this.toString(), userId: session.userId }
  396. },
  397. this
  398. );
  399. async.waterfall(
  400. [
  401. next => {
  402. importJobModel.create(
  403. {
  404. type: "youtube",
  405. query: {
  406. url,
  407. musicOnly
  408. },
  409. status: "in-progress",
  410. response: {},
  411. requestedBy: session.userId,
  412. requestedAt: Date.now()
  413. },
  414. next
  415. );
  416. },
  417. (importJob, next) => {
  418. YouTubeModule.runJob("REQUEST_SET", { url, musicOnly, returnVideos }, this)
  419. .then(response => {
  420. next(null, importJob, response);
  421. })
  422. .catch(err => {
  423. next(err, importJob);
  424. });
  425. },
  426. (importJob, response, next) => {
  427. importJobModel.updateOne(
  428. { _id: importJob._id },
  429. {
  430. $set: {
  431. status: "success",
  432. response: {
  433. failed: response.failed,
  434. successful: response.successful,
  435. alreadyInDatabase: response.alreadyInDatabase,
  436. successfulVideoIds: response.successfulVideoIds,
  437. failedVideoIds: response.failedVideoIds
  438. }
  439. }
  440. },
  441. err => {
  442. next(err, importJob, response);
  443. }
  444. );
  445. }
  446. ],
  447. async (err, importJob, response) => {
  448. if (err) {
  449. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  450. this.log(
  451. "ERROR",
  452. "REQUEST_SET_ADMIN",
  453. `Importing a YouTube playlist to be requested failed for admin "${session.userId}". "${err}"`
  454. );
  455. importJobModel.updateOne({ _id: importJob._id }, { $set: { status: "error" } });
  456. return cb({ status: "error", message: err });
  457. }
  458. this.log(
  459. "SUCCESS",
  460. "REQUEST_SET_ADMIN",
  461. `Successfully imported a YouTube playlist to be requested for admin "${session.userId}".`
  462. );
  463. this.publishProgress({
  464. status: "success",
  465. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`
  466. });
  467. return cb({
  468. status: "success",
  469. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  470. videos: returnVideos ? response.videos : null
  471. });
  472. }
  473. );
  474. })
  475. };