diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 8e969446..4664c2dc 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -246,10 +246,13 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first() if log and log.retriever_resources: for r in log.retriever_resources: + if not isinstance(r, dict): + continue source_url = str(r.get('source_download_url') or '') if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]): - dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip() - remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip() + resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r) + dataset_id = dataset_id or str(resolved_dataset_id or '').strip() + remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip() if dataset_id and remote_document_id: break except Exception as e: @@ -1411,12 +1414,6 @@ def resolve_source_file(): source_ext = str(payload.get('source_ext') or '').strip().lower() source_download_url = payload.get('source_download_url') - if source_ext in {'txt', 'md', 'markdown', 'csv', 'vtt', 'properties', 'html', 'htm'}: - current_agent = getattr(g, 'current_agent', None) - source_download_url = ( - f"{request.host_url.rstrip('/')}/api/chat/source-file-text" - f"?agent_id={getattr(current_agent, 'id', '')}&dataset_id={dataset_id}&remote_document_id={remote_document_id}" - ) return jsonify({ 'dataset_id': dataset_id, @@ -1649,7 +1646,6 @@ def preview_file_raw(): # 避免在服务端走旧版转换链路导致长时间卡住。 needs_pdf_conversion = ( request.args.get('download') != '1' - and original_ext in ('doc', 'ppt', 'pptx') and ext in ('doc', 'ppt', 'pptx') ) if needs_pdf_conversion: diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py index 3bfee934..1a87683e 100644 --- a/backend/app/api/integration.py +++ b/backend/app/api/integration.py @@ -12,6 +12,95 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status 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() @@ -24,15 +113,8 @@ def _require_integration_key(): return None token = request.args.get('token') - if token: - try: - import jwt - secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() - jwt.decode(token, secret, algorithms=['HS256']) - return None - except Exception as e: - current_app.logger.warning(f"Integration API token validation failed: {e}") - pass + if token and _decode_integration_token(token): + return None raise UnauthorizedError('Unauthorized') @@ -57,9 +139,8 @@ def _serialize_integration_document(document: KbDocument, *, version: KbDocument 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)) - base_url = _integration_base_url() - source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source' - markdown_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=md' if version.cleaned_file_path or version.cleaned_preview_path else None + source_download_url = _build_download_url(document.id, kind='source', version_id=version.id) + markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None 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': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, '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: @@ -189,13 +270,12 @@ def resolve_files_by_dify(): @integration_bp.route('/files//download', methods=['GET']) def download_file(file_id: int): kind = str(request.args.get('kind') or 'md').strip().lower() - document = _document_query().filter(KbDocument.id == file_id).first() + version, document = _resolve_requested_version(file_id) if not document: raise NotFoundError('Document not found.') - version = _current_version(document) 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) \ No newline at end of file + return send_file(path, as_attachment=True, download_name=filename) diff --git a/backend/app/api/knowledge_base.py b/backend/app/api/knowledge_base.py index d0479035..450fd790 100644 --- a/backend/app/api/knowledge_base.py +++ b/backend/app/api/knowledge_base.py @@ -26,12 +26,9 @@ def _safe_upload_filename(raw_filename: str | None) -> str: original_name = Path(raw_filename or '').name.strip() if not original_name: return 'uploaded_file' - original_path = Path(original_name) - safe_stem = secure_filename(original_path.stem) - suffix = original_path.suffix.lower() - if not safe_stem: - safe_stem = 'uploaded_file' - return f'{safe_stem}{suffix}' + import re + safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name) + return safe_name or 'uploaded_file' def _require_user(): user = get_current_user() diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 19f30dd4..a9b759ce 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -867,22 +867,23 @@ class DifyService: remote_document_id = ( resource.get('remote_document_id') or resource.get('dify_document_id') - or resource.get('document_id') + or resource.get('source_document_id') or resource.get('doc_id') or metadata.get('remote_document_id') or metadata.get('dify_document_id') - or metadata.get('document_id') + or metadata.get('source_document_id') or metadata.get('doc_id') or DifyService._find_first_by_keys( resource, [ 'remote_document_id', 'dify_document_id', - 'document_id', - 'doc_id', 'source_document_id', + 'doc_id', ], ) + or resource.get('document_id') + or metadata.get('document_id') ) return dataset_id, remote_document_id diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index 3227bc39..af193887 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -203,13 +203,19 @@ class IntegrationApiService: from app import db from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument + normalized_dataset_id = str(dataset_id or '').strip() + normalized_remote_document_id = str(remote_document_id or '').strip() + if not normalized_dataset_id or not normalized_remote_document_id: + return None + 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, + KbDifySyncRecord.dataset_id == normalized_dataset_id, + KbDifySyncRecord.remote_document_id == normalized_remote_document_id, ) .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) .first() @@ -236,13 +242,17 @@ class IntegrationApiService: 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, + 'dataset_id': normalized_dataset_id, + 'remote_document_id': normalized_remote_document_id, + 'version_id': version.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}' + source_download_url = ( + f'{base_url}/api/integration/files/{document.id}/download' + f'?kind=source&version_id={version.id}&token={token}' + ) return { "source_download_url": source_download_url, @@ -266,7 +276,7 @@ class IntegrationApiService: base_url = IntegrationApiService.get_base_url() api_key = IntegrationApiService.get_api_key() if not base_url or not api_key: - return None + return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id) url = f"{base_url}/api/integration/dify-file" headers = {"X-Integration-Key": api_key} diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index 36285771..e28f217a 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -177,6 +177,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | remote_document_id = None remote_document_name = None + upload_name = version.source_file_name or document.title if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash: try: payload = service.get_document( @@ -184,23 +185,23 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | document_id=existing_record.remote_document_id, ) remote_document_id = payload.get('id') or existing_record.remote_document_id - remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title + remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name except KbDifySyncError as exc: if not _is_remote_document_missing(str(exc)): raise payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name elif existing_record and existing_record.dataset_id == dataset_id: try: payload = service.update_document_by_text( dataset_id=dataset_id, document_id=existing_record.remote_document_id, - name=document.title, + name=upload_name, text=text, ) except KbDifySyncError as exc: @@ -208,19 +209,19 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | raise payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name else: payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name if not remote_document_id: raise KbDifySyncError('Dify 未返回远端文档 ID') diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 2cd2b85e..cd091f65 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -311,18 +311,57 @@ const findFirstByKeys = (payload: any, keyCandidates: string[]): string => { return ''; }; +const findDirectByKeys = (payloads: any[], keyCandidates: string[]): string => { + for (const payload of payloads) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue; + for (const key of keyCandidates) { + const value = payload?.[key]; + if (value != null && String(value).trim()) { + return String(value).trim(); + } + } + } + return ''; +}; + const getResourceIds = (item: any) => { + const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata) + ? item.metadata + : null; const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']); - const remoteDocumentId = findFirstByKeys(item, [ + const remoteDocumentId = findDirectByKeys([item, metadata], [ 'remote_document_id', 'dify_document_id', - 'document_id', - 'doc_id', 'source_document_id', - ]); + 'doc_id', + ]) || findFirstByKeys(item, [ + 'remote_document_id', + 'dify_document_id', + 'source_document_id', + 'doc_id', + ]) || findDirectByKeys([item, metadata], ['document_id']); return { datasetId, remoteDocumentId }; }; +const canPreviewSourceLink = (link: Partial | null | undefined) => { + if (!link) return false; + return Boolean(link.url || (link.datasetId && link.remoteDocumentId)); +}; + +const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => { + const normalizedName = String(name || '').trim(); + const normalizedDatasetId = String(datasetId || '').trim(); + const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim(); + const normalizedUrl = String(url || '').split('?')[0]; + if (normalizedDatasetId && normalizedRemoteDocumentId) { + return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`; + } + if (looksLikeFileName(normalizedName)) { + return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName; + } + return `${normalizedName}|${normalizedUrl}`; +}; + const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim()); const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase()); @@ -405,8 +444,8 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { const forceName = item?.source_filename || item?.document_name || item?.title; const forceUrl = normalizeUrl(item?.source_download_url || item?.url || ''); - if (forceName) { - const key = forceName; + if (forceName && (forceUrl || (datasetId && remoteDocumentId))) { + const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl); mergeSourceLink(key, { name: forceName, ...(forceUrl ? { url: forceUrl } : {}), @@ -442,8 +481,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { // 根据配置决定是否显示 MD 文件 if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue; - // Deduplicate by name if it looks like a filename, else by name + base URL - const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`; + const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url); mergeSourceLink(key, { name, url, @@ -452,7 +490,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { }); } } - const links = Array.from(map.values()); + const links = Array.from(map.values()).filter((link) => canPreviewSourceLink(link)); // 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示 // const preferred = links.filter((l) => isPreferredSourceLink(l.url)); // return preferred.length > 0 ? preferred : links; @@ -481,18 +519,19 @@ const getMessageLinks = (msg: any): SourceFileLink[] => { }); }; for (const link of links) { + if (!canPreviewSourceLink(link)) continue; const linkUrl = link.url || ''; if (linkUrl && isChunkLikeLink(linkUrl)) continue; // 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。 if (isNoisySourceName(link.name)) continue; if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue; if (isMarkdownFileName(link.name)) { - const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`; + const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl); mergeMessageLink(key, link); continue; } if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue; - const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`; + const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl); mergeMessageLink(key, link); } }; @@ -561,33 +600,32 @@ const filePreviewVisible = ref(false); const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null); const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => { - if (file.url) { - return { - name: file.name, - url: file.url, - actualExt: file.actualExt, - }; + if (file.datasetId && file.remoteDocumentId) { + const data = await resolveChatSourceFile({ + agent_id: agentId, + dataset_id: file.datasetId, + remote_document_id: file.remoteDocumentId, + }); + + const resolvedUrl = normalizeUrl(data?.source_download_url || ''); + if (resolvedUrl) { + return { + ...file, + url: resolvedUrl, + name: data?.source_filename || file.name, + actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined, + }; + } } - if (!file.datasetId || !file.remoteDocumentId) { + + if (!file.url) { throw new Error('当前源文件暂未返回可预览链接'); } - const data = await resolveChatSourceFile({ - agent_id: agentId, - dataset_id: file.datasetId, - remote_document_id: file.remoteDocumentId, - }); - - const resolvedUrl = normalizeUrl(data?.source_download_url || ''); - if (!resolvedUrl) { - throw new Error('未查询到源文件下载地址'); - } - return { - ...file, - url: resolvedUrl, - name: data?.source_filename || file.name, - actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined, + name: file.name, + url: file.url, + actualExt: file.actualExt, }; };