2019-03-21 04:50:44 +09:00
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as request from 'request';
|
|
|
|
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
|
|
|
|
|
|
|
await new Promise((res, rej) => {
|
|
|
|
logger.info(`Downloading ${chalk.cyan(url)} ...`);
|
|
|
|
|
|
|
|
const writable = fs.createWriteStream(path);
|
|
|
|
|
|
|
|
writable.on('finish', () => {
|
|
|
|
logger.succ(`Download finished: ${chalk.cyan(url)}`);
|
|
|
|
res();
|
|
|
|
});
|
|
|
|
|
|
|
|
writable.on('error', error => {
|
|
|
|
logger.error(`Download failed: ${chalk.cyan(url)}: ${error}`, {
|
|
|
|
url: url,
|
|
|
|
e: error
|
|
|
|
});
|
|
|
|
rej(error);
|
|
|
|
});
|
|
|
|
|
|
|
|
const req = request({
|
2019-06-18 15:19:19 +09:00
|
|
|
url: new URL(url).href, // https://github.com/syuilo/misskey/issues/2637
|
2019-03-21 04:50:44 +09:00
|
|
|
proxy: config.proxy,
|
|
|
|
timeout: 10 * 1000,
|
2019-07-28 09:49:02 +09:00
|
|
|
forever: true,
|
2019-03-21 04:50:44 +09:00
|
|
|
headers: {
|
|
|
|
'User-Agent': config.userAgent
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
req.pipe(writable);
|
|
|
|
|
|
|
|
req.on('response', response => {
|
|
|
|
if (response.statusCode !== 200) {
|
|
|
|
logger.error(`Got ${response.statusCode} (${url})`);
|
|
|
|
writable.close();
|
|
|
|
rej(response.statusCode);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
req.on('error', error => {
|
|
|
|
logger.error(`Failed to start download: ${chalk.cyan(url)}: ${error}`, {
|
|
|
|
url: url,
|
|
|
|
e: error
|
|
|
|
});
|
|
|
|
writable.close();
|
|
|
|
rej(error);
|
|
|
|
});
|
|
|
|
|
|
|
|
logger.succ(`Downloaded to: ${path}`);
|
|
|
|
});
|
|
|
|
}
|