xitzin 0.5.0__tar.gz → 0.6.1__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.
- {xitzin-0.5.0 → xitzin-0.6.1}/PKG-INFO +1 -1
- {xitzin-0.5.0 → xitzin-0.6.1}/pyproject.toml +1 -1
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/__init__.py +4 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/application.py +59 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/routing.py +3 -0
- xitzin-0.6.1/src/xitzin/staticfiles.py +487 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/README.md +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/auth.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/cgi.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/exceptions.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/middleware.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/py.typed +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/requests.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/responses.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/scgi.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/sqlmodel.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/tasks.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/templating.py +0 -0
- {xitzin-0.5.0 → xitzin-0.6.1}/src/xitzin/testing.py +0 -0
|
@@ -24,6 +24,7 @@ from .application import Xitzin
|
|
|
24
24
|
from .cgi import CGIConfig, CGIHandler, CGIScript
|
|
25
25
|
from .middleware import VirtualHostMiddleware
|
|
26
26
|
from .scgi import SCGIApp, SCGIConfig, SCGIHandler
|
|
27
|
+
from .staticfiles import StaticFiles, StaticFilesConfig
|
|
27
28
|
from .exceptions import (
|
|
28
29
|
BadRequest,
|
|
29
30
|
CertificateNotAuthorized,
|
|
@@ -66,6 +67,9 @@ __all__ = [
|
|
|
66
67
|
"SCGIApp",
|
|
67
68
|
"SCGIConfig",
|
|
68
69
|
"SCGIHandler",
|
|
70
|
+
# Static files
|
|
71
|
+
"StaticFiles",
|
|
72
|
+
"StaticFilesConfig",
|
|
69
73
|
# Exceptions
|
|
70
74
|
"GeminiException",
|
|
71
75
|
"InputRequired",
|
|
@@ -26,6 +26,7 @@ from .responses import Input, Redirect, convert_response
|
|
|
26
26
|
from .routing import MountedRoute, Route, Router, TitanRoute
|
|
27
27
|
|
|
28
28
|
if TYPE_CHECKING:
|
|
29
|
+
from .staticfiles import StaticFiles
|
|
29
30
|
from .tasks import BackgroundTask
|
|
30
31
|
from .templating import TemplateEngine
|
|
31
32
|
|
|
@@ -399,6 +400,64 @@ class Xitzin:
|
|
|
399
400
|
|
|
400
401
|
self.mount(path, handler, name=name)
|
|
401
402
|
|
|
403
|
+
def static(
|
|
404
|
+
self,
|
|
405
|
+
path: str,
|
|
406
|
+
directory: Path | str,
|
|
407
|
+
*,
|
|
408
|
+
name: str | None = None,
|
|
409
|
+
index_files: list[str] | None = None,
|
|
410
|
+
directory_listing: bool = False,
|
|
411
|
+
max_file_size: int = 100 * 1024 * 1024,
|
|
412
|
+
mime_types: dict[str, str] | None = None,
|
|
413
|
+
follow_symlinks: bool = False,
|
|
414
|
+
) -> "StaticFiles":
|
|
415
|
+
"""Mount a static file directory at a path prefix.
|
|
416
|
+
|
|
417
|
+
This is a convenience method that creates a StaticFiles handler and
|
|
418
|
+
mounts it. Returns the handler so you can add a custom 404 handler.
|
|
419
|
+
|
|
420
|
+
Args:
|
|
421
|
+
path: Mount point prefix (e.g., "/files", "/static").
|
|
422
|
+
directory: Directory to serve files from.
|
|
423
|
+
name: Optional name for the mount.
|
|
424
|
+
index_files: Files to serve for directory requests.
|
|
425
|
+
Defaults to ["index.gmi", "index.gemini"].
|
|
426
|
+
directory_listing: Enable directory listing when no index found.
|
|
427
|
+
max_file_size: Maximum file size to serve (bytes). Default: 100 MiB.
|
|
428
|
+
mime_types: Custom MIME type mappings by extension.
|
|
429
|
+
follow_symlinks: Whether to follow symbolic links.
|
|
430
|
+
|
|
431
|
+
Returns:
|
|
432
|
+
The StaticFiles handler, for adding custom 404 handling.
|
|
433
|
+
|
|
434
|
+
Example:
|
|
435
|
+
# Simple usage
|
|
436
|
+
app.static("/files", "./public")
|
|
437
|
+
|
|
438
|
+
# With directory listing
|
|
439
|
+
app.static("/docs", "./documentation", directory_listing=True)
|
|
440
|
+
|
|
441
|
+
# With custom 404 handler
|
|
442
|
+
static = app.static("/images", "./static/images")
|
|
443
|
+
|
|
444
|
+
@static.not_found
|
|
445
|
+
def image_not_found(request, path_info):
|
|
446
|
+
return "# Image Not Found"
|
|
447
|
+
"""
|
|
448
|
+
from .staticfiles import StaticFiles
|
|
449
|
+
|
|
450
|
+
handler = StaticFiles(
|
|
451
|
+
directory,
|
|
452
|
+
index_files=index_files,
|
|
453
|
+
directory_listing=directory_listing,
|
|
454
|
+
max_file_size=max_file_size,
|
|
455
|
+
mime_types=mime_types,
|
|
456
|
+
follow_symlinks=follow_symlinks,
|
|
457
|
+
)
|
|
458
|
+
self.mount(path, handler, name=name)
|
|
459
|
+
return handler
|
|
460
|
+
|
|
402
461
|
def vhost(
|
|
403
462
|
self,
|
|
404
463
|
hosts: dict[str, "Xitzin"],
|
|
@@ -243,6 +243,9 @@ class MountedRoute:
|
|
|
243
243
|
Returns:
|
|
244
244
|
True if path starts with this mount's prefix.
|
|
245
245
|
"""
|
|
246
|
+
# Root mount matches all paths
|
|
247
|
+
if self.path_prefix == "/":
|
|
248
|
+
return path.startswith("/")
|
|
246
249
|
# Exact match or prefix with /
|
|
247
250
|
return path == self.path_prefix or path.startswith(self.path_prefix + "/")
|
|
248
251
|
|
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Static file serving for Xitzin applications.
|
|
2
|
+
|
|
3
|
+
This module provides static file serving capabilities for Xitzin,
|
|
4
|
+
enabling capsules to serve files from a directory with configurable
|
|
5
|
+
options for directory listings, MIME types, and security settings.
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
from xitzin import Xitzin
|
|
9
|
+
from xitzin.staticfiles import StaticFiles
|
|
10
|
+
|
|
11
|
+
app = Xitzin()
|
|
12
|
+
|
|
13
|
+
# Mount static files at a path
|
|
14
|
+
app.mount("/files", StaticFiles("./public"))
|
|
15
|
+
|
|
16
|
+
# Or use the convenience method
|
|
17
|
+
app.static("/docs", "./documentation", directory_listing=True)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import mimetypes
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
27
|
+
|
|
28
|
+
from nauyaca.protocol.response import GeminiResponse
|
|
29
|
+
from nauyaca.protocol.status import StatusCode
|
|
30
|
+
|
|
31
|
+
from .exceptions import BadRequest, NotFound
|
|
32
|
+
from .responses import Redirect
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from .requests import Request
|
|
36
|
+
|
|
37
|
+
# Default MIME types for Gemini/common files
|
|
38
|
+
DEFAULT_MIME_TYPES: dict[str, str] = {
|
|
39
|
+
".gmi": "text/gemini",
|
|
40
|
+
".gemini": "text/gemini",
|
|
41
|
+
".txt": "text/plain",
|
|
42
|
+
".md": "text/markdown",
|
|
43
|
+
".html": "text/html",
|
|
44
|
+
".css": "text/css",
|
|
45
|
+
".js": "text/javascript",
|
|
46
|
+
".json": "application/json",
|
|
47
|
+
".xml": "application/xml",
|
|
48
|
+
".png": "image/png",
|
|
49
|
+
".jpg": "image/jpeg",
|
|
50
|
+
".jpeg": "image/jpeg",
|
|
51
|
+
".gif": "image/gif",
|
|
52
|
+
".svg": "image/svg+xml",
|
|
53
|
+
".webp": "image/webp",
|
|
54
|
+
".pdf": "application/pdf",
|
|
55
|
+
".zip": "application/zip",
|
|
56
|
+
".gz": "application/gzip",
|
|
57
|
+
".tar": "application/x-tar",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
# MIME types that should be read as binary
|
|
61
|
+
BINARY_MIME_PREFIXES = (
|
|
62
|
+
"image/",
|
|
63
|
+
"video/",
|
|
64
|
+
"audio/",
|
|
65
|
+
"application/pdf",
|
|
66
|
+
"application/zip",
|
|
67
|
+
"application/gzip",
|
|
68
|
+
"application/x-tar",
|
|
69
|
+
"application/octet-stream",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class StaticFilesConfig:
|
|
75
|
+
"""Configuration for static file serving.
|
|
76
|
+
|
|
77
|
+
Attributes:
|
|
78
|
+
index_files: Files to serve for directory requests.
|
|
79
|
+
directory_listing: Enable directory listing when no index found.
|
|
80
|
+
max_file_size: Maximum file size to serve (bytes).
|
|
81
|
+
mime_types: Custom MIME type mappings by extension.
|
|
82
|
+
follow_symlinks: Whether to follow symbolic links.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
index_files: list[str] = field(
|
|
86
|
+
default_factory=lambda: ["index.gmi", "index.gemini"]
|
|
87
|
+
)
|
|
88
|
+
directory_listing: bool = False
|
|
89
|
+
max_file_size: int = 100 * 1024 * 1024 # 100 MiB
|
|
90
|
+
mime_types: dict[str, str] = field(default_factory=dict)
|
|
91
|
+
follow_symlinks: bool = False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _format_file_size(size: int) -> str:
|
|
95
|
+
"""Format file size in human-readable form.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
size: Size in bytes.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
Human-readable size string (e.g., "1.5 KB", "100 MB").
|
|
102
|
+
"""
|
|
103
|
+
value: float = float(size)
|
|
104
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
105
|
+
if value < 1024:
|
|
106
|
+
if unit == "B":
|
|
107
|
+
return f"{int(value)} {unit}"
|
|
108
|
+
if value < 10:
|
|
109
|
+
return f"{value:.1f} {unit}"
|
|
110
|
+
return f"{int(value)} {unit}"
|
|
111
|
+
value /= 1024
|
|
112
|
+
return f"{int(value)} PB"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class StaticFiles:
|
|
116
|
+
"""Serve static files from a directory.
|
|
117
|
+
|
|
118
|
+
This handler serves files from a specified directory, with support
|
|
119
|
+
for directory indexes, directory listings, custom MIME types,
|
|
120
|
+
and security controls.
|
|
121
|
+
|
|
122
|
+
Example:
|
|
123
|
+
from xitzin.staticfiles import StaticFiles
|
|
124
|
+
|
|
125
|
+
# Basic usage
|
|
126
|
+
handler = StaticFiles("./public")
|
|
127
|
+
app.mount("/files", handler)
|
|
128
|
+
|
|
129
|
+
# With configuration
|
|
130
|
+
handler = StaticFiles(
|
|
131
|
+
"./docs",
|
|
132
|
+
directory_listing=True,
|
|
133
|
+
max_file_size=50 * 1024 * 1024,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
@handler.not_found
|
|
137
|
+
def custom_404(request, path_info):
|
|
138
|
+
return "# File Not Found"
|
|
139
|
+
|
|
140
|
+
app.mount("/docs", handler)
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(
|
|
144
|
+
self,
|
|
145
|
+
directory: Path | str,
|
|
146
|
+
*,
|
|
147
|
+
config: StaticFilesConfig | None = None,
|
|
148
|
+
index_files: list[str] | None = None,
|
|
149
|
+
directory_listing: bool | None = None,
|
|
150
|
+
max_file_size: int | None = None,
|
|
151
|
+
mime_types: dict[str, str] | None = None,
|
|
152
|
+
follow_symlinks: bool | None = None,
|
|
153
|
+
) -> None:
|
|
154
|
+
"""Create a static file handler.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
directory: Directory to serve files from.
|
|
158
|
+
config: Configuration object (overridden by other params).
|
|
159
|
+
index_files: Files to serve for directory requests.
|
|
160
|
+
directory_listing: Enable directory listing when no index found.
|
|
161
|
+
max_file_size: Maximum file size to serve (bytes).
|
|
162
|
+
mime_types: Custom MIME type mappings by extension.
|
|
163
|
+
follow_symlinks: Whether to follow symbolic links.
|
|
164
|
+
|
|
165
|
+
Raises:
|
|
166
|
+
ValueError: If directory doesn't exist or isn't a directory.
|
|
167
|
+
"""
|
|
168
|
+
self.directory = Path(directory).resolve()
|
|
169
|
+
self._not_found_handler: Callable[[Any, str], Any] | None = None
|
|
170
|
+
|
|
171
|
+
if not self.directory.exists():
|
|
172
|
+
raise ValueError(f"Directory not found: {directory}")
|
|
173
|
+
if not self.directory.is_dir():
|
|
174
|
+
raise ValueError(f"Path is not a directory: {directory}")
|
|
175
|
+
|
|
176
|
+
# Start with config defaults, override with explicit parameters
|
|
177
|
+
base_config = config or StaticFilesConfig()
|
|
178
|
+
|
|
179
|
+
self.index_files = (
|
|
180
|
+
index_files if index_files is not None else base_config.index_files
|
|
181
|
+
)
|
|
182
|
+
self.directory_listing = (
|
|
183
|
+
directory_listing
|
|
184
|
+
if directory_listing is not None
|
|
185
|
+
else base_config.directory_listing
|
|
186
|
+
)
|
|
187
|
+
self.max_file_size = (
|
|
188
|
+
max_file_size if max_file_size is not None else base_config.max_file_size
|
|
189
|
+
)
|
|
190
|
+
self.follow_symlinks = (
|
|
191
|
+
follow_symlinks
|
|
192
|
+
if follow_symlinks is not None
|
|
193
|
+
else base_config.follow_symlinks
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# Build MIME type mapping: defaults + config + explicit
|
|
197
|
+
self._mime_types = {**DEFAULT_MIME_TYPES}
|
|
198
|
+
self._mime_types.update(base_config.mime_types)
|
|
199
|
+
if mime_types:
|
|
200
|
+
self._mime_types.update(mime_types)
|
|
201
|
+
|
|
202
|
+
def not_found(
|
|
203
|
+
self, handler: Callable[[Any, str], Any]
|
|
204
|
+
) -> Callable[[Any, str], Any]:
|
|
205
|
+
"""Register a custom not-found handler.
|
|
206
|
+
|
|
207
|
+
The handler receives (request, path_info) and should return a response.
|
|
208
|
+
|
|
209
|
+
Example:
|
|
210
|
+
@handler.not_found
|
|
211
|
+
def custom_404(request, path_info):
|
|
212
|
+
return f"# Not Found\\n\\nFile {path_info} doesn't exist."
|
|
213
|
+
"""
|
|
214
|
+
self._not_found_handler = handler
|
|
215
|
+
return handler
|
|
216
|
+
|
|
217
|
+
async def __call__(self, request: Request, path_info: str) -> GeminiResponse:
|
|
218
|
+
"""Handle a request for a static file.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
request: The Gemini request.
|
|
222
|
+
path_info: Path after the mount prefix (e.g., "/docs/page.gmi").
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
GeminiResponse with the file content or error.
|
|
226
|
+
|
|
227
|
+
Raises:
|
|
228
|
+
NotFound: If file doesn't exist (and no custom handler).
|
|
229
|
+
BadRequest: If path validation fails.
|
|
230
|
+
"""
|
|
231
|
+
try:
|
|
232
|
+
# Normalize path_info
|
|
233
|
+
path_info = path_info.lstrip("/") if path_info else ""
|
|
234
|
+
|
|
235
|
+
# Resolve and validate path
|
|
236
|
+
file_path = self._resolve_path(path_info)
|
|
237
|
+
|
|
238
|
+
# Handle directory
|
|
239
|
+
if file_path.is_dir():
|
|
240
|
+
return await self._serve_directory(request, file_path, path_info)
|
|
241
|
+
|
|
242
|
+
# Handle file
|
|
243
|
+
return await self._serve_file(file_path)
|
|
244
|
+
|
|
245
|
+
except NotFound:
|
|
246
|
+
if self._not_found_handler is not None:
|
|
247
|
+
result = self._not_found_handler(request, path_info)
|
|
248
|
+
if asyncio.iscoroutine(result):
|
|
249
|
+
result = await result
|
|
250
|
+
return self._convert_handler_result(result)
|
|
251
|
+
raise
|
|
252
|
+
|
|
253
|
+
def _resolve_path(self, path_info: str) -> Path:
|
|
254
|
+
"""Resolve path_info to a validated filesystem path.
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
path_info: Requested path relative to mount point.
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
Resolved Path object.
|
|
261
|
+
|
|
262
|
+
Raises:
|
|
263
|
+
BadRequest: If path contains traversal attempts.
|
|
264
|
+
NotFound: If resolved path doesn't exist.
|
|
265
|
+
"""
|
|
266
|
+
# Reject obvious traversal attempts early
|
|
267
|
+
if ".." in path_info:
|
|
268
|
+
raise BadRequest("Invalid path")
|
|
269
|
+
|
|
270
|
+
# Build candidate path
|
|
271
|
+
if path_info:
|
|
272
|
+
candidate = self.directory / path_info
|
|
273
|
+
else:
|
|
274
|
+
candidate = self.directory
|
|
275
|
+
|
|
276
|
+
# Resolve the path, handling symlinks based on config
|
|
277
|
+
if self.follow_symlinks:
|
|
278
|
+
resolved = candidate.resolve()
|
|
279
|
+
else:
|
|
280
|
+
# Resolve parent but not the final component
|
|
281
|
+
resolved = candidate.parent.resolve() / candidate.name
|
|
282
|
+
# Check if final component is a symlink
|
|
283
|
+
if resolved.is_symlink():
|
|
284
|
+
raise BadRequest("Symbolic links not allowed")
|
|
285
|
+
# Now fully resolve to catch any issues
|
|
286
|
+
resolved = resolved.resolve()
|
|
287
|
+
|
|
288
|
+
# Security check: ensure path is within allowed directory
|
|
289
|
+
try:
|
|
290
|
+
resolved.relative_to(self.directory)
|
|
291
|
+
except ValueError:
|
|
292
|
+
raise BadRequest("Invalid path") from None
|
|
293
|
+
|
|
294
|
+
# Check existence
|
|
295
|
+
if not resolved.exists():
|
|
296
|
+
raise NotFound("File not found")
|
|
297
|
+
|
|
298
|
+
return resolved
|
|
299
|
+
|
|
300
|
+
def _get_mime_type(self, file_path: Path) -> str:
|
|
301
|
+
"""Determine MIME type for a file.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
file_path: Path to the file.
|
|
305
|
+
|
|
306
|
+
Returns:
|
|
307
|
+
MIME type string.
|
|
308
|
+
"""
|
|
309
|
+
suffix = file_path.suffix.lower()
|
|
310
|
+
|
|
311
|
+
# Check custom mappings first
|
|
312
|
+
if suffix in self._mime_types:
|
|
313
|
+
return self._mime_types[suffix]
|
|
314
|
+
|
|
315
|
+
# Try stdlib mimetypes
|
|
316
|
+
guessed, _ = mimetypes.guess_type(str(file_path))
|
|
317
|
+
if guessed:
|
|
318
|
+
return guessed
|
|
319
|
+
|
|
320
|
+
# Default to text/gemini for Gemini-centric behavior
|
|
321
|
+
return "text/gemini"
|
|
322
|
+
|
|
323
|
+
def _is_binary_mime(self, mime_type: str) -> bool:
|
|
324
|
+
"""Check if MIME type indicates binary content.
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
mime_type: MIME type string.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
True if content should be read as binary.
|
|
331
|
+
"""
|
|
332
|
+
return mime_type.startswith(BINARY_MIME_PREFIXES)
|
|
333
|
+
|
|
334
|
+
async def _serve_file(self, file_path: Path) -> GeminiResponse:
|
|
335
|
+
"""Serve a file with appropriate MIME type.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
file_path: Path to the file.
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
GeminiResponse with file content.
|
|
342
|
+
|
|
343
|
+
Raises:
|
|
344
|
+
BadRequest: If file exceeds size limit.
|
|
345
|
+
NotFound: If file cannot be read.
|
|
346
|
+
"""
|
|
347
|
+
# Check file size before reading
|
|
348
|
+
try:
|
|
349
|
+
size = file_path.stat().st_size
|
|
350
|
+
except OSError:
|
|
351
|
+
raise NotFound("File not found") from None
|
|
352
|
+
|
|
353
|
+
if size > self.max_file_size:
|
|
354
|
+
raise BadRequest(
|
|
355
|
+
f"File too large ({_format_file_size(size)}, "
|
|
356
|
+
f"max {_format_file_size(self.max_file_size)})"
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
mime_type = self._get_mime_type(file_path)
|
|
360
|
+
is_binary = self._is_binary_mime(mime_type)
|
|
361
|
+
|
|
362
|
+
try:
|
|
363
|
+
if is_binary:
|
|
364
|
+
# Read binary in thread to avoid blocking
|
|
365
|
+
body: str | bytes = await asyncio.to_thread(file_path.read_bytes)
|
|
366
|
+
else:
|
|
367
|
+
body = await asyncio.to_thread(file_path.read_text, encoding="utf-8")
|
|
368
|
+
except UnicodeDecodeError:
|
|
369
|
+
# Fall back to binary if text decode fails
|
|
370
|
+
body = await asyncio.to_thread(file_path.read_bytes)
|
|
371
|
+
except OSError:
|
|
372
|
+
raise NotFound("File not found") from None
|
|
373
|
+
|
|
374
|
+
return GeminiResponse(
|
|
375
|
+
status=StatusCode.SUCCESS,
|
|
376
|
+
meta=mime_type,
|
|
377
|
+
body=body,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
async def _serve_directory(
|
|
381
|
+
self, request: Request, dir_path: Path, path_info: str
|
|
382
|
+
) -> GeminiResponse:
|
|
383
|
+
"""Serve a directory request.
|
|
384
|
+
|
|
385
|
+
Args:
|
|
386
|
+
request: The Gemini request.
|
|
387
|
+
dir_path: Path to the directory.
|
|
388
|
+
path_info: Original path_info for this request.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
GeminiResponse with index file, directory listing, or redirect.
|
|
392
|
+
|
|
393
|
+
Raises:
|
|
394
|
+
NotFound: If no index and directory listing disabled.
|
|
395
|
+
"""
|
|
396
|
+
# Ensure trailing slash for directories
|
|
397
|
+
if path_info and not request.path.endswith("/"):
|
|
398
|
+
redirect_url = request.path + "/"
|
|
399
|
+
return Redirect(redirect_url, permanent=False).to_gemini_response()
|
|
400
|
+
|
|
401
|
+
# Try to find an index file
|
|
402
|
+
for index_name in self.index_files:
|
|
403
|
+
index_path = dir_path / index_name
|
|
404
|
+
if index_path.is_file():
|
|
405
|
+
return await self._serve_file(index_path)
|
|
406
|
+
|
|
407
|
+
# Generate directory listing if enabled
|
|
408
|
+
if self.directory_listing:
|
|
409
|
+
listing = self._generate_directory_listing(dir_path, path_info)
|
|
410
|
+
return GeminiResponse(
|
|
411
|
+
status=StatusCode.SUCCESS,
|
|
412
|
+
meta="text/gemini",
|
|
413
|
+
body=listing,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
raise NotFound("Directory index not found")
|
|
417
|
+
|
|
418
|
+
def _generate_directory_listing(self, dir_path: Path, request_path: str) -> str:
|
|
419
|
+
"""Generate a Gemini directory listing.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
dir_path: Path to the directory.
|
|
423
|
+
request_path: The request path for display.
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
Gemtext directory listing.
|
|
427
|
+
"""
|
|
428
|
+
display_path = "/" + request_path if request_path else "/"
|
|
429
|
+
lines = [f"# Index of {display_path}", ""]
|
|
430
|
+
|
|
431
|
+
# Parent directory link (if not at root)
|
|
432
|
+
if request_path:
|
|
433
|
+
lines.append("=> ../ ..")
|
|
434
|
+
lines.append("")
|
|
435
|
+
|
|
436
|
+
# Collect and sort entries: directories first, then files
|
|
437
|
+
entries = []
|
|
438
|
+
try:
|
|
439
|
+
for entry in dir_path.iterdir():
|
|
440
|
+
# Skip hidden files
|
|
441
|
+
if entry.name.startswith("."):
|
|
442
|
+
continue
|
|
443
|
+
|
|
444
|
+
# Skip symlinks if not following them
|
|
445
|
+
if not self.follow_symlinks and entry.is_symlink():
|
|
446
|
+
continue
|
|
447
|
+
|
|
448
|
+
entries.append(entry)
|
|
449
|
+
except OSError:
|
|
450
|
+
pass
|
|
451
|
+
|
|
452
|
+
# Sort: directories first, then alphabetically by name
|
|
453
|
+
entries.sort(key=lambda p: (not p.is_dir(), p.name.lower()))
|
|
454
|
+
|
|
455
|
+
# Generate links
|
|
456
|
+
for entry in entries:
|
|
457
|
+
name = entry.name
|
|
458
|
+
if entry.is_dir():
|
|
459
|
+
lines.append(f"=> {name}/ {name}/")
|
|
460
|
+
else:
|
|
461
|
+
try:
|
|
462
|
+
size = _format_file_size(entry.stat().st_size)
|
|
463
|
+
lines.append(f"=> {name} {name} ({size})")
|
|
464
|
+
except OSError:
|
|
465
|
+
lines.append(f"=> {name} {name}")
|
|
466
|
+
|
|
467
|
+
return "\n".join(lines)
|
|
468
|
+
|
|
469
|
+
def _convert_handler_result(self, result: Any) -> GeminiResponse:
|
|
470
|
+
"""Convert a custom handler result to GeminiResponse.
|
|
471
|
+
|
|
472
|
+
Args:
|
|
473
|
+
result: Handler return value.
|
|
474
|
+
|
|
475
|
+
Returns:
|
|
476
|
+
GeminiResponse.
|
|
477
|
+
"""
|
|
478
|
+
# Import here to avoid circular import
|
|
479
|
+
from .responses import convert_response
|
|
480
|
+
|
|
481
|
+
return convert_response(result)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
__all__ = [
|
|
485
|
+
"StaticFiles",
|
|
486
|
+
"StaticFilesConfig",
|
|
487
|
+
]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|