blazeserve 0.1.0__py3-none-any.whl

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.
blazeserve/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __all__ = ["__version__"]
2
+ __version__ = "0.1.0"
blazeserve/cli.py ADDED
@@ -0,0 +1,418 @@
1
+ import os
2
+ import sys
3
+ import socket
4
+ import webbrowser
5
+ from typing import Optional
6
+
7
+ try:
8
+ import rich_click as click
9
+
10
+ click.rich_click.SHOW_ARGUMENTS = True
11
+ click.rich_click.USE_MARKDOWN = True
12
+ click.rich_click.STYLE_HELPTEXT = "cyan"
13
+ click.rich_click.STYLE_OPTION = "bold bright_white"
14
+ click.rich_click.STYLE_SWITCH = "bold bright_white"
15
+ click.rich_click.STYLE_HELPTEXT_FIRST_LINE = "bold cyan"
16
+ except Exception:
17
+ import click # type: ignore
18
+
19
+ from rich.table import Table
20
+ from rich.panel import Panel
21
+ from rich import box
22
+
23
+ from .logging import setup_logging, get_console
24
+ from .server import build_arg_parser, run_server
25
+ from .utils import sha256_file, human_size
26
+ from . import __version__
27
+
28
+ console = get_console()
29
+
30
+
31
+ def _lan_ip() -> str:
32
+ try:
33
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
34
+ s.settimeout(0.05)
35
+ s.connect(("8.8.8.8", 80))
36
+ ip = s.getsockname()[0]
37
+ s.close()
38
+ return ip
39
+ except Exception:
40
+ return "127.0.0.1"
41
+
42
+
43
+ @click.group(
44
+ context_settings=dict(help_option_names=["-h", "--help"]),
45
+ invoke_without_command=False,
46
+ )
47
+ @click.version_option(version=__version__, prog_name="blaze")
48
+ def cli() -> None:
49
+ setup_logging("WARNING")
50
+
51
+
52
+ @cli.command("serve", short_help="Serve a directory or a single file.")
53
+ @click.argument(
54
+ "path",
55
+ type=click.Path(exists=True, dir_okay=True, file_okay=True, path_type=str),
56
+ default=".",
57
+ )
58
+ @click.option(
59
+ "--host",
60
+ default="0.0.0.0",
61
+ show_default=True,
62
+ help="Bind address (IPv4/IPv6 literal ok).",
63
+ )
64
+ @click.option(
65
+ "-p", "--port", type=int, default=8000, show_default=True, help="Port to listen on."
66
+ )
67
+ @click.option(
68
+ "--single",
69
+ type=click.Path(exists=True, dir_okay=False, file_okay=True, path_type=str),
70
+ help="Serve exactly this file.",
71
+ )
72
+ @click.option("--no-listing", is_flag=True, help="Disable directory listing.")
73
+ @click.option(
74
+ "--chunk-mb",
75
+ type=click.IntRange(4, 4096),
76
+ default=128,
77
+ show_default=True,
78
+ help="mmap/read window size.",
79
+ )
80
+ @click.option(
81
+ "--sock-sndbuf-mb",
82
+ type=click.IntRange(1, 2048),
83
+ default=64,
84
+ show_default=True,
85
+ help="SO_SNDBUF size.",
86
+ )
87
+ @click.option(
88
+ "--timeout",
89
+ type=click.IntRange(60, 86400),
90
+ default=1800,
91
+ show_default=True,
92
+ help="Per-connection timeout (seconds).",
93
+ )
94
+ @click.option(
95
+ "--rate-mbps",
96
+ type=click.FloatRange(min=0.1),
97
+ default=None,
98
+ help="Throttle to MB/s (omit for unlimited).",
99
+ )
100
+ @click.option(
101
+ "--auth", metavar="USER:PASS", envvar=None, help="Enable HTTP Basic Auth."
102
+ )
103
+ @click.option(
104
+ "--auth-env", metavar="ENVVAR", help="Load USER:PASS from environment variable."
105
+ )
106
+ @click.option(
107
+ "--tls-cert",
108
+ type=click.Path(exists=True, dir_okay=False, path_type=str),
109
+ help="TLS certificate (PEM).",
110
+ )
111
+ @click.option(
112
+ "--tls-key",
113
+ type=click.Path(exists=True, dir_okay=False, path_type=str),
114
+ help="TLS private key (PEM).",
115
+ )
116
+ @click.option("--cors/--no-cors", default=False, show_default=True, help="Enable CORS.")
117
+ @click.option(
118
+ "--cors-origin", default="*", show_default=True, help="CORS allow origin."
119
+ )
120
+ @click.option("--no-cache", is_flag=True, help="Disable HTTP caching.")
121
+ @click.option(
122
+ "--index", multiple=True, help="Additional index filenames to try (repeatable)."
123
+ )
124
+ @click.option(
125
+ "--backlog",
126
+ type=click.IntRange(1, 20000),
127
+ default=4096,
128
+ show_default=True,
129
+ help="Listen backlog size.",
130
+ )
131
+ @click.option(
132
+ "--precompress/--no-precompress",
133
+ default=True,
134
+ show_default=True,
135
+ help="Serve .gz assets when safe.",
136
+ )
137
+ @click.option(
138
+ "--max-upload-mb",
139
+ type=click.IntRange(0, 1024 * 1024),
140
+ default=0,
141
+ show_default=True,
142
+ help="Max upload size (0 = unlimited).",
143
+ )
144
+ @click.option(
145
+ "--open", "open_browser", is_flag=True, help="Open the URL in a browser on start."
146
+ )
147
+ @click.option("-v", "--verbose", is_flag=True, help="Verbose startup banner.")
148
+ def serve_cmd(
149
+ path: str,
150
+ host: str,
151
+ port: int,
152
+ single: Optional[str],
153
+ no_listing: bool,
154
+ chunk_mb: int,
155
+ sock_sndbuf_mb: int,
156
+ timeout: int,
157
+ rate_mbps: Optional[float],
158
+ auth: Optional[str],
159
+ auth_env: Optional[str],
160
+ tls_cert: Optional[str],
161
+ tls_key: Optional[str],
162
+ cors: bool,
163
+ cors_origin: str,
164
+ no_cache: bool,
165
+ index: tuple[str, ...],
166
+ backlog: int,
167
+ precompress: bool,
168
+ max_upload_mb: int,
169
+ open_browser: bool,
170
+ verbose: bool,
171
+ ) -> None:
172
+ setup_logging("INFO" if verbose else "WARNING")
173
+ target = os.path.abspath(path)
174
+ if single:
175
+ single = os.path.abspath(single)
176
+ if not os.path.isfile(single):
177
+ raise click.ClickException(f"Single file not found: {single}")
178
+ base = os.path.dirname(single)
179
+ else:
180
+ if not os.path.exists(target):
181
+ raise click.ClickException(f"Path not found: {target}")
182
+ base = os.path.dirname(target) if os.path.isfile(target) else target
183
+ os.chdir(base)
184
+ if not auth and auth_env:
185
+ val = os.environ.get(auth_env, "")
186
+ if val:
187
+ auth = val
188
+ scheme = "https" if (tls_cert and tls_key) else "http"
189
+ lan = _lan_ip()
190
+ table = Table.grid(padding=(0, 2))
191
+ table.add_column(justify="right", style="bold cyan")
192
+ table.add_column(style="bold white")
193
+ table.add_row("Serving", single or base)
194
+ table.add_row("Local", f"[green]{scheme}://localhost:{port}/[/]")
195
+ table.add_row("Network", f"[green]{scheme}://{lan}:{port}/[/]")
196
+ console.print(
197
+ Panel(table, title="[bold magenta]BlazeServe", box=box.ROUNDED), soft_wrap=True
198
+ )
199
+ if open_browser:
200
+ try:
201
+ webbrowser.open(f"{scheme}://localhost:{port}/")
202
+ except Exception:
203
+ pass
204
+ try:
205
+ run_server(
206
+ host=host,
207
+ port=port,
208
+ base=base,
209
+ single=single,
210
+ listing=not no_listing,
211
+ chunk_mb=chunk_mb,
212
+ sndbuf_mb=sock_sndbuf_mb,
213
+ timeout=timeout,
214
+ rate_mbps=rate_mbps,
215
+ auth=auth,
216
+ tls_cert=tls_cert,
217
+ tls_key=tls_key,
218
+ cors=cors,
219
+ cors_origin=cors_origin,
220
+ no_cache=no_cache,
221
+ index=list(index) if index else None,
222
+ backlog=backlog,
223
+ precompress=precompress,
224
+ max_upload_mb=max_upload_mb,
225
+ verbose=False,
226
+ )
227
+ except KeyboardInterrupt:
228
+ console.print("[yellow]Shutting down...[/]")
229
+
230
+
231
+ @cli.command("send", short_help="Quick share a single file.")
232
+ @click.argument(
233
+ "file", type=click.Path(exists=True, dir_okay=False, file_okay=True, path_type=str)
234
+ )
235
+ @click.option("--host", default="0.0.0.0", show_default=True)
236
+ @click.option("-p", "--port", type=int, default=8000, show_default=True)
237
+ @click.option("--rate-mbps", type=click.FloatRange(min=0.1), default=None)
238
+ @click.option("--auth", metavar="USER:PASS")
239
+ @click.option("--auth-env", metavar="ENVVAR")
240
+ @click.option("--tls-cert", type=click.Path(exists=True, dir_okay=False, path_type=str))
241
+ @click.option("--tls-key", type=click.Path(exists=True, dir_okay=False, path_type=str))
242
+ @click.option("--cors/--no-cors", default=False, show_default=True)
243
+ @click.option("--cors-origin", default="*", show_default=True)
244
+ @click.option("--no-cache", is_flag=True)
245
+ @click.option(
246
+ "--backlog", type=click.IntRange(1, 20000), default=4096, show_default=True
247
+ )
248
+ @click.option("--precompress/--no-precompress", default=True, show_default=True)
249
+ @click.option(
250
+ "--max-upload-mb", type=click.IntRange(0, 1024 * 1024), default=0, show_default=True
251
+ )
252
+ def send_cmd(
253
+ file: str,
254
+ host: str,
255
+ port: int,
256
+ rate_mbps: Optional[float],
257
+ auth: Optional[str],
258
+ auth_env: Optional[str],
259
+ tls_cert: Optional[str],
260
+ tls_key: Optional[str],
261
+ cors: bool,
262
+ cors_origin: str,
263
+ no_cache: bool,
264
+ backlog: int,
265
+ precompress: bool,
266
+ max_upload_mb: int,
267
+ ) -> None:
268
+ setup_logging("INFO")
269
+ ap = os.path.abspath(file)
270
+ base = os.path.dirname(ap)
271
+ os.chdir(base)
272
+ if not auth and auth_env:
273
+ val = os.environ.get(auth_env, "")
274
+ if val:
275
+ auth = val
276
+ scheme = "https" if (tls_cert and tls_key) else "http"
277
+ lan = _lan_ip()
278
+ console.print(f"[bold green]Share:[/] {ap}")
279
+ console.print(f"[cyan]{scheme}://{lan}:{port}/[/]")
280
+ try:
281
+ run_server(
282
+ host=host,
283
+ port=port,
284
+ base=base,
285
+ single=ap,
286
+ listing=False,
287
+ chunk_mb=128,
288
+ sndbuf_mb=64,
289
+ timeout=1800,
290
+ rate_mbps=rate_mbps,
291
+ auth=auth,
292
+ tls_cert=tls_cert,
293
+ tls_key=tls_key,
294
+ cors=cors,
295
+ cors_origin=cors_origin,
296
+ no_cache=no_cache,
297
+ index=None,
298
+ backlog=backlog,
299
+ precompress=precompress,
300
+ max_upload_mb=max_upload_mb,
301
+ verbose=False,
302
+ )
303
+ except KeyboardInterrupt:
304
+ console.print("[yellow]Shutting down...[/]")
305
+
306
+
307
+ @cli.command("checksum", short_help="SHA256 for files.")
308
+ @click.argument(
309
+ "files", nargs=-1, type=click.Path(exists=True, dir_okay=False, path_type=str)
310
+ )
311
+ def checksum_cmd(files):
312
+ if not files:
313
+ raise click.ClickException("Provide at least one file.")
314
+ rows = []
315
+ for p in files:
316
+ ap = os.path.abspath(p)
317
+ digest = sha256_file(ap)
318
+ rows.append((digest, p, human_size(os.path.getsize(ap))))
319
+ tbl = Table(title="SHA256", box=box.SIMPLE, show_lines=False)
320
+ tbl.add_column("Digest", style="green")
321
+ tbl.add_column("File", overflow="fold")
322
+ tbl.add_column("Size", justify="right", style="cyan")
323
+ for d, f, sz in rows:
324
+ tbl.add_row(d, f, sz)
325
+ console.print(tbl)
326
+
327
+
328
+ @cli.command("version", short_help="Show version.")
329
+ def version_cmd():
330
+ console.print(f"[bold]BlazeServe[/] {__version__}")
331
+
332
+
333
+ def main():
334
+ if len(sys.argv) > 1 and sys.argv[1] not in (
335
+ "serve",
336
+ "send",
337
+ "checksum",
338
+ "version",
339
+ "-h",
340
+ "--help",
341
+ "--version",
342
+ ):
343
+ try:
344
+ parser = build_arg_parser()
345
+ args = parser.parse_args()
346
+ if getattr(args, "cmd", None) in (None, "serve"):
347
+ target = os.path.abspath(getattr(args, "path", "."))
348
+ if getattr(args, "single", None):
349
+ single = os.path.abspath(args.single)
350
+ base = os.path.dirname(single)
351
+ else:
352
+ base = os.path.dirname(target) if os.path.isfile(target) else target
353
+ os.chdir(base)
354
+ run_server(
355
+ host=args.host,
356
+ port=args.port,
357
+ base=base,
358
+ single=getattr(args, "single", None),
359
+ listing=not getattr(args, "no_listing", False),
360
+ chunk_mb=getattr(args, "chunk_mb", 128),
361
+ sndbuf_mb=getattr(args, "sock_sndbuf_mb", 64),
362
+ timeout=getattr(args, "timeout", 1800),
363
+ rate_mbps=getattr(args, "rate_mbps", None),
364
+ auth=getattr(args, "auth", None),
365
+ tls_cert=getattr(args, "tls_cert", None),
366
+ tls_key=getattr(args, "tls_key", None),
367
+ cors=False,
368
+ cors_origin="*",
369
+ no_cache=False,
370
+ index=None,
371
+ backlog=4096,
372
+ precompress=True,
373
+ max_upload_mb=0,
374
+ verbose=False,
375
+ )
376
+ return
377
+ if args.cmd == "send":
378
+ ap = os.path.abspath(args.file)
379
+ base = os.path.dirname(ap)
380
+ os.chdir(base)
381
+ run_server(
382
+ host=args.host,
383
+ port=args.port,
384
+ base=base,
385
+ single=ap,
386
+ listing=False,
387
+ chunk_mb=128,
388
+ sndbuf_mb=64,
389
+ timeout=1800,
390
+ rate_mbps=args.rate_mbps,
391
+ auth=args.auth,
392
+ tls_cert=args.tls_cert,
393
+ tls_key=args.tls_key,
394
+ cors=False,
395
+ cors_origin="*",
396
+ no_cache=False,
397
+ index=None,
398
+ backlog=4096,
399
+ precompress=True,
400
+ max_upload_mb=0,
401
+ verbose=False,
402
+ )
403
+ return
404
+ if args.cmd == "checksum":
405
+ rc = 0
406
+ for p in args.files:
407
+ ap = os.path.abspath(p)
408
+ if not os.path.isfile(ap):
409
+ sys.stderr.write(f"Skip (not a file): {p}\n")
410
+ rc = 2
411
+ continue
412
+ print(f"{sha256_file(ap)} {p}")
413
+ sys.exit(rc)
414
+ except SystemExit:
415
+ raise
416
+ except Exception as e:
417
+ raise click.ClickException(str(e))
418
+ cli()
blazeserve/logging.py ADDED
@@ -0,0 +1,24 @@
1
+ import logging
2
+ from typing import Optional
3
+ from rich.console import Console
4
+ from rich.logging import RichHandler
5
+
6
+ _console: Optional[Console] = None
7
+
8
+
9
+ def setup_logging(level: str = "WARNING") -> None:
10
+ global _console
11
+ _console = _console or Console()
12
+ logging.basicConfig(
13
+ level=getattr(logging, level.upper(), logging.WARNING),
14
+ format="%(message)s",
15
+ datefmt="[%X]",
16
+ handlers=[RichHandler(console=_console, markup=True, rich_tracebacks=True)],
17
+ )
18
+
19
+
20
+ def get_console() -> Console:
21
+ global _console
22
+ if _console is None:
23
+ _console = Console()
24
+ return _console