44 lines
1.7 KiB
TypeScript
44 lines
1.7 KiB
TypeScript
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. */
|
|
export default async function downloadWrapper({ host, path, size, useCurl = false }: {host: string, path: string, size: number, useCurl: boolean}): Promise<string> {
|
|
//Generate file name we want to save it under
|
|
//e.g. on Linux: /tmp/patcher/cdn-patch.swtor.com/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);
|
|
await createDirRecursively(folderName);
|
|
|
|
//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) {
|
|
//Try up to three times
|
|
for (let i = 0; i < 3; i += 1) {
|
|
try {
|
|
const downloadResult = await downloadWithCurl({ host, path, tempFileName });
|
|
return downloadResult;
|
|
} catch (err) {
|
|
console.error(err);
|
|
//ignore error and try again
|
|
}
|
|
}
|
|
//Download failed, throw error
|
|
throw new Error('Could not download with curl');
|
|
} else {
|
|
const downloadResult = await new Promise((resolve, reject) => {
|
|
downloadUrlContents(host, path, tempFileName, resolve, reject);
|
|
}) as string;
|
|
return downloadResult;
|
|
}
|
|
}
|