原始文件气泡映射错误 + 多版本下载错版本
This commit is contained in:
1 parent
f877f61efd
commit
854bc8e4db
7 files changed
+194
-71
No files matched your search
@@ -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()
|
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:
|
if log and log.retriever_resources:
|
||||||
for r in log.retriever_resources:
|
for r in log.retriever_resources:
|
||||||
|
if not isinstance(r, dict):
|
||||||
|
continue
|
||||||
source_url = str(r.get('source_download_url') or '')
|
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]):
|
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()
|
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
|
||||||
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()
|
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:
|
if dataset_id and remote_document_id:
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -1411,12 +1414,6 @@ def resolve_source_file():
|
|||||||
|
|
||||||
source_ext = str(payload.get('source_ext') or '').strip().lower()
|
source_ext = str(payload.get('source_ext') or '').strip().lower()
|
||||||
source_download_url = payload.get('source_download_url')
|
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({
|
return jsonify({
|
||||||
'dataset_id': dataset_id,
|
'dataset_id': dataset_id,
|
||||||
@@ -1649,7 +1646,6 @@ def preview_file_raw():
|
|||||||
# 避免在服务端走旧版转换链路导致长时间卡住。
|
# 避免在服务端走旧版转换链路导致长时间卡住。
|
||||||
needs_pdf_conversion = (
|
needs_pdf_conversion = (
|
||||||
request.args.get('download') != '1'
|
request.args.get('download') != '1'
|
||||||
and original_ext in ('doc', 'ppt', 'pptx')
|
|
||||||
and ext in ('doc', 'ppt', 'pptx')
|
and ext in ('doc', 'ppt', 'pptx')
|
||||||
)
|
)
|
||||||
if needs_pdf_conversion:
|
if needs_pdf_conversion:
|
||||||
|
|||||||
@@ -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
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||||
integration_bp = Blueprint('integration', __name__)
|
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():
|
def _require_integration_key():
|
||||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||||
@@ -24,15 +113,8 @@ def _require_integration_key():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
token = request.args.get('token')
|
token = request.args.get('token')
|
||||||
if token:
|
if token and _decode_integration_token(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
|
return None
|
||||||
except Exception as e:
|
|
||||||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
|
||||||
pass
|
|
||||||
|
|
||||||
raise UnauthorizedError('Unauthorized')
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
|
||||||
@@ -57,9 +139,8 @@ def _serialize_integration_document(document: KbDocument, *, version: KbDocument
|
|||||||
if not version:
|
if not version:
|
||||||
abort(404, description='No current version found.')
|
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))
|
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 = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||||
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
|
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
|
||||||
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
|
|
||||||
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}}
|
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:
|
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||||
@@ -189,10 +270,9 @@ def resolve_files_by_dify():
|
|||||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||||
def download_file(file_id: int):
|
def download_file(file_id: int):
|
||||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
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:
|
if not document:
|
||||||
raise NotFoundError('Document not found.')
|
raise NotFoundError('Document not found.')
|
||||||
version = _current_version(document)
|
|
||||||
if not version:
|
if not version:
|
||||||
raise NotFoundError('No version found.')
|
raise NotFoundError('No version found.')
|
||||||
path, filename = _resolve_download_path(version, kind)
|
path, filename = _resolve_download_path(version, kind)
|
||||||
|
|||||||
@@ -26,12 +26,9 @@ def _safe_upload_filename(raw_filename: str | None) -> str:
|
|||||||
original_name = Path(raw_filename or '').name.strip()
|
original_name = Path(raw_filename or '').name.strip()
|
||||||
if not original_name:
|
if not original_name:
|
||||||
return 'uploaded_file'
|
return 'uploaded_file'
|
||||||
original_path = Path(original_name)
|
import re
|
||||||
safe_stem = secure_filename(original_path.stem)
|
safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name)
|
||||||
suffix = original_path.suffix.lower()
|
return safe_name or 'uploaded_file'
|
||||||
if not safe_stem:
|
|
||||||
safe_stem = 'uploaded_file'
|
|
||||||
return f'{safe_stem}{suffix}'
|
|
||||||
|
|
||||||
def _require_user():
|
def _require_user():
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
|
|||||||
@@ -867,22 +867,23 @@ class DifyService:
|
|||||||
remote_document_id = (
|
remote_document_id = (
|
||||||
resource.get('remote_document_id')
|
resource.get('remote_document_id')
|
||||||
or resource.get('dify_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 resource.get('doc_id')
|
||||||
or metadata.get('remote_document_id')
|
or metadata.get('remote_document_id')
|
||||||
or metadata.get('dify_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 metadata.get('doc_id')
|
||||||
or DifyService._find_first_by_keys(
|
or DifyService._find_first_by_keys(
|
||||||
resource,
|
resource,
|
||||||
[
|
[
|
||||||
'remote_document_id',
|
'remote_document_id',
|
||||||
'dify_document_id',
|
'dify_document_id',
|
||||||
'document_id',
|
|
||||||
'doc_id',
|
|
||||||
'source_document_id',
|
'source_document_id',
|
||||||
|
'doc_id',
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
or resource.get('document_id')
|
||||||
|
or metadata.get('document_id')
|
||||||
)
|
)
|
||||||
|
|
||||||
return dataset_id, remote_document_id
|
return dataset_id, remote_document_id
|
||||||
|
|||||||
@@ -203,13 +203,19 @@ class IntegrationApiService:
|
|||||||
from app import db
|
from app import db
|
||||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
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 = (
|
record = (
|
||||||
db.session.query(KbDifySyncRecord)
|
db.session.query(KbDifySyncRecord)
|
||||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||||
.filter(
|
.filter(
|
||||||
KbDocument.is_deleted.is_(False),
|
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())
|
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
.first()
|
.first()
|
||||||
@@ -236,13 +242,17 @@ class IntegrationApiService:
|
|||||||
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||||
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
|
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
|
||||||
payload = {
|
payload = {
|
||||||
'dataset_id': 'local',
|
'dataset_id': normalized_dataset_id,
|
||||||
'remote_document_id': remote_document_id,
|
'remote_document_id': normalized_remote_document_id,
|
||||||
|
'version_id': version.id,
|
||||||
'exp': exp
|
'exp': exp
|
||||||
}
|
}
|
||||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
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 {
|
return {
|
||||||
"source_download_url": source_download_url,
|
"source_download_url": source_download_url,
|
||||||
@@ -266,7 +276,7 @@ class IntegrationApiService:
|
|||||||
base_url = IntegrationApiService.get_base_url()
|
base_url = IntegrationApiService.get_base_url()
|
||||||
api_key = IntegrationApiService.get_api_key()
|
api_key = IntegrationApiService.get_api_key()
|
||||||
if not base_url or not 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"
|
url = f"{base_url}/api/integration/dify-file"
|
||||||
headers = {"X-Integration-Key": api_key}
|
headers = {"X-Integration-Key": api_key}
|
||||||
|
|||||||
@@ -177,6 +177,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
|||||||
|
|
||||||
remote_document_id = None
|
remote_document_id = None
|
||||||
remote_document_name = 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:
|
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
|
||||||
try:
|
try:
|
||||||
payload = service.get_document(
|
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,
|
document_id=existing_record.remote_document_id,
|
||||||
)
|
)
|
||||||
remote_document_id = payload.get('id') or 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:
|
except KbDifySyncError as exc:
|
||||||
if not _is_remote_document_missing(str(exc)):
|
if not _is_remote_document_missing(str(exc)):
|
||||||
raise
|
raise
|
||||||
payload = service.create_document_by_text(
|
payload = service.create_document_by_text(
|
||||||
dataset_id=dataset_id,
|
dataset_id=dataset_id,
|
||||||
name=document.title,
|
name=upload_name,
|
||||||
text=text,
|
text=text,
|
||||||
)
|
)
|
||||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
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:
|
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||||
try:
|
try:
|
||||||
payload = service.update_document_by_text(
|
payload = service.update_document_by_text(
|
||||||
dataset_id=dataset_id,
|
dataset_id=dataset_id,
|
||||||
document_id=existing_record.remote_document_id,
|
document_id=existing_record.remote_document_id,
|
||||||
name=document.title,
|
name=upload_name,
|
||||||
text=text,
|
text=text,
|
||||||
)
|
)
|
||||||
except KbDifySyncError as exc:
|
except KbDifySyncError as exc:
|
||||||
@@ -208,19 +209,19 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
|||||||
raise
|
raise
|
||||||
payload = service.create_document_by_text(
|
payload = service.create_document_by_text(
|
||||||
dataset_id=dataset_id,
|
dataset_id=dataset_id,
|
||||||
name=document.title,
|
name=upload_name,
|
||||||
text=text,
|
text=text,
|
||||||
)
|
)
|
||||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
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:
|
else:
|
||||||
payload = service.create_document_by_text(
|
payload = service.create_document_by_text(
|
||||||
dataset_id=dataset_id,
|
dataset_id=dataset_id,
|
||||||
name=document.title,
|
name=upload_name,
|
||||||
text=text,
|
text=text,
|
||||||
)
|
)
|
||||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
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:
|
if not remote_document_id:
|
||||||
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
||||||
|
|||||||
@@ -311,18 +311,57 @@ const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
|
|||||||
return '';
|
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 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 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',
|
'remote_document_id',
|
||||||
'dify_document_id',
|
'dify_document_id',
|
||||||
'document_id',
|
|
||||||
'doc_id',
|
|
||||||
'source_document_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 };
|
return { datasetId, remoteDocumentId };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const canPreviewSourceLink = (link: Partial<SourceFileLink> | 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 isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
|
||||||
|
|
||||||
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
|
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 forceName = item?.source_filename || item?.document_name || item?.title;
|
||||||
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
|
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
|
||||||
|
|
||||||
if (forceName) {
|
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
|
||||||
const key = forceName;
|
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
|
||||||
mergeSourceLink(key, {
|
mergeSourceLink(key, {
|
||||||
name: forceName,
|
name: forceName,
|
||||||
...(forceUrl ? { url: forceUrl } : {}),
|
...(forceUrl ? { url: forceUrl } : {}),
|
||||||
@@ -442,8 +481,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
|||||||
// 根据配置决定是否显示 MD 文件
|
// 根据配置决定是否显示 MD 文件
|
||||||
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
|
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
|
||||||
|
|
||||||
// Deduplicate by name if it looks like a filename, else by name + base URL
|
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
|
||||||
const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`;
|
|
||||||
mergeSourceLink(key, {
|
mergeSourceLink(key, {
|
||||||
name,
|
name,
|
||||||
url,
|
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 的过滤,让所有解析出来的气泡都能显示
|
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
|
||||||
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||||
// return preferred.length > 0 ? preferred : links;
|
// return preferred.length > 0 ? preferred : links;
|
||||||
@@ -481,18 +519,19 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
for (const link of links) {
|
for (const link of links) {
|
||||||
|
if (!canPreviewSourceLink(link)) continue;
|
||||||
const linkUrl = link.url || '';
|
const linkUrl = link.url || '';
|
||||||
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
|
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
|
||||||
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
|
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
|
||||||
if (isNoisySourceName(link.name)) continue;
|
if (isNoisySourceName(link.name)) continue;
|
||||||
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
|
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
|
||||||
if (isMarkdownFileName(link.name)) {
|
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);
|
mergeMessageLink(key, link);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) 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);
|
mergeMessageLink(key, link);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -561,17 +600,7 @@ const filePreviewVisible = ref(false);
|
|||||||
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
|
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
|
||||||
|
|
||||||
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
|
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
|
||||||
if (file.url) {
|
if (file.datasetId && file.remoteDocumentId) {
|
||||||
return {
|
|
||||||
name: file.name,
|
|
||||||
url: file.url,
|
|
||||||
actualExt: file.actualExt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (!file.datasetId || !file.remoteDocumentId) {
|
|
||||||
throw new Error('当前源文件暂未返回可预览链接');
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await resolveChatSourceFile({
|
const data = await resolveChatSourceFile({
|
||||||
agent_id: agentId,
|
agent_id: agentId,
|
||||||
dataset_id: file.datasetId,
|
dataset_id: file.datasetId,
|
||||||
@@ -579,16 +608,25 @@ const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string;
|
|||||||
});
|
});
|
||||||
|
|
||||||
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
|
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
|
||||||
if (!resolvedUrl) {
|
if (resolvedUrl) {
|
||||||
throw new Error('未查询到源文件下载地址');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...file,
|
...file,
|
||||||
url: resolvedUrl,
|
url: resolvedUrl,
|
||||||
name: data?.source_filename || file.name,
|
name: data?.source_filename || file.name,
|
||||||
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
|
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!file.url) {
|
||||||
|
throw new Error('当前源文件暂未返回可预览链接');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: file.name,
|
||||||
|
url: file.url,
|
||||||
|
actualExt: file.actualExt,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const openPreview = async (file: SourceFileLink) => {
|
const openPreview = async (file: SourceFileLink) => {
|
||||||
|
|||||||
Reference in new issue
Block a user