youtube.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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("admin.view.youtube", 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. "admin.view.youtube",
  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. "admin.view.youtube",
  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 {Function} cb - gets called with the result
  235. */
  236. getVideos: useHasPermission(
  237. "admin.view.youtubeVideos",
  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. songId: [
  255. // Fetch songs from songs collection with a matching mediaSource, which we first need to assemble
  256. {
  257. $lookup: {
  258. from: "songs",
  259. let: {
  260. mediaSource: { $concat: ["youtube:", "$youtubeId"] }
  261. },
  262. pipeline: [
  263. {
  264. $match: {
  265. $expr: { $eq: ["$mediaSource", "$$mediaSource"] }
  266. }
  267. }
  268. ],
  269. as: "song"
  270. }
  271. },
  272. // Turn the array of songs returned in the last step into one object, since only one song should have been returned maximum
  273. {
  274. $unwind: {
  275. path: "$song",
  276. preserveNullAndEmptyArrays: true
  277. }
  278. },
  279. // Add new field songId, which grabs the song object's _id and tries turning it into a string
  280. {
  281. $addFields: {
  282. songId: {
  283. $convert: {
  284. input: "$song._id",
  285. to: "string",
  286. onError: "",
  287. onNull: ""
  288. }
  289. }
  290. }
  291. },
  292. // Cleanup, don't return the song object for any further steps
  293. {
  294. $project: {
  295. song: 0
  296. }
  297. }
  298. ]
  299. },
  300. specialQueries: {},
  301. specialFilters: {
  302. importJob: importJobId => [
  303. {
  304. $lookup: {
  305. from: "importjobs",
  306. let: { youtubeId: "$youtubeId" },
  307. pipeline: [
  308. {
  309. $match: {
  310. _id: mongoose.Types.ObjectId(importJobId)
  311. }
  312. },
  313. {
  314. $addFields: {
  315. importJob: {
  316. $in: ["$$youtubeId", "$response.successfulVideoIds"]
  317. }
  318. }
  319. },
  320. {
  321. $project: {
  322. importJob: 1,
  323. _id: 0
  324. }
  325. }
  326. ],
  327. as: "importJob"
  328. }
  329. },
  330. {
  331. $unwind: "$importJob"
  332. },
  333. {
  334. $set: {
  335. importJob: "$importJob.importJob"
  336. }
  337. }
  338. ]
  339. }
  340. },
  341. this
  342. )
  343. .then(response => {
  344. next(null, response);
  345. })
  346. .catch(err => {
  347. next(err);
  348. });
  349. }
  350. ],
  351. async (err, response) => {
  352. if (err && err !== true) {
  353. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  354. this.log("ERROR", "YOUTUBE_GET_VIDEOS", `Failed to get YouTube videos. "${err}"`);
  355. return cb({ status: "error", message: err });
  356. }
  357. this.log("SUCCESS", "YOUTUBE_GET_VIDEOS", `Fetched YouTube videos successfully.`);
  358. return cb({
  359. status: "success",
  360. message: "Successfully fetched YouTube videos.",
  361. data: response
  362. });
  363. }
  364. );
  365. }
  366. ),
  367. /**
  368. * Gets channels, used in the admin youtube page by the AdvancedTable component
  369. *
  370. * @param {object} session - the session object automatically added by the websocket
  371. * @param page - the page
  372. * @param pageSize - the size per page
  373. * @param properties - the properties to return for each news item
  374. * @param sort - the sort object
  375. * @param queries - the queries array
  376. * @param operator - the operator for queries
  377. * @param {Function} cb - gets called with the result
  378. */
  379. getChannels: useHasPermission(
  380. "admin.view.youtubeChannels",
  381. async function getChannels(session, page, pageSize, properties, sort, queries, operator, cb) {
  382. async.waterfall(
  383. [
  384. next => {
  385. DBModule.runJob(
  386. "GET_DATA",
  387. {
  388. page,
  389. pageSize,
  390. properties,
  391. sort,
  392. queries,
  393. operator,
  394. modelName: "youtubeChannel",
  395. blacklistedProperties: [],
  396. specialProperties: {},
  397. specialQueries: {},
  398. specialFilters: {}
  399. },
  400. this
  401. )
  402. .then(response => {
  403. next(null, response);
  404. })
  405. .catch(err => {
  406. next(err);
  407. });
  408. }
  409. ],
  410. async (err, response) => {
  411. if (err && err !== true) {
  412. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  413. this.log("ERROR", "YOUTUBE_GET_CHANNELS", `Failed to get YouTube channels. "${err}"`);
  414. return cb({ status: "error", message: err });
  415. }
  416. this.log("SUCCESS", "YOUTUBE_GET_CHANNELS", `Fetched YouTube channels successfully.`);
  417. return cb({
  418. status: "success",
  419. message: "Successfully fetched YouTube channels.",
  420. data: response
  421. });
  422. }
  423. );
  424. }
  425. ),
  426. /**
  427. * Get a YouTube video
  428. *
  429. * @param {object} session - the session object automatically added by the websocket
  430. * @param {string} identifier - the identifier of the video to get
  431. * @param {string} createMissing - whether to create the video if it doesn't exist yet
  432. * @param {Function} cb - gets called with the result
  433. * @returns {{status: string, data: object}}
  434. */
  435. getVideo: isLoginRequired(function getVideo(session, identifier, createMissing, cb) {
  436. return YouTubeModule.runJob("GET_VIDEOS", { identifiers: [identifier], createMissing }, this)
  437. .then(res => {
  438. this.log("SUCCESS", "YOUTUBE_GET_VIDEO", `Fetching video was successful.`);
  439. return cb({ status: "success", message: "Successfully fetched YouTube video", data: res.videos[0] });
  440. })
  441. .catch(async err => {
  442. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  443. this.log("ERROR", "YOUTUBE_GET_VIDEO", `Fetching video failed. "${err}"`);
  444. return cb({ status: "error", message: err });
  445. });
  446. }),
  447. /**
  448. * Get a YouTube channel from ID
  449. *
  450. * @param {object} session - the session object automatically added by the websocket
  451. * @param {string} channelId - the YouTube channel id to get
  452. * @param {Function} cb - gets called with the result
  453. * @returns {{status: string, data: object}}
  454. */
  455. getChannel: useHasPermission("youtube.getChannel", function getChannel(session, channelId, cb) {
  456. return YouTubeModule.runJob("GET_CHANNELS_FROM_IDS", { channelIds: [channelId] }, this)
  457. .then(res => {
  458. if (res.channels.length === 0) {
  459. this.log("ERROR", "YOUTUBE_GET_CHANNELS_FROM_IDS", `Fetching channel failed.`);
  460. return cb({ status: "error", message: "Failed to get channel" });
  461. }
  462. this.log("SUCCESS", "YOUTUBE_GET_CHANNELS_FROM_IDS", `Fetching channel was successful.`);
  463. return cb({
  464. status: "success",
  465. message: "Successfully fetched YouTube channel",
  466. data: res.channels[0]
  467. });
  468. })
  469. .catch(async err => {
  470. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  471. this.log("ERROR", "YOUTUBE_GET_CHANNELS_FROM_IDS", `Fetching video failed. "${err}"`);
  472. return cb({ status: "error", message: err });
  473. });
  474. }),
  475. /**
  476. * Remove YouTube videos
  477. *
  478. * @param {object} session - the session object automatically added by the websocket
  479. * @param {Array} videoIds - the YouTube video ids to remove
  480. * @param {Function} cb - gets called with the result
  481. * @returns {{status: string, data: object}}
  482. */
  483. removeVideos: useHasPermission("youtube.removeVideos", async function removeVideos(session, videoIds, cb) {
  484. this.keepLongJob();
  485. this.publishProgress({
  486. status: "started",
  487. title: "Bulk remove YouTube videos",
  488. message: "Bulk removing YouTube videos.",
  489. id: this.toString()
  490. });
  491. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  492. await CacheModule.runJob(
  493. "PUB",
  494. {
  495. channel: "longJob.added",
  496. value: { jobId: this.toString(), userId: session.userId }
  497. },
  498. this
  499. );
  500. YouTubeModule.runJob("REMOVE_VIDEOS", { videoIds }, this)
  501. .then(() => {
  502. this.log("SUCCESS", "YOUTUBE_REMOVE_VIDEOS", `Removing videos was successful.`);
  503. this.publishProgress({
  504. status: "success",
  505. message: "Successfully removed YouTube videos."
  506. });
  507. return cb({ status: "success", message: "Successfully removed YouTube videos" });
  508. })
  509. .catch(async err => {
  510. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  511. this.log("ERROR", "YOUTUBE_REMOVE_VIDEOS", `Removing videos failed. "${err}"`);
  512. this.publishProgress({
  513. status: "error",
  514. message: err
  515. });
  516. return cb({ status: "error", message: err });
  517. });
  518. }),
  519. /**
  520. * Gets missing YouTube video's from all playlists, stations and songs
  521. *
  522. * @param {object} session - the session object automatically added by the websocket
  523. * @param {Function} cb - gets called with the result
  524. * @returns {{status: string, data: object}}
  525. */
  526. getMissingVideos: useHasPermission("youtube.getMissingVideos", async function getMissingVideos(session, cb) {
  527. this.keepLongJob();
  528. this.publishProgress({
  529. status: "started",
  530. title: "Get missing YouTube videos",
  531. message: "Fetching missing YouTube videos.",
  532. id: this.toString()
  533. });
  534. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  535. await CacheModule.runJob(
  536. "PUB",
  537. {
  538. channel: "longJob.added",
  539. value: { jobId: this.toString(), userId: session.userId }
  540. },
  541. this
  542. );
  543. return YouTubeModule.runJob("GET_MISSING_VIDEOS", {}, this)
  544. .then(response => {
  545. this.log("SUCCESS", "YOUTUBE_GET_MISSING_VIDEOS", `Getting missing videos was successful.`);
  546. this.publishProgress({
  547. status: "success",
  548. message: "Successfully fetched missing YouTube videos."
  549. });
  550. return cb({ status: "success", data: { ...response } });
  551. })
  552. .catch(async err => {
  553. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  554. this.log("ERROR", "YOUTUBE_GET_MISSING_VIDEOS", `Getting missing videos failed. "${err}"`);
  555. this.publishProgress({
  556. status: "error",
  557. message: err
  558. });
  559. return cb({ status: "error", message: err });
  560. });
  561. }),
  562. /**
  563. * Updates YouTube video's from version 1 to version 2, by re-fetching the video's
  564. *
  565. * @param {object} session - the session object automatically added by the websocket
  566. * @param {Function} cb - gets called with the result
  567. * @returns {{status: string, data: object}}
  568. */
  569. updateVideosV1ToV2: useHasPermission("youtube.updateVideosV1ToV2", async function updateVideosV1ToV2(session, cb) {
  570. this.keepLongJob();
  571. this.publishProgress({
  572. status: "started",
  573. title: "Update YouTube videos to v2",
  574. message: "Updating YouTube videos from v1 to v2.",
  575. id: this.toString()
  576. });
  577. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  578. await CacheModule.runJob(
  579. "PUB",
  580. {
  581. channel: "longJob.added",
  582. value: { jobId: this.toString(), userId: session.userId }
  583. },
  584. this
  585. );
  586. return YouTubeModule.runJob("UPDATE_VIDEOS_V1_TO_V2", {}, this)
  587. .then(response => {
  588. this.log("SUCCESS", "YOUTUBE_UPDATE_VIDEOS_V1_TO_V2", `Updating v1 videos to v2 was successful.`);
  589. this.publishProgress({
  590. status: "success",
  591. message: "Successfully updated YouTube videos from v1 to v2."
  592. });
  593. return cb({ status: "success", data: { ...response } });
  594. })
  595. .catch(async err => {
  596. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  597. this.log("ERROR", "YOUTUBE_UPDATE_VIDEOS_V1_TO_V2", `Updating v1 videos to v2 failed. "${err}"`);
  598. this.publishProgress({
  599. status: "error",
  600. message: err
  601. });
  602. return cb({ status: "error", message: err });
  603. });
  604. }),
  605. /**
  606. * Requests a set of YouTube videos
  607. *
  608. * @param {object} session - the session object automatically added by the websocket
  609. * @param {string} url - the url of the the YouTube playlist
  610. * @param {boolean} musicOnly - whether to only get music from the playlist
  611. * @param {boolean} musicOnly - whether to return videos
  612. * @param {Function} cb - gets called with the result
  613. */
  614. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnVideos, cb) {
  615. YouTubeModule.runJob("REQUEST_SET", { url, musicOnly, returnVideos }, this)
  616. .then(response => {
  617. this.log(
  618. "SUCCESS",
  619. "REQUEST_SET",
  620. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  621. );
  622. return cb({
  623. status: "success",
  624. message: `Playlist is done importing.`,
  625. videos: returnVideos ? response.videos : null
  626. });
  627. })
  628. .catch(async err => {
  629. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  630. this.log(
  631. "ERROR",
  632. "REQUEST_SET",
  633. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  634. );
  635. return cb({ status: "error", message: err });
  636. });
  637. }),
  638. /**
  639. * Requests a set of YouTube videos as an admin
  640. *
  641. * @param {object} session - the session object automatically added by the websocket
  642. * @param {string} url - the url of the the YouTube playlist
  643. * @param {boolean} musicOnly - whether to only get music from the playlist
  644. * @param {boolean} musicOnly - whether to return videos
  645. * @param {Function} cb - gets called with the result
  646. */
  647. requestSetAdmin: useHasPermission(
  648. "youtube.requestSetAdmin",
  649. async function requestSetAdmin(session, url, musicOnly, returnVideos, cb) {
  650. const importJobModel = await DBModule.runJob("GET_MODEL", { modelName: "importJob" }, this);
  651. this.keepLongJob();
  652. this.publishProgress({
  653. status: "started",
  654. title: "Import playlist",
  655. message: "Importing playlist.",
  656. id: this.toString()
  657. });
  658. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  659. await CacheModule.runJob(
  660. "PUB",
  661. {
  662. channel: "longJob.added",
  663. value: { jobId: this.toString(), userId: session.userId }
  664. },
  665. this
  666. );
  667. async.waterfall(
  668. [
  669. next => {
  670. importJobModel.create(
  671. {
  672. type: "youtube",
  673. query: {
  674. url,
  675. musicOnly
  676. },
  677. status: "in-progress",
  678. response: {},
  679. requestedBy: session.userId,
  680. requestedAt: Date.now()
  681. },
  682. next
  683. );
  684. },
  685. (importJob, next) => {
  686. YouTubeModule.runJob("REQUEST_SET", { url, musicOnly, returnVideos }, this)
  687. .then(response => {
  688. next(null, importJob, response);
  689. })
  690. .catch(err => {
  691. next(err, importJob);
  692. });
  693. },
  694. (importJob, response, next) => {
  695. importJobModel.updateOne(
  696. { _id: importJob._id },
  697. {
  698. $set: {
  699. status: "success",
  700. response: {
  701. failed: response.failed,
  702. successful: response.successful,
  703. alreadyInDatabase: response.alreadyInDatabase,
  704. successfulVideoIds: response.successfulVideoIds,
  705. failedVideoIds: response.failedVideoIds
  706. }
  707. }
  708. },
  709. err => {
  710. if (err) next(err, importJob);
  711. else
  712. MediaModule.runJob("UPDATE_IMPORT_JOBS", { jobIds: importJob._id })
  713. .then(() => next(null, importJob, response))
  714. .catch(error => next(error, importJob));
  715. }
  716. );
  717. }
  718. ],
  719. async (err, importJob, response) => {
  720. if (err) {
  721. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  722. this.log(
  723. "ERROR",
  724. "REQUEST_SET_ADMIN",
  725. `Importing a YouTube playlist to be requested failed for admin "${session.userId}". "${err}"`
  726. );
  727. importJobModel.updateOne({ _id: importJob._id }, { $set: { status: "error" } });
  728. MediaModule.runJob("UPDATE_IMPORT_JOBS", { jobIds: importJob._id });
  729. return cb({ status: "error", message: err });
  730. }
  731. this.log(
  732. "SUCCESS",
  733. "REQUEST_SET_ADMIN",
  734. `Successfully imported a YouTube playlist to be requested for admin "${session.userId}".`
  735. );
  736. this.publishProgress({
  737. status: "success",
  738. message: `Playlist is done importing.`
  739. });
  740. return cb({
  741. status: "success",
  742. message: `Playlist is done importing.`,
  743. videos: returnVideos ? response.videos : null
  744. });
  745. }
  746. );
  747. }
  748. ),
  749. /**
  750. * Gets missing YouTube channels
  751. *
  752. * @param {object} session - the session object automatically added by the websocket
  753. * @param {Function} cb - gets called with the result
  754. * @returns {{status: string, data: object}}
  755. */
  756. getMissingChannels: useHasPermission("youtube.getMissingChannels", function getMissingChannels(session, cb) {
  757. return YouTubeModule.runJob("GET_MISSING_CHANNELS", {}, this)
  758. .then(response => {
  759. this.log("SUCCESS", "YOUTUBE_GET_MISSING_CHANNELS", `Getting missing YouTube channels was successful.`);
  760. return cb({ status: "success", data: { ...response } });
  761. })
  762. .catch(async err => {
  763. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  764. this.log("ERROR", "YOUTUBE_GET_MISSING_CHANNELS", `Getting missing YouTube channels failed. "${err}"`);
  765. return cb({ status: "error", message: err });
  766. });
  767. })
  768. };