|
| 1 | +""" |
| 2 | +Editor routes for BlockNote document editing. |
| 3 | +""" |
| 4 | + |
| 5 | +from datetime import UTC, datetime |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from fastapi import APIRouter, Depends, HTTPException |
| 9 | +from sqlalchemy import select |
| 10 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 11 | + |
| 12 | +from app.db import Document, SearchSpace, User, get_async_session |
| 13 | +from app.users import current_active_user |
| 14 | + |
| 15 | +router = APIRouter() |
| 16 | + |
| 17 | + |
| 18 | +@router.get("/documents/{document_id}/editor-content") |
| 19 | +async def get_editor_content( |
| 20 | + document_id: int, |
| 21 | + session: AsyncSession = Depends(get_async_session), |
| 22 | + user: User = Depends(current_active_user), |
| 23 | +): |
| 24 | + """ |
| 25 | + Get document content for editing. |
| 26 | +
|
| 27 | + Returns BlockNote JSON document. If blocknote_document is NULL, |
| 28 | + attempts to generate it from chunks (lazy migration). |
| 29 | + """ |
| 30 | + from sqlalchemy.orm import selectinload |
| 31 | + |
| 32 | + result = await session.execute( |
| 33 | + select(Document) |
| 34 | + .options(selectinload(Document.chunks)) |
| 35 | + .join(SearchSpace) |
| 36 | + .filter(Document.id == document_id, SearchSpace.user_id == user.id) |
| 37 | + ) |
| 38 | + document = result.scalars().first() |
| 39 | + |
| 40 | + if not document: |
| 41 | + raise HTTPException(status_code=404, detail="Document not found") |
| 42 | + |
| 43 | + # If blocknote_document exists, return it |
| 44 | + if document.blocknote_document: |
| 45 | + return { |
| 46 | + "document_id": document.id, |
| 47 | + "title": document.title, |
| 48 | + "blocknote_document": document.blocknote_document, |
| 49 | + "last_edited_at": document.last_edited_at.isoformat() |
| 50 | + if document.last_edited_at |
| 51 | + else None, |
| 52 | + } |
| 53 | + |
| 54 | + # Lazy migration: Try to generate blocknote_document from chunks |
| 55 | + from app.utils.blocknote_converter import convert_markdown_to_blocknote |
| 56 | + |
| 57 | + chunks = sorted(document.chunks, key=lambda c: c.id) |
| 58 | + |
| 59 | + if not chunks: |
| 60 | + raise HTTPException( |
| 61 | + status_code=400, |
| 62 | + detail="This document has no chunks and cannot be edited. Please re-upload to enable editing.", |
| 63 | + ) |
| 64 | + |
| 65 | + # Reconstruct markdown from chunks |
| 66 | + markdown_content = "\n\n".join(chunk.content for chunk in chunks) |
| 67 | + |
| 68 | + if not markdown_content.strip(): |
| 69 | + raise HTTPException( |
| 70 | + status_code=400, |
| 71 | + detail="This document has empty content and cannot be edited.", |
| 72 | + ) |
| 73 | + |
| 74 | + # Convert to BlockNote |
| 75 | + blocknote_json = await convert_markdown_to_blocknote(markdown_content) |
| 76 | + |
| 77 | + if not blocknote_json: |
| 78 | + raise HTTPException( |
| 79 | + status_code=500, |
| 80 | + detail="Failed to convert document to editable format. Please try again later.", |
| 81 | + ) |
| 82 | + |
| 83 | + # Save the generated blocknote_document (lazy migration) |
| 84 | + document.blocknote_document = blocknote_json |
| 85 | + document.content_needs_reindexing = False |
| 86 | + document.last_edited_at = None |
| 87 | + await session.commit() |
| 88 | + |
| 89 | + return { |
| 90 | + "document_id": document.id, |
| 91 | + "title": document.title, |
| 92 | + "blocknote_document": blocknote_json, |
| 93 | + "last_edited_at": None, |
| 94 | + } |
| 95 | + |
| 96 | + |
| 97 | +@router.post("/documents/{document_id}/save") |
| 98 | +async def save_document( |
| 99 | + document_id: int, |
| 100 | + data: dict[str, Any], |
| 101 | + session: AsyncSession = Depends(get_async_session), |
| 102 | + user: User = Depends(current_active_user), |
| 103 | +): |
| 104 | + """ |
| 105 | + Save BlockNote document and trigger reindexing. |
| 106 | + Called when user clicks 'Save & Exit'. |
| 107 | + """ |
| 108 | + from app.tasks.celery_tasks.document_reindex_tasks import reindex_document_task |
| 109 | + |
| 110 | + # Verify ownership |
| 111 | + result = await session.execute( |
| 112 | + select(Document) |
| 113 | + .join(SearchSpace) |
| 114 | + .filter(Document.id == document_id, SearchSpace.user_id == user.id) |
| 115 | + ) |
| 116 | + document = result.scalars().first() |
| 117 | + |
| 118 | + if not document: |
| 119 | + raise HTTPException(status_code=404, detail="Document not found") |
| 120 | + |
| 121 | + blocknote_document = data.get("blocknote_document") |
| 122 | + if not blocknote_document: |
| 123 | + raise HTTPException(status_code=400, detail="blocknote_document is required") |
| 124 | + |
| 125 | + # Save BlockNote document |
| 126 | + document.blocknote_document = blocknote_document |
| 127 | + document.last_edited_at = datetime.now(UTC) |
| 128 | + document.content_needs_reindexing = True |
| 129 | + |
| 130 | + await session.commit() |
| 131 | + |
| 132 | + # Queue reindex task |
| 133 | + reindex_document_task.delay(document_id, str(user.id)) |
| 134 | + |
| 135 | + return { |
| 136 | + "status": "saved", |
| 137 | + "document_id": document_id, |
| 138 | + "message": "Document saved and will be reindexed in the background", |
| 139 | + "last_edited_at": document.last_edited_at.isoformat(), |
| 140 | + } |
0 commit comments