]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/requests.ts
remove isAdministration
[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, CONFIG } from '../initializers'
5 import { processImage } from './image-utils'
6 import { join } from 'path'
7
8 function doRequest <T> (
9 requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean }
10 ): Bluebird<{ response: request.RequestResponse, body: T }> {
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, destDir: string, destName: string, size: { width: number, height: number }) {
33 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
34 await doRequestAndSaveToFile({ method: 'GET', uri: url }, tmpPath)
35
36 const destPath = join(destDir, destName)
37 await processImage({ path: tmpPath }, destPath, size)
38 }
39
40 // ---------------------------------------------------------------------------
41
42 export {
43 doRequest,
44 doRequestAndSaveToFile,
45 downloadImage
46 }