Merge branch 'dev' into test

This commit is contained in:
runny committed 2026-05-30 15:27:33 +08:00
commit 55ccb16bb2
3 files changed
+123 -14

No files matched your search

+113 -11
View File
@@ -15,7 +15,7 @@ import uuid
from urllib.parse import urlparse
import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
from sqlalchemy import func, desc
from openpyxl import load_workbook
from app.services.dify import DifyService
@@ -73,7 +73,6 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return True
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
from flask import request, has_request_context
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
@@ -172,10 +171,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
def _build_headers(raw_url: str):
next_headers = {}
if not api_key:
current_app.logger.info(f"[_build_headers] api_key is missing")
return next_headers
is_trusted = False
if base_url and raw_url.startswith(base_url):
is_trusted = True
@@ -185,7 +181,6 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
try:
parsed = urlparse(raw_url)
host = (parsed.hostname or "").strip().lower()
from flask import request, has_request_context
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
@@ -197,7 +192,15 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
if is_trusted:
next_headers['X-Integration-Key'] = api_key
if api_key:
next_headers['X-Integration-Key'] = api_key
if has_request_context():
auth_header = (request.headers.get('Authorization') or '').strip()
cookie_header = (request.headers.get('Cookie') or '').strip()
if auth_header:
next_headers['Authorization'] = auth_header
if cookie_header:
next_headers['Cookie'] = cookie_header
return next_headers
@@ -281,6 +284,71 @@ def _extract_placeholder_text(content: bytes) -> str:
return first_line
return ''
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
"""
对于 Dify 中以 text_model / txt 形式存储的文档,
直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
service = KbDifySyncService()
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
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_ext = str(upload_info.get('extension') or '').strip().lower()
doc_form = str(document_payload.get('doc_form') or '').strip().lower()
mime_type = str(upload_info.get('mime_type') or '').strip().lower()
is_text_doc = (
source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt')
or doc_form == 'text_model'
or mime_type.startswith('text/')
)
if not is_text_doc:
return None
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text = str(row.get('content') or '').strip()
if text:
parts.append(text)
return '\n\n'.join(parts).strip() or None
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
e,
)
return None
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
@@ -971,16 +1039,49 @@ def resolve_source_file():
if not payload:
return jsonify({'error': 'source file mapping not found'}), 404
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,
'remote_document_id': remote_document_id,
'source_filename': payload.get('source_filename'),
'source_ext': payload.get('source_ext'),
'source_download_url': payload.get('source_download_url'),
'source_ext': source_ext,
'source_download_url': source_download_url,
'download_url_expires_at': payload.get('download_url_expires_at'),
})
@chat_bp.route('/source-file-text', methods=['GET'])
@require_agent_permission
def source_file_text():
dataset_id = (request.args.get('dataset_id') or '').strip()
remote_document_id = (request.args.get('remote_document_id') or '').strip()
if not dataset_id or not remote_document_id:
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
text = _fetch_dify_text_document(dataset_id, remote_document_id)
if not text:
return jsonify({'error': 'failed to resolve text source file'}), 404
filename = f'{remote_document_id}.txt'
return Response(
text,
status=200,
mimetype='text/plain; charset=utf-8',
headers={
'Content-Disposition': f'inline; filename="{filename}"',
'Cache-Control': 'no-store',
},
)
@chat_bp.route('/preview-excel', methods=['GET'])
@require_agent_permission
def preview_excel():
@@ -1095,7 +1196,8 @@ def preview_text():
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext
explicit_ext = (request.args.get('ext') or '').strip().lower()
ext = explicit_ext or url_path_ext or name_ext
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
if ext and ext not in allowed:
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
@@ -20,6 +20,7 @@ import '@vue-office/excel/lib/index.css';
interface PreviewFile {
name: string;
url: string;
actualExt?: string;
}
interface ExcelPreviewData {
@@ -69,6 +70,8 @@ const getExt = (raw: string) => {
};
const ext = computed(() => {
const actual = getExt(props.file?.actualExt || '');
if (actual) return actual;
// Display name extension has higher priority than URL.
const byName = getExt(props.file?.name || '');
if (byName) return byName;
@@ -385,6 +388,7 @@ const loadContent = async () => {
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
ext: ext.value || '',
});
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
headers: props.authHeaders || {},
+6 -3
View File
@@ -1,4 +1,4 @@


<script setup lang="ts">
/**
@@ -186,6 +186,7 @@ interface SourceFileLink {
url?: string;
datasetId?: string;
remoteDocumentId?: string;
actualExt?: string;
}
// 源文件展示配置(来自 config.ts)
@@ -541,13 +542,14 @@ const shouldShowThinkingBubble = computed(() => {
});
const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string } | null>(null);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string }> => {
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) {
@@ -576,6 +578,7 @@ const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string;
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
};