""" api/chat/shared.py 用途:汇总聊天 API 子模块共同使用的框架对象、模型、服务和常量。 依赖:Flask、SQLAlchemy、DifyService、IntegrationApiService、聊天数据模型。 逻辑:各 chat 路由模块从本文件复用基础依赖;Blueprint 仅由 api/chat/__init__.py 创建,避免重复注册。 """ import io import ipaddress import mimetypes import ntpath import posixpath import tempfile import os import re import subprocess import uuid import json import time from datetime import datetime from urllib.parse import urlparse import requests from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context from sqlalchemy import func, desc, or_, exists, and_ from openpyxl import load_workbook from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs from app.services.integrations.dify import DifyService from app.core.config.settings import Config from app.services.integrations.integration_api import IntegrationApiService from app.core.decorators import require_agent_permission from app.models import Agent, ChatLog, ChatSession, Feedback from app import db from app.core.errors import ( AppError, ConflictError, ForbiddenError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError, raise_for_status, ) SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' # 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。 CHAT_USER_ATTACHMENT_LIMIT = 200 CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024 CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'} CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'} def _normalize_user_attachments(value) -> list[dict]: """ 校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举; 列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。 Args: value: 前端 user_attachments 原始值;必须为列表。 Returns: 可安全写入 JSON 的附件快照列表;非法项目被忽略。 Raises: ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。 """ if not isinstance(value, list): return [] if len(value) > CHAT_USER_ATTACHMENT_LIMIT: raise ValidationError( f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})', code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED', details={ 'limit': CHAT_USER_ATTACHMENT_LIMIT, 'count': len(value), }, ) normalized: list[dict] = [] for item in value: if not isinstance(item, dict): continue raw_name = str(item.get('name') or '') basename = re.split(r'[\\/]+', raw_name)[-1] name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255] attachment_type = str(item.get('type') or '').strip().lower() source = str(item.get('source') or '').strip().lower() if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES: continue snapshot = { 'name': name, 'type': attachment_type, 'source': source, } extension = str(item.get('extension') or '').strip().lower() if re.fullmatch(r'[a-z0-9]{1,16}', extension): snapshot['extension'] = extension try: size = int(item.get('size')) if item.get('size') is not None else None except (TypeError, ValueError): size = None if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE: snapshot['size'] = size normalized.append(snapshot) return normalized def _merge_user_attachments_from_terminal_event( event_data: dict, *, user_id: int, agent_id: int, session_id: str, user_attachments: list[dict], ) -> bool: """ 在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。 Args: event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。 user_id: 当前用户 ID。 agent_id: 当前 Agent ID。 session_id: 当前 HXOPS 本地会话 ID。 user_attachments: 已完成白名单校验的附件快照。 Returns: 找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。 """ if not user_attachments: return False try: chat_log_id = int(event_data.get('chat_log_id') or 0) except (TypeError, ValueError): return False if chat_log_id <= 0: return False from app.services.chat.log_service import merge_chat_log_payload return merge_chat_log_payload( chat_log_id=chat_log_id, user_id=int(user_id or 0), agent_id=int(agent_id or 0), session_id=session_id, payload_patch={'user_attachments': user_attachments}, ) PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()