fix: 支持原文件下载,同时将postgres地址由localhost变更为8.152.207.171
This commit is contained in:
1 parent
70f95e9f5c
commit
c380248502
12 files changed
+1273
-273
No files matched your search
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
Integration API client for resolving original source-file download links.
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app.config import Config
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp = payload.get("download_url_expires_at")
|
||||
if not exp:
|
||||
return True
|
||||
try:
|
||||
return datetime.fromisoformat(exp) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
@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:
|
||||
return None
|
||||
|
||||
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
cached = IntegrationApiService._cache.get(cache_key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
|
||||
api_key = Config.INTEGRATION_API_KEY
|
||||
if not base_url or not api_key:
|
||||
return None
|
||||
|
||||
url = f"{base_url}/api/integration/dify-file"
|
||||
headers = {"X-Integration-Key": api_key}
|
||||
params = {
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
payload = resp.json()
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||
"""
|
||||
Batch resolve source files by (dataset_id, remote_document_id).
|
||||
Returns a mapping keyed by (dataset_id, remote_document_id).
|
||||
"""
|
||||
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
if not items:
|
||||
return results
|
||||
|
||||
unresolved: List[Dict[str, str]] = []
|
||||
seen = set()
|
||||
|
||||
for item in items:
|
||||
dataset_id = str(item.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(item.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
cached = IntegrationApiService._cache.get(key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
results[key] = cached
|
||||
else:
|
||||
unresolved.append({
|
||||
"dataset_id": dataset_id,
|
||||
"remote_document_id": remote_document_id,
|
||||
})
|
||||
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
|
||||
api_key = Config.INTEGRATION_API_KEY
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {"items": unresolved}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if current_app:
|
||||
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
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
if not row.get("found"):
|
||||
continue
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
continue
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
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
|
||||
Reference in new issue
Block a user