blip-speedtest 0.2.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.
- blip.py +2092 -0
- blip_speedtest-0.2.0.dist-info/METADATA +397 -0
- blip_speedtest-0.2.0.dist-info/RECORD +7 -0
- blip_speedtest-0.2.0.dist-info/WHEEL +5 -0
- blip_speedtest-0.2.0.dist-info/entry_points.txt +2 -0
- blip_speedtest-0.2.0.dist-info/licenses/LICENSE +21 -0
- blip_speedtest-0.2.0.dist-info/top_level.txt +1 -0
blip.py
ADDED
|
@@ -0,0 +1,2092 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import ast
|
|
3
|
+
import curses
|
|
4
|
+
import http.client
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import socket
|
|
10
|
+
import sqlite3
|
|
11
|
+
import ssl
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
VERSION = "0.2.0"
|
|
20
|
+
DB_PATH = Path.home() / ".blip" / "history.db"
|
|
21
|
+
|
|
22
|
+
LOGO_DOTS = ("·", "▪", "■", "▪")
|
|
23
|
+
PULSE_BARS = (
|
|
24
|
+
(" ▁", " ▃▅", "▂▆█"),
|
|
25
|
+
(" ▁ ", "▃▅▂", "▆█▄"),
|
|
26
|
+
("▁ ", "▅▂▄", "█▄▆"),
|
|
27
|
+
(" ▁ ", "▂▄▆", "▄▆█"),
|
|
28
|
+
)
|
|
29
|
+
H_EIGHTHS = (" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█")
|
|
30
|
+
SPARK_BARS = ("▁", "▂", "▃", "▄", "▅", "▆", "▇", "█")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_logo_lines(dot: str = "●") -> tuple[str, ...]:
|
|
34
|
+
"""Returns the 5-line ANSI Shadow wordmark with the given status dot."""
|
|
35
|
+
return (
|
|
36
|
+
f"██╗ ██╗ {dot} ",
|
|
37
|
+
"██║ ██║██╗██████╗ ",
|
|
38
|
+
"██████╗ ██║██║██╔══██╗",
|
|
39
|
+
"██████╔╝██║██║██████╔╝",
|
|
40
|
+
"╚═════╝ ╚═╝╚═╝██╔═══╝ ",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# (Label, Download Bytes, Upload Bytes) — Index 0 is the default
|
|
44
|
+
SIZE_PRESETS = (
|
|
45
|
+
("25 MB", 25_000_000, 10_000_000),
|
|
46
|
+
("50 MB", 50_000_000, 20_000_000),
|
|
47
|
+
("100 MB", 100_000_000, 25_000_000),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Common Cloudflare PoP IATA codes -> City, CCA2
|
|
51
|
+
IATA_CITIES = {
|
|
52
|
+
# India
|
|
53
|
+
"AMD": "Ahmedabad, IN",
|
|
54
|
+
"BBI": "Bhubaneswar, IN",
|
|
55
|
+
"BLR": "Bengaluru, IN",
|
|
56
|
+
"BOM": "Mumbai, IN",
|
|
57
|
+
"CCU": "Kolkata, IN",
|
|
58
|
+
"COK": "Kochi, IN",
|
|
59
|
+
"DEL": "New Delhi, IN",
|
|
60
|
+
"GAU": "Guwahati, IN",
|
|
61
|
+
"HYD": "Hyderabad, IN",
|
|
62
|
+
"IXC": "Chandigarh, IN",
|
|
63
|
+
"JAI": "Jaipur, IN",
|
|
64
|
+
"LKO": "Lucknow, IN",
|
|
65
|
+
"MAA": "Chennai, IN",
|
|
66
|
+
"NAG": "Nagpur, IN",
|
|
67
|
+
"PAT": "Patna, IN",
|
|
68
|
+
"PNQ": "Pune, IN",
|
|
69
|
+
"VTZ": "Visakhapatnam, IN",
|
|
70
|
+
# Asia-Pacific & Middle East
|
|
71
|
+
"BKK": "Bangkok, TH",
|
|
72
|
+
"CGK": "Jakarta, ID",
|
|
73
|
+
"DOH": "Doha, QA",
|
|
74
|
+
"DXB": "Dubai, AE",
|
|
75
|
+
"HKG": "Hong Kong, HK",
|
|
76
|
+
"ICN": "Seoul, KR",
|
|
77
|
+
"KUL": "Kuala Lumpur, MY",
|
|
78
|
+
"MNL": "Manila, PH",
|
|
79
|
+
"NRT": "Tokyo, JP",
|
|
80
|
+
"SIN": "Singapore, SG",
|
|
81
|
+
"SYD": "Sydney, AU",
|
|
82
|
+
"TPE": "Taipei, TW",
|
|
83
|
+
# Europe
|
|
84
|
+
"AMS": "Amsterdam, NL",
|
|
85
|
+
"ARN": "Stockholm, SE",
|
|
86
|
+
"CDG": "Paris, FR",
|
|
87
|
+
"DUB": "Dublin, IE",
|
|
88
|
+
"FRA": "Frankfurt, DE",
|
|
89
|
+
"LHR": "London, GB",
|
|
90
|
+
"MAD": "Madrid, ES",
|
|
91
|
+
"MRS": "Marseille, FR",
|
|
92
|
+
"MXP": "Milan, IT",
|
|
93
|
+
"WAW": "Warsaw, PL",
|
|
94
|
+
"ZRH": "Zurich, CH",
|
|
95
|
+
# Americas & Africa
|
|
96
|
+
"ATL": "Atlanta, US",
|
|
97
|
+
"DFW": "Dallas, US",
|
|
98
|
+
"EWR": "Newark, US",
|
|
99
|
+
"GRU": "São Paulo, BR",
|
|
100
|
+
"IAD": "Ashburn, US",
|
|
101
|
+
"JNB": "Johannesburg, ZA",
|
|
102
|
+
"LAX": "Los Angeles, US",
|
|
103
|
+
"MIA": "Miami, US",
|
|
104
|
+
"ORD": "Chicago, US",
|
|
105
|
+
"SEA": "Seattle, US",
|
|
106
|
+
"SJC": "San Jose, US",
|
|
107
|
+
"YYZ": "Toronto, CA",
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
VPN_PREFIXES = (
|
|
111
|
+
"utun",
|
|
112
|
+
"tun",
|
|
113
|
+
"tap",
|
|
114
|
+
"wg",
|
|
115
|
+
"tailscale",
|
|
116
|
+
"ppp",
|
|
117
|
+
"ipsec",
|
|
118
|
+
"zt",
|
|
119
|
+
"nordlynx",
|
|
120
|
+
"proton",
|
|
121
|
+
"mullvad",
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
BROWSER_HEADERS = {
|
|
125
|
+
"User-Agent": (
|
|
126
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
127
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
|
128
|
+
),
|
|
129
|
+
"Accept": "*/*",
|
|
130
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
131
|
+
"Origin": "https://speed.cloudflare.com",
|
|
132
|
+
"Referer": "https://speed.cloudflare.com/",
|
|
133
|
+
"Cache-Control": "no-cache",
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_colo_info(colo_raw: object) -> tuple[str, str]:
|
|
138
|
+
"""
|
|
139
|
+
Normalizes Cloudflare's `colo` field (dict, JSON/dict string, or 3-letter IATA string)
|
|
140
|
+
into `(iata_code, formatted_display)` e.g. `('HYD', 'HYD (Hyderabad, IN)')`.
|
|
141
|
+
"""
|
|
142
|
+
if colo_raw is None:
|
|
143
|
+
return "--", "Detecting..."
|
|
144
|
+
|
|
145
|
+
data: dict | None = None
|
|
146
|
+
if isinstance(colo_raw, dict):
|
|
147
|
+
data = colo_raw
|
|
148
|
+
elif isinstance(colo_raw, str):
|
|
149
|
+
s = colo_raw.strip()
|
|
150
|
+
if not s or s in ("--", "None", "null"):
|
|
151
|
+
return "--", "Detecting..."
|
|
152
|
+
if s.startswith("{") and s.endswith("}"):
|
|
153
|
+
try:
|
|
154
|
+
parsed = json.loads(s)
|
|
155
|
+
if isinstance(parsed, dict):
|
|
156
|
+
data = parsed
|
|
157
|
+
except Exception:
|
|
158
|
+
try:
|
|
159
|
+
parsed = ast.literal_eval(s)
|
|
160
|
+
if isinstance(parsed, dict):
|
|
161
|
+
data = parsed
|
|
162
|
+
except Exception:
|
|
163
|
+
pass
|
|
164
|
+
|
|
165
|
+
if data is not None:
|
|
166
|
+
iata = str(data.get("iata") or data.get("code") or "").strip().upper()
|
|
167
|
+
city = str(data.get("city") or "").strip()
|
|
168
|
+
cca2 = str(data.get("cca2") or data.get("country") or "").strip().upper()
|
|
169
|
+
if iata:
|
|
170
|
+
if city and cca2:
|
|
171
|
+
return iata, f"{iata} ({city}, {cca2})"
|
|
172
|
+
if city:
|
|
173
|
+
return iata, f"{iata} ({city})"
|
|
174
|
+
mapped = IATA_CITIES.get(iata)
|
|
175
|
+
return iata, (f"{iata} ({mapped})" if mapped else iata)
|
|
176
|
+
|
|
177
|
+
code = str(colo_raw).strip()
|
|
178
|
+
upper = code.upper()
|
|
179
|
+
if upper == "FALLBACK":
|
|
180
|
+
return "Fallback", "Fallback (ipinfo.io)"
|
|
181
|
+
if upper == "HETZNER":
|
|
182
|
+
return "HETZNER", "NBG1 (Nuremberg, DE)"
|
|
183
|
+
# Already formatted like "HYD (Hyderabad, IN)"
|
|
184
|
+
if len(upper) > 4 and upper[3] == " " and "(" in code:
|
|
185
|
+
return upper[:3], code
|
|
186
|
+
mapped = IATA_CITIES.get(upper)
|
|
187
|
+
return upper, (f"{upper} ({mapped})" if mapped else code)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def format_edge_node(colo_raw: object, privacy: bool = False) -> str:
|
|
191
|
+
"""Formats edge node info and respects Privacy Mode."""
|
|
192
|
+
if privacy:
|
|
193
|
+
return "••• (Location Hidden)"
|
|
194
|
+
_, display = parse_colo_info(colo_raw)
|
|
195
|
+
return display
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def render_thick_bar(width: int, progress: float) -> str:
|
|
199
|
+
"""Renders a sub-character precision horizontal progress bar using eighth-blocks."""
|
|
200
|
+
clamped = max(0.0, min(1.0, progress))
|
|
201
|
+
total_eighths = int(round(width * 8 * clamped))
|
|
202
|
+
full_cells = total_eighths // 8
|
|
203
|
+
rem_eighths = total_eighths % 8
|
|
204
|
+
|
|
205
|
+
if full_cells >= width:
|
|
206
|
+
return "█" * width
|
|
207
|
+
partial = H_EIGHTHS[rem_eighths] if rem_eighths > 0 else ""
|
|
208
|
+
empty_cells = width - full_cells - (1 if partial else 0)
|
|
209
|
+
return ("█" * full_cells) + partial + ("░" * max(0, empty_cells))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def split_legacy_iface_vpn(raw_iface: str, raw_vpn: str) -> tuple[str, str]:
|
|
213
|
+
"""Handles both dedicated `vpn` columns and older rows formatted as `'Wi-Fi (en0) + VPN(utun0)'`."""
|
|
214
|
+
iface_s = str(raw_iface or "Unknown")
|
|
215
|
+
vpn_s = str(raw_vpn or "").strip()
|
|
216
|
+
if not vpn_s and " + VPN(" in iface_s and iface_s.endswith(")"):
|
|
217
|
+
base, tail = iface_s.split(" + VPN(", 1)
|
|
218
|
+
return base.strip(), tail[:-1].strip()
|
|
219
|
+
return iface_s, vpn_s
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class HistoryStore:
|
|
223
|
+
"""Thread-safe local SQLite storage with automatic schema migration."""
|
|
224
|
+
|
|
225
|
+
def __init__(self, db_path: Path = DB_PATH) -> None:
|
|
226
|
+
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
227
|
+
self.lock = threading.Lock()
|
|
228
|
+
self.conn = sqlite3.connect(db_path, check_same_thread=False)
|
|
229
|
+
self._init_and_migrate()
|
|
230
|
+
|
|
231
|
+
def _init_and_migrate(self) -> None:
|
|
232
|
+
with self.lock:
|
|
233
|
+
self.conn.execute(
|
|
234
|
+
"""
|
|
235
|
+
CREATE TABLE IF NOT EXISTS results (
|
|
236
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
237
|
+
tested_at TEXT NOT NULL,
|
|
238
|
+
ping_ms REAL NOT NULL,
|
|
239
|
+
download_mbps REAL NOT NULL,
|
|
240
|
+
upload_mbps REAL NOT NULL,
|
|
241
|
+
isp TEXT DEFAULT 'Unknown',
|
|
242
|
+
location TEXT DEFAULT 'Unknown',
|
|
243
|
+
ip TEXT DEFAULT '',
|
|
244
|
+
iface TEXT DEFAULT 'Unknown',
|
|
245
|
+
vpn TEXT DEFAULT '',
|
|
246
|
+
down_mb REAL DEFAULT 25.0,
|
|
247
|
+
up_mb REAL DEFAULT 10.0,
|
|
248
|
+
edge TEXT DEFAULT '--'
|
|
249
|
+
)
|
|
250
|
+
"""
|
|
251
|
+
)
|
|
252
|
+
cols = {row[1] for row in self.conn.execute("PRAGMA table_info(results)")}
|
|
253
|
+
migrations = {
|
|
254
|
+
"isp": "ALTER TABLE results ADD COLUMN isp TEXT DEFAULT 'Unknown'",
|
|
255
|
+
"location": "ALTER TABLE results ADD COLUMN location TEXT DEFAULT 'Unknown'",
|
|
256
|
+
"ip": "ALTER TABLE results ADD COLUMN ip TEXT DEFAULT ''",
|
|
257
|
+
"iface": "ALTER TABLE results ADD COLUMN iface TEXT DEFAULT 'Unknown'",
|
|
258
|
+
"vpn": "ALTER TABLE results ADD COLUMN vpn TEXT DEFAULT ''",
|
|
259
|
+
"down_mb": "ALTER TABLE results ADD COLUMN down_mb REAL DEFAULT 25.0",
|
|
260
|
+
"up_mb": "ALTER TABLE results ADD COLUMN up_mb REAL DEFAULT 10.0",
|
|
261
|
+
"edge": "ALTER TABLE results ADD COLUMN edge TEXT DEFAULT '--'",
|
|
262
|
+
}
|
|
263
|
+
for col_name, ddl in migrations.items():
|
|
264
|
+
if col_name not in cols:
|
|
265
|
+
self.conn.execute(ddl)
|
|
266
|
+
self.conn.commit()
|
|
267
|
+
|
|
268
|
+
def save(
|
|
269
|
+
self,
|
|
270
|
+
ping_ms: float,
|
|
271
|
+
down_mbps: float,
|
|
272
|
+
up_mbps: float,
|
|
273
|
+
isp: str,
|
|
274
|
+
location: str,
|
|
275
|
+
ip: str,
|
|
276
|
+
iface: str,
|
|
277
|
+
vpn: str,
|
|
278
|
+
down_mb: float,
|
|
279
|
+
up_mb: float,
|
|
280
|
+
edge: str,
|
|
281
|
+
) -> None:
|
|
282
|
+
tested_at = datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
283
|
+
with self.lock:
|
|
284
|
+
self.conn.execute(
|
|
285
|
+
"""
|
|
286
|
+
INSERT INTO results (
|
|
287
|
+
tested_at, ping_ms, download_mbps, upload_mbps,
|
|
288
|
+
isp, location, ip, iface, vpn, down_mb, up_mb, edge
|
|
289
|
+
)
|
|
290
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
291
|
+
""",
|
|
292
|
+
(
|
|
293
|
+
tested_at,
|
|
294
|
+
round(ping_ms, 1),
|
|
295
|
+
round(down_mbps, 2),
|
|
296
|
+
round(up_mbps, 2),
|
|
297
|
+
str(isp or "Unknown"),
|
|
298
|
+
str(location or "Unknown"),
|
|
299
|
+
str(ip or ""),
|
|
300
|
+
str(iface or "Unknown"),
|
|
301
|
+
str(vpn or ""),
|
|
302
|
+
round(down_mb, 1),
|
|
303
|
+
round(up_mb, 1),
|
|
304
|
+
str(edge or "--"),
|
|
305
|
+
),
|
|
306
|
+
)
|
|
307
|
+
self.conn.commit()
|
|
308
|
+
|
|
309
|
+
def fetch_all(self) -> list[tuple]:
|
|
310
|
+
with self.lock:
|
|
311
|
+
cur = self.conn.execute(
|
|
312
|
+
"""
|
|
313
|
+
SELECT id, tested_at, ping_ms, download_mbps, upload_mbps,
|
|
314
|
+
COALESCE(isp, 'Unknown'), COALESCE(location, 'Unknown'),
|
|
315
|
+
COALESCE(ip, ''), COALESCE(iface, 'Unknown'),
|
|
316
|
+
COALESCE(vpn, ''), COALESCE(down_mb, 25.0),
|
|
317
|
+
COALESCE(up_mb, 10.0), COALESCE(edge, '--')
|
|
318
|
+
FROM results
|
|
319
|
+
ORDER BY id DESC
|
|
320
|
+
"""
|
|
321
|
+
)
|
|
322
|
+
return cur.fetchall()
|
|
323
|
+
|
|
324
|
+
def delete(self, row_id: int) -> None:
|
|
325
|
+
with self.lock:
|
|
326
|
+
self.conn.execute("DELETE FROM results WHERE id = ?", (row_id,))
|
|
327
|
+
self.conn.commit()
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
_CA_BUNDLE_CANDIDATES = (
|
|
331
|
+
"/etc/ssl/cert.pem", # macOS
|
|
332
|
+
"/etc/ssl/certs/ca-certificates.crt", # Debian, Ubuntu, Alpine
|
|
333
|
+
"/etc/pki/tls/certs/ca-bundle.crt", # RHEL, Fedora
|
|
334
|
+
"/etc/ssl/certs/ca-bundle.crt", # Arch
|
|
335
|
+
"/etc/ssl/ca-bundle.pem", # openSUSE
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _create_ssl_context() -> ssl.SSLContext:
|
|
340
|
+
"""Create a TLS context that can verify certificates in frozen builds.
|
|
341
|
+
|
|
342
|
+
PyInstaller bundles OpenSSL, whose compiled-in CA path points at the
|
|
343
|
+
machine that built the binary. Load the operating system trust store so
|
|
344
|
+
the binary works on other machines.
|
|
345
|
+
"""
|
|
346
|
+
ctx = ssl.create_default_context()
|
|
347
|
+
ssl_cert_file = os.environ.get("SSL_CERT_FILE")
|
|
348
|
+
if ssl_cert_file and os.path.isfile(ssl_cert_file):
|
|
349
|
+
return ctx
|
|
350
|
+
for path in _CA_BUNDLE_CANDIDATES:
|
|
351
|
+
if os.path.isfile(path):
|
|
352
|
+
try:
|
|
353
|
+
ctx.load_verify_locations(cafile=path)
|
|
354
|
+
except (OSError, ssl.SSLError):
|
|
355
|
+
continue
|
|
356
|
+
break
|
|
357
|
+
return ctx
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
class SpeedTestRunner:
|
|
361
|
+
"""Headless network metadata & speed test engine shared by TUI and CLI modes."""
|
|
362
|
+
|
|
363
|
+
def __init__(self) -> None:
|
|
364
|
+
self.phase = "idle" # idle | ping | download | upload | done | error
|
|
365
|
+
self.progress = 0.0
|
|
366
|
+
self.status = "Ready — Press [r] to run speed test"
|
|
367
|
+
self.ping_val = "--"
|
|
368
|
+
self.down_val = "--"
|
|
369
|
+
self.up_val = "--"
|
|
370
|
+
|
|
371
|
+
# Connection & Edge Metadata
|
|
372
|
+
self.isp = "Detecting ISP..."
|
|
373
|
+
self.asn = ""
|
|
374
|
+
self.location = "Detecting location..."
|
|
375
|
+
self.ip = "..."
|
|
376
|
+
self.colo_code = "--"
|
|
377
|
+
self.colo_display = "Detecting..."
|
|
378
|
+
self.edge_server = "speed.cloudflare.com (Anycast)"
|
|
379
|
+
self.tls_version = "TLS 1.3"
|
|
380
|
+
self.iface_summary = "Detecting..."
|
|
381
|
+
self.iface_type = "Unknown"
|
|
382
|
+
self.vpn_name = ""
|
|
383
|
+
self.lan_ip = "..."
|
|
384
|
+
|
|
385
|
+
self.state_lock = threading.Lock()
|
|
386
|
+
|
|
387
|
+
def _classify_physical_iface(self, iface: str, sys_name: str) -> tuple[str, str]:
|
|
388
|
+
low = iface.lower()
|
|
389
|
+
if not iface:
|
|
390
|
+
return "Default Route", "Network"
|
|
391
|
+
if sys_name == "Linux" and (Path(f"/sys/class/net/{iface}/wireless").exists() or low.startswith("wl")):
|
|
392
|
+
return f"Wi-Fi ({iface})", "Wi-Fi"
|
|
393
|
+
if sys_name == "Darwin":
|
|
394
|
+
iface_type = "Wi-Fi" if iface == "en0" else ("Ethernet" if iface.startswith("en") else "Network")
|
|
395
|
+
try:
|
|
396
|
+
ports = subprocess.check_output(
|
|
397
|
+
["networksetup", "-listallhardwareports"], stderr=subprocess.DEVNULL, text=True, timeout=2
|
|
398
|
+
)
|
|
399
|
+
m = re.search(rf"Hardware Port:\s*(.+?)\nDevice:\s*{re.escape(iface)}\b", ports)
|
|
400
|
+
if m:
|
|
401
|
+
port_name = m.group(1).strip()
|
|
402
|
+
iface_type = (
|
|
403
|
+
"Wi-Fi"
|
|
404
|
+
if "Wi-Fi" in port_name
|
|
405
|
+
else ("Ethernet" if "Ethernet" in port_name or "LAN" in port_name else port_name)
|
|
406
|
+
)
|
|
407
|
+
except Exception:
|
|
408
|
+
pass
|
|
409
|
+
return f"{iface_type} ({iface})", iface_type
|
|
410
|
+
if low.startswith(("en", "eth")):
|
|
411
|
+
return f"Ethernet ({iface})", "Ethernet"
|
|
412
|
+
if low.startswith(("wwan", "rmnet", "usb")):
|
|
413
|
+
return f"Cellular ({iface})", "Cellular"
|
|
414
|
+
return iface, "Network"
|
|
415
|
+
|
|
416
|
+
def _detect_local_interface(self) -> tuple[str, str, str, str]:
|
|
417
|
+
"""
|
|
418
|
+
Detects active physical interface and VPN tunnel separately.
|
|
419
|
+
Returns `(iface_summary, iface_type, vpn_name, lan_ip)` where `vpn_name` is `""` if no VPN is active.
|
|
420
|
+
"""
|
|
421
|
+
lan_ip = "Unavailable"
|
|
422
|
+
try:
|
|
423
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
424
|
+
sock.settimeout(1.0)
|
|
425
|
+
sock.connect(("1.1.1.1", 80))
|
|
426
|
+
lan_ip = sock.getsockname()[0]
|
|
427
|
+
sock.close()
|
|
428
|
+
except Exception:
|
|
429
|
+
pass
|
|
430
|
+
|
|
431
|
+
sys_name = platform.system()
|
|
432
|
+
default_iface = ""
|
|
433
|
+
physical_fallback = ""
|
|
434
|
+
active_tunnels: list[str] = []
|
|
435
|
+
|
|
436
|
+
if sys_name == "Linux":
|
|
437
|
+
try:
|
|
438
|
+
with open("/proc/net/route", encoding="utf-8") as f:
|
|
439
|
+
for line in f.readlines()[1:]:
|
|
440
|
+
parts = line.strip().split()
|
|
441
|
+
if len(parts) >= 4 and parts[1] == "00000000" and (int(parts[3], 16) & 2):
|
|
442
|
+
cand = parts[0]
|
|
443
|
+
if not default_iface:
|
|
444
|
+
default_iface = cand
|
|
445
|
+
if not cand.lower().startswith(VPN_PREFIXES) and not physical_fallback:
|
|
446
|
+
physical_fallback = cand
|
|
447
|
+
except Exception:
|
|
448
|
+
pass
|
|
449
|
+
|
|
450
|
+
if not default_iface:
|
|
451
|
+
try:
|
|
452
|
+
out = subprocess.check_output(
|
|
453
|
+
["ip", "route", "get", "1.1.1.1"], stderr=subprocess.DEVNULL, text=True, timeout=2
|
|
454
|
+
)
|
|
455
|
+
m = re.search(r"\bdev\s+(\S+)", out)
|
|
456
|
+
if m:
|
|
457
|
+
default_iface = m.group(1)
|
|
458
|
+
except Exception:
|
|
459
|
+
pass
|
|
460
|
+
|
|
461
|
+
try:
|
|
462
|
+
for net_if in sorted(os.listdir("/sys/class/net")):
|
|
463
|
+
if net_if == "lo":
|
|
464
|
+
continue
|
|
465
|
+
oper = Path(f"/sys/class/net/{net_if}/operstate")
|
|
466
|
+
state = oper.read_text().strip() if oper.exists() else "unknown"
|
|
467
|
+
if net_if.lower().startswith(VPN_PREFIXES):
|
|
468
|
+
if state in ("up", "unknown"):
|
|
469
|
+
active_tunnels.append(net_if)
|
|
470
|
+
elif not physical_fallback and state == "up":
|
|
471
|
+
physical_fallback = net_if
|
|
472
|
+
except Exception:
|
|
473
|
+
pass
|
|
474
|
+
|
|
475
|
+
elif sys_name == "Darwin":
|
|
476
|
+
try:
|
|
477
|
+
out = subprocess.check_output(
|
|
478
|
+
["route", "-n", "get", "1.1.1.1"], stderr=subprocess.DEVNULL, text=True, timeout=2
|
|
479
|
+
)
|
|
480
|
+
m = re.search(r"interface:\s*(\S+)", out)
|
|
481
|
+
if m:
|
|
482
|
+
default_iface = m.group(1)
|
|
483
|
+
except Exception:
|
|
484
|
+
pass
|
|
485
|
+
|
|
486
|
+
try:
|
|
487
|
+
if_out = subprocess.check_output(
|
|
488
|
+
["ifconfig"], stderr=subprocess.DEVNULL, text=True, timeout=2
|
|
489
|
+
)
|
|
490
|
+
cur_if = ""
|
|
491
|
+
for line in if_out.splitlines():
|
|
492
|
+
if line and not line[0].isspace():
|
|
493
|
+
cur_if = line.split(":", 1)[0]
|
|
494
|
+
elif cur_if and "inet " in line and "127.0.0.1" not in line:
|
|
495
|
+
if cur_if.lower().startswith(VPN_PREFIXES):
|
|
496
|
+
if cur_if not in active_tunnels:
|
|
497
|
+
active_tunnels.append(cur_if)
|
|
498
|
+
elif not physical_fallback and cur_if.startswith("en"):
|
|
499
|
+
physical_fallback = cur_if
|
|
500
|
+
except Exception:
|
|
501
|
+
pass
|
|
502
|
+
|
|
503
|
+
vpn_name = ""
|
|
504
|
+
phys_iface = default_iface
|
|
505
|
+
|
|
506
|
+
if default_iface.lower().startswith(VPN_PREFIXES):
|
|
507
|
+
vpn_name = default_iface
|
|
508
|
+
phys_iface = physical_fallback
|
|
509
|
+
elif active_tunnels:
|
|
510
|
+
vpn_name = active_tunnels[0]
|
|
511
|
+
|
|
512
|
+
if phys_iface:
|
|
513
|
+
iface_summary, iface_type = self._classify_physical_iface(phys_iface, sys_name)
|
|
514
|
+
elif vpn_name:
|
|
515
|
+
iface_summary, iface_type = "Tunnel Route", "Tunnel"
|
|
516
|
+
else:
|
|
517
|
+
iface_summary, iface_type = "Default Route", "Network"
|
|
518
|
+
|
|
519
|
+
return iface_summary, iface_type, vpn_name, lan_ip
|
|
520
|
+
|
|
521
|
+
def _https_conn(self, host: str, timeout: float = 20.0) -> http.client.HTTPSConnection:
|
|
522
|
+
ctx = _create_ssl_context()
|
|
523
|
+
return http.client.HTTPSConnection(host, timeout=timeout, context=ctx)
|
|
524
|
+
|
|
525
|
+
def _extract_tls_version(self, conn: http.client.HTTPSConnection) -> str:
|
|
526
|
+
try:
|
|
527
|
+
if conn.sock and hasattr(conn.sock, "version"):
|
|
528
|
+
ver = conn.sock.version()
|
|
529
|
+
if ver:
|
|
530
|
+
return str(ver).replace("TLSv", "TLS ")
|
|
531
|
+
except Exception:
|
|
532
|
+
pass
|
|
533
|
+
return "TLS 1.3"
|
|
534
|
+
|
|
535
|
+
def _fetch_network_meta(self) -> None:
|
|
536
|
+
summary, iface_type, vpn_name, lan_ip = self._detect_local_interface()
|
|
537
|
+
with self.state_lock:
|
|
538
|
+
self.iface_summary = summary
|
|
539
|
+
self.iface_type = iface_type
|
|
540
|
+
self.vpn_name = vpn_name
|
|
541
|
+
self.lan_ip = lan_ip
|
|
542
|
+
|
|
543
|
+
try:
|
|
544
|
+
conn = self._https_conn("speed.cloudflare.com", timeout=8.0)
|
|
545
|
+
conn.request("GET", "/meta", headers=BROWSER_HEADERS)
|
|
546
|
+
resp = conn.getresponse()
|
|
547
|
+
tls_ver = self._extract_tls_version(conn)
|
|
548
|
+
raw = resp.read().decode("utf-8", errors="ignore")
|
|
549
|
+
conn.close()
|
|
550
|
+
if resp.status == 200:
|
|
551
|
+
data = json.loads(raw)
|
|
552
|
+
asn_raw = data.get("asn")
|
|
553
|
+
asn_str = f"AS{asn_raw}" if asn_raw else ""
|
|
554
|
+
isp = str(data.get("asOrganization") or asn_str or "Unknown ISP")
|
|
555
|
+
loc_parts = [str(p) for p in (data.get("city"), data.get("region"), data.get("country")) if p]
|
|
556
|
+
location = ", ".join(loc_parts) if loc_parts else "Unknown Location"
|
|
557
|
+
colo_code, colo_disp = parse_colo_info(data.get("colo"))
|
|
558
|
+
with self.state_lock:
|
|
559
|
+
self.isp = isp
|
|
560
|
+
self.asn = asn_str
|
|
561
|
+
self.location = location
|
|
562
|
+
self.ip = str(data.get("clientIp") or "Unknown")
|
|
563
|
+
self.colo_code = colo_code
|
|
564
|
+
self.colo_display = colo_disp
|
|
565
|
+
self.edge_server = "speed.cloudflare.com (Anycast)"
|
|
566
|
+
self.tls_version = tls_ver
|
|
567
|
+
return
|
|
568
|
+
except Exception:
|
|
569
|
+
pass
|
|
570
|
+
|
|
571
|
+
try:
|
|
572
|
+
conn = self._https_conn("ipinfo.io", timeout=8.0)
|
|
573
|
+
conn.request("GET", "/json", headers={"User-Agent": BROWSER_HEADERS["User-Agent"]})
|
|
574
|
+
resp = conn.getresponse()
|
|
575
|
+
tls_ver = self._extract_tls_version(conn)
|
|
576
|
+
raw = resp.read().decode("utf-8", errors="ignore")
|
|
577
|
+
conn.close()
|
|
578
|
+
if resp.status == 200:
|
|
579
|
+
data = json.loads(raw)
|
|
580
|
+
org = str(data.get("org") or "Unknown ISP")
|
|
581
|
+
if org.startswith("AS") and " " in org:
|
|
582
|
+
asn_str, isp = org.split(" ", 1)
|
|
583
|
+
else:
|
|
584
|
+
asn_str, isp = "", org
|
|
585
|
+
loc_parts = [str(p) for p in (data.get("city"), data.get("region"), data.get("country")) if p]
|
|
586
|
+
colo_code, colo_disp = parse_colo_info("Fallback")
|
|
587
|
+
with self.state_lock:
|
|
588
|
+
self.isp = isp
|
|
589
|
+
self.asn = asn_str
|
|
590
|
+
self.location = ", ".join(loc_parts) if loc_parts else "Unknown"
|
|
591
|
+
self.ip = str(data.get("ip") or "Unknown")
|
|
592
|
+
self.colo_code = colo_code
|
|
593
|
+
self.colo_display = colo_disp
|
|
594
|
+
self.tls_version = tls_ver
|
|
595
|
+
return
|
|
596
|
+
except Exception:
|
|
597
|
+
pass
|
|
598
|
+
|
|
599
|
+
with self.state_lock:
|
|
600
|
+
if self.isp == "Detecting ISP...":
|
|
601
|
+
self.isp = "Unavailable"
|
|
602
|
+
self.location = "Unknown"
|
|
603
|
+
|
|
604
|
+
def _run_cloudflare_test(self, down_bytes: int, up_bytes: int) -> tuple[float, float, float, float, float]:
|
|
605
|
+
conn = self._https_conn("speed.cloudflare.com", timeout=35.0)
|
|
606
|
+
try:
|
|
607
|
+
with self.state_lock:
|
|
608
|
+
self.phase = "ping"
|
|
609
|
+
self.status = "Measuring latency (ping)..."
|
|
610
|
+
self.progress = 0.12
|
|
611
|
+
self.edge_server = "speed.cloudflare.com (Anycast)"
|
|
612
|
+
|
|
613
|
+
conn.request("GET", "/__down?bytes=0", headers=BROWSER_HEADERS)
|
|
614
|
+
warm = conn.getresponse()
|
|
615
|
+
tls_ver = self._extract_tls_version(conn)
|
|
616
|
+
warm.read()
|
|
617
|
+
if warm.status == 403:
|
|
618
|
+
raise PermissionError("Cloudflare returned 403")
|
|
619
|
+
if warm.status >= 400:
|
|
620
|
+
raise RuntimeError(f"HTTP {warm.status}")
|
|
621
|
+
|
|
622
|
+
with self.state_lock:
|
|
623
|
+
self.tls_version = tls_ver
|
|
624
|
+
|
|
625
|
+
pings = []
|
|
626
|
+
for i in range(4):
|
|
627
|
+
t0 = time.perf_counter()
|
|
628
|
+
conn.request("GET", "/__down?bytes=0", headers=BROWSER_HEADERS)
|
|
629
|
+
r = conn.getresponse()
|
|
630
|
+
r.read()
|
|
631
|
+
pings.append((time.perf_counter() - t0) * 1000)
|
|
632
|
+
with self.state_lock:
|
|
633
|
+
self.progress = 0.14 + (i + 1) * 0.04
|
|
634
|
+
ping_ms = sorted(pings)[len(pings) // 2]
|
|
635
|
+
with self.state_lock:
|
|
636
|
+
self.ping_val = f"{ping_ms:.1f}"
|
|
637
|
+
|
|
638
|
+
# Download Phase
|
|
639
|
+
down_mb_target = down_bytes / 1_000_000
|
|
640
|
+
with self.state_lock:
|
|
641
|
+
self.phase = "download"
|
|
642
|
+
self.status = f"Testing download throughput ({down_mb_target:.0f} MB)..."
|
|
643
|
+
t0 = time.perf_counter()
|
|
644
|
+
conn.request("GET", f"/__down?bytes={down_bytes}", headers=BROWSER_HEADERS)
|
|
645
|
+
resp = conn.getresponse()
|
|
646
|
+
if resp.status >= 400:
|
|
647
|
+
raise RuntimeError(f"Download HTTP {resp.status}")
|
|
648
|
+
|
|
649
|
+
received = 0
|
|
650
|
+
while chunk := resp.read(65536):
|
|
651
|
+
received += len(chunk)
|
|
652
|
+
elapsed = max(time.perf_counter() - t0, 0.001)
|
|
653
|
+
live_mbps = (received * 8) / (elapsed * 1_000_000)
|
|
654
|
+
frac = min(received / down_bytes, 1.0)
|
|
655
|
+
with self.state_lock:
|
|
656
|
+
self.down_val = f"{live_mbps:.2f}"
|
|
657
|
+
self.progress = 0.30 + frac * 0.35
|
|
658
|
+
down_elapsed = max(time.perf_counter() - t0, 0.001)
|
|
659
|
+
down_mbps = (received * 8) / (down_elapsed * 1_000_000)
|
|
660
|
+
actual_down_mb = received / 1_000_000
|
|
661
|
+
|
|
662
|
+
# Upload Phase
|
|
663
|
+
up_mb_target = up_bytes / 1_000_000
|
|
664
|
+
with self.state_lock:
|
|
665
|
+
self.phase = "upload"
|
|
666
|
+
self.status = f"Testing upload throughput ({up_mb_target:.0f} MB)..."
|
|
667
|
+
chunk_data = b"0" * 131072
|
|
668
|
+
sent = 0
|
|
669
|
+
t0 = time.perf_counter()
|
|
670
|
+
|
|
671
|
+
conn.putrequest("POST", "/__up")
|
|
672
|
+
for k, v in BROWSER_HEADERS.items():
|
|
673
|
+
conn.putheader(k, v)
|
|
674
|
+
conn.putheader("Content-Type", "application/octet-stream")
|
|
675
|
+
conn.putheader("Content-Length", str(up_bytes))
|
|
676
|
+
conn.endheaders()
|
|
677
|
+
|
|
678
|
+
while sent < up_bytes:
|
|
679
|
+
to_send = min(len(chunk_data), up_bytes - sent)
|
|
680
|
+
conn.send(chunk_data[:to_send])
|
|
681
|
+
sent += to_send
|
|
682
|
+
elapsed = max(time.perf_counter() - t0, 0.001)
|
|
683
|
+
live_up = (sent * 8) / (elapsed * 1_000_000)
|
|
684
|
+
frac = min(sent / up_bytes, 1.0)
|
|
685
|
+
with self.state_lock:
|
|
686
|
+
self.up_val = f"{live_up:.2f}"
|
|
687
|
+
self.progress = 0.65 + frac * 0.33
|
|
688
|
+
|
|
689
|
+
up_resp = conn.getresponse()
|
|
690
|
+
up_resp.read()
|
|
691
|
+
if up_resp.status >= 400:
|
|
692
|
+
raise RuntimeError(f"Upload HTTP {up_resp.status}")
|
|
693
|
+
up_elapsed = max(time.perf_counter() - t0, 0.001)
|
|
694
|
+
up_mbps = (sent * 8) / (up_elapsed * 1_000_000)
|
|
695
|
+
actual_up_mb = sent / 1_000_000
|
|
696
|
+
|
|
697
|
+
return ping_ms, down_mbps, up_mbps, actual_down_mb, actual_up_mb
|
|
698
|
+
finally:
|
|
699
|
+
conn.close()
|
|
700
|
+
|
|
701
|
+
def _run_fallback_test(self, down_bytes: int, up_bytes: int) -> tuple[float, float, float, float, float]:
|
|
702
|
+
host = "nbg1-speed.hetzner.com"
|
|
703
|
+
conn = self._https_conn(host, timeout=35.0)
|
|
704
|
+
try:
|
|
705
|
+
colo_code, colo_disp = parse_colo_info("HETZNER")
|
|
706
|
+
with self.state_lock:
|
|
707
|
+
self.phase = "ping"
|
|
708
|
+
self.status = "Using fallback server (Hetzner) — Ping..."
|
|
709
|
+
self.colo_code = colo_code
|
|
710
|
+
self.colo_display = colo_disp
|
|
711
|
+
self.edge_server = "nbg1-speed.hetzner.com (Fallback)"
|
|
712
|
+
|
|
713
|
+
pings = []
|
|
714
|
+
for i in range(4):
|
|
715
|
+
t0 = time.perf_counter()
|
|
716
|
+
conn.request("HEAD", "/100MB.bin", headers={"User-Agent": BROWSER_HEADERS["User-Agent"]})
|
|
717
|
+
r = conn.getresponse()
|
|
718
|
+
tls_ver = self._extract_tls_version(conn)
|
|
719
|
+
r.read()
|
|
720
|
+
pings.append((time.perf_counter() - t0) * 1000)
|
|
721
|
+
with self.state_lock:
|
|
722
|
+
self.tls_version = tls_ver
|
|
723
|
+
self.progress = 0.15 + (i + 1) * 0.04
|
|
724
|
+
ping_ms = sorted(pings)[len(pings) // 2]
|
|
725
|
+
target_down = min(down_bytes, 100_000_000)
|
|
726
|
+
with self.state_lock:
|
|
727
|
+
self.ping_val = f"{ping_ms:.1f}"
|
|
728
|
+
self.phase = "download"
|
|
729
|
+
self.status = f"Using fallback server — Testing download ({target_down / 1_000_000:.0f} MB)..."
|
|
730
|
+
|
|
731
|
+
t0 = time.perf_counter()
|
|
732
|
+
conn.request(
|
|
733
|
+
"GET",
|
|
734
|
+
"/100MB.bin",
|
|
735
|
+
headers={
|
|
736
|
+
"User-Agent": BROWSER_HEADERS["User-Agent"],
|
|
737
|
+
"Range": f"bytes=0-{target_down - 1}",
|
|
738
|
+
},
|
|
739
|
+
)
|
|
740
|
+
resp = conn.getresponse()
|
|
741
|
+
received = 0
|
|
742
|
+
while chunk := resp.read(65536):
|
|
743
|
+
received += len(chunk)
|
|
744
|
+
elapsed = max(time.perf_counter() - t0, 0.001)
|
|
745
|
+
live_mbps = (received * 8) / (elapsed * 1_000_000)
|
|
746
|
+
frac = min(received / target_down, 1.0)
|
|
747
|
+
with self.state_lock:
|
|
748
|
+
self.down_val = f"{live_mbps:.2f}"
|
|
749
|
+
self.progress = 0.32 + frac * 0.50
|
|
750
|
+
down_elapsed = max(time.perf_counter() - t0, 0.001)
|
|
751
|
+
down_mbps = (received * 8) / (down_elapsed * 1_000_000)
|
|
752
|
+
actual_down_mb = received / 1_000_000
|
|
753
|
+
|
|
754
|
+
target_up = min(up_bytes, 15_000_000)
|
|
755
|
+
with self.state_lock:
|
|
756
|
+
self.phase = "upload"
|
|
757
|
+
self.status = f"Using fallback server — Testing upload ({target_up / 1_000_000:.0f} MB)..."
|
|
758
|
+
up_conn = self._https_conn("postman-echo.com", timeout=35.0)
|
|
759
|
+
chunk_data = b"0" * 131072
|
|
760
|
+
sent = 0
|
|
761
|
+
t0 = time.perf_counter()
|
|
762
|
+
up_conn.putrequest("POST", "/post")
|
|
763
|
+
up_conn.putheader("User-Agent", BROWSER_HEADERS["User-Agent"])
|
|
764
|
+
up_conn.putheader("Content-Type", "application/octet-stream")
|
|
765
|
+
up_conn.putheader("Content-Length", str(target_up))
|
|
766
|
+
up_conn.endheaders()
|
|
767
|
+
while sent < target_up:
|
|
768
|
+
to_send = min(len(chunk_data), target_up - sent)
|
|
769
|
+
up_conn.send(chunk_data[:to_send])
|
|
770
|
+
sent += to_send
|
|
771
|
+
elapsed = max(time.perf_counter() - t0, 0.001)
|
|
772
|
+
with self.state_lock:
|
|
773
|
+
self.up_val = f"{(sent * 8) / (elapsed * 1_000_000):.2f}"
|
|
774
|
+
self.progress = 0.82 + min(sent / target_up, 1.0) * 0.16
|
|
775
|
+
up_r = up_conn.getresponse()
|
|
776
|
+
up_r.read()
|
|
777
|
+
up_conn.close()
|
|
778
|
+
up_mbps = (sent * 8) / (max(time.perf_counter() - t0, 0.001) * 1_000_000)
|
|
779
|
+
actual_up_mb = sent / 1_000_000
|
|
780
|
+
return ping_ms, down_mbps, up_mbps, actual_down_mb, actual_up_mb
|
|
781
|
+
finally:
|
|
782
|
+
conn.close()
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
class BlipTUI(SpeedTestRunner):
|
|
786
|
+
C_ACCENT = 1 # Electric Sky Blue (Interface, Edge & UI Accents)
|
|
787
|
+
C_DOWN = 2 # Emerald Green (Download)
|
|
788
|
+
C_UP = 3 # Soft Violet (Upload)
|
|
789
|
+
C_WARN = 4 # Warm Amber (Latency / Ping & Alerts)
|
|
790
|
+
C_MUTED = 5 # Slate Gray
|
|
791
|
+
C_SELECT = 6 # Selected Row Highlight
|
|
792
|
+
C_WHITE = 7 # Crisp Platinum White (Logo, Connection Profile, ISP Column)
|
|
793
|
+
|
|
794
|
+
def __init__(
|
|
795
|
+
self,
|
|
796
|
+
stdscr: curses.window,
|
|
797
|
+
size_preset_idx: int = 0,
|
|
798
|
+
privacy_mode: bool = False,
|
|
799
|
+
db_path: Path = DB_PATH,
|
|
800
|
+
) -> None:
|
|
801
|
+
super().__init__()
|
|
802
|
+
self.stdscr = stdscr
|
|
803
|
+
self.store = HistoryStore(db_path)
|
|
804
|
+
self.rows: list[tuple] = []
|
|
805
|
+
self.selected_idx = 0
|
|
806
|
+
self.scroll_offset = 0
|
|
807
|
+
|
|
808
|
+
self.is_testing = False
|
|
809
|
+
self.privacy_mode = privacy_mode
|
|
810
|
+
self.detail_modal_open = False
|
|
811
|
+
self.size_preset_idx = size_preset_idx
|
|
812
|
+
self.anim_tick = 0
|
|
813
|
+
self.last_down_mb = SIZE_PRESETS[size_preset_idx][1] / 1_000_000
|
|
814
|
+
self.last_up_mb = SIZE_PRESETS[size_preset_idx][2] / 1_000_000
|
|
815
|
+
|
|
816
|
+
self._setup_colors()
|
|
817
|
+
self.stdscr.timeout(80)
|
|
818
|
+
self.reload_history()
|
|
819
|
+
|
|
820
|
+
threading.Thread(target=self._fetch_network_meta, daemon=True).start()
|
|
821
|
+
|
|
822
|
+
def _setup_colors(self) -> None:
|
|
823
|
+
curses.curs_set(0)
|
|
824
|
+
curses.use_default_colors()
|
|
825
|
+
if curses.COLORS >= 256:
|
|
826
|
+
curses.init_pair(self.C_ACCENT, 39, -1)
|
|
827
|
+
curses.init_pair(self.C_DOWN, 42, -1)
|
|
828
|
+
curses.init_pair(self.C_UP, 141, -1)
|
|
829
|
+
curses.init_pair(self.C_WARN, 214, -1)
|
|
830
|
+
curses.init_pair(self.C_MUTED, 244, -1)
|
|
831
|
+
curses.init_pair(self.C_SELECT, 255, 237)
|
|
832
|
+
curses.init_pair(self.C_WHITE, 255, -1)
|
|
833
|
+
else:
|
|
834
|
+
curses.init_pair(self.C_ACCENT, curses.COLOR_CYAN, -1)
|
|
835
|
+
curses.init_pair(self.C_DOWN, curses.COLOR_GREEN, -1)
|
|
836
|
+
curses.init_pair(self.C_UP, curses.COLOR_MAGENTA, -1)
|
|
837
|
+
curses.init_pair(self.C_WARN, curses.COLOR_YELLOW, -1)
|
|
838
|
+
curses.init_pair(self.C_MUTED, curses.COLOR_WHITE, -1)
|
|
839
|
+
curses.init_pair(self.C_SELECT, curses.COLOR_BLACK, curses.COLOR_CYAN)
|
|
840
|
+
curses.init_pair(self.C_WHITE, curses.COLOR_WHITE, -1)
|
|
841
|
+
|
|
842
|
+
def _active_color(self, phase: str) -> int:
|
|
843
|
+
if phase == "ping":
|
|
844
|
+
return self.C_WARN
|
|
845
|
+
if phase in ("download", "done"):
|
|
846
|
+
return self.C_DOWN
|
|
847
|
+
if phase == "upload":
|
|
848
|
+
return self.C_UP
|
|
849
|
+
if phase == "error":
|
|
850
|
+
return self.C_WARN
|
|
851
|
+
return self.C_WHITE
|
|
852
|
+
|
|
853
|
+
def reload_history(self) -> None:
|
|
854
|
+
self.rows = self.store.fetch_all()
|
|
855
|
+
if self.rows:
|
|
856
|
+
self.selected_idx = min(self.selected_idx, len(self.rows) - 1)
|
|
857
|
+
else:
|
|
858
|
+
self.selected_idx = 0
|
|
859
|
+
self.detail_modal_open = False
|
|
860
|
+
|
|
861
|
+
def run_speed_test_worker(self) -> None:
|
|
862
|
+
try:
|
|
863
|
+
with self.state_lock:
|
|
864
|
+
_, down_bytes, up_bytes = SIZE_PRESETS[self.size_preset_idx]
|
|
865
|
+
self.phase = "ping"
|
|
866
|
+
self.progress = 0.05
|
|
867
|
+
self.ping_val = "..."
|
|
868
|
+
self.down_val = "..."
|
|
869
|
+
self.up_val = "..."
|
|
870
|
+
self.status = "Refreshing network & ISP metadata..."
|
|
871
|
+
|
|
872
|
+
self._fetch_network_meta()
|
|
873
|
+
|
|
874
|
+
try:
|
|
875
|
+
ping_ms, down_mbps, up_mbps, down_mb, up_mb = self._run_cloudflare_test(down_bytes, up_bytes)
|
|
876
|
+
except PermissionError:
|
|
877
|
+
ping_ms, down_mbps, up_mbps, down_mb, up_mb = self._run_fallback_test(down_bytes, up_bytes)
|
|
878
|
+
|
|
879
|
+
with self.state_lock:
|
|
880
|
+
isp, location, ip, iface, vpn, edge = (
|
|
881
|
+
self.isp,
|
|
882
|
+
self.location,
|
|
883
|
+
self.ip,
|
|
884
|
+
self.iface_summary,
|
|
885
|
+
self.vpn_name,
|
|
886
|
+
self.colo_display,
|
|
887
|
+
)
|
|
888
|
+
|
|
889
|
+
self.store.save(ping_ms, down_mbps, up_mbps, isp, location, ip, iface, vpn, down_mb, up_mb, edge)
|
|
890
|
+
|
|
891
|
+
with self.state_lock:
|
|
892
|
+
self.down_val = f"{down_mbps:.2f}"
|
|
893
|
+
self.up_val = f"{up_mbps:.2f}"
|
|
894
|
+
self.last_down_mb = down_mb
|
|
895
|
+
self.last_up_mb = up_mb
|
|
896
|
+
self.progress = 1.0
|
|
897
|
+
self.phase = "done"
|
|
898
|
+
self.status = f"Complete ({down_mb:.0f} MB ↓ / {up_mb:.0f} MB ↑) — Saved to ~/.blip/history.db"
|
|
899
|
+
self.reload_history()
|
|
900
|
+
self.selected_idx = 0
|
|
901
|
+
self.scroll_offset = 0
|
|
902
|
+
except Exception as exc:
|
|
903
|
+
with self.state_lock:
|
|
904
|
+
self.phase = "error"
|
|
905
|
+
self.status = f"Test failed: {exc}"
|
|
906
|
+
self.progress = 0.0
|
|
907
|
+
finally:
|
|
908
|
+
with self.state_lock:
|
|
909
|
+
self.is_testing = False
|
|
910
|
+
|
|
911
|
+
def put(self, y: int, x: int, text: str, attr: int = 0, max_w: int | None = None) -> None:
|
|
912
|
+
max_y, max_x = self.stdscr.getmaxyx()
|
|
913
|
+
if 0 <= y < max_y and 0 <= x < max_x:
|
|
914
|
+
limit = max_x - x - 1
|
|
915
|
+
if max_w is not None:
|
|
916
|
+
limit = min(limit, max_w)
|
|
917
|
+
if limit > 0:
|
|
918
|
+
try:
|
|
919
|
+
self.stdscr.addstr(y, x, str(text)[:limit], attr)
|
|
920
|
+
except curses.error:
|
|
921
|
+
pass
|
|
922
|
+
|
|
923
|
+
def draw_box(
|
|
924
|
+
self, y: int, x: int, h: int, w: int, title: str = "", border_attr: int = 0, fill_bg: bool = False
|
|
925
|
+
) -> None:
|
|
926
|
+
if h < 2 or w < 4:
|
|
927
|
+
return
|
|
928
|
+
self.put(y, x, "╭" + "─" * (w - 2) + "╮", border_attr)
|
|
929
|
+
for row in range(1, h - 1):
|
|
930
|
+
if fill_bg:
|
|
931
|
+
self.put(y + row, x + 1, " " * (w - 2), 0)
|
|
932
|
+
self.put(y + row, x, "│", border_attr)
|
|
933
|
+
self.put(y + row, x + w - 1, "│", border_attr)
|
|
934
|
+
self.put(y + h - 1, x, "╰" + "─" * (w - 2) + "╯", border_attr)
|
|
935
|
+
if title and w > len(title) + 5:
|
|
936
|
+
self.put(y, x + 2, f" {title} ", border_attr | curses.A_BOLD)
|
|
937
|
+
|
|
938
|
+
def _render_thick_bar(self, width: int, progress: float) -> str:
|
|
939
|
+
return render_thick_bar(width, progress)
|
|
940
|
+
|
|
941
|
+
def _split_legacy_iface_vpn(self, raw_iface: str, raw_vpn: str) -> tuple[str, str]:
|
|
942
|
+
"""Handles both dedicated `vpn` columns and older rows formatted as `'Wi-Fi (en0) + VPN(utun0)'`."""
|
|
943
|
+
return split_legacy_iface_vpn(raw_iface, raw_vpn)
|
|
944
|
+
|
|
945
|
+
def _draw_header_trends(
|
|
946
|
+
self, y: int, x: int, w: int, rows: list[tuple], selected_idx: int
|
|
947
|
+
) -> None:
|
|
948
|
+
"""Compact 5-line Speed Trends sparkline widget tucked into the top-right header."""
|
|
949
|
+
self.draw_box(y, x, 5, w, "SPEED TRENDS", curses.color_pair(self.C_ACCENT))
|
|
950
|
+
inner_w = w - 4
|
|
951
|
+
if inner_w < 16:
|
|
952
|
+
return
|
|
953
|
+
|
|
954
|
+
if not rows:
|
|
955
|
+
self.put(y + 2, x + 2, "No history yet", curses.color_pair(self.C_MUTED), inner_w)
|
|
956
|
+
return
|
|
957
|
+
|
|
958
|
+
spark_w = max(6, inner_w - 11)
|
|
959
|
+
sample_count = min(len(rows), spark_w)
|
|
960
|
+
recent = list(reversed(rows[:sample_count]))
|
|
961
|
+
sel_bar_idx = (sample_count - 1 - selected_idx) if selected_idx < sample_count else -1
|
|
962
|
+
pad_left = spark_w - sample_count
|
|
963
|
+
|
|
964
|
+
def draw_spark_row(row_y: int, arrow: str, vals: list[float], color_id: int) -> None:
|
|
965
|
+
peak = max(vals) if vals else 1.0
|
|
966
|
+
scale = peak if peak > 0 else 1.0
|
|
967
|
+
self.put(row_y, x + 2, f"{arrow} ", curses.color_pair(color_id) | curses.A_BOLD, 2)
|
|
968
|
+
for idx, v in enumerate(vals):
|
|
969
|
+
level = min(7, max(0, int(round((v / scale) * 7))))
|
|
970
|
+
ch = SPARK_BARS[level]
|
|
971
|
+
is_sel = idx == sel_bar_idx
|
|
972
|
+
attr = curses.color_pair(color_id) | (curses.A_BOLD | curses.A_REVERSE if is_sel else 0)
|
|
973
|
+
self.put(row_y, x + 4 + pad_left + idx, ch, attr, 1)
|
|
974
|
+
max_lbl = f"max {peak:>3.0f}"
|
|
975
|
+
self.put(row_y, x + w - 2 - len(max_lbl), max_lbl, curses.color_pair(self.C_MUTED), len(max_lbl))
|
|
976
|
+
|
|
977
|
+
draw_spark_row(y + 1, "↓", [r[3] for r in recent], self.C_DOWN)
|
|
978
|
+
draw_spark_row(y + 2, "↑", [r[4] for r in recent], self.C_UP)
|
|
979
|
+
|
|
980
|
+
sel = rows[selected_idx]
|
|
981
|
+
readout = f"#{sel[0]} ↓{sel[3]:.0f} ↑{sel[4]:.0f}"
|
|
982
|
+
self.put(y + 3, x + w - 2 - len(readout), readout, curses.color_pair(self.C_ACCENT), len(readout))
|
|
983
|
+
if sel_bar_idx >= 0:
|
|
984
|
+
self.put(
|
|
985
|
+
y + 3,
|
|
986
|
+
x + 4 + pad_left + sel_bar_idx,
|
|
987
|
+
"▲",
|
|
988
|
+
curses.color_pair(self.C_ACCENT) | curses.A_BOLD,
|
|
989
|
+
1,
|
|
990
|
+
)
|
|
991
|
+
|
|
992
|
+
def _draw_detail_modal(self, max_y: int, max_x: int, rows: list[tuple], privacy: bool) -> None:
|
|
993
|
+
"""Draws a centered modal dialog with full run details, Edge Node, Public IP, and navigation controls."""
|
|
994
|
+
if not rows:
|
|
995
|
+
return
|
|
996
|
+
row = rows[self.selected_idx]
|
|
997
|
+
r_id, tested_at, ping, down, up, r_isp, r_loc, r_ip, r_iface, r_vpn, r_down_mb, r_up_mb, r_edge = row
|
|
998
|
+
|
|
999
|
+
modal_w = min(68, max_x - 6)
|
|
1000
|
+
modal_h = min(19, max_y - 4)
|
|
1001
|
+
if modal_w < 44 or modal_h < 16:
|
|
1002
|
+
return
|
|
1003
|
+
|
|
1004
|
+
mx = (max_x - modal_w) // 2
|
|
1005
|
+
my = (max_y - modal_h) // 2
|
|
1006
|
+
inner_w = modal_w - 4
|
|
1007
|
+
|
|
1008
|
+
title = f"RUN #{r_id} DETAILS ({self.selected_idx + 1}/{len(rows)})"
|
|
1009
|
+
self.draw_box(
|
|
1010
|
+
my, mx, modal_h, modal_w, title, curses.color_pair(self.C_ACCENT) | curses.A_BOLD, fill_bg=True
|
|
1011
|
+
)
|
|
1012
|
+
|
|
1013
|
+
clean_iface, clean_vpn = self._split_legacy_iface_vpn(r_iface, r_vpn)
|
|
1014
|
+
disp_isp = "ISP Hidden" if privacy else str(r_isp or "Unknown")
|
|
1015
|
+
disp_loc = "Location Hidden" if privacy else str(r_loc or "Unknown")
|
|
1016
|
+
disp_ip = "•••.•••.•••.•••" if privacy else (str(r_ip) if r_ip else "Unavailable")
|
|
1017
|
+
disp_iface = (clean_iface.split(" (", 1)[0] + " (•••)") if (privacy and " (" in clean_iface) else clean_iface
|
|
1018
|
+
disp_vpn = ("•••" if privacy else clean_vpn) if clean_vpn else ""
|
|
1019
|
+
disp_edge = format_edge_node(r_edge, privacy=privacy)
|
|
1020
|
+
|
|
1021
|
+
fields = [
|
|
1022
|
+
("Tested At", str(tested_at), self.C_WHITE),
|
|
1023
|
+
("Latency (Ping)", f"{ping:.1f} ms", self.C_WARN),
|
|
1024
|
+
("Download", f"{down:.2f} Mbps ({r_down_mb:.0f} MB payload)", self.C_DOWN),
|
|
1025
|
+
("Upload", f"{up:.2f} Mbps ({r_up_mb:.0f} MB payload)", self.C_UP),
|
|
1026
|
+
("Interface", disp_iface, self.C_ACCENT),
|
|
1027
|
+
("VPN", disp_vpn, self.C_ACCENT),
|
|
1028
|
+
("Edge Node", disp_edge, self.C_ACCENT),
|
|
1029
|
+
("ISP", disp_isp, self.C_WHITE),
|
|
1030
|
+
("Location", disp_loc, self.C_WHITE),
|
|
1031
|
+
("Public IP", disp_ip, self.C_WARN if privacy else self.C_WHITE),
|
|
1032
|
+
]
|
|
1033
|
+
|
|
1034
|
+
label_col_w = 17
|
|
1035
|
+
for idx, (lbl, val, val_col) in enumerate(fields):
|
|
1036
|
+
fy = my + 2 + idx
|
|
1037
|
+
if fy >= my + modal_h - 3:
|
|
1038
|
+
break
|
|
1039
|
+
self.put(fy, mx + 2, f"{lbl:<{label_col_w}}:", curses.color_pair(self.C_MUTED), label_col_w + 1)
|
|
1040
|
+
if val:
|
|
1041
|
+
self.put(
|
|
1042
|
+
fy,
|
|
1043
|
+
mx + 2 + label_col_w + 2,
|
|
1044
|
+
val,
|
|
1045
|
+
curses.color_pair(val_col) | curses.A_BOLD,
|
|
1046
|
+
inner_w - label_col_w - 2,
|
|
1047
|
+
)
|
|
1048
|
+
|
|
1049
|
+
sep_y = my + modal_h - 3
|
|
1050
|
+
self.put(sep_y, mx + 2, "─" * inner_w, curses.color_pair(self.C_MUTED), inner_w)
|
|
1051
|
+
|
|
1052
|
+
ctrl_y = my + modal_h - 2
|
|
1053
|
+
controls = [
|
|
1054
|
+
("[←/↑]", "Prev", self.C_ACCENT),
|
|
1055
|
+
("[→/↓]", "Next", self.C_ACCENT),
|
|
1056
|
+
("[P]", "Privacy", self.C_WARN if privacy else self.C_ACCENT),
|
|
1057
|
+
("[Esc/Enter]", "Close", self.C_WHITE),
|
|
1058
|
+
]
|
|
1059
|
+
cx = mx + 2
|
|
1060
|
+
for k_txt, d_txt, k_col in controls:
|
|
1061
|
+
if cx + len(k_txt) + len(d_txt) + 2 > mx + modal_w - 2:
|
|
1062
|
+
break
|
|
1063
|
+
self.put(ctrl_y, cx, k_txt, curses.color_pair(k_col) | curses.A_BOLD)
|
|
1064
|
+
cx += len(k_txt) + 1
|
|
1065
|
+
self.put(ctrl_y, cx, d_txt, curses.color_pair(self.C_MUTED))
|
|
1066
|
+
cx += len(d_txt) + 2
|
|
1067
|
+
|
|
1068
|
+
def _handle_resize(self) -> None:
|
|
1069
|
+
"""Drains burst KEY_RESIZE events from tmux pane zoom and forces a clean repaint."""
|
|
1070
|
+
self.stdscr.nodelay(True)
|
|
1071
|
+
try:
|
|
1072
|
+
while True:
|
|
1073
|
+
nxt = self.stdscr.getch()
|
|
1074
|
+
if nxt == -1:
|
|
1075
|
+
break
|
|
1076
|
+
if nxt != curses.KEY_RESIZE:
|
|
1077
|
+
curses.ungetch(nxt)
|
|
1078
|
+
break
|
|
1079
|
+
finally:
|
|
1080
|
+
self.stdscr.nodelay(False)
|
|
1081
|
+
self.stdscr.timeout(80)
|
|
1082
|
+
|
|
1083
|
+
if hasattr(curses, "update_lines_cols"):
|
|
1084
|
+
curses.update_lines_cols()
|
|
1085
|
+
self.stdscr.clear()
|
|
1086
|
+
|
|
1087
|
+
def draw(self) -> None:
|
|
1088
|
+
self.stdscr.erase()
|
|
1089
|
+
max_y, max_x = self.stdscr.getmaxyx()
|
|
1090
|
+
|
|
1091
|
+
min_w, min_h = 82, 27
|
|
1092
|
+
if max_y < min_h or max_x < min_w:
|
|
1093
|
+
if max_y < 4:
|
|
1094
|
+
compact = f"Terminal too small: {max_x}x{max_y} (min {min_w}x{min_h})"
|
|
1095
|
+
self.put(
|
|
1096
|
+
0,
|
|
1097
|
+
max(0, (max_x - len(compact)) // 2),
|
|
1098
|
+
compact,
|
|
1099
|
+
curses.color_pair(self.C_WARN) | curses.A_BOLD,
|
|
1100
|
+
)
|
|
1101
|
+
else:
|
|
1102
|
+
title = "Terminal window too small"
|
|
1103
|
+
cur_line = f"Current : {max_x}x{max_y}"
|
|
1104
|
+
req_line = f"Minimum : {min_w}x{min_h}"
|
|
1105
|
+
cy = (max_y - 3) // 2
|
|
1106
|
+
self.put(
|
|
1107
|
+
cy,
|
|
1108
|
+
max(1, (max_x - len(title)) // 2),
|
|
1109
|
+
title,
|
|
1110
|
+
curses.color_pair(self.C_WARN) | curses.A_BOLD,
|
|
1111
|
+
)
|
|
1112
|
+
self.put(
|
|
1113
|
+
cy + 1,
|
|
1114
|
+
max(1, (max_x - len(cur_line)) // 2),
|
|
1115
|
+
cur_line,
|
|
1116
|
+
curses.color_pair(self.C_WHITE) | curses.A_BOLD,
|
|
1117
|
+
)
|
|
1118
|
+
self.put(
|
|
1119
|
+
cy + 2,
|
|
1120
|
+
max(1, (max_x - len(req_line)) // 2),
|
|
1121
|
+
req_line,
|
|
1122
|
+
curses.color_pair(self.C_MUTED),
|
|
1123
|
+
)
|
|
1124
|
+
self.stdscr.refresh()
|
|
1125
|
+
return
|
|
1126
|
+
|
|
1127
|
+
with self.state_lock:
|
|
1128
|
+
status = self.status
|
|
1129
|
+
progress = self.progress
|
|
1130
|
+
is_testing = self.is_testing
|
|
1131
|
+
privacy = self.privacy_mode
|
|
1132
|
+
modal_open = self.detail_modal_open
|
|
1133
|
+
size_label, down_bytes, up_bytes = SIZE_PRESETS[self.size_preset_idx]
|
|
1134
|
+
phase = self.phase
|
|
1135
|
+
ping_v, down_v, up_v = self.ping_val, self.down_val, self.up_val
|
|
1136
|
+
isp, asn, location, ip = self.isp, self.asn, self.location, self.ip
|
|
1137
|
+
colo_code, colo_display = self.colo_code, self.colo_display
|
|
1138
|
+
edge_server, tls_ver = self.edge_server, self.tls_version
|
|
1139
|
+
iface_summary, iface_type, vpn_name, lan_ip = (
|
|
1140
|
+
self.iface_summary,
|
|
1141
|
+
self.iface_type,
|
|
1142
|
+
self.vpn_name,
|
|
1143
|
+
self.lan_ip,
|
|
1144
|
+
)
|
|
1145
|
+
rows = list(self.rows)
|
|
1146
|
+
|
|
1147
|
+
if is_testing:
|
|
1148
|
+
self.anim_tick = (self.anim_tick + 1) % 4
|
|
1149
|
+
|
|
1150
|
+
margin = 2
|
|
1151
|
+
inner_w = max_x - margin * 2
|
|
1152
|
+
active_col_id = self._active_color(phase)
|
|
1153
|
+
active_attr = curses.color_pair(active_col_id) | curses.A_BOLD
|
|
1154
|
+
|
|
1155
|
+
# Apply Privacy Mode redactions
|
|
1156
|
+
if privacy:
|
|
1157
|
+
disp_isp = "ISP Hidden (AS•••••)" if asn else "ISP Hidden"
|
|
1158
|
+
disp_loc = "Location Hidden"
|
|
1159
|
+
disp_ip = "•••.•••.•••.•••"
|
|
1160
|
+
disp_lan = "•••.•••.•••.•••"
|
|
1161
|
+
disp_iface = f"{iface_type} (•••)"
|
|
1162
|
+
disp_vpn = "•••" if vpn_name else ""
|
|
1163
|
+
disp_node = "••• (Location Hidden)"
|
|
1164
|
+
else:
|
|
1165
|
+
disp_isp = f"{isp} ({asn})" if (asn and asn not in str(isp)) else str(isp)
|
|
1166
|
+
disp_loc = str(location)
|
|
1167
|
+
disp_ip = str(ip)
|
|
1168
|
+
disp_lan = str(lan_ip)
|
|
1169
|
+
disp_iface = str(iface_summary)
|
|
1170
|
+
disp_vpn = str(vpn_name) if vpn_name else ""
|
|
1171
|
+
disp_node = str(colo_display)
|
|
1172
|
+
|
|
1173
|
+
# ── 1. Compact 5-Line ANSI Shadow Logo + Signature + Header Trends ──
|
|
1174
|
+
dot = LOGO_DOTS[self.anim_tick] if is_testing else "●"
|
|
1175
|
+
logo_lines = build_logo_lines(dot)
|
|
1176
|
+
for i, line in enumerate(logo_lines):
|
|
1177
|
+
self.put(1 + i, margin, line, active_attr)
|
|
1178
|
+
|
|
1179
|
+
# Signature directly beneath the logo on row 6
|
|
1180
|
+
self.put(6, margin, "made with ", curses.color_pair(self.C_MUTED))
|
|
1181
|
+
self.put(6, margin + 10, "♥", curses.color_pair(self.C_WARN) | curses.A_BOLD)
|
|
1182
|
+
self.put(6, margin + 11, " by ", curses.color_pair(self.C_MUTED))
|
|
1183
|
+
self.put(6, margin + 15, "picogeeks.com", curses.color_pair(self.C_ACCENT))
|
|
1184
|
+
|
|
1185
|
+
info_x = margin + 24
|
|
1186
|
+
if is_testing:
|
|
1187
|
+
bars = PULSE_BARS[self.anim_tick]
|
|
1188
|
+
for i, bar_row in enumerate(bars):
|
|
1189
|
+
self.put(2 + i, info_x, bar_row, active_attr)
|
|
1190
|
+
meta_x = info_x + 5
|
|
1191
|
+
else:
|
|
1192
|
+
meta_x = info_x
|
|
1193
|
+
|
|
1194
|
+
show_header_trends = max_x >= 98
|
|
1195
|
+
trends_w = min(34, max(26, inner_w // 3)) if show_header_trends else 0
|
|
1196
|
+
trends_x = max_x - margin - trends_w
|
|
1197
|
+
meta_max_w = (trends_x - meta_x - 2) if show_header_trends else (max_x - margin - meta_x)
|
|
1198
|
+
|
|
1199
|
+
version_txt = f"v{VERSION}"
|
|
1200
|
+
if privacy:
|
|
1201
|
+
privacy_banner = "🔒 PRIVACY MODE ACTIVE"
|
|
1202
|
+
self.put(1, meta_x, privacy_banner, curses.color_pair(self.C_WARN) | curses.A_BOLD, meta_max_w)
|
|
1203
|
+
ver_offset = len(privacy_banner) + 2
|
|
1204
|
+
rem_meta_w = meta_max_w - ver_offset - 1
|
|
1205
|
+
if rem_meta_w >= len(version_txt) + 2:
|
|
1206
|
+
self.put(1, meta_x + ver_offset, f"• {version_txt}", curses.color_pair(self.C_MUTED), rem_meta_w)
|
|
1207
|
+
else:
|
|
1208
|
+
self.put(1, meta_x, version_txt, curses.color_pair(self.C_MUTED), meta_max_w)
|
|
1209
|
+
self.put(2, meta_x, "terminal bandwidth & latency monitor", curses.color_pair(self.C_MUTED), meta_max_w)
|
|
1210
|
+
self.put(3, meta_x, f"Interface: {disp_iface}", curses.color_pair(self.C_ACCENT), meta_max_w)
|
|
1211
|
+
self.put(4, meta_x, f"VPN : {disp_vpn}", curses.color_pair(self.C_ACCENT), meta_max_w)
|
|
1212
|
+
payload_txt = f"Payload : {down_bytes // 1_000_000} MB ↓ / {up_bytes // 1_000_000} MB ↑"
|
|
1213
|
+
self.put(5, meta_x, payload_txt, curses.color_pair(self.C_MUTED), meta_max_w)
|
|
1214
|
+
|
|
1215
|
+
if show_header_trends:
|
|
1216
|
+
self._draw_header_trends(1, trends_x, trends_w, rows, self.selected_idx)
|
|
1217
|
+
|
|
1218
|
+
# ── 2. Option A: Two-Column Split (CONNECTION PROFILE | EDGE & ROUTE) ─
|
|
1219
|
+
split_gap = 1
|
|
1220
|
+
left_w = (inner_w - split_gap) // 2
|
|
1221
|
+
right_w = inner_w - left_w - split_gap
|
|
1222
|
+
left_x = margin
|
|
1223
|
+
right_x = margin + left_w + split_gap
|
|
1224
|
+
|
|
1225
|
+
# Left Box: CONNECTION PROFILE (Platinum White)
|
|
1226
|
+
self.draw_box(7, left_x, 6, left_w, "CONNECTION PROFILE", curses.color_pair(self.C_WHITE))
|
|
1227
|
+
l_inner = left_w - 4
|
|
1228
|
+
if l_inner > 12:
|
|
1229
|
+
self.put(8, left_x + 2, "ISP : ", curses.color_pair(self.C_MUTED), l_inner)
|
|
1230
|
+
self.put(8, left_x + 13, disp_isp, curses.color_pair(self.C_WHITE) | curses.A_BOLD, l_inner - 11)
|
|
1231
|
+
|
|
1232
|
+
self.put(9, left_x + 2, "Location : ", curses.color_pair(self.C_MUTED), l_inner)
|
|
1233
|
+
self.put(9, left_x + 13, disp_loc, curses.color_pair(self.C_WHITE), l_inner - 11)
|
|
1234
|
+
|
|
1235
|
+
iface_lan = f"{disp_iface} • LAN: {disp_lan}"
|
|
1236
|
+
self.put(10, left_x + 2, "Interface: ", curses.color_pair(self.C_MUTED), l_inner)
|
|
1237
|
+
self.put(10, left_x + 13, iface_lan, curses.color_pair(self.C_WHITE), l_inner - 11)
|
|
1238
|
+
|
|
1239
|
+
self.put(11, left_x + 2, "VPN : ", curses.color_pair(self.C_MUTED), l_inner)
|
|
1240
|
+
if disp_vpn:
|
|
1241
|
+
self.put(11, left_x + 13, disp_vpn, curses.color_pair(self.C_WHITE) | curses.A_BOLD, l_inner - 11)
|
|
1242
|
+
|
|
1243
|
+
# Right Box: EDGE & ROUTE (Electric Sky Blue)
|
|
1244
|
+
self.draw_box(7, right_x, 6, right_w, "EDGE & ROUTE", curses.color_pair(self.C_ACCENT))
|
|
1245
|
+
r_inner = right_w - 4
|
|
1246
|
+
if r_inner > 12:
|
|
1247
|
+
self.put(8, right_x + 2, "Node : ", curses.color_pair(self.C_MUTED), r_inner)
|
|
1248
|
+
self.put(
|
|
1249
|
+
8,
|
|
1250
|
+
right_x + 13,
|
|
1251
|
+
disp_node,
|
|
1252
|
+
curses.color_pair(self.C_WARN if privacy else self.C_ACCENT) | curses.A_BOLD,
|
|
1253
|
+
r_inner - 11,
|
|
1254
|
+
)
|
|
1255
|
+
|
|
1256
|
+
self.put(9, right_x + 2, "Server : ", curses.color_pair(self.C_MUTED), r_inner)
|
|
1257
|
+
self.put(9, right_x + 13, edge_server, curses.color_pair(self.C_WHITE), r_inner - 11)
|
|
1258
|
+
|
|
1259
|
+
proto_line = f"HTTP/1.1 • {tls_ver}"
|
|
1260
|
+
self.put(10, right_x + 2, "Protocol : ", curses.color_pair(self.C_MUTED), r_inner)
|
|
1261
|
+
self.put(10, right_x + 13, proto_line, curses.color_pair(self.C_WHITE), r_inner - 11)
|
|
1262
|
+
|
|
1263
|
+
self.put(11, right_x + 2, "Public IP: ", curses.color_pair(self.C_MUTED), r_inner)
|
|
1264
|
+
self.put(
|
|
1265
|
+
11,
|
|
1266
|
+
right_x + 13,
|
|
1267
|
+
disp_ip,
|
|
1268
|
+
curses.color_pair(self.C_WARN if privacy else self.C_WHITE),
|
|
1269
|
+
r_inner - 11,
|
|
1270
|
+
)
|
|
1271
|
+
|
|
1272
|
+
# ── 3. Metric Cards ─────────────────────────────────────────────────
|
|
1273
|
+
gap = 1
|
|
1274
|
+
card_w = (inner_w - gap * 2) // 3
|
|
1275
|
+
cards = [
|
|
1276
|
+
("ping", "LATENCY", ping_v, "ms", self.C_WARN),
|
|
1277
|
+
("download", f"DOWNLOAD ({down_bytes // 1_000_000} MB)", down_v, "Mbps", self.C_DOWN),
|
|
1278
|
+
("upload", f"UPLOAD ({up_bytes // 1_000_000} MB)", up_v, "Mbps", self.C_UP),
|
|
1279
|
+
]
|
|
1280
|
+
for idx, (card_phase, label, val, unit, color_id) in enumerate(cards):
|
|
1281
|
+
cx = margin + idx * (card_w + gap)
|
|
1282
|
+
cw = card_w if idx < 2 else (inner_w - cx + margin)
|
|
1283
|
+
is_card_active = is_testing and phase == card_phase
|
|
1284
|
+
box_title = f"▸ {label}" if is_card_active else label
|
|
1285
|
+
border_style = curses.color_pair(color_id) | (curses.A_BOLD if is_card_active else 0)
|
|
1286
|
+
self.draw_box(13, cx, 4, cw, box_title, border_style)
|
|
1287
|
+
|
|
1288
|
+
val_str = f"{val} {unit}"
|
|
1289
|
+
vx = cx + max(2, (cw - len(val_str)) // 2)
|
|
1290
|
+
self.put(14, vx, val, curses.color_pair(color_id) | curses.A_BOLD)
|
|
1291
|
+
self.put(14, vx + len(val) + 1, unit, curses.color_pair(self.C_MUTED))
|
|
1292
|
+
|
|
1293
|
+
# ── 4. Thick Double-Height Block Progress Bar & Live Status ─────────
|
|
1294
|
+
bar_w = max(10, inner_w - 7)
|
|
1295
|
+
bar_str = self._render_thick_bar(bar_w, progress)
|
|
1296
|
+
pct_str = f"{int(progress * 100):>3}%"
|
|
1297
|
+
|
|
1298
|
+
if is_testing or progress >= 1.0:
|
|
1299
|
+
bar_color = active_col_id
|
|
1300
|
+
else:
|
|
1301
|
+
bar_color = self.C_MUTED
|
|
1302
|
+
|
|
1303
|
+
thick_rows = 2 if max_y >= 30 else 1
|
|
1304
|
+
for r in range(thick_rows):
|
|
1305
|
+
self.put(17 + r, margin, bar_str, curses.color_pair(bar_color))
|
|
1306
|
+
|
|
1307
|
+
pct_y = 17 + (1 if thick_rows == 2 else 0)
|
|
1308
|
+
self.put(pct_y, margin + bar_w + 2, pct_str, curses.color_pair(bar_color) | curses.A_BOLD)
|
|
1309
|
+
|
|
1310
|
+
status_y = 17 + thick_rows
|
|
1311
|
+
dot_char = "◉" if is_testing else "●"
|
|
1312
|
+
self.put(
|
|
1313
|
+
status_y,
|
|
1314
|
+
margin,
|
|
1315
|
+
f"{dot_char} {status}",
|
|
1316
|
+
curses.color_pair(bar_color) | (curses.A_BOLD if is_testing else 0),
|
|
1317
|
+
inner_w,
|
|
1318
|
+
)
|
|
1319
|
+
|
|
1320
|
+
# ── 5. Full-Width Color-Coded History Browser Box ───────────────────
|
|
1321
|
+
hist_y = status_y + 1
|
|
1322
|
+
hist_h = max_y - hist_y - 2
|
|
1323
|
+
self.draw_box(hist_y, margin, hist_h, inner_w, "TEST HISTORY", curses.color_pair(self.C_ACCENT))
|
|
1324
|
+
t_inner = inner_w - 4
|
|
1325
|
+
|
|
1326
|
+
if rows:
|
|
1327
|
+
avg_d = sum(r[3] for r in rows) / len(rows)
|
|
1328
|
+
avg_u = sum(r[4] for r in rows) / len(rows)
|
|
1329
|
+
best_d = max(r[3] for r in rows)
|
|
1330
|
+
stats = (
|
|
1331
|
+
f"Runs: {len(rows)} │ Avg ↓ {avg_d:.1f} Mbps │ "
|
|
1332
|
+
f"Avg ↑ {avg_u:.1f} Mbps │ Peak ↓ {best_d:.1f} Mbps │ [Enter] Full Details"
|
|
1333
|
+
)
|
|
1334
|
+
else:
|
|
1335
|
+
stats = "No saved runs yet. Press [r] to run your first benchmark."
|
|
1336
|
+
self.put(hist_y + 1, margin + 2, stats, curses.color_pair(self.C_MUTED), t_inner)
|
|
1337
|
+
|
|
1338
|
+
# Column widths & colored headers matching metric scheme
|
|
1339
|
+
col_y = hist_y + 2
|
|
1340
|
+
w_id = 4
|
|
1341
|
+
w_dt = 17
|
|
1342
|
+
w_ping = 10
|
|
1343
|
+
w_down = 12
|
|
1344
|
+
w_up = 12
|
|
1345
|
+
w_sz = 9
|
|
1346
|
+
w_if = 15
|
|
1347
|
+
w_vpn = 12
|
|
1348
|
+
fixed_used = w_id + w_dt + w_ping + w_down + w_up + w_sz + w_if + w_vpn
|
|
1349
|
+
w_isp = max(12, t_inner - fixed_used)
|
|
1350
|
+
|
|
1351
|
+
hdr_segments = [
|
|
1352
|
+
(f"{'#':<{w_id}}", self.C_MUTED),
|
|
1353
|
+
(f"{'Date & Time':<{w_dt}}", self.C_MUTED),
|
|
1354
|
+
(f"{'Ping':<{w_ping}}", self.C_WARN),
|
|
1355
|
+
(f"{'Down':<{w_down}}", self.C_DOWN),
|
|
1356
|
+
(f"{'Up':<{w_up}}", self.C_UP),
|
|
1357
|
+
(f"{'Size ↓/↑':<{w_sz}}", self.C_MUTED),
|
|
1358
|
+
(f"{'Interface':<{w_if}}", self.C_ACCENT),
|
|
1359
|
+
(f"{'VPN':<{w_vpn}}", self.C_ACCENT),
|
|
1360
|
+
(f"{'ISP & Location':<{w_isp}}", self.C_WHITE),
|
|
1361
|
+
]
|
|
1362
|
+
hx = margin + 2
|
|
1363
|
+
for seg_txt, seg_col in hdr_segments:
|
|
1364
|
+
self.put(
|
|
1365
|
+
col_y,
|
|
1366
|
+
hx,
|
|
1367
|
+
seg_txt,
|
|
1368
|
+
curses.color_pair(seg_col) | curses.A_BOLD | curses.A_UNDERLINE,
|
|
1369
|
+
t_inner - (hx - margin - 2),
|
|
1370
|
+
)
|
|
1371
|
+
hx += len(seg_txt)
|
|
1372
|
+
|
|
1373
|
+
list_y = hist_y + 3
|
|
1374
|
+
visible_rows = max(1, hist_h - 5)
|
|
1375
|
+
if self.selected_idx < self.scroll_offset:
|
|
1376
|
+
self.scroll_offset = self.selected_idx
|
|
1377
|
+
elif self.selected_idx >= self.scroll_offset + visible_rows:
|
|
1378
|
+
self.scroll_offset = self.selected_idx - visible_rows + 1
|
|
1379
|
+
|
|
1380
|
+
for idx in range(self.scroll_offset, min(len(rows), self.scroll_offset + visible_rows)):
|
|
1381
|
+
r_id, tested_at, ping, down, up, r_isp, r_loc, _, r_iface, r_vpn, r_d_mb, r_u_mb, _ = rows[idx]
|
|
1382
|
+
clean_iface, clean_vpn = self._split_legacy_iface_vpn(r_iface, r_vpn)
|
|
1383
|
+
if privacy:
|
|
1384
|
+
row_isp_loc = "ISP Hidden (Location Hidden)"
|
|
1385
|
+
row_iface = clean_iface.split(" (", 1)[0] if " (" in clean_iface else clean_iface
|
|
1386
|
+
row_vpn = "•••" if clean_vpn else ""
|
|
1387
|
+
else:
|
|
1388
|
+
row_isp_loc = f"{r_isp} ({r_loc})"
|
|
1389
|
+
row_iface = clean_iface
|
|
1390
|
+
row_vpn = clean_vpn
|
|
1391
|
+
|
|
1392
|
+
sz_str = f"{r_d_mb:.0f}/{r_u_mb:.0f}M"
|
|
1393
|
+
y = list_y + (idx - self.scroll_offset)
|
|
1394
|
+
is_sel = idx == self.selected_idx
|
|
1395
|
+
|
|
1396
|
+
row_segments = [
|
|
1397
|
+
(f"{r_id:<{w_id}}", self.C_MUTED, False),
|
|
1398
|
+
(f"{tested_at:<{w_dt}}", self.C_WHITE, False),
|
|
1399
|
+
(f"{ping:>5.1f} ms ", self.C_WARN, True),
|
|
1400
|
+
(f"{down:>6.2f} Mbps ", self.C_DOWN, True),
|
|
1401
|
+
(f"{up:>6.2f} Mbps ", self.C_UP, True),
|
|
1402
|
+
(f"{sz_str:<{w_sz}}", self.C_MUTED, False),
|
|
1403
|
+
(f"{row_iface:<{w_if}.{w_if - 1}}", self.C_ACCENT, False),
|
|
1404
|
+
(f"{row_vpn:<{w_vpn}.{w_vpn - 1}}", self.C_ACCENT, False),
|
|
1405
|
+
(f"{row_isp_loc:<{w_isp}}", self.C_WHITE, False),
|
|
1406
|
+
]
|
|
1407
|
+
|
|
1408
|
+
if is_sel:
|
|
1409
|
+
self.put(y, margin + 2, " " * t_inner, curses.color_pair(self.C_SELECT) | curses.A_BOLD, t_inner)
|
|
1410
|
+
|
|
1411
|
+
rx = margin + 2
|
|
1412
|
+
for seg_txt, seg_col, is_bold in row_segments:
|
|
1413
|
+
rem_w = t_inner - (rx - margin - 2)
|
|
1414
|
+
if rem_w <= 0:
|
|
1415
|
+
break
|
|
1416
|
+
if is_sel:
|
|
1417
|
+
attr = curses.color_pair(self.C_SELECT) | curses.A_BOLD
|
|
1418
|
+
else:
|
|
1419
|
+
attr = curses.color_pair(seg_col) | (curses.A_BOLD if is_bold else 0)
|
|
1420
|
+
self.put(y, rx, seg_txt, attr, rem_w)
|
|
1421
|
+
rx += len(seg_txt)
|
|
1422
|
+
|
|
1423
|
+
if rows and hist_h >= 6:
|
|
1424
|
+
sel = rows[self.selected_idx]
|
|
1425
|
+
sel_iface, sel_vpn = self._split_legacy_iface_vpn(sel[8], sel[9])
|
|
1426
|
+
edge_short = "•••" if privacy else format_edge_node(sel[12], privacy=False)
|
|
1427
|
+
if privacy:
|
|
1428
|
+
vpn_part = " • VPN: •••" if sel_vpn else ""
|
|
1429
|
+
detail = (
|
|
1430
|
+
f"Selected #{sel[0]}: ISP Hidden • Edge: {edge_short} • "
|
|
1431
|
+
f"Interface: {sel_iface.split(' (', 1)[0]}{vpn_part}"
|
|
1432
|
+
)
|
|
1433
|
+
else:
|
|
1434
|
+
vpn_part = f" • VPN: {sel_vpn}" if sel_vpn else ""
|
|
1435
|
+
detail = (
|
|
1436
|
+
f"Selected #{sel[0]}: {sel[5]} • Edge: {edge_short} • "
|
|
1437
|
+
f"Interface: {sel_iface}{vpn_part}"
|
|
1438
|
+
)
|
|
1439
|
+
self.put(hist_y + hist_h - 2, margin + 2, detail, curses.color_pair(self.C_ACCENT), t_inner)
|
|
1440
|
+
|
|
1441
|
+
# ── 6. Bottom Keybinding Bar ────────────────────────────────────────
|
|
1442
|
+
privacy_label = "Privacy: ON" if privacy else "Privacy"
|
|
1443
|
+
keys = [
|
|
1444
|
+
("[R]", "Run", self.C_ACCENT),
|
|
1445
|
+
("[S]", f"Size: {size_label}", self.C_DOWN),
|
|
1446
|
+
("[Enter]", "Details", self.C_ACCENT),
|
|
1447
|
+
("[↑/↓]", "Browse", self.C_ACCENT),
|
|
1448
|
+
("[P]", privacy_label, self.C_WARN if privacy else self.C_ACCENT),
|
|
1449
|
+
("[D]", "Delete", self.C_ACCENT),
|
|
1450
|
+
("[Q]", "Quit", self.C_ACCENT),
|
|
1451
|
+
]
|
|
1452
|
+
kx = margin
|
|
1453
|
+
for key_cap, desc, k_col in keys:
|
|
1454
|
+
self.put(max_y - 1, kx, key_cap, curses.color_pair(k_col) | curses.A_BOLD)
|
|
1455
|
+
kx += len(key_cap) + 1
|
|
1456
|
+
desc_attr = (
|
|
1457
|
+
(curses.color_pair(self.C_WARN) | curses.A_BOLD)
|
|
1458
|
+
if (key_cap == "[P]" and privacy)
|
|
1459
|
+
else curses.color_pair(self.C_MUTED)
|
|
1460
|
+
)
|
|
1461
|
+
self.put(max_y - 1, kx, desc, desc_attr)
|
|
1462
|
+
kx += len(desc) + 2
|
|
1463
|
+
|
|
1464
|
+
# ── 7. Overlay Detail Modal (if active) ─────────────────────────────
|
|
1465
|
+
if modal_open and rows:
|
|
1466
|
+
self._draw_detail_modal(max_y, max_x, rows, privacy)
|
|
1467
|
+
|
|
1468
|
+
self.stdscr.refresh()
|
|
1469
|
+
|
|
1470
|
+
def loop(self) -> None:
|
|
1471
|
+
while True:
|
|
1472
|
+
self.draw()
|
|
1473
|
+
key = self.stdscr.getch()
|
|
1474
|
+
if key == -1:
|
|
1475
|
+
continue
|
|
1476
|
+
|
|
1477
|
+
if key == curses.KEY_RESIZE:
|
|
1478
|
+
self._handle_resize()
|
|
1479
|
+
continue
|
|
1480
|
+
|
|
1481
|
+
# Modal-specific controls when details popup is open
|
|
1482
|
+
if self.detail_modal_open:
|
|
1483
|
+
if key in (27, 10, 13, curses.KEY_ENTER, ord("q"), ord("Q"), ord("c"), ord("C")):
|
|
1484
|
+
self.detail_modal_open = False
|
|
1485
|
+
elif key in (curses.KEY_LEFT, curses.KEY_UP) and self.rows:
|
|
1486
|
+
self.selected_idx = (self.selected_idx - 1) % len(self.rows)
|
|
1487
|
+
elif key in (curses.KEY_RIGHT, curses.KEY_DOWN) and self.rows:
|
|
1488
|
+
self.selected_idx = (self.selected_idx + 1) % len(self.rows)
|
|
1489
|
+
elif key in (ord("p"), ord("P")):
|
|
1490
|
+
with self.state_lock:
|
|
1491
|
+
self.privacy_mode = not self.privacy_mode
|
|
1492
|
+
continue
|
|
1493
|
+
|
|
1494
|
+
if key in (ord("q"), ord("Q")):
|
|
1495
|
+
break
|
|
1496
|
+
elif key in (ord("p"), ord("P")):
|
|
1497
|
+
with self.state_lock:
|
|
1498
|
+
self.privacy_mode = not self.privacy_mode
|
|
1499
|
+
state_txt = "enabled (PII masked)" if self.privacy_mode else "disabled"
|
|
1500
|
+
if not self.is_testing:
|
|
1501
|
+
self.status = f"Privacy Mode {state_txt}"
|
|
1502
|
+
elif key in (ord("s"), ord("S")):
|
|
1503
|
+
with self.state_lock:
|
|
1504
|
+
if not self.is_testing:
|
|
1505
|
+
self.size_preset_idx = (self.size_preset_idx + 1) % len(SIZE_PRESETS)
|
|
1506
|
+
lbl, d_b, u_b = SIZE_PRESETS[self.size_preset_idx]
|
|
1507
|
+
self.status = f"Test payload set to {lbl} ({d_b // 1_000_000} MB ↓ / {u_b // 1_000_000} MB ↑)"
|
|
1508
|
+
elif key in (10, 13, curses.KEY_ENTER) and self.rows:
|
|
1509
|
+
self.detail_modal_open = True
|
|
1510
|
+
elif key in (ord("r"), ord("R")):
|
|
1511
|
+
with self.state_lock:
|
|
1512
|
+
if not self.is_testing:
|
|
1513
|
+
self.is_testing = True
|
|
1514
|
+
threading.Thread(target=self.run_speed_test_worker, daemon=True).start()
|
|
1515
|
+
elif key == curses.KEY_UP and self.rows:
|
|
1516
|
+
self.selected_idx = max(0, self.selected_idx - 1)
|
|
1517
|
+
elif key == curses.KEY_DOWN and self.rows:
|
|
1518
|
+
self.selected_idx = min(len(self.rows) - 1, self.selected_idx + 1)
|
|
1519
|
+
elif key in (ord("d"), ord("D")) and self.rows:
|
|
1520
|
+
with self.state_lock:
|
|
1521
|
+
row_id = self.rows[self.selected_idx][0]
|
|
1522
|
+
self.store.delete(row_id)
|
|
1523
|
+
self.reload_history()
|
|
1524
|
+
self.status = f"Deleted run #{row_id} from history."
|
|
1525
|
+
|
|
1526
|
+
|
|
1527
|
+
class CliPrinter:
|
|
1528
|
+
"""ANSI 256-color stdout logger matching blip's semantic palette."""
|
|
1529
|
+
|
|
1530
|
+
CODES = {
|
|
1531
|
+
"accent": "\033[38;5;39m",
|
|
1532
|
+
"down": "\033[38;5;42m",
|
|
1533
|
+
"up": "\033[38;5;141m",
|
|
1534
|
+
"warn": "\033[38;5;214m",
|
|
1535
|
+
"muted": "\033[38;5;244m",
|
|
1536
|
+
"white": "\033[38;5;255m",
|
|
1537
|
+
"bold": "\033[1m",
|
|
1538
|
+
"reset": "\033[0m",
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
def __init__(self, use_color: bool, is_tty: bool) -> None:
|
|
1542
|
+
self.use_color = use_color
|
|
1543
|
+
self.is_tty = is_tty
|
|
1544
|
+
self._has_inline = False
|
|
1545
|
+
|
|
1546
|
+
def style(self, text: str, *tokens: str) -> str:
|
|
1547
|
+
if not self.use_color or not tokens:
|
|
1548
|
+
return text
|
|
1549
|
+
prefix = "".join(self.CODES.get(t, "") for t in tokens)
|
|
1550
|
+
return f"{prefix}{text}{self.CODES['reset']}"
|
|
1551
|
+
|
|
1552
|
+
def ts(self) -> str:
|
|
1553
|
+
return self.style(f"[{datetime.now().strftime('%H:%M:%S')}]", "muted")
|
|
1554
|
+
|
|
1555
|
+
def clear_inline(self) -> None:
|
|
1556
|
+
if self._has_inline and self.is_tty:
|
|
1557
|
+
sys.stdout.write("\r\033[2K")
|
|
1558
|
+
sys.stdout.flush()
|
|
1559
|
+
self._has_inline = False
|
|
1560
|
+
|
|
1561
|
+
def log(self, message: str) -> None:
|
|
1562
|
+
self.clear_inline()
|
|
1563
|
+
print(f"{self.ts()} {message}", flush=True)
|
|
1564
|
+
|
|
1565
|
+
def inline(self, message: str) -> None:
|
|
1566
|
+
if not self.is_tty:
|
|
1567
|
+
return
|
|
1568
|
+
sys.stdout.write(f"\r\033[2K{message}")
|
|
1569
|
+
sys.stdout.flush()
|
|
1570
|
+
self._has_inline = True
|
|
1571
|
+
|
|
1572
|
+
|
|
1573
|
+
def _format_profile_fields(runner: SpeedTestRunner, privacy: bool) -> dict[str, str]:
|
|
1574
|
+
"""Formats connection & edge fields with consistent Privacy Mode redaction."""
|
|
1575
|
+
with runner.state_lock:
|
|
1576
|
+
isp, asn, location, ip = runner.isp, runner.asn, runner.location, runner.ip
|
|
1577
|
+
colo_display, edge_server, tls_ver = runner.colo_display, runner.edge_server, runner.tls_version
|
|
1578
|
+
iface_summary, iface_type, vpn_name, lan_ip = (
|
|
1579
|
+
runner.iface_summary,
|
|
1580
|
+
runner.iface_type,
|
|
1581
|
+
runner.vpn_name,
|
|
1582
|
+
runner.lan_ip,
|
|
1583
|
+
)
|
|
1584
|
+
|
|
1585
|
+
if privacy:
|
|
1586
|
+
return {
|
|
1587
|
+
"isp": "ISP Hidden (AS•••••)" if asn else "ISP Hidden",
|
|
1588
|
+
"location": "Location Hidden",
|
|
1589
|
+
"ip": "•••.•••.•••.•••",
|
|
1590
|
+
"lan_ip": "•••.•••.•••.•••",
|
|
1591
|
+
"iface": f"{iface_type} (•••)",
|
|
1592
|
+
"vpn": "•••" if vpn_name else "",
|
|
1593
|
+
"edge": "••• (Location Hidden)",
|
|
1594
|
+
"server": edge_server,
|
|
1595
|
+
"protocol": f"HTTP/1.1 • {tls_ver}",
|
|
1596
|
+
}
|
|
1597
|
+
return {
|
|
1598
|
+
"isp": f"{isp} ({asn})" if (asn and asn not in str(isp)) else str(isp),
|
|
1599
|
+
"location": str(location),
|
|
1600
|
+
"ip": str(ip),
|
|
1601
|
+
"lan_ip": str(lan_ip),
|
|
1602
|
+
"iface": str(iface_summary),
|
|
1603
|
+
"vpn": str(vpn_name) if vpn_name else "",
|
|
1604
|
+
"edge": str(colo_display),
|
|
1605
|
+
"server": edge_server,
|
|
1606
|
+
"protocol": f"HTTP/1.1 • {tls_ver}",
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
|
|
1610
|
+
def run_cli_test(
|
|
1611
|
+
size_preset_idx: int,
|
|
1612
|
+
privacy: bool,
|
|
1613
|
+
save_history: bool,
|
|
1614
|
+
db_path: Path,
|
|
1615
|
+
as_json: bool,
|
|
1616
|
+
no_color: bool,
|
|
1617
|
+
) -> int:
|
|
1618
|
+
"""Runs a non-TUI speed test and prints detailed, themed logs (or JSON) to stdout."""
|
|
1619
|
+
is_tty = sys.stdout.isatty()
|
|
1620
|
+
use_color = is_tty and not no_color and not os.environ.get("NO_COLOR") and not as_json
|
|
1621
|
+
out = CliPrinter(use_color=use_color, is_tty=is_tty)
|
|
1622
|
+
|
|
1623
|
+
size_label, down_bytes, up_bytes = SIZE_PRESETS[size_preset_idx]
|
|
1624
|
+
runner = SpeedTestRunner()
|
|
1625
|
+
|
|
1626
|
+
if not as_json:
|
|
1627
|
+
for line in build_logo_lines("●"):
|
|
1628
|
+
print(out.style(line, "white", "bold"), flush=True)
|
|
1629
|
+
dot = out.style("●", "accent", "bold")
|
|
1630
|
+
title = out.style(f"blip v{VERSION}", "white", "bold")
|
|
1631
|
+
sub = out.style("terminal bandwidth & latency monitor", "muted")
|
|
1632
|
+
print(f"{dot} {title} — {sub}", flush=True)
|
|
1633
|
+
if privacy:
|
|
1634
|
+
print(out.style("🔒 PRIVACY MODE ACTIVE (PII redacted)", "warn", "bold"), flush=True)
|
|
1635
|
+
print(
|
|
1636
|
+
out.style(
|
|
1637
|
+
f" Payload: {size_label} ({down_bytes // 1_000_000} MB ↓ / {up_bytes // 1_000_000} MB ↑)",
|
|
1638
|
+
"muted",
|
|
1639
|
+
),
|
|
1640
|
+
flush=True,
|
|
1641
|
+
)
|
|
1642
|
+
out.log(out.style("Detecting local interface & network metadata...", "white"))
|
|
1643
|
+
|
|
1644
|
+
runner._fetch_network_meta()
|
|
1645
|
+
meta = _format_profile_fields(runner, privacy)
|
|
1646
|
+
|
|
1647
|
+
if not as_json:
|
|
1648
|
+
out.log(out.style("Connection Profile & Edge Route:", "accent", "bold"))
|
|
1649
|
+
profile_rows = [
|
|
1650
|
+
("ISP", meta["isp"], "white"),
|
|
1651
|
+
("Location", meta["location"], "white"),
|
|
1652
|
+
("Interface", f"{meta['iface']} • LAN: {meta['lan_ip']}", "accent"),
|
|
1653
|
+
]
|
|
1654
|
+
if meta["vpn"]:
|
|
1655
|
+
profile_rows.append(("VPN", meta["vpn"], "accent"))
|
|
1656
|
+
profile_rows.extend(
|
|
1657
|
+
[
|
|
1658
|
+
("Edge Node", meta["edge"], "warn" if privacy else "accent"),
|
|
1659
|
+
("Server", meta["server"], "white"),
|
|
1660
|
+
("Protocol", meta["protocol"], "white"),
|
|
1661
|
+
("Public IP", meta["ip"], "warn" if privacy else "white"),
|
|
1662
|
+
]
|
|
1663
|
+
)
|
|
1664
|
+
for lbl, val, col in profile_rows:
|
|
1665
|
+
print(f" {out.style(f'{lbl:<10}:', 'muted')} {out.style(val, col)}", flush=True)
|
|
1666
|
+
|
|
1667
|
+
result: dict[str, object] = {}
|
|
1668
|
+
error_holder: list[Exception] = []
|
|
1669
|
+
done_event = threading.Event()
|
|
1670
|
+
|
|
1671
|
+
def _worker() -> None:
|
|
1672
|
+
try:
|
|
1673
|
+
try:
|
|
1674
|
+
res = runner._run_cloudflare_test(down_bytes, up_bytes)
|
|
1675
|
+
except PermissionError:
|
|
1676
|
+
res = runner._run_fallback_test(down_bytes, up_bytes)
|
|
1677
|
+
ping_ms, down_mbps, up_mbps, actual_down_mb, actual_up_mb = res
|
|
1678
|
+
result["ping_ms"] = ping_ms
|
|
1679
|
+
result["down_mbps"] = down_mbps
|
|
1680
|
+
result["up_mbps"] = up_mbps
|
|
1681
|
+
result["down_mb"] = actual_down_mb
|
|
1682
|
+
result["up_mb"] = actual_up_mb
|
|
1683
|
+
except Exception as exc:
|
|
1684
|
+
error_holder.append(exc)
|
|
1685
|
+
finally:
|
|
1686
|
+
done_event.set()
|
|
1687
|
+
|
|
1688
|
+
threading.Thread(target=_worker, daemon=True).start()
|
|
1689
|
+
|
|
1690
|
+
last_phase = ""
|
|
1691
|
+
phase_colors = {"ping": "warn", "download": "down", "upload": "up"}
|
|
1692
|
+
while not done_event.wait(0.08):
|
|
1693
|
+
with runner.state_lock:
|
|
1694
|
+
phase = runner.phase
|
|
1695
|
+
status = runner.status
|
|
1696
|
+
progress = runner.progress
|
|
1697
|
+
ping_v, down_v, up_v = runner.ping_val, runner.down_val, runner.up_val
|
|
1698
|
+
|
|
1699
|
+
if not as_json:
|
|
1700
|
+
if phase != last_phase and phase in phase_colors:
|
|
1701
|
+
if last_phase == "ping" and ping_v not in ("--", "..."):
|
|
1702
|
+
out.log(f"{out.style('Latency :', 'muted')} {out.style(f'{ping_v} ms', 'warn', 'bold')}")
|
|
1703
|
+
elif last_phase == "download" and down_v not in ("--", "..."):
|
|
1704
|
+
out.log(f"{out.style('Download :', 'muted')} {out.style(f'{down_v} Mbps', 'down', 'bold')}")
|
|
1705
|
+
out.log(out.style(f"▸ {status}", phase_colors[phase], "bold"))
|
|
1706
|
+
last_phase = phase
|
|
1707
|
+
|
|
1708
|
+
if is_tty and phase in phase_colors:
|
|
1709
|
+
col = phase_colors[phase]
|
|
1710
|
+
bar = render_thick_bar(24, progress)
|
|
1711
|
+
pct = f"{int(progress * 100):>3}%"
|
|
1712
|
+
live_metric = ""
|
|
1713
|
+
if phase == "download" and down_v not in ("--", "..."):
|
|
1714
|
+
live_metric = f" {down_v} Mbps"
|
|
1715
|
+
elif phase == "upload" and up_v not in ("--", "..."):
|
|
1716
|
+
live_metric = f" {up_v} Mbps"
|
|
1717
|
+
out.inline(f" {out.style(bar, col)} {out.style(pct, col, 'bold')}{out.style(live_metric, col)}")
|
|
1718
|
+
|
|
1719
|
+
out.clear_inline()
|
|
1720
|
+
|
|
1721
|
+
if error_holder:
|
|
1722
|
+
err_msg = str(error_holder[0])
|
|
1723
|
+
if as_json:
|
|
1724
|
+
print(json.dumps({"ok": False, "error": err_msg}, indent=2))
|
|
1725
|
+
else:
|
|
1726
|
+
print(f"{out.ts()} {out.style(f'✖ Test failed: {err_msg}', 'warn', 'bold')}", file=sys.stderr)
|
|
1727
|
+
return 1
|
|
1728
|
+
|
|
1729
|
+
ping_ms = float(result["ping_ms"])
|
|
1730
|
+
down_mbps = float(result["down_mbps"])
|
|
1731
|
+
up_mbps = float(result["up_mbps"])
|
|
1732
|
+
actual_down_mb = float(result["down_mb"])
|
|
1733
|
+
actual_up_mb = float(result["up_mb"])
|
|
1734
|
+
|
|
1735
|
+
if not as_json:
|
|
1736
|
+
if last_phase == "ping":
|
|
1737
|
+
out.log(f"{out.style('Latency :', 'muted')} {out.style(f'{ping_ms:.1f} ms', 'warn', 'bold')}")
|
|
1738
|
+
elif last_phase == "download":
|
|
1739
|
+
out.log(f"{out.style('Download :', 'muted')} {out.style(f'{down_mbps:.2f} Mbps', 'down', 'bold')}")
|
|
1740
|
+
elif last_phase == "upload":
|
|
1741
|
+
out.log(f"{out.style('Upload :', 'muted')} {out.style(f'{up_mbps:.2f} Mbps', 'up', 'bold')}")
|
|
1742
|
+
|
|
1743
|
+
if save_history:
|
|
1744
|
+
with runner.state_lock:
|
|
1745
|
+
raw_isp = runner.isp
|
|
1746
|
+
raw_loc = runner.location
|
|
1747
|
+
raw_ip = runner.ip
|
|
1748
|
+
raw_iface = runner.iface_summary
|
|
1749
|
+
raw_vpn = runner.vpn_name
|
|
1750
|
+
raw_edge = runner.colo_display
|
|
1751
|
+
store = HistoryStore(db_path)
|
|
1752
|
+
store.save(
|
|
1753
|
+
ping_ms,
|
|
1754
|
+
down_mbps,
|
|
1755
|
+
up_mbps,
|
|
1756
|
+
raw_isp,
|
|
1757
|
+
raw_loc,
|
|
1758
|
+
raw_ip,
|
|
1759
|
+
raw_iface,
|
|
1760
|
+
raw_vpn,
|
|
1761
|
+
actual_down_mb,
|
|
1762
|
+
actual_up_mb,
|
|
1763
|
+
raw_edge,
|
|
1764
|
+
)
|
|
1765
|
+
|
|
1766
|
+
final_meta = _format_profile_fields(runner, privacy)
|
|
1767
|
+
|
|
1768
|
+
if as_json:
|
|
1769
|
+
payload = {
|
|
1770
|
+
"ok": True,
|
|
1771
|
+
"version": VERSION,
|
|
1772
|
+
"tested_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
|
1773
|
+
"privacy_mode": privacy,
|
|
1774
|
+
"saved": save_history,
|
|
1775
|
+
"db_path": str(db_path) if save_history else None,
|
|
1776
|
+
"ping_ms": round(ping_ms, 1),
|
|
1777
|
+
"download_mbps": round(down_mbps, 2),
|
|
1778
|
+
"upload_mbps": round(up_mbps, 2),
|
|
1779
|
+
"down_mb": round(actual_down_mb, 1),
|
|
1780
|
+
"up_mb": round(actual_up_mb, 1),
|
|
1781
|
+
"profile": final_meta,
|
|
1782
|
+
}
|
|
1783
|
+
print(json.dumps(payload, indent=2))
|
|
1784
|
+
return 0
|
|
1785
|
+
|
|
1786
|
+
box_w = 58
|
|
1787
|
+
title_txt = " BLIP SUMMARY "
|
|
1788
|
+
top_border = "╭─" + title_txt + "─" * (box_w - 3 - len(title_txt)) + "╮"
|
|
1789
|
+
bot_border = "╰" + "─" * (box_w - 2) + "╯"
|
|
1790
|
+
print(out.style(top_border, "accent"))
|
|
1791
|
+
|
|
1792
|
+
summary_lines = [
|
|
1793
|
+
("Latency", f"{ping_ms:.1f} ms", "warn"),
|
|
1794
|
+
("Download", f"{down_mbps:.2f} Mbps ({actual_down_mb:.0f} MB)", "down"),
|
|
1795
|
+
("Upload", f"{up_mbps:.2f} Mbps ({actual_up_mb:.0f} MB)", "up"),
|
|
1796
|
+
("Edge", f"{final_meta['edge']} • {final_meta['server']}", "accent"),
|
|
1797
|
+
]
|
|
1798
|
+
for lbl, val, col in summary_lines:
|
|
1799
|
+
prefix = f" {lbl:<9}: "
|
|
1800
|
+
max_val_w = (box_w - 2) - len(prefix)
|
|
1801
|
+
disp_val = val if len(val) <= max_val_w else val[: max(0, max_val_w - 3)] + "..."
|
|
1802
|
+
pad = " " * max(0, max_val_w - len(disp_val))
|
|
1803
|
+
styled_line = (
|
|
1804
|
+
out.style("│", "accent")
|
|
1805
|
+
+ out.style(prefix, "muted")
|
|
1806
|
+
+ out.style(disp_val, col, "bold")
|
|
1807
|
+
+ pad
|
|
1808
|
+
+ out.style("│", "accent")
|
|
1809
|
+
)
|
|
1810
|
+
print(styled_line)
|
|
1811
|
+
|
|
1812
|
+
print(out.style(bot_border, "accent"))
|
|
1813
|
+
|
|
1814
|
+
if save_history:
|
|
1815
|
+
out.log(out.style(f"● Saved result to {db_path}", "down"))
|
|
1816
|
+
else:
|
|
1817
|
+
out.log(out.style("● Skipped saving (--no-save)", "muted"))
|
|
1818
|
+
|
|
1819
|
+
sig = (
|
|
1820
|
+
out.style("made with ", "muted")
|
|
1821
|
+
+ out.style("♥", "warn", "bold")
|
|
1822
|
+
+ out.style(" by ", "muted")
|
|
1823
|
+
+ out.style("picogeeks.com", "accent")
|
|
1824
|
+
)
|
|
1825
|
+
print(sig)
|
|
1826
|
+
|
|
1827
|
+
return 0
|
|
1828
|
+
|
|
1829
|
+
|
|
1830
|
+
def run_cli_history(
|
|
1831
|
+
limit: int,
|
|
1832
|
+
privacy: bool,
|
|
1833
|
+
db_path: Path,
|
|
1834
|
+
as_json: bool,
|
|
1835
|
+
no_color: bool,
|
|
1836
|
+
) -> int:
|
|
1837
|
+
"""Prints saved speed test history from SQLite to stdout (or JSON)."""
|
|
1838
|
+
is_tty = sys.stdout.isatty()
|
|
1839
|
+
use_color = is_tty and not no_color and not os.environ.get("NO_COLOR") and not as_json
|
|
1840
|
+
out = CliPrinter(use_color=use_color, is_tty=is_tty)
|
|
1841
|
+
|
|
1842
|
+
all_rows = HistoryStore(db_path).fetch_all()
|
|
1843
|
+
shown_rows = all_rows[:limit] if limit > 0 else all_rows
|
|
1844
|
+
|
|
1845
|
+
avg_d = sum(r[3] for r in all_rows) / len(all_rows) if all_rows else 0.0
|
|
1846
|
+
avg_u = sum(r[4] for r in all_rows) / len(all_rows) if all_rows else 0.0
|
|
1847
|
+
peak_d = max((r[3] for r in all_rows), default=0.0)
|
|
1848
|
+
|
|
1849
|
+
def _format_row(row: tuple) -> dict[str, object]:
|
|
1850
|
+
r_id, tested_at, ping_ms, down_mbps, up_mbps, r_isp, r_loc, r_ip, r_iface, r_vpn, r_dmb, r_umb, r_edge = row
|
|
1851
|
+
clean_iface, clean_vpn = split_legacy_iface_vpn(r_iface, r_vpn)
|
|
1852
|
+
if privacy:
|
|
1853
|
+
disp_isp = "ISP Hidden"
|
|
1854
|
+
disp_loc = "Location Hidden"
|
|
1855
|
+
disp_ip = "•••.•••.•••.•••"
|
|
1856
|
+
disp_iface = (clean_iface.split(" (", 1)[0] + " (•••)") if " (" in clean_iface else clean_iface
|
|
1857
|
+
disp_vpn = "•••" if clean_vpn else ""
|
|
1858
|
+
disp_edge = "••• (Location Hidden)"
|
|
1859
|
+
else:
|
|
1860
|
+
disp_isp = str(r_isp or "Unknown")
|
|
1861
|
+
disp_loc = str(r_loc or "Unknown")
|
|
1862
|
+
disp_ip = str(r_ip or "")
|
|
1863
|
+
disp_iface = clean_iface
|
|
1864
|
+
disp_vpn = clean_vpn
|
|
1865
|
+
disp_edge = format_edge_node(r_edge, privacy=False)
|
|
1866
|
+
return {
|
|
1867
|
+
"id": r_id,
|
|
1868
|
+
"tested_at": tested_at,
|
|
1869
|
+
"ping_ms": round(ping_ms, 1),
|
|
1870
|
+
"download_mbps": round(down_mbps, 2),
|
|
1871
|
+
"upload_mbps": round(up_mbps, 2),
|
|
1872
|
+
"down_mb": round(r_dmb, 1),
|
|
1873
|
+
"up_mb": round(r_umb, 1),
|
|
1874
|
+
"iface": disp_iface,
|
|
1875
|
+
"vpn": disp_vpn,
|
|
1876
|
+
"edge": disp_edge,
|
|
1877
|
+
"isp": disp_isp,
|
|
1878
|
+
"location": disp_loc,
|
|
1879
|
+
"ip": disp_ip,
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
formatted = [_format_row(r) for r in shown_rows]
|
|
1883
|
+
|
|
1884
|
+
if as_json:
|
|
1885
|
+
payload = {
|
|
1886
|
+
"ok": True,
|
|
1887
|
+
"version": VERSION,
|
|
1888
|
+
"db_path": str(db_path),
|
|
1889
|
+
"privacy_mode": privacy,
|
|
1890
|
+
"total_runs": len(all_rows),
|
|
1891
|
+
"shown_runs": len(formatted),
|
|
1892
|
+
"stats": {
|
|
1893
|
+
"avg_download_mbps": round(avg_d, 2),
|
|
1894
|
+
"avg_upload_mbps": round(avg_u, 2),
|
|
1895
|
+
"peak_download_mbps": round(peak_d, 2),
|
|
1896
|
+
},
|
|
1897
|
+
"runs": formatted,
|
|
1898
|
+
}
|
|
1899
|
+
print(json.dumps(payload, indent=2))
|
|
1900
|
+
return 0
|
|
1901
|
+
|
|
1902
|
+
for line in build_logo_lines("●"):
|
|
1903
|
+
print(out.style(line, "white", "bold"), flush=True)
|
|
1904
|
+
dot = out.style("●", "accent", "bold")
|
|
1905
|
+
title = out.style(f"blip v{VERSION}", "white", "bold")
|
|
1906
|
+
sub = out.style("test history", "muted")
|
|
1907
|
+
print(f"{dot} {title} — {sub}", flush=True)
|
|
1908
|
+
if privacy:
|
|
1909
|
+
print(out.style("🔒 PRIVACY MODE ACTIVE (PII redacted)", "warn", "bold"), flush=True)
|
|
1910
|
+
|
|
1911
|
+
if not all_rows:
|
|
1912
|
+
print(out.style(f"No test history found in {db_path}.", "muted"), flush=True)
|
|
1913
|
+
return 0
|
|
1914
|
+
|
|
1915
|
+
stats_line = (
|
|
1916
|
+
out.style(f"Runs: {len(all_rows)}", "white", "bold")
|
|
1917
|
+
+ out.style(" • ", "muted")
|
|
1918
|
+
+ out.style(f"Showing: {len(formatted)}", "muted")
|
|
1919
|
+
+ out.style(" • ", "muted")
|
|
1920
|
+
+ out.style(f"Avg ↓: {avg_d:.2f} Mbps", "down", "bold")
|
|
1921
|
+
+ out.style(" • ", "muted")
|
|
1922
|
+
+ out.style(f"Avg ↑: {avg_u:.2f} Mbps", "up", "bold")
|
|
1923
|
+
+ out.style(" • ", "muted")
|
|
1924
|
+
+ out.style(f"Peak ↓: {peak_d:.2f} Mbps", "down")
|
|
1925
|
+
)
|
|
1926
|
+
print(stats_line, flush=True)
|
|
1927
|
+
print(out.style("─" * 102, "muted"), flush=True)
|
|
1928
|
+
|
|
1929
|
+
header = (
|
|
1930
|
+
f"{'#':>4} {'Date & Time':<16} {'Ping':>8} {'Down':>11} {'Up':>11} "
|
|
1931
|
+
f"{'Size':>7} {'Interface':<14} {'VPN':<8} {'ISP & Location'}"
|
|
1932
|
+
)
|
|
1933
|
+
print(out.style(header, "muted", "bold"), flush=True)
|
|
1934
|
+
print(out.style("─" * 102, "muted"), flush=True)
|
|
1935
|
+
|
|
1936
|
+
for item in formatted:
|
|
1937
|
+
size_str = f"{item['down_mb']:.0f}/{item['up_mb']:.0f}M"
|
|
1938
|
+
iface_str = str(item["iface"])[:14]
|
|
1939
|
+
vpn_str = str(item["vpn"])[:8]
|
|
1940
|
+
isp_loc = f"{item['isp']} ({item['location']})"
|
|
1941
|
+
if len(isp_loc) > 30:
|
|
1942
|
+
isp_loc = isp_loc[:27] + "..."
|
|
1943
|
+
|
|
1944
|
+
row_line = (
|
|
1945
|
+
out.style(f"{item['id']:>4}", "muted")
|
|
1946
|
+
+ " "
|
|
1947
|
+
+ out.style(f"{item['tested_at']:<16}", "white")
|
|
1948
|
+
+ " "
|
|
1949
|
+
+ out.style(f"{item['ping_ms']:>5.1f} ms", "warn")
|
|
1950
|
+
+ " "
|
|
1951
|
+
+ out.style(f"{item['download_mbps']:>6.2f} Mbps", "down", "bold")
|
|
1952
|
+
+ " "
|
|
1953
|
+
+ out.style(f"{item['upload_mbps']:>6.2f} Mbps", "up", "bold")
|
|
1954
|
+
+ " "
|
|
1955
|
+
+ out.style(f"{size_str:>7}", "muted")
|
|
1956
|
+
+ " "
|
|
1957
|
+
+ out.style(f"{iface_str:<14}", "accent")
|
|
1958
|
+
+ " "
|
|
1959
|
+
+ out.style(f"{vpn_str:<8}", "accent")
|
|
1960
|
+
+ " "
|
|
1961
|
+
+ out.style(isp_loc, "white")
|
|
1962
|
+
)
|
|
1963
|
+
print(row_line, flush=True)
|
|
1964
|
+
|
|
1965
|
+
print(out.style("─" * 102, "muted"), flush=True)
|
|
1966
|
+
sig = (
|
|
1967
|
+
out.style("made with ", "muted")
|
|
1968
|
+
+ out.style("♥", "warn", "bold")
|
|
1969
|
+
+ out.style(" by ", "muted")
|
|
1970
|
+
+ out.style("picogeeks.com", "accent")
|
|
1971
|
+
)
|
|
1972
|
+
print(sig, flush=True)
|
|
1973
|
+
return 0
|
|
1974
|
+
|
|
1975
|
+
|
|
1976
|
+
def build_arg_parser() -> argparse.ArgumentParser:
|
|
1977
|
+
parser = argparse.ArgumentParser(
|
|
1978
|
+
prog="blip",
|
|
1979
|
+
description="blip — zero-dependency terminal bandwidth & latency monitor",
|
|
1980
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
1981
|
+
epilog=(
|
|
1982
|
+
"examples:\n"
|
|
1983
|
+
" blip Launch interactive TUI\n"
|
|
1984
|
+
" blip --run Run a speed test in headless CLI mode\n"
|
|
1985
|
+
" blip --run --size 50 Run 50 MB download / 20 MB upload test\n"
|
|
1986
|
+
" blip --run --privacy Run CLI test with PII redacted\n"
|
|
1987
|
+
" blip --run --json --no-save Output JSON without writing to history.db\n"
|
|
1988
|
+
" blip --history Show recent 20 runs from history.db\n"
|
|
1989
|
+
" blip --history 0 --json Dump all saved runs as JSON\n"
|
|
1990
|
+
),
|
|
1991
|
+
)
|
|
1992
|
+
parser.add_argument(
|
|
1993
|
+
"-v",
|
|
1994
|
+
"--version",
|
|
1995
|
+
action="version",
|
|
1996
|
+
version=f"blip v{VERSION}",
|
|
1997
|
+
)
|
|
1998
|
+
parser.add_argument(
|
|
1999
|
+
"--run",
|
|
2000
|
+
"--cli",
|
|
2001
|
+
action="store_true",
|
|
2002
|
+
dest="run_cli",
|
|
2003
|
+
help="Run speed test in non-TUI CLI mode and print detailed logs to stdout",
|
|
2004
|
+
)
|
|
2005
|
+
parser.add_argument(
|
|
2006
|
+
"--history",
|
|
2007
|
+
nargs="?",
|
|
2008
|
+
const=20,
|
|
2009
|
+
type=int,
|
|
2010
|
+
metavar="N",
|
|
2011
|
+
help="Print saved test history from SQLite to stdout (default: 20 runs, 0 for all)",
|
|
2012
|
+
)
|
|
2013
|
+
parser.add_argument(
|
|
2014
|
+
"-s",
|
|
2015
|
+
"--size",
|
|
2016
|
+
type=int,
|
|
2017
|
+
choices=[25, 50, 100],
|
|
2018
|
+
default=25,
|
|
2019
|
+
help="Download payload size preset in MB: 25 (default), 50, or 100",
|
|
2020
|
+
)
|
|
2021
|
+
parser.add_argument(
|
|
2022
|
+
"-p",
|
|
2023
|
+
"--privacy",
|
|
2024
|
+
action="store_true",
|
|
2025
|
+
help="Enable Privacy Mode (redact ISP, location, IPs, interface device, VPN, edge)",
|
|
2026
|
+
)
|
|
2027
|
+
parser.add_argument(
|
|
2028
|
+
"--no-save",
|
|
2029
|
+
action="store_true",
|
|
2030
|
+
help="Do not save CLI test result to SQLite history (CLI mode only)",
|
|
2031
|
+
)
|
|
2032
|
+
parser.add_argument(
|
|
2033
|
+
"--db",
|
|
2034
|
+
type=Path,
|
|
2035
|
+
default=DB_PATH,
|
|
2036
|
+
help=f"Path to SQLite history database (default: {DB_PATH})",
|
|
2037
|
+
)
|
|
2038
|
+
parser.add_argument(
|
|
2039
|
+
"--json",
|
|
2040
|
+
action="store_true",
|
|
2041
|
+
help="Output CLI test result as JSON (implies --run)",
|
|
2042
|
+
)
|
|
2043
|
+
parser.add_argument(
|
|
2044
|
+
"--no-color",
|
|
2045
|
+
action="store_true",
|
|
2046
|
+
help="Disable ANSI colors in CLI mode",
|
|
2047
|
+
)
|
|
2048
|
+
return parser
|
|
2049
|
+
|
|
2050
|
+
|
|
2051
|
+
def main() -> None:
|
|
2052
|
+
args = build_arg_parser().parse_args()
|
|
2053
|
+
size_map = {25: 0, 50: 1, 100: 2}
|
|
2054
|
+
preset_idx = size_map[args.size]
|
|
2055
|
+
|
|
2056
|
+
if args.history is not None:
|
|
2057
|
+
raise SystemExit(
|
|
2058
|
+
run_cli_history(
|
|
2059
|
+
limit=args.history,
|
|
2060
|
+
privacy=args.privacy,
|
|
2061
|
+
db_path=args.db,
|
|
2062
|
+
as_json=args.json,
|
|
2063
|
+
no_color=args.no_color,
|
|
2064
|
+
)
|
|
2065
|
+
)
|
|
2066
|
+
|
|
2067
|
+
if args.run_cli or args.json:
|
|
2068
|
+
raise SystemExit(
|
|
2069
|
+
run_cli_test(
|
|
2070
|
+
size_preset_idx=preset_idx,
|
|
2071
|
+
privacy=args.privacy,
|
|
2072
|
+
save_history=not args.no_save,
|
|
2073
|
+
db_path=args.db,
|
|
2074
|
+
as_json=args.json,
|
|
2075
|
+
no_color=args.no_color,
|
|
2076
|
+
)
|
|
2077
|
+
)
|
|
2078
|
+
|
|
2079
|
+
os.environ.setdefault("ESCDELAY", "25")
|
|
2080
|
+
curses.wrapper(
|
|
2081
|
+
lambda stdscr: BlipTUI(
|
|
2082
|
+
stdscr,
|
|
2083
|
+
size_preset_idx=preset_idx,
|
|
2084
|
+
privacy_mode=args.privacy,
|
|
2085
|
+
db_path=args.db,
|
|
2086
|
+
).loop()
|
|
2087
|
+
)
|
|
2088
|
+
|
|
2089
|
+
|
|
2090
|
+
if __name__ == "__main__":
|
|
2091
|
+
main()
|
|
2092
|
+
|