346 lines
14 KiB
Python
346 lines
14 KiB
Python
|
|
"""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)
|