youtube.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. * @returns {{status: string, data: object}}
  16. */
  17. getQuotaStatus: useHasPermission("admin.view.youtube", function getQuotaStatus(session, fromDate, cb) {
  18. YouTubeModule.runJob("GET_QUOTA_STATUS", { fromDate }, this)
  19. .then(response => {
  20. this.log("SUCCESS", "YOUTUBE_GET_QUOTA_STATUS", `Getting quota status was successful.`);
  21. return cb({ status: "success", data: { status: response.status } });
  22. })
  23. .catch(async err => {
  24. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  25. this.log("ERROR", "YOUTUBE_GET_QUOTA_STATUS", `Getting quota status failed. "${err}"`);
  26. return cb({ status: "error", message: err });
  27. });
  28. }),
  29. /**
  30. * Returns YouTube quota chart data
  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: useHasPermission(
  39. "admin.view.youtube",
  40. function getQuotaChartData(session, timePeriod, startDate, endDate, dataType, cb) {
  41. YouTubeModule.runJob(
  42. "GET_QUOTA_CHART_DATA",
  43. { timePeriod, startDate: new Date(startDate), endDate: new Date(endDate), dataType },
  44. this
  45. )
  46. .then(data => {
  47. this.log("SUCCESS", "YOUTUBE_GET_QUOTA_CHART_DATA", `Getting quota chart data was successful.`);
  48. return cb({ status: "success", data });
  49. })
  50. .catch(async err => {
  51. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  52. this.log("ERROR", "YOUTUBE_GET_QUOTA_CHART_DATA", `Getting quota chart data failed. "${err}"`);
  53. return cb({ status: "error", message: err });
  54. });
  55. }
  56. ),
  57. /**
  58. * Gets api requests, used in the admin youtube page by the AdvancedTable component
  59. * @param {object} session - the session object automatically added by the websocket
  60. * @param page - the page
  61. * @param pageSize - the size per page
  62. * @param properties - the properties to return for each news item
  63. * @param sort - the sort object
  64. * @param queries - the queries array
  65. * @param operator - the operator for queries
  66. * @param cb
  67. */
  68. getApiRequests: useHasPermission(
  69. "admin.view.youtube",
  70. async function getApiRequests(session, page, pageSize, properties, sort, queries, operator, cb) {
  71. async.waterfall(
  72. [
  73. next => {
  74. DBModule.runJob(
  75. "GET_DATA",
  76. {
  77. page,
  78. pageSize,
  79. properties,
  80. sort,
  81. queries,
  82. operator,
  83. modelName: "youtubeApiRequest",
  84. blacklistedProperties: [],
  85. specialProperties: {},
  86. specialQueries: {}
  87. },
  88. this
  89. )
  90. .then(response => {
  91. next(null, response);
  92. })
  93. .catch(err => {
  94. next(err);
  95. });
  96. }
  97. ],
  98. async (err, response) => {
  99. if (err && err !== true) {
  100. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  101. this.log("ERROR", "YOUTUBE_GET_API_REQUESTS", `Failed to get YouTube api requests. "${err}"`);
  102. return cb({ status: "error", message: err });
  103. }
  104. this.log("SUCCESS", "YOUTUBE_GET_API_REQUESTS", `Fetched YouTube api requests successfully.`);
  105. return cb({
  106. status: "success",
  107. message: "Successfully fetched YouTube api requests.",
  108. data: response
  109. });
  110. }
  111. );
  112. }
  113. ),
  114. /**
  115. * Returns a specific api request
  116. * @returns {{status: string, data: object}}
  117. */
  118. getApiRequest: useHasPermission("youtube.getApiRequest", function getApiRequest(session, apiRequestId, cb) {
  119. if (!mongoose.Types.ObjectId.isValid(apiRequestId))
  120. return cb({ status: "error", message: "Api request id is not a valid ObjectId." });
  121. return YouTubeModule.runJob("GET_API_REQUEST", { apiRequestId }, this)
  122. .then(response => {
  123. this.log(
  124. "SUCCESS",
  125. "YOUTUBE_GET_API_REQUEST",
  126. `Getting api request with id ${apiRequestId} was successful.`
  127. );
  128. return cb({ status: "success", data: { apiRequest: response.apiRequest } });
  129. })
  130. .catch(async err => {
  131. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  132. this.log(
  133. "ERROR",
  134. "YOUTUBE_GET_API_REQUEST",
  135. `Getting api request with id ${apiRequestId} failed. "${err}"`
  136. );
  137. return cb({ status: "error", message: err });
  138. });
  139. }),
  140. /**
  141. * Reset stored API requests
  142. * @returns {{status: string, data: object}}
  143. */
  144. resetStoredApiRequests: useHasPermission(
  145. "youtube.resetStoredApiRequests",
  146. async function resetStoredApiRequests(session, cb) {
  147. this.keepLongJob();
  148. this.publishProgress({
  149. status: "started",
  150. title: "Reset stored API requests",
  151. message: "Resetting stored API requests.",
  152. id: this.toString()
  153. });
  154. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  155. await CacheModule.runJob(
  156. "PUB",
  157. {
  158. channel: "longJob.added",
  159. value: { jobId: this.toString(), userId: session.userId }
  160. },
  161. this
  162. );
  163. YouTubeModule.runJob("RESET_STORED_API_REQUESTS", {}, this)
  164. .then(() => {
  165. this.log(
  166. "SUCCESS",
  167. "YOUTUBE_RESET_STORED_API_REQUESTS",
  168. `Resetting stored API requests was successful.`
  169. );
  170. this.publishProgress({
  171. status: "success",
  172. message: "Successfully reset stored YouTube API requests."
  173. });
  174. return cb({ status: "success", message: "Successfully reset stored YouTube API requests" });
  175. })
  176. .catch(async err => {
  177. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  178. this.log(
  179. "ERROR",
  180. "YOUTUBE_RESET_STORED_API_REQUESTS",
  181. `Resetting stored API requests failed. "${err}"`
  182. );
  183. this.publishProgress({
  184. status: "error",
  185. message: err
  186. });
  187. return cb({ status: "error", message: err });
  188. });
  189. }
  190. ),
  191. /**
  192. * Remove stored API requests
  193. * @returns {{status: string, data: object}}
  194. */
  195. removeStoredApiRequest: useHasPermission(
  196. "youtube.removeStoredApiRequest",
  197. function removeStoredApiRequest(session, requestId, cb) {
  198. YouTubeModule.runJob("REMOVE_STORED_API_REQUEST", { requestId }, this)
  199. .then(() => {
  200. this.log(
  201. "SUCCESS",
  202. "YOUTUBE_REMOVE_STORED_API_REQUEST",
  203. `Removing stored API request "${requestId}" was successful.`
  204. );
  205. return cb({ status: "success", message: "Successfully removed stored YouTube API request" });
  206. })
  207. .catch(async err => {
  208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  209. this.log(
  210. "ERROR",
  211. "YOUTUBE_REMOVE_STORED_API_REQUEST",
  212. `Removing stored API request "${requestId}" failed. "${err}"`
  213. );
  214. return cb({ status: "error", message: err });
  215. });
  216. }
  217. ),
  218. /**
  219. * Gets videos, used in the admin youtube page by the AdvancedTable component
  220. * @param {object} session - the session object automatically added by the websocket
  221. * @param page - the page
  222. * @param pageSize - the size per page
  223. * @param properties - the properties to return for each news item
  224. * @param sort - the sort object
  225. * @param queries - the queries array
  226. * @param operator - the operator for queries
  227. * @param {Function} cb - gets called with the result
  228. */
  229. getVideos: useHasPermission(
  230. "admin.view.youtubeVideos",
  231. async function getVideos(session, page, pageSize, properties, sort, queries, operator, cb) {
  232. async.waterfall(
  233. [
  234. next => {
  235. DBModule.runJob(
  236. "GET_DATA",
  237. {
  238. page,
  239. pageSize,
  240. properties,
  241. sort,
  242. queries,
  243. operator,
  244. modelName: "youtubeVideo",
  245. blacklistedProperties: [],
  246. specialProperties: {
  247. songId: [
  248. // Fetch songs from songs collection with a matching mediaSource, which we first need to assemble
  249. {
  250. $lookup: {
  251. from: "songs",
  252. let: {
  253. mediaSource: { $concat: ["youtube:", "$youtubeId"] }
  254. },
  255. pipeline: [
  256. {
  257. $match: {
  258. $expr: { $eq: ["$mediaSource", "$$mediaSource"] }
  259. }
  260. }
  261. ],
  262. as: "song"
  263. }
  264. },
  265. // Turn the array of songs returned in the last step into one object, since only one song should have been returned maximum
  266. {
  267. $unwind: {
  268. path: "$song",
  269. preserveNullAndEmptyArrays: true
  270. }
  271. },
  272. // Add new field songId, which grabs the song object's _id and tries turning it into a string
  273. {
  274. $addFields: {
  275. songId: {
  276. $convert: {
  277. input: "$song._id",
  278. to: "string",
  279. onError: "",
  280. onNull: ""
  281. }
  282. }
  283. }
  284. },
  285. // Cleanup, don't return the song object for any further steps
  286. {
  287. $project: {
  288. song: 0
  289. }
  290. }
  291. ]
  292. },
  293. specialQueries: {},
  294. specialFilters: {
  295. importJob: importJobId => [
  296. {
  297. $lookup: {
  298. from: "importjobs",
  299. let: { youtubeId: "$youtubeId" },
  300. pipeline: [
  301. {
  302. $match: {
  303. _id: mongoose.Types.ObjectId(importJobId)
  304. }
  305. },
  306. {
  307. $addFields: {
  308. importJob: {
  309. $in: ["$$youtubeId", "$response.successfulVideoIds"]
  310. }
  311. }
  312. },
  313. {
  314. $project: {
  315. importJob: 1,
  316. _id: 0
  317. }
  318. }
  319. ],
  320. as: "importJob"
  321. }
  322. },
  323. {
  324. $unwind: "$importJob"
  325. },
  326. {
  327. $set: {
  328. importJob: "$importJob.importJob"
  329. }
  330. }
  331. ]
  332. }
  333. },
  334. this
  335. )
  336. .then(response => {
  337. next(null, response);
  338. })
  339. .catch(err => {
  340. next(err);
  341. });
  342. }
  343. ],
  344. async (err, response) => {
  345. if (err && err !== true) {
  346. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  347. this.log("ERROR", "YOUTUBE_GET_VIDEOS", `Failed to get YouTube videos. "${err}"`);
  348. return cb({ status: "error", message: err });
  349. }
  350. this.log("SUCCESS", "YOUTUBE_GET_VIDEOS", `Fetched YouTube videos successfully.`);
  351. return cb({
  352. status: "success",
  353. message: "Successfully fetched YouTube videos.",
  354. data: response
  355. });
  356. }
  357. );
  358. }
  359. ),
  360. /**
  361. * Gets channels, used in the admin youtube page by the AdvancedTable component
  362. * @param {object} session - the session object automatically added by the websocket
  363. * @param page - the page
  364. * @param pageSize - the size per page
  365. * @param properties - the properties to return for each news item
  366. * @param sort - the sort object
  367. * @param queries - the queries array
  368. * @param operator - the operator for queries
  369. * @param {Function} cb - gets called with the result
  370. */
  371. getChannels: useHasPermission(
  372. "admin.view.youtubeChannels",
  373. async function getChannels(session, page, pageSize, properties, sort, queries, operator, cb) {
  374. async.waterfall(
  375. [
  376. next => {
  377. DBModule.runJob(
  378. "GET_DATA",
  379. {
  380. page,
  381. pageSize,
  382. properties,
  383. sort,
  384. queries,
  385. operator,
  386. modelName: "youtubeChannel",
  387. blacklistedProperties: [],
  388. specialProperties: {},
  389. specialQueries: {},
  390. specialFilters: {}
  391. },
  392. this
  393. )
  394. .then(response => {
  395. next(null, response);
  396. })
  397. .catch(err => {
  398. next(err);
  399. });
  400. }
  401. ],
  402. async (err, response) => {
  403. if (err && err !== true) {
  404. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  405. this.log("ERROR", "YOUTUBE_GET_CHANNELS", `Failed to get YouTube channels. "${err}"`);
  406. return cb({ status: "error", message: err });
  407. }
  408. this.log("SUCCESS", "YOUTUBE_GET_CHANNELS", `Fetched YouTube channels successfully.`);
  409. return cb({
  410. status: "success",
  411. message: "Successfully fetched YouTube channels.",
  412. data: response
  413. });
  414. }
  415. );
  416. }
  417. ),
  418. /**
  419. * Get a YouTube video
  420. * @param {object} session - the session object automatically added by the websocket
  421. * @param {string} identifier - the identifier of the video to get
  422. * @param {string} createMissing - whether to create the video if it doesn't exist yet
  423. * @param {Function} cb - gets called with the result
  424. * @returns {{status: string, data: object}}
  425. */
  426. getVideo: isLoginRequired(function getVideo(session, identifier, createMissing, cb) {
  427. return YouTubeModule.runJob("GET_VIDEOS", { identifiers: [identifier], createMissing }, this)
  428. .then(res => {
  429. this.log("SUCCESS", "YOUTUBE_GET_VIDEO", `Fetching video was successful.`);
  430. return cb({ status: "success", message: "Successfully fetched YouTube video", data: res.videos[0] });
  431. })
  432. .catch(async err => {
  433. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  434. this.log("ERROR", "YOUTUBE_GET_VIDEO", `Fetching video failed. "${err}"`);
  435. return cb({ status: "error", message: err });
  436. });
  437. }),
  438. /**
  439. * Get a YouTube channel from ID
  440. * @param {object} session - the session object automatically added by the websocket
  441. * @param {string} channelId - the YouTube channel id to get
  442. * @param {Function} cb - gets called with the result
  443. * @returns {{status: string, data: object}}
  444. */
  445. getChannel: useHasPermission("youtube.getChannel", function getChannel(session, channelId, cb) {
  446. return YouTubeModule.runJob("GET_CHANNELS_FROM_IDS", { channelIds: [channelId] }, this)
  447. .then(res => {
  448. if (res.channels.length === 0) {
  449. this.log("ERROR", "YOUTUBE_GET_CHANNELS_FROM_IDS", `Fetching channel failed.`);
  450. return cb({ status: "error", message: "Failed to get channel" });
  451. }
  452. this.log("SUCCESS", "YOUTUBE_GET_CHANNELS_FROM_IDS", `Fetching channel was successful.`);
  453. return cb({
  454. status: "success",
  455. message: "Successfully fetched YouTube channel",
  456. data: res.channels[0]
  457. });
  458. })
  459. .catch(async err => {
  460. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  461. this.log("ERROR", "YOUTUBE_GET_CHANNELS_FROM_IDS", `Fetching video failed. "${err}"`);
  462. return cb({ status: "error", message: err });
  463. });
  464. }),
  465. /**
  466. * Remove YouTube videos
  467. * @param {object} session - the session object automatically added by the websocket
  468. * @param {Array} videoIds - the YouTube video ids to remove
  469. * @param {Function} cb - gets called with the result
  470. * @returns {{status: string, data: object}}
  471. */
  472. removeVideos: useHasPermission("youtube.removeVideos", async function removeVideos(session, videoIds, cb) {
  473. this.keepLongJob();
  474. this.publishProgress({
  475. status: "started",
  476. title: "Bulk remove YouTube videos",
  477. message: "Bulk removing YouTube videos.",
  478. id: this.toString()
  479. });
  480. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  481. await CacheModule.runJob(
  482. "PUB",
  483. {
  484. channel: "longJob.added",
  485. value: { jobId: this.toString(), userId: session.userId }
  486. },
  487. this
  488. );
  489. YouTubeModule.runJob("REMOVE_VIDEOS", { videoIds }, this)
  490. .then(() => {
  491. this.log("SUCCESS", "YOUTUBE_REMOVE_VIDEOS", `Removing videos was successful.`);
  492. this.publishProgress({
  493. status: "success",
  494. message: "Successfully removed YouTube videos."
  495. });
  496. return cb({ status: "success", message: "Successfully removed YouTube videos" });
  497. })
  498. .catch(async err => {
  499. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  500. this.log("ERROR", "YOUTUBE_REMOVE_VIDEOS", `Removing videos failed. "${err}"`);
  501. this.publishProgress({
  502. status: "error",
  503. message: err
  504. });
  505. return cb({ status: "error", message: err });
  506. });
  507. }),
  508. /**
  509. * Gets missing YouTube video's from all playlists, stations and songs
  510. * @param {object} session - the session object automatically added by the websocket
  511. * @param {Function} cb - gets called with the result
  512. * @returns {{status: string, data: object}}
  513. */
  514. getMissingVideos: useHasPermission("youtube.getMissingVideos", async function getMissingVideos(session, cb) {
  515. this.keepLongJob();
  516. this.publishProgress({
  517. status: "started",
  518. title: "Get missing YouTube videos",
  519. message: "Fetching missing YouTube videos.",
  520. id: this.toString()
  521. });
  522. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  523. await CacheModule.runJob(
  524. "PUB",
  525. {
  526. channel: "longJob.added",
  527. value: { jobId: this.toString(), userId: session.userId }
  528. },
  529. this
  530. );
  531. return YouTubeModule.runJob("GET_MISSING_VIDEOS", {}, this)
  532. .then(response => {
  533. this.log("SUCCESS", "YOUTUBE_GET_MISSING_VIDEOS", `Getting missing videos was successful.`);
  534. this.publishProgress({
  535. status: "success",
  536. message: "Successfully fetched missing YouTube videos."
  537. });
  538. return cb({ status: "success", data: { ...response } });
  539. })
  540. .catch(async err => {
  541. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  542. this.log("ERROR", "YOUTUBE_GET_MISSING_VIDEOS", `Getting missing videos failed. "${err}"`);
  543. this.publishProgress({
  544. status: "error",
  545. message: err
  546. });
  547. return cb({ status: "error", message: err });
  548. });
  549. }),
  550. /**
  551. * Updates YouTube video's from version 1 to version 2, by re-fetching the video's
  552. * @param {object} session - the session object automatically added by the websocket
  553. * @param {Function} cb - gets called with the result
  554. * @returns {{status: string, data: object}}
  555. */
  556. updateVideosV1ToV2: useHasPermission("youtube.updateVideosV1ToV2", async function updateVideosV1ToV2(session, cb) {
  557. this.keepLongJob();
  558. this.publishProgress({
  559. status: "started",
  560. title: "Update YouTube videos to v2",
  561. message: "Updating YouTube videos from v1 to v2.",
  562. id: this.toString()
  563. });
  564. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  565. await CacheModule.runJob(
  566. "PUB",
  567. {
  568. channel: "longJob.added",
  569. value: { jobId: this.toString(), userId: session.userId }
  570. },
  571. this
  572. );
  573. return YouTubeModule.runJob("UPDATE_VIDEOS_V1_TO_V2", {}, this)
  574. .then(response => {
  575. this.log("SUCCESS", "YOUTUBE_UPDATE_VIDEOS_V1_TO_V2", `Updating v1 videos to v2 was successful.`);
  576. this.publishProgress({
  577. status: "success",
  578. message: "Successfully updated YouTube videos from v1 to v2."
  579. });
  580. return cb({ status: "success", data: { ...response } });
  581. })
  582. .catch(async err => {
  583. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  584. this.log("ERROR", "YOUTUBE_UPDATE_VIDEOS_V1_TO_V2", `Updating v1 videos to v2 failed. "${err}"`);
  585. this.publishProgress({
  586. status: "error",
  587. message: err
  588. });
  589. return cb({ status: "error", message: err });
  590. });
  591. }),
  592. /**
  593. * Requests a set of YouTube videos
  594. * @param {object} session - the session object automatically added by the websocket
  595. * @param {string} url - the url of the the YouTube playlist
  596. * @param {boolean} musicOnly - whether to only get music from the playlist
  597. * @param {boolean} musicOnly - whether to return videos
  598. * @param {Function} cb - gets called with the result
  599. */
  600. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnVideos, cb) {
  601. YouTubeModule.runJob("REQUEST_SET", { url, musicOnly, returnVideos }, this)
  602. .then(response => {
  603. this.log(
  604. "SUCCESS",
  605. "REQUEST_SET",
  606. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  607. );
  608. return cb({
  609. status: "success",
  610. message: `Playlist is done importing.`,
  611. videos: returnVideos ? response.videos : null
  612. });
  613. })
  614. .catch(async err => {
  615. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  616. this.log(
  617. "ERROR",
  618. "REQUEST_SET",
  619. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  620. );
  621. return cb({ status: "error", message: err });
  622. });
  623. }),
  624. /**
  625. * Requests a set of YouTube videos as an admin
  626. * @param {object} session - the session object automatically added by the websocket
  627. * @param {string} url - the url of the the YouTube playlist
  628. * @param {boolean} musicOnly - whether to only get music from the playlist
  629. * @param {boolean} musicOnly - whether to return videos
  630. * @param {Function} cb - gets called with the result
  631. */
  632. requestSetAdmin: useHasPermission(
  633. "youtube.requestSetAdmin",
  634. async function requestSetAdmin(session, url, musicOnly, returnVideos, cb) {
  635. const importJobModel = await DBModule.runJob("GET_MODEL", { modelName: "importJob" }, this);
  636. this.keepLongJob();
  637. this.publishProgress({
  638. status: "started",
  639. title: "Import playlist",
  640. message: "Importing playlist.",
  641. id: this.toString()
  642. });
  643. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  644. await CacheModule.runJob(
  645. "PUB",
  646. {
  647. channel: "longJob.added",
  648. value: { jobId: this.toString(), userId: session.userId }
  649. },
  650. this
  651. );
  652. async.waterfall(
  653. [
  654. next => {
  655. importJobModel.create(
  656. {
  657. type: "youtube",
  658. query: {
  659. url,
  660. musicOnly
  661. },
  662. status: "in-progress",
  663. response: {},
  664. requestedBy: session.userId,
  665. requestedAt: Date.now()
  666. },
  667. next
  668. );
  669. },
  670. (importJob, next) => {
  671. YouTubeModule.runJob("REQUEST_SET", { url, musicOnly, returnVideos }, this)
  672. .then(response => {
  673. next(null, importJob, response);
  674. })
  675. .catch(err => {
  676. next(err, importJob);
  677. });
  678. },
  679. (importJob, response, next) => {
  680. importJobModel.updateOne(
  681. { _id: importJob._id },
  682. {
  683. $set: {
  684. status: "success",
  685. response: {
  686. failed: response.failed,
  687. successful: response.successful,
  688. alreadyInDatabase: response.alreadyInDatabase,
  689. successfulVideoIds: response.successfulVideoIds,
  690. failedVideoIds: response.failedVideoIds
  691. }
  692. }
  693. },
  694. err => {
  695. if (err) next(err, importJob);
  696. else
  697. MediaModule.runJob("UPDATE_IMPORT_JOBS", { jobIds: importJob._id })
  698. .then(() => next(null, importJob, response))
  699. .catch(error => next(error, importJob));
  700. }
  701. );
  702. }
  703. ],
  704. async (err, importJob, response) => {
  705. if (err) {
  706. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  707. this.log(
  708. "ERROR",
  709. "REQUEST_SET_ADMIN",
  710. `Importing a YouTube playlist to be requested failed for admin "${session.userId}". "${err}"`
  711. );
  712. importJobModel.updateOne({ _id: importJob._id }, { $set: { status: "error" } });
  713. MediaModule.runJob("UPDATE_IMPORT_JOBS", { jobIds: importJob._id });
  714. return cb({ status: "error", message: err });
  715. }
  716. this.log(
  717. "SUCCESS",
  718. "REQUEST_SET_ADMIN",
  719. `Successfully imported a YouTube playlist to be requested for admin "${session.userId}".`
  720. );
  721. this.publishProgress({
  722. status: "success",
  723. message: `Playlist is done importing.`
  724. });
  725. return cb({
  726. status: "success",
  727. message: `Playlist is done importing.`,
  728. videos: returnVideos ? response.videos : null
  729. });
  730. }
  731. );
  732. }
  733. ),
  734. /**
  735. * Gets missing YouTube channels
  736. * @param {object} session - the session object automatically added by the websocket
  737. * @param {Function} cb - gets called with the result
  738. * @returns {{status: string, data: object}}
  739. */
  740. getMissingChannels: useHasPermission("youtube.getMissingChannels", function getMissingChannels(session, cb) {
  741. return YouTubeModule.runJob("GET_MISSING_CHANNELS", {}, this)
  742. .then(response => {
  743. this.log("SUCCESS", "YOUTUBE_GET_MISSING_CHANNELS", `Getting missing YouTube channels was successful.`);
  744. return cb({ status: "success", data: { ...response } });
  745. })
  746. .catch(async err => {
  747. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  748. this.log("ERROR", "YOUTUBE_GET_MISSING_CHANNELS", `Getting missing YouTube channels failed. "${err}"`);
  749. return cb({ status: "error", message: err });
  750. });
  751. })
  752. };