379 lines
15 KiB
Python
379 lines
15 KiB
Python
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from pydantic import BaseModel
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from fastapi.responses import FileResponse
|
|
from sqlalchemy import func
|
|
from sqlalchemy.orm import Session, joinedload
|
|
|
|
from app.config import get_settings
|
|
from app.database import get_db
|
|
from app.deps import require_integration_key
|
|
from app.models import DifySyncRecord, Document, DocumentVersion, Group
|
|
from app.security import create_integration_download_token, decode_integration_download_token
|
|
from app.serializers import current_version, serialize_group
|
|
from app.time_utils import utc_now
|
|
|
|
|
|
router = APIRouter(prefix="/integration", tags=["integration"])
|
|
settings = get_settings()
|
|
|
|
|
|
class DifyResolveItem(BaseModel):
|
|
remote_document_id: str
|
|
dataset_id: str | None = None
|
|
|
|
|
|
class DifyResolveRequest(BaseModel):
|
|
items: list[DifyResolveItem]
|
|
|
|
|
|
def _document_query(db: Session):
|
|
return (
|
|
db.query(Document)
|
|
.options(
|
|
joinedload(Document.group).joinedload(Group.department),
|
|
joinedload(Document.versions).joinedload(DocumentVersion.sync_records),
|
|
)
|
|
.filter(Document.is_deleted.is_(False))
|
|
)
|
|
|
|
|
|
def _knowledge_base_summary(group: Group, *, document_count: int) -> dict:
|
|
payload = serialize_group(group, document_count=document_count)
|
|
payload["knowledge_base_id"] = payload["id"]
|
|
return payload
|
|
|
|
|
|
def _integration_document_payload(
|
|
document: Document,
|
|
*,
|
|
version: DocumentVersion | None = None,
|
|
sync_record: DifySyncRecord | None = None,
|
|
) -> dict:
|
|
version = version or current_version(document)
|
|
if version is None:
|
|
raise HTTPException(status_code=404, detail="No current version found.")
|
|
sync_record = sync_record or (version.sync_records[0] if version.sync_records else None)
|
|
try:
|
|
source_token, source_expires_at = create_integration_download_token(
|
|
file_id=document.id,
|
|
version_id=version.id,
|
|
kind="source",
|
|
)
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
md_token = None
|
|
md_expires_at = None
|
|
if version.md_path:
|
|
try:
|
|
md_token, md_expires_at = create_integration_download_token(
|
|
file_id=document.id,
|
|
version_id=version.id,
|
|
kind="md",
|
|
)
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
return {
|
|
"queried_at": utc_now().isoformat(),
|
|
"document_id": document.id,
|
|
"knowledge_base": {
|
|
"id": document.group.id,
|
|
"name": document.group.name,
|
|
"department_id": document.group.department_id,
|
|
"department_name": document.group.department.name if document.group.department else None,
|
|
"dify_dataset_id": document.group.dify_dataset_id,
|
|
},
|
|
"title": document.title,
|
|
"source_filename": version.source_filename,
|
|
"source_ext": version.source_ext,
|
|
"file_name": version.source_filename,
|
|
"version_id": version.id,
|
|
"version_no": version.version_no,
|
|
"convert_status": version.convert_status,
|
|
"sync_status": version.sync_status,
|
|
"uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None,
|
|
"converted_at": version.converted_at.isoformat() if version.converted_at else None,
|
|
"download_url_expires_at": source_expires_at.isoformat(),
|
|
"source_download_url": (
|
|
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
|
|
f"?version_id={version.id}&kind=source&token={source_token}"
|
|
),
|
|
"markdown_download_url": (
|
|
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
|
|
f"?version_id={version.id}&kind=md&token={md_token}"
|
|
if version.md_path and md_token
|
|
else None
|
|
),
|
|
"markdown_download_url_expires_at": md_expires_at.isoformat() if md_expires_at else None,
|
|
"markdown_public_url": version.md_public_url,
|
|
"dify": {
|
|
"dataset_id": sync_record.dataset_id if sync_record else document.group.dify_dataset_id,
|
|
"remote_document_id": sync_record.remote_document_id if sync_record else None,
|
|
"status": sync_record.status if sync_record else None,
|
|
"last_indexing_status": sync_record.last_indexing_status if sync_record else None,
|
|
"last_synced_at": sync_record.last_synced_at.isoformat() if sync_record and sync_record.last_synced_at else None,
|
|
},
|
|
}
|
|
|
|
|
|
@router.get("/knowledge-bases")
|
|
def list_knowledge_bases(
|
|
department_id: int | None = None,
|
|
q: str | None = None,
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
document_counts = (
|
|
db.query(Document.group_id.label("group_id"), func.count(Document.id).label("document_count"))
|
|
.filter(Document.is_deleted.is_(False))
|
|
.group_by(Document.group_id)
|
|
.subquery()
|
|
)
|
|
query = (
|
|
db.query(Group, func.coalesce(document_counts.c.document_count, 0).label("document_count"))
|
|
.outerjoin(document_counts, document_counts.c.group_id == Group.id)
|
|
.options(joinedload(Group.department))
|
|
.order_by(Group.name.asc())
|
|
)
|
|
if department_id is not None:
|
|
query = query.filter(Group.department_id == department_id)
|
|
if q:
|
|
query = query.filter(Group.name.ilike(f"%{q.strip()}%"))
|
|
rows = query.all()
|
|
return {"data": [_knowledge_base_summary(group, document_count=document_count) for group, document_count in rows]}
|
|
|
|
|
|
@router.get("/files")
|
|
def list_files(
|
|
knowledge_base_id: int | None = None,
|
|
department_id: int | None = None,
|
|
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
query = _document_query(db)
|
|
if knowledge_base_id is not None:
|
|
query = query.filter(Document.group_id == knowledge_base_id)
|
|
if department_id is not None:
|
|
query = query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
|
documents = query.order_by(Document.updated_at.desc()).all()
|
|
normalized = file_name.strip().lower() if file_name else None
|
|
|
|
payload: list[dict] = []
|
|
for document in documents:
|
|
version = current_version(document)
|
|
if version is None:
|
|
continue
|
|
if normalized and normalized not in version.source_filename.lower() and normalized not in document.title.lower():
|
|
continue
|
|
payload.append(_integration_document_payload(document))
|
|
return {"data": payload}
|
|
|
|
|
|
@router.get("/knowledge-bases/{knowledge_base_id}/files")
|
|
def list_files_for_knowledge_base(
|
|
knowledge_base_id: int,
|
|
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
return list_files(
|
|
knowledge_base_id=knowledge_base_id,
|
|
file_name=file_name,
|
|
db=db,
|
|
_="integration",
|
|
)
|
|
|
|
|
|
@router.get("/files/{file_id}")
|
|
def get_file_detail(
|
|
file_id: int,
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
document = _document_query(db).filter(Document.id == file_id).first()
|
|
if not document:
|
|
raise HTTPException(status_code=404, detail="Document not found.")
|
|
return _integration_document_payload(document)
|
|
|
|
|
|
@router.get("/dify-file")
|
|
def get_file_detail_by_dify(
|
|
remote_document_id: str = Query(..., description="Dify document id."),
|
|
dataset_id: str | None = Query(default=None, description="Optional Dify dataset id."),
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
record_query = (
|
|
db.query(DifySyncRecord)
|
|
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
|
|
.join(Document, Document.id == DocumentVersion.document_id)
|
|
.options(
|
|
joinedload(DifySyncRecord.version)
|
|
.joinedload(DocumentVersion.document)
|
|
.joinedload(Document.group)
|
|
.joinedload(Group.department),
|
|
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
|
|
)
|
|
.filter(
|
|
Document.is_deleted.is_(False),
|
|
DifySyncRecord.remote_document_id == remote_document_id,
|
|
)
|
|
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
|
)
|
|
if dataset_id:
|
|
record_query = record_query.filter(DifySyncRecord.dataset_id == dataset_id)
|
|
record = record_query.first()
|
|
if not record or not record.version or not record.version.document:
|
|
raise HTTPException(status_code=404, detail="No local file mapping found for the given Dify document.")
|
|
return _integration_document_payload(record.version.document, version=record.version, sync_record=record)
|
|
|
|
|
|
@router.post("/dify-files/resolve")
|
|
def resolve_files_by_dify(
|
|
payload: DifyResolveRequest,
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
if not payload.items:
|
|
return {"data": []}
|
|
|
|
remote_ids = sorted({item.remote_document_id for item in payload.items if item.remote_document_id})
|
|
dataset_ids = sorted({item.dataset_id for item in payload.items if item.dataset_id})
|
|
|
|
record_query = (
|
|
db.query(DifySyncRecord)
|
|
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
|
|
.join(Document, Document.id == DocumentVersion.document_id)
|
|
.options(
|
|
joinedload(DifySyncRecord.version)
|
|
.joinedload(DocumentVersion.document)
|
|
.joinedload(Document.group)
|
|
.joinedload(Group.department),
|
|
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
|
|
)
|
|
.filter(
|
|
Document.is_deleted.is_(False),
|
|
DifySyncRecord.remote_document_id.in_(remote_ids),
|
|
)
|
|
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
|
)
|
|
if dataset_ids:
|
|
record_query = record_query.filter(
|
|
(DifySyncRecord.dataset_id.in_(dataset_ids)) | (DifySyncRecord.dataset_id.is_(None))
|
|
)
|
|
records = record_query.all()
|
|
|
|
records_by_key: dict[tuple[str | None, str], DifySyncRecord] = {}
|
|
records_by_remote: dict[str, DifySyncRecord] = {}
|
|
for record in records:
|
|
key = (record.dataset_id, record.remote_document_id)
|
|
records_by_key.setdefault(key, record)
|
|
records_by_remote.setdefault(record.remote_document_id, record)
|
|
|
|
data: list[dict] = []
|
|
for item in payload.items:
|
|
record = records_by_key.get((item.dataset_id, item.remote_document_id))
|
|
if record is None and item.dataset_id is None:
|
|
record = records_by_remote.get(item.remote_document_id)
|
|
data.append(
|
|
{
|
|
"request": {
|
|
"dataset_id": item.dataset_id,
|
|
"remote_document_id": item.remote_document_id,
|
|
},
|
|
"found": bool(record and record.version and record.version.document),
|
|
"document": (
|
|
_integration_document_payload(record.version.document, version=record.version, sync_record=record)
|
|
if record and record.version and record.version.document
|
|
else None
|
|
),
|
|
}
|
|
)
|
|
return {"data": data}
|
|
|
|
|
|
@router.get("/files/{file_id}/download")
|
|
def download_file(
|
|
file_id: int,
|
|
kind: str = Query(default="md"),
|
|
db: Session = Depends(get_db),
|
|
_: str = Depends(require_integration_key),
|
|
):
|
|
document = _document_query(db).filter(Document.id == file_id).first()
|
|
if not document:
|
|
raise HTTPException(status_code=404, detail="Document not found.")
|
|
version = current_version(document)
|
|
if not version:
|
|
raise HTTPException(status_code=404, detail="No version found.")
|
|
|
|
if kind == "source":
|
|
path = Path(version.source_path)
|
|
filename = version.source_filename
|
|
else:
|
|
if not version.md_path:
|
|
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
|
path = Path(version.md_path)
|
|
filename = f"{document.title}.md"
|
|
|
|
if not path.exists():
|
|
raise HTTPException(status_code=404, detail="File missing on disk.")
|
|
|
|
return FileResponse(path, filename=filename)
|
|
|
|
|
|
@router.get("/download")
|
|
def download_file_from_signed_url(
|
|
file_id: int | None = Query(default=None),
|
|
version_id: int | None = Query(default=None),
|
|
kind: str = Query(default="source"),
|
|
token: str = Query(...),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
try:
|
|
payload = decode_integration_download_token(token)
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
if not payload:
|
|
raise HTTPException(status_code=401, detail="Invalid or expired download token.")
|
|
expected_kind = payload.get("kind")
|
|
expected_version_id = payload.get("version_id")
|
|
expected_file_id = payload.get("file_id")
|
|
if expected_kind != kind:
|
|
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
|
if expected_version_id is not None:
|
|
if version_id != int(expected_version_id):
|
|
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
|
version = db.query(DocumentVersion).join(Document).filter(
|
|
DocumentVersion.id == version_id,
|
|
Document.is_deleted.is_(False),
|
|
).first()
|
|
if not version or not version.document:
|
|
raise HTTPException(status_code=404, detail="Version not found.")
|
|
document = version.document
|
|
else:
|
|
if file_id is None or expected_file_id is None or int(expected_file_id) != file_id:
|
|
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
|
document = _document_query(db).filter(Document.id == file_id).first()
|
|
if not document:
|
|
raise HTTPException(status_code=404, detail="Document not found.")
|
|
version = current_version(document)
|
|
if not version:
|
|
raise HTTPException(status_code=404, detail="No version found.")
|
|
|
|
if kind == "source":
|
|
path = Path(version.source_path)
|
|
filename = version.source_filename
|
|
else:
|
|
if not version.md_path:
|
|
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
|
path = Path(version.md_path)
|
|
filename = f"{document.title}.md"
|
|
|
|
if not path.exists():
|
|
raise HTTPException(status_code=404, detail="File missing on disk.")
|
|
return FileResponse(path, filename=filename)
|