Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

13.0 KB
Raw Blame
"""
Routes for the Zotero integration (FastAPI).

Exposes a small page plus JSON endpoints to test the connection, list the
user's Zotero collections, trigger a manual sync, and read sync status.
Credentials and options live in user settings (category ``zotero``); these
routes never accept or return the API key.

Ported from the Flask ``research_library/routes/zotero_routes.py`` blueprint
(feature #4723). ``ZoteroSyncService`` is framework-free (opens the user's
encrypted DB via ``get_user_db_session(username, password)``), so the manual
sync runs in a daemon thread that needs only ``thread_cleanup()`` — no Flask
app context.
"""

import threading

from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from loguru import logger

from ...database.session_passwords import session_password_store
from ...database.thread_local_session import thread_cleanup
from ...research_library.utils import handle_api_error
from ...research_library.zotero import (
    client_safe_zotero_message,
    ZoteroAuthError,
    ZoteroError,
    ZoteroSyncService,
    ZoteroTransientError,
)
from ...security import scrub_error
from ..dependencies.auth import require_auth
from ..template_config import templates
from typing import Annotated

router = APIRouter(prefix="/library", tags=["zotero"])


def _zotero_error_status(exc: ZoteroError) -> int:
    """Map a Zotero client error to the matching HTTP status."""
    if isinstance(exc, ZoteroAuthError):
        return 401
    if isinstance(exc, ZoteroTransientError):
        return 503
    return 400


def _zotero_error_response(exc: ZoteroError) -> JSONResponse:
    """Map a Zotero failure to a client-safe body and a status code.

    The message is never ``str(exc)``. ``client_safe_zotero_message`` looks
    the failure text up in the package's allowlist of author-written
    diagnostics and returns THAT constant, or the fallback below — so the
    guidance a user actually needs survives (the HTTP 400 "your library ID is
    a username, not the numeric ID" hint is the one Zotero misconfiguration
    that is unguessable from a generic message) while nothing exception-
    derived reaches the response.
    """
    if isinstance(exc, ZoteroAuthError):
        fallback = "Zotero authentication failed. Check the configured API key."
    elif isinstance(exc, ZoteroTransientError):
        fallback = "Zotero is temporarily unavailable. Please try again later."
    else:
        fallback = "Zotero request failed. Check the integration settings."
    # Log the text as well as the class. Every ``ZoteroError`` in the
    # research_library.zotero package is built from author-written strings
    # whose only interpolations are an HTTP status, a retry count, an item
    # count, the pagination cap or ``type(exc).__name__`` — no upstream
    # response body, no filesystem path, no API key (the client reduces a
    # transport failure to its exception TYPE before raising). So the text is
    # safe here, and it is the only server-side record of WHICH failure
    # produced a generic fallback body. It goes through ``scrub_error``
    # anyway (a no-op on this text) so this catch site matches the
    # repo-wide idiom. No traceback: this runs on the request path, where
    # the caller's frames hold the SQLCipher password.
    safe_msg = scrub_error(exc)
    logger.warning(f"Zotero request failed ({type(exc).__name__}): {safe_msg}")
    return JSONResponse(
        {"success": False, "error": client_safe_zotero_message(exc, fallback)},
        status_code=_zotero_error_status(exc),
    )


def _db_password(request: Request, username: str) -> str | None:
    """Resolve the current session's database password."""
    return session_password_store.get_session_password(
        username, request.session.get("session_id")
    )


def _session_expired_response() -> JSONResponse:
    """401 for a logged-in session whose cached DB password has expired.

    Every endpoint below opens the user's encrypted database, so without the
    password the request cannot succeed — tell the client to re-authenticate
    instead of failing with a generic 500.
    """
    return JSONResponse(
        {
            "success": False,
            "error": "Session expired — please sign in again.",
        },
        status_code=401,
    )


@router.get("/zotero")
def zotero_page(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Render the Zotero integration page."""
    return templates.TemplateResponse(
        request=request,
        name="pages/zotero.html",
        context={"active_page": "zotero"},
    )


@router.get("/api/zotero/config")
def get_config(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Return a non-secret summary of the Zotero configuration."""
    password = _db_password(request, username)  # gitleaks:allow
    if not password:
        return _session_expired_response()
    try:
        cfg = ZoteroSyncService(username, password).get_config()
        return {
            "success": True,
            "enabled": cfg.enabled,
            "configured": cfg.is_configured,
            "library_type": cfg.library_type,
            "library_id": cfg.library_id,
            "collection_keys": cfg.collection_keys,
            "import_tags": cfg.import_tags,
            "import_items_without_pdf": cfg.import_items_without_pdf,
            "import_annotations": cfg.import_annotations,
            "pdf_storage_mode": cfg.pdf_storage_mode,
            "auto_sync_enabled": cfg.auto_sync_enabled,
            "sync_interval_minutes": cfg.sync_interval_minutes,
            "use_local_api": cfg.use_local_api,
            "has_api_key": bool(cfg.api_key),
        }
    except Exception as e:
        return handle_api_error("getting Zotero config", e)


@router.post("/api/zotero/test")
def test_connection(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Validate the configured Zotero credentials."""
    password = _db_password(request, username)  # gitleaks:allow
    if not password:
        return _session_expired_response()
    try:
        result = ZoteroSyncService(username, password).test_connection()
        # Rebuild the body from an explicit key allowlist rather than
        # forwarding the service's dict: a field added to the service result
        # later (a config echo, a resolved id) would otherwise ship to the
        # browser silently. The `error` value is the service's own curated
        # text — every failure branch of `test_connection` returns either a
        # module constant from `CLIENT_SAFE_ZOTERO_MESSAGES` or its own
        # literal, and none of them is derived from an exception.
        if not result.get("success"):
            return JSONResponse(
                {
                    "success": False,
                    "error": result.get("error")
                    or (
                        "Zotero connection failed. Check the configured API "
                        "key and library settings."
                    ),
                },
                status_code=400,
            )
        return JSONResponse(
            {
                "success": True,
                "library_version": result.get("library_version"),
                "collection_count": result.get("collection_count"),
            },
            status_code=200,
        )
    except Exception as e:
        return handle_api_error("testing Zotero connection", e)


def _not_configured_response() -> JSONResponse:
    """400 when Zotero credentials aren't set.

    Endpoints that reach out to the Zotero API (rather than just reading local
    settings/state) must not surface an opaque 500 when the integration is
    simply unconfigured — that is a client-state problem, not a server error.
    Mirrors the ``is_configured`` guard in ``sync_now``.
    """
    return JSONResponse(
        {
            "success": False,
            "error": "Zotero is not enabled/configured. Set your API key "
            "and library ID in Settings first.",
        },
        status_code=400,
    )


@router.get("/api/zotero/collections")
def list_collections(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """List the user's Zotero collections (key + name)."""
    password = _db_password(request, username)  # gitleaks:allow
    if not password:
        return _session_expired_response()
    try:
        service = ZoteroSyncService(username, password)
        if not service.get_config().is_configured:
            return _not_configured_response()
        return {"success": True, "collections": service.list_collections()}
    except ZoteroError as e:
        return _zotero_error_response(e)
    except Exception as e:
        return handle_api_error("listing Zotero collections", e)


@router.get("/api/zotero/groups")
def list_groups(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """List the groups the configured API key can access (id + name)."""
    password = _db_password(request, username)  # gitleaks:allow
    if not password:
        return _session_expired_response()
    try:
        service = ZoteroSyncService(username, password)
        if not service.get_config().is_configured:
            return _not_configured_response()
        return {"success": True, "groups": service.list_groups()}
    except ZoteroError as e:
        return _zotero_error_response(e)
    except Exception as e:
        return handle_api_error("listing Zotero groups", e)


@router.post("/api/zotero/sync")
def sync_now(request: Request, username: Annotated[str, Depends(require_auth)]):
    """Trigger a background sync of the configured collections.

    Runs in a daemon thread using the current session's password and returns
    immediately. Progress is observable via the ``/api/zotero/status``
    endpoint.
    """
    password = _db_password(request, username)  # gitleaks:allow
    if not password:
        return _session_expired_response()

    try:
        cfg = ZoteroSyncService(username, password).get_config()
    except Exception as e:
        return handle_api_error("starting Zotero sync", e)
    if not cfg.is_configured:
        return JSONResponse(
            {
                "success": False,
                "error": "Zotero is not enabled/configured. Set your API key "
                "and library ID in Settings first.",
            },
            status_code=400,
        )

    # Fast feedback if a sync (manual OR scheduled) is already in flight.
    # The authoritative guard is the per-user lock inside sync_all(), which
    # serialises both entry points; this is just a best-effort early exit.
    if ZoteroSyncService.is_user_syncing(username):
        return {
            "success": True,
            "message": "A Zotero sync is already running.",
            "already_running": True,
        }

    def _run():
        # thread_cleanup() releases the thread-local DB session + cached
        # credentials when this daemon thread exits — without it each manual
        # sync would strand a pooled connection and the plaintext password.
        with thread_cleanup():
            try:
                # Manual syncs re-examine previously skipped items so settings
                # changes apply without waiting for the items to change in
                # Zotero (scheduled syncs stay cheap).
                result = ZoteroSyncService(username, password).sync_all(
                    reprocess_skipped=True
                )
                logger.info(f"Zotero manual sync finished: {result}")
            except Exception as exc:
                # Not logger.exception: this closure's own `password` and
                # the sync code's `cfg.api_key` are both live further down
                # this call stack, and an attached traceback would render
                # them under loguru's diagnose. Same pattern as
                # ZoteroSyncService._sync_one's bare-Exception arm
                # (sync_service.py) -- scrub the known secrets into a local,
                # then log without the traceback chain.
                safe_msg = scrub_error(exc, password, cfg.api_key)
                logger.warning(f"Zotero manual sync failed: {safe_msg}")

    threading.Thread(
        target=_run, name=f"zotero-sync-{username}", daemon=True
    ).start()
    return {"success": True, "message": "Zotero sync started."}


@router.get("/api/zotero/status")
def get_status(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Return stored sync state for all configured collections."""
    password = _db_password(request, username)  # gitleaks:allow
    if not password:
        return _session_expired_response()
    try:
        status = ZoteroSyncService(username, password).get_status()
        return {
            "success": True,
            "collections": status,
            # Live counters while a sync runs (None when idle) — lets the
            # page render a real progress bar during long imports.
            "progress": ZoteroSyncService.get_sync_progress(username),
        }
    except Exception as e:
        return handle_api_error("getting Zotero status", e)