75 lines
2.7 KiB
Python
75 lines
2.7 KiB
Python
"""Store reference cohorts on the local filesystem."""
|
|
|
|
import re
|
|
import shutil
|
|
from pathlib import Path
|
|
from tempfile import NamedTemporaryFile
|
|
from typing import BinaryIO
|
|
|
|
COHORT_NAME = re.compile(r"[A-Za-z0-9._-]{1,64}")
|
|
AGES_FILE = "edades.csv"
|
|
|
|
|
|
def _safe_component(value: str) -> bool:
|
|
return bool(value) and value != "." and not any(char in value for char in ("/", "\\", "..", "\0", ":"))
|
|
|
|
|
|
class ReferenceCohortStore:
|
|
"""List cohorts and atomically publish uploads under a configured root."""
|
|
|
|
def __init__(self, root: str | Path):
|
|
self.root = Path(root).resolve()
|
|
|
|
def list_cohorts(self) -> list[dict]:
|
|
if not self.root.exists():
|
|
return []
|
|
|
|
cohorts = []
|
|
for folder in sorted(self.root.iterdir()):
|
|
if (not COHORT_NAME.fullmatch(folder.name) or not _safe_component(folder.name)
|
|
or folder.is_symlink() or not folder.is_dir()):
|
|
continue
|
|
edfs = [
|
|
path for path in folder.rglob("*")
|
|
if path.suffix.lower() == ".edf" and not path.is_symlink() and path.is_file()
|
|
]
|
|
ages = folder / AGES_FILE
|
|
has_ages = not ages.is_symlink() and ages.is_file()
|
|
size = sum(path.stat().st_size for path in edfs)
|
|
if has_ages:
|
|
size += ages.stat().st_size
|
|
cohorts.append({
|
|
"name": folder.name,
|
|
"edfs": len(edfs),
|
|
"size_bytes": size,
|
|
"has_ages": has_ages,
|
|
"path": str(folder),
|
|
})
|
|
return cohorts
|
|
|
|
def save_file(self, name: str, filename: str, stream: BinaryIO) -> dict:
|
|
if not COHORT_NAME.fullmatch(name) or not _safe_component(name):
|
|
raise ValueError("Nombre de cohorte inválido.")
|
|
if not _safe_component(filename):
|
|
raise ValueError("Nombre de archivo inválido.")
|
|
if filename != AGES_FILE and Path(filename).suffix.lower() != ".edf":
|
|
raise ValueError("Solo se admite un archivo EDF o edades.csv.")
|
|
|
|
folder = self.root / name
|
|
target = folder / filename
|
|
if folder.is_symlink() or target.is_symlink():
|
|
raise ValueError("Ruta de archivo inválida.")
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
|
|
temporary = None
|
|
try:
|
|
with NamedTemporaryFile(dir=folder, suffix=".tmp", delete=False) as output:
|
|
temporary = Path(output.name)
|
|
shutil.copyfileobj(stream, output, length=1024 * 1024)
|
|
size = output.tell()
|
|
temporary.replace(target)
|
|
finally:
|
|
if temporary is not None:
|
|
temporary.unlink(missing_ok=True)
|
|
return {"name": name, "file": filename, "size_bytes": size}
|