1
0
Fork 0
peertube/server/helpers/requests.ts

46 lines
1.5 KiB
TypeScript
Raw Normal View History

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