requests.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import * as Bluebird from 'bluebird'
  2. import { createWriteStream, remove } from 'fs-extra'
  3. import * as request from 'request'
  4. import { ACTIVITY_PUB, PEERTUBE_VERSION, WEBSERVER } from '../initializers/constants'
  5. import { processImage } from './image-utils'
  6. import { join } from 'path'
  7. import { logger } from './logger'
  8. import { CONFIG } from '../initializers/config'
  9. function doRequest <T> (
  10. requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean },
  11. bodyKBLimit = 1000 // 1MB
  12. ): Bluebird<{ response: request.RequestResponse, body: T }> {
  13. if (!(requestOptions.headers)) requestOptions.headers = {}
  14. requestOptions.headers['User-Agent'] = getUserAgent()
  15. if (requestOptions.activityPub === true) {
  16. requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
  17. }
  18. return new Bluebird<{ response: request.RequestResponse, body: T }>((res, rej) => {
  19. request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
  20. .on('data', onRequestDataLengthCheck(bodyKBLimit))
  21. })
  22. }
  23. function doRequestAndSaveToFile (
  24. requestOptions: request.CoreOptions & request.UriOptions,
  25. destPath: string,
  26. bodyKBLimit = 10000 // 10MB
  27. ) {
  28. if (!requestOptions.headers) requestOptions.headers = {}
  29. requestOptions.headers['User-Agent'] = getUserAgent()
  30. return new Bluebird<void>((res, rej) => {
  31. const file = createWriteStream(destPath)
  32. file.on('finish', () => res())
  33. request(requestOptions)
  34. .on('data', onRequestDataLengthCheck(bodyKBLimit))
  35. .on('error', err => {
  36. file.close()
  37. remove(destPath)
  38. .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err }))
  39. return rej(err)
  40. })
  41. .pipe(file)
  42. })
  43. }
  44. async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
  45. const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
  46. await doRequestAndSaveToFile({ method: 'GET', uri: url }, tmpPath)
  47. const destPath = join(destDir, destName)
  48. try {
  49. await processImage(tmpPath, destPath, size)
  50. } catch (err) {
  51. await remove(tmpPath)
  52. throw err
  53. }
  54. }
  55. function getUserAgent () {
  56. return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
  57. }
  58. // ---------------------------------------------------------------------------
  59. export {
  60. doRequest,
  61. doRequestAndSaveToFile,
  62. downloadImage
  63. }
  64. // ---------------------------------------------------------------------------
  65. // Thanks to https://github.com/request/request/issues/2470#issuecomment-268929907 <3
  66. function onRequestDataLengthCheck (bodyKBLimit: number) {
  67. let bufferLength = 0
  68. const bytesLimit = bodyKBLimit * 1000
  69. return function (chunk) {
  70. bufferLength += chunk.length
  71. if (bufferLength > bytesLimit) {
  72. this.abort()
  73. const error = new Error(`Response was too large - aborted after ${bytesLimit} bytes.`)
  74. this.emit('error', error)
  75. }
  76. }
  77. }