webstat 0.1.0__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.
webstat-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 h45sh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
webstat-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: webstat
3
+ Version: 0.1.0
4
+ Summary: Fast website status checker, recovery watcher, and desktop reminder
5
+ Author: h45sh
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/h45sh/webstat
8
+ Project-URL: Repository, https://github.com/h45sh/webstat
9
+ Project-URL: Issues, https://github.com/h45sh/webstat/issues
10
+ Keywords: website,uptime,status,monitoring,cli,desktop-widget,omarchy
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: System :: Monitoring
22
+ Classifier: Topic :: System :: Networking :: Monitoring
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: httpx>=0.25.0
27
+ Requires-Dist: rich>=13.0.0
28
+ Requires-Dist: typer>=0.9.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
31
+ Requires-Dist: build>=1.0.0; extra == "dev"
32
+ Requires-Dist: twine>=4.0.0; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # webstat
36
+
37
+ Fast website status checker, recovery watcher, and desktop reminder for Linux and Omarchy.
38
+
39
+ `webstat` is designed to solve a simple, frustrating problem: a website or service you are trying to use is down or failing to respond, and you don't want to keep pressing `F5` / `Ctrl+R` manually. You enter the site name; `webstat` checks its status immediately, monitors it in the background if it's down, and reminds you the instant it comes back online with an actionable desktop notification and automatic browser launch.
40
+
41
+ ## Features
42
+
43
+ - **Instant Check**: Quick one-shot diagnosis (`webstat github.com` or `webstat check mysite.org`).
44
+ - **Foreground Watch Mode**: Real-time updating terminal status (`webstat watch downsite.com`).
45
+ - **Desktop Recovery Notification**: Dispatches native Omarchy desktop notifications (`omarchy notification send`) or standard `notify-send`.
46
+ - **One-Click Browser Launch**: Click the notification or use the `--open` flag to automatically open the site in your default browser once it recovers.
47
+ - **Persistent Watchlist**: Queue sites for background monitoring (`webstat add`, `webstat list`, `webstat remove`).
48
+ - **Omarchy Shell Integration**: Native top-bar widget and interactive management panel.
49
+ - **SSL Certificate Expiry Warnings**: Alerts if TLS certificates are expiring soon.
50
+
51
+ ## Installation
52
+
53
+ ### CLI Installation
54
+
55
+ ```bash
56
+ # Recommended: Install from PyPI via pipx
57
+ pipx install webstat
58
+ # or standard pip:
59
+ pip install webstat
60
+
61
+ # Arch Linux / Omarchy (AUR):
62
+ yay -S webstat-git
63
+
64
+ # Or install from source:
65
+ git clone https://github.com/h45sh/webstat.git
66
+ cd webstat
67
+ pip install .
68
+ ```
69
+
70
+ ### Omarchy Shell Plugin Installation
71
+ ```bash
72
+ # Add and enable the plugin in Omarchy
73
+ omarchy plugin add https://github.com/h45sh/omarchy-webstat.git --enable
74
+ ```
75
+ Or for local development from this monorepo:
76
+ ```bash
77
+ cp -r plugin ~/.config/omarchy/plugins/h45sh.webstat
78
+ omarchy plugin enable h45sh.webstat
79
+ ```
80
+
81
+ ## Usage
82
+
83
+ ### Quick Status Check
84
+ ```bash
85
+ webstat github.com
86
+ webstat check httpbin.org/status/503 --watch
87
+ ```
88
+
89
+ ### Watching a Site Until Recovery
90
+ ```bash
91
+ # Watch until online and automatically open in browser
92
+ webstat watch mysite.com --open
93
+
94
+ # Watch multiple sites concurrently
95
+ webstat watch github.com api.mycorp.internal staging.service.io
96
+ ```
97
+
98
+ ### Background Watchlist Management
99
+ ```bash
100
+ # Add a site to monitor in background
101
+ webstat add api.myservice.com --open
102
+
103
+ # View current status of all monitored sites
104
+ webstat list
105
+
106
+ # Remove a site
107
+ webstat remove api.myservice.com
108
+ ```
109
+
110
+ ## License
111
+ MIT © [h45sh](https://github.com/h45sh)
@@ -0,0 +1,77 @@
1
+ # webstat
2
+
3
+ Fast website status checker, recovery watcher, and desktop reminder for Linux and Omarchy.
4
+
5
+ `webstat` is designed to solve a simple, frustrating problem: a website or service you are trying to use is down or failing to respond, and you don't want to keep pressing `F5` / `Ctrl+R` manually. You enter the site name; `webstat` checks its status immediately, monitors it in the background if it's down, and reminds you the instant it comes back online with an actionable desktop notification and automatic browser launch.
6
+
7
+ ## Features
8
+
9
+ - **Instant Check**: Quick one-shot diagnosis (`webstat github.com` or `webstat check mysite.org`).
10
+ - **Foreground Watch Mode**: Real-time updating terminal status (`webstat watch downsite.com`).
11
+ - **Desktop Recovery Notification**: Dispatches native Omarchy desktop notifications (`omarchy notification send`) or standard `notify-send`.
12
+ - **One-Click Browser Launch**: Click the notification or use the `--open` flag to automatically open the site in your default browser once it recovers.
13
+ - **Persistent Watchlist**: Queue sites for background monitoring (`webstat add`, `webstat list`, `webstat remove`).
14
+ - **Omarchy Shell Integration**: Native top-bar widget and interactive management panel.
15
+ - **SSL Certificate Expiry Warnings**: Alerts if TLS certificates are expiring soon.
16
+
17
+ ## Installation
18
+
19
+ ### CLI Installation
20
+
21
+ ```bash
22
+ # Recommended: Install from PyPI via pipx
23
+ pipx install webstat
24
+ # or standard pip:
25
+ pip install webstat
26
+
27
+ # Arch Linux / Omarchy (AUR):
28
+ yay -S webstat-git
29
+
30
+ # Or install from source:
31
+ git clone https://github.com/h45sh/webstat.git
32
+ cd webstat
33
+ pip install .
34
+ ```
35
+
36
+ ### Omarchy Shell Plugin Installation
37
+ ```bash
38
+ # Add and enable the plugin in Omarchy
39
+ omarchy plugin add https://github.com/h45sh/omarchy-webstat.git --enable
40
+ ```
41
+ Or for local development from this monorepo:
42
+ ```bash
43
+ cp -r plugin ~/.config/omarchy/plugins/h45sh.webstat
44
+ omarchy plugin enable h45sh.webstat
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ### Quick Status Check
50
+ ```bash
51
+ webstat github.com
52
+ webstat check httpbin.org/status/503 --watch
53
+ ```
54
+
55
+ ### Watching a Site Until Recovery
56
+ ```bash
57
+ # Watch until online and automatically open in browser
58
+ webstat watch mysite.com --open
59
+
60
+ # Watch multiple sites concurrently
61
+ webstat watch github.com api.mycorp.internal staging.service.io
62
+ ```
63
+
64
+ ### Background Watchlist Management
65
+ ```bash
66
+ # Add a site to monitor in background
67
+ webstat add api.myservice.com --open
68
+
69
+ # View current status of all monitored sites
70
+ webstat list
71
+
72
+ # Remove a site
73
+ webstat remove api.myservice.com
74
+ ```
75
+
76
+ ## License
77
+ MIT © [h45sh](https://github.com/h45sh)
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "webstat"
7
+ version = "0.1.0"
8
+ description = "Fast website status checker, recovery watcher, and desktop reminder"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ authors = [
12
+ { name = "h45sh" }
13
+ ]
14
+ license = "MIT"
15
+ license-files = ["LICENSE"]
16
+ keywords = ["website", "uptime", "status", "monitoring", "cli", "desktop-widget", "omarchy"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: End Users/Desktop",
22
+ "Operating System :: POSIX :: Linux",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Topic :: Internet :: WWW/HTTP",
28
+ "Topic :: System :: Monitoring",
29
+ "Topic :: System :: Networking :: Monitoring",
30
+ ]
31
+ dependencies = [
32
+ "httpx>=0.25.0",
33
+ "rich>=13.0.0",
34
+ "typer>=0.9.0",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/h45sh/webstat"
39
+ Repository = "https://github.com/h45sh/webstat"
40
+ Issues = "https://github.com/h45sh/webstat/issues"
41
+
42
+ [project.optional-dependencies]
43
+ dev = [
44
+ "pytest>=7.0.0",
45
+ "build>=1.0.0",
46
+ "twine>=4.0.0",
47
+ ]
48
+
49
+ [project.scripts]
50
+ webstat = "webstat.cli:main"
51
+
52
+ [tool.setuptools.packages.find]
53
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """webstat: website availability monitor and desktop reminder."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,407 @@
1
+ """Command line interface for webstat."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import sys
8
+ from typing import List, Optional
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.live import Live
13
+ from rich.panel import Panel
14
+ from rich.spinner import Spinner
15
+ from rich.table import Table
16
+ from rich.text import Text
17
+
18
+ from webstat.core.checker import HttpChecker
19
+ from webstat.core.models import CheckResult, MonitoredSite, SiteStatus
20
+ from webstat.core.notifier import NotificationDispatcher
21
+ from webstat.core.scheduler import WatchScheduler
22
+ from webstat.core.store import SiteStore
23
+ from webstat.utils.formatting import build_sites_table, get_latency_text, get_status_badge
24
+ from webstat.utils.url import get_display_name, normalize_url
25
+
26
+ app = typer.Typer(
27
+ name="webstat",
28
+ help="Fast website status checker, background watcher, and desktop reminder.",
29
+ no_args_is_help=False,
30
+ )
31
+ console = Console()
32
+
33
+
34
+ @app.command(name="check")
35
+ def check_command(
36
+ url: str = typer.Argument(..., help="Website URL or domain name (e.g. github.com)"),
37
+ watch: bool = typer.Option(
38
+ False,
39
+ "--watch",
40
+ "-w",
41
+ help="Automatically watch in foreground if site is down or not responding",
42
+ ),
43
+ open_browser: bool = typer.Option(
44
+ False,
45
+ "--open",
46
+ "-o",
47
+ help="Automatically open website in default browser when reachable",
48
+ ),
49
+ timeout: float = typer.Option(8.0, "--timeout", "-t", help="HTTP timeout in seconds"),
50
+ check_ssl: bool = typer.Option(False, "--check-ssl", "-s", help="Check TLS/SSL certificate expiration days"),
51
+ json_output: bool = typer.Option(False, "--json", "-j", help="Output raw JSON"),
52
+ ) -> None:
53
+ """Check the status of a website immediately."""
54
+ if timeout <= 0:
55
+ console.print("[bold red]Error:[/bold red] Timeout must be greater than 0.")
56
+ raise typer.Exit(code=1)
57
+
58
+ try:
59
+ normalized = normalize_url(url)
60
+ except Exception as e:
61
+ console.print(f"[bold red]Error:[/bold red] {e}")
62
+ raise typer.Exit(code=1)
63
+
64
+ checker = HttpChecker(timeout=timeout, check_ssl=check_ssl)
65
+
66
+ with console.status(f"[cyan]Checking[/cyan] {normalized}...", spinner="dots"):
67
+ result = asyncio.run(checker.check(normalized))
68
+
69
+ # Automatically update store if site is in watchlist
70
+ store = SiteStore()
71
+ site = store.get_by_id_or_url(normalized)
72
+ if site:
73
+ site.status = result.status
74
+ site.status_code = result.status_code
75
+ site.latency_ms = result.latency_ms
76
+ site.last_checked = result.timestamp
77
+ site.last_error = result.error_message
78
+ if result.is_up:
79
+ site.retries = 0
80
+ else:
81
+ site.retries += 1
82
+ store.update_site(site)
83
+
84
+ if json_output:
85
+ print(json.dumps(result.to_dict(), indent=2))
86
+ return
87
+
88
+ badge = get_status_badge(result.status, result.status_code)
89
+ latency = get_latency_text(result.latency_ms)
90
+
91
+ details = []
92
+ if result.latency_ms:
93
+ details.append(f"Latency: {result.latency_ms} ms")
94
+ if result.redirect_chain:
95
+ details.append(f"Redirects: {' -> '.join(result.redirect_chain)}")
96
+ if result.ssl_expires_days is not None:
97
+ if result.ssl_expires_days < 7:
98
+ details.append(f"[bold yellow]SSL Warning: Expires in {result.ssl_expires_days} days![/bold yellow]")
99
+ else:
100
+ details.append(f"SSL: Valid ({result.ssl_expires_days} days left)")
101
+ if result.error_message:
102
+ details.append(f"[red]Error: {result.error_message}[/red]")
103
+
104
+ details_str = "\n".join(details)
105
+ panel_content = f"{badge} [bold white]{normalized}[/bold white]\n\n{details_str}"
106
+
107
+ console.print(
108
+ Panel(
109
+ panel_content,
110
+ title="[bold cyan]Webstat Status[/bold cyan]",
111
+ border_style="green" if result.is_up else "red",
112
+ expand=False,
113
+ )
114
+ )
115
+
116
+ if result.is_up:
117
+ if open_browser:
118
+ import subprocess
119
+ subprocess.Popen(["xdg-open", normalized], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
120
+ return
121
+
122
+ # Site is down or non-positive
123
+ if watch:
124
+ console.print("\n[yellow]Site is not responding positively. Entering watch mode...[/yellow]")
125
+ run_watch_loop(
126
+ urls=[url],
127
+ auto_open=open_browser,
128
+ poll_interval=5.0,
129
+ keep_watching=False,
130
+ with_bell=True,
131
+ )
132
+
133
+
134
+ @app.command(name="watch")
135
+ def watch_command(
136
+ urls: List[str] = typer.Argument(..., help="One or more website URLs or domains to monitor"),
137
+ open_browser: bool = typer.Option(
138
+ False,
139
+ "--open",
140
+ "-o",
141
+ help="Automatically open website in default browser when reachable",
142
+ ),
143
+ interval: float = typer.Option(
144
+ 5.0,
145
+ "--interval",
146
+ "-i",
147
+ help="Polling interval in seconds",
148
+ ),
149
+ keep: bool = typer.Option(
150
+ False,
151
+ "--keep",
152
+ "-k",
153
+ help="Keep watching even after site recovers",
154
+ ),
155
+ no_bell: bool = typer.Option(
156
+ False,
157
+ "--no-bell",
158
+ help="Disable audible terminal bell on recovery",
159
+ ),
160
+ ) -> None:
161
+ """Watch one or more websites and alert you with desktop notification when they are UP."""
162
+ if interval < 0.5:
163
+ console.print("[bold red]Error:[/bold red] Polling interval must be at least 0.5 seconds.")
164
+ raise typer.Exit(code=1)
165
+
166
+ run_watch_loop(
167
+ urls=urls,
168
+ auto_open=open_browser,
169
+ poll_interval=interval,
170
+ keep_watching=keep,
171
+ with_bell=not no_bell,
172
+ )
173
+
174
+
175
+ def run_watch_loop(
176
+ urls: List[str],
177
+ auto_open: bool,
178
+ poll_interval: float,
179
+ keep_watching: bool,
180
+ with_bell: bool,
181
+ ) -> None:
182
+ store = SiteStore()
183
+ sites: list[MonitoredSite] = []
184
+
185
+ for u in urls:
186
+ try:
187
+ site = store.add(
188
+ raw_url=u,
189
+ auto_open=auto_open,
190
+ notify_on_up=True,
191
+ keep_watching=keep_watching,
192
+ )
193
+ sites.append(site)
194
+ except Exception as e:
195
+ console.print(f"[bold red]Skipping invalid URL '{u}':[/bold red] {e}")
196
+
197
+ if not sites:
198
+ raise typer.Exit(code=1)
199
+
200
+ dispatcher = NotificationDispatcher(with_bell=with_bell)
201
+ scheduler = WatchScheduler(
202
+ store=store,
203
+ dispatcher=dispatcher,
204
+ poll_interval=poll_interval,
205
+ )
206
+
207
+ console.print(
208
+ f"[bold cyan]Monitoring {len(sites)} site(s)...[/bold cyan] (Press [bold red]Ctrl+C[/bold red] to stop)\n"
209
+ )
210
+
211
+ def render_progress_table() -> Table:
212
+ table = Table(box=None, expand=True, padding=(0, 1))
213
+ table.add_column("Site", style="bold white", width=30)
214
+ table.add_column("Status", width=22)
215
+ table.add_column("Latency", justify="right", width=12)
216
+ table.add_column("Checks", justify="right", width=10)
217
+ table.add_column("Details", style="dim")
218
+
219
+ for s in sites:
220
+ badge = get_status_badge(s.status, s.status_code)
221
+ latency = get_latency_text(s.latency_ms)
222
+ checks_count = str(s.retries) if s.retries > 0 else "1"
223
+ details = s.last_error or ("Ready" if s.is_up else "Checking...")
224
+ table.add_row(s.display_name, badge, latency, checks_count, details)
225
+
226
+ return table
227
+
228
+ recovered_any = False
229
+
230
+ try:
231
+ with Live(render_progress_table(), refresh_per_second=2, console=console) as live:
232
+ def on_tick(site: MonitoredSite, result: CheckResult, just_recovered: bool):
233
+ nonlocal recovered_any
234
+ if just_recovered:
235
+ recovered_any = True
236
+ live.update(render_progress_table())
237
+
238
+ asyncio.run(scheduler.watch_sites(sites, on_tick=on_tick))
239
+
240
+ except KeyboardInterrupt:
241
+ console.print("\n[yellow]Watch stopped by user.[/yellow]")
242
+ return
243
+
244
+ if recovered_any:
245
+ console.print("\n[bold green]✓ Site is back online! Notification sent.[/bold green]")
246
+
247
+
248
+ @app.command(name="add")
249
+ def add_command(
250
+ url: str = typer.Argument(..., help="Website URL to add to background watchlist"),
251
+ open_browser: bool = typer.Option(
252
+ False,
253
+ "--open",
254
+ "-o",
255
+ help="Automatically launch browser when site recovers",
256
+ ),
257
+ keep: bool = typer.Option(
258
+ False,
259
+ "--keep",
260
+ "-k",
261
+ help="Keep monitoring continuously even after it recovers",
262
+ ),
263
+ ) -> None:
264
+ """Add a website to the persistent background monitoring watchlist."""
265
+ store = SiteStore()
266
+ try:
267
+ site = store.add(
268
+ raw_url=url,
269
+ auto_open=open_browser,
270
+ notify_on_up=True,
271
+ keep_watching=keep,
272
+ )
273
+ # Perform fast initial health check so numbers appear immediately
274
+ checker = HttpChecker(timeout=4.0)
275
+ result = asyncio.run(checker.check(site.url))
276
+ site.status = result.status
277
+ site.status_code = result.status_code
278
+ site.latency_ms = result.latency_ms
279
+ site.last_checked = result.timestamp
280
+ site.last_error = result.error_message
281
+ store.update_site(site)
282
+
283
+ console.print(f"[bold green]Added:[/bold green] {site.display_name} ({site.url}) [{site.status.value}]")
284
+ except Exception as e:
285
+ console.print(f"[bold red]Failed to add site:[/bold red] {e}")
286
+ raise typer.Exit(code=1)
287
+
288
+
289
+ @app.command(name="list")
290
+ def list_command(
291
+ json_output: bool = typer.Option(False, "--json", "-j", help="Output raw JSON array"),
292
+ ) -> None:
293
+ """List all currently watched websites and their statuses."""
294
+ store = SiteStore()
295
+ sites = store.load_all()
296
+
297
+ if json_output:
298
+ data = [s.to_dict() for s in sites]
299
+ print(json.dumps(data, indent=2))
300
+ return
301
+
302
+ if not sites:
303
+ console.print("[dim]No websites in watchlist. Add one with: [bold cyan]webstat add <url>[/bold cyan][/dim]")
304
+ return
305
+
306
+ console.print(build_sites_table(sites))
307
+
308
+
309
+ @app.command(name="remove")
310
+ def remove_command(
311
+ target: str = typer.Argument(..., help="URL, domain name, or site ID to remove"),
312
+ ) -> None:
313
+ """Remove a website from the monitoring watchlist."""
314
+ store = SiteStore()
315
+ if store.remove(target):
316
+ console.print(f"[bold green]Removed:[/bold green] '{target}' from watchlist.")
317
+ else:
318
+ console.print(f"[bold red]Not found:[/bold red] No site matching '{target}' in watchlist.")
319
+ raise typer.Exit(code=1)
320
+
321
+
322
+ @app.command(name="clear")
323
+ def clear_command() -> None:
324
+ """Clear all websites from the watchlist."""
325
+ store = SiteStore()
326
+ store.clear()
327
+ console.print("[bold green]Watchlist cleared.[/bold green]")
328
+
329
+
330
+ @app.command(name="refresh")
331
+ def refresh_command() -> None:
332
+ """Check all monitored websites immediately and update their status."""
333
+ store = SiteStore()
334
+ sites = store.load_all()
335
+ if not sites:
336
+ console.print("[dim]No websites in watchlist.[/dim]")
337
+ return
338
+ dispatcher = NotificationDispatcher()
339
+ checker = HttpChecker()
340
+ scheduler = WatchScheduler(store=store, dispatcher=dispatcher, checker=checker)
341
+
342
+ async def run_all():
343
+ sem = asyncio.Semaphore(10)
344
+
345
+ async def bounded_check(s):
346
+ async with sem:
347
+ return await scheduler.check_and_update(s)
348
+
349
+ tasks = [bounded_check(s) for s in sites]
350
+ await asyncio.gather(*tasks)
351
+
352
+ asyncio.run(run_all())
353
+ console.print(f"[bold green]Refreshed {len(sites)} website(s).[/bold green]")
354
+
355
+
356
+ @app.command(name="daemon")
357
+ def daemon_command(
358
+ interval: float = typer.Option(10.0, "--interval", "-i", help="Polling interval in seconds"),
359
+ ) -> None:
360
+ """Run the continuous background monitoring daemon."""
361
+ if interval < 1.0:
362
+ console.print("[bold red]Error:[/bold red] Daemon polling interval must be at least 1.0 second.")
363
+ raise typer.Exit(code=1)
364
+
365
+ store = SiteStore()
366
+ dispatcher = NotificationDispatcher()
367
+ checker = HttpChecker()
368
+ scheduler = WatchScheduler(store=store, dispatcher=dispatcher, checker=checker, poll_interval=interval)
369
+
370
+ console.print("[bold cyan]webstat daemon started.[/bold cyan] Watching state queue...")
371
+
372
+ async def daemon_loop():
373
+ while True:
374
+ sites = store.load_all()
375
+ # Only poll sites that are either down or marked keep_watching
376
+ to_poll = [s for s in sites if not s.is_up or s.keep_watching or s.status == SiteStatus.UNKNOWN]
377
+ if to_poll:
378
+ for site in to_poll:
379
+ result, just_recovered = await scheduler.check_and_update(site)
380
+ if just_recovered:
381
+ console.print(f"[green]Recovered:[/green] {site.display_name} -> {result.status_code} OK")
382
+ await asyncio.sleep(interval)
383
+
384
+ try:
385
+ asyncio.run(daemon_loop())
386
+ except KeyboardInterrupt:
387
+ console.print("\n[yellow]webstat daemon stopped.[/yellow]")
388
+
389
+
390
+ KNOWN_COMMANDS = {"check", "watch", "add", "list", "remove", "clear", "refresh", "daemon"}
391
+
392
+
393
+ @app.callback()
394
+ def main_callback() -> None:
395
+ """webstat: Website status checker and desktop recovery reminder."""
396
+ pass
397
+
398
+
399
+ def main() -> None:
400
+ # If the first non-flag argument is not a known subcommand, default to "check"
401
+ if len(sys.argv) > 1 and not sys.argv[1].startswith("-") and sys.argv[1] not in KNOWN_COMMANDS:
402
+ sys.argv.insert(1, "check")
403
+ app()
404
+
405
+
406
+ if __name__ == "__main__":
407
+ main()