2019-03-20 20:50:44 +01:00
|
|
|
import * as fs from 'fs';
|
2020-04-11 11:28:40 +02:00
|
|
|
import * as stream from 'stream';
|
|
|
|
import * as util from 'util';
|
2021-03-24 03:05:37 +01:00
|
|
|
import { URL } from 'url';
|
2020-04-09 16:42:23 +02:00
|
|
|
import fetch from 'node-fetch';
|
2021-08-19 14:55:45 +02:00
|
|
|
import { getAgentByUrl } from './fetch';
|
2020-04-11 11:28:40 +02:00
|
|
|
import { AbortController } from 'abort-controller';
|
2021-08-19 14:55:45 +02:00
|
|
|
import config from '@/config/index';
|
2019-11-24 09:09:32 +01:00
|
|
|
import * as chalk from 'chalk';
|
2021-08-19 14:55:45 +02:00
|
|
|
import Logger from '@/services/logger';
|
2019-03-20 20:50:44 +01:00
|
|
|
|
2020-04-11 11:28:40 +02:00
|
|
|
const pipeline = util.promisify(stream.pipeline);
|
|
|
|
|
2019-03-20 20:50:44 +01:00
|
|
|
export async function downloadUrl(url: string, path: string) {
|
2019-06-30 20:25:31 +02:00
|
|
|
const logger = new Logger('download');
|
2019-03-20 20:50:44 +01:00
|
|
|
|
2020-04-09 16:42:23 +02:00
|
|
|
logger.info(`Downloading ${chalk.cyan(url)} ...`);
|
2020-04-11 11:28:40 +02:00
|
|
|
const controller = new AbortController();
|
|
|
|
setTimeout(() => {
|
|
|
|
controller.abort();
|
2020-07-06 16:55:59 +02:00
|
|
|
}, 60 * 1000);
|
2020-04-09 16:42:23 +02:00
|
|
|
|
|
|
|
const response = await fetch(new URL(url).href, {
|
|
|
|
headers: {
|
|
|
|
'User-Agent': config.userAgent
|
|
|
|
},
|
|
|
|
timeout: 10 * 1000,
|
2020-04-11 11:28:40 +02:00
|
|
|
signal: controller.signal,
|
2020-04-12 13:32:34 +02:00
|
|
|
agent: getAgentByUrl,
|
2020-04-09 16:42:23 +02:00
|
|
|
});
|
2019-03-20 20:50:44 +01:00
|
|
|
|
2020-04-11 11:28:40 +02:00
|
|
|
if (!response.ok) {
|
|
|
|
logger.error(`Got ${response.status} (${url})`);
|
|
|
|
throw response.status;
|
|
|
|
}
|
2019-03-20 20:50:44 +01:00
|
|
|
|
2020-04-11 11:28:40 +02:00
|
|
|
await pipeline(response.body, fs.createWriteStream(path));
|
2019-03-20 20:50:44 +01:00
|
|
|
|
2020-04-11 11:28:40 +02:00
|
|
|
logger.succ(`Download finished: ${chalk.cyan(url)}`);
|
2019-03-20 20:50:44 +01:00
|
|
|
}
|