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