优化查看源文件报objact
This commit is contained in:
1 parent
854bc8e4db
commit
07a1494a1e
2 files changed
+69
-22
No files matched your search
+27
-11
@@ -303,12 +303,26 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if resp.status_code == 401:
|
||||
return True
|
||||
if resp.status_code in (403, 404) and 'token=' in file_url:
|
||||
return True
|
||||
if ctype == 'application/json':
|
||||
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
|
||||
if 'unauthorized' in body or '"error"' in body:
|
||||
return True
|
||||
return False
|
||||
if base_url and file_url.startswith(base_url) and ('token=' in file_url):
|
||||
|
||||
def _retry_with_refreshed_url(raw_url: str):
|
||||
refreshed_url = _resolve_latest_integration_url(raw_url)
|
||||
if not refreshed_url or refreshed_url == raw_url:
|
||||
return None, raw_url
|
||||
retry_headers = _build_headers(refreshed_url)
|
||||
try:
|
||||
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return None, refreshed_url
|
||||
|
||||
if 'token=' in file_url:
|
||||
try:
|
||||
parsed = urlparse(file_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
@@ -330,18 +344,20 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream):
|
||||
refreshed_url = _resolve_latest_integration_url(file_url)
|
||||
if refreshed_url != file_url:
|
||||
headers = _build_headers(refreshed_url)
|
||||
try:
|
||||
upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20))
|
||||
file_url = refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if 'token=' in file_url and _should_refresh_from_response(upstream):
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
if upstream.status_code != 200:
|
||||
if 'token=' in file_url:
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
|
||||
if upstream.status_code == 404:
|
||||
return None, None, ('source file not found', 404)
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
content = upstream.content or b''
|
||||
|
||||
@@ -129,6 +129,42 @@ const clearOfficeObjectUrl = () => {
|
||||
officeKind.value = null;
|
||||
};
|
||||
|
||||
const extractErrorMessage = (payload: any, fallback: string) => {
|
||||
if (!payload) return fallback;
|
||||
if (typeof payload === 'string' && payload.trim()) return payload.trim();
|
||||
if (typeof payload?.message === 'string' && payload.message.trim()) return payload.message.trim();
|
||||
if (typeof payload?.error === 'string' && payload.error.trim()) return payload.error.trim();
|
||||
if (typeof payload?.error?.message === 'string' && payload.error.message.trim()) return payload.error.message.trim();
|
||||
if (typeof payload?.detail === 'string' && payload.detail.trim()) return payload.detail.trim();
|
||||
return fallback;
|
||||
};
|
||||
|
||||
const readErrorMessage = async (res: Response) => {
|
||||
const fallback = `HTTP ${res.status}`;
|
||||
const contentType = (res.headers.get('content-type') || '').toLowerCase();
|
||||
if (contentType.includes('application/json')) {
|
||||
const payload = await res.json().catch(() => null);
|
||||
return extractErrorMessage(payload, fallback);
|
||||
}
|
||||
const text = await res.text().catch(() => '');
|
||||
return extractErrorMessage(text, fallback);
|
||||
};
|
||||
|
||||
const extractDownloadFilename = (res: Response) => {
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
|
||||
if (utf8Match?.[1]) {
|
||||
try {
|
||||
return decodeURIComponent(utf8Match[1]);
|
||||
} catch {
|
||||
return utf8Match[1];
|
||||
}
|
||||
}
|
||||
const asciiMatch = disposition.match(/filename="([^"]+)"/i);
|
||||
if (asciiMatch?.[1]) return asciiMatch[1];
|
||||
return '';
|
||||
};
|
||||
|
||||
const applyExcelPreview = (buffer: ArrayBuffer) => {
|
||||
const workbook = XLSX.read(buffer, { type: 'array' });
|
||||
if (!workbook.SheetNames.length) {
|
||||
@@ -182,8 +218,7 @@ const loadSheetPreview = async () => {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data?.error || `HTTP ${res.status}`);
|
||||
throw new Error(await readErrorMessage(res));
|
||||
}
|
||||
|
||||
excelPreview.value = await res.json();
|
||||
@@ -202,8 +237,7 @@ const loadOfficeContent = async () => {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
throw new Error(await readErrorMessage(res));
|
||||
}
|
||||
|
||||
const buffer = await res.arrayBuffer();
|
||||
@@ -238,8 +272,7 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
throw new Error(await readErrorMessage(res));
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
@@ -290,8 +323,7 @@ const loadBinaryContent = async () => {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
throw new Error(await readErrorMessage(res));
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
@@ -314,15 +346,14 @@ const downloadFile = async () => {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
throw new Error(await readErrorMessage(res));
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
const downloadUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl;
|
||||
link.download = props.file.name || 'download';
|
||||
link.download = extractDownloadFilename(res) || props.file.name || 'download';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
|
||||
Reference in new issue
Block a user