- Add /documents router with webhook, upload, search, health endpoints - Create DocumentSyncService for indexing documents to vectors/graph - Add PaperlessClient for REST API integration - Configure dependency injection for Paperless client - Add document models for webhook payloads and responses - Event-driven architecture via Paperless workflow webhooks 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
489 lines
16 KiB
Python
489 lines
16 KiB
Python
"""
|
|
Paperless-ngx API client for Library Desk.
|
|
|
|
Provides async document management via Paperless-ngx:
|
|
- Document upload and retrieval
|
|
- Search and filtering
|
|
- Custom field management
|
|
- Task status tracking
|
|
"""
|
|
|
|
import httpx
|
|
from typing import Optional, List, Dict, Any
|
|
from dataclasses import dataclass
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@dataclass
|
|
class PaperlessDocument:
|
|
"""Represents a document from Paperless-ngx."""
|
|
id: int
|
|
title: str
|
|
content: str
|
|
created: Optional[str] = None
|
|
modified: Optional[str] = None
|
|
added: Optional[str] = None
|
|
correspondent: Optional[int] = None
|
|
document_type: Optional[int] = None
|
|
storage_path: Optional[int] = None
|
|
tags: List[int] = None
|
|
archive_serial_number: Optional[int] = None
|
|
original_file_name: Optional[str] = None
|
|
archived_file_name: Optional[str] = None
|
|
custom_fields: List[Dict[str, Any]] = None
|
|
|
|
def __post_init__(self):
|
|
if self.tags is None:
|
|
self.tags = []
|
|
if self.custom_fields is None:
|
|
self.custom_fields = []
|
|
|
|
|
|
@dataclass
|
|
class SearchHit:
|
|
"""Search result with relevance info."""
|
|
document: PaperlessDocument
|
|
score: float
|
|
rank: int
|
|
highlights: Optional[str] = None
|
|
|
|
|
|
class PaperlessClient:
|
|
"""
|
|
Paperless-ngx REST API client.
|
|
|
|
Documentation: https://docs.paperless-ngx.com/api/
|
|
"""
|
|
|
|
def __init__(self, base_url: str, token: str, timeout: int = 30):
|
|
"""
|
|
Initialize Paperless-ngx client.
|
|
|
|
Args:
|
|
base_url: Paperless-ngx base URL (e.g., "http://paperless:8000")
|
|
token: API token for authentication
|
|
timeout: Request timeout in seconds
|
|
"""
|
|
self.base_url = base_url.rstrip("/")
|
|
self.api_url = f"{self.base_url}/api"
|
|
self.headers = {
|
|
"Authorization": f"Token {token}",
|
|
"Accept": "application/json",
|
|
}
|
|
self.client = httpx.AsyncClient(timeout=float(timeout), headers=self.headers)
|
|
logger.info(f"Initialized Paperless client: {base_url}")
|
|
|
|
async def close(self):
|
|
"""Close HTTP client."""
|
|
await self.client.aclose()
|
|
|
|
# =========================================================================
|
|
# Document Operations
|
|
# =========================================================================
|
|
|
|
async def get_document(self, document_id: int) -> Optional[PaperlessDocument]:
|
|
"""
|
|
Get a document by ID.
|
|
|
|
Args:
|
|
document_id: Paperless document ID
|
|
|
|
Returns:
|
|
PaperlessDocument or None if not found
|
|
"""
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/documents/{document_id}/")
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
return self._parse_document(data)
|
|
except httpx.HTTPStatusError as e:
|
|
if e.response.status_code == 404:
|
|
return None
|
|
logger.error(f"Failed to get document {document_id}: {e}")
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Failed to get document {document_id}: {e}")
|
|
raise
|
|
|
|
async def get_document_content(self, document_id: int) -> Optional[str]:
|
|
"""
|
|
Get extracted text content of a document.
|
|
|
|
Args:
|
|
document_id: Paperless document ID
|
|
|
|
Returns:
|
|
Text content or None if not found
|
|
"""
|
|
doc = await self.get_document(document_id)
|
|
return doc.content if doc else None
|
|
|
|
async def list_documents(
|
|
self,
|
|
page: int = 1,
|
|
page_size: int = 25,
|
|
ordering: str = "-added",
|
|
correspondent: Optional[int] = None,
|
|
document_type: Optional[int] = None,
|
|
tags: Optional[List[int]] = None,
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
List documents with pagination and filtering.
|
|
|
|
Args:
|
|
page: Page number (starts at 1)
|
|
page_size: Results per page
|
|
ordering: Sort order (prefix with - for descending)
|
|
correspondent: Filter by correspondent ID
|
|
document_type: Filter by document type ID
|
|
tags: Filter by tag IDs
|
|
|
|
Returns:
|
|
Paginated response with count, next, previous, results
|
|
"""
|
|
params = {
|
|
"page": page,
|
|
"page_size": page_size,
|
|
"ordering": ordering,
|
|
}
|
|
if correspondent:
|
|
params["correspondent__id"] = correspondent
|
|
if document_type:
|
|
params["document_type__id"] = document_type
|
|
if tags:
|
|
params["tags__id__in"] = ",".join(str(t) for t in tags)
|
|
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/documents/", params=params)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
return {
|
|
"count": data.get("count", 0),
|
|
"next": data.get("next"),
|
|
"previous": data.get("previous"),
|
|
"results": [self._parse_document(d) for d in data.get("results", [])],
|
|
}
|
|
except Exception as e:
|
|
logger.error(f"Failed to list documents: {e}")
|
|
raise
|
|
|
|
async def search_documents(
|
|
self,
|
|
query: str,
|
|
page: int = 1,
|
|
page_size: int = 25,
|
|
) -> List[SearchHit]:
|
|
"""
|
|
Full-text search documents.
|
|
|
|
Args:
|
|
query: Search query string
|
|
page: Page number
|
|
page_size: Results per page
|
|
|
|
Returns:
|
|
List of SearchHit with document and relevance info
|
|
"""
|
|
params = {
|
|
"query": query,
|
|
"page": page,
|
|
"page_size": page_size,
|
|
}
|
|
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/documents/", params=params)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
|
|
results = []
|
|
for item in data.get("results", []):
|
|
doc = self._parse_document(item)
|
|
hit_info = item.get("__search_hit__", {})
|
|
results.append(SearchHit(
|
|
document=doc,
|
|
score=hit_info.get("score", 0.0),
|
|
rank=hit_info.get("rank", 0),
|
|
highlights=hit_info.get("highlights"),
|
|
))
|
|
return results
|
|
except Exception as e:
|
|
logger.error(f"Search failed for '{query}': {e}")
|
|
raise
|
|
|
|
async def upload_document(
|
|
self,
|
|
file_content: bytes,
|
|
filename: str,
|
|
title: Optional[str] = None,
|
|
correspondent: Optional[int] = None,
|
|
document_type: Optional[int] = None,
|
|
tags: Optional[List[int]] = None,
|
|
custom_fields: Optional[List[Dict[str, Any]]] = None,
|
|
) -> str:
|
|
"""
|
|
Upload a document to Paperless-ngx.
|
|
|
|
Args:
|
|
file_content: File bytes
|
|
filename: Original filename
|
|
title: Document title (optional, derived from filename if not set)
|
|
correspondent: Correspondent ID
|
|
document_type: Document type ID
|
|
tags: List of tag IDs
|
|
custom_fields: List of custom field values
|
|
|
|
Returns:
|
|
Task UUID for tracking consumption status
|
|
"""
|
|
files = {"document": (filename, file_content)}
|
|
data = {}
|
|
|
|
if title:
|
|
data["title"] = title
|
|
if correspondent:
|
|
data["correspondent"] = correspondent
|
|
if document_type:
|
|
data["document_type"] = document_type
|
|
if tags:
|
|
# Tags need to be sent multiple times for multiple values
|
|
data["tags"] = tags
|
|
if custom_fields:
|
|
data["custom_fields"] = custom_fields
|
|
|
|
try:
|
|
response = await self.client.post(
|
|
f"{self.api_url}/documents/post_document/",
|
|
files=files,
|
|
data=data,
|
|
)
|
|
response.raise_for_status()
|
|
result = response.json()
|
|
task_id = result.get("task_id", "")
|
|
logger.info(f"Uploaded document '{filename}', task_id: {task_id}")
|
|
return task_id
|
|
except Exception as e:
|
|
logger.error(f"Failed to upload document '{filename}': {e}")
|
|
raise
|
|
|
|
async def get_task_status(self, task_id: str) -> Dict[str, Any]:
|
|
"""
|
|
Get status of a consumption task.
|
|
|
|
Args:
|
|
task_id: Task UUID from upload
|
|
|
|
Returns:
|
|
Task status with state, result, etc.
|
|
"""
|
|
try:
|
|
response = await self.client.get(
|
|
f"{self.api_url}/tasks/",
|
|
params={"task_id": task_id},
|
|
)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
results = data.get("results", [])
|
|
if results:
|
|
return results[0]
|
|
return {"status": "NOT_FOUND"}
|
|
except Exception as e:
|
|
logger.error(f"Failed to get task status {task_id}: {e}")
|
|
raise
|
|
|
|
async def update_document(
|
|
self,
|
|
document_id: int,
|
|
title: Optional[str] = None,
|
|
correspondent: Optional[int] = None,
|
|
document_type: Optional[int] = None,
|
|
tags: Optional[List[int]] = None,
|
|
custom_fields: Optional[List[Dict[str, Any]]] = None,
|
|
) -> PaperlessDocument:
|
|
"""
|
|
Update a document's metadata.
|
|
|
|
Args:
|
|
document_id: Document ID to update
|
|
title: New title
|
|
correspondent: New correspondent ID
|
|
document_type: New document type ID
|
|
tags: New tag IDs (replaces existing)
|
|
custom_fields: New custom field values
|
|
|
|
Returns:
|
|
Updated document
|
|
"""
|
|
data = {}
|
|
if title is not None:
|
|
data["title"] = title
|
|
if correspondent is not None:
|
|
data["correspondent"] = correspondent
|
|
if document_type is not None:
|
|
data["document_type"] = document_type
|
|
if tags is not None:
|
|
data["tags"] = tags
|
|
if custom_fields is not None:
|
|
data["custom_fields"] = custom_fields
|
|
|
|
try:
|
|
response = await self.client.patch(
|
|
f"{self.api_url}/documents/{document_id}/",
|
|
json=data,
|
|
)
|
|
response.raise_for_status()
|
|
return self._parse_document(response.json())
|
|
except Exception as e:
|
|
logger.error(f"Failed to update document {document_id}: {e}")
|
|
raise
|
|
|
|
# =========================================================================
|
|
# Custom Fields
|
|
# =========================================================================
|
|
|
|
async def list_custom_fields(self) -> List[Dict[str, Any]]:
|
|
"""
|
|
List all custom fields.
|
|
|
|
Returns:
|
|
List of custom field definitions
|
|
"""
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/custom_fields/")
|
|
response.raise_for_status()
|
|
return response.json().get("results", [])
|
|
except Exception as e:
|
|
logger.error(f"Failed to list custom fields: {e}")
|
|
raise
|
|
|
|
async def get_custom_field_by_name(self, name: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Get a custom field by name.
|
|
|
|
Args:
|
|
name: Custom field name
|
|
|
|
Returns:
|
|
Custom field definition or None
|
|
"""
|
|
fields = await self.list_custom_fields()
|
|
for field in fields:
|
|
if field.get("name") == name:
|
|
return field
|
|
return None
|
|
|
|
# =========================================================================
|
|
# Tags, Correspondents, Document Types
|
|
# =========================================================================
|
|
|
|
async def list_tags(self) -> List[Dict[str, Any]]:
|
|
"""List all tags."""
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/tags/")
|
|
response.raise_for_status()
|
|
return response.json().get("results", [])
|
|
except Exception as e:
|
|
logger.error(f"Failed to list tags: {e}")
|
|
raise
|
|
|
|
async def list_correspondents(self) -> List[Dict[str, Any]]:
|
|
"""List all correspondents."""
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/correspondents/")
|
|
response.raise_for_status()
|
|
return response.json().get("results", [])
|
|
except Exception as e:
|
|
logger.error(f"Failed to list correspondents: {e}")
|
|
raise
|
|
|
|
async def list_document_types(self) -> List[Dict[str, Any]]:
|
|
"""List all document types."""
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/document_types/")
|
|
response.raise_for_status()
|
|
return response.json().get("results", [])
|
|
except Exception as e:
|
|
logger.error(f"Failed to list document types: {e}")
|
|
raise
|
|
|
|
# =========================================================================
|
|
# Bulk Operations
|
|
# =========================================================================
|
|
|
|
async def bulk_edit(
|
|
self,
|
|
document_ids: List[int],
|
|
method: str,
|
|
parameters: Optional[Dict[str, Any]] = None,
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Bulk edit documents.
|
|
|
|
Args:
|
|
document_ids: List of document IDs
|
|
method: Operation (add_tag, remove_tag, set_correspondent, etc.)
|
|
parameters: Operation parameters
|
|
|
|
Returns:
|
|
Operation result
|
|
"""
|
|
data = {
|
|
"documents": document_ids,
|
|
"method": method,
|
|
}
|
|
if parameters:
|
|
data["parameters"] = parameters
|
|
|
|
try:
|
|
response = await self.client.post(
|
|
f"{self.api_url}/documents/bulk_edit/",
|
|
json=data,
|
|
)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except Exception as e:
|
|
logger.error(f"Bulk edit failed: {e}")
|
|
raise
|
|
|
|
# =========================================================================
|
|
# Health Check
|
|
# =========================================================================
|
|
|
|
async def health_check(self) -> bool:
|
|
"""
|
|
Check if Paperless-ngx is responding.
|
|
|
|
Returns:
|
|
True if service is healthy
|
|
"""
|
|
try:
|
|
response = await self.client.get(f"{self.api_url}/", timeout=5.0)
|
|
return response.status_code < 400
|
|
except Exception as e:
|
|
logger.error(f"Paperless health check failed: {e}")
|
|
return False
|
|
|
|
# =========================================================================
|
|
# Helpers
|
|
# =========================================================================
|
|
|
|
def _parse_document(self, data: Dict[str, Any]) -> PaperlessDocument:
|
|
"""Parse API response into PaperlessDocument."""
|
|
return PaperlessDocument(
|
|
id=data.get("id", 0),
|
|
title=data.get("title", ""),
|
|
content=data.get("content", ""),
|
|
created=data.get("created"),
|
|
modified=data.get("modified"),
|
|
added=data.get("added"),
|
|
correspondent=data.get("correspondent"),
|
|
document_type=data.get("document_type"),
|
|
storage_path=data.get("storage_path"),
|
|
tags=data.get("tags", []),
|
|
archive_serial_number=data.get("archive_serial_number"),
|
|
original_file_name=data.get("original_file_name"),
|
|
archived_file_name=data.get("archived_file_name"),
|
|
custom_fields=data.get("custom_fields", []),
|
|
)
|