Files
surveybox/surveybox/media/storage.py
T
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

115 lines
3.1 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Dateien im Volume ablegen, ausliefern und aufräumen.
Ablage unter `<data>/media/<aa>/<zufall>`; der Schlüssel enthält nichts aus
dem Dateinamen. Uploads werden zuerst in `<data>/tmp` geschrieben und dann
mit einer atomaren Umbenennung an ihren Platz gelegt.
"""
from __future__ import annotations
import logging
import os
import re
import secrets
import time
from collections.abc import Iterable
from pathlib import Path
from typing import BinaryIO
log = logging.getLogger(__name__)
_KEY = re.compile(r"[0-9a-f]{2}/[0-9a-f]{32}")
CHUNK = 1024 * 1024
ORPHAN_MIN_AGE = 24 * 3600 # Sekunden; siehe models.MediaFile
TMP_MAX_AGE = 24 * 3600
class TooLarge(ValueError):
"""Die Datei überschreitet die erlaubte Größe."""
def new_key() -> str:
token = secrets.token_hex(16)
return f"{token[:2]}/{token}"
def path_for(root: Path, key: str) -> Path:
if not _KEY.fullmatch(key):
raise ValueError("ungültiger Speicherschlüssel")
return root / key
def temp_path(tmp_dir: Path) -> Path:
tmp_dir.mkdir(parents=True, exist_ok=True)
return tmp_dir / f"upload-{secrets.token_hex(12)}"
def receive(source: BinaryIO, target: Path, max_bytes: int) -> int:
"""Kopiert einen Upload in eine temporäre Datei, höchstens `max_bytes`."""
size = 0
try:
with target.open("wb") as out:
while chunk := source.read(CHUNK):
size += len(chunk)
if size > max_bytes:
raise TooLarge()
out.write(chunk)
except BaseException:
target.unlink(missing_ok=True)
raise
return size
def commit(root: Path, temp: Path) -> str:
"""Legt eine fertige temporäre Datei unter einem neuen Schlüssel ab."""
key = new_key()
final = path_for(root, key)
final.parent.mkdir(parents=True, exist_ok=True)
os.replace(temp, final)
return key
def stored_keys(root: Path) -> Iterable[str]:
if not root.is_dir():
return
for sub in root.iterdir():
if not sub.is_dir():
continue
for item in sub.iterdir():
key = f"{sub.name}/{item.name}"
if _KEY.fullmatch(key) and item.is_file():
yield key
def sweep(root: Path, referenced: set[str], min_age: int = ORPHAN_MIN_AGE) -> int:
"""Löscht Dateien ohne Verweis, die älter als `min_age` Sekunden sind."""
now = time.time()
removed = 0
for key in list(stored_keys(root)):
if key in referenced:
continue
path = root / key
try:
if now - path.stat().st_mtime < min_age:
continue
path.unlink()
removed += 1
except FileNotFoundError:
continue
if removed:
log.info("%d verwaiste Dateien gelöscht", removed)
return removed
def clean_tmp(tmp_dir: Path, max_age: int = TMP_MAX_AGE) -> None:
if not tmp_dir.is_dir():
return
now = time.time()
for item in tmp_dir.iterdir():
try:
if item.is_file() and now - item.stat().st_mtime > max_age:
item.unlink()
except FileNotFoundError:
continue