Allow strict file checking

If the file is unexpected, an unstrict file checking will only warn the user that the file is unexpected, and it should pass it off anyway.
This commit is contained in:
buzzcode2007 2024-04-03 10:13:52 +08:00
parent 1ea9683d35
commit 1ce691bec6

View file

@ -6,40 +6,46 @@
Download a file from the network or locally. Download a file from the network or locally.
@param {string} URL the URL to download @param {string} URL the URL to download
@param {string} type the expected type of file @param {string} TYPE the expected TYPE of file
@param {boolean} verify_only whether to verify the file only, not return its content @param {boolean} VERIFY_ONLY whether to verify the file only, not return its content
@param {boolean} STRICT strictly follow the file type provided
@returns {Promise} the downloaded file @returns {Promise} the downloaded file
*/ */
export async function download(URL, type, verify_only = false) { export async function download(URL, TYPE, VERIFY_ONLY = false, STRICT = false) {
const alert = await import(chrome.runtime.getURL(`gui/scripts/alerts.js`))
.default;
const texts = (await import(chrome.runtime.getURL(`gui/scripts/read.js`))) const texts = (await import(chrome.runtime.getURL(`gui/scripts/read.js`)))
.default; .default;
const alerts = (await import(chrome.runtime.getURL(`gui/scripts/alerts.js`))).default;
let connect = await fetch(URL), let CONNECT, DATA;
data;
if (connect.ok && !verify_only) {
try { try {
data = await connect.text(); CONNECT = await fetch(URL);
if (CONNECT.ok && !VERIFY_ONLY) {
DATA = await CONNECT.text();
if ( if (
type TYPE
? type.toLowerCase().includes(`json`) || type.toLowerCase().includes(`dictionary`) ? TYPE.toLowerCase().includes(`json`) || TYPE.toLowerCase().includes(`dictionary`)
: false : false
) { ) {
try { try {
data = JSON.parse(data); DATA = JSON.parse(DATA);
// When not in JSON, run this. // When not in JSON, run this.
} catch(err) { } catch(err) {
if (STRICT) {
// Should not allow the data to be returned since it's not correct.
DATA = null;
throw new TypeError(texts.localized(`error_msg_notJSON`, false)); throw new TypeError(texts.localized(`error_msg_notJSON`, false));
} else {alerts.warn(texts.localized(`error_msg_notJSON`, false));}
}; };
}; };
} catch(err) {
alert.error(err.name, err.message, err.stack);
} }
} catch(err) {
alerts.error(err.name, err.message, err.stack);
let DATA = null;
} }
// Return the filter. // Return the filter.
return verify_only ? connect.ok : data; return VERIFY_ONLY ? CONNECT.ok : DATA;
} }