Spaces:
Sleeping

File size: 3,788 Bytes
45e7ae0
 
 
 
 
 
 
 
 
 
719c278
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
719c278
 
 
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import os
import io
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse, StreamingResponse
from sqlalchemy.orm import Session

from app.db.database import get_db
from app.core.dependencies import get_current_user
from app.models.user import User
from app.models.document import Document
from app.models.chat_message import ChatMessage
from app.services.vector_service import delete_document_vectors
from app.services.storage_service import storage_service

router = APIRouter()


@router.get("/")
def list_documents(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    documents = db.query(Document).filter(
        Document.user_id == current_user.id
    ).order_by(Document.created_at.desc()).all()

    return {
        "documents": [
            {
                "document_id": doc.id,
                "filename": doc.filename,
                "status": doc.status,
                "error_message": doc.error_message,
                "uploaded_at": doc.created_at
            }
            for doc in documents
        ]
    }


@router.get("/{document_id}/file")
def get_document_file(
    document_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    document = db.query(Document).filter(
        Document.id == document_id,
        Document.user_id == current_user.id
    ).first()

    if document is None:
        raise HTTPException(status_code=404, detail="Document not found")

    # Check if it's GCS path
    if document.file_path.startswith("uploads/"):
        content = storage_service.download_file(document.file_path)
        if not content:
            raise HTTPException(status_code=404, detail="File not found in cloud storage")
        
        return StreamingResponse(
            io.BytesIO(content),
            media_type="application/pdf",
            headers={"Content-Disposition": f"inline; filename={document.filename}"}
        )
    
    # Fallback to local
    if not document.file_path or not os.path.exists(document.file_path):
        raise HTTPException(status_code=404, detail="File not found")

    return FileResponse(
        path=document.file_path,
        media_type="application/pdf",
        filename=document.filename
    )


@router.delete("/{document_id}")
def delete_document(
    document_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    document_query = db.query(Document).filter(
        Document.id == document_id,
        Document.user_id == current_user.id
    )
    document = document_query.first()

    if document is None:
        raise HTTPException(status_code=404, detail="Document not found")

    # Delete from GCS if applicable
    if document.file_path.startswith("uploads/"):
        storage_service.delete_file(document.file_path)
    elif document.file_path and os.path.exists(document.file_path):
        os.remove(document.file_path)

    # Delete associated chat messages first
    db.query(ChatMessage).filter(ChatMessage.document_id == document_id).delete()
    
    vectors_deleted = delete_document_vectors(
        user_id=str(current_user.id),
        document_id=str(document.id)
    )

    rows_deleted = document_query.delete(synchronize_session=False)
    db.commit()

    response = {
        "message": "Document deleted successfully",
        "document_id": document_id
    }

    if rows_deleted == 0:
        response["warning"] = (
            "Document metadata was already removed before delete confirmation."
        )

    if not vectors_deleted:
        response["warning"] = (
            "Document was removed from the app, but vector cleanup could not be completed."
        )

    return response