1 import * as Bluebird from 'bluebird'
2 import { createWriteStream, remove } from 'fs-extra'
3 import * as request from 'request'
4 import { ACTIVITY_PUB } 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'
10 function doRequest <T> (
11 requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean },
12 bodyKBLimit = 1000 // 1MB
13 ): Bluebird<{ response: request.RequestResponse, body: T }> {
14 if (requestOptions.activityPub === true) {
15 if (!Array.isArray(requestOptions.headers)) requestOptions.headers = {}
16 requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
19 return new Bluebird<{ response: request.RequestResponse, body: T }>((res, rej) => {
20 request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
21 .on('data', onRequestDataLengthCheck(bodyKBLimit))
25 function doRequestAndSaveToFile (
26 requestOptions: request.CoreOptions & request.UriOptions,
28 bodyKBLimit = 10000 // 10MB
30 return new Bluebird<void>((res, rej) => {
31 const file = createWriteStream(destPath)
32 file.on('finish', () => res())
34 request(requestOptions)
35 .on('data', onRequestDataLengthCheck(bodyKBLimit))
40 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err }))
48 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
49 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
50 await doRequestAndSaveToFile({ method: 'GET', uri: url }, tmpPath)
52 const destPath = join(destDir, destName)
55 await processImage({ path: tmpPath }, destPath, size)
63 // ---------------------------------------------------------------------------
67 doRequestAndSaveToFile,
71 // ---------------------------------------------------------------------------
73 // Thanks to https://github.com/request/request/issues/2470#issuecomment-268929907 <3
74 function onRequestDataLengthCheck (bodyKBLimit: number) {
76 const bytesLimit = bodyKBLimit * 1000
78 return function (chunk) {
79 bufferLength += chunk.length
80 if (bufferLength > bytesLimit) {
83 const error = new Error(`Response was too large - aborted after ${bytesLimit} bytes.`)
84 this.emit('error', error)