2019-03-20 13:50:44 -06:00
|
|
|
import * as fs from 'fs';
|
2020-04-09 08:42:23 -06:00
|
|
|
import fetch from 'node-fetch';
|
|
|
|
import { httpAgent, httpsAgent } from './fetch';
|
2019-03-20 13:50:44 -06:00
|
|
|
import config from '../config';
|
2019-11-24 01:09:32 -07:00
|
|
|
import * as chalk from 'chalk';
|
2019-03-20 13:50:44 -06:00
|
|
|
import Logger from '../services/logger';
|
|
|
|
|
|
|
|
export async function downloadUrl(url: string, path: string) {
|
2019-06-30 12:25:31 -06:00
|
|
|
const logger = new Logger('download');
|
2019-03-20 13:50:44 -06:00
|
|
|
|
2020-04-09 08:42:23 -06:00
|
|
|
logger.info(`Downloading ${chalk.cyan(url)} ...`);
|
|
|
|
|
|
|
|
const response = await fetch(new URL(url).href, {
|
|
|
|
headers: {
|
|
|
|
'User-Agent': config.userAgent
|
|
|
|
},
|
|
|
|
timeout: 10 * 1000,
|
|
|
|
agent: u => u.protocol == 'http:' ? httpAgent : httpsAgent,
|
|
|
|
}).then(response => {
|
|
|
|
if (!response.ok) {
|
|
|
|
logger.error(`Got ${response.status} (${url})`);
|
|
|
|
throw response.status;
|
|
|
|
} else {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
});
|
2019-03-20 13:50:44 -06:00
|
|
|
|
2020-04-09 08:42:23 -06:00
|
|
|
await new Promise((res, rej) => {
|
2019-03-20 13:50:44 -06:00
|
|
|
const writable = fs.createWriteStream(path);
|
|
|
|
|
2020-04-09 08:42:23 -06:00
|
|
|
response.body.on('error', (error: any) => {
|
|
|
|
logger.error(`Failed to start download: ${chalk.cyan(url)}: ${error}`, {
|
2019-03-20 13:50:44 -06:00
|
|
|
url: url,
|
|
|
|
e: error
|
|
|
|
});
|
2020-04-09 08:42:23 -06:00
|
|
|
writable.close();
|
2019-03-20 13:50:44 -06:00
|
|
|
rej(error);
|
|
|
|
});
|
|
|
|
|
2020-04-09 08:42:23 -06:00
|
|
|
writable.on('finish', () => {
|
|
|
|
logger.succ(`Download finished: ${chalk.cyan(url)}`);
|
|
|
|
res();
|
2019-03-20 13:50:44 -06:00
|
|
|
});
|
|
|
|
|
2020-04-09 08:42:23 -06:00
|
|
|
writable.on('error', error => {
|
|
|
|
logger.error(`Download failed: ${chalk.cyan(url)}: ${error}`, {
|
2019-03-20 13:50:44 -06:00
|
|
|
url: url,
|
|
|
|
e: error
|
|
|
|
});
|
|
|
|
rej(error);
|
|
|
|
});
|
|
|
|
|
2020-04-09 08:42:23 -06:00
|
|
|
response.body.pipe(writable);
|
2019-03-20 13:50:44 -06:00
|
|
|
});
|
|
|
|
}
|