412 lines
21 KiB
Python
412 lines
21 KiB
Python
"""
|
||
backend/app/api/integration.py
|
||
|
||
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
|
||
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
||
逻辑:聊天预览经 /api/chat/preview-* 代理到本模块 download;dify-file 供 IntegrationApiService 反查本地映射。
|
||
"""
|
||
from __future__ import annotations
|
||
from pathlib import Path
|
||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||
from sqlalchemy import func
|
||
from sqlalchemy.orm import joinedload
|
||
from app import db
|
||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||
from app.core.errors import (
|
||
AppError,
|
||
ConflictError,
|
||
ForbiddenError,
|
||
NotFoundError,
|
||
ServiceUnavailableError,
|
||
UnauthorizedError,
|
||
ValidationError,
|
||
raise_for_status,
|
||
)
|
||
from app.services.integration_api import IntegrationApiService
|
||
integration_bp = Blueprint('integration', __name__)
|
||
|
||
|
||
def _integration_token_secret() -> str:
|
||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||
return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||
|
||
|
||
def _decode_integration_token(token: str | None) -> dict | None:
|
||
normalized_token = str(token or '').strip()
|
||
if not normalized_token:
|
||
return None
|
||
try:
|
||
import jwt
|
||
payload = jwt.decode(
|
||
normalized_token,
|
||
_integration_token_secret(),
|
||
algorithms=['HS256'],
|
||
)
|
||
return payload if isinstance(payload, dict) else None
|
||
except Exception as e:
|
||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||
return None
|
||
|
||
|
||
def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str:
|
||
base_url = _integration_base_url()
|
||
url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}'
|
||
if version_id is not None:
|
||
url += f'&version_id={version_id}'
|
||
return url
|
||
|
||
|
||
def _version_query():
|
||
return (
|
||
db.session.query(KbDocumentVersion)
|
||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||
.filter(KbDocument.is_deleted.is_(False))
|
||
)
|
||
|
||
|
||
def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]:
|
||
requested_version_id = request.args.get('version_id', type=int)
|
||
token_payload = _decode_integration_token(request.args.get('token'))
|
||
if isinstance(token_payload, dict):
|
||
token_version_id = token_payload.get('version_id')
|
||
if token_version_id is not None:
|
||
try:
|
||
requested_version_id = int(token_version_id)
|
||
except (TypeError, ValueError):
|
||
current_app.logger.warning(
|
||
'Integration API token carried invalid version_id: %r',
|
||
token_version_id,
|
||
)
|
||
dataset_id = str(token_payload.get('dataset_id') or '').strip()
|
||
remote_document_id = str(token_payload.get('remote_document_id') or '').strip()
|
||
if dataset_id and remote_document_id:
|
||
record = (
|
||
db.session.query(KbDifySyncRecord)
|
||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||
.options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document))
|
||
.filter(
|
||
KbDocument.is_deleted.is_(False),
|
||
KbDocument.id == file_id,
|
||
KbDifySyncRecord.dataset_id == dataset_id,
|
||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||
)
|
||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||
.first()
|
||
)
|
||
if record and record.document_version and record.document_version.document:
|
||
return record.document_version, record.document_version.document
|
||
|
||
if requested_version_id is not None:
|
||
version = (
|
||
_version_query()
|
||
.filter(
|
||
KbDocumentVersion.id == requested_version_id,
|
||
KbDocumentVersion.document_id == file_id,
|
||
)
|
||
.first()
|
||
)
|
||
if version:
|
||
return version, version.document
|
||
|
||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||
if not document:
|
||
return None, None
|
||
return _current_version(document), document
|
||
|
||
def _require_integration_key():
|
||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||
|
||
if not configured:
|
||
|
||
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
|
||
|
||
if configured == incoming:
|
||
return None
|
||
|
||
token = request.args.get('token')
|
||
if token and _decode_integration_token(token):
|
||
return None
|
||
|
||
raise UnauthorizedError('Unauthorized')
|
||
|
||
|
||
def _integration_base_url() -> str:
|
||
request_origin = IntegrationApiService._request_origin_url()
|
||
if request_origin:
|
||
return request_origin
|
||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||
if explicit:
|
||
return explicit
|
||
return request.host_url.rstrip('/')
|
||
|
||
def _kb_storage_root() -> Path:
|
||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||
root.mkdir(parents=True, exist_ok=True)
|
||
return root
|
||
|
||
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||
"""
|
||
解析知识库存储相对/绝对路径,并校验落在 KB_STORAGE_ROOT 内。
|
||
核心逻辑:相对路径拼到存储根;绝对路径直接 resolve 后做越界校验。
|
||
@param path_value: 数据库中的路径字符串
|
||
@returns 合法绝对 Path,越界或空则 None
|
||
"""
|
||
if not path_value:
|
||
return None
|
||
raw_path = Path(str(path_value))
|
||
candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve()
|
||
root = _kb_storage_root()
|
||
try:
|
||
candidate.relative_to(root)
|
||
except ValueError:
|
||
return None
|
||
return candidate
|
||
|
||
|
||
def _existing_storage_path(path_value: str | None) -> Path | None:
|
||
"""
|
||
解析存储路径且要求文件真实存在。
|
||
核心逻辑:先 _resolve_storage_path,再校验 is_file。
|
||
@returns 存在的 Path,否则 None
|
||
"""
|
||
path = _resolve_storage_path(path_value)
|
||
if path is None or not path.exists() or not path.is_file():
|
||
return None
|
||
return path
|
||
|
||
|
||
def _markdown_storage_path(version: KbDocumentVersion) -> Path | None:
|
||
"""
|
||
取版本可用的清洗 Markdown 文件路径(优先 cleaned_file,其次 preview)。
|
||
核心逻辑:路径存在且内容像文本时才返回,避免误把 OLE 二进制当 md。
|
||
"""
|
||
for path_value in (version.cleaned_file_path, version.cleaned_preview_path):
|
||
path = _existing_storage_path(path_value)
|
||
if path is None:
|
||
continue
|
||
try:
|
||
head = path.read_bytes()[:4096]
|
||
except OSError:
|
||
continue
|
||
if head.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
|
||
current_app.logger.warning(
|
||
'[integration] skip binary cleaned path version_id=%s path=%s',
|
||
version.id,
|
||
path,
|
||
)
|
||
continue
|
||
if b'\x00' in head:
|
||
continue
|
||
return path
|
||
return None
|
||
|
||
|
||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||
versions = list(getattr(document, 'versions', []) or [])
|
||
if not versions:
|
||
return None
|
||
return next((item for item in versions if item.is_current), versions[0])
|
||
|
||
def _document_query():
|
||
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||
|
||
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||
"""
|
||
序列化集成侧文档元数据与可下载 URL。
|
||
核心逻辑:源文件在磁盘存在时返回 kind=source;否则回退到清洗 Markdown(kind=md),
|
||
避免聊天预览拿到“库有映射、盘无文件”的死链。
|
||
"""
|
||
version = version or _current_version(document)
|
||
if not version:
|
||
abort(404, description='No current version found.')
|
||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||
source_path = _existing_storage_path(version.source_file_path)
|
||
markdown_path = _markdown_storage_path(version)
|
||
markdown_download_url = (
|
||
_build_download_url(document.id, kind='md', version_id=version.id) if markdown_path else None
|
||
)
|
||
if source_path is not None:
|
||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||
source_filename = version.source_file_name
|
||
source_ext = version.source_file_ext
|
||
elif markdown_path is not None:
|
||
# [STEP] 源文件缺失时用清洗稿顶替预览入口,扩展名改为 md 以便前端走文本预览
|
||
source_download_url = markdown_download_url
|
||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||
source_filename = f'{stem}.md'
|
||
source_ext = 'md'
|
||
current_app.logger.info(
|
||
'[integration] source missing, serialize fallback to markdown document_id=%s version_id=%s',
|
||
document.id,
|
||
version.id,
|
||
)
|
||
else:
|
||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||
source_filename = version.source_file_name
|
||
source_ext = version.source_file_ext
|
||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': source_filename, 'source_ext': source_ext, 'file_name': source_filename, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||
|
||
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||
|
||
def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: int | None=None, file_name: str | None=None) -> list[dict]:
|
||
normalized_file_name = str(file_name or '').strip().lower()
|
||
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||
if knowledge_base_id is not None:
|
||
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||
if department_id is not None:
|
||
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||
documents = query.all()
|
||
payload = []
|
||
for document in documents:
|
||
version = _current_version(document)
|
||
if not version:
|
||
continue
|
||
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
||
if normalized_file_name and normalized_file_name not in normalized_name and (normalized_file_name not in document.title.lower()):
|
||
continue
|
||
payload.append(_serialize_integration_document(document, version=version))
|
||
return payload
|
||
|
||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||
"""
|
||
解析下载目标路径与文件名。
|
||
核心逻辑:kind=source 优先原始文件;缺失时回退清洗 Markdown,避免预览 404。
|
||
@param version: 文档版本
|
||
@param kind: source | md
|
||
@returns (绝对路径, 下载文件名)
|
||
@raises NotFoundError: 源文件与清洗稿均不存在
|
||
"""
|
||
if kind == 'source':
|
||
path = _existing_storage_path(version.source_file_path)
|
||
if path is not None:
|
||
filename = version.source_file_name or f'document-{version.document_id}'
|
||
return (path, filename)
|
||
preferred = _markdown_storage_path(version)
|
||
if preferred is not None:
|
||
current_app.logger.warning(
|
||
'[integration] source file missing, fallback to markdown document_id=%s version_id=%s path=%s',
|
||
version.document_id,
|
||
version.id,
|
||
preferred,
|
||
)
|
||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||
return (preferred, filename)
|
||
raise NotFoundError('File not found on disk.')
|
||
preferred = _markdown_storage_path(version)
|
||
if not preferred:
|
||
abort(409, description='Markdown not ready.')
|
||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||
return (preferred, filename)
|
||
|
||
@integration_bp.before_request
|
||
def _verify_integration_access():
|
||
result = _require_integration_key()
|
||
if result is not None:
|
||
return result
|
||
return None
|
||
|
||
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||
def get_file_detail(file_id: int):
|
||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||
if not document:
|
||
raise NotFoundError('Document not found.')
|
||
return jsonify(_serialize_integration_document(document))
|
||
|
||
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||
def list_knowledge_bases():
|
||
department_id = request.args.get('department_id', type=int)
|
||
q = str(request.args.get('q') or '').strip()
|
||
document_counts = db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')).filter(KbDocument.is_deleted.is_(False)).group_by(KbDocument.group_id).subquery()
|
||
query = db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')).outerjoin(document_counts, document_counts.c.group_id == KbGroup.id).filter(KbGroup.is_active.is_(True)).order_by(KbGroup.name.asc())
|
||
if department_id is not None:
|
||
query = query.filter(KbGroup.department_id == department_id)
|
||
if q:
|
||
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||
rows = query.all()
|
||
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||
|
||
@integration_bp.route('/files', methods=['GET'])
|
||
def list_files():
|
||
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||
department_id = request.args.get('department_id', type=int)
|
||
file_name = request.args.get('file_name')
|
||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, department_id=department_id, file_name=file_name)})
|
||
|
||
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
||
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
|
||
|
||
@integration_bp.route('/dify-file', methods=['GET'])
|
||
def get_file_detail_by_dify():
|
||
"""
|
||
按 Dify dataset/document 反查本地知识库文件元数据。
|
||
核心逻辑:查 KbDifySyncRecord;若源文件与清洗稿均不在磁盘,返回 404 以便上层改走 Dify 下载。
|
||
"""
|
||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||
if not remote_document_id:
|
||
raise ValidationError('remote_document_id is required')
|
||
record_query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id == remote_document_id).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||
if dataset_id:
|
||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||
record = record_query.first()
|
||
version = record.document_version if record else None
|
||
document = version.document if version else None
|
||
if not document or not version:
|
||
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||
if _existing_storage_path(version.source_file_path) is None and _markdown_storage_path(version) is None:
|
||
raise NotFoundError('No readable local file for the given Dify document.')
|
||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||
|
||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||
def resolve_files_by_dify():
|
||
data = request.get_json(silent=True) or {}
|
||
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||
if not items:
|
||
return jsonify({'data': []})
|
||
remote_ids = sorted({str(item.get('remote_document_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()})
|
||
dataset_ids = sorted({str(item.get('dataset_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()})
|
||
if not remote_ids:
|
||
return jsonify({'data': []})
|
||
query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id.in_(remote_ids)).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||
if dataset_ids:
|
||
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
|
||
records = query.all()
|
||
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||
for record in records:
|
||
key = (record.dataset_id, record.remote_document_id)
|
||
records_by_key.setdefault(key, record)
|
||
records_by_remote.setdefault(record.remote_document_id, record)
|
||
payload = []
|
||
for item in items:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
|
||
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
|
||
if not requested_remote_document_id:
|
||
continue
|
||
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
|
||
if record is None and requested_dataset_id is None:
|
||
record = records_by_remote.get(requested_remote_document_id)
|
||
version = record.document_version if record else None
|
||
document = version.document if version else None
|
||
payload.append({'request': {'dataset_id': requested_dataset_id, 'remote_document_id': requested_remote_document_id}, 'found': bool(document), 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None})
|
||
return jsonify({'data': payload})
|
||
|
||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||
def download_file(file_id: int):
|
||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||
version, document = _resolve_requested_version(file_id)
|
||
if not document:
|
||
raise NotFoundError('Document not found.')
|
||
if not version:
|
||
raise NotFoundError('No version found.')
|
||
path, filename = _resolve_download_path(version, kind)
|
||
if not path.exists():
|
||
raise NotFoundError('File not found on disk.')
|
||
return send_file(path, as_attachment=True, download_name=filename)
|