2018-09-30 14:35:25 +02:00
|
|
|
import * as os from 'os';
|
|
|
|
import * as nodePath from 'path';
|
|
|
|
import downloadUrlContents from './downloadUrlContents';
|
|
|
|
import downloadWithCurl from './downloadWithCurl';
|
|
|
|
import checkLocalCache from './funcs/checkLocalCache';
|
|
|
|
import createDirRecursively from './funcs/createDirRecursively';
|
|
|
|
|
|
|
|
/** Downloads the given URL and saves it to disk. Returns the location where file is saved under. Throws error if download fails. */
|
2018-10-05 15:00:01 +02:00
|
|
|
export default async function downloadWrapper({ host, path, size, useCurl = false }: {host: string, path: string, size: number, useCurl: boolean}): Promise<string> {
|
2018-10-05 14:56:43 +02:00
|
|
|
//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);
|
2018-09-30 14:35:25 +02:00
|
|
|
|
2018-10-05 14:56:43 +02:00
|
|
|
//Create parent directory recursively
|
|
|
|
const folderName = nodePath.dirname(tempFileName);
|
|
|
|
await createDirRecursively(folderName);
|
2018-09-30 14:35:25 +02:00
|
|
|
|
2018-10-05 14:56:43 +02:00
|
|
|
//Check if file already exists locally
|
|
|
|
const cacheStatus = await checkLocalCache(tempFileName, size);
|
|
|
|
if (cacheStatus) {
|
|
|
|
return tempFileName;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Download either via curl or natively with Node
|
|
|
|
if (useCurl) {
|
2018-10-05 15:00:01 +02:00
|
|
|
const downloadResult = await new Promise((resolve, reject) => {
|
2018-10-05 14:56:43 +02:00
|
|
|
downloadWithCurl({ host, path, tempFileName, size, resolve, reject });
|
2018-10-05 15:00:01 +02:00
|
|
|
}) as string;
|
|
|
|
return downloadResult;
|
2018-10-05 14:56:43 +02:00
|
|
|
} else {
|
2018-10-05 15:00:01 +02:00
|
|
|
const downloadResult = await new Promise((resolve, reject) => {
|
2018-10-05 14:56:43 +02:00
|
|
|
downloadUrlContents(host, path, tempFileName, resolve, reject);
|
2018-10-05 15:00:01 +02:00
|
|
|
}) as string;
|
|
|
|
return downloadResult;
|
2018-10-05 14:56:43 +02:00
|
|
|
}
|
2018-09-30 14:35:25 +02:00
|
|
|
}
|