2019-03-21 04:50:44 +09:00
|
|
|
import * as fs from 'fs';
|
2020-04-11 18:28:40 +09:00
|
|
|
import * as stream from 'stream';
|
|
|
|
import * as util from 'util';
|
2020-04-09 23:42:23 +09:00
|
|
|
import fetch from 'node-fetch';
|
|
|
|
import { httpAgent, httpsAgent } from './fetch';
|
2020-04-11 18:28:40 +09:00
|
|
|
import { AbortController } from 'abort-controller';
|
2019-03-21 04:50:44 +09:00
|
|
|
import config from '../config';
|
2019-11-24 17:09:32 +09:00
|
|
|
import * as chalk from 'chalk';
|
2019-03-21 04:50:44 +09:00
|
|
|
import Logger from '../services/logger';
|
|
|
|
|
2020-04-11 18:28:40 +09:00
|
|
|
const pipeline = util.promisify(stream.pipeline);
|
|
|
|
|
2019-03-21 04:50:44 +09:00
|
|
|
export async function downloadUrl(url: string, path: string) {
|
2019-07-01 03:25:31 +09:00
|
|
|
const logger = new Logger('download');
|
2019-03-21 04:50:44 +09:00
|
|
|
|
2020-04-09 23:42:23 +09:00
|
|
|
logger.info(`Downloading ${chalk.cyan(url)} ...`);
|
2020-04-11 18:28:40 +09:00
|
|
|
const controller = new AbortController();
|
|
|
|
setTimeout(() => {
|
|
|
|
controller.abort();
|
|
|
|
}, 11 * 1000);
|
2020-04-09 23:42:23 +09:00
|
|
|
|
|
|
|
const response = await fetch(new URL(url).href, {
|
|
|
|
headers: {
|
|
|
|
'User-Agent': config.userAgent
|
|
|
|
},
|
|
|
|
timeout: 10 * 1000,
|
2020-04-11 18:28:40 +09:00
|
|
|
signal: controller.signal,
|
2020-04-09 23:42:23 +09:00
|
|
|
agent: u => u.protocol == 'http:' ? httpAgent : httpsAgent,
|
|
|
|
});
|
2019-03-21 04:50:44 +09:00
|
|
|
|
2020-04-11 18:28:40 +09:00
|
|
|
if (!response.ok) {
|
|
|
|
logger.error(`Got ${response.status} (${url})`);
|
|
|
|
throw response.status;
|
|
|
|
}
|
2019-03-21 04:50:44 +09:00
|
|
|
|
2020-04-11 18:28:40 +09:00
|
|
|
await pipeline(response.body, fs.createWriteStream(path));
|
2019-03-21 04:50:44 +09:00
|
|
|
|
2020-04-11 18:28:40 +09:00
|
|
|
logger.succ(`Download finished: ${chalk.cyan(url)}`);
|
2019-03-21 04:50:44 +09:00
|
|
|
}
|