Estructura inicial funcional con documentación en el README.md de la FastAPI
This commit is contained in:
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
170
app/busqueda.py
Normal file
170
app/busqueda.py
Normal file
@@ -0,0 +1,170 @@
|
||||
"""Búsqueda por contenido en Elasticsearch (índice que arma FSCrawler).
|
||||
|
||||
Reglas (las mismas que antes, ahora como consulta de Elasticsearch):
|
||||
- Cédula: con o sin puntos ("1234567", "1.234.567", "1,234,567") en el contenido,
|
||||
o dentro de la ruta/nombre del archivo.
|
||||
- Nombre, en cualquier orden:
|
||||
* completo: aparecen TODOS los nombres y apellidos cerca entre sí.
|
||||
* parcial: aparecen el primer nombre y el primer apellido juntos ("Juan Pérez", "Pérez, Juan").
|
||||
|
||||
Orden de los resultados: cédula + nombre > cédula > nombre completo > nombre parcial,
|
||||
y dentro de cada grupo, el archivo modificado más recientemente primero.
|
||||
|
||||
Campos que usa (los que genera FSCrawler): content, file.filename, file.extension,
|
||||
file.filesize, file.last_modified, path.virtual.
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from app import elastic
|
||||
from app.config import get_settings
|
||||
from app.utils import normalizar, solo_digitos
|
||||
|
||||
DISTANCIA_COMPLETO = 6 # máximo de palabras entre nombres/apellidos para "completo"
|
||||
DISTANCIA_PARCIAL = 2 # "Juan Pérez", "Pérez, Juan", "Juan C. Pérez"
|
||||
|
||||
# Puntaje fijo por tipo de coincidencia: define el orden sin depender de la relevancia
|
||||
PESO_CEDULA, PESO_COMPLETO, PESO_PARCIAL = 1000, 100, 10
|
||||
|
||||
CAMPOS = ["file.filename", "file.extension", "file.filesize", "file.last_modified", "path.virtual"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Palabra:
|
||||
original: str # como la escribió el usuario, en minúsculas ("pérez")
|
||||
normal: str # sin tildes ("perez")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Coincidencia:
|
||||
doc_id: str
|
||||
nombre: str
|
||||
ruta_relativa: str
|
||||
carpeta: str
|
||||
extension: str
|
||||
tamano_bytes: int
|
||||
modificado_en: datetime | None
|
||||
coincide_cedula: bool
|
||||
coincide_nombre: str | None # "completo" | "parcial" | None
|
||||
fragmento: str
|
||||
|
||||
|
||||
def _palabras(texto: str | None) -> list[Palabra]:
|
||||
# Solo letras y números: el texto del usuario nunca llega crudo a la consulta
|
||||
return [Palabra(p, normalizar(p)) for p in re.split(r"[^\w]+", (texto or "").lower().replace("_", " ")) if p]
|
||||
|
||||
|
||||
def validar(cedula: str | None, nombres: str | None,
|
||||
apellidos: str | None) -> tuple[str, list[Palabra], list[Palabra]]:
|
||||
"""Devuelve (cedula_limpia, palabras_nombres, palabras_apellidos) o lanza ValueError."""
|
||||
ced = solo_digitos(cedula or "")
|
||||
if cedula and len(ced) < 5:
|
||||
raise ValueError("La cédula debe tener al menos 5 dígitos")
|
||||
nom, ape = _palabras(nombres), _palabras(apellidos)
|
||||
if (nom and not ape) or (ape and not nom):
|
||||
raise ValueError("Para buscar por nombre enviá nombres y apellidos juntos")
|
||||
if not ced and not nom:
|
||||
raise ValueError("Enviá la cédula, o nombres y apellidos (o los tres)")
|
||||
return ced, nom, ape
|
||||
|
||||
|
||||
def variantes_cedula(cedula: str) -> list[str]:
|
||||
"""'1234567' -> ['1234567', '1.234.567', '1,234,567'].
|
||||
Elasticsearch guarda "1.234.567" como una sola palabra, por eso se buscan las tres formas."""
|
||||
grupos, resto = [], cedula
|
||||
while len(resto) > 3:
|
||||
grupos.insert(0, resto[-3:])
|
||||
resto = resto[:-3]
|
||||
grupos.insert(0, resto)
|
||||
return list(dict.fromkeys([cedula, ".".join(grupos), ",".join(grupos)]))
|
||||
|
||||
|
||||
def _regla(p: Palabra) -> dict:
|
||||
"""Busca la palabra con y sin tilde. Si el índice ya ignora tildes (asciifolding),
|
||||
las dos formas dan lo mismo; si no, al menos coincide lo que se escribió igual."""
|
||||
if p.original == p.normal:
|
||||
return {"match": {"query": p.normal}}
|
||||
return {"any_of": {"intervals": [{"match": {"query": p.original}}, {"match": {"query": p.normal}}]}}
|
||||
|
||||
|
||||
def _cerca(palabras: list[Palabra], distancia: int) -> dict:
|
||||
return {"intervals": {"content": {"all_of": {
|
||||
"ordered": False, "max_gaps": distancia, "intervals": [_regla(p) for p in palabras]}}}}
|
||||
|
||||
|
||||
def armar_consulta(cedula: str, nombres: list[Palabra], apellidos: list[Palabra], limite: int) -> dict:
|
||||
"""Cuerpo de la búsqueda para Elasticsearch (función aparte para poder probarla)."""
|
||||
should, resaltar = [], []
|
||||
|
||||
if cedula:
|
||||
variantes = variantes_cedula(cedula)
|
||||
filtro = {"bool": {"should": [{"match_phrase": {"content": v}} for v in variantes]
|
||||
+ [{"wildcard": {"path.virtual": {"value": f"*{cedula}*"}}}]}}
|
||||
should.append({"constant_score": {"filter": filtro, "boost": PESO_CEDULA, "_name": "cedula"}})
|
||||
resaltar += [{"match_phrase": {"content": v}} for v in variantes]
|
||||
|
||||
if nombres:
|
||||
todas = nombres + apellidos
|
||||
should.append({"constant_score": {"filter": _cerca(todas, DISTANCIA_COMPLETO),
|
||||
"boost": PESO_COMPLETO, "_name": "nombre_completo"}})
|
||||
should.append({"constant_score": {"filter": _cerca([nombres[0], apellidos[0]], DISTANCIA_PARCIAL),
|
||||
"boost": PESO_PARCIAL, "_name": "nombre_parcial"}})
|
||||
palabras = " ".join(dict.fromkeys([p.original for p in todas] + [p.normal for p in todas]))
|
||||
resaltar.append({"match": {"content": palabras}})
|
||||
|
||||
# Segunda barrera: carpetas que nunca se devuelven aunque FSCrawler las haya indexado
|
||||
excluir = [{"prefix": {"path.virtual": f"/{c}/"}} for c in get_settings().carpetas_excluidas]
|
||||
|
||||
return {
|
||||
"query": {"bool": {"should": should, "minimum_should_match": 1, "must_not": excluir}},
|
||||
"sort": ["_score", {"file.last_modified": {"order": "desc", "unmapped_type": "date"}}],
|
||||
"size": limite,
|
||||
"track_total_hits": True,
|
||||
"_source": CAMPOS, # nunca se trae "content": puede pesar megas por documento
|
||||
"highlight": {
|
||||
"pre_tags": ["«"], "post_tags": ["»"],
|
||||
"fields": {"content": {"type": "unified", "fragment_size": 160, "number_of_fragments": 1,
|
||||
"highlight_query": {"bool": {"should": resaltar}}}},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def a_ruta_relativa(path_virtual: str) -> str:
|
||||
"""FSCrawler guarda '/IPS/planilla.xlsx' relativo a la carpeta que recorre (fs.url)."""
|
||||
return path_virtual.lstrip("/")
|
||||
|
||||
|
||||
def _extension(valor: str | None) -> str:
|
||||
valor = (valor or "").lower()
|
||||
return valor if not valor or valor.startswith(".") else f".{valor}" # FSCrawler guarda "pdf"
|
||||
|
||||
|
||||
def buscar(cedula: str, nombres: list[Palabra], apellidos: list[Palabra],
|
||||
limite: int) -> tuple[list[Coincidencia], int]:
|
||||
"""Devuelve (las `limite` mejores coincidencias, total de archivos que coinciden)."""
|
||||
respuesta = elastic.buscar(armar_consulta(cedula, nombres, apellidos, limite))
|
||||
hits = respuesta.get("hits", {})
|
||||
total = hits.get("total", {})
|
||||
total = total.get("value", 0) if isinstance(total, dict) else int(total)
|
||||
|
||||
resultados = []
|
||||
for h in hits.get("hits", []):
|
||||
fuente = h.get("_source", {})
|
||||
archivo, ruta = fuente.get("file", {}), fuente.get("path", {})
|
||||
nombradas = h.get("matched_queries", []) # lista (o dict en versiones nuevas)
|
||||
ruta_rel = a_ruta_relativa(ruta.get("virtual", ""))
|
||||
resultados.append(Coincidencia(
|
||||
doc_id=h["_id"],
|
||||
nombre=archivo.get("filename") or ruta_rel.rsplit("/", 1)[-1],
|
||||
ruta_relativa=ruta_rel,
|
||||
carpeta=ruta_rel.rsplit("/", 1)[0] if "/" in ruta_rel else "",
|
||||
extension=_extension(archivo.get("extension")),
|
||||
tamano_bytes=int(archivo.get("filesize") or 0),
|
||||
modificado_en=archivo.get("last_modified"),
|
||||
coincide_cedula="cedula" in nombradas,
|
||||
coincide_nombre=("completo" if "nombre_completo" in nombradas
|
||||
else "parcial" if "nombre_parcial" in nombradas else None),
|
||||
fragmento=" ".join(" ".join(h.get("highlight", {}).get("content", [""])).split()),
|
||||
))
|
||||
return resultados, total
|
||||
107
app/config.py
Normal file
107
app/config.py
Normal file
@@ -0,0 +1,107 @@
|
||||
"""Configuración central: todo lo que cambia entre entornos sale del archivo .env."""
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic import SecretStr, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
# Almacenamiento
|
||||
# local = carpeta del servidor (disco propio o unidad montada)
|
||||
# smb = la API se conecta a un recurso compartido SMB (Samba/NAS) con usuario y clave
|
||||
storage_type: str = "local"
|
||||
storage_root: str = "./almacenamiento" # solo para storage_type=local
|
||||
|
||||
# Conexión SMB (solo para storage_type=smb)
|
||||
smb_server: str = "" # IP o nombre del servidor SMB / NAS
|
||||
smb_share: str = "" # nombre del recurso compartido
|
||||
smb_base_path: str = "" # subcarpeta dentro del recurso (opcional)
|
||||
smb_username: str = ""
|
||||
smb_password: SecretStr = SecretStr("") # SecretStr: nunca se imprime en logs ni errores
|
||||
smb_domain: str = "" # dominio o nombre del equipo si la cuenta es local
|
||||
smb_port: int = 445
|
||||
smb_encrypt: bool = True # cifra el tráfico (SMB 3)
|
||||
smb_timeout: int = 15
|
||||
# Carpetas que la API NUNCA devuelve, aunque FSCrawler las haya indexado
|
||||
# (rutas relativas a la raíz, separadas por coma). Lo ideal es excluirlas también
|
||||
# en FSCrawler (fs.excludes); esto es una segunda barrera.
|
||||
exclude_folders: str = ""
|
||||
|
||||
# Elasticsearch (lo alimenta FSCrawler)
|
||||
es_url: str = "https://localhost:9200"
|
||||
es_index: str = "archivos" # el "name" del job de FSCrawler
|
||||
es_username: str = ""
|
||||
es_password: SecretStr = SecretStr("")
|
||||
es_api_key: SecretStr = SecretStr("") # alternativa a usuario/clave
|
||||
es_ca_cert: str = "" # ruta al http_ca.crt de Elasticsearch 8 (recomendado)
|
||||
es_verify_tls: bool = True # False solo para pruebas: no verifica el certificado
|
||||
es_timeout: int = 10
|
||||
|
||||
# Base de datos (solo para los logs de búsquedas y descargas)
|
||||
database_url: str = "sqlite:///./api_archivos.db"
|
||||
|
||||
# Seguridad
|
||||
jwt_secret: str = "cambiar-este-secreto"
|
||||
jwt_algorithm: str = "HS256"
|
||||
download_secret: str = "cambiar-este-otro-secreto"
|
||||
download_link_ttl_minutes: int = 30
|
||||
allowed_roles: str = "admin,rrhh"
|
||||
|
||||
# URLs / descargas
|
||||
public_base_url: str = "http://localhost:8000"
|
||||
download_mode: str = "direct" # direct | nginx
|
||||
nginx_internal_prefix: str = "/protegido/"
|
||||
cors_origins: str = "http://localhost"
|
||||
|
||||
log_file: str = "logs/api_archivos.log"
|
||||
|
||||
@field_validator("download_mode")
|
||||
@classmethod
|
||||
def _modo_valido(cls, v: str) -> str:
|
||||
v = v.lower().strip()
|
||||
if v not in {"direct", "nginx"}:
|
||||
raise ValueError("DOWNLOAD_MODE debe ser 'direct' o 'nginx'")
|
||||
return v
|
||||
|
||||
@field_validator("storage_type")
|
||||
@classmethod
|
||||
def _tipo_valido(cls, v: str) -> str:
|
||||
v = v.lower().strip()
|
||||
if v not in {"local", "smb"}:
|
||||
raise ValueError("STORAGE_TYPE debe ser 'local' o 'smb'")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _coherencia(self) -> "Settings":
|
||||
if self.storage_type == "smb":
|
||||
faltan = [n for n in ("smb_server", "smb_share", "smb_username") if not getattr(self, n)]
|
||||
if not self.smb_password.get_secret_value():
|
||||
faltan.append("smb_password")
|
||||
if faltan:
|
||||
raise ValueError(f"Con STORAGE_TYPE=smb faltan: {', '.join(f.upper() for f in faltan)}")
|
||||
if self.download_mode == "nginx":
|
||||
# Nginx no puede leer una carpeta SMB que no está montada
|
||||
raise ValueError("DOWNLOAD_MODE=nginx no es compatible con STORAGE_TYPE=smb; usá direct")
|
||||
return self
|
||||
|
||||
# Helpers para convertir las listas separadas por coma
|
||||
@property
|
||||
def carpetas_excluidas(self) -> list[str]:
|
||||
"""'DATOS POLICIA, INFORMATICA/claves' -> ['DATOS POLICIA', 'INFORMATICA/claves']
|
||||
(se respeta mayúsculas/minúsculas: en Linux las rutas las distinguen)."""
|
||||
return [c.strip().strip("/") for c in self.exclude_folders.split(",") if c.strip()]
|
||||
|
||||
@property
|
||||
def roles_permitidos(self) -> set[str]:
|
||||
return {r.strip().lower() for r in self.allowed_roles.split(",") if r.strip()}
|
||||
|
||||
@property
|
||||
def origenes_cors(self) -> list[str]:
|
||||
return [o.strip() for o in self.cors_origins.split(",") if o.strip()]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
54
app/database.py
Normal file
54
app/database.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""Conexión a la base de datos de la API (solo logs de búsquedas y descargas).
|
||||
|
||||
La búsqueda en sí la resuelve Elasticsearch. Esta base puede ser SQLite o
|
||||
PostgreSQL: solo cambia DATABASE_URL.
|
||||
"""
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def _crear_engine():
|
||||
url = get_settings().database_url
|
||||
kwargs = {"pool_pre_ping": True}
|
||||
if url.startswith("sqlite"):
|
||||
# SQLite no permite compartir la conexión entre hilos por defecto; FastAPI usa varios.
|
||||
kwargs["connect_args"] = {"check_same_thread": False, "timeout": 30}
|
||||
eng = create_engine(url, **kwargs)
|
||||
|
||||
if url.startswith("sqlite"):
|
||||
@event.listens_for(eng, "connect")
|
||||
def _pragmas(conexion, _):
|
||||
cur = conexion.cursor()
|
||||
# WAL: varios pedidos pueden escribir logs a la vez sin bloquearse
|
||||
cur.execute("PRAGMA journal_mode=WAL")
|
||||
cur.execute("PRAGMA busy_timeout=30000")
|
||||
cur.close()
|
||||
|
||||
return eng
|
||||
|
||||
|
||||
engine = _crear_engine()
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
||||
|
||||
def init_db() -> None:
|
||||
"""Crea las tablas si no existen (para producción seria, migrar a Alembic)."""
|
||||
from app import models # noqa: F401 (registra los modelos)
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""Dependencia de FastAPI: abre una sesión por request y la cierra al terminar."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
67
app/elastic.py
Normal file
67
app/elastic.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""Cliente mínimo de Elasticsearch por HTTP (sirve para Elasticsearch 7.x y 8.x).
|
||||
|
||||
Se usa la API REST directamente con httpx en vez de la librería oficial: así no
|
||||
hay que alinear la versión de la librería con la del servidor.
|
||||
"""
|
||||
import logging
|
||||
from functools import lru_cache
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
|
||||
class ElasticError(Exception):
|
||||
"""Elasticsearch no respondió o respondió con error."""
|
||||
|
||||
|
||||
@lru_cache
|
||||
def cliente() -> httpx.Client:
|
||||
s = get_settings()
|
||||
headers = {"Content-Type": "application/json"}
|
||||
auth = None
|
||||
if s.es_api_key.get_secret_value():
|
||||
headers["Authorization"] = f"ApiKey {s.es_api_key.get_secret_value()}"
|
||||
elif s.es_username:
|
||||
auth = (s.es_username, s.es_password.get_secret_value())
|
||||
verificar = s.es_ca_cert or s.es_verify_tls # ruta al CA, o True/False
|
||||
return httpx.Client(base_url=s.es_url.rstrip("/"), headers=headers, auth=auth,
|
||||
verify=verificar, timeout=s.es_timeout)
|
||||
|
||||
|
||||
def _pedir(metodo: str, ruta: str, **kwargs) -> httpx.Response:
|
||||
try:
|
||||
r = cliente().request(metodo, ruta, **kwargs)
|
||||
except httpx.HTTPError as e:
|
||||
raise ElasticError(f"No se pudo conectar con Elasticsearch: {type(e).__name__}") from e
|
||||
if r.status_code in (401, 403):
|
||||
raise ElasticError("Elasticsearch rechazó las credenciales (revisar ES_USERNAME/ES_PASSWORD o ES_API_KEY)")
|
||||
return r
|
||||
|
||||
|
||||
def buscar(cuerpo: dict) -> dict:
|
||||
r = _pedir("POST", f"/{get_settings().es_index}/_search", json=cuerpo)
|
||||
if r.status_code != 200:
|
||||
log.error("Elasticsearch respondió %s a la búsqueda: %s", r.status_code, r.text[:500])
|
||||
raise ElasticError(f"Elasticsearch respondió {r.status_code}")
|
||||
return r.json()
|
||||
|
||||
|
||||
def obtener(doc_id: str, campos: list[str]) -> dict | None:
|
||||
"""Un documento por su id (el que genera FSCrawler), o None si no existe."""
|
||||
r = _pedir("GET", f"/{get_settings().es_index}/_doc/{quote(doc_id, safe='')}", params={"_source_includes": ",".join(campos)})
|
||||
if r.status_code == 404:
|
||||
return None
|
||||
if r.status_code != 200:
|
||||
raise ElasticError(f"Elasticsearch respondió {r.status_code}")
|
||||
return r.json().get("_source", {})
|
||||
|
||||
|
||||
def disponible() -> bool:
|
||||
try:
|
||||
return _pedir("GET", f"/{get_settings().es_index}/_count").status_code == 200
|
||||
except ElasticError:
|
||||
return False
|
||||
66
app/main.py
Normal file
66
app/main.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""Punto de entrada de la API. Ejecutar: uvicorn app.main:app --host 0.0.0.0 --port 8000"""
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import init_db
|
||||
from app.routers import archivos, descargas
|
||||
from app import elastic
|
||||
from app.storage import get_storage
|
||||
|
||||
|
||||
def configurar_logs() -> None:
|
||||
ruta = Path(get_settings().log_file)
|
||||
ruta.parent.mkdir(parents=True, exist_ok=True)
|
||||
handler = RotatingFileHandler(ruta, maxBytes=5_000_000, backupCount=5, encoding="utf-8")
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
|
||||
for nombre in ("api", "indexador"):
|
||||
logger = logging.getLogger(nombre)
|
||||
logger.setLevel(logging.INFO)
|
||||
if not logger.handlers:
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
configurar_logs()
|
||||
s = get_settings()
|
||||
if "cambiar" in s.jwt_secret or "cambiar" in s.download_secret:
|
||||
logging.getLogger("api").warning("JWT_SECRET/DOWNLOAD_SECRET tienen el valor de ejemplo: cambialos en el .env")
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="API de archivos por persona", version="1.0.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=get_settings().origenes_cors,
|
||||
allow_methods=["GET"],
|
||||
allow_headers=["Authorization"],
|
||||
)
|
||||
|
||||
app.include_router(archivos.router)
|
||||
app.include_router(descargas.router)
|
||||
|
||||
|
||||
@app.get("/salud", tags=["sistema"])
|
||||
def salud():
|
||||
"""Para monitoreo: confirma que la API responde, que Elasticsearch contesta
|
||||
(búsquedas) y que la carpeta de archivos es accesible (descargas)."""
|
||||
try:
|
||||
accesible = get_storage().disponible()
|
||||
except Exception: # noqa: BLE001 - ej. carpeta no montada
|
||||
accesible = False
|
||||
buscador = elastic.disponible()
|
||||
return {
|
||||
"estado": "ok" if accesible and buscador else "degradado",
|
||||
"elasticsearch_accesible": buscador,
|
||||
"tipo_almacenamiento": get_settings().storage_type,
|
||||
"almacenamiento_accesible": accesible,
|
||||
}
|
||||
37
app/models.py
Normal file
37
app/models.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""Tablas de la API: solo los logs de búsquedas y descargas.
|
||||
|
||||
Los archivos y su texto ya no están acá: los indexa FSCrawler en Elasticsearch.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
def ahora() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class LogBusqueda(Base):
|
||||
__tablename__ = "log_busquedas"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
usuario: Mapped[str] = mapped_column(String(100), index=True)
|
||||
criterio: Mapped[str] = mapped_column(String(50)) # ej. "cedula+nombre"
|
||||
valor: Mapped[str] = mapped_column(String(300))
|
||||
resultados: Mapped[int] = mapped_column(Integer, default=0)
|
||||
ip: Mapped[str] = mapped_column(String(64), default="")
|
||||
fecha: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=ahora, index=True)
|
||||
|
||||
|
||||
class LogDescarga(Base):
|
||||
__tablename__ = "log_descargas"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
usuario: Mapped[str] = mapped_column(String(100), index=True)
|
||||
documento_id: Mapped[str] = mapped_column(String(128), index=True) # _id en Elasticsearch
|
||||
ruta_relativa: Mapped[str] = mapped_column(String(1000))
|
||||
ip: Mapped[str] = mapped_column(String(64), default="")
|
||||
fecha: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=ahora, index=True)
|
||||
0
app/routers/__init__.py
Normal file
0
app/routers/__init__.py
Normal file
71
app/routers/archivos.py
Normal file
71
app/routers/archivos.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""GET /archivos?cedula=...&nombres=...&apellidos=...
|
||||
|
||||
Busca DENTRO del contenido de los archivos (y en sus rutas) consultando el índice
|
||||
de Elasticsearch que mantiene FSCrawler.
|
||||
"""
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.busqueda import buscar, validar
|
||||
from app.database import get_db
|
||||
from app.elastic import ElasticError
|
||||
from app.models import LogBusqueda
|
||||
from app.schemas import ArchivoOut, BusquedaOut, CriteriosOut
|
||||
from app.security import Usuario, generar_url_descarga, usuario_actual
|
||||
|
||||
router = APIRouter(tags=["archivos"])
|
||||
log = logging.getLogger("api")
|
||||
|
||||
|
||||
@router.get("/archivos", response_model=BusquedaOut)
|
||||
def buscar_archivos(
|
||||
request: Request,
|
||||
cedula: str | None = Query(None, max_length=20, description="Cédula, con o sin puntos"),
|
||||
nombres: str | None = Query(None, max_length=100, description="Nombres (ej. Juan Carlos)"),
|
||||
apellidos: str | None = Query(None, max_length=100, description="Apellidos (ej. Pérez González)"),
|
||||
limite: int = Query(100, ge=1, le=500, description="Máximo de archivos a devolver"),
|
||||
db: Session = Depends(get_db),
|
||||
usuario: Usuario = Depends(usuario_actual),
|
||||
):
|
||||
try:
|
||||
ced, nom, ape = validar(cedula, nombres, apellidos)
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, str(e))
|
||||
|
||||
try:
|
||||
coincidencias, total_coincidencias = buscar(ced, nom, ape, limite)
|
||||
except ElasticError as e:
|
||||
log.error("Búsqueda fallida: %s", e)
|
||||
raise HTTPException(503, "El buscador no está disponible en este momento")
|
||||
|
||||
resultados = [
|
||||
ArchivoOut(
|
||||
id=c.doc_id,
|
||||
nombre=c.nombre,
|
||||
carpeta=c.carpeta,
|
||||
extension=c.extension,
|
||||
tamano_bytes=c.tamano_bytes,
|
||||
modificado_en=c.modificado_en,
|
||||
coincide_cedula=c.coincide_cedula,
|
||||
coincide_nombre=c.coincide_nombre,
|
||||
fragmento=c.fragmento,
|
||||
url_descarga=generar_url_descarga(c.doc_id, usuario.id),
|
||||
)
|
||||
for c in coincidencias
|
||||
]
|
||||
|
||||
criterio = "+".join(n for n, v in (("cedula", ced), ("nombre", nom)) if v)
|
||||
valor = " | ".join(v for v in (ced, " ".join(p.normal for p in nom), " ".join(p.normal for p in ape)) if v)
|
||||
ip = request.client.host if request.client else ""
|
||||
db.add(LogBusqueda(usuario=usuario.id, criterio=criterio, valor=valor[:300], resultados=total_coincidencias, ip=ip))
|
||||
db.commit()
|
||||
log.info("BUSQUEDA usuario=%s %s=%s archivos=%s ip=%s", usuario.id, criterio, valor, total_coincidencias, ip)
|
||||
|
||||
return BusquedaOut(
|
||||
criterios=CriteriosOut(cedula=ced or None, nombres=nombres, apellidos=apellidos),
|
||||
total=len(resultados),
|
||||
total_coincidencias=total_coincidencias,
|
||||
resultados=resultados,
|
||||
)
|
||||
89
app/routers/descargas.py
Normal file
89
app/routers/descargas.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""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)}",
|
||||
},
|
||||
)
|
||||
36
app/schemas.py
Normal file
36
app/schemas.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""Forma exacta del JSON que devuelve la API (lo que consume el frontend)."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
|
||||
class ArchivoOut(BaseModel):
|
||||
id: str # _id del documento en Elasticsearch
|
||||
nombre: str
|
||||
carpeta: str
|
||||
extension: str
|
||||
tamano_bytes: int
|
||||
modificado_en: datetime | None
|
||||
coincide_cedula: bool
|
||||
coincide_nombre: str | None # "completo" | "parcial" | null
|
||||
fragmento: str # texto alrededor de la coincidencia, marcada con « »
|
||||
url_descarga: str # enlace firmado, válido por DOWNLOAD_LINK_TTL_MINUTES
|
||||
|
||||
@field_validator("modificado_en")
|
||||
@classmethod
|
||||
def _en_utc(cls, v: datetime | None) -> datetime | None:
|
||||
# Si la fecha viene sin zona horaria, se asume UTC
|
||||
return v if v is None or v.tzinfo else v.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class CriteriosOut(BaseModel):
|
||||
cedula: str | None
|
||||
nombres: str | None
|
||||
apellidos: str | None
|
||||
|
||||
|
||||
class BusquedaOut(BaseModel):
|
||||
criterios: CriteriosOut
|
||||
total: int # archivos devueltos (como máximo `limite`)
|
||||
total_coincidencias: int # todos los archivos que coinciden
|
||||
resultados: list[ArchivoOut]
|
||||
67
app/security.py
Normal file
67
app/security.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""Seguridad: quién puede buscar (JWT) y enlaces de descarga firmados que vencen."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import quote
|
||||
|
||||
import jwt
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Usuario:
|
||||
id: str
|
||||
rol: str
|
||||
|
||||
|
||||
def usuario_actual(cred: HTTPAuthorizationCredentials | None = Depends(_bearer)) -> Usuario:
|
||||
"""El sistema Admin genera un JWT con {sub, rol, exp} firmado con JWT_SECRET
|
||||
y lo manda en el header: Authorization: Bearer <token>."""
|
||||
if cred is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Falta el token", {"WWW-Authenticate": "Bearer"})
|
||||
s = get_settings()
|
||||
try:
|
||||
datos = jwt.decode(
|
||||
cred.credentials, s.jwt_secret, algorithms=[s.jwt_algorithm], options={"require": ["exp", "sub"]}
|
||||
)
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token vencido")
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token inválido")
|
||||
|
||||
usuario = Usuario(id=str(datos["sub"]), rol=str(datos.get("rol", "")).lower())
|
||||
if usuario.rol not in s.roles_permitidos:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Sin permiso para consultar archivos")
|
||||
return usuario
|
||||
|
||||
|
||||
# ---------- Enlaces de descarga firmados ----------
|
||||
# El enlace lleva: id del archivo, usuario que lo pidió, vencimiento y una firma HMAC.
|
||||
# Nadie puede cambiar el id ni extender el vencimiento sin invalidar la firma.
|
||||
|
||||
def _firma(archivo_id: str, usuario_id: str, exp: int) -> str:
|
||||
msg = f"{archivo_id}:{usuario_id}:{exp}".encode()
|
||||
digest = hmac.new(get_settings().download_secret.encode(), msg, hashlib.sha256).digest()
|
||||
return base64.urlsafe_b64encode(digest).decode().rstrip("=")
|
||||
|
||||
|
||||
def generar_url_descarga(archivo_id: str, usuario_id: str) -> str:
|
||||
s = get_settings()
|
||||
exp = int(time.time()) + s.download_link_ttl_minutes * 60
|
||||
firma = _firma(archivo_id, usuario_id, exp)
|
||||
base = s.public_base_url.rstrip("/")
|
||||
return f"{base}/descargas/{quote(archivo_id, safe='')}?u={quote(usuario_id, safe='')}&exp={exp}&sig={firma}"
|
||||
|
||||
|
||||
def validar_firma(archivo_id: str, usuario_id: str, exp: int, sig: str) -> None:
|
||||
if exp < int(time.time()):
|
||||
raise HTTPException(status.HTTP_410_GONE, "El enlace de descarga venció")
|
||||
if not hmac.compare_digest(_firma(archivo_id, usuario_id, exp), sig):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Enlace de descarga inválido")
|
||||
346
app/storage.py
Normal file
346
app/storage.py
Normal file
@@ -0,0 +1,346 @@
|
||||
"""Capa de almacenamiento: el resto del sistema no sabe si los archivos están
|
||||
en una carpeta local del servidor Linux o en un recurso compartido SMB (Samba/NAS).
|
||||
|
||||
Backends disponibles (se elige con STORAGE_TYPE en el .env):
|
||||
- local: una ruta del sistema de archivos (disco, unidad montada).
|
||||
- smb: la API se conecta sola a la carpeta compartida con usuario y clave.
|
||||
No necesita montar nada (ideal para contenedores LXC de Proxmox).
|
||||
|
||||
Para agregar otro backend (ej. S3/MinIO) se crea una clase con los mismos
|
||||
métodos que StorageBackend y se registra en get_storage().
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import stat as stat_mod
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from functools import lru_cache
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import BinaryIO
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
# Archivos que nunca se indexan: temporales de Office, miniaturas de Windows (Thumbs.db), ocultos
|
||||
_IGNORAR_PREFIJOS = (".", "~$")
|
||||
_IGNORAR_NOMBRES = {"thumbs.db", "desktop.ini"}
|
||||
|
||||
|
||||
class RutaInvalidaError(Exception):
|
||||
"""La ruta pedida intenta salir de la carpeta raíz (path traversal)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntradaArchivo:
|
||||
ruta_relativa: str # siempre con "/"
|
||||
nombre: str
|
||||
extension: str
|
||||
tamano_bytes: int
|
||||
modificado_en: datetime
|
||||
|
||||
|
||||
def _ignorar(nombre: str) -> bool:
|
||||
return nombre.startswith(_IGNORAR_PREFIJOS) or nombre.lower() in _IGNORAR_NOMBRES
|
||||
|
||||
|
||||
def _es_utf8(nombre: str, ruta: Path) -> bool:
|
||||
"""En Linux un nombre puede venir en Latin-1 (copiado de Windows o de un pendrive).
|
||||
Python lo representa con caracteres inválidos que no se pueden guardar en la base.
|
||||
Se saltea y se avisa; se arregla renombrando con: convmv -f latin1 -t utf8 -r --notest <carpeta>"""
|
||||
try:
|
||||
nombre.encode("utf-8")
|
||||
return True
|
||||
except UnicodeEncodeError:
|
||||
log.warning("Nombre con codificación inválida (no UTF-8), se omite: %r", bytes(ruta))
|
||||
return False
|
||||
|
||||
|
||||
_UNIDAD_WINDOWS = re.compile(r"^[A-Za-z]:")
|
||||
|
||||
|
||||
def _partes_seguras(ruta_relativa: str, estilo_windows: bool = False) -> list[str]:
|
||||
"""Divide 'persona/2025/doc.pdf' en partes y rechaza '..' y rutas absolutas.
|
||||
|
||||
En Linux, ':' y '\\' son caracteres válidos en un nombre ("Reunión 10:30.pdf"),
|
||||
así que solo se tratan como peligrosos cuando la ruta va a un servidor Windows/SMB."""
|
||||
normalizada = ruta_relativa.replace("\\", "/") if estilo_windows else ruta_relativa
|
||||
if normalizada.startswith("/") or _UNIDAD_WINDOWS.match(normalizada):
|
||||
raise RutaInvalidaError(ruta_relativa)
|
||||
if estilo_windows and ":" in normalizada:
|
||||
raise RutaInvalidaError(ruta_relativa)
|
||||
partes = [p for p in PurePosixPath(normalizada).parts if p not in ("", ".")]
|
||||
if any(p == ".." for p in partes):
|
||||
raise RutaInvalidaError(ruta_relativa)
|
||||
return partes
|
||||
|
||||
|
||||
class StorageBackend(ABC):
|
||||
@abstractmethod
|
||||
def listar_carpetas_raiz(self) -> Iterator[str]:
|
||||
"""Nombres de las carpetas de primer nivel."""
|
||||
|
||||
@abstractmethod
|
||||
def listar_archivos(self, carpeta: str = "", excluir: frozenset[str] = frozenset()) -> Iterator[EntradaArchivo]:
|
||||
"""Todos los archivos dentro de una carpeta ("" = la raíz), incluidas subcarpetas.
|
||||
`excluir`: rutas relativas en minúsculas ('datos policia') que no se recorren."""
|
||||
|
||||
@abstractmethod
|
||||
def existe(self, ruta_relativa: str) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def tamano(self, ruta_relativa: str) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
def abrir(self, ruta_relativa: str) -> BinaryIO:
|
||||
"""Abre el archivo en modo lectura binaria."""
|
||||
|
||||
@abstractmethod
|
||||
def disponible(self) -> bool:
|
||||
"""True si el almacenamiento responde (para /salud)."""
|
||||
|
||||
def iterar_bytes(self, ruta_relativa: str, bloque: int = 1024 * 1024) -> Iterator[bytes]:
|
||||
"""Lee el archivo en bloques de 1 MB para enviarlo sin cargarlo entero en memoria."""
|
||||
with self.abrir(ruta_relativa) as f:
|
||||
while datos := f.read(bloque):
|
||||
yield datos
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- local
|
||||
|
||||
class LocalFileSystemBackend(StorageBackend):
|
||||
"""Carpeta local del servidor (/srv/archivos) o un NAS ya montado (/mnt/nas)."""
|
||||
|
||||
def __init__(self, raiz: str):
|
||||
self.raiz = Path(raiz).expanduser().resolve()
|
||||
if not self.raiz.is_dir():
|
||||
raise FileNotFoundError(f"STORAGE_ROOT no existe o no es accesible: {self.raiz}")
|
||||
|
||||
def listar_carpetas_raiz(self) -> Iterator[str]:
|
||||
for item in sorted(self.raiz.iterdir()):
|
||||
if item.is_dir() and not item.name.startswith((".", "$", "~")):
|
||||
yield item.name
|
||||
|
||||
def listar_archivos(self, carpeta: str = "", excluir: frozenset[str] = frozenset()) -> Iterator[EntradaArchivo]:
|
||||
"""Recorre la carpeta sin seguir enlaces simbólicos. Se saltean (con aviso en el log)
|
||||
los casos que en Linux podrían frenar o colgar la indexación: nombres que no son
|
||||
UTF-8, enlaces simbólicos, FIFOs/sockets/dispositivos y archivos sin permiso."""
|
||||
base = self.ruta_absoluta(carpeta)
|
||||
|
||||
def sin_acceso(error: OSError) -> None:
|
||||
log.warning("No se pudo leer la carpeta %s: %s", error.filename, error.strerror)
|
||||
|
||||
for actual, subcarpetas, archivos in os.walk(base, onerror=sin_acceso): # no sigue symlinks
|
||||
rel_actual = PurePosixPath(*Path(actual).relative_to(self.raiz).parts)
|
||||
# Poda: no entra a carpetas excluidas, ocultas ni con nombre inválido
|
||||
subcarpetas[:] = sorted(
|
||||
d for d in subcarpetas
|
||||
if not d.startswith((".", "$", "~")) and (rel_actual / d).as_posix().lower() not in excluir
|
||||
and _es_utf8(d, Path(actual) / d)
|
||||
)
|
||||
for nombre in sorted(archivos):
|
||||
if _ignorar(nombre):
|
||||
continue
|
||||
f = Path(actual) / nombre
|
||||
if not _es_utf8(nombre, f):
|
||||
continue
|
||||
try:
|
||||
st = f.lstat() # lstat: mira el enlace en sí, no a dónde apunta
|
||||
except OSError as e:
|
||||
log.warning("No se pudo leer %s: %s", f, e.strerror)
|
||||
continue
|
||||
# Solo archivos regulares: un symlink puede apuntar fuera de la raíz, y leer
|
||||
# una FIFO o un dispositivo deja al indexador esperando para siempre.
|
||||
if not stat_mod.S_ISREG(st.st_mode):
|
||||
continue
|
||||
yield EntradaArchivo(
|
||||
ruta_relativa=(rel_actual / nombre).as_posix(),
|
||||
nombre=nombre,
|
||||
extension=f.suffix.lower(),
|
||||
tamano_bytes=st.st_size,
|
||||
modificado_en=datetime.fromtimestamp(st.st_mtime, tz=timezone.utc),
|
||||
)
|
||||
|
||||
def ruta_absoluta(self, ruta_relativa: str) -> Path:
|
||||
destino = self.raiz.joinpath(*_partes_seguras(ruta_relativa)).resolve()
|
||||
# Segunda barrera: aunque haya enlaces simbólicos, no se puede salir de la raíz
|
||||
if destino != self.raiz and self.raiz not in destino.parents:
|
||||
raise RutaInvalidaError(ruta_relativa)
|
||||
return destino
|
||||
|
||||
def existe(self, ruta_relativa: str) -> bool:
|
||||
try:
|
||||
ruta = self.ruta_absoluta(ruta_relativa)
|
||||
return stat_mod.S_ISREG(ruta.lstat().st_mode) # regular y no enlace
|
||||
except (RutaInvalidaError, OSError):
|
||||
return False
|
||||
|
||||
def tamano(self, ruta_relativa: str) -> int:
|
||||
return self.ruta_absoluta(ruta_relativa).stat().st_size
|
||||
|
||||
def abrir(self, ruta_relativa: str) -> BinaryIO:
|
||||
return open(self.ruta_absoluta(ruta_relativa), "rb")
|
||||
|
||||
def disponible(self) -> bool:
|
||||
return self.raiz.is_dir()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- smb
|
||||
|
||||
class SMBBackend(StorageBackend):
|
||||
"""Se conecta directo a \\\\SERVIDOR\\RECURSO con usuario y clave (SMB 2/3),
|
||||
con cifrado activado por defecto. No requiere montar la carpeta en el sistema."""
|
||||
|
||||
def __init__(self, servidor: str, recurso: str, usuario: str, clave: str, dominio: str = "",
|
||||
subcarpeta: str = "", puerto: int = 445, cifrar: bool = True, timeout: int = 15):
|
||||
self.servidor = servidor
|
||||
self.recurso = recurso
|
||||
self.base = _partes_seguras(subcarpeta, estilo_windows=True) if subcarpeta else []
|
||||
self._usuario = f"{dominio}\\{usuario}" if dominio else usuario
|
||||
self._clave = clave
|
||||
self._puerto = puerto
|
||||
self._cifrar = cifrar
|
||||
self._timeout = timeout
|
||||
self._conectar()
|
||||
|
||||
# -- conexión --------------------------------------------------------------
|
||||
def _conectar(self) -> None:
|
||||
import smbclient
|
||||
|
||||
smbclient.register_session(
|
||||
self.servidor,
|
||||
username=self._usuario,
|
||||
password=self._clave,
|
||||
port=self._puerto,
|
||||
encrypt=self._cifrar,
|
||||
connection_timeout=self._timeout,
|
||||
)
|
||||
|
||||
def _reconectar(self) -> None:
|
||||
import smbclient
|
||||
|
||||
log.warning("Reconectando SMB con %s", self.servidor)
|
||||
smbclient.reset_connection_cache()
|
||||
self._conectar()
|
||||
|
||||
def _con_reintento(self, operacion):
|
||||
"""Si el servidor SMB se reinició, la conexión guardada queda muerta:
|
||||
se reconecta una vez y se reintenta. Los errores de archivo (no existe,
|
||||
sin permiso) se devuelven tal cual."""
|
||||
from smbprotocol.exceptions import SMBException, SMBOSError
|
||||
|
||||
try:
|
||||
return operacion()
|
||||
except SMBOSError:
|
||||
raise
|
||||
except (SMBException, ConnectionError, EOFError, ValueError):
|
||||
self._reconectar()
|
||||
return operacion()
|
||||
|
||||
def _unc(self, ruta_relativa: str = "") -> str:
|
||||
partes = [self.servidor, self.recurso, *self.base, *_partes_seguras(ruta_relativa, estilo_windows=True)]
|
||||
return "\\\\" + "\\".join(partes)
|
||||
|
||||
# -- listado -----------------------------------------------------------------
|
||||
def listar_carpetas_raiz(self) -> Iterator[str]:
|
||||
import smbclient
|
||||
|
||||
entradas = self._con_reintento(lambda: list(smbclient.scandir(self._unc())))
|
||||
for e in sorted(entradas, key=lambda x: x.name):
|
||||
if e.is_dir() and not e.name.startswith((".", "$", "~")):
|
||||
yield e.name
|
||||
|
||||
def listar_archivos(self, carpeta: str = "", excluir: frozenset[str] = frozenset()) -> Iterator[EntradaArchivo]:
|
||||
yield from self._recorrer(_partes_seguras(carpeta, estilo_windows=True) if carpeta else [], excluir)
|
||||
|
||||
def _recorrer(self, partes: list[str], excluir: frozenset[str]) -> Iterator[EntradaArchivo]:
|
||||
import smbclient
|
||||
|
||||
from smbprotocol.exceptions import SMBOSError
|
||||
|
||||
unc = self._unc("/".join(partes))
|
||||
try:
|
||||
entradas = self._con_reintento(lambda: list(smbclient.scandir(unc)))
|
||||
except SMBOSError as e:
|
||||
if not partes:
|
||||
raise # si falla la raíz, es un problema real (permisos, recurso inexistente)
|
||||
# Una subcarpeta sin permiso no frena toda la indexación
|
||||
log.warning("No se pudo leer la carpeta %s: %s", "/".join(partes), e.strerror)
|
||||
return
|
||||
for e in sorted(entradas, key=lambda x: x.name):
|
||||
if _ignorar(e.name):
|
||||
continue
|
||||
if e.is_dir():
|
||||
if e.name.startswith(("$", "~")) or "/".join([*partes, e.name]).lower() in excluir:
|
||||
continue
|
||||
yield from self._recorrer([*partes, e.name], excluir)
|
||||
elif e.is_file():
|
||||
st = e.stat() # viene en la misma respuesta del listado: no hace otra consulta
|
||||
yield EntradaArchivo(
|
||||
ruta_relativa="/".join([*partes, e.name]),
|
||||
nombre=e.name,
|
||||
extension=PurePosixPath(e.name).suffix.lower(),
|
||||
tamano_bytes=st.st_size,
|
||||
modificado_en=datetime.fromtimestamp(st.st_mtime, tz=timezone.utc),
|
||||
)
|
||||
|
||||
# -- archivos ----------------------------------------------------------------
|
||||
def existe(self, ruta_relativa: str) -> bool:
|
||||
import smbclient
|
||||
from smbprotocol.exceptions import SMBOSError
|
||||
|
||||
try:
|
||||
unc = self._unc(ruta_relativa)
|
||||
st = self._con_reintento(lambda: smbclient.stat(unc))
|
||||
return stat_mod.S_ISREG(st.st_mode)
|
||||
except (RutaInvalidaError, SMBOSError):
|
||||
return False
|
||||
|
||||
def tamano(self, ruta_relativa: str) -> int:
|
||||
import smbclient
|
||||
|
||||
unc = self._unc(ruta_relativa)
|
||||
return self._con_reintento(lambda: smbclient.stat(unc)).st_size
|
||||
|
||||
def abrir(self, ruta_relativa: str) -> BinaryIO:
|
||||
import smbclient
|
||||
|
||||
unc = self._unc(ruta_relativa)
|
||||
# share_access="r": no bloquea a quien tenga el archivo abierto en Windows
|
||||
return self._con_reintento(lambda: smbclient.open_file(unc, mode="rb", share_access="r"))
|
||||
|
||||
def disponible(self) -> bool:
|
||||
import smbclient
|
||||
|
||||
try:
|
||||
self._con_reintento(lambda: next(iter(smbclient.scandir(self._unc())), None))
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- fábrica
|
||||
|
||||
@lru_cache
|
||||
def get_storage() -> StorageBackend:
|
||||
"""Punto único para elegir backend. Se crea una sola vez y se reutiliza
|
||||
(la conexión SMB queda abierta entre pedidos)."""
|
||||
s = get_settings()
|
||||
if s.storage_type == "smb":
|
||||
return SMBBackend(
|
||||
servidor=s.smb_server,
|
||||
recurso=s.smb_share,
|
||||
usuario=s.smb_username,
|
||||
clave=s.smb_password.get_secret_value(),
|
||||
dominio=s.smb_domain,
|
||||
subcarpeta=s.smb_base_path,
|
||||
puerto=s.smb_port,
|
||||
cifrar=s.smb_encrypt,
|
||||
timeout=s.smb_timeout,
|
||||
)
|
||||
return LocalFileSystemBackend(s.storage_root)
|
||||
12
app/utils.py
Normal file
12
app/utils.py
Normal file
@@ -0,0 +1,12 @@
|
||||
import unicodedata
|
||||
|
||||
|
||||
def normalizar(texto: str) -> str:
|
||||
"""' José PÉREZ ' -> 'jose perez'. Se usa al armar la búsqueda."""
|
||||
sin_tildes = unicodedata.normalize("NFKD", texto).encode("ascii", "ignore").decode()
|
||||
return " ".join(sin_tildes.lower().replace("_", " ").split())
|
||||
|
||||
|
||||
def solo_digitos(texto: str) -> str:
|
||||
"""'1.234.567' -> '1234567' (en Paraguay la cédula suele escribirse con puntos)."""
|
||||
return "".join(c for c in texto if c.isdigit())
|
||||
Reference in New Issue
Block a user