文件预览优化

This commit is contained in:
runny committed 2026-05-30 14:10:44 +08:00
1 parent f91d44ca24
commit 7f66d6f20c
5 files changed
+504 -165

No files matched your search

+182 -27
View File
@@ -71,6 +71,13 @@ def _is_allowed_preview_url(target_url: str) -> bool:
integration_host = (urlparse(integration_base).hostname or "").strip().lower()
if integration_host and host == integration_host:
return True
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
from flask import request, has_request_context
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
return True
if host in ("localhost", "127.0.0.1", "::1"):
return True
@@ -80,7 +87,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return ip.is_private or ip.is_loopback
except ValueError:
# 非 IP 主机:仅放行内网风格本地域名。
return host.endswith(".local") or host.endswith(".lan")
return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com")
except Exception:
return False
@@ -165,8 +172,33 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
def _build_headers(raw_url: str):
next_headers = {}
if base_url and raw_url.startswith(base_url) and api_key:
if not api_key:
current_app.logger.info(f"[_build_headers] api_key is missing")
return next_headers
is_trusted = False
if base_url and raw_url.startswith(base_url):
is_trusted = True
elif _is_allowed_preview_url(raw_url):
is_trusted = True
else:
try:
parsed = urlparse(raw_url)
host = (parsed.hostname or "").strip().lower()
from flask import request, has_request_context
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
is_trusted = True
if host in ("localhost", "127.0.0.1", "::1"):
is_trusted = True
except Exception:
pass
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
if is_trusted:
next_headers['X-Integration-Key'] = api_key
return next_headers
def _should_refresh_from_response(resp) -> bool:
@@ -217,6 +249,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
return None, None, ('failed to fetch source file', 502)
if upstream.status_code != 200:
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b''
@@ -250,9 +283,11 @@ def _extract_placeholder_text(content: bytes) -> str:
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 将 office 文件转为 PDF
使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
"""
with tempfile.TemporaryDirectory() as temp_dir:
import shutil
temp_dir = tempfile.mkdtemp()
try:
input_path = os.path.join(temp_dir, f"input.{ext}")
with open(input_path, 'wb') as f:
f.write(content)
@@ -283,6 +318,9 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
# 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office
if not success and os.name == 'nt':
app = None
doc_obj = None
pythoncom = None
try:
import win32com.client
import pythoncom
@@ -291,14 +329,42 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
if ext in ('doc', 'docx'):
try:
app = win32com.client.Dispatch("KWPS.Application") # 尝试 WPS Word
from pathlib import Path
from edkb_system.skills.word_bridge import convert_with_word
convert_with_word(Path(input_path), Path(output_path), 17)
success = True
except Exception as word_bridge_exc:
current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc)
if not success and ext in ('doc', 'docx'):
try:
# 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS
app = win32com.client.Dispatch("Word.Application")
except Exception:
app = win32com.client.Dispatch("Word.Application") # 回退 MS Word
app = win32com.client.Dispatch("KWPS.Application")
app.Visible = False
doc = app.Documents.Open(os.path.abspath(input_path))
doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF
doc.Close()
app.Quit()
app.DisplayAlerts = False
input_abs = os.path.abspath(input_path)
output_abs = os.path.abspath(output_path)
try:
doc_obj = app.Documents.Open(
FileName=input_abs,
ConfirmConversions=False,
ReadOnly=True,
AddToRecentFiles=False,
Visible=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
except TypeError:
doc_obj = app.Documents.Open(input_abs, ReadOnly=True)
try:
# 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17)
doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF
except Exception:
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
success = True
elif ext in ('ppt', 'pptx'):
@@ -307,10 +373,12 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
except Exception:
app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT
app.Visible = False
presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False)
presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
presentation.Close()
app.Quit()
try:
app.DisplayAlerts = False
except Exception:
pass
doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False)
doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
success = True
elif ext in ('xls', 'xlsx'):
@@ -319,15 +387,30 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
except Exception:
app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel
app.Visible = False
wb = app.Workbooks.Open(os.path.abspath(input_path))
wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
wb.Close(False)
app.Quit()
app.DisplayAlerts = False
doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True)
doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
success = True
except ImportError:
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.")
except Exception as e:
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
finally:
if doc_obj is not None:
try:
doc_obj.Close(False)
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
if pythoncom is not None:
try:
pythoncom.CoUninitialize()
except Exception:
pass
if not success:
raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office")
@@ -338,6 +421,8 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
return f.read()
else:
raise Exception("PDF output not found after conversion")
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
@@ -911,8 +996,6 @@ def preview_excel():
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext
if ext and ext not in ('xlsx', 'xls'):
return jsonify({'error': f'unsupported file extension: {ext}'}), 415
try:
limit = int(request.args.get('limit', 100))
@@ -925,10 +1008,13 @@ def preview_excel():
msg, code = err
return jsonify({'error': msg}), code
detected_ext = _detect_excel_format(content or b'', ext)
if detected_ext not in ('xlsx', 'xls'):
return jsonify({'error': f'unsupported file extension: {ext or detected_ext or "unknown"}'}), 415
try:
wb = _load_excel_workbook(content, ext)
wb = _load_excel_workbook(content, detected_ext)
except Exception as e:
detected_ext = _detect_excel_format(content or b'', ext)
current_app.logger.warning(
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
ext,
@@ -1032,13 +1118,55 @@ def preview_text():
})
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
"""
根据文件内容(Magic Bytes)纠正可能的错误扩展名
"""
import io
import zipfile
if not content:
return default_ext
if content.startswith(b'%PDF-'):
return 'pdf'
if content.startswith(b'PK\x03\x04'):
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
try:
with zipfile.ZipFile(io.BytesIO(content)) as zf:
names = {name.lower() for name in zf.namelist()}
if any(name.startswith('word/') for name in names):
return 'docx'
if any(name.startswith('xl/') for name in names):
return 'xlsx'
if any(name.startswith('ppt/') for name in names):
return 'pptx'
except Exception:
pass
if default_ext == 'doc':
return 'docx'
if default_ext == 'xls':
return 'xlsx'
if default_ext == 'ppt':
return 'pptx'
if default_ext in ('docx', 'xlsx', 'pptx'):
return default_ext
return 'docx'
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
# OLE 复合文件,通常是 doc, xls, ppt 等。
if default_ext == 'docx': return 'doc'
if default_ext == 'xlsx': return 'xls'
if default_ext == 'pptx': return 'ppt'
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
return 'doc'
return default_ext
@chat_bp.route('/preview-file-raw', methods=['GET'])
@require_agent_permission
def preview_file_raw():
"""
二进制文件内网代理预览接口。
用途:
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
- 尽量使用 inline 响应头,避免强制下载。
"""
file_url = (request.args.get('url') or '').strip()
@@ -1051,7 +1179,8 @@ def preview_file_raw():
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext
original_ext = url_path_ext or name_ext
ext = original_ext
is_download = request.args.get('download') == '1'
max_size = None if is_download else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
@@ -1059,15 +1188,39 @@ def preview_file_raw():
msg, code = err
return jsonify({'error': msg}), code
# 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染
if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1':
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
real_ext = _guess_ext_from_content(content, ext)
if real_ext != ext:
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
ext = real_ext
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.{ext}"
elif name:
name = f"{name}.{ext}"
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
# 避免在服务端走旧版转换链路导致长时间卡住。
needs_pdf_conversion = (
request.args.get('download') != '1'
and original_ext in ('doc', 'ppt', 'pptx')
and ext in ('doc', 'ppt', 'pptx')
)
if needs_pdf_conversion:
try:
content = _convert_office_to_pdf(content, ext)
ext = 'pdf'
content_type = 'application/pdf'
except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
# 转换失败则回退到原始格式
placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
content = placeholder_text.encode('utf-8')
ext = 'txt'
content_type = 'text/plain; charset=utf-8'
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
else:
return jsonify({'error': 'failed to convert office file for preview'}), 422
fallback_types = {
'pdf': 'application/pdf',
@@ -1101,4 +1254,6 @@ def preview_file_raw():
resp = Response(content, status=200, mimetype=mime)
resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
resp.headers['Cache-Control'] = 'no-store'
resp.headers['X-Preview-Actual-Ext'] = ext or ''
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
return resp
+17 -3
View File
@@ -19,11 +19,25 @@ integration_bp = Blueprint('integration', __name__)
def _require_integration_key():
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
if not configured:
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
if configured != incoming:
return jsonify({'error': 'Unauthorized'}), 401
return None
if configured == incoming:
return None
token = request.args.get('token')
if token:
try:
import jwt
secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
jwt.decode(token, secret, algorithms=['HS256'])
return None
except Exception as e:
current_app.logger.warning(f"Integration API token validation failed: {e}")
pass
return jsonify({'error': 'Unauthorized'}), 401
def _integration_base_url() -> str: