From b745a9c80304ba6471266041836909782a090cc2 Mon Sep 17 00:00:00 2001
From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com>
Date: Tue, 19 May 2026 04:23:38 +0800
Subject: [PATCH] =?UTF-8?q?chat=E4=B8=AD=E6=BA=90=E6=96=87=E4=BB=B6?=
=?UTF-8?q?=E6=B2=A1=E7=94=A8=E7=9A=84=E9=97=AE=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
backend/app/api/chat.py | 67 +++++-
backend/app/services/integration_api.py | 116 +++++++----
backend/app/services/plm_oracle.py | 131 ++++++++++--
frontend/src/components/FilePreviewModal.vue | 59 ++++--
frontend/src/composables/useChat.ts | 12 +-
frontend/src/views/ChatView.vue | 204 ++++++++++++++++---
6 files changed, 490 insertions(+), 99 deletions(-)
diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py
index 7ba509f4..ba67c101 100644
--- a/backend/app/api/chat.py
+++ b/backend/app/api/chat.py
@@ -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"}'
diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py
index c6f3f54f..4a629c72 100644
--- a/backend/app/services/integration_api.py
+++ b/backend/app/services/integration_api.py
@@ -14,6 +14,32 @@ from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
+ @staticmethod
+ def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
+ if not isinstance(row, dict):
+ return None
+ req = row.get("request") if isinstance(row.get("request"), dict) else {}
+ dataset_id = str(req.get("dataset_id") or "").strip()
+ remote_document_id = str(req.get("remote_document_id") or "").strip()
+ if not dataset_id or not remote_document_id or not row.get("found"):
+ return None
+
+ doc = row.get("document") if isinstance(row.get("document"), dict) else {}
+ source_url = doc.get("source_download_url")
+ if not source_url:
+ return None
+
+ normalized = {
+ "source_download_url": source_url,
+ "source_filename": doc.get("source_filename"),
+ "source_ext": doc.get("source_ext"),
+ "download_url_expires_at": doc.get("download_url_expires_at"),
+ "version_id": doc.get("version_id"),
+ "document_id": doc.get("document_id"),
+ }
+ key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
+ return key, normalized
+
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
@@ -37,14 +63,13 @@ class IntegrationApiService:
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
public_base = ""
+ # For server-side lookups, always prefer the explicitly configured
+ # integration service endpoint when present. Falling back to the current
+ # request host would incorrectly call this backend itself.
+ if configured:
+ return configured
+
if mode != "external":
- # For server-side lookups inside containers/workers, an explicit integration
- # endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
- if configured and (
- not has_request_context()
- or IntegrationApiService._is_loopback_url(public_base)
- ):
- return configured
if public_base:
return public_base
if has_request_context():
@@ -113,16 +138,55 @@ class IntegrationApiService:
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
- if resp.status_code != 200:
- return None
- payload = resp.json()
- if not isinstance(payload, dict):
- return None
- IntegrationApiService._cache[cache_key] = payload
- return payload
+ if resp.status_code == 200:
+ payload = resp.json()
+ if isinstance(payload, dict):
+ IntegrationApiService._cache[cache_key] = payload
+ return payload
+ elif has_app_context():
+ current_app.logger.info(
+ "Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
+ dataset_id,
+ remote_document_id,
+ resp.status_code,
+ )
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
+
+ batch_url = f"{base_url}/api/integration/dify-files/resolve"
+ batch_headers = {
+ "X-Integration-Key": api_key,
+ "Content-Type": "application/json",
+ }
+ batch_body = {
+ "items": [
+ {
+ "dataset_id": str(dataset_id),
+ "remote_document_id": str(remote_document_id),
+ }
+ ]
+ }
+ try:
+ resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
+ if resp.status_code != 200:
+ return None
+ payload = resp.json()
+ data = payload.get("data") if isinstance(payload, dict) else None
+ if not isinstance(data, list):
+ return None
+ for row in data:
+ normalized_row = IntegrationApiService._normalize_batch_row(row)
+ if not normalized_row:
+ continue
+ key, normalized = normalized_row
+ IntegrationApiService._cache[key] = normalized
+ if key == cache_key:
+ return normalized
+ return None
+ except Exception as e:
+ if has_app_context():
+ current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
return None
@staticmethod
@@ -199,28 +263,10 @@ class IntegrationApiService:
for row in data:
if not isinstance(row, dict):
continue
- req = row.get("request") if isinstance(row.get("request"), dict) else {}
- dataset_id = str(req.get("dataset_id") or "").strip()
- remote_document_id = str(req.get("remote_document_id") or "").strip()
- if not dataset_id or not remote_document_id:
+ normalized_row = IntegrationApiService._normalize_batch_row(row)
+ if not normalized_row:
continue
- if not row.get("found"):
- continue
-
- doc = row.get("document") if isinstance(row.get("document"), dict) else {}
- source_url = doc.get("source_download_url")
- if not source_url:
- continue
-
- normalized = {
- "source_download_url": source_url,
- "source_filename": doc.get("source_filename"),
- "source_ext": doc.get("source_ext"),
- "download_url_expires_at": doc.get("download_url_expires_at"),
- "version_id": doc.get("version_id"),
- "document_id": doc.get("document_id"),
- }
- key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
+ key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
diff --git a/backend/app/services/plm_oracle.py b/backend/app/services/plm_oracle.py
index 0ebfbf3a..15e67d37 100644
--- a/backend/app/services/plm_oracle.py
+++ b/backend/app/services/plm_oracle.py
@@ -3,6 +3,8 @@ import os
import re
import time
from datetime import datetime
+from html import escape
+from urllib.parse import quote
from flask import current_app
@@ -13,6 +15,8 @@ from app.services.text2sql import Text2SQLService
class PLMOracleService:
_ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"}
_MAX_RESULT_ROWS = 50
+ _PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
+ _SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
_EXPLICIT_LABEL_PATTERN = re.compile(
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
@@ -184,6 +188,114 @@ select *
return f"{size / 1024:.1f} KB"
return f"{size / 1024 / 1024:.2f} MB"
+ @classmethod
+ def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
+ parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
+ for value in (storage_id, file_path, file_id):
+ text = str(value or "").strip()
+ if not text:
+ continue
+ parts.append(text.replace("/", "\\").strip("\\"))
+ return "\\".join(part for part in parts if part)
+
+ @classmethod
+ def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
+ def raw(column_name: str):
+ idx = index_map.get(column_name.upper())
+ if idx is None or idx >= len(row):
+ return None
+ value = row[idx]
+ return None if value in (None, "") else value
+
+ file_name = str(raw("NAME") or "").strip()
+ if not file_name:
+ return "-"
+
+ storage_id = raw("STORAGEID")
+ file_path = raw("FILEPATH")
+ file_id = str(raw("ID") or "").strip()
+ if not storage_id or file_path is None or not file_id:
+ return escape(file_name)
+
+ share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
+ preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
+ return f'{escape(file_name)}'
+
+ @staticmethod
+ def _escape_markdown_cell(value: str) -> str:
+ return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "
")
+
+ @staticmethod
+ def _escape_html_text(value) -> str:
+ return escape(str(value), quote=True).replace("\r", " ").replace("\n", "
")
+
+ @classmethod
+ def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
+ idx = index_map.get(column_name.upper())
+ if idx is None or idx >= len(row):
+ return "-"
+ value = row[idx]
+ if value in (None, ""):
+ return "-"
+ upper_name = column_name.upper()
+ if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
+ return cls._format_datetime(value)
+ if upper_name == "FILESIZE":
+ return cls._format_size(value)
+ if upper_name == "NAME":
+ return cls._render_file_name(row, index_map)
+ return str(value)
+
+ @classmethod
+ def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
+ parts = [f"记录 {row_no}"]
+ for column_name in cls._SUMMARY_COLUMNS:
+ if column_name.upper() not in index_map:
+ continue
+ rendered = cls._render_column_value(row, column_name, index_map)
+ label = {
+ "NAME": "文件名",
+ "EXTENTIONNAME": "扩展名",
+ "FILETYPE": "文件类型",
+ "FILESIZE": "文件大小",
+ "RELATIVEPATH": "相对路径",
+ "LASTACCESSTIME": "最后访问时间",
+ }.get(column_name.upper(), column_name)
+ if column_name.upper() == "NAME":
+ parts.append(f"{label}: {rendered}")
+ else:
+ parts.append(f"{label}: {cls._escape_html_text(rendered)}")
+ return " | ".join(parts)
+
+ @classmethod
+ def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
+ rows_html = []
+ for column_name in columns:
+ rendered_value = cls._render_column_value(row, column_name, index_map)
+ safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
+ rows_html.append(
+ "
| 字段 | " + "值 | " + "
|---|