youtube.js 16 KB

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