2018-01-15 11:10:46 +01:00
|
|
|
import * as Bluebird from 'bluebird'
|
2018-08-27 13:28:49 +02:00
|
|
|
import { createWriteStream } from 'fs-extra'
|
2017-11-10 17:27:49 +01:00
|
|
|
import * as request from 'request'
|
2018-12-04 16:02:49 +01:00
|
|
|
import { ACTIVITY_PUB, CONFIG } from '../initializers'
|
2018-11-16 16:48:17 +01:00
|
|
|
import { processImage } from './image-utils'
|
2018-12-04 16:02:49 +01:00
|
|
|
import { join } from 'path'
|
2017-12-28 11:16:08 +01:00
|
|
|
|
2018-11-14 15:01:28 +01:00
|
|
|
function doRequest <T> (
|
2018-01-15 09:46:46 +01:00
|
|
|
requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean }
|
2019-02-07 15:08:19 +01:00
|
|
|
): Bluebird<{ response: request.RequestResponse, body: T }> {
|
2017-12-28 11:16:08 +01:00
|
|
|
if (requestOptions.activityPub === true) {
|
|
|
|
if (!Array.isArray(requestOptions.headers)) requestOptions.headers = {}
|
|
|
|
requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
|
|
|
|
}
|
2017-11-09 17:51:58 +01:00
|
|
|
|
2018-11-14 15:01:28 +01:00
|
|
|
return new Bluebird<{ response: request.RequestResponse, body: T }>((res, rej) => {
|
2017-11-09 17:51:58 +01:00
|
|
|
request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
|
|
|
|
})
|
|
|
|
}
|
2016-02-05 18:03:20 +01:00
|
|
|
|
2017-11-10 14:34:45 +01:00
|
|
|
function doRequestAndSaveToFile (requestOptions: request.CoreOptions & request.UriOptions, destPath: string) {
|
2018-02-15 18:40:24 +01:00
|
|
|
return new Bluebird<void>((res, rej) => {
|
|
|
|
const file = createWriteStream(destPath)
|
|
|
|
file.on('finish', () => res())
|
|
|
|
|
2017-11-10 14:34:45 +01:00
|
|
|
request(requestOptions)
|
|
|
|
.on('error', err => rej(err))
|
2018-02-15 18:40:24 +01:00
|
|
|
.pipe(file)
|
2017-11-10 14:34:45 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-12-04 16:02:49 +01:00
|
|
|
async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
|
|
|
|
const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
|
2018-11-16 16:48:17 +01:00
|
|
|
await doRequestAndSaveToFile({ method: 'GET', uri: url }, tmpPath)
|
|
|
|
|
2018-12-04 16:02:49 +01:00
|
|
|
const destPath = join(destDir, destName)
|
2018-11-16 16:48:17 +01:00
|
|
|
await processImage({ path: tmpPath }, destPath, size)
|
|
|
|
}
|
|
|
|
|
2016-02-07 11:23:23 +01:00
|
|
|
// ---------------------------------------------------------------------------
|
2016-02-05 18:03:20 +01:00
|
|
|
|
2017-05-15 22:22:03 +02:00
|
|
|
export {
|
2017-11-09 17:51:58 +01:00
|
|
|
doRequest,
|
2018-11-16 16:48:17 +01:00
|
|
|
doRequestAndSaveToFile,
|
|
|
|
downloadImage
|
2017-05-15 22:22:03 +02:00
|
|
|
}
|