41 lines
1.5 KiB
TypeScript
41 lines
1.5 KiB
TypeScript
import * as http from 'http';
|
|
import * as os from 'os';
|
|
import * as nodePath from 'path';
|
|
import checkLocalCache from './funcs/checkLocalCache';
|
|
import createDirRecursively from './funcs/createDirRecursively';
|
|
import saveResponse from './funcs/saveResponse';
|
|
|
|
/** Downloads the given URL and saves it to disk. Throws error if download fails. */
|
|
export default function downloadUrlContents({ host, path, size }: {host: string, path: string, size: number}): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
//Generate file name we want to save it under
|
|
//e.g. on Linux: /tmp/patcher/patch/assets_swtor_main/assets_swtor_main_-1to0/assets_swtor_main_-1to0.zip
|
|
const tempFileName = nodePath.join(os.tmpdir(), 'patcher', host, path);
|
|
|
|
//Create parent directory recursively
|
|
const folderName = nodePath.dirname(tempFileName);
|
|
createDirRecursively(folderName).then(() => {
|
|
//Check if file already exists locally
|
|
checkLocalCache(tempFileName, size).then((cacheStatus) => {
|
|
if (cacheStatus) {
|
|
return resolve(tempFileName);
|
|
}
|
|
|
|
//Create HTTP request
|
|
const request = http.request({
|
|
family: 4,
|
|
hostname: host,
|
|
path,
|
|
}, saveResponse.bind(null, tempFileName, resolve, (reason: string) => { request.abort(); reject(reason); }));
|
|
|
|
//In case of connection errors, exit early
|
|
request.on('error', (error) => {
|
|
request.abort();
|
|
reject(error);
|
|
});
|
|
|
|
request.end();
|
|
});
|
|
});
|
|
});
|
|
}
|