chat中源文件没用的问题
This commit is contained in:
1 parent
3d4b2647ae
commit
b745a9c803
6 files changed
+490
-99
No files matched your search
+65
-2
@@ -7,6 +7,7 @@ backend/app/api/chat.py
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -25,6 +26,25 @@ from app import db
|
||||
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
|
||||
if normalized.startswith("\\\\"):
|
||||
return "\\\\" + normalized[2:].rstrip("\\")
|
||||
return normalized.rstrip("\\")
|
||||
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
|
||||
return bool(
|
||||
normalized_root
|
||||
and normalized_target.startswith("\\\\")
|
||||
and normalized_target.lower().startswith(normalized_root.lower())
|
||||
)
|
||||
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -35,6 +55,8 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
3) 私网 IP 或常见内网域名(.local/.lan)。
|
||||
"""
|
||||
try:
|
||||
if _is_allowed_share_path(target_url):
|
||||
return True
|
||||
parsed = urlparse(target_url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
return False
|
||||
@@ -75,6 +97,25 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return None, None, ('source file not found', 404)
|
||||
file_size = os.path.getsize(normalized_path)
|
||||
if max_size is not None and file_size > max_size:
|
||||
return None, None, ('file too large for online preview', 413)
|
||||
with open(normalized_path, 'rb') as fh:
|
||||
content = fh.read()
|
||||
except OSError as exc:
|
||||
current_app.logger.warning("[file-preview] failed to read share path %s: %s", normalized_path, exc)
|
||||
return None, None, ('failed to read source file', 502)
|
||||
|
||||
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
|
||||
if _extract_placeholder_text(content):
|
||||
guessed_type = 'text/plain; charset=utf-8'
|
||||
return content, guessed_type, None
|
||||
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
@@ -188,6 +229,24 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
return None, None, ('upstream returned invalid preview payload', 502)
|
||||
return content, content_type, None
|
||||
|
||||
|
||||
def _extract_placeholder_text(content: bytes) -> str:
|
||||
sample = content[:2048]
|
||||
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
text = sample.decode(enc).replace('\x00', '').strip()
|
||||
except Exception:
|
||||
continue
|
||||
if not text:
|
||||
continue
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
continue
|
||||
first_line = lines[0][:160]
|
||||
if any(token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密')):
|
||||
return first_line
|
||||
return ''
|
||||
|
||||
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 将 office 文件转为 PDF
|
||||
@@ -909,9 +968,13 @@ def preview_file_raw():
|
||||
'htm': 'text/html',
|
||||
}
|
||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
||||
placeholder_text = _extract_placeholder_text(content)
|
||||
if placeholder_text:
|
||||
content = placeholder_text.encode('utf-8')
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
|
||||
|
||||
mime = fallback_types.get(ext) or content_type or 'application/octet-stream'
|
||||
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
|
||||
|
||||
from urllib.parse import quote
|
||||
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
|
||||
|
||||
Reference in new issue
Block a user