""" api/chat/uploads.py 用途:处理聊天附件上传并转发至当前 Agent 对应的 Dify 应用。 依赖:chat.shared、DifyService、Config、requests、chat_bp。 逻辑:校验文件类型、上传方式和大小限制后调用 Dify 文件接口,返回标准化文件元数据。 """ from __future__ import annotations from .shared import * # noqa: F403 from . import chat_bp @chat_bp.route('/files/upload', methods=['POST']) @require_agent_permission def upload_chat_file(): user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) if user is None or agent is None: raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500) if str(getattr(agent, 'type', '') or '').strip().lower() != 'api': raise ValidationError('This agent does not support file upload') if not getattr(agent, 'dify_api_key', None): raise ValidationError('This agent does not support file upload') upload = request.files.get('file') if not upload: raise ValidationError('file is required') from app.services.integrations.dify import DifyService from app.core.config.settings import Config params = DifyService.get_app_parameters(agent, force_refresh=True) file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {} system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {} filename = str(getattr(upload, 'filename', '') or '').strip() mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip() detected_type, ext = DifyService.detect_file_type(filename, mimetype) file_type = None normalized_allowed_types = None normalized_allowed_methods = None normalized_allowed_exts = None is_new_schema = False if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list): is_new_schema = True normalized_allowed_types = set( ( str(v or '').strip().lower() for v in (file_upload_cfg.get('allowed_file_types') or []) if str(v or '').strip() ) ) normalized_allowed_methods = set( ( str(v or '').strip().lower() for v in (file_upload_cfg.get('allowed_file_upload_methods') or []) if str(v or '').strip() ) ) exts = [] for v in (file_upload_cfg.get('allowed_file_extensions') or []): s = str(v or '').strip() if not s: continue if s.startswith('.'): s = s[1:] s = s.lower().strip() if s: exts.append(s) normalized_allowed_exts = set(exts) if exts else None if detected_type: file_type = detected_type else: if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)): file_type = 'custom' else: custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)): file_type = 'custom' else: raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})') def _effective_type_methods(target_type: str) -> set[str]: if not isinstance(file_upload_cfg, dict): return set(normalized_allowed_methods or set()) cfg = file_upload_cfg.get(target_type) transfer_methods = [] if isinstance(cfg, dict): transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or [] if isinstance(transfer_methods, str): transfer_methods = [transfer_methods] if isinstance(transfer_methods, list) and len(transfer_methods) > 0: return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip()) return set(normalized_allowed_methods or set()) def _is_type_enabled_in_new_schema(target_type: str) -> bool: if not (is_new_schema and normalized_allowed_types): return False if not isinstance(file_upload_cfg, dict): return target_type in normalized_allowed_types cfg = file_upload_cfg.get(target_type) if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool): if cfg.get('enabled') is False: return False if cfg.get('enabled') is True: return True return target_type in normalized_allowed_types if is_new_schema and normalized_allowed_types: if not _is_type_enabled_in_new_schema(file_type): raise ValidationError(f'File type not enabled: {file_type}') type_methods = _effective_type_methods(file_type) if 'local_file' not in type_methods: raise ValidationError('local_file upload is not enabled') if normalized_allowed_exts: allowed_for_type = set() for e in normalized_allowed_exts: t, _ = DifyService.detect_file_type(f'file.{e}', None) if t is None: if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)): allowed_for_type.add(e) continue if t == file_type: allowed_for_type.add(e) if allowed_for_type and (not ext or ext not in allowed_for_type): raise ValidationError(f'Unsupported file extension: .{ext or ""}') else: # legacy schema checks type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'): raise ValidationError(f'File type not enabled: {file_type}') transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or [] if isinstance(transfer_methods, str): transfer_methods = [transfer_methods] if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)): raise ValidationError('local_file upload is not enabled') def _mb_limit_for_type() -> float | None: merged = {} if isinstance(system_params, dict): merged.update(system_params) if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict): merged.update(file_upload_cfg.get('fileUploadConfig') or {}) if file_type == 'image': return merged.get('image_file_size_limit') or merged.get('file_size_limit') if file_type == 'audio': return merged.get('audio_file_size_limit') or merged.get('file_size_limit') if file_type == 'video': return merged.get('video_file_size_limit') or merged.get('file_size_limit') return merged.get('file_size_limit') size_limit_mb = _mb_limit_for_type() if size_limit_mb is not None: try: import os stream = getattr(upload, 'stream', None) if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'): cur = stream.tell() stream.seek(0, os.SEEK_END) size_bytes = stream.tell() stream.seek(cur) limit_bytes = int(float(size_limit_mb) * 1024 * 1024) if size_bytes > limit_bytes: raise ValidationError(f'File too large (limit {size_limit_mb}MB)') except ValidationError: raise except Exception: pass base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE dify_url = DifyService._build_files_upload_url(base_url) headers = {'Authorization': f'Bearer {agent.dify_api_key}'} try: try: upload.stream.seek(0) except Exception: pass resp = requests.post( dify_url, headers=headers, files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')}, data={'user': str(getattr(user, 'id', 'system'))}, timeout=(5, 300), ) except requests.RequestException as exc: raise ServiceUnavailableError(f'Upload failed: {exc}') if not resp.ok: body = (resp.text or '')[:1500] header_snapshot = {} try: for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'): v = resp.headers.get(k) or resp.headers.get(k.title()) if v: header_snapshot[k] = v except Exception: header_snapshot = {} current_app.logger.warning( '[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s', resp.status_code, dify_url, header_snapshot, body, ) raise AppError( code='DIFY.UPLOAD_FAILED', message='Upload failed', http_status=502, details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot}, ) data = resp.json() if resp.content else {} return jsonify({ 'id': data.get('id'), 'name': data.get('name') or filename, 'size': data.get('size'), 'extension': data.get('extension') or ext, 'mime_type': data.get('mime_type') or mimetype, 'type': file_type, })