2019-03-20 20:50:44 +01:00
|
|
|
import * as fs from 'fs';
|
2020-04-09 16:42:23 +02:00
|
|
|
import fetch from 'node-fetch';
|
|
|
|
import { httpAgent, httpsAgent } from './fetch';
|
2019-03-20 20:50:44 +01:00
|
|
|
import config from '../config';
|
2019-11-24 09:09:32 +01:00
|
|
|
import * as chalk from 'chalk';
|
2019-03-20 20:50:44 +01:00
|
|
|
import Logger from '../services/logger';
|
|
|
|
|
|
|
|
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)} ...`);
|
|
|
|
|
|
|
|
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 20:50:44 +01:00
|
|
|
|
2020-04-09 16:42:23 +02:00
|
|
|
await new Promise((res, rej) => {
|
2019-03-20 20:50:44 +01:00
|
|
|
const writable = fs.createWriteStream(path);
|
|
|
|
|
2020-04-09 16:42:23 +02:00
|
|
|
response.body.on('error', (error: any) => {
|
|
|
|
logger.error(`Failed to start download: ${chalk.cyan(url)}: ${error}`, {
|
2019-03-20 20:50:44 +01:00
|
|
|
url: url,
|
|
|
|
e: error
|
|
|
|
});
|
2020-04-09 16:42:23 +02:00
|
|
|
writable.close();
|
2019-03-20 20:50:44 +01:00
|
|
|
rej(error);
|
|
|
|
});
|
|
|
|
|
2020-04-09 16:42:23 +02:00
|
|
|
writable.on('finish', () => {
|
|
|
|
logger.succ(`Download finished: ${chalk.cyan(url)}`);
|
|
|
|
res();
|
2019-03-20 20:50:44 +01:00
|
|
|
});
|
|
|
|
|
2020-04-09 16:42:23 +02:00
|
|
|
writable.on('error', error => {
|
|
|
|
logger.error(`Download failed: ${chalk.cyan(url)}: ${error}`, {
|
2019-03-20 20:50:44 +01:00
|
|
|
url: url,
|
|
|
|
e: error
|
|
|
|
});
|
|
|
|
rej(error);
|
|
|
|
});
|
|
|
|
|
2020-04-09 16:42:23 +02:00
|
|
|
response.body.pipe(writable);
|
2019-03-20 20:50:44 +01:00
|
|
|
});
|
|
|
|
}
|