soundcloud.js 20 KB

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