filebridge 0.2.4__tar.gz → 0.2.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: filebridge
3
- Version: 0.2.4
3
+ Version: 0.2.8
4
4
  Summary: A Python library for interacting with the Filebridge daemon (filebridged).
5
5
  Author: Stefan Schönberger
6
6
  Author-email: Stefan Schönberger <stefan@sniner.dev>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "filebridge"
3
- version = "0.2.4"
3
+ version = "0.2.8"
4
4
  description = "A Python library for interacting with the Filebridge daemon (filebridged)."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -25,7 +25,8 @@ is encrypted transparently::
25
25
 
26
26
  from .client import (
27
27
  FileBridgeClient,
28
- Location,
28
+ )
29
+ from .entry import (
29
30
  LocationEntry,
30
31
  )
31
32
  from .exceptions import (
@@ -38,6 +39,9 @@ from .exceptions import (
38
39
  from .io import (
39
40
  FileBridgeReadStream,
40
41
  )
42
+ from .location import (
43
+ Location,
44
+ )
41
45
  from .models import (
42
46
  Metadata,
43
47
  )
@@ -0,0 +1,55 @@
1
+ """FileBridgeClient — entry point for connecting to a Filebridge server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import httpx
6
+
7
+ from .location import Location
8
+
9
+
10
+ class FileBridgeClient:
11
+ """Client for a Filebridge server.
12
+
13
+ Use as a context manager to ensure the underlying HTTP connection is
14
+ closed::
15
+
16
+ with FileBridgeClient("http://localhost:8000") as client:
17
+ loc = client.location("my-share")
18
+ data = loc.read("hello.txt")
19
+
20
+ Args:
21
+ base_url: Server base URL (e.g. ``http://localhost:8000``).
22
+ timeout: HTTP timeout in seconds. Defaults to ``30.0``.
23
+ """
24
+
25
+ def __init__(self, base_url: str, *, timeout: float = 30.0):
26
+ self.base_url = base_url.rstrip("/") + "/"
27
+ self.client = httpx.Client(timeout=timeout)
28
+
29
+ def location(
30
+ self,
31
+ dir_id: str,
32
+ token: str | None = None,
33
+ *,
34
+ case_sensitive: bool = True,
35
+ ) -> Location:
36
+ """Return a ``Location`` handle for the given directory ID.
37
+
38
+ Args:
39
+ dir_id: Server-side directory identifier.
40
+ token: Optional authentication token. When set, enables HMAC
41
+ signing and end-to-end encryption.
42
+ case_sensitive: Whether filename comparisons are case-sensitive.
43
+ """
44
+ return Location(self, dir_id, token, case_sensitive=case_sensitive)
45
+
46
+ at = location
47
+
48
+ def close(self):
49
+ self.client.close()
50
+
51
+ def __enter__(self):
52
+ return self
53
+
54
+ def __exit__(self, exc_type, exc_val, exc_tb):
55
+ self.close()
@@ -0,0 +1,50 @@
1
+ """Filename comparison strategies (case-sensitive / case-insensitive)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ from abc import ABC, abstractmethod
7
+ from typing import Type
8
+
9
+
10
+ class FilenameComparator(ABC):
11
+ """Strategy for comparing filenames (case-sensitive or case-insensitive)."""
12
+
13
+ def __init__(self, base: str):
14
+ self.base = self.normalize(str(base))
15
+
16
+ @abstractmethod
17
+ def normalize(self, name: str) -> str: ...
18
+
19
+ def __eq__(self, other: object) -> bool:
20
+ if isinstance(other, str):
21
+ return self.base == self.normalize(other)
22
+ elif isinstance(other, self.__class__):
23
+ return self.base == other.base
24
+ return NotImplemented
25
+
26
+ def match(self, name: str) -> bool:
27
+ return fnmatch.fnmatchcase(self.normalize(name), self.base)
28
+
29
+ def equals(self, name: str) -> bool:
30
+ return self.base == self.normalize(str(name))
31
+
32
+ @classmethod
33
+ def compare(cls, a: str, b: str) -> bool:
34
+ return cls(a).equals(b)
35
+
36
+ @staticmethod
37
+ def build(*, case_sensitive: bool) -> Type[FilenameComparator]:
38
+ if case_sensitive:
39
+ return CaseSensitiveComparator
40
+ return CaseInsensitiveComparator
41
+
42
+
43
+ class CaseSensitiveComparator(FilenameComparator):
44
+ def normalize(self, name: str) -> str:
45
+ return name
46
+
47
+
48
+ class CaseInsensitiveComparator(FilenameComparator):
49
+ def normalize(self, name: str) -> str:
50
+ return name.casefold()
@@ -0,0 +1,117 @@
1
+ """Low-level request building and response handling for the Filebridge API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import secrets
9
+ import time
10
+ from typing import Any
11
+ from urllib.parse import urlparse
12
+
13
+ from .exceptions import (
14
+ AuthenticationError,
15
+ FileBridgePermissionError,
16
+ NotFoundError,
17
+ )
18
+ from .stream import build_encrypted_envelope
19
+
20
+
21
+ def calculate_signature(
22
+ token: str | None, method: str, url: str, timestamp: str, nonce: str
23
+ ) -> str:
24
+ """Compute the HMAC-SHA256 request signature. Returns ``""`` if no token."""
25
+ if not token:
26
+ return ""
27
+
28
+ parsed = urlparse(url)
29
+ path = parsed.path
30
+ if parsed.query:
31
+ path += "?" + parsed.query
32
+
33
+ mac = hmac.new(token.encode(), digestmod=hashlib.sha256)
34
+ mac.update(timestamp.encode())
35
+ mac.update(nonce.encode())
36
+ mac.update(method.upper().encode())
37
+ mac.update(path.encode())
38
+
39
+ return mac.hexdigest()
40
+
41
+
42
+ def get_api_path(dir_id: str, path: str | None, *, use_encrypted_body: bool = False) -> str:
43
+ """Build the API path, stripping leading slashes from the requested path.
44
+
45
+ When *use_encrypted_body* is True the path is omitted from the URL
46
+ (it will be sent in an encrypted body instead).
47
+ """
48
+ if use_encrypted_body:
49
+ return f"api/v1/fs/{dir_id}"
50
+ if path:
51
+ clean_path = path.lstrip("/")
52
+ if clean_path:
53
+ return f"api/v1/fs/{dir_id}/{clean_path}"
54
+ return f"api/v1/fs/{dir_id}"
55
+
56
+
57
+ def prepare_request_kwargs(
58
+ method: str, url: str, token: str | None, kwargs: dict[str, Any]
59
+ ) -> tuple[dict[str, Any], str]:
60
+ """Add authentication headers to request kwargs. Returns ``(kwargs, nonce)``."""
61
+ content = kwargs.get("content", b"")
62
+ if isinstance(content, str):
63
+ kwargs["content"] = content.encode()
64
+ elif kwargs.get("json") is not None:
65
+ kwargs["content"] = json.dumps(kwargs["json"], separators=(",", ":")).encode()
66
+ if "json" in kwargs:
67
+ del kwargs["json"]
68
+
69
+ nonce = ""
70
+ if token:
71
+ headers = kwargs.get("headers", {})
72
+ if "X-Signature" not in headers:
73
+ timestamp = str(int(time.time()))
74
+ nonce = secrets.token_hex(8)
75
+ signature = calculate_signature(token, method, url, timestamp, nonce)
76
+ headers.update(
77
+ {"X-Signature": signature, "X-Timestamp": timestamp, "X-Nonce": nonce}
78
+ )
79
+ kwargs["headers"] = headers
80
+
81
+ return kwargs, nonce
82
+
83
+
84
+ def prepare_encrypted_request_kwargs(
85
+ method: str,
86
+ url: str,
87
+ token: str,
88
+ path: str,
89
+ offset: int | None = None,
90
+ length: int | None = None,
91
+ extra_headers: dict[str, str] | None = None,
92
+ extensive: bool = False,
93
+ ) -> tuple[dict[str, Any], str]:
94
+ """Build kwargs for a request with path in encrypted body (token-mode)."""
95
+ timestamp = str(int(time.time()))
96
+ nonce = secrets.token_hex(8)
97
+ signature = calculate_signature(token, method, url, timestamp, nonce)
98
+ envelope = build_encrypted_envelope(token, signature, path, offset, length, extensive)
99
+ headers = {
100
+ "X-Signature": signature,
101
+ "X-Timestamp": timestamp,
102
+ "X-Nonce": nonce,
103
+ "Content-Type": "application/vnd.filebridge.request",
104
+ }
105
+ if extra_headers:
106
+ headers.update(extra_headers)
107
+ return {"headers": headers, "content": envelope.encode()}, nonce
108
+
109
+
110
+ def handle_response_errors(status_code: int, text: str):
111
+ """Raise a typed exception for known HTTP error status codes."""
112
+ if status_code == 401:
113
+ raise AuthenticationError(text)
114
+ if status_code == 403:
115
+ raise FileBridgePermissionError(text)
116
+ if status_code == 404:
117
+ raise NotFoundError(text)
@@ -0,0 +1,237 @@
1
+ """LocationEntry — a pathlib-like handle to a file or directory within a location."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from collections.abc import Iterator
7
+ from contextlib import contextmanager
8
+ from pathlib import PurePosixPath
9
+ from typing import TYPE_CHECKING, ContextManager, Literal, overload
10
+
11
+ from .comparator import CaseInsensitiveComparator
12
+ from .io import FileBridgeReadStream
13
+ from .models import Metadata
14
+ from .types import LocationProtocol, StrPath
15
+
16
+ if TYPE_CHECKING:
17
+ from .location import _WriteHandle
18
+
19
+
20
+ class LocationEntry:
21
+ """A pathlib-like handle to a file or directory within a location.
22
+
23
+ Supports path operations (``/``, ``name``, ``stem``, ``suffix``, ``parent``),
24
+ metadata access (``stat()``, ``is_dir()``, ``is_file()``), directory traversal
25
+ (``iterdir()``, ``glob()``, ``walk()``), and file I/O (``open()``).
26
+
27
+ Instances are obtained from ``Location.list()``, ``Location.iterdir()``,
28
+ ``Location.glob()``, or by joining paths with ``/``.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ loc: LocationProtocol,
34
+ path: LocationPath,
35
+ metadata: Metadata | None = None,
36
+ ):
37
+ self._location = loc
38
+ self._path = PurePosixPath(path)
39
+ self._stat = metadata
40
+
41
+ def __fspath__(self) -> str:
42
+ return str(self.path)
43
+
44
+ @property
45
+ def path(self) -> PurePosixPath:
46
+ return self._path
47
+
48
+ def is_dir(self) -> bool:
49
+ return self.stat().is_dir
50
+
51
+ def is_file(self) -> bool:
52
+ return not self.is_dir()
53
+
54
+ def _refresh(self, *, extensive: bool | None = None) -> Metadata:
55
+ ex = self._stat is not None and self._stat.sha256 is not None
56
+ return self._location.stat(self._path, extensive=ex if extensive is None else extensive)
57
+
58
+ def refresh(self, *, extensive: bool | None = None) -> LocationEntry:
59
+ """Re-fetch metadata from the server and return ``self``."""
60
+ self._stat = self._refresh(extensive=extensive)
61
+ return self
62
+
63
+ @property
64
+ def name(self) -> str:
65
+ return self._path.name
66
+
67
+ @property
68
+ def stem(self) -> str:
69
+ return self._path.stem
70
+
71
+ @property
72
+ def suffix(self) -> str:
73
+ return self._path.suffix
74
+
75
+ @property
76
+ def suffixes(self) -> list[str]:
77
+ return self._path.suffixes
78
+
79
+ @property
80
+ def parent(self) -> PurePosixPath:
81
+ return self._path.parent
82
+
83
+ @property
84
+ def location(self) -> LocationProtocol:
85
+ return self._location
86
+
87
+ def is_relative_to(self, other: LocationPath) -> bool:
88
+ if isinstance(other, LocationEntry):
89
+ if self._location != other._location:
90
+ return False
91
+ other_path = other.path
92
+ else:
93
+ other_path = PurePosixPath(other)
94
+
95
+ if self._location.case_sensitive:
96
+ # pathlib.Path.is_relative_to() is always case-sensitive
97
+ return self.path.is_relative_to(other_path)
98
+
99
+ if len(self.path.parts) < len(other_path.parts):
100
+ return False
101
+
102
+ cmp = CaseInsensitiveComparator
103
+ for t, o in zip(self.path.parts, other_path.parts):
104
+ if not cmp.compare(t, o):
105
+ return False
106
+ return True
107
+
108
+ def stat(self, *, extensive: bool | None = None, refresh: bool = False) -> Metadata:
109
+ """Return cached metadata, fetching from the server if needed.
110
+
111
+ Args:
112
+ extensive: Request SHA-256 hash. Defaults to preserving the
113
+ current state (extensive if already fetched with hash).
114
+ refresh: Force re-fetching metadata from the server.
115
+ """
116
+ if self._stat is None:
117
+ self._stat = self._refresh(extensive=extensive)
118
+ elif refresh or (extensive and self._stat.sha256 is None):
119
+ self._stat = self._refresh(extensive=extensive)
120
+ return self._stat
121
+
122
+ def glob(self, pattern: str, *, extensive: bool = False) -> Iterator[LocationEntry]:
123
+ """Iterate over entries matching *pattern* relative to this entry."""
124
+ yield from self._location.glob(pattern, self._path, extensive=extensive)
125
+
126
+ def iterdir(self, *, extensive: bool = False) -> Iterator[LocationEntry]:
127
+ """Iterate over the entries in this directory.
128
+
129
+ Raises:
130
+ NotADirectoryError: If this entry is not a directory.
131
+ """
132
+ if not self.is_dir():
133
+ raise NotADirectoryError(f"{self._path} is not a directory")
134
+ yield from self._location.iterdir(self._path, extensive=extensive)
135
+
136
+ def walk(
137
+ self, *, extensive: bool = False
138
+ ) -> Iterator[tuple[PurePosixPath, list[LocationEntry], list[LocationEntry]]]:
139
+ """Walk the directory tree, yielding ``(dirpath, subdirs, files)`` tuples."""
140
+ yield from self._location.walk(self._path, extensive=extensive)
141
+
142
+ def __truediv__(self, other: LocationPath) -> LocationEntry:
143
+ if isinstance(other, LocationEntry):
144
+ if self._location != other._location:
145
+ raise ValueError("Cannot join paths from different locations")
146
+ other_path = other.path
147
+ else:
148
+ other_path = PurePosixPath(other)
149
+ new_path = self._path / other_path
150
+ return LocationEntry(self._location, new_path)
151
+
152
+ @overload
153
+ def open(
154
+ self,
155
+ mode: Literal["w", "wb"],
156
+ *,
157
+ encoding: str | None = ...,
158
+ ) -> ContextManager[_WriteHandle]: ...
159
+
160
+ @overload
161
+ def open(
162
+ self,
163
+ mode: Literal["r", "rb"] = ...,
164
+ *,
165
+ encoding: None = ...,
166
+ offset: int | None = ...,
167
+ length: int | None = ...,
168
+ ) -> ContextManager[FileBridgeReadStream]: ...
169
+
170
+ @overload
171
+ def open(
172
+ self,
173
+ mode: Literal["r", "rb"] = ...,
174
+ *,
175
+ encoding: str,
176
+ offset: int | None = ...,
177
+ length: int | None = ...,
178
+ ) -> ContextManager[io.TextIOWrapper]: ...
179
+
180
+ @contextmanager
181
+ def open(
182
+ self,
183
+ mode: str = "r",
184
+ *,
185
+ encoding: str | None = None,
186
+ offset: int | None = None,
187
+ length: int | None = None,
188
+ ):
189
+ """Open this entry for reading or writing.
190
+
191
+ Args:
192
+ mode: ``"r"``/``"rb"`` for reading, ``"w"``/``"wb"`` for writing.
193
+ encoding: Text encoding. When set in read mode, returns a
194
+ ``TextIOWrapper``; in write mode, encodes strings before sending.
195
+ offset: Start reading at this byte offset (read mode only).
196
+ length: Read at most this many bytes (read mode only).
197
+ """
198
+ with self._location.open( # type: ignore[attr-defined]
199
+ self._path,
200
+ mode=mode,
201
+ encoding=encoding,
202
+ offset=offset,
203
+ length=length,
204
+ ) as f:
205
+ yield f
206
+
207
+ def __str__(self) -> str:
208
+ return str(self.path)
209
+
210
+ def __repr__(self) -> str:
211
+ return f"{self.__class__.__name__}(path={self.path!r})"
212
+
213
+ def __eq__(self, other: object) -> bool:
214
+ if not isinstance(other, LocationEntry):
215
+ return NotImplemented
216
+ if self._location != other._location:
217
+ return False
218
+ if self._location.case_sensitive:
219
+ return self.path == other.path
220
+ else:
221
+ if len(self.path.parts) != len(other.path.parts):
222
+ return False
223
+ cmp = CaseInsensitiveComparator
224
+ for t, o in zip(self.path.parts, other.path.parts):
225
+ if not cmp.compare(t, o):
226
+ return False
227
+ return True
228
+
229
+ def __hash__(self) -> int:
230
+ if self._location.case_sensitive:
231
+ return hash((self._location, self._path))
232
+ else:
233
+ parts = tuple(p.casefold() for p in self._path.parts)
234
+ return hash((self._location, parts))
235
+
236
+
237
+ LocationPath = StrPath | LocationEntry
@@ -69,7 +69,8 @@ class FileBridgeReadStream(io.RawIOBase):
69
69
  # Verified stream logic
70
70
  decoder = self._decoder
71
71
  aead = self._aead
72
- assert decoder is not None and aead is not None
72
+ if decoder is None or aead is None:
73
+ raise FileBridgeError("stream decoder/aead not initialized")
73
74
 
74
75
  while not self._eof:
75
76
  frame = decoder.next_frame()