youhua
This commit is contained in:
1 parent
08a19ebe96
commit
dea3b39048
6 files changed
+240
-33
No files matched your search
+61
-8
@@ -62,7 +62,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _fetch_preview_source_bytes(file_url: str):
|
||||
def _fetch_preview_source_bytes(file_url: str, max_size: int = 15 * 1024 * 1024):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
@@ -178,7 +178,6 @@ def _fetch_preview_source_bytes(file_url: str):
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
content = upstream.content or b''
|
||||
max_size = 15 * 1024 * 1024
|
||||
if len(content) > max_size:
|
||||
return None, None, ('file too large for online preview', 413)
|
||||
|
||||
@@ -281,6 +280,58 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
raise Exception("PDF output not found after conversion")
|
||||
|
||||
|
||||
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。
|
||||
"""
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
if normalized_ext != 'xls':
|
||||
return content
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
input_path = os.path.join(temp_dir, "input.xls")
|
||||
output_path = os.path.join(temp_dir, "input.xlsx")
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
|
||||
commands = [
|
||||
'soffice',
|
||||
'libreoffice',
|
||||
r'C:\Program Files\LibreOffice\program\soffice.exe',
|
||||
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
|
||||
]
|
||||
|
||||
errors = []
|
||||
for cmd in commands:
|
||||
try:
|
||||
process = subprocess.run(
|
||||
[cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=60
|
||||
)
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
|
||||
errors.append(f"{cmd}: {e}")
|
||||
continue
|
||||
|
||||
if process.returncode == 0 and os.path.exists(output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
|
||||
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
|
||||
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
|
||||
|
||||
|
||||
def _load_excel_workbook(content: bytes, ext: str):
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
if normalized_ext == 'xls':
|
||||
content = _convert_excel_to_xlsx(content, normalized_ext)
|
||||
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
@@ -579,8 +630,8 @@ def preview_excel():
|
||||
"""
|
||||
内网 Excel 预览接口(简版可上线)。
|
||||
说明:
|
||||
- 当前仅支持 xlsx;
|
||||
- xls 返回 415,由前端走下载兜底。
|
||||
- xlsx 直接解析;
|
||||
- xls 先转为 xlsx 后再解析。
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
@@ -603,13 +654,13 @@ def preview_excel():
|
||||
limit = 100
|
||||
limit = max(1, min(limit, 300))
|
||||
|
||||
content, _, err = _fetch_preview_source_bytes(file_url)
|
||||
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
|
||||
try:
|
||||
wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
wb = _load_excel_workbook(content, ext)
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
|
||||
return jsonify({'error': 'failed to parse excel file'}), 422
|
||||
@@ -674,7 +725,8 @@ def preview_text():
|
||||
if ext and ext not in allowed:
|
||||
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
||||
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url)
|
||||
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
@@ -717,7 +769,8 @@ def preview_file_raw():
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
ext = url_path_ext or name_ext
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url)
|
||||
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
|
||||
Reference in new issue
Block a user