This commit is contained in:
runny committed 2026-05-12 14:33:48 +08:00
1 parent 08a19ebe96
commit dea3b39048
6 files changed
+240 -33

No files matched your search

+61 -8
View File
@@ -62,7 +62,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return False 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 拉取二进制内容(供预览接口复用)。 从上游文件 URL 拉取二进制内容(供预览接口复用)。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。 如果 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) return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b'' content = upstream.content or b''
max_size = 15 * 1024 * 1024
if len(content) > max_size: if len(content) > max_size:
return None, None, ('file too large for online preview', 413) 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") 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']) @chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission @require_agent_permission
def get_chat_sessions(): def get_chat_sessions():
@@ -579,8 +630,8 @@ def preview_excel():
""" """
内网 Excel 预览接口(简版可上线)。 内网 Excel 预览接口(简版可上线)。
说明: 说明:
- 当前仅支持 xlsx; - xlsx 直接解析;
- xls 返回 415,由前端走下载兜底。 - xls 先转为 xlsx 后再解析。
""" """
file_url = (request.args.get('url') or '').strip() file_url = (request.args.get('url') or '').strip()
if not file_url: if not file_url:
@@ -603,13 +654,13 @@ def preview_excel():
limit = 100 limit = 100
limit = max(1, min(limit, 300)) 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: if err:
msg, code = err msg, code = err
return jsonify({'error': msg}), code return jsonify({'error': msg}), code
try: try:
wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) wb = _load_excel_workbook(content, ext)
except Exception as e: except Exception as e:
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e) current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
return jsonify({'error': 'failed to parse excel file'}), 422 return jsonify({'error': 'failed to parse excel file'}), 422
@@ -674,7 +725,8 @@ def preview_text():
if ext and ext not in allowed: if ext and ext not in allowed:
return jsonify({'error': f'unsupported text extension: {ext}'}), 415 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: if err:
msg, code = err msg, code = err
return jsonify({'error': msg}), code return jsonify({'error': msg}), code
@@ -717,7 +769,8 @@ def preview_file_raw():
name = (request.args.get('name') or '').strip() name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower() name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext 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: if err:
msg, code = err msg, code = err
return jsonify({'error': msg}), code return jsonify({'error': msg}), code
+30 -2
View File
@@ -37,6 +37,35 @@ from app.services.integration_api import IntegrationApiService
class DifyService: class DifyService:
"""Dify service wrapper.""" """Dify service wrapper."""
@staticmethod
def _build_chat_messages_url(base_url: str) -> str:
"""
Build the Dify chat-messages endpoint URL from a base URL.
Our config/agent base_url may be:
- https://api.dify.ai/v1
- http://host:port
- http://host:port/v1
- (user mistake) http://host:port/v1/chat-messages
This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`.
"""
base = str(base_url or "").strip().rstrip("/")
if not base:
# Keep old behavior: downstream will fail with a request error.
return "/v1/chat-messages"
# User mistake hardening: strip endpoint suffix if someone stored it as base_url.
if base.endswith("/v1/chat-messages"):
base = base[: -len("/v1/chat-messages")].rstrip("/")
elif base.endswith("/chat-messages"):
base = base[: -len("/chat-messages")].rstrip("/")
# Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1".
if base.endswith("/v1"):
return f"{base}/chat-messages"
return f"{base}/v1/chat-messages"
@staticmethod @staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None): def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
""" """
@@ -60,8 +89,7 @@ class DifyService:
""" """
# Prefer agent-specific base URL; fallback to global config. # Prefer agent-specific base URL; fallback to global config.
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
base_url = base_url.rstrip('/') url = DifyService._build_chat_messages_url(base_url)
url = f"{base_url}/v1/chat-messages"
headers = { headers = {
'Authorization': f'Bearer {agent.dify_api_key}', 'Authorization': f'Bearer {agent.dify_api_key}',
+13
View File
@@ -3,6 +3,7 @@ Integration API client for resolving original source-file download links.
""" """
from datetime import datetime from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import requests import requests
from flask import current_app, has_app_context, has_request_context, request from flask import current_app, has_app_context, has_request_context, request
@@ -13,6 +14,11 @@ from app.config import Config
class IntegrationApiService: class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {} _cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
return host in {"127.0.0.1", "localhost", "::1"}
@staticmethod @staticmethod
def get_api_key() -> str: def get_api_key() -> str:
if has_app_context(): if has_app_context():
@@ -32,6 +38,13 @@ class IntegrationApiService:
public_base = "" public_base = ""
if mode != "external": 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: if public_base:
return public_base return public_base
if has_request_context(): if has_request_context():
+130 -22
View File
@@ -2,10 +2,13 @@ import json
import os import os
import re import re
import time import time
from pathlib import Path
from flask import current_app from flask import current_app
class Text2SQLService: class Text2SQLService:
_schema_text = None _schema_text = None
_oracle_client_initialized = False
_jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar"
@staticmethod @staticmethod
def _backend_dir() -> str: def _backend_dir() -> str:
@@ -33,6 +36,122 @@ class Text2SQLService:
return client_dirs[0] return client_dirs[0]
return None return None
@classmethod
def _get_oracle_client_dir(cls) -> str | None:
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
if env_dir and os.path.exists(env_dir):
return env_dir
linux_candidates = [
"/opt/oracle/instantclient",
"/opt/oracle/instantclient_19_28",
"/opt/oracle/instantclient_19_27",
]
for path in linux_candidates:
if os.path.exists(path):
return path
return cls._find_oracle_client_dir()
@classmethod
def _init_oracle_client(cls, oracledb) -> None:
if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
return
import platform
import shutil
import tempfile
target_lib_dir = cls._get_oracle_client_dir()
if platform.system() == 'Windows' and target_lib_dir:
# OCI C-library fails to load if path contains non-ASCII.
if not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
target_lib_dir = safe_lib_dir
if target_lib_dir:
oracledb.init_oracle_client(lib_dir=target_lib_dir)
else:
oracledb.init_oracle_client()
cls._oracle_client_initialized = True
@classmethod
def _jdbc_dir(cls) -> Path:
return Path(cls._backend_dir()) / "jdbc"
@classmethod
def _ensure_jdbc_driver_jar(cls) -> str:
env_path = (os.getenv("ERP_JDBC_JAR") or "").strip()
if env_path and os.path.exists(env_path):
return env_path
jar_dir = cls._jdbc_dir()
jar_dir.mkdir(parents=True, exist_ok=True)
jar_path = jar_dir / "ojdbc8-19.25.0.0.jar"
if jar_path.exists():
return str(jar_path)
import requests
driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url
with requests.get(driver_url, stream=True, timeout=120) as resp:
resp.raise_for_status()
with open(jar_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=1024 * 256):
if chunk:
f.write(chunk)
return str(jar_path)
@staticmethod
def _dsn_to_jdbc_url(dsn: str) -> str:
dsn = (dsn or "").strip()
if not dsn:
raise ValueError("ERP_DB_DSN is empty")
if dsn.startswith("jdbc:oracle:thin:@"):
return dsn
if dsn.startswith("("):
return f"jdbc:oracle:thin:@{dsn}"
match = re.match(r"^(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", dsn)
if match:
host = match.group("host")
port = match.group("port") or "1521"
service = match.group("service")
return f"jdbc:oracle:thin:@//{host}:{port}/{service}"
return f"jdbc:oracle:thin:@{dsn}"
@classmethod
def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str):
import jaydebeapi
jar_path = cls._ensure_jdbc_driver_jar()
jdbc_url = cls._dsn_to_jdbc_url(dsn)
connection = jaydebeapi.connect(
"oracle.jdbc.OracleDriver",
jdbc_url,
{
"user": user,
"password": password,
"oracle.jdbc.timezoneAsRegion": "false",
},
jar_path,
)
cursor = connection.cursor()
try:
cursor.execute(sql)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchall() if columns else []
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod @classmethod
def get_schema(cls): def get_schema(cls):
if cls._schema_text is None: if cls._schema_text is None:
@@ -211,27 +330,8 @@ class Text2SQLService:
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod") dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
try: try:
# Enable thick mode to support older Oracle versions # Old ERP Oracle versions require python-oracledb thick mode.
import platform cls._init_oracle_client(oracledb)
import tempfile
import shutil
if platform.system() == 'Windows':
target_lib_dir = cls._find_oracle_client_dir()
# Fix for OCI path issue with Chinese characters (like "HX工作目录")
# OCI C-library fails to load if path contains non-ASCII
if target_lib_dir and not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
target_lib_dir = safe_lib_dir
if target_lib_dir:
oracledb.init_oracle_client(lib_dir=target_lib_dir)
else:
oracledb.init_oracle_client()
except Exception as e: except Exception as e:
if current_app: if current_app:
current_app.logger.warning(f"Failed to init thick mode: {e}") current_app.logger.warning(f"Failed to init thick mode: {e}")
@@ -249,7 +349,15 @@ class Text2SQLService:
return columns, rows return columns, rows
except Exception as e: except Exception as e:
return ["Error"], [[str(e)]] error_text = str(e)
if current_app:
current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}")
if "DPY-3010" in error_text or "DPI-1047" in error_text:
try:
return cls._execute_sql_via_jdbc(sql, user, password, dsn)
except Exception as jdbc_error:
return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]]
return ["Error"], [[error_text]]
@classmethod @classmethod
def format_result(cls, columns, rows, sql, original_query): def format_result(cls, columns, rows, sql, original_query):
+2
View File
@@ -16,6 +16,8 @@ pycryptodome
PyJWT PyJWT
cryptography cryptography
oracledb oracledb
jaydebeapi
JPype1
pywin32; sys_platform == "win32" pywin32; sys_platform == "win32"
# File Parsing & edkb_system dependencies from xinxin2 # File Parsing & edkb_system dependencies from xinxin2
+4 -1
View File
@@ -571,7 +571,10 @@ const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\
const isLeaveIntent = (content: string) => { const isLeaveIntent = (content: string) => {
const normalized = getLeaveIntentNormalized(content); const normalized = getLeaveIntentNormalized(content);
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程|请假流程)/.test(normalized); // 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/;
if (weakConsultationIntent.test(normalized)) return false;
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|帮我请假|代我请假|提交请假)/.test(normalized);
}; };
const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => ( const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (