原始文件气泡映射错误 + 多版本下载错版本
This commit is contained in:
1 parent
f877f61efd
commit
854bc8e4db
7 files changed
+203
-80
No files matched your search
@@ -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/<int:file_id>/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)
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
Reference in new issue
Block a user