ファイルのダウンロードがタイムアウトしなくなっているのを修正など (#6233)

* Refactor download / file-info

* body read timeout on download Fix syuilo#6232
This commit is contained in:
MeiMei 2020-04-11 18:28:40 +09:00 committed by GitHub
parent 9fcf94b197
commit ca66acac2b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 52 deletions

View file

@ -1,55 +1,39 @@
import * as fs from 'fs';
import * as stream from 'stream';
import * as util from 'util';
import fetch from 'node-fetch';
import { httpAgent, httpsAgent } from './fetch';
import { AbortController } from 'abort-controller';
import config from '../config';
import * as chalk from 'chalk';
import Logger from '../services/logger';
const pipeline = util.promisify(stream.pipeline);
export async function downloadUrl(url: string, path: string) {
const logger = new Logger('download');
logger.info(`Downloading ${chalk.cyan(url)} ...`);
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, 11 * 1000);
const response = await fetch(new URL(url).href, {
headers: {
'User-Agent': config.userAgent
},
timeout: 10 * 1000,
signal: controller.signal,
agent: u => u.protocol == 'http:' ? httpAgent : httpsAgent,
}).then(response => {
if (!response.ok) {
logger.error(`Got ${response.status} (${url})`);
throw response.status;
} else {
return response;
}
});
await new Promise((res, rej) => {
const writable = fs.createWriteStream(path);
if (!response.ok) {
logger.error(`Got ${response.status} (${url})`);
throw response.status;
}
response.body.on('error', (error: any) => {
logger.error(`Failed to start download: ${chalk.cyan(url)}: ${error}`, {
url: url,
e: error
});
writable.close();
rej(error);
});
await pipeline(response.body, fs.createWriteStream(path));
writable.on('finish', () => {
logger.succ(`Download finished: ${chalk.cyan(url)}`);
res();
});
writable.on('error', error => {
logger.error(`Download failed: ${chalk.cyan(url)}: ${error}`, {
url: url,
e: error
});
rej(error);
});
response.body.pipe(writable);
});
logger.succ(`Download finished: ${chalk.cyan(url)}`);
}