feat(api,ai): #72 OpenAPI 3.1 enrichie + fiabilisation de l'outil AI UI
CI / lint (push) Successful in 55s
CI / security (push) Successful in 37s
CI / test (push) Successful in 1m19s
CI / build (push) Successful in 34s
CI / e2e (push) Successful in 10m27s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
CI / lint (push) Successful in 55s
CI / security (push) Successful in 37s
CI / test (push) Successful in 1m19s
CI / build (push) Successful in 34s
CI / e2e (push) Successful in 10m27s
Desktop Build / build-windows (push) Canceled after 0s
Desktop Build / build-linux (push) Canceled after 0s
API (#72): - backend/openapi_docs.py: 18 tags documentes, assignation auto par prefixe, securite bearerAuth/cookieAuth, erreurs 401/403/404/422/500, exemples, page /api autonome (liens /docs, /redoc, /openapi.json) - backend/schemas.py: response_model Pydantic pour ~35 endpoints sans modele - main.py: FastAPI enrichi + override app.openapi; routes /api et /api/ - ai_routes/bookslm_routes: response_model + doc SSE - frontend: entree 'API' du menu (i18n FR/EN) - tests/test_openapi.py (58 tests) AI UI: - BooksLM: requetes authentifiees (AuthManager), parsing SSE {token}/error, message utilisateur correct (plus le placeholder vide), barre de contexte - AI Editor: Ctrl/Cmd+J lie une seule fois, libelles i18n, modale de reecriture accessible a la place de window.prompt() - tests/frontend/ai.test.mjs (7 tests) + CI
This commit is contained in:
@@ -25,12 +25,13 @@ from backend.ai import (
|
||||
ai_summarize,
|
||||
ai_translate,
|
||||
)
|
||||
from backend.schemas import AIStatusResponse
|
||||
|
||||
logger = logging.getLogger("obsigate.ai_routes")
|
||||
router = APIRouter(prefix="/api/ai", tags=["AI"])
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
@router.get("/status", response_model=AIStatusResponse)
|
||||
async def api_status():
|
||||
"""Check if AI is configured and which providers are available.
|
||||
|
||||
|
||||
@@ -165,6 +165,8 @@ def collect_directory_context(vault_path: Path, directory: str) -> dict[str, Any
|
||||
"total_chars": total_chars,
|
||||
"file_count": len(collected),
|
||||
"directory_tree": dir_tree,
|
||||
"max_total_chars": BOOKSLM_MAX_TOTAL_CHARS,
|
||||
"max_files": BOOKSLM_MAX_FILES,
|
||||
}
|
||||
|
||||
# Store in cache
|
||||
|
||||
@@ -11,6 +11,7 @@ from pydantic import BaseModel, Field
|
||||
from backend.auth.middleware import check_vault_access, require_auth
|
||||
from backend.bookslm import build_system_prompt, collect_directory_context
|
||||
from backend.indexer import get_vault_data
|
||||
from backend.schemas import BooksLMContextResponse
|
||||
|
||||
logger = logging.getLogger("obsigate.bookslm_routes")
|
||||
router = APIRouter(prefix="/api/ai/bookslm", tags=["BooksLM"])
|
||||
@@ -46,7 +47,7 @@ class BooksLMChatRequest(BaseModel):
|
||||
# ── Endpoints ──
|
||||
|
||||
|
||||
@router.post("/context")
|
||||
@router.post("/context", response_model=BooksLMContextResponse)
|
||||
async def api_bookslm_context(
|
||||
req: BooksLMContextRequest,
|
||||
current_user=Depends(require_auth),
|
||||
@@ -67,7 +68,11 @@ async def api_bookslm_context(
|
||||
return context
|
||||
|
||||
|
||||
@router.post("/chat")
|
||||
@router.post(
|
||||
"/chat",
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"text/event-stream": {}}, "description": "SSE token stream"}},
|
||||
)
|
||||
async def api_bookslm_chat(
|
||||
req: BooksLMChatRequest,
|
||||
current_user=Depends(require_auth),
|
||||
|
||||
+164
-58
@@ -56,6 +56,47 @@ from backend.indexer import (
|
||||
remove_vault_from_index,
|
||||
update_single_file,
|
||||
)
|
||||
from backend.openapi_docs import (
|
||||
API_DESCRIPTION,
|
||||
TAGS_METADATA,
|
||||
enrich_openapi_schema,
|
||||
render_api_landing,
|
||||
)
|
||||
from backend.schemas import (
|
||||
AIKeyDeleteResponse,
|
||||
AIKeysResponse,
|
||||
AIModelsResponse,
|
||||
AITestResponse,
|
||||
AllVaultSettingsResponse,
|
||||
AppConfigResponse,
|
||||
AttachmentRescanResponse,
|
||||
AttachmentStatsResponse,
|
||||
BacklinksResponse,
|
||||
BackupContentResponse,
|
||||
BackupsAutoResponse,
|
||||
BackupsCompressResponse,
|
||||
BackupsDeletedResponse,
|
||||
BackupsListResponse,
|
||||
BackupsResponse,
|
||||
BookmarksResponse,
|
||||
BookmarkToggleResponse,
|
||||
ConflictResolveResponse,
|
||||
ConflictsResponse,
|
||||
DashboardResponse,
|
||||
DiagnosticsResponse,
|
||||
PdfInfoResponse,
|
||||
RecentResponse,
|
||||
ReplaceResponse,
|
||||
SavedSearch,
|
||||
ShareModel,
|
||||
StatusResponse,
|
||||
VaultActionResponse,
|
||||
VaultFilesResponse,
|
||||
VaultSettingsResponse,
|
||||
VaultsStatusResponse,
|
||||
VaultStatsResponse,
|
||||
WebhookModel,
|
||||
)
|
||||
from backend.search import (
|
||||
advanced_search,
|
||||
get_all_tags,
|
||||
@@ -668,7 +709,33 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
from backend.version import get_git_commit, get_git_describe, get_version
|
||||
|
||||
app = FastAPI(title="ObsiGate", version=get_version(), lifespan=lifespan)
|
||||
app = FastAPI(
|
||||
title="ObsiGate API",
|
||||
version=get_version(),
|
||||
lifespan=lifespan,
|
||||
description=API_DESCRIPTION.strip(),
|
||||
openapi_tags=TAGS_METADATA,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
contact={"name": "ObsiGate", "url": "https://git.dracodev.net/Projets/ObsiGate"},
|
||||
license_info={"name": "MIT"},
|
||||
)
|
||||
|
||||
# Enrich the auto-generated OpenAPI 3.1 schema (#72): tags per category,
|
||||
# examples, security schemes and documented error responses.
|
||||
_original_openapi = app.openapi
|
||||
|
||||
|
||||
def _custom_openapi():
|
||||
if app.openapi_schema:
|
||||
return app.openapi_schema
|
||||
schema = _original_openapi()
|
||||
app.openapi_schema = enrich_openapi_schema(schema)
|
||||
return app.openapi_schema
|
||||
|
||||
|
||||
app.openapi = _custom_openapi
|
||||
|
||||
# GZip compression — reduces bandwidth by ~70% for text responses
|
||||
# Custom wrapper: skip compression for SSE streams (/api/events)
|
||||
@@ -766,6 +833,17 @@ except ImportError as e:
|
||||
FRONTEND_DIR = Path(__file__).resolve().parent.parent / "frontend"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API documentation landing page (#72)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api", include_in_schema=False, response_class=HTMLResponse)
|
||||
@app.get("/api/", include_in_schema=False, response_class=HTMLResponse)
|
||||
async def api_docs_landing():
|
||||
"""Human-friendly API documentation landing page (links to /docs, /redoc)."""
|
||||
return HTMLResponse(render_api_landing(get_version()))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Path safety helper
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1220,7 +1298,7 @@ def humanize_mtime(mtime: float) -> str:
|
||||
return datetime.fromtimestamp(mtime).strftime("%d %b %Y")
|
||||
|
||||
|
||||
@app.get("/api/recent")
|
||||
@app.get("/api/recent", response_model=RecentResponse)
|
||||
async def api_recent(limit: int | None = Query(None), vault: str | None = Query(None), mode: str | None = Query("opened"), current_user=Depends(require_auth)):
|
||||
config = _load_config()
|
||||
actual_limit = limit if limit is not None else config.get("recent_files_limit", 20)
|
||||
@@ -1314,7 +1392,7 @@ async def api_recent(limit: int | None = Query(None), vault: str | None = Query(
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/bookmarks")
|
||||
@app.get("/api/bookmarks", response_model=BookmarksResponse)
|
||||
async def api_bookmarks(vault: str | None = Query(None), current_user=Depends(require_auth)):
|
||||
username = current_user.get("username")
|
||||
user_vaults = current_user.get("_token_vaults") or current_user.get("vaults", [])
|
||||
@@ -1362,7 +1440,7 @@ class BookmarkToggleRequest(BaseModel):
|
||||
path: str
|
||||
title: str | None = None
|
||||
|
||||
@app.post("/api/bookmarks/toggle")
|
||||
@app.post("/api/bookmarks/toggle", response_model=BookmarkToggleResponse)
|
||||
async def api_toggle_bookmark(req: BookmarkToggleRequest, current_user=Depends(require_auth)):
|
||||
username = current_user.get("username")
|
||||
if not username:
|
||||
@@ -1396,7 +1474,7 @@ async def api_toggle_bookmark(req: BookmarkToggleRequest, current_user=Depends(r
|
||||
return {"bookmarked": is_now_bookmarked}
|
||||
|
||||
|
||||
@app.get("/api/saved-searches")
|
||||
@app.get("/api/saved-searches", response_model=list[SavedSearch])
|
||||
async def api_saved_searches(current_user=Depends(require_auth)):
|
||||
username = current_user.get("username")
|
||||
if not username:
|
||||
@@ -1404,7 +1482,7 @@ async def api_saved_searches(current_user=Depends(require_auth)):
|
||||
return get_saved(username)
|
||||
|
||||
|
||||
@app.post("/api/saved-searches")
|
||||
@app.post("/api/saved-searches", response_model=SavedSearch)
|
||||
async def api_save_search(body: dict = Body(...), current_user=Depends(require_auth)):
|
||||
username = current_user.get("username")
|
||||
if not username:
|
||||
@@ -1412,7 +1490,7 @@ async def api_save_search(body: dict = Body(...), current_user=Depends(require_a
|
||||
return save_search(username, body)
|
||||
|
||||
|
||||
@app.delete("/api/saved-searches/{search_id}")
|
||||
@app.delete("/api/saved-searches/{search_id}", response_model=StatusResponse)
|
||||
async def api_delete_saved_search(search_id: str, current_user=Depends(require_auth)):
|
||||
username = current_user.get("username")
|
||||
if not username:
|
||||
@@ -1550,7 +1628,7 @@ async def api_file_raw(vault_name: str, path: str = Query(..., description="Rela
|
||||
return {"vault": vault_name, "path": path, "raw": raw}
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/download")
|
||||
@app.get("/api/file/{vault_name}/download", response_class=FileResponse)
|
||||
async def api_file_download(vault_name: str, path: str = Query(..., description="Relative path to file"), current_user=Depends(require_auth)):
|
||||
"""Download a file as an attachment.
|
||||
|
||||
@@ -1583,7 +1661,11 @@ async def api_file_download(vault_name: str, path: str = Query(..., description=
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/pdf")
|
||||
@app.get(
|
||||
"/api/file/{vault_name}/pdf",
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/pdf": {}}, "description": "PDF document"}},
|
||||
)
|
||||
async def api_file_pdf(vault_name: str, path: str = Query(..., description="Relative path to file"), current_user=Depends(require_auth)):
|
||||
"""Download a markdown file as PDF."""
|
||||
if generate_pdf is None:
|
||||
@@ -1631,7 +1713,11 @@ def _resolve_export_target(vault_name: str, path: str, current_user: dict) -> tu
|
||||
return vault_root, target
|
||||
|
||||
|
||||
@app.get("/api/export/html")
|
||||
@app.get(
|
||||
"/api/export/html",
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"text/html": {}}, "description": "Standalone HTML file"}},
|
||||
)
|
||||
async def api_export_html(
|
||||
vault: str = Query(..., description="Vault name"),
|
||||
path: str = Query(..., description="Relative path to file"),
|
||||
@@ -1652,7 +1738,11 @@ async def api_export_html(
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/export/md-bundle")
|
||||
@app.get(
|
||||
"/api/export/md-bundle",
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/zip": {}}, "description": "Markdown ZIP bundle"}},
|
||||
)
|
||||
async def api_export_md_bundle(
|
||||
vault: str = Query(..., description="Vault name"),
|
||||
path: str = Query(..., description="Relative path to directory or file"),
|
||||
@@ -1672,7 +1762,11 @@ async def api_export_md_bundle(
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/export/epub")
|
||||
@app.get(
|
||||
"/api/export/epub",
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/epub+zip": {}}, "description": "ePub document"}},
|
||||
)
|
||||
async def api_export_epub(
|
||||
vault: str = Query(..., description="Vault name"),
|
||||
path: str = Query(..., description="Relative path to file"),
|
||||
@@ -2379,7 +2473,7 @@ def _list_backup_files(vault_name: str, relative_path: str) -> list[dict]:
|
||||
return backups
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/backups")
|
||||
@app.get("/api/file/{vault_name}/backups", response_model=BackupsResponse)
|
||||
async def api_file_backups(
|
||||
vault_name: str,
|
||||
path: str = Query(..., description="Relative path to file"),
|
||||
@@ -2416,7 +2510,7 @@ async def api_file_backups(
|
||||
return {"vault": vault_name, "path": path, "backups": backups}
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/diff")
|
||||
@app.get("/api/file/{vault_name}/diff", response_model=DiffResponse)
|
||||
async def api_file_diff(
|
||||
vault_name: str,
|
||||
path: str = Query(..., description="Relative path to file"),
|
||||
@@ -2504,7 +2598,7 @@ async def api_file_diff(
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors de la génération du diff: {e!s}")
|
||||
|
||||
|
||||
@app.post("/api/file/{vault_name}/restore")
|
||||
@app.post("/api/file/{vault_name}/restore", response_model=RestoreResponse)
|
||||
async def api_file_restore(
|
||||
vault_name: str,
|
||||
path: str = Query(..., description="Relative path to file"),
|
||||
@@ -2586,7 +2680,7 @@ async def api_file_restore(
|
||||
raise HTTPException(status_code=500, detail=f"Error restoring file: {e!s}")
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/backlinks")
|
||||
@app.get("/api/file/{vault_name}/backlinks", response_model=BacklinksResponse)
|
||||
async def api_file_backlinks(
|
||||
vault_name: str,
|
||||
path: str = Query(..., description="Relative path to file"),
|
||||
@@ -2881,7 +2975,7 @@ async def api_file(vault_name: str, path: str = Query(..., description="Relative
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/pdf/stream")
|
||||
@app.get("/api/file/{vault_name}/pdf/stream", response_class=FileResponse)
|
||||
async def api_pdf_stream(
|
||||
request: Request,
|
||||
vault_name: str,
|
||||
@@ -2965,7 +3059,7 @@ async def api_pdf_stream(
|
||||
"Content-Disposition": _content_disposition("inline", file_path.name)})
|
||||
|
||||
|
||||
@app.get("/api/file/{vault_name}/pdf/info")
|
||||
@app.get("/api/file/{vault_name}/pdf/info", response_model=PdfInfoResponse)
|
||||
async def api_pdf_info(
|
||||
vault_name: str,
|
||||
path: str = Query(..., description="Relative path to PDF file"),
|
||||
@@ -3144,7 +3238,7 @@ async def api_advanced_search(
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/search/replace")
|
||||
@app.post("/api/search/replace", response_model=ReplaceResponse)
|
||||
async def api_search_replace(
|
||||
body: dict = Body(...),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -3491,7 +3585,7 @@ def _add_wikilink_edges(nodes: list, edges: list, node_ids: set, vault_name: str
|
||||
break
|
||||
|
||||
|
||||
@app.get("/api/index/reload/{vault_name}")
|
||||
@app.get("/api/index/reload/{vault_name}", response_model=VaultStatsResponse)
|
||||
async def api_reload_vault(vault_name: str, current_user=Depends(require_admin)):
|
||||
"""Force a re-index of a single vault.
|
||||
|
||||
@@ -3517,7 +3611,11 @@ async def api_reload_vault(vault_name: str, current_user=Depends(require_admin))
|
||||
# SSE endpoint — Server-Sent Events stream
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/events")
|
||||
@app.get(
|
||||
"/api/events",
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"text/event-stream": {}}, "description": "Server-Sent Events stream"}},
|
||||
)
|
||||
async def api_events(current_user=Depends(require_auth)):
|
||||
"""SSE stream for real-time index update notifications.
|
||||
|
||||
@@ -3560,7 +3658,7 @@ async def api_events(current_user=Depends(require_auth)):
|
||||
# Dynamic vault management endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/vaults/add")
|
||||
@app.post("/api/vaults/add", response_model=VaultStatsResponse)
|
||||
async def api_add_vault(body: dict = Body(...), current_user=Depends(require_admin)):
|
||||
"""Add a new vault dynamically without restarting.
|
||||
|
||||
@@ -3590,7 +3688,7 @@ async def api_add_vault(body: dict = Body(...), current_user=Depends(require_adm
|
||||
return {"status": "ok", "vault": name, "stats": stats}
|
||||
|
||||
|
||||
@app.delete("/api/vaults/{vault_name}")
|
||||
@app.delete("/api/vaults/{vault_name}", response_model=VaultActionResponse)
|
||||
async def api_remove_vault(vault_name: str, current_user=Depends(require_admin)):
|
||||
"""Remove a vault from the index and stop watching it.
|
||||
|
||||
@@ -3609,7 +3707,7 @@ async def api_remove_vault(vault_name: str, current_user=Depends(require_admin))
|
||||
return {"status": "ok", "vault": vault_name}
|
||||
|
||||
|
||||
@app.get("/api/vaults/status")
|
||||
@app.get("/api/vaults/status", response_model=VaultsStatusResponse)
|
||||
async def api_vaults_status(current_user=Depends(require_auth)):
|
||||
"""Detailed status of all vaults including watcher state.
|
||||
|
||||
@@ -3631,7 +3729,11 @@ async def api_vaults_status(current_user=Depends(require_auth)):
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/image/{vault_name}")
|
||||
@app.get(
|
||||
"/api/image/{vault_name}",
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/octet-stream": {}}, "description": "Image bytes"}},
|
||||
)
|
||||
async def api_image(vault_name: str, path: str = Query(..., description="Relative path to image"), current_user=Depends(require_auth)):
|
||||
"""Serve an image file with proper MIME type.
|
||||
|
||||
@@ -3671,7 +3773,7 @@ async def api_image(vault_name: str, path: str = Query(..., description="Relativ
|
||||
raise HTTPException(status_code=500, detail=f"Error serving image: {e!s}")
|
||||
|
||||
|
||||
@app.post("/api/attachments/rescan/{vault_name}")
|
||||
@app.post("/api/attachments/rescan/{vault_name}", response_model=AttachmentRescanResponse)
|
||||
async def api_rescan_attachments(vault_name: str, current_user=Depends(require_admin)):
|
||||
"""Rescan attachments for a specific vault.
|
||||
|
||||
@@ -3692,7 +3794,7 @@ async def api_rescan_attachments(vault_name: str, current_user=Depends(require_a
|
||||
return {"status": "ok", "vault": vault_name, "attachment_count": count}
|
||||
|
||||
|
||||
@app.get("/api/attachments/stats")
|
||||
@app.get("/api/attachments/stats", response_model=AttachmentStatsResponse)
|
||||
async def api_attachment_stats(vault: str | None = Query(None, description="Vault filter"), current_user=Depends(require_auth)):
|
||||
"""Get attachment statistics for vaults.
|
||||
|
||||
@@ -3710,7 +3812,7 @@ async def api_attachment_stats(vault: str | None = Query(None, description="Vaul
|
||||
# Vault Settings API — Display preferences
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/vaults/{vault_name}/settings")
|
||||
@app.get("/api/vaults/{vault_name}/settings", response_model=VaultSettingsResponse)
|
||||
async def api_get_vault_settings(vault_name: str, current_user=Depends(require_auth)):
|
||||
"""Get UI display settings for a specific vault.
|
||||
|
||||
@@ -3735,7 +3837,7 @@ async def api_get_vault_settings(vault_name: str, current_user=Depends(require_a
|
||||
return settings
|
||||
|
||||
|
||||
@app.post("/api/vaults/{vault_name}/settings")
|
||||
@app.post("/api/vaults/{vault_name}/settings", response_model=VaultSettingsResponse)
|
||||
async def api_update_vault_settings(vault_name: str, body: dict = Body(...), current_user=Depends(require_admin)):
|
||||
"""Update UI display settings for a specific vault.
|
||||
|
||||
@@ -3778,7 +3880,7 @@ async def api_update_vault_settings(vault_name: str, body: dict = Body(...), cur
|
||||
return updated
|
||||
|
||||
|
||||
@app.get("/api/vault/{vault_name}/files")
|
||||
@app.get("/api/vault/{vault_name}/files", response_model=VaultFilesResponse)
|
||||
async def api_vault_recent_files(
|
||||
vault_name: str,
|
||||
dir: str = Query("", description="Directory path within the vault (empty = root)"),
|
||||
@@ -3889,7 +3991,7 @@ async def api_vault_recent_files(
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/vaults/settings/all")
|
||||
@app.get("/api/vaults/settings/all", response_model=AllVaultSettingsResponse)
|
||||
async def api_get_all_vault_settings(current_user=Depends(require_auth)):
|
||||
"""Get UI display settings for all vaults.
|
||||
|
||||
@@ -3914,7 +4016,7 @@ async def api_get_all_vault_settings(current_user=Depends(require_auth)):
|
||||
# Backup Management API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/backups")
|
||||
@app.get("/api/backups", response_model=BackupsListResponse)
|
||||
async def api_backups_list(
|
||||
vault: str | None = Query(None, description="Filter by vault name"),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -3966,7 +4068,7 @@ async def api_backups_list(
|
||||
raise HTTPException(status_code=500, detail=f"Erreur listing backups: {e!s}")
|
||||
|
||||
|
||||
@app.post("/api/backups/delete")
|
||||
@app.post("/api/backups/delete", response_model=BackupsDeletedResponse)
|
||||
async def api_backups_delete(
|
||||
body: dict = Body(...),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -3992,7 +4094,7 @@ async def api_backups_delete(
|
||||
return {"deleted": deleted}
|
||||
|
||||
|
||||
@app.post("/api/backups/purge")
|
||||
@app.post("/api/backups/purge", response_model=BackupsDeletedResponse)
|
||||
async def api_backups_purge(
|
||||
body: dict = Body(...),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -4042,7 +4144,7 @@ async def api_backups_purge(
|
||||
|
||||
|
||||
|
||||
@app.get("/api/backups/content")
|
||||
@app.get("/api/backups/content", response_model=BackupContentResponse)
|
||||
async def api_backups_content(
|
||||
path: str = Query(..., description="Full path to backup file"),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -4065,7 +4167,7 @@ async def api_backups_content(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.post("/api/backups/compress")
|
||||
@app.post("/api/backups/compress", response_model=BackupsCompressResponse)
|
||||
async def api_backups_compress(
|
||||
body: dict = Body(...),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -4121,7 +4223,7 @@ async def api_backups_compress(
|
||||
return {"compressed": compressed, "saved_bytes": saved_bytes, "dry_run": dry_run}
|
||||
|
||||
|
||||
@app.post("/api/backups/auto")
|
||||
@app.post("/api/backups/auto", response_model=BackupsAutoResponse)
|
||||
async def api_backups_auto(
|
||||
body: dict = Body(...),
|
||||
current_user=Depends(require_auth),
|
||||
@@ -4211,13 +4313,13 @@ def _save_config(config: dict) -> None:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to save config: {e}")
|
||||
|
||||
|
||||
@app.get("/api/config")
|
||||
@app.get("/api/config", response_model=AppConfigResponse)
|
||||
async def api_get_config(current_user=Depends(require_auth)):
|
||||
"""Return current configuration with defaults for missing keys."""
|
||||
return _load_config()
|
||||
|
||||
|
||||
@app.post("/api/config")
|
||||
@app.post("/api/config", response_model=AppConfigResponse)
|
||||
async def api_set_config(body: dict = Body(...), current_user=Depends(require_admin)):
|
||||
"""Update configuration. Only known keys are accepted.
|
||||
|
||||
@@ -4257,7 +4359,7 @@ def _write_ai_keys(data: dict):
|
||||
tmp.write_text(_json.dumps(data, indent=2), encoding="utf-8")
|
||||
tmp.replace(AI_KEYS_FILE)
|
||||
|
||||
@app.get("/api/config/ai-keys")
|
||||
@app.get("/api/config/ai-keys", response_model=AIKeysResponse)
|
||||
async def api_get_ai_keys(current_user=Depends(require_admin)):
|
||||
"""Return stored AI keys (values masked)."""
|
||||
keys = _read_ai_keys()
|
||||
@@ -4270,7 +4372,7 @@ async def api_get_ai_keys(current_user=Depends(require_admin)):
|
||||
masked[k] = ""
|
||||
return masked
|
||||
|
||||
@app.post("/api/config/ai-keys")
|
||||
@app.post("/api/config/ai-keys", response_model=StatusResponse)
|
||||
async def api_set_ai_keys(body: dict = Body(...), current_user=Depends(require_admin)):
|
||||
"""Save AI keys. Pass {"DEEPSEEK_API_KEY":"sk-...","OPENROUTER_API_KEY":"...","GEMINI_API_KEY":"..."}"""
|
||||
keys = _read_ai_keys()
|
||||
@@ -4282,7 +4384,7 @@ async def api_set_ai_keys(body: dict = Body(...), current_user=Depends(require_a
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.delete("/api/config/ai-keys/{provider_env}")
|
||||
@app.delete("/api/config/ai-keys/{provider_env}", response_model=AIKeyDeleteResponse)
|
||||
async def api_delete_ai_key(provider_env: str, current_user=Depends(require_admin)):
|
||||
"""Delete a specific AI provider key from storage."""
|
||||
allowed = {"DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY",
|
||||
@@ -4300,7 +4402,7 @@ async def api_delete_ai_key(provider_env: str, current_user=Depends(require_admi
|
||||
return {"status": "deleted", "key": key_name}
|
||||
|
||||
|
||||
@app.post("/api/config/ai-keys/test")
|
||||
@app.post("/api/config/ai-keys/test", response_model=AITestResponse)
|
||||
async def api_test_ai_keys(current_user=Depends(require_admin)):
|
||||
"""Test which AI providers are configured.
|
||||
|
||||
@@ -4345,7 +4447,7 @@ async def api_test_ai_keys(current_user=Depends(require_admin)):
|
||||
# AI Models — list available models per provider
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/config/ai-models")
|
||||
@app.get("/api/config/ai-models", response_model=AIModelsResponse)
|
||||
async def api_list_ai_models(provider: str = Query(...), current_user=Depends(require_admin)):
|
||||
"""List available models for a given AI provider.
|
||||
|
||||
@@ -4492,7 +4594,7 @@ _FALLBACK_MODELS: dict[str, list[str]] = {
|
||||
# Diagnostics API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/diagnostics")
|
||||
@app.get("/api/diagnostics", response_model=DiagnosticsResponse)
|
||||
async def api_diagnostics(current_user=Depends(require_admin)):
|
||||
"""Return index statistics and system diagnostics.
|
||||
|
||||
@@ -4550,7 +4652,7 @@ async def api_diagnostics(current_user=Depends(require_admin)):
|
||||
# Dashboard endpoint (aggregated stats)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/dashboard")
|
||||
@app.get("/api/dashboard", response_model=DashboardResponse)
|
||||
async def api_dashboard(current_user=Depends(require_auth)):
|
||||
"""Aggregated dashboard statistics across all accessible vaults."""
|
||||
user_vaults = current_user.get("_token_vaults") or current_user.get("vaults", [])
|
||||
@@ -4579,12 +4681,12 @@ async def api_dashboard(current_user=Depends(require_auth)):
|
||||
# Webhook CRUD endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/webhooks")
|
||||
@app.get("/api/webhooks", response_model=list[WebhookModel])
|
||||
async def api_webhooks_list(current_user=Depends(require_admin)):
|
||||
return get_webhooks()
|
||||
|
||||
|
||||
@app.post("/api/webhooks")
|
||||
@app.post("/api/webhooks", response_model=WebhookModel)
|
||||
async def api_webhooks_create(body: dict = Body(...), current_user=Depends(require_admin)):
|
||||
name = body.get("name", "Unnamed")
|
||||
url = body.get("url", "")
|
||||
@@ -4595,7 +4697,7 @@ async def api_webhooks_create(body: dict = Body(...), current_user=Depends(requi
|
||||
return create_webhook(name, url, events, secret)
|
||||
|
||||
|
||||
@app.patch("/api/webhooks/{webhook_id}")
|
||||
@app.patch("/api/webhooks/{webhook_id}", response_model=WebhookModel)
|
||||
async def api_webhooks_update(webhook_id: str, body: dict = Body(...), current_user=Depends(require_admin)):
|
||||
result = update_webhook(webhook_id, body)
|
||||
if not result:
|
||||
@@ -4603,7 +4705,7 @@ async def api_webhooks_update(webhook_id: str, body: dict = Body(...), current_u
|
||||
return result
|
||||
|
||||
|
||||
@app.delete("/api/webhooks/{webhook_id}")
|
||||
@app.delete("/api/webhooks/{webhook_id}", response_model=StatusResponse)
|
||||
async def api_webhooks_delete(webhook_id: str, current_user=Depends(require_admin)):
|
||||
if not delete_webhook(webhook_id):
|
||||
raise HTTPException(404, "Webhook not found")
|
||||
@@ -4614,7 +4716,7 @@ async def api_webhooks_delete(webhook_id: str, current_user=Depends(require_admi
|
||||
# Share (public document) endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/share/{vault_name}")
|
||||
@app.post("/api/share/{vault_name}", response_model=ShareModel)
|
||||
async def api_share_create(
|
||||
vault_name: str,
|
||||
body: dict = Body(...),
|
||||
@@ -4653,7 +4755,7 @@ async def api_share_create(
|
||||
return share
|
||||
|
||||
|
||||
@app.get("/api/shares")
|
||||
@app.get("/api/shares", response_model=list[ShareModel])
|
||||
async def api_shares_list(vault: str | None = Query(None), current_user=Depends(require_auth)):
|
||||
"""List all shares (optionally filtered by vault)."""
|
||||
shares = list_shares(vault)
|
||||
@@ -4662,13 +4764,17 @@ async def api_shares_list(vault: str | None = Query(None), current_user=Depends(
|
||||
return shares
|
||||
|
||||
|
||||
@app.delete("/api/share/{share_id}")
|
||||
@app.delete("/api/share/{share_id}", response_model=StatusResponse)
|
||||
async def api_share_revoke(share_id: str, current_user=Depends(require_auth)):
|
||||
if not revoke_share(share_id):
|
||||
raise HTTPException(404, "Share not found")
|
||||
return {"status": "revoked"}
|
||||
|
||||
@app.get("/s/{token}/pdf")
|
||||
@app.get(
|
||||
"/s/{token}/pdf",
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/pdf": {}}, "description": "Shared document as PDF"}},
|
||||
)
|
||||
async def public_share_pdf_download(token: str):
|
||||
"""Download shared document as real PDF via WeasyPrint."""
|
||||
if generate_pdf is None:
|
||||
@@ -4702,7 +4808,7 @@ async def public_share_pdf_download(token: str):
|
||||
return Response(content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="{safe_name}.pdf"'})
|
||||
|
||||
|
||||
@app.get("/s/{token}/raw")
|
||||
@app.get("/s/{token}/raw", response_class=FileResponse)
|
||||
async def public_share_raw(token: str):
|
||||
"""Download the raw (original) shared document."""
|
||||
share = get_share_by_token(token)
|
||||
@@ -4719,7 +4825,7 @@ async def public_share_raw(token: str):
|
||||
return FileResponse(path=str(file_path), filename=file_path.name, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@app.get("/s/{token}")
|
||||
@app.get("/s/{token}", response_class=HTMLResponse)
|
||||
async def public_share_view(token: str):
|
||||
"""Public share view — no authentication required."""
|
||||
share = get_share_by_token(token)
|
||||
@@ -4839,7 +4945,7 @@ function exportMD(){{var raw=JSON.parse(document.getElementById("raw-content").t
|
||||
# Syncthing conflict endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/conflicts")
|
||||
@app.get("/api/conflicts", response_model=ConflictsResponse)
|
||||
async def api_conflicts(current_user=Depends(require_auth)):
|
||||
"""List sync-conflict files across accessible vaults."""
|
||||
user_vaults = current_user.get("_token_vaults") or current_user.get("vaults", [])
|
||||
@@ -4849,7 +4955,7 @@ async def api_conflicts(current_user=Depends(require_auth)):
|
||||
return {"conflicts": all_conflicts, "total": len(all_conflicts)}
|
||||
|
||||
|
||||
@app.post("/api/conflicts/resolve")
|
||||
@app.post("/api/conflicts/resolve", response_model=ConflictResolveResponse)
|
||||
async def api_conflict_resolve(body: dict = Body(...), current_user=Depends(require_auth)):
|
||||
"""Resolve a conflict: keep_local (delete conflict file) or keep_conflict (replace original)."""
|
||||
vault_name = body.get("vault")
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
"""OpenAPI 3.1 documentation helpers for ObsiGate (#72).
|
||||
|
||||
This module keeps the API-documentation concerns out of ``backend/main.py``:
|
||||
|
||||
* :data:`TAGS_METADATA` — human descriptions and ordering for every tag.
|
||||
* :func:`enrich_openapi_schema` — post-processes the schema generated by
|
||||
FastAPI to assign tags, add servers/security/examples and document common
|
||||
error responses.
|
||||
* :func:`render_api_landing` — a self-contained ``/api`` landing page that
|
||||
reads ``/openapi.json`` at runtime and groups endpoints by tag, with direct
|
||||
links to the Swagger UI (``/docs``) and ReDoc (``/redoc``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tag metadata
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
TAGS_METADATA: list[dict[str, str]] = [
|
||||
{"name": "System", "description": "Health checks, runtime configuration, diagnostics, dashboard stats and the SSE event stream."},
|
||||
{"name": "Auth", "description": "Authentication, sessions, user profile, MFA (TOTP/WebAuthn) and API keys."},
|
||||
{"name": "Files", "description": "Browse, read, create, rename, move, delete and download vault files."},
|
||||
{"name": "PDF", "description": "PDF metadata and byte-range streaming for inline viewing."},
|
||||
{"name": "Vaults", "description": "List, add and remove vaults; per-vault display settings; attachment indexing."},
|
||||
{"name": "Search", "description": "Full-text and advanced search, tags, title suggestions and the link graph."},
|
||||
{"name": "Bookmarks", "description": "Recently opened files, bookmarks and saved searches."},
|
||||
{"name": "Backups", "description": "Automatic file backups, diffs, restore, compression and purge."},
|
||||
{"name": "Export", "description": "Export notes or whole vaults to HTML, Markdown bundle or ePub."},
|
||||
{"name": "AI", "description": "AI-powered editor actions, provider status and model discovery."},
|
||||
{"name": "BooksLM", "description": "Directory-scoped AI chat (NotebookLM-style) over a vault folder."},
|
||||
{"name": "Sharing", "description": "Create and manage public read-only share links for documents."},
|
||||
{"name": "Webhooks", "description": "HTTP callbacks signed with HMAC-SHA256 for file events."},
|
||||
{"name": "Conflicts", "description": "Detect and resolve Syncthing sync-conflict files."},
|
||||
{"name": "Admin", "description": "Admin-only system monitoring: stats, audit log, backup stats and live stream."},
|
||||
{"name": "Plugins", "description": "Install, enable and manage user plugins."},
|
||||
{"name": "Push", "description": "Web Push (VAPID) subscription management and test notifications."},
|
||||
{"name": "Frontend", "description": "Static assets and SPA fallback routes."},
|
||||
]
|
||||
|
||||
API_DESCRIPTION = """
|
||||
**ObsiGate** exposes a REST API covering the entire application: vaults, files,
|
||||
full-text search, backups, exports, AI actions, sharing and administration.
|
||||
|
||||
### Authentication
|
||||
When authentication is enabled, send a bearer token obtained from
|
||||
`POST /api/auth/login`:
|
||||
|
||||
```
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
The same token is also accepted as an HTTP-only cookie, so browser clients can
|
||||
simply use `credentials: "include"`.
|
||||
|
||||
### Interactive documentation
|
||||
* **Swagger UI** — [/docs](/docs): try requests directly from the browser.
|
||||
* **ReDoc** — [/redoc](/redoc): clean, reading-oriented reference.
|
||||
* **OpenAPI JSON** — [/openapi.json](/openapi.json): machine-readable schema.
|
||||
|
||||
### Errors
|
||||
Errors use the standard FastAPI envelope `{"detail": "..."}` with the
|
||||
appropriate HTTP status (`400`, `401`, `403`, `404`, `409`, `422`, `500`).
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Automatic tag assignment
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Rules are evaluated in order; the first match wins. Keep the most specific
|
||||
# prefixes first (e.g. BooksLM before AI, config/ai-* before config).
|
||||
_TAG_RULES: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^/api/auth"), "Auth"),
|
||||
(re.compile(r"^/api/admin"), "Admin"),
|
||||
(re.compile(r"^/api/plugins"), "Plugins"),
|
||||
(re.compile(r"^/api/push"), "Push"),
|
||||
(re.compile(r"^/api/ai/bookslm"), "BooksLM"),
|
||||
(re.compile(r"^/api/ai"), "AI"),
|
||||
(re.compile(r"^/api/config/ai-"), "AI"),
|
||||
(re.compile(r"^/api/share"), "Sharing"),
|
||||
(re.compile(r"^/api/shares"), "Sharing"),
|
||||
(re.compile(r"^/s/"), "Sharing"),
|
||||
(re.compile(r"^/api/webhooks"), "Webhooks"),
|
||||
(re.compile(r"^/api/conflicts"), "Conflicts"),
|
||||
(re.compile(r"^/api/backups"), "Backups"),
|
||||
(re.compile(r"^/api/file/[^/]+/(backups|diff|restore)"), "Backups"),
|
||||
(re.compile(r"^/api/export"), "Export"),
|
||||
(re.compile(r"^/api/file/[^/]+/pdf"), "PDF"),
|
||||
(re.compile(r"^/api/search"), "Search"),
|
||||
(re.compile(r"^/api/tags"), "Search"),
|
||||
(re.compile(r"^/api/tree-search"), "Search"),
|
||||
(re.compile(r"^/api/suggest"), "Search"),
|
||||
(re.compile(r"^/api/graph"), "Search"),
|
||||
(re.compile(r"^/api/recent"), "Bookmarks"),
|
||||
(re.compile(r"^/api/bookmarks"), "Bookmarks"),
|
||||
(re.compile(r"^/api/saved-searches"), "Bookmarks"),
|
||||
(re.compile(r"^/api/vaults"), "Vaults"),
|
||||
(re.compile(r"^/api/vault/"), "Vaults"),
|
||||
(re.compile(r"^/api/index/reload"), "Vaults"),
|
||||
(re.compile(r"^/api/attachments"), "Vaults"),
|
||||
(re.compile(r"^/api/browse"), "Files"),
|
||||
(re.compile(r"^/api/file"), "Files"),
|
||||
(re.compile(r"^/api/directory"), "Files"),
|
||||
(re.compile(r"^/api/move"), "Files"),
|
||||
(re.compile(r"^/api/image"), "Files"),
|
||||
(re.compile(r"^/api/health"), "System"),
|
||||
(re.compile(r"^/api/config"), "System"),
|
||||
(re.compile(r"^/api/diagnostics"), "System"),
|
||||
(re.compile(r"^/api/dashboard"), "System"),
|
||||
(re.compile(r"^/api/events"), "System"),
|
||||
]
|
||||
|
||||
|
||||
def tag_for_path(path: str) -> str:
|
||||
"""Return the documentation tag for an API path (``Frontend`` as fallback)."""
|
||||
for pattern, tag in _TAG_RULES:
|
||||
if pattern.match(path):
|
||||
return tag
|
||||
return "Frontend"
|
||||
|
||||
|
||||
# Normalise tags declared by individual routers (``tags=["auth"]``) to the
|
||||
# canonical, documented tag names.
|
||||
_TAG_ALIASES: dict[str, str] = {
|
||||
"auth": "Auth",
|
||||
"admin": "Admin",
|
||||
"plugins": "Plugins",
|
||||
"push": "Push",
|
||||
"files": "Files",
|
||||
"vaults": "Vaults",
|
||||
"search": "Search",
|
||||
"backups": "Backups",
|
||||
"export": "Export",
|
||||
"sharing": "Sharing",
|
||||
"webhooks": "Webhooks",
|
||||
"conflicts": "Conflicts",
|
||||
"system": "System",
|
||||
"frontend": "Frontend",
|
||||
"ai": "AI",
|
||||
"bookslm": "BooksLM",
|
||||
"pdf": "PDF",
|
||||
"bookmarks": "Bookmarks",
|
||||
}
|
||||
|
||||
_CANONICAL_TAGS = {tag["name"] for tag in TAGS_METADATA}
|
||||
|
||||
|
||||
def canonical_tag(name: str) -> str:
|
||||
"""Map a router-declared tag to its documented name (unchanged if unknown)."""
|
||||
mapped = _TAG_ALIASES.get(name.lower(), name)
|
||||
return mapped if mapped in _CANONICAL_TAGS else name
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Request/response examples injected into the schema
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_ENDPOINT_EXAMPLES: dict[tuple[str, str], dict[str, Any]] = {
|
||||
("post", "/api/file/{vault_name}"): {
|
||||
"request": {"path": "notes/Nouvelle note.md", "content": "# Titre\n\nContenu"},
|
||||
"response": {"success": True, "path": "notes/Nouvelle note.md"},
|
||||
},
|
||||
("put", "/api/file/{vault_name}/save"): {
|
||||
"request": {"path": "notes/Accueil.md", "content": "# Accueil\n\nMis à jour."},
|
||||
"response": {"status": "ok", "vault": "TestVault", "path": "notes/Accueil.md", "size": 26},
|
||||
},
|
||||
("post", "/api/search/replace"): {
|
||||
"request": {"query": "Python", "replacement": "Python 3", "vault": "all", "dry_run": True},
|
||||
"response": {"matches": [{"vault": "TestVault", "path": "note1.md", "title": "Python", "match_count": 3}], "total_matches": 3, "dry_run": True},
|
||||
},
|
||||
("post", "/api/ai/improve"): {
|
||||
"request": {"text": "ce texte est bof", "provider": "deepseek"},
|
||||
"response": {"result": "Ce texte mérite d'être amélioré.", "provider": "deepseek"},
|
||||
},
|
||||
("post", "/api/ai/bookslm/chat"): {
|
||||
"request": {"vault": "TestVault", "directory": "projets", "message": "Résume ce dossier", "conversation_history": []},
|
||||
"response": {"token": "Voici un résumé…", "provider": "deepseek", "model": "deepseek-chat"},
|
||||
},
|
||||
("post", "/api/share/{vault_name}"): {
|
||||
"request": {"path": "notes/Accueil.md", "expires_in_hours": 168},
|
||||
"response": {"id": "abc…", "token": "abc…", "vault": "TestVault", "path": "notes/Accueil.md", "url": "/s/abc…"},
|
||||
},
|
||||
("post", "/api/webhooks"): {
|
||||
"request": {"name": "CI", "url": "https://example.com/hook", "events": ["file_modified"], "secret": "s3cr3t"},
|
||||
"response": {"id": "3f2c…", "name": "CI", "url": "https://example.com/hook", "events": ["file_modified"], "enabled": True},
|
||||
},
|
||||
}
|
||||
|
||||
# Common error responses documented on every operation.
|
||||
_COMMON_ERRORS: dict[str, dict[str, Any]] = {
|
||||
"401": {
|
||||
"description": "Authentication required or token expired",
|
||||
"content": {"application/json": {"example": {"detail": "Not authenticated"}}},
|
||||
},
|
||||
"403": {
|
||||
"description": "Access to the vault is denied",
|
||||
"content": {"application/json": {"example": {"detail": "Accès refusé à la vault 'Notes'"}}},
|
||||
},
|
||||
"404": {
|
||||
"description": "Resource not found",
|
||||
"content": {"application/json": {"example": {"detail": "File not found: notes/x.md"}}},
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation error",
|
||||
"content": {"application/json": {"example": {"detail": [{"loc": ["query", "path"], "msg": "field required", "type": "value_error.missing"}]}}},
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"content": {"application/json": {"example": {"detail": "Internal server error"}}},
|
||||
},
|
||||
}
|
||||
|
||||
# Paths that return a binary/streaming body — never add a JSON error example
|
||||
# to their 200 response, and skip the 500 JSON example for streams.
|
||||
_BINARY_MEDIA = ("application/pdf", "application/octet-stream", "image/", "text/event-stream")
|
||||
|
||||
|
||||
def _is_binary_operation(operation: dict[str, Any]) -> bool:
|
||||
content = operation.get("responses", {}).get("200", {}).get("content", {})
|
||||
return any(media.startswith(_BINARY_MEDIA) for media in content)
|
||||
|
||||
|
||||
def enrich_openapi_schema(schema: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Enrich a FastAPI-generated OpenAPI schema in place and return it.
|
||||
|
||||
The transformation is idempotent: calling it twice yields the same result.
|
||||
"""
|
||||
schema.setdefault("openapi", "3.1.0")
|
||||
info = schema.setdefault("info", {})
|
||||
info.setdefault("description", API_DESCRIPTION.strip())
|
||||
info.setdefault("contact", {"name": "ObsiGate", "url": "https://git.dracodev.net/Projets/ObsiGate"})
|
||||
info.setdefault("license", {"name": "MIT"})
|
||||
|
||||
schema.setdefault("servers", [{"url": "/", "description": "Current ObsiGate instance"}])
|
||||
schema["externalDocs"] = {
|
||||
"description": "ObsiGate source repository",
|
||||
"url": "https://git.dracodev.net/Projets/ObsiGate",
|
||||
}
|
||||
schema["tags"] = TAGS_METADATA
|
||||
|
||||
components = schema.setdefault("components", {})
|
||||
security_schemes = components.setdefault("securitySchemes", {})
|
||||
security_schemes.setdefault("bearerAuth", {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"bearerFormat": "JWT",
|
||||
"description": "JWT access token issued by POST /api/auth/login.",
|
||||
})
|
||||
security_schemes.setdefault("cookieAuth", {
|
||||
"type": "apiKey",
|
||||
"in": "cookie",
|
||||
"name": "obsigate_token",
|
||||
"description": "HTTP-only session cookie (browser clients).",
|
||||
})
|
||||
components.setdefault("schemas", {}).setdefault("ErrorResponse", {
|
||||
"type": "object",
|
||||
"properties": {"detail": {"title": "Detail", "description": "Error message"}},
|
||||
})
|
||||
|
||||
for path, operations in schema.get("paths", {}).items():
|
||||
default_tag = tag_for_path(path)
|
||||
for method, operation in operations.items():
|
||||
if not isinstance(operation, dict):
|
||||
continue
|
||||
if operation.get("tags"):
|
||||
operation["tags"] = [canonical_tag(t) for t in operation["tags"]]
|
||||
else:
|
||||
operation["tags"] = [default_tag]
|
||||
|
||||
# Document common error responses without overriding explicit ones.
|
||||
responses = operation.setdefault("responses", {})
|
||||
binary = _is_binary_operation(operation)
|
||||
for code, spec in _COMMON_ERRORS.items():
|
||||
if code == "500" and binary:
|
||||
continue
|
||||
responses.setdefault(code, spec)
|
||||
|
||||
# Inject request/response examples for key endpoints.
|
||||
example = _ENDPOINT_EXAMPLES.get((method, path))
|
||||
if example:
|
||||
if "request" in example:
|
||||
body = operation.setdefault("requestBody", {})
|
||||
content = body.setdefault("content", {}).setdefault("application/json", {})
|
||||
content.setdefault("example", example["request"])
|
||||
if "response" in example:
|
||||
ok = responses.setdefault("200", {})
|
||||
content = ok.setdefault("content", {}).setdefault("application/json", {})
|
||||
content.setdefault("example", example["response"])
|
||||
|
||||
return schema
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# /api landing page
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_METHOD_COLORS = {
|
||||
"get": "#2563eb",
|
||||
"post": "#16a34a",
|
||||
"put": "#d97706",
|
||||
"patch": "#7c3aed",
|
||||
"delete": "#dc2626",
|
||||
"head": "#64748b",
|
||||
"options": "#64748b",
|
||||
}
|
||||
|
||||
|
||||
def render_api_landing(version: str = "") -> str:
|
||||
"""Return the self-contained HTML for the ``/api`` documentation page."""
|
||||
return f"""<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>ObsiGate API{(' — v' + version) if version else ''}</title>
|
||||
<style>
|
||||
:root {{
|
||||
--bg: #0f172a; --surface: #1e293b; --border: #334155;
|
||||
--text: #e2e8f0; --muted: #94a3b8; --accent: #60a5fa; --accent-2: #34d399;
|
||||
}}
|
||||
html[data-theme="light"] {{
|
||||
--bg: #f8fafc; --surface: #ffffff; --border: #e2e8f0;
|
||||
--text: #0f172a; --muted: #64748b; --accent: #2563eb; --accent-2: #059669;
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0; background: var(--bg); color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
}}
|
||||
.wrap {{ max-width: 1080px; margin: 0 auto; padding: 40px 24px 80px; }}
|
||||
header h1 {{ margin: 0 0 4px; font-size: 1.9rem; }}
|
||||
header p {{ margin: 0; color: var(--muted); }}
|
||||
.actions {{ display: flex; flex-wrap: wrap; gap: 10px; margin: 24px 0 32px; }}
|
||||
.actions a {{
|
||||
text-decoration: none; color: var(--text); background: var(--surface);
|
||||
border: 1px solid var(--border); border-radius: 8px; padding: 10px 16px;
|
||||
font-weight: 600; font-size: .9rem; transition: border-color .15s, transform .15s;
|
||||
}}
|
||||
.actions a:hover {{ border-color: var(--accent); transform: translateY(-1px); }}
|
||||
.actions a.primary {{ background: var(--accent); border-color: var(--accent); color: #fff; }}
|
||||
.meta {{ color: var(--muted); font-size: .85rem; margin-bottom: 24px; }}
|
||||
.tag {{ margin: 28px 0; }}
|
||||
.tag > h2 {{
|
||||
font-size: 1.1rem; margin: 0 0 2px; display: flex; align-items: center; gap: 8px;
|
||||
}}
|
||||
.tag > p {{ margin: 0 0 12px; color: var(--muted); font-size: .85rem; }}
|
||||
.ops {{ display: flex; flex-direction: column; gap: 6px; }}
|
||||
.op {{
|
||||
display: flex; align-items: center; gap: 12px; padding: 8px 12px;
|
||||
background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
|
||||
text-decoration: none; color: var(--text); font-size: .88rem;
|
||||
}}
|
||||
.op:hover {{ border-color: var(--accent); }}
|
||||
.method {{
|
||||
flex: 0 0 62px; text-align: center; font-weight: 700; font-size: .68rem;
|
||||
text-transform: uppercase; letter-spacing: .04em; color: #fff; border-radius: 5px; padding: 3px 0;
|
||||
}}
|
||||
.op code {{ color: var(--accent-2); font-size: .85rem; }}
|
||||
.op .summary {{ color: var(--muted); margin-left: auto; text-align: right; }}
|
||||
.loading {{ color: var(--muted); }}
|
||||
footer {{ margin-top: 48px; color: var(--muted); font-size: .8rem; }}
|
||||
@media (max-width: 640px) {{ .op .summary {{ display: none; }} }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<h1>ObsiGate API</h1>
|
||||
<p>Interactive reference for the ObsiGate REST API (OpenAPI 3.1).</p>
|
||||
</header>
|
||||
<div class="actions">
|
||||
<a class="primary" href="/docs">Swagger UI — try it</a>
|
||||
<a href="/redoc">ReDoc — reference</a>
|
||||
<a href="/openapi.json">OpenAPI JSON</a>
|
||||
<a href="/">← Back to ObsiGate</a>
|
||||
</div>
|
||||
<div class="meta" id="meta">Loading specification…</div>
|
||||
<div id="tags"><p class="loading">Loading endpoints…</p></div>
|
||||
<footer>Generated from the live OpenAPI schema. Authentication: <code>Authorization: Bearer <token></code>.</footer>
|
||||
</div>
|
||||
<script>
|
||||
(function () {{
|
||||
var COLORS = {_js_colors()};
|
||||
function el(tag, cls, text) {{
|
||||
var e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text != null) e.textContent = text;
|
||||
return e;
|
||||
}}
|
||||
fetch('/openapi.json', {{ credentials: 'include' }})
|
||||
.then(function (r) {{ if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }})
|
||||
.then(function (spec) {{
|
||||
var info = spec.info || {{}};
|
||||
var tagMeta = {{}};
|
||||
(spec.tags || []).forEach(function (t) {{ tagMeta[t.name] = t.description || ''; }});
|
||||
var groups = {{}};
|
||||
var paths = spec.paths || {{}};
|
||||
var opCount = 0;
|
||||
Object.keys(paths).forEach(function (path) {{
|
||||
var ops = paths[path];
|
||||
Object.keys(ops).forEach(function (method) {{
|
||||
if (['get','post','put','patch','delete','head','options'].indexOf(method) === -1) return;
|
||||
var op = ops[method];
|
||||
if (op.deprecated && false) return;
|
||||
opCount++;
|
||||
var tag = (op.tags && op.tags[0]) || 'Other';
|
||||
(groups[tag] = groups[tag] || []).push({{ path: path, method: method, summary: op.summary || '' }});
|
||||
}});
|
||||
}});
|
||||
document.getElementById('meta').textContent =
|
||||
(info.title || 'ObsiGate') + (info.version ? ' v' + info.version : '') +
|
||||
' — OpenAPI ' + (spec.openapi || '3.1') + ' — ' + opCount + ' operations';
|
||||
var host = document.getElementById('tags');
|
||||
host.innerHTML = '';
|
||||
Object.keys(groups).forEach(function (tag) {{
|
||||
var section = el('section', 'tag');
|
||||
section.appendChild(el('h2', null, tag));
|
||||
if (tagMeta[tag]) section.appendChild(el('p', null, tagMeta[tag]));
|
||||
var ops = el('div', 'ops');
|
||||
groups[tag].forEach(function (o) {{
|
||||
var a = el('a', 'op');
|
||||
a.href = '/docs#/' + encodeURIComponent(tag) + '/' + encodeURIComponent(o.path);
|
||||
var m = el('span', 'method', o.method);
|
||||
m.style.background = COLORS[o.method] || '#64748b';
|
||||
a.appendChild(m);
|
||||
a.appendChild(el('code', null, o.path));
|
||||
if (o.summary) a.appendChild(el('span', 'summary', o.summary));
|
||||
ops.appendChild(a);
|
||||
}});
|
||||
section.appendChild(ops);
|
||||
host.appendChild(section);
|
||||
}});
|
||||
}})
|
||||
.catch(function (e) {{
|
||||
document.getElementById('meta').textContent = 'Failed to load OpenAPI schema: ' + e.message;
|
||||
}});
|
||||
}})();
|
||||
</script>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def _js_colors() -> str:
|
||||
"""Serialise the method→colour map for the landing page script."""
|
||||
import json
|
||||
|
||||
return json.dumps(_METHOD_COLORS)
|
||||
@@ -0,0 +1,512 @@
|
||||
"""Additional Pydantic response models for the ObsiGate REST API.
|
||||
|
||||
These models enrich the auto-generated OpenAPI 3.1 schema (#72). They are
|
||||
intentionally permissive (``extra="allow"``) so that adding a new field to an
|
||||
existing endpoint never breaks response validation — the model documents the
|
||||
stable, public shape while still accepting internal additions.
|
||||
|
||||
Models whose endpoints are already typed in :mod:`backend.main` (e.g.
|
||||
``FileContentResponse``) live there; this module only holds the ones used to
|
||||
fill the gaps.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Generic helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class StatusResponse(BaseModel):
|
||||
"""Generic ``{"status": "..."}`` acknowledgement."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
status: str = Field(default="ok", description="Operation status")
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Standard FastAPI error envelope."""
|
||||
|
||||
detail: str | list[dict[str, Any]] | None = Field(
|
||||
default=None,
|
||||
description="Human-readable error message, or a list of validation errors",
|
||||
examples=["Vault 'Notes' not found"],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Recent files & bookmarks
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class RecentFileItem(BaseModel):
|
||||
"""A recently opened or recently modified file."""
|
||||
|
||||
path: str = Field(description="Relative path within the vault")
|
||||
title: str = Field(description="File title")
|
||||
vault: str = Field(description="Vault name")
|
||||
mtime: float | int | str | None = Field(default=None, description="Modification timestamp")
|
||||
mtime_human: str | None = Field(default=None, description="Human-readable modification time")
|
||||
mtime_iso: str | None = Field(default=None, description="ISO-8601 modification time")
|
||||
size_bytes: int | None = Field(default=None, description="File size in bytes")
|
||||
tags: list[str] = Field(default_factory=list, description="Up to 5 leading tags")
|
||||
preview: str | None = Field(default=None, description="Short content preview")
|
||||
bookmarked: bool | None = Field(default=None, description="Whether the file is bookmarked")
|
||||
|
||||
|
||||
class RecentResponse(BaseModel):
|
||||
"""Response for ``GET /api/recent``."""
|
||||
|
||||
files: list[RecentFileItem]
|
||||
total: int = Field(description="Total number of files in the selected mode")
|
||||
limit: int = Field(description="Applied limit")
|
||||
mode: str = Field(description="'opened' or 'modified'")
|
||||
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"files": [
|
||||
{
|
||||
"path": "notes/Accueil.md",
|
||||
"title": "Accueil",
|
||||
"vault": "TestVault",
|
||||
"mtime": 1750000000.0,
|
||||
"mtime_human": "il y a 2 h",
|
||||
"size_bytes": 1024,
|
||||
"tags": ["#accueil"],
|
||||
"preview": "# Bienvenue…",
|
||||
"bookmarked": False,
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"limit": 20,
|
||||
"mode": "opened",
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class BookmarkFileItem(BaseModel):
|
||||
"""A bookmarked file."""
|
||||
|
||||
path: str = Field(description="Relative path within the vault")
|
||||
title: str = Field(description="File title")
|
||||
vault: str = Field(description="Vault name")
|
||||
mtime: float | int | str | None = Field(default=None, description="Bookmark timestamp")
|
||||
mtime_human: str | None = Field(default=None, description="Human-readable bookmark time")
|
||||
size_bytes: int | None = Field(default=None, description="File size in bytes")
|
||||
tags: list[str] = Field(default_factory=list, description="Up to 5 leading tags")
|
||||
bookmarked: bool | None = Field(default=True, description="Always true for this endpoint")
|
||||
|
||||
|
||||
class BookmarksResponse(BaseModel):
|
||||
"""Response for ``GET /api/bookmarks``."""
|
||||
|
||||
files: list[BookmarkFileItem]
|
||||
total: int = Field(description="Number of bookmarked files")
|
||||
|
||||
|
||||
class BookmarkToggleResponse(BaseModel):
|
||||
"""Response for ``POST /api/bookmarks/toggle``."""
|
||||
|
||||
bookmarked: bool = Field(description="New bookmark state")
|
||||
|
||||
|
||||
class SavedSearch(BaseModel):
|
||||
"""A persisted search definition."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
id: str = Field(description="Unique identifier (millisecond timestamp)")
|
||||
query: str = Field(description="Search query text")
|
||||
vault: str = Field(default="all", description="Vault filter")
|
||||
case_sensitive: bool = Field(default=False)
|
||||
whole_word: bool = Field(default=False)
|
||||
regex: bool = Field(default=False)
|
||||
include_paths: str = Field(default="")
|
||||
exclude_paths: str = Field(default="")
|
||||
created_at: float = Field(description="Creation timestamp (epoch seconds)")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backups & diffs
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class BackupsResponse(BaseModel):
|
||||
"""Response for ``GET /api/file/{vault}/backups``."""
|
||||
|
||||
vault: str
|
||||
path: str
|
||||
backups: list[dict[str, Any]] = Field(description="Backups, newest first")
|
||||
|
||||
|
||||
class BacklinksResponse(BaseModel):
|
||||
"""Response for ``GET /api/file/{vault}/backlinks``."""
|
||||
|
||||
vault: str
|
||||
path: str
|
||||
backlinks: list[dict[str, Any]] = Field(description="Files linking to the target")
|
||||
total: int
|
||||
|
||||
|
||||
class BackupsListResponse(BaseModel):
|
||||
"""Response for ``GET /api/backups``."""
|
||||
|
||||
backups: list[dict[str, Any]] = Field(description="All backups across vaults")
|
||||
total: int
|
||||
total_size_bytes: int
|
||||
|
||||
|
||||
class BackupsDeletedResponse(BaseModel):
|
||||
"""Response for backup deletion / purge endpoints."""
|
||||
|
||||
deleted: int = Field(description="Number of backup files deleted")
|
||||
|
||||
|
||||
class BackupContentResponse(BaseModel):
|
||||
"""Response for ``GET /api/backups/content``."""
|
||||
|
||||
content: str = Field(description="Backup file content (truncated to 100 KB)")
|
||||
name: str = Field(description="Backup file name")
|
||||
size: int = Field(description="Returned content size in characters")
|
||||
|
||||
|
||||
class BackupsCompressResponse(BaseModel):
|
||||
"""Response for ``POST /api/backups/compress``."""
|
||||
|
||||
compressed: int = Field(description="Number of backups processed")
|
||||
saved_bytes: int = Field(description="Bytes saved by gzip compression")
|
||||
dry_run: bool
|
||||
|
||||
|
||||
class BackupsAutoResponse(BaseModel):
|
||||
"""Response for ``POST /api/backups/auto``."""
|
||||
|
||||
backed_up: int = Field(description="Number of files backed up")
|
||||
since_hours: int | float = Field(description="Look-back window in hours")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PDF
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PdfInfoResponse(BaseModel):
|
||||
"""Response for ``GET /api/file/{vault}/pdf/info``."""
|
||||
|
||||
vault: str
|
||||
path: str
|
||||
pages: int = Field(description="Page count")
|
||||
title: str = Field(description="PDF title (metadata or filename)")
|
||||
author: str = Field(default="", description="PDF author")
|
||||
size_bytes: int = Field(description="File size in bytes")
|
||||
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"vault": "TestVault",
|
||||
"path": "docs/rapport.pdf",
|
||||
"pages": 12,
|
||||
"title": "Rapport annuel",
|
||||
"author": "ObsiGate",
|
||||
"size_bytes": 524288,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Search & replace
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ReplaceMatch(BaseModel):
|
||||
"""A single file affected by a find/replace operation."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
vault: str
|
||||
path: str
|
||||
title: str | None = None
|
||||
match_count: int | None = Field(default=None, description="Occurrences found (dry run)")
|
||||
replacements: int | None = Field(default=None, description="Occurrences replaced")
|
||||
preview: list[str] = Field(default_factory=list, description="Context snippets (dry run)")
|
||||
|
||||
|
||||
class ReplaceResponse(BaseModel):
|
||||
"""Response for ``POST /api/search/replace``."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
matches: list[ReplaceMatch] = Field(default_factory=list, description="Dry-run matches")
|
||||
replaced: list[ReplaceMatch] = Field(default_factory=list, description="Applied replacements")
|
||||
total_matches: int | None = Field(default=None, description="Total matches (dry run)")
|
||||
total_replacements: int = Field(description="Total replacements performed or previewed")
|
||||
dry_run: bool | None = Field(default=None, description="True when no file was written")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Vaults, attachments & settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class VaultStatsResponse(BaseModel):
|
||||
"""Response for ``POST /api/vaults/add`` and ``GET /api/index/reload/{vault}``."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
status: str = Field(default="ok")
|
||||
vault: str
|
||||
stats: dict[str, Any] = Field(default_factory=dict, description="Index statistics for the vault")
|
||||
|
||||
|
||||
class VaultActionResponse(BaseModel):
|
||||
"""Response for ``DELETE /api/vaults/{vault}``."""
|
||||
|
||||
status: str = Field(default="ok")
|
||||
vault: str
|
||||
|
||||
|
||||
class VaultStatusEntry(BaseModel):
|
||||
"""Per-vault status entry."""
|
||||
|
||||
file_count: int
|
||||
tag_count: int
|
||||
path: str = ""
|
||||
watching: bool = False
|
||||
|
||||
|
||||
class VaultsStatusResponse(BaseModel):
|
||||
"""Response for ``GET /api/vaults/status``."""
|
||||
|
||||
vaults: dict[str, VaultStatusEntry]
|
||||
watcher_active: bool
|
||||
sse_clients: int
|
||||
|
||||
|
||||
class AttachmentRescanResponse(BaseModel):
|
||||
"""Response for ``POST /api/attachments/rescan/{vault}``."""
|
||||
|
||||
status: str = Field(default="ok")
|
||||
vault: str
|
||||
attachment_count: int
|
||||
|
||||
|
||||
class AttachmentStatsResponse(BaseModel):
|
||||
"""Response for ``GET /api/attachments/stats``."""
|
||||
|
||||
vaults: dict[str, Any] = Field(description="Vault name → attachment statistics")
|
||||
|
||||
|
||||
class VaultSettingsResponse(BaseModel):
|
||||
"""Response for the per-vault display settings endpoints."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
hideHiddenFiles: bool = Field(default=False, description="Hide dotfiles in the tree")
|
||||
|
||||
|
||||
class AllVaultSettingsResponse(BaseModel):
|
||||
"""Response for ``GET /api/vaults/settings/all``."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
class VaultFileEntry(BaseModel):
|
||||
"""A file entry returned by the vault home listing."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
name: str
|
||||
path: str
|
||||
vault: str
|
||||
size: int = 0
|
||||
modified: float = 0
|
||||
modified_iso: str | None = None
|
||||
extension: str = ""
|
||||
rel_dir: str | None = None
|
||||
|
||||
|
||||
class VaultFilesResponse(BaseModel):
|
||||
"""Response for ``GET /api/vault/{vault}/files``."""
|
||||
|
||||
vault: str
|
||||
directory: str = ""
|
||||
recursive: bool = True
|
||||
count: int
|
||||
files: list[VaultFileEntry]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Configuration, AI keys & diagnostics
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class AppConfigResponse(BaseModel):
|
||||
"""Application configuration (``GET/POST /api/config``)."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
class AIKeysResponse(BaseModel):
|
||||
"""Masked AI provider keys (``GET /api/config/ai-keys``)."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
class AIKeyDeleteResponse(BaseModel):
|
||||
"""Response for ``DELETE /api/config/ai-keys/{provider}``."""
|
||||
|
||||
status: str = Field(default="deleted")
|
||||
key: str = Field(description="Deleted environment variable name")
|
||||
|
||||
|
||||
class AITestResponse(BaseModel):
|
||||
"""Response for ``POST /api/config/ai-keys/test`` (provider → status)."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
class AIModelsResponse(BaseModel):
|
||||
"""Response for ``GET /api/config/ai-models``."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
models: list[str] = Field(default_factory=list, description="Available model identifiers")
|
||||
source: str = Field(default="fallback", description="'live', 'fallback' or 'validation'")
|
||||
count: int | None = Field(default=None, description="Number of live models")
|
||||
error: str | None = Field(default=None, description="Provider/network error, if any")
|
||||
note: str | None = Field(default=None, description="Explanatory note when using fallback")
|
||||
|
||||
|
||||
class DiagnosticsResponse(BaseModel):
|
||||
"""Response for ``GET /api/diagnostics``."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
index: dict[str, Any] = Field(default_factory=dict)
|
||||
inverted_index: dict[str, Any] = Field(default_factory=dict)
|
||||
config: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class DashboardVaultStat(BaseModel):
|
||||
"""Per-vault dashboard statistics."""
|
||||
|
||||
name: str
|
||||
file_count: int
|
||||
tag_count: int
|
||||
total_size_bytes: int
|
||||
|
||||
|
||||
class DashboardResponse(BaseModel):
|
||||
"""Response for ``GET /api/dashboard``."""
|
||||
|
||||
vaults: list[DashboardVaultStat]
|
||||
total_files: int
|
||||
total_tags: int
|
||||
total_size_bytes: int
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Webhooks, sharing & conflicts
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WebhookModel(BaseModel):
|
||||
"""A configured webhook."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
id: str = Field(description="Webhook UUID")
|
||||
name: str
|
||||
url: str = Field(description="Target HTTP(S) URL")
|
||||
events: list[str] = Field(default_factory=list, description="Subscribed event types")
|
||||
secret: str | None = Field(default=None, description="HMAC-SHA256 signing secret")
|
||||
enabled: bool = True
|
||||
created_at: str | None = None
|
||||
last_fired_at: str | None = None
|
||||
|
||||
|
||||
class ShareModel(BaseModel):
|
||||
"""A public document share."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
id: str
|
||||
token: str = Field(description="Opaque share token")
|
||||
vault: str
|
||||
path: str
|
||||
url: str | None = Field(default=None, description="Relative public URL (/s/{token})")
|
||||
created_by: str | None = None
|
||||
created_at: str | None = None
|
||||
expires_at: str | None = None
|
||||
access_count: int = 0
|
||||
last_accessed: str | None = None
|
||||
|
||||
|
||||
class ConflictEntry(BaseModel):
|
||||
"""A Syncthing sync-conflict file."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
vault: str
|
||||
path: str
|
||||
original_path: str | None = None
|
||||
|
||||
|
||||
class ConflictsResponse(BaseModel):
|
||||
"""Response for ``GET /api/conflicts``."""
|
||||
|
||||
conflicts: list[ConflictEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class ConflictResolveResponse(BaseModel):
|
||||
"""Response for ``POST /api/conflicts/resolve``."""
|
||||
|
||||
status: str = Field(default="resolved")
|
||||
action: str | None = Field(default=None, description="'keep_local' or 'keep_conflict'")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AI status & BooksLM context
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class AIProviderStatus(BaseModel):
|
||||
"""Availability of a single AI provider."""
|
||||
|
||||
available: bool
|
||||
model: str | None = Field(default=None, description="Default model when the provider is configured")
|
||||
|
||||
|
||||
class AIAutocompleteStatus(BaseModel):
|
||||
"""Status of the local Ollama autocomplete backend."""
|
||||
|
||||
available: bool = False
|
||||
server_ok: bool = False
|
||||
model_loaded: bool = False
|
||||
model: str = ""
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class AIStatusResponse(BaseModel):
|
||||
"""Response for ``GET /api/ai/status``."""
|
||||
|
||||
configured: bool = Field(description="True when at least one provider has an API key")
|
||||
default_provider: str
|
||||
providers: dict[str, AIProviderStatus]
|
||||
autocomplete: AIAutocompleteStatus
|
||||
|
||||
|
||||
class BooksLMContextFile(BaseModel):
|
||||
"""A single document included in the BooksLM context."""
|
||||
|
||||
path: str
|
||||
title: str
|
||||
content: str
|
||||
type: str = Field(default="markdown", description="'markdown' (and future types)")
|
||||
|
||||
|
||||
class BooksLMContextResponse(BaseModel):
|
||||
"""Response for ``POST /api/ai/bookslm/context``."""
|
||||
|
||||
files: list[BooksLMContextFile]
|
||||
total_chars: int
|
||||
file_count: int
|
||||
directory_tree: str = ""
|
||||
max_total_chars: int = Field(default=200000, description="Configured context character limit")
|
||||
max_files: int = Field(default=200, description="Configured file-count limit")
|
||||
|
||||
Reference in New Issue
Block a user