]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/requests.ts
Fix thumbnail processing
[github/Chocobozzz/PeerTube.git] / server / helpers / requests.ts
1 import * as Bluebird from 'bluebird'
2 import { createWriteStream } from 'fs-extra'
3 import * as request from 'request'
4 import { ACTIVITY_PUB } from '../initializers'
5 import { processImage } from './image-utils'
6 import { extname } from 'path'
7
8 function doRequest <T> (
9 requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean }
10 ): Bluebird<{ response: request.RequestResponse, body: any }> {
11 if (requestOptions.activityPub === true) {
12 if (!Array.isArray(requestOptions.headers)) requestOptions.headers = {}
13 requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
14 }
15
16 return new Bluebird<{ response: request.RequestResponse, body: T }>((res, rej) => {
17 request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
18 })
19 }
20
21 function doRequestAndSaveToFile (requestOptions: request.CoreOptions & request.UriOptions, destPath: string) {
22 return new Bluebird<void>((res, rej) => {
23 const file = createWriteStream(destPath)
24 file.on('finish', () => res())
25
26 request(requestOptions)
27 .on('error', err => rej(err))
28 .pipe(file)
29 })
30 }
31
32 async function downloadImage (url: string, destPath: string, size: { width: number, height: number }) {
33 const tmpPath = destPath + '.tmp' + extname(destPath)
34 await doRequestAndSaveToFile({ method: 'GET', uri: url }, tmpPath)
35
36 await processImage({ path: tmpPath }, destPath, size)
37 }
38
39 // ---------------------------------------------------------------------------
40
41 export {
42 doRequest,
43 doRequestAndSaveToFile,
44 downloadImage
45 }