""" Integration API client for resolving original source-file download links. """ from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from urllib.parse import urlparse import requests from flask import current_app, has_app_context, has_request_context, request from app.config import Config class IntegrationApiService: _cache: Dict[Tuple[str, str], Dict[str, Any]] = {} @staticmethod def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]: if not isinstance(row, dict): return None 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 or not row.get("found"): return None doc = row.get("document") if isinstance(row.get("document"), dict) else {} source_url = doc.get("source_download_url") if not source_url: return None 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) return key, normalized @staticmethod def _is_loopback_url(url: str) -> bool: host = (urlparse(str(url or "").strip()).hostname or "").strip().lower() return host in {"127.0.0.1", "localhost", "::1"} @staticmethod def get_api_key() -> str: if has_app_context(): return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip() return str(Config.INTEGRATION_API_KEY or "").strip() @staticmethod def get_base_url() -> str: mode = "local" if has_app_context(): mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower() configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/") public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/") else: mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower() configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/") public_base = "" # For server-side lookups, always prefer the explicitly configured # integration service endpoint when present. Falling back to the current # request host would incorrectly call this backend itself. if configured: return configured if mode != "external": if public_base: return public_base if has_request_context(): return request.host_url.rstrip("/") return configured @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_str = payload.get("download_url_expires_at") if exp_str: try: return datetime.fromisoformat(exp_str) > datetime.now().astimezone() except Exception: pass # 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查 source_url = payload.get("source_download_url") or "" if "token=" in source_url: try: import base64 import json from urllib.parse import urlparse, parse_qs import time qs = parse_qs(urlparse(source_url).query) if 'token' in qs: token = qs['token'][0] parts = token.split('.') if len(parts) >= 2: payload_b64 = parts[1] payload_b64 += '=' * (-len(payload_b64) % 4) payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) exp = payload_data.get('exp', 0) if exp and exp < time.time() + 300: return False # 已过期或即将过期 except Exception: pass 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 = IntegrationApiService.get_base_url() api_key = IntegrationApiService.get_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: payload = resp.json() if isinstance(payload, dict): IntegrationApiService._cache[cache_key] = payload return payload elif has_app_context(): current_app.logger.info( "Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s", dataset_id, remote_document_id, resp.status_code, ) except Exception as e: if has_app_context(): current_app.logger.warning(f"Integration API lookup failed: {e}") batch_url = f"{base_url}/api/integration/dify-files/resolve" batch_headers = { "X-Integration-Key": api_key, "Content-Type": "application/json", } batch_body = { "items": [ { "dataset_id": str(dataset_id), "remote_document_id": str(remote_document_id), } ] } 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 except Exception as e: if has_app_context(): current_app.logger.warning(f"Integration API batch fallback 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 = IntegrationApiService.get_base_url() api_key = IntegrationApiService.get_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 has_app_context(): 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 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