文件预览优化

This commit is contained in:
runny committed 2026-05-30 14:10:44 +08:00
1 parent f91d44ca24
commit 7f66d6f20c
5 files changed
+504 -165

No files matched your search

+202 -56
View File
@@ -1,7 +1,7 @@
"""
Integration API client for resolving original source-file download links.
"""
from datetime import datetime
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
@@ -14,6 +14,88 @@ from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
except Exception:
return None
try:
service = KbDifySyncService()
if not service.base_url or not service.api_key:
return None
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
download_resp = requests.get(
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
headers=service._headers(),
timeout=(5, 15),
)
if download_resp.status_code != 200:
if has_app_context():
current_app.logger.info(
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
download_resp.status_code,
)
return None
download_payload = download_resp.json() if download_resp.content else {}
source_url = str((download_payload or {}).get("url") or "").strip()
if not source_url:
return None
upload_info = (
((document_payload.get("data_source_info") or {}).get("upload_file"))
if isinstance(document_payload.get("data_source_info"), dict)
else {}
) or {}
source_filename = str(
upload_info.get("name")
or document_payload.get("name")
or ""
).strip() or None
source_ext = str(
upload_info.get("extension")
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
).strip().lower() or None
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
return {
"source_download_url": source_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": expires_at,
"version_id": None,
"document_id": remote_document_id,
}
except Exception as e:
if has_app_context():
current_app.logger.warning(
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
dataset_id,
remote_document_id,
e,
)
return None
@staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict):
@@ -114,6 +196,63 @@ class IntegrationApiService:
return True
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not has_app_context():
return None
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if not record or not record.document_version or not record.document_version.document:
return None
version = record.document_version
document = version.document
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
base_url = explicit
elif has_request_context():
base_url = request.host_url.rstrip('/')
else:
base_url = ''
import time
import jwt
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not secret:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': 'local',
'remote_document_id': remote_document_id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source&token={token}'
return {
"source_download_url": source_download_url,
"source_filename": version.source_file_name,
"source_ext": version.source_file_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
}
@staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id:
@@ -169,25 +308,35 @@ class IntegrationApiService:
}
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
if resp.status_code == 200:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
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
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
return None
# Fallback to local database if remote integration API fails or misses
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[cache_key] = local_result
return local_result
# Last fallback: query Dify document API directly and request a signed download URL.
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
if dify_result:
IntegrationApiService._cache[cache_key] = dify_result
return dify_result
return None
@staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
@@ -243,45 +392,42 @@ class IntegrationApiService:
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
# Fallback to single lookup for reliability.
for item in unresolved:
payload = IntegrationApiService.lookup_file_by_dify(
item["dataset_id"], item["remote_document_id"]
)
if payload:
key = IntegrationApiService._cache_key(
item["dataset_id"], item["remote_document_id"]
)
results[key] = payload
return results
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(data, list):
return results
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
return results
else:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup when batch call errors.
for item in unresolved:
payload = IntegrationApiService.lookup_file_by_dify(
item["dataset_id"], item["remote_document_id"]
)
if payload:
key = IntegrationApiService._cache_key(
item["dataset_id"], item["remote_document_id"]
)
results[key] = payload
return results
# Fallback to single lookup or local DB for unresolved items
for item in unresolved:
dataset_id = item["dataset_id"]
remote_document_id = item["remote_document_id"]
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in results:
continue
# Check if single lookup was not called already (if it was, it might be cached)
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[key] = local_result
results[key] = local_result
continue
# As a last resort, try remote single lookup if batch missed it
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if payload:
results[key] = payload
return results