askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_user_files.py · 3.8 KB · 132 lines
| 1 | """Per-user file storage: bytes on disk, visibility on the metadata record. |
| 2 | |
| 3 | Files uploaded by users live under ``data/user_files/{owner_id}/{file_id}``. |
| 4 | The bytes carry no access rules of their own — every read and delete is |
| 5 | authorized against the file's metadata record in the ``files`` collection, |
| 6 | so owner rows, public flags, and project sharing govern downloads exactly |
| 7 | like any other record. Quotas count actual bytes on disk, not metadata. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import os |
| 13 | import re |
| 14 | import shutil |
| 15 | from pathlib import Path |
| 16 | |
| 17 | from object_versions import DEFAULT_DATA_DIR |
| 18 | |
| 19 | USER_FILES_DIR = "user_files" |
| 20 | _ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$") |
| 21 | |
| 22 | |
| 23 | class InvalidUserFileError(ValueError): |
| 24 | """Raised when a file id, owner, or payload is not usable.""" |
| 25 | |
| 26 | |
| 27 | class UserFileNotFoundError(FileNotFoundError): |
| 28 | """Raised when stored bytes are missing.""" |
| 29 | |
| 30 | |
| 31 | def user_files_root(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 32 | return Path(base_dir) / USER_FILES_DIR |
| 33 | |
| 34 | |
| 35 | def file_path( |
| 36 | owner_id: str, |
| 37 | file_id: str, |
| 38 | *, |
| 39 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 40 | ) -> Path: |
| 41 | """Return the storage path for one file, refusing unsafe ids.""" |
| 42 | owner = _validated(owner_id, "owner_id") |
| 43 | name = _validated(file_id, "file_id") |
| 44 | root = user_files_root(base_dir) |
| 45 | path = root / owner / name |
| 46 | resolved_root = root.resolve(strict=False) |
| 47 | try: |
| 48 | path.resolve(strict=False).relative_to(resolved_root) |
| 49 | except ValueError as exc: |
| 50 | raise InvalidUserFileError("File path escapes the user files directory") from exc |
| 51 | return path |
| 52 | |
| 53 | |
| 54 | def save_file( |
| 55 | owner_id: str, |
| 56 | file_id: str, |
| 57 | content: bytes, |
| 58 | *, |
| 59 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 60 | ) -> int: |
| 61 | """Write one file's bytes atomically; return the size stored.""" |
| 62 | if not isinstance(content, (bytes, bytearray)): |
| 63 | raise InvalidUserFileError("File content must be bytes") |
| 64 | path = file_path(owner_id, file_id, base_dir=base_dir) |
| 65 | path.parent.mkdir(parents=True, exist_ok=True) |
| 66 | os.chmod(path.parent, 0o700) |
| 67 | temp_path = path.with_name(f".{path.name}.tmp") |
| 68 | temp_path.write_bytes(content) |
| 69 | os.chmod(temp_path, 0o600) |
| 70 | temp_path.replace(path) |
| 71 | return len(content) |
| 72 | |
| 73 | |
| 74 | def read_file( |
| 75 | owner_id: str, |
| 76 | file_id: str, |
| 77 | *, |
| 78 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 79 | ) -> bytes: |
| 80 | """Return one file's bytes.""" |
| 81 | path = file_path(owner_id, file_id, base_dir=base_dir) |
| 82 | if not path.is_file(): |
| 83 | raise UserFileNotFoundError(f"File not found: {file_id}") |
| 84 | return path.read_bytes() |
| 85 | |
| 86 | |
| 87 | def delete_file( |
| 88 | owner_id: str, |
| 89 | file_id: str, |
| 90 | *, |
| 91 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 92 | ) -> bool: |
| 93 | """Delete one file's bytes; return whether they existed.""" |
| 94 | path = file_path(owner_id, file_id, base_dir=base_dir) |
| 95 | if not path.is_file(): |
| 96 | return False |
| 97 | path.unlink() |
| 98 | return True |
| 99 | |
| 100 | |
| 101 | def delete_all_files( |
| 102 | owner_id: str, |
| 103 | *, |
| 104 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 105 | ) -> int: |
| 106 | """Delete one user's whole file directory (user cleanup); return count.""" |
| 107 | owner = _validated(owner_id, "owner_id") |
| 108 | directory = user_files_root(base_dir) / owner |
| 109 | if not directory.is_dir(): |
| 110 | return 0 |
| 111 | count = sum(1 for item in directory.iterdir() if item.is_file()) |
| 112 | shutil.rmtree(directory) |
| 113 | return count |
| 114 | |
| 115 | |
| 116 | def usage_bytes( |
| 117 | owner_id: str, |
| 118 | *, |
| 119 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 120 | ) -> int: |
| 121 | """Return one user's total stored bytes — the quota input.""" |
| 122 | owner = _validated(owner_id, "owner_id") |
| 123 | directory = user_files_root(base_dir) / owner |
| 124 | if not directory.is_dir(): |
| 125 | return 0 |
| 126 | return sum(item.stat().st_size for item in directory.iterdir() if item.is_file()) |
| 127 | |
| 128 | |
| 129 | def _validated(value: str, name: str) -> str: |
| 130 | if not isinstance(value, str) or not _ID_RE.fullmatch(value): |
| 131 | raise InvalidUserFileError(f"Invalid {name}") |
| 132 | return value |