89 lines
3.9 KiB
Python
89 lines
3.9 KiB
Python
|
|
"""GET /descargas/{id}?u=&exp=&sig= — valida el enlace firmado, busca la ruta en Elasticsearch,
|
||
|
|
registra y entrega el archivo desde el disco."""
|
||
|
|
import logging
|
||
|
|
import mimetypes
|
||
|
|
from urllib.parse import quote
|
||
|
|
|
||
|
|
from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request, Response
|
||
|
|
from fastapi.responses import FileResponse, StreamingResponse
|
||
|
|
from sqlalchemy.orm import Session
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
from app.database import get_db
|
||
|
|
from app import elastic
|
||
|
|
from app.busqueda import a_ruta_relativa
|
||
|
|
from app.models import LogDescarga
|
||
|
|
from app.security import validar_firma
|
||
|
|
from app.storage import LocalFileSystemBackend, get_storage
|
||
|
|
|
||
|
|
router = APIRouter(tags=["descargas"])
|
||
|
|
log = logging.getLogger("api")
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/descargas/{archivo_id}")
|
||
|
|
def descargar(
|
||
|
|
request: Request,
|
||
|
|
archivo_id: str = Path(..., max_length=128),
|
||
|
|
u: str = Query(..., max_length=100),
|
||
|
|
exp: int = Query(...),
|
||
|
|
sig: str = Query(..., max_length=100),
|
||
|
|
db: Session = Depends(get_db),
|
||
|
|
):
|
||
|
|
# 1) El enlace tiene que ser auténtico y estar vigente
|
||
|
|
validar_firma(archivo_id, u, exp, sig)
|
||
|
|
|
||
|
|
# 2) El documento tiene que existir en Elasticsearch: de ahí sale la ruta real
|
||
|
|
# (nunca de la URL, así nadie puede pedir otra ruta cambiando el enlace)
|
||
|
|
try:
|
||
|
|
doc = elastic.obtener(archivo_id, ["file.filename", "path.virtual"])
|
||
|
|
except elastic.ElasticError:
|
||
|
|
log.exception("Elasticsearch no disponible al descargar %s", archivo_id)
|
||
|
|
raise HTTPException(503, "El buscador no está disponible en este momento")
|
||
|
|
ruta_relativa = a_ruta_relativa((doc or {}).get("path", {}).get("virtual", ""))
|
||
|
|
if not doc or not ruta_relativa:
|
||
|
|
raise HTTPException(404, "Archivo no encontrado")
|
||
|
|
nombre_archivo = doc.get("file", {}).get("filename") or ruta_relativa.rsplit("/", 1)[-1]
|
||
|
|
|
||
|
|
# 3) Y seguir existiendo en disco (pudo borrarse después de la última pasada de FSCrawler)
|
||
|
|
try:
|
||
|
|
storage = get_storage()
|
||
|
|
existe = storage.existe(ruta_relativa)
|
||
|
|
except Exception: # noqa: BLE001 - carpeta no montada, disco no disponible
|
||
|
|
log.exception("Almacenamiento no disponible al descargar %s", ruta_relativa)
|
||
|
|
raise HTTPException(503, "El almacenamiento de archivos no está disponible en este momento")
|
||
|
|
if not existe:
|
||
|
|
raise HTTPException(404, "Archivo no encontrado (puede que se haya movido o borrado)")
|
||
|
|
if any(ruta_relativa == c or ruta_relativa.startswith(c + "/") for c in get_settings().carpetas_excluidas):
|
||
|
|
raise HTTPException(404, "Archivo no encontrado")
|
||
|
|
|
||
|
|
# 4) Log
|
||
|
|
ip = request.client.host if request.client else ""
|
||
|
|
db.add(LogDescarga(usuario=u, documento_id=archivo_id, ruta_relativa=ruta_relativa, ip=ip))
|
||
|
|
db.commit()
|
||
|
|
log.info("DESCARGA usuario=%s archivo=%s ip=%s", u, ruta_relativa, ip)
|
||
|
|
|
||
|
|
s = get_settings()
|
||
|
|
if s.download_mode == "nginx":
|
||
|
|
# FastAPI solo autoriza; Nginx lee el archivo del disco/NAS y lo envía (más eficiente)
|
||
|
|
interno = s.nginx_internal_prefix.rstrip("/") + "/" + quote(ruta_relativa)
|
||
|
|
return Response(
|
||
|
|
headers={
|
||
|
|
"X-Accel-Redirect": interno,
|
||
|
|
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(nombre_archivo)}",
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
# Modo direct con carpeta local: FastAPI envía el archivo desde el disco
|
||
|
|
if isinstance(storage, LocalFileSystemBackend):
|
||
|
|
return FileResponse(storage.ruta_absoluta(ruta_relativa), filename=nombre_archivo)
|
||
|
|
|
||
|
|
# Modo direct con SMB: se lee del servidor SMB en bloques y se reenvía al navegador
|
||
|
|
tipo = mimetypes.guess_type(nombre_archivo)[0] or "application/octet-stream"
|
||
|
|
return StreamingResponse(
|
||
|
|
storage.iterar_bytes(ruta_relativa),
|
||
|
|
media_type=tipo,
|
||
|
|
headers={
|
||
|
|
"Content-Length": str(storage.tamano(ruta_relativa)),
|
||
|
|
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(nombre_archivo)}",
|
||
|
|
},
|
||
|
|
)
|