feat: proxy-gui
No files matched your search
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Badged tray icons: every base state with a failed, busy or unknown badge in its bottom-right corner.
|
||||
|
||||
python3 badges.py <icon dir> <out dir>
|
||||
|
||||
proxy-suite-<state>[-symbolic].svg -> proxy-suite-<state>-<badge>[-symbolic].svg, next to copies of the bases.
|
||||
The shield is cut away around the badge, so it reads on any panel color.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
STATES = ("disabled", "zapret", "proxy", "active", "tunnel")
|
||||
CX, CY = 18.5, 18.5
|
||||
CUT, DOT = 5.8, 4.8 # radius of the gap in the shield, and of the badge inside it
|
||||
|
||||
# badge -> (fill, stroke, glyph drawn in the glyph color)
|
||||
GLYPHS = {
|
||||
"failed": (
|
||||
"#D32F2F",
|
||||
"#7F0000",
|
||||
f'<path d="M {CX} {CY - 2.6} L {CX} {CY + 0.4}" stroke-width="1.5" stroke-linecap="round" fill="none"/>'
|
||||
f'<circle cx="{CX}" cy="{CY + 2.4}" r="0.85" stroke="none"/>',
|
||||
),
|
||||
"busy": (
|
||||
"#FFA000",
|
||||
"#8D5A00",
|
||||
"".join(f'<circle cx="{CX + dx}" cy="{CY}" r="0.85" stroke="none"/>' for dx in (-2.2, 0, 2.2)),
|
||||
),
|
||||
"unknown": (
|
||||
"#757575",
|
||||
"#424242",
|
||||
f'<path d="M {CX - 1.6} {CY - 1.2} C {CX - 1.6} {CY - 3.4} {CX + 1.8} {CY - 3.4} {CX + 1.8} {CY - 1.2} '
|
||||
f'C {CX + 1.8} {CY + 0.2} {CX} {CY} {CX} {CY + 1}" stroke-width="1.4" stroke-linecap="round" fill="none"/>'
|
||||
f'<circle cx="{CX}" cy="{CY + 2.7}" r="0.8" stroke="none"/>',
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def inner(svg):
|
||||
return re.search(r"<svg[^>]*>(.*)</svg>", svg, re.S).group(1)
|
||||
|
||||
|
||||
def badged(svg, badge, symbolic):
|
||||
fill, stroke, glyph = GLYPHS[badge]
|
||||
mask = (
|
||||
f'<mask id="cut"><rect width="24" height="24" fill="white"/>'
|
||||
f'<circle cx="{CX}" cy="{CY}" r="{CUT}" fill="black"/></mask>'
|
||||
)
|
||||
if symbolic:
|
||||
# One color: the badge is a disc with its glyph knocked out.
|
||||
mask += (
|
||||
f'<mask id="glyph"><rect width="24" height="24" fill="white"/>'
|
||||
f'<g stroke="black" fill="black">{glyph}</g></mask>'
|
||||
)
|
||||
badge_svg = f'<circle cx="{CX}" cy="{CY}" r="{DOT}" fill="currentColor" mask="url(#glyph)"/>'
|
||||
else:
|
||||
badge_svg = (
|
||||
f'<circle cx="{CX}" cy="{CY}" r="{DOT}" fill="{fill}" stroke="{stroke}" stroke-width="0.6"/>'
|
||||
f'<g stroke="#FFFFFF" fill="#FFFFFF">{glyph}</g>'
|
||||
)
|
||||
return (
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">\n'
|
||||
f" <defs>{mask}</defs>\n"
|
||||
f' <g mask="url(#cut)">{inner(svg)}</g>\n'
|
||||
f" {badge_svg}\n"
|
||||
"</svg>\n"
|
||||
)
|
||||
|
||||
|
||||
def main(src, out):
|
||||
os.makedirs(out, exist_ok=True)
|
||||
for state in STATES:
|
||||
for suffix in ("", "-symbolic"):
|
||||
base = os.path.join(src, f"proxy-suite-{state}{suffix}.svg")
|
||||
shutil.copyfile(base, os.path.join(out, os.path.basename(base)))
|
||||
with open(base) as f:
|
||||
svg = f.read()
|
||||
for badge in GLYPHS:
|
||||
with open(os.path.join(out, f"proxy-suite-{state}-{badge}{suffix}.svg"), "w") as f:
|
||||
f.write(badged(svg, badge, bool(suffix)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(*sys.argv[1:3])
|
||||
@@ -0,0 +1,22 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
|
||||
<!-- Proxy Suite: the tray's shield, with a route through it -->
|
||||
<defs>
|
||||
<linearGradient id="shield" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#66BB6A"/>
|
||||
<stop offset="1" stop-color="#2E7D32"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="rim" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#9C27B0"/>
|
||||
<stop offset="1" stop-color="#4A148C"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M 64 8 L 110 28 L 110 68 C 110 98 64 120 64 120 C 64 120 18 98 18 68 L 18 28 Z"
|
||||
fill="url(#rim)"/>
|
||||
<path d="M 64 17 L 101 33.5 L 101 68 C 101 92 64 110 64 110 C 64 110 27 92 27 68 L 27 33.5 Z"
|
||||
fill="url(#shield)"/>
|
||||
<path d="M 40 80 C 52 80 52 50 64 50 C 76 50 76 64 88 64"
|
||||
stroke="#FFFFFF" stroke-width="7" fill="none" stroke-linecap="round"/>
|
||||
<circle cx="40" cy="80" r="7" fill="#FFFFFF"/>
|
||||
<path d="M 84 54 L 94 64 L 84 74" stroke="#FFFFFF" stroke-width="7" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="currentColor"/>
|
||||
<path d="M 9 13 L 11.5 15.5 L 15.5 9.5"
|
||||
stroke="white" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 354 B |
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Green shield: proxy + zapret both enabled -->
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="#4CAF50" stroke="#2E7D32" stroke-width="0.8"/>
|
||||
<path d="M 9 13 L 11.5 15.5 L 15.5 9.5"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 440 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="currentColor"/>
|
||||
<line x1="9" y1="9.5" x2="15" y2="15.5" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
|
||||
<line x1="15" y1="9.5" x2="9" y2="15.5" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 403 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Red shield: everything disabled -->
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="#F44336" stroke="#B71C1C" stroke-width="0.8"/>
|
||||
<line x1="9" y1="9.5" x2="15" y2="15.5"
|
||||
stroke="#FFFFFF" stroke-width="1.4" stroke-linecap="round"/>
|
||||
<line x1="15" y1="9.5" x2="9" y2="15.5"
|
||||
stroke="#FFFFFF" stroke-width="1.4" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 497 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="currentColor"/>
|
||||
<circle cx="12" cy="12.5" r="2.5" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 252 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Orange shield: only proxy (SOCKS) enabled -->
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="#FF9800" stroke="#E65100" stroke-width="0.8"/>
|
||||
<!-- Dot in center -->
|
||||
<circle cx="12" cy="12.5" r="2.5" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 363 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="currentColor"/>
|
||||
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
|
||||
stroke="white" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 371 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Purple shield: TUN/TProxy active -->
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="#9C27B0" stroke="#4A148C" stroke-width="0.8"/>
|
||||
<!-- Up arrow: traffic routed through tunnel -->
|
||||
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 499 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="currentColor"/>
|
||||
<path d="M 9 9 L 15 9 L 9 15 L 15 15"
|
||||
stroke="white" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 352 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Blue shield: only zapret enabled -->
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="#2196F3" stroke="#0D47A1" stroke-width="0.8"/>
|
||||
<!-- Z letter for Zapret -->
|
||||
<path d="M 9 9 L 15 9 L 9 15 L 15 15"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 460 B |
@@ -46,7 +46,7 @@ HELP = """\
|
||||
Usage: proxy-ctl <group> [verb] [args]
|
||||
A group without a verb shows its status or list.
|
||||
|
||||
status [--tray] services and routing mode
|
||||
status [--json] services and routing mode (--tray: deprecated key=value lines)
|
||||
restart restart active services
|
||||
logs [unit] follow logs (default: every proxy-suite unit)
|
||||
where <domain> how this host is routed right now
|
||||
@@ -303,7 +303,7 @@ COMPLETE = {
|
||||
"help": "usage",
|
||||
}
|
||||
},
|
||||
"status": {"flags": {"--tray": "key=value lines for the tray"}},
|
||||
"status": {"flags": {"--json": "machine-readable state, with the GUI's overall state"}},
|
||||
"logs": {"args": lambda: _names([*ALL_SERVICES, *map(_awg_service, _awg_profiles())]), "repeat": True},
|
||||
"where": {"args": _autoproxy_choices},
|
||||
"proxy": {
|
||||
@@ -469,24 +469,115 @@ def _route_mode_label(mode):
|
||||
return ROUTE_MODE_LABELS.get(mode, "Unknown")
|
||||
|
||||
|
||||
def _status_tray():
|
||||
for key, svc in (
|
||||
("socks", "proxy-suite-socks"),
|
||||
("tproxy", "proxy-suite-tproxy"),
|
||||
("tun", "proxy-suite-tun"),
|
||||
("zapret", "proxy-suite-zapret"),
|
||||
):
|
||||
print(f"{key}_available={_bool(svc_exists(svc))}")
|
||||
print(f"{key}_active={_bool(svc_active(svc))}")
|
||||
def _unit_states(units):
|
||||
"""unit -> ActiveState for the units that exist, in one systemctl call."""
|
||||
if not units:
|
||||
return {}
|
||||
_, out = _run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True)
|
||||
states = {}
|
||||
for unit, block in zip(units, out.strip().split("\n\n")):
|
||||
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
|
||||
if props.get("LoadState") not in (None, "not-found"):
|
||||
states[unit] = props.get("ActiveState", "unknown")
|
||||
return states
|
||||
|
||||
|
||||
SNAPSHOT_UNITS = {
|
||||
"proxy": "proxy-suite-socks",
|
||||
"tproxy": "proxy-suite-tproxy",
|
||||
"tun": "proxy-suite-tun",
|
||||
"zapret": "proxy-suite-zapret",
|
||||
}
|
||||
SUBSCRIPTION_UPDATE = "proxy-suite-subscription-update"
|
||||
BUSY_STATES = ("activating", "deactivating", "reloading")
|
||||
|
||||
|
||||
def _snapshot_units():
|
||||
return [*ALL_SERVICES, SUBSCRIPTION_UPDATE, *map(_awg_service, _awg_profiles())]
|
||||
|
||||
|
||||
def _status_snapshot(states=None):
|
||||
"""What runs, as data: the GUI's tray, `status --json` and `status --tray` all read this.
|
||||
|
||||
states: unit -> ActiveState for the existing units, when the caller already has them.
|
||||
"""
|
||||
if states is None:
|
||||
states = _unit_states(_snapshot_units())
|
||||
profiles = _awg_profiles()
|
||||
active = _active_awg_profiles()
|
||||
print(f"subscription_update_available={_bool(svc_exists('proxy-suite-subscription-update'))}")
|
||||
print(f"route_mode_available={_bool(svc_exists('proxy-suite-socks'))}")
|
||||
print(f"route_mode={_route_mode_current()}")
|
||||
print(f"default_route_mode={_route_mode_default()}")
|
||||
print(f"awg_available={_bool(profiles)}")
|
||||
print(f"awg_active={active[0] if active else ''}")
|
||||
print(f"awg_profiles={','.join(profiles)}")
|
||||
snapshot = {
|
||||
name: {"available": unit in states, "active": states.get(unit) == "active"} for name, unit in SNAPSHOT_UNITS.items()
|
||||
}
|
||||
snapshot["awg"] = {
|
||||
"available": bool(profiles),
|
||||
"profiles": profiles,
|
||||
"active": next((p for p in profiles if states.get(_awg_service(p)) == "active"), ""),
|
||||
}
|
||||
snapshot["route_mode"] = {
|
||||
"available": "proxy-suite-socks" in states,
|
||||
"current": _route_mode_current(),
|
||||
"default": _route_mode_default(),
|
||||
}
|
||||
snapshot["subscription_update"] = {"available": SUBSCRIPTION_UPDATE in states, "state": states.get(SUBSCRIPTION_UPDATE, "")}
|
||||
snapshot["units"] = dict(states)
|
||||
snapshot["failed"] = sorted(u for u, s in states.items() if s == "failed")
|
||||
snapshot["overall"] = _overall_state(snapshot)
|
||||
return snapshot
|
||||
|
||||
|
||||
def _overall_state(snapshot):
|
||||
"""base: the tray icon's color (tunnel > active > proxy > zapret > disabled); badge: failed > busy.
|
||||
|
||||
A snapshot of None is state that could not be read.
|
||||
"""
|
||||
if snapshot is None:
|
||||
return {"base": "disabled", "badge": "unknown", "label": "Status unavailable"}
|
||||
proxy, zapret = snapshot["proxy"]["active"], snapshot["zapret"]["active"]
|
||||
traffic = snapshot["tun"]["active"] or snapshot["tproxy"]["active"] or bool(snapshot["awg"]["active"])
|
||||
if traffic:
|
||||
base = "tunnel"
|
||||
elif proxy and zapret:
|
||||
base = "active"
|
||||
else:
|
||||
base = "proxy" if proxy else "zapret" if zapret else "disabled"
|
||||
if proxy:
|
||||
label = "Proxy" + (" + traffic" if traffic else "") + (" + zapret" if zapret else "")
|
||||
label = "Proxy only" if label == "Proxy" else label
|
||||
elif snapshot["awg"]["active"]:
|
||||
label = "AmneziaWG"
|
||||
else:
|
||||
label = "Zapret only" if zapret else "Inactive"
|
||||
units = snapshot.get("units") or {}
|
||||
if snapshot.get("failed"):
|
||||
badge = "failed"
|
||||
elif any(s in BUSY_STATES for s in units.values()):
|
||||
badge = "busy"
|
||||
else:
|
||||
badge = ""
|
||||
return {"base": base, "badge": badge, "label": label}
|
||||
|
||||
|
||||
def _status_tray():
|
||||
"""Deprecated key=value lines, for scripts written against the old tray."""
|
||||
snapshot = _status_snapshot()
|
||||
for key, name in (("socks", "proxy"), ("tproxy", "tproxy"), ("tun", "tun"), ("zapret", "zapret")):
|
||||
print(f"{key}_available={_bool(snapshot[name]['available'])}")
|
||||
print(f"{key}_active={_bool(snapshot[name]['active'])}")
|
||||
print(f"subscription_update_available={_bool(snapshot['subscription_update']['available'])}")
|
||||
print(f"route_mode_available={_bool(snapshot['route_mode']['available'])}")
|
||||
print(f"route_mode={snapshot['route_mode']['current']}")
|
||||
print(f"default_route_mode={snapshot['route_mode']['default']}")
|
||||
print(f"awg_available={_bool(snapshot['awg']['available'])}")
|
||||
print(f"awg_active={snapshot['awg']['active']}")
|
||||
print(f"awg_profiles={','.join(snapshot['awg']['profiles'])}")
|
||||
|
||||
|
||||
def _status_json():
|
||||
snapshot = _status_snapshot()
|
||||
if snapshot["proxy"]["active"]:
|
||||
snapshot["outbound"] = _status_outbound() or ""
|
||||
snapshot["autoproxy"] = _status_autoproxy()
|
||||
snapshot["zapret"]["learned"] = _status_zapret()
|
||||
print(json.dumps(snapshot, indent=2))
|
||||
|
||||
|
||||
def _status_row(key, value):
|
||||
@@ -546,6 +637,9 @@ def _status_zapret():
|
||||
|
||||
|
||||
def cmd_status(*args):
|
||||
if args[:1] == ("--json",):
|
||||
_status_json()
|
||||
return
|
||||
if args[:1] == ("--tray",):
|
||||
_status_tray()
|
||||
return
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
"""What proxy-tui and proxy-suite-gui show and do, without drawing any of it.
|
||||
|
||||
Reads come from proxy_ctl in-process. Every change runs proxy-ctl itself, so
|
||||
validation, permission errors and systemd triggers stay in one place, and its
|
||||
die() cannot take a front end down.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
import proxy_ctl as ctl
|
||||
|
||||
CTL = "proxy-ctl"
|
||||
|
||||
|
||||
def _die(message, status=1):
|
||||
# Readers run in-process: the message rides the SystemExit, so an empty tab can say why.
|
||||
sys.exit(message)
|
||||
|
||||
|
||||
ctl.die = _die
|
||||
|
||||
_memo = {} # (reader, args) -> result, cleared at the start of every load
|
||||
|
||||
|
||||
def _per_load(fn):
|
||||
def wrapped(*args):
|
||||
key = (fn, args)
|
||||
if key not in _memo:
|
||||
_memo[key] = fn(*args)
|
||||
return _memo[key]
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
# Clash API calls and systemctl spawns that several readers repeat within one load.
|
||||
for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"):
|
||||
setattr(ctl, _name, _per_load(getattr(ctl, _name)))
|
||||
|
||||
|
||||
def new_load():
|
||||
_memo.clear()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Action:
|
||||
key: str
|
||||
label: str
|
||||
argv: Callable # (selected row or None, prompt text, unit states) -> proxy-ctl argv
|
||||
when: Callable = None # row -> applies; None: a tab-wide action that needs no row
|
||||
prompt: str = "" # ask for text first
|
||||
confirm: bool | Callable = False # or row -> ask first
|
||||
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tab:
|
||||
id: str
|
||||
title: str
|
||||
available: Callable # unit states -> bool
|
||||
columns: list # (row field, heading)
|
||||
rows: Callable # unit states -> [row dict with a unique "key"]
|
||||
summary: Callable = None # () -> text above the table, read with every load
|
||||
actions: list = field(default_factory=list)
|
||||
|
||||
|
||||
def ROW(_):
|
||||
return True
|
||||
|
||||
|
||||
# --- readers ------------------------------------------------------------------
|
||||
|
||||
|
||||
def unit_states(units):
|
||||
return ctl._unit_states(units)
|
||||
|
||||
|
||||
def all_units():
|
||||
# The subscription update is read for the status line and the tray; it is no service to toggle.
|
||||
return ctl._snapshot_units()
|
||||
|
||||
|
||||
def _lines(name):
|
||||
try:
|
||||
return [line for line in ctl.lines(ctl.read_text(ctl._zapret_auto_file(name))) if line]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
TOGGLES = {
|
||||
"proxy-suite-socks": ["proxy"],
|
||||
"proxy-suite-tun": ["proxy", "tun"],
|
||||
"proxy-suite-tproxy": ["proxy", "tproxy"],
|
||||
"proxy-suite-ssh-proxy": ["ssh"],
|
||||
"proxy-suite-warp-tunnel": ["warp"],
|
||||
"proxy-suite-tg-ws-proxy": ["tg"],
|
||||
"proxy-suite-zapret": ["zapret"],
|
||||
}
|
||||
AWG_PREFIX = ctl._awg_service("")
|
||||
ZAPRET_LISTS = (
|
||||
("learned", "zapret-hosts-auto.txt"),
|
||||
("pinned", "zapret-hosts-user.txt"),
|
||||
("excluded", "zapret-hosts-user-exclude.txt"),
|
||||
)
|
||||
|
||||
|
||||
def toggle_argv(row, *_):
|
||||
verb = "off" if row["state"] == "active" else "on"
|
||||
if row["unit"].startswith(AWG_PREFIX):
|
||||
return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)]
|
||||
return [*TOGGLES[row["unit"]], verb]
|
||||
|
||||
|
||||
def service_rows(states):
|
||||
return [
|
||||
{"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s}
|
||||
for u, s in states.items()
|
||||
if u != ctl.SUBSCRIPTION_UPDATE
|
||||
]
|
||||
|
||||
|
||||
def route_rows(_):
|
||||
current = ctl._route_mode_current()
|
||||
return [
|
||||
{"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)}
|
||||
for m in ("default", *ctl.ROUTE_MODES)
|
||||
]
|
||||
|
||||
|
||||
def outbound_rows(_):
|
||||
inventory = ctl._outbound_inventory()
|
||||
pinned = ctl._s(inventory.get("pinned") or "")
|
||||
sources = inventory.get("sources") or {}
|
||||
current = ctl._outbound_current()
|
||||
reputation = ctl._reputation_by_tag()
|
||||
runtime = set(ctl._runtime_tags("outbound"))
|
||||
return [
|
||||
{
|
||||
"key": t,
|
||||
"mark": "★" if t == pinned else "▸" if t == current else "",
|
||||
"tag": t,
|
||||
"reputation": reputation.get(t, "-"),
|
||||
"source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"),
|
||||
"runtime": t in runtime,
|
||||
}
|
||||
for t in ctl._outbound_tags()
|
||||
]
|
||||
|
||||
|
||||
def outbound_summary():
|
||||
inventory = ctl._outbound_inventory()
|
||||
if not inventory:
|
||||
return "No outbounds yet - is proxy-suite-socks running?"
|
||||
return (
|
||||
f"Selection: {ctl._s(inventory.get('selection') or 'first')} "
|
||||
f"Pinned: {ctl._s(inventory.get('pinned') or '(none)')} "
|
||||
f"Current: {ctl._outbound_current() or '-'}"
|
||||
)
|
||||
|
||||
|
||||
def subscription_rows(_):
|
||||
rows = []
|
||||
for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
|
||||
for t in tags:
|
||||
cache = ctl._subscription_cache(t)
|
||||
cached = os.path.isfile(cache)
|
||||
count = ctl._subscription_proxy_count_text(cache) if cached else "-"
|
||||
updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-"
|
||||
rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source})
|
||||
return rows
|
||||
|
||||
|
||||
def autoproxy_rows(_):
|
||||
state = ctl._autoproxy_state(ctl._autoproxy_dir())
|
||||
domains = state.get("domains") or {}
|
||||
rows = [
|
||||
{"key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}"}
|
||||
for d, v in sorted(domains.items())
|
||||
]
|
||||
backlog = sorted((state.get("backlog") or {}).items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0))
|
||||
rows += [
|
||||
{"key": h, "domain": h, "kind": "queued", "detail": f"{ctl._s((v or {}).get('hits'))} hits"}
|
||||
for h, v in backlog
|
||||
if h not in domains
|
||||
]
|
||||
return rows
|
||||
|
||||
|
||||
def zapret_rows(_):
|
||||
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||
return []
|
||||
rows = {}
|
||||
for kind, name in ZAPRET_LISTS:
|
||||
for host in _lines(name):
|
||||
rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind})
|
||||
return list(rows.values())
|
||||
|
||||
|
||||
def zapret_summary():
|
||||
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||
return 'Learned hostlists need zapret.engine = "zapret2".'
|
||||
text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS)
|
||||
if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1":
|
||||
text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2])
|
||||
return text
|
||||
|
||||
|
||||
_cutoff = {} # ts mtime -> status text: a probe rewrites ts
|
||||
|
||||
|
||||
def _cutoff_status():
|
||||
try:
|
||||
mtime = os.path.getmtime(os.path.join(ctl._zapret_state_dir(), "cutoff", "ts"))
|
||||
except OSError:
|
||||
mtime = None
|
||||
if mtime not in _cutoff:
|
||||
_cutoff.clear()
|
||||
_cutoff[mtime] = _capture(["zapret", "cutoff", "status"])
|
||||
return _cutoff[mtime]
|
||||
|
||||
|
||||
def inbound_rows(_):
|
||||
return [
|
||||
{"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
|
||||
for x in ctl._inbound_links()
|
||||
]
|
||||
|
||||
|
||||
def app_rows(_):
|
||||
return [
|
||||
{"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))}
|
||||
for p in ctl._per_app_profiles()
|
||||
]
|
||||
|
||||
|
||||
def snapshot(states):
|
||||
"""proxy-ctl's status snapshot for these unit states; None when it cannot be read."""
|
||||
return _safe(ctl._status_snapshot, states)
|
||||
|
||||
|
||||
def status_items(states):
|
||||
"""(label, value, style) for the status line: style is "", "ok", "warn" or "bad"."""
|
||||
items = []
|
||||
overall = ctl._overall_state(snapshot(states) if states else None)
|
||||
items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], "")))
|
||||
if "proxy-suite-socks" in states:
|
||||
default = " (default)" if ctl._route_mode_current() == "default" else ""
|
||||
items.append(("mode ", ctl._route_mode_effective() + default, ""))
|
||||
items.append(("outbound ", ctl._status_outbound() or "-", ""))
|
||||
if autoproxy := ctl._status_autoproxy():
|
||||
items.append(("autoProxy ", autoproxy, ""))
|
||||
if zapret := ctl._status_zapret():
|
||||
items.append(("zapret ", f"{zapret} learned", ""))
|
||||
failed = sum(1 for s in states.values() if s == "failed")
|
||||
if failed:
|
||||
items.append(("", f"{failed} failed", "bad"))
|
||||
return items
|
||||
|
||||
|
||||
def filter_rows(rows, columns, text):
|
||||
"""Every word must match: column:value in that column (by heading or field), anything else in any column."""
|
||||
names = {k.lower(): name for name, heading in columns for k in (name, heading) if k}
|
||||
|
||||
def matches(row, term):
|
||||
column, sep, value = term.lower().partition(":")
|
||||
if sep and column in names:
|
||||
return value in str(row.get(names[column], "")).lower()
|
||||
return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns)
|
||||
|
||||
return [r for r in rows if all(matches(r, t) for t in text.split())]
|
||||
|
||||
|
||||
def _natural(value):
|
||||
# "port 443" before "port 2053": digit runs compare as numbers.
|
||||
return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", str(value or "").lower())]
|
||||
|
||||
|
||||
def _link(row, *extra):
|
||||
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra]
|
||||
|
||||
|
||||
def _kind(*kinds):
|
||||
return lambda row: row["kind"] in kinds
|
||||
|
||||
|
||||
def _socks(states):
|
||||
return "proxy-suite-socks" in states
|
||||
|
||||
|
||||
def _enabled(name):
|
||||
return lambda _: ctl.env(name) == "1"
|
||||
|
||||
|
||||
def _zapret_toggle(row, _, states):
|
||||
return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"]
|
||||
|
||||
|
||||
TABS = [
|
||||
Tab(
|
||||
"services",
|
||||
"Services",
|
||||
lambda _: True,
|
||||
[("name", "Unit"), ("state", "State")],
|
||||
service_rows,
|
||||
actions=[
|
||||
Action(
|
||||
"space",
|
||||
"start / stop",
|
||||
toggle_argv,
|
||||
when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX),
|
||||
# proxy off takes tun and tproxy down with it.
|
||||
confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active",
|
||||
),
|
||||
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
|
||||
Action(
|
||||
"ctrl+r",
|
||||
"restart it",
|
||||
lambda r, *_: ["awg", "restart", r["unit"].removeprefix(AWG_PREFIX)],
|
||||
when=lambda r: r["unit"].startswith(AWG_PREFIX) and r["state"] == "active",
|
||||
),
|
||||
Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"routing",
|
||||
"Routing",
|
||||
_socks,
|
||||
[("active", ""), ("key", "Mode"), ("mode", "Meaning")],
|
||||
route_rows,
|
||||
summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.",
|
||||
actions=[Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"])],
|
||||
),
|
||||
Tab(
|
||||
"outbounds",
|
||||
"Outbounds",
|
||||
_socks,
|
||||
[("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source")],
|
||||
outbound_rows,
|
||||
summary=outbound_summary,
|
||||
actions=[
|
||||
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"),
|
||||
Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
|
||||
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
|
||||
Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"subs",
|
||||
"Subs",
|
||||
_socks,
|
||||
[("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")],
|
||||
subscription_rows,
|
||||
summary=lambda: f"proxy-suite-subscription-update: {ctl.svc_state('proxy-suite-subscription-update') or 'unknown'}",
|
||||
actions=[
|
||||
Action("u", "refetch all", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"),
|
||||
Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"),
|
||||
Action("n", "add a runtime subscription…", lambda r, t, _: ["proxy", "subs", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"autoproxy",
|
||||
"autoProxy",
|
||||
_enabled("AUTOPROXY_ENABLED"),
|
||||
[("domain", "Domain"), ("kind", "State"), ("detail", "")],
|
||||
autoproxy_rows,
|
||||
summary=ctl._status_autoproxy,
|
||||
actions=[
|
||||
Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, mode="dialog"),
|
||||
Action("e", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"),
|
||||
Action("p", "probe it through every exit", lambda r, *_: ["proxy", "auto", "probe", r["domain"], "--keep-going"], when=ROW, mode="dialog"),
|
||||
Action("P", "probe a domain…", lambda r, t, _: ["proxy", "auto", "probe", t], prompt="<domain>[/path]", mode="dialog"),
|
||||
Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
|
||||
Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"zapret",
|
||||
"zapret",
|
||||
lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
|
||||
[("host", "Host"), ("kind", "List")],
|
||||
zapret_rows,
|
||||
summary=zapret_summary,
|
||||
actions=[
|
||||
Action("f", "forget it (may be learned again)", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")),
|
||||
Action("x", "exclude it (never learn)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")),
|
||||
Action("u", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")),
|
||||
Action("i", "include it (may be learned again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")),
|
||||
Action("a", "pin a host (always bypass)…", lambda r, t, _: ["zapret", "auto", "add", t], prompt="<domain>"),
|
||||
Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True),
|
||||
Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"),
|
||||
Action("z", "start / stop zapret", _zapret_toggle),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"inbounds",
|
||||
"Inbounds",
|
||||
_enabled("INBOUNDS_ENABLED"),
|
||||
[("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")],
|
||||
inbound_rows,
|
||||
summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}",
|
||||
actions=[
|
||||
Action("l", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"),
|
||||
Action("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"),
|
||||
Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"),
|
||||
Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"),
|
||||
Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"),
|
||||
Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="copy"),
|
||||
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"apps",
|
||||
"Apps",
|
||||
_enabled("PER_APP_ROUTING_ENABLED"),
|
||||
[("profile", "Profile"), ("route", "Route")],
|
||||
app_rows,
|
||||
actions=[
|
||||
Action("x", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="pause"),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog")
|
||||
|
||||
|
||||
def available_tabs(states):
|
||||
return [t.id for t in TABS if _safe(t.available, states, fallback=False)]
|
||||
|
||||
|
||||
def applicable(tab, row):
|
||||
return [a for a in tab.actions if a.when is None or (row is not None and a.when(row))]
|
||||
|
||||
|
||||
def load_tab(tab, states):
|
||||
"""(rows, summary) for a tab: a failed read empties the rows and says why in the summary."""
|
||||
summary = (_safe(tab.summary, fallback="") or "") if tab.summary else ""
|
||||
try:
|
||||
rows = tab.rows(states)
|
||||
except (Exception, SystemExit) as e:
|
||||
return [], f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "")
|
||||
if not rows:
|
||||
hints = " ".join(f"{a.key}: {short(a.label)}" for a in tab.actions if a.prompt)
|
||||
summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "")
|
||||
return rows, summary
|
||||
|
||||
|
||||
def short(label):
|
||||
return label.split(" (")[0].removesuffix("…")
|
||||
|
||||
|
||||
def _capture(argv):
|
||||
try:
|
||||
p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
||||
except OSError as e:
|
||||
return f"cannot run proxy-ctl: {e}"
|
||||
return p.stdout + p.stderr
|
||||
|
||||
|
||||
def _safe(fn, *args, fallback=None):
|
||||
try:
|
||||
return fn(*args)
|
||||
except (Exception, SystemExit):
|
||||
return fallback # Unreadable state: shown empty; a tab's own rows say why in its summary.
|
||||
|
||||
|
||||
def _read_states():
|
||||
return _safe(unit_states, _safe(all_units, fallback=list(ctl.ALL_SERVICES)), fallback={})
|
||||
|
||||
|
||||
# --- tray menu ----------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class MenuItem:
|
||||
id: str
|
||||
label: str = ""
|
||||
kind: str = "normal" # normal, check, radio, separator, submenu
|
||||
checked: bool = False
|
||||
enabled: bool = True
|
||||
argv: list = None # proxy-ctl argv to run when clicked
|
||||
app: str = "" # or an app action: open, quit
|
||||
confirm: bool = False
|
||||
children: list = field(default_factory=list)
|
||||
|
||||
|
||||
def _sep(n):
|
||||
return MenuItem(f"sep-{n}", kind="separator")
|
||||
|
||||
|
||||
def tray_menu(snap, outbounds=None):
|
||||
"""The tray's menu for a status snapshot (None: unreadable). outbounds: (tags, pinned) or None."""
|
||||
overall = ctl._overall_state(snap)
|
||||
items = [MenuItem("status", overall["label"] + (f" — {len(snap['failed'])} failed" if snap and snap["failed"] else ""), enabled=False)]
|
||||
items.append(MenuItem("open", "Open Proxy Suite", app="open"))
|
||||
if snap is None:
|
||||
return items + [_sep(0), MenuItem("quit", "Quit", app="quit")]
|
||||
items.append(_sep(1))
|
||||
if snap["proxy"]["available"]:
|
||||
active = snap["proxy"]["active"]
|
||||
items.append(MenuItem("proxy", "Proxy", kind="check", checked=active, argv=["proxy", "off" if active else "on"], confirm=active))
|
||||
if snap["route_mode"]["available"]:
|
||||
current = snap["route_mode"]["current"]
|
||||
items.append(
|
||||
MenuItem(
|
||||
"mode",
|
||||
f"Routing: {ctl._route_mode_label(current)}",
|
||||
kind="submenu",
|
||||
children=[
|
||||
MenuItem(f"mode-{m}", ctl._route_mode_label(m), kind="radio", checked=m == current, argv=["proxy", "mode", m])
|
||||
for m in ("default", *ctl.ROUTE_MODES)
|
||||
],
|
||||
)
|
||||
)
|
||||
if outbounds and outbounds[0]:
|
||||
tags, pinned = outbounds
|
||||
items.append(
|
||||
MenuItem(
|
||||
"pin",
|
||||
f"Outbound: {pinned or 'auto'}",
|
||||
kind="submenu",
|
||||
children=[
|
||||
MenuItem("pin-auto", "Automatic (unpin)", kind="radio", checked=not pinned, argv=["proxy", "unpin"]),
|
||||
_sep(2),
|
||||
*(MenuItem(f"pin-{t}", t, kind="radio", checked=t == pinned, argv=["proxy", "pin", t]) for t in tags),
|
||||
],
|
||||
)
|
||||
)
|
||||
traffic = []
|
||||
for name, label in (("tun", "TUN mode"), ("tproxy", "TProxy mode")):
|
||||
if snap[name]["available"]:
|
||||
active = snap[name]["active"]
|
||||
traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"]))
|
||||
if snap["awg"]["available"]:
|
||||
current = snap["awg"]["active"]
|
||||
traffic.append(
|
||||
MenuItem(
|
||||
"awg",
|
||||
f"AmneziaWG: {current or 'off'}",
|
||||
kind="submenu",
|
||||
children=[
|
||||
MenuItem("awg-off", "Off", kind="radio", checked=not current, argv=["awg", "off"]),
|
||||
*(MenuItem(f"awg-{p}", p, kind="radio", checked=p == current, argv=["awg", "on", p]) for p in snap["awg"]["profiles"]),
|
||||
],
|
||||
)
|
||||
)
|
||||
if traffic:
|
||||
items += [_sep(3), *traffic]
|
||||
if snap["zapret"]["available"]:
|
||||
active = snap["zapret"]["active"]
|
||||
items += [_sep(4), MenuItem("zapret", "zapret (DPI bypass)", kind="check", checked=active, argv=["zapret", "off" if active else "on"])]
|
||||
items.append(_sep(5))
|
||||
if snap["subscription_update"]["available"]:
|
||||
busy = snap["subscription_update"]["state"] in ctl.BUSY_STATES
|
||||
items.append(MenuItem("subs", "Updating subscriptions…" if busy else "Update subscriptions", enabled=not busy, argv=["proxy", "subs", "update"]))
|
||||
items.append(MenuItem("restart", "Restart active services", argv=["restart"]))
|
||||
items += [_sep(6), MenuItem("quit", "Quit", app="quit")]
|
||||
return items
|
||||
|
||||
|
||||
def tray_outbounds(snap):
|
||||
"""(tags, pinned) for the tray's pin submenu, when the proxy runs."""
|
||||
if not snap or not snap["proxy"]["active"]:
|
||||
return None
|
||||
inventory = _safe(ctl._outbound_inventory, fallback={}) or {}
|
||||
return [ctl._s(t) for t in inventory.get("tags") or []], ctl._s(inventory.get("pinned") or "")
|
||||
|
||||
|
||||
def icon_name(overall):
|
||||
return "proxy-suite-" + overall["base"] + (f"-{overall['badge']}" if overall["badge"] else "")
|
||||
@@ -0,0 +1,327 @@
|
||||
"""A tray icon over D-Bus: org.kde.StatusNotifierItem with a com.canonical.dbusmenu menu.
|
||||
|
||||
Hosts that show these: waybar, KDE Plasma, most wlroots bars, GNOME with the AppIndicator extension.
|
||||
The menu is proxy_model's MenuItem tree; this module only speaks the protocols.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from gi.repository import Gio, GLib
|
||||
|
||||
WATCHER = "org.kde.StatusNotifierWatcher"
|
||||
ITEM_PATH = "/StatusNotifierItem"
|
||||
MENU_PATH = "/MenuBar"
|
||||
|
||||
ITEM_XML = """
|
||||
<node>
|
||||
<interface name="org.kde.StatusNotifierItem">
|
||||
<property name="Category" type="s" access="read"/>
|
||||
<property name="Id" type="s" access="read"/>
|
||||
<property name="Title" type="s" access="read"/>
|
||||
<property name="Status" type="s" access="read"/>
|
||||
<property name="WindowId" type="i" access="read"/>
|
||||
<property name="IconName" type="s" access="read"/>
|
||||
<property name="IconThemePath" type="s" access="read"/>
|
||||
<property name="IconPixmap" type="a(iiay)" access="read"/>
|
||||
<property name="OverlayIconName" type="s" access="read"/>
|
||||
<property name="OverlayIconPixmap" type="a(iiay)" access="read"/>
|
||||
<property name="AttentionIconName" type="s" access="read"/>
|
||||
<property name="AttentionIconPixmap" type="a(iiay)" access="read"/>
|
||||
<property name="AttentionMovieName" type="s" access="read"/>
|
||||
<property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
|
||||
<property name="ItemIsMenu" type="b" access="read"/>
|
||||
<property name="Menu" type="o" access="read"/>
|
||||
<method name="ContextMenu"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
|
||||
<method name="Activate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
|
||||
<method name="SecondaryActivate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
|
||||
<method name="Scroll"><arg name="delta" type="i" direction="in"/><arg name="orientation" type="s" direction="in"/></method>
|
||||
<signal name="NewTitle"/>
|
||||
<signal name="NewIcon"/>
|
||||
<signal name="NewAttentionIcon"/>
|
||||
<signal name="NewOverlayIcon"/>
|
||||
<signal name="NewToolTip"/>
|
||||
<signal name="NewStatus"><arg name="status" type="s"/></signal>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
MENU_XML = """
|
||||
<node>
|
||||
<interface name="com.canonical.dbusmenu">
|
||||
<property name="Version" type="u" access="read"/>
|
||||
<property name="TextDirection" type="s" access="read"/>
|
||||
<property name="Status" type="s" access="read"/>
|
||||
<property name="IconThemePath" type="as" access="read"/>
|
||||
<method name="GetLayout">
|
||||
<arg name="parentId" type="i" direction="in"/>
|
||||
<arg name="recursionDepth" type="i" direction="in"/>
|
||||
<arg name="propertyNames" type="as" direction="in"/>
|
||||
<arg name="revision" type="u" direction="out"/>
|
||||
<arg name="layout" type="(ia{sv}av)" direction="out"/>
|
||||
</method>
|
||||
<method name="GetGroupProperties">
|
||||
<arg name="ids" type="ai" direction="in"/>
|
||||
<arg name="propertyNames" type="as" direction="in"/>
|
||||
<arg name="properties" type="a(ia{sv})" direction="out"/>
|
||||
</method>
|
||||
<method name="GetProperty">
|
||||
<arg name="id" type="i" direction="in"/>
|
||||
<arg name="name" type="s" direction="in"/>
|
||||
<arg name="value" type="v" direction="out"/>
|
||||
</method>
|
||||
<method name="Event">
|
||||
<arg name="id" type="i" direction="in"/>
|
||||
<arg name="eventId" type="s" direction="in"/>
|
||||
<arg name="data" type="v" direction="in"/>
|
||||
<arg name="timestamp" type="u" direction="in"/>
|
||||
</method>
|
||||
<method name="EventGroup">
|
||||
<arg name="events" type="a(isvu)" direction="in"/>
|
||||
<arg name="idErrors" type="ai" direction="out"/>
|
||||
</method>
|
||||
<method name="AboutToShow">
|
||||
<arg name="id" type="i" direction="in"/>
|
||||
<arg name="needUpdate" type="b" direction="out"/>
|
||||
</method>
|
||||
<method name="AboutToShowGroup">
|
||||
<arg name="ids" type="ai" direction="in"/>
|
||||
<arg name="updatesNeeded" type="ai" direction="out"/>
|
||||
<arg name="idErrors" type="ai" direction="out"/>
|
||||
</method>
|
||||
<signal name="ItemsPropertiesUpdated">
|
||||
<arg name="updatedProps" type="a(ia{sv})"/>
|
||||
<arg name="removedProps" type="a(ias)"/>
|
||||
</signal>
|
||||
<signal name="LayoutUpdated">
|
||||
<arg name="revision" type="u"/>
|
||||
<arg name="parent" type="i"/>
|
||||
</signal>
|
||||
<signal name="ItemActivationRequested">
|
||||
<arg name="id" type="i"/>
|
||||
<arg name="timestamp" type="u"/>
|
||||
</signal>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
|
||||
def item_properties(item):
|
||||
"""dbusmenu properties of one MenuItem, as plain values."""
|
||||
if item.kind == "separator":
|
||||
return {"type": "separator"}
|
||||
props = {"label": item.label.replace("_", "__"), "enabled": item.enabled}
|
||||
if item.kind in ("check", "radio"):
|
||||
props["toggle-type"] = "checkmark" if item.kind == "check" else "radio"
|
||||
props["toggle-state"] = 1 if item.checked else 0
|
||||
if item.kind == "submenu":
|
||||
props["children-display"] = "submenu"
|
||||
return props
|
||||
|
||||
|
||||
def _variant(value):
|
||||
kind = {bool: "b", int: "i", str: "s"}[type(value)]
|
||||
return GLib.Variant(kind, value)
|
||||
|
||||
|
||||
class Menu:
|
||||
"""The item ids a host sees stay put across updates: string ids map to the same numbers."""
|
||||
|
||||
def __init__(self):
|
||||
self.numbers = {} # MenuItem id -> dbusmenu id; 0 is the root
|
||||
self.items = {} # dbusmenu id -> MenuItem
|
||||
self.children = {0: []}
|
||||
self.revision = 1
|
||||
self.shape = None
|
||||
|
||||
def number(self, item_id):
|
||||
return self.numbers.setdefault(item_id, len(self.numbers) + 1)
|
||||
|
||||
def update(self, tree):
|
||||
"""Takes a new tree; True when anything a host shows changed."""
|
||||
items, children = {}, {0: []}
|
||||
|
||||
def add(parent, nodes):
|
||||
for node in nodes:
|
||||
n = self.number(node.id)
|
||||
items[n] = node
|
||||
children[parent].append(n)
|
||||
children[n] = []
|
||||
add(n, node.children)
|
||||
|
||||
add(0, tree)
|
||||
shape = (children, {n: item_properties(i) for n, i in items.items()})
|
||||
self.items, self.children = items, children
|
||||
if shape == self.shape:
|
||||
return False
|
||||
self.shape = shape
|
||||
self.revision += 1
|
||||
return True
|
||||
|
||||
def properties(self, n, names=()):
|
||||
props = item_properties(self.items[n]) if n in self.items else {"children-display": "submenu"}
|
||||
return {k: _variant(v) for k, v in props.items() if not names or k in names}
|
||||
|
||||
def layout(self, n, depth, names=()):
|
||||
kids = [] if depth == 0 else [
|
||||
GLib.Variant("(ia{sv}av)", self.layout(c, depth - 1, names)) for c in self.children.get(n, [])
|
||||
]
|
||||
return (n, self.properties(n, names), kids)
|
||||
|
||||
|
||||
class StatusNotifierItem:
|
||||
"""Exports the icon and its menu on connection, and keeps it registered while a watcher runs.
|
||||
|
||||
on_activate(): a click on the icon. on_menu(item): a menu item was clicked.
|
||||
on_available(bool): whether a host shows the icon.
|
||||
"""
|
||||
|
||||
def __init__(self, connection, app_id, title, icon_theme_path, on_activate, on_menu, on_available=None):
|
||||
self.connection = connection
|
||||
self.app_id, self.title, self.icon_theme_path = app_id, title, icon_theme_path
|
||||
self.on_activate, self.on_menu, self.on_available = on_activate, on_menu, on_available or (lambda _: None)
|
||||
self.icon, self.tooltip, self.status = "proxy-suite-disabled-unknown", "", "Active"
|
||||
self.menu = Menu()
|
||||
self.available = False
|
||||
self.name = f"org.kde.StatusNotifierItem-{os.getpid()}-1"
|
||||
# register_object_with_closures2 is GLib 2.84's; register_object is the older name for the same.
|
||||
register = getattr(connection, "register_object_with_closures2", None) or connection.register_object
|
||||
self.registrations = [
|
||||
register(ITEM_PATH, Gio.DBusNodeInfo.new_for_xml(ITEM_XML).interfaces[0], self._item_call, self._item_get, None),
|
||||
register(MENU_PATH, Gio.DBusNodeInfo.new_for_xml(MENU_XML).interfaces[0], self._menu_call, self._menu_get, None),
|
||||
]
|
||||
self.owner = Gio.bus_own_name_on_connection(connection, self.name, Gio.BusNameOwnerFlags.NONE, None, None)
|
||||
self.watch = Gio.bus_watch_name_on_connection(
|
||||
connection, WATCHER, Gio.BusNameWatcherFlags.NONE, self._watcher_appeared, self._watcher_vanished
|
||||
)
|
||||
|
||||
def close(self):
|
||||
Gio.bus_unwatch_name(self.watch)
|
||||
Gio.bus_unown_name(self.owner)
|
||||
for r in self.registrations:
|
||||
self.connection.unregister_object(r)
|
||||
|
||||
# --- what the app changes -----------------------------------------------------
|
||||
|
||||
def update(self, icon, tooltip, tree, attention=False):
|
||||
if icon != self.icon:
|
||||
self.icon = icon
|
||||
self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewIcon")
|
||||
if tooltip != self.tooltip:
|
||||
self.tooltip = tooltip
|
||||
self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewToolTip")
|
||||
status = "NeedsAttention" if attention else "Active"
|
||||
if status != self.status:
|
||||
self.status = status
|
||||
self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewStatus", GLib.Variant("(s)", (status,)))
|
||||
if self.menu.update(tree):
|
||||
self._emit(MENU_PATH, "com.canonical.dbusmenu", "LayoutUpdated", GLib.Variant("(ui)", (self.menu.revision, 0)))
|
||||
|
||||
def _emit(self, path, interface, signal, args=None):
|
||||
try:
|
||||
self.connection.emit_signal(None, path, interface, signal, args)
|
||||
except GLib.Error:
|
||||
pass # the bus went away: nothing shows the icon anyway
|
||||
|
||||
# --- registration ---------------------------------------------------------------
|
||||
|
||||
def _watcher_appeared(self, connection, name, owner):
|
||||
# A bar that restarts brings a new watcher: register again each time.
|
||||
connection.call(
|
||||
WATCHER, "/StatusNotifierWatcher", WATCHER, "RegisterStatusNotifierItem",
|
||||
GLib.Variant("(s)", (self.name,)), None, Gio.DBusCallFlags.NONE, -1, None, self._registered,
|
||||
)
|
||||
|
||||
def _registered(self, connection, result):
|
||||
try:
|
||||
connection.call_finish(result)
|
||||
except GLib.Error:
|
||||
self._set_available(False)
|
||||
else:
|
||||
self._set_available(True)
|
||||
|
||||
def _watcher_vanished(self, connection, name):
|
||||
self._set_available(False)
|
||||
|
||||
def _set_available(self, available):
|
||||
if available != self.available:
|
||||
self.available = available
|
||||
self.on_available(available)
|
||||
|
||||
# --- org.kde.StatusNotifierItem ---------------------------------------------------
|
||||
|
||||
def _item_get(self, connection, sender, path, interface, prop):
|
||||
values = {
|
||||
"Category": ("s", "SystemServices"),
|
||||
"Id": ("s", self.app_id),
|
||||
"Title": ("s", self.title),
|
||||
"Status": ("s", self.status),
|
||||
"WindowId": ("i", 0),
|
||||
"IconName": ("s", self.icon),
|
||||
"IconThemePath": ("s", self.icon_theme_path),
|
||||
"IconPixmap": ("a(iiay)", []),
|
||||
"OverlayIconName": ("s", ""),
|
||||
"OverlayIconPixmap": ("a(iiay)", []),
|
||||
"AttentionIconName": ("s", self.icon),
|
||||
"AttentionIconPixmap": ("a(iiay)", []),
|
||||
"AttentionMovieName": ("s", ""),
|
||||
"ToolTip": ("(sa(iiay)ss)", (self.icon, [], self.title, self.tooltip)),
|
||||
"ItemIsMenu": ("b", False),
|
||||
"Menu": ("o", MENU_PATH),
|
||||
}
|
||||
return GLib.Variant(*values[prop]) if prop in values else None
|
||||
|
||||
def _item_call(self, connection, sender, path, interface, method, params, invocation):
|
||||
if method in ("Activate", "SecondaryActivate"):
|
||||
GLib.idle_add(self.on_activate)
|
||||
invocation.return_value(None)
|
||||
|
||||
# --- com.canonical.dbusmenu ---------------------------------------------------------
|
||||
|
||||
def _menu_get(self, connection, sender, path, interface, prop):
|
||||
values = {
|
||||
"Version": ("u", 3),
|
||||
"TextDirection": ("s", "ltr"),
|
||||
"Status": ("s", "normal"),
|
||||
"IconThemePath": ("as", [self.icon_theme_path] if self.icon_theme_path else []),
|
||||
}
|
||||
return GLib.Variant(*values[prop]) if prop in values else None
|
||||
|
||||
def _menu_call(self, connection, sender, path, interface, method, params, invocation):
|
||||
args = params.unpack()
|
||||
menu = self.menu
|
||||
if method == "GetLayout":
|
||||
parent, depth, names = args
|
||||
invocation.return_value(GLib.Variant("(u(ia{sv}av))", (menu.revision, menu.layout(parent, depth, names))))
|
||||
elif method == "GetGroupProperties":
|
||||
ids, names = args
|
||||
found = [(n, menu.properties(n, names)) for n in ids if n in menu.items] if ids else [
|
||||
(n, menu.properties(n, names)) for n in menu.items
|
||||
]
|
||||
invocation.return_value(GLib.Variant("(a(ia{sv}))", (found,)))
|
||||
elif method == "GetProperty":
|
||||
n, name = args
|
||||
value = menu.properties(n).get(name)
|
||||
if value is None:
|
||||
invocation.return_dbus_error("com.canonical.dbusmenu.Error", f"no property {name} on {n}")
|
||||
else:
|
||||
invocation.return_value(GLib.Variant("(v)", (value,)))
|
||||
elif method == "Event":
|
||||
self._event(*args[:2])
|
||||
invocation.return_value(None)
|
||||
elif method == "EventGroup":
|
||||
errors = [n for n, event, _, _ in args[0] if not self._event(n, event)]
|
||||
invocation.return_value(GLib.Variant("(ai)", (errors,)))
|
||||
elif method == "AboutToShow":
|
||||
invocation.return_value(GLib.Variant("(b)", (False,)))
|
||||
elif method == "AboutToShowGroup":
|
||||
invocation.return_value(GLib.Variant("(aiai)", ([], [n for n in args[0] if n and n not in menu.items])))
|
||||
else:
|
||||
invocation.return_dbus_error("org.freedesktop.DBus.Error.UnknownMethod", method)
|
||||
|
||||
def _event(self, n, event):
|
||||
item = self.menu.items.get(n)
|
||||
if item is None:
|
||||
return False
|
||||
if event == "clicked" and item.enabled and item.kind not in ("separator", "submenu"):
|
||||
GLib.idle_add(self.on_menu, item)
|
||||
return True
|
||||
@@ -1,19 +1,11 @@
|
||||
"""proxy-tui: an interactive front end to proxy-ctl.
|
||||
|
||||
Reads come from proxy_ctl in-process. Every change runs proxy-ctl itself, so
|
||||
validation, permission errors and systemd triggers stay in one place, and its
|
||||
die() cannot take the TUI down.
|
||||
What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
from rich.text import Text
|
||||
from textual import events, work
|
||||
@@ -28,248 +20,17 @@ from textual.theme import Theme
|
||||
from textual.widgets import DataTable, Input, Label, OptionList, RichLog, Static, TabbedContent, TabPane
|
||||
from textual.widgets.option_list import Option
|
||||
|
||||
import proxy_ctl as ctl
|
||||
import proxy_model as model
|
||||
from proxy_model import CTL, TABS, ctl, filter_rows, _natural, _read_states, _safe
|
||||
|
||||
CTL = "proxy-ctl"
|
||||
REFRESH_SECONDS = 3
|
||||
|
||||
|
||||
def _die(message, status=1):
|
||||
# Readers run in-process: the message rides the SystemExit, so an empty tab can say why.
|
||||
sys.exit(message)
|
||||
|
||||
|
||||
ctl.die = _die
|
||||
|
||||
_memo = {} # (reader, args) -> result, cleared at the start of every load
|
||||
|
||||
|
||||
def _per_load(fn):
|
||||
def wrapped(*args):
|
||||
key = (fn, args)
|
||||
if key not in _memo:
|
||||
_memo[key] = fn(*args)
|
||||
return _memo[key]
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
# Clash API calls and systemctl spawns that several readers repeat within one load.
|
||||
for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"):
|
||||
setattr(ctl, _name, _per_load(getattr(ctl, _name)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Action:
|
||||
key: str
|
||||
label: str
|
||||
argv: Callable # (selected row or None, prompt text, unit states) -> proxy-ctl argv
|
||||
when: Callable = None # row -> applies; None: a tab-wide action that needs no row
|
||||
prompt: str = "" # ask for text first
|
||||
confirm: bool | Callable = False # or row -> ask first
|
||||
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tab:
|
||||
id: str
|
||||
title: str
|
||||
available: Callable # unit states -> bool
|
||||
columns: list # (row field, heading)
|
||||
rows: Callable # unit states -> [row dict with a unique "key"]
|
||||
summary: Callable = None # () -> text above the table, read with every load
|
||||
actions: list = field(default_factory=list)
|
||||
|
||||
|
||||
def ROW(_):
|
||||
return True
|
||||
|
||||
|
||||
# --- readers ------------------------------------------------------------------
|
||||
|
||||
|
||||
def unit_states(units):
|
||||
"""unit -> ActiveState for the units that exist, in one systemctl call."""
|
||||
if not units:
|
||||
return {}
|
||||
_, out = ctl._run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True)
|
||||
states = {}
|
||||
for unit, block in zip(units, out.strip().split("\n\n")):
|
||||
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
|
||||
if props.get("LoadState") not in (None, "not-found"):
|
||||
states[unit] = props.get("ActiveState", "unknown")
|
||||
return states
|
||||
|
||||
|
||||
def all_units():
|
||||
return [*ctl.ALL_SERVICES, *map(ctl._awg_service, ctl._awg_profiles())]
|
||||
|
||||
|
||||
def _lines(name):
|
||||
try:
|
||||
return [line for line in ctl.lines(ctl.read_text(ctl._zapret_auto_file(name))) if line]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
TOGGLES = {
|
||||
"proxy-suite-socks": ["proxy"],
|
||||
"proxy-suite-tun": ["proxy", "tun"],
|
||||
"proxy-suite-tproxy": ["proxy", "tproxy"],
|
||||
"proxy-suite-ssh-proxy": ["ssh"],
|
||||
"proxy-suite-warp-tunnel": ["warp"],
|
||||
"proxy-suite-tg-ws-proxy": ["tg"],
|
||||
"proxy-suite-zapret": ["zapret"],
|
||||
}
|
||||
AWG_PREFIX = ctl._awg_service("")
|
||||
ZAPRET_LISTS = (
|
||||
("learned", "zapret-hosts-auto.txt"),
|
||||
("pinned", "zapret-hosts-user.txt"),
|
||||
("excluded", "zapret-hosts-user-exclude.txt"),
|
||||
)
|
||||
|
||||
|
||||
def toggle_argv(row, *_):
|
||||
verb = "off" if row["state"] == "active" else "on"
|
||||
if row["unit"].startswith(AWG_PREFIX):
|
||||
return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)]
|
||||
return [*TOGGLES[row["unit"]], verb]
|
||||
|
||||
|
||||
def service_rows(states):
|
||||
return [{"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s} for u, s in states.items()]
|
||||
|
||||
|
||||
def route_rows(_):
|
||||
current = ctl._route_mode_current()
|
||||
return [
|
||||
{"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)}
|
||||
for m in ("default", *ctl.ROUTE_MODES)
|
||||
]
|
||||
|
||||
|
||||
def outbound_rows(_):
|
||||
inventory = ctl._outbound_inventory()
|
||||
pinned = ctl._s(inventory.get("pinned") or "")
|
||||
sources = inventory.get("sources") or {}
|
||||
current = ctl._outbound_current()
|
||||
reputation = ctl._reputation_by_tag()
|
||||
runtime = set(ctl._runtime_tags("outbound"))
|
||||
return [
|
||||
{
|
||||
"key": t,
|
||||
"mark": "★" if t == pinned else "▸" if t == current else "",
|
||||
"tag": t,
|
||||
"reputation": reputation.get(t, "-"),
|
||||
"source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"),
|
||||
"runtime": t in runtime,
|
||||
}
|
||||
for t in ctl._outbound_tags()
|
||||
]
|
||||
|
||||
|
||||
def outbound_summary():
|
||||
inventory = ctl._outbound_inventory()
|
||||
if not inventory:
|
||||
return "No outbounds yet - is proxy-suite-socks running?"
|
||||
return (
|
||||
f"Selection: {ctl._s(inventory.get('selection') or 'first')} "
|
||||
f"Pinned: {ctl._s(inventory.get('pinned') or '(none)')} "
|
||||
f"Current: {ctl._outbound_current() or '-'}"
|
||||
)
|
||||
|
||||
|
||||
def subscription_rows(_):
|
||||
rows = []
|
||||
for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
|
||||
for t in tags:
|
||||
cache = ctl._subscription_cache(t)
|
||||
cached = os.path.isfile(cache)
|
||||
count = ctl._subscription_proxy_count_text(cache) if cached else "-"
|
||||
updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-"
|
||||
rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source})
|
||||
return rows
|
||||
|
||||
|
||||
def autoproxy_rows(_):
|
||||
state = ctl._autoproxy_state(ctl._autoproxy_dir())
|
||||
domains = state.get("domains") or {}
|
||||
rows = [
|
||||
{"key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}"}
|
||||
for d, v in sorted(domains.items())
|
||||
]
|
||||
backlog = sorted((state.get("backlog") or {}).items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0))
|
||||
rows += [
|
||||
{"key": h, "domain": h, "kind": "queued", "detail": f"{ctl._s((v or {}).get('hits'))} hits"}
|
||||
for h, v in backlog
|
||||
if h not in domains
|
||||
]
|
||||
return rows
|
||||
|
||||
|
||||
def zapret_rows(_):
|
||||
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||
return []
|
||||
rows = {}
|
||||
for kind, name in ZAPRET_LISTS:
|
||||
for host in _lines(name):
|
||||
rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind})
|
||||
return list(rows.values())
|
||||
|
||||
|
||||
def zapret_summary():
|
||||
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||
return 'Learned hostlists need zapret.engine = "zapret2".'
|
||||
text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS)
|
||||
if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1":
|
||||
text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2])
|
||||
return text
|
||||
|
||||
|
||||
_cutoff = {} # ts mtime -> status text: a probe rewrites ts
|
||||
|
||||
|
||||
def _cutoff_status():
|
||||
try:
|
||||
mtime = os.path.getmtime(os.path.join(ctl._zapret_state_dir(), "cutoff", "ts"))
|
||||
except OSError:
|
||||
mtime = None
|
||||
if mtime not in _cutoff:
|
||||
_cutoff.clear()
|
||||
_cutoff[mtime] = _capture(["zapret", "cutoff", "status"])
|
||||
return _cutoff[mtime]
|
||||
|
||||
|
||||
def inbound_rows(_):
|
||||
return [
|
||||
{"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
|
||||
for x in ctl._inbound_links()
|
||||
]
|
||||
|
||||
|
||||
def app_rows(_):
|
||||
return [
|
||||
{"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))}
|
||||
for p in ctl._per_app_profiles()
|
||||
]
|
||||
STATUS_STYLES = {"ok": "b ansi_green", "warn": "b ansi_yellow", "bad": "b ansi_red", "": "b"}
|
||||
|
||||
|
||||
def status_text(states):
|
||||
parts = []
|
||||
if "proxy-suite-socks" in states:
|
||||
default = " (default)" if ctl._route_mode_current() == "default" else ""
|
||||
parts.append(("mode ", ctl._route_mode_effective() + default))
|
||||
parts.append(("outbound ", ctl._status_outbound() or "-"))
|
||||
if autoproxy := ctl._status_autoproxy():
|
||||
parts.append(("autoProxy ", autoproxy))
|
||||
if zapret := ctl._status_zapret():
|
||||
parts.append(("zapret ", f"{zapret} learned"))
|
||||
failed = sum(1 for s in states.values() if s == "failed")
|
||||
return [
|
||||
"[b ansi_cyan]proxy-suite[/]",
|
||||
*(f"[dim]{label}[/][b]{escape(value)}[/]" for label, value in parts),
|
||||
*([f"[b ansi_red]{failed} failed[/]"] if failed else []),
|
||||
]
|
||||
return ["[b ansi_cyan]proxy-suite[/]", *(
|
||||
f"[dim]{escape(label)}[/][{STATUS_STYLES[style]}]{escape(value)}[/]" for label, value, style in model.status_items(states)
|
||||
)]
|
||||
|
||||
|
||||
def pack(items, width, gap=" "):
|
||||
@@ -283,172 +44,6 @@ def pack(items, width, gap=" "):
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def filter_rows(rows, columns, text):
|
||||
"""Every word must match: column:value in that column (by heading or field), anything else in any column."""
|
||||
names = {k.lower(): name for name, heading in columns for k in (name, heading) if k}
|
||||
|
||||
def matches(row, term):
|
||||
column, sep, value = term.lower().partition(":")
|
||||
if sep and column in names:
|
||||
return value in str(row.get(names[column], "")).lower()
|
||||
return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns)
|
||||
|
||||
return [r for r in rows if all(matches(r, t) for t in text.split())]
|
||||
|
||||
|
||||
def _natural(value):
|
||||
# "port 443" before "port 2053": digit runs compare as numbers.
|
||||
return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", str(value or "").lower())]
|
||||
|
||||
|
||||
def _link(row, *extra):
|
||||
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra]
|
||||
|
||||
|
||||
def _kind(*kinds):
|
||||
return lambda row: row["kind"] in kinds
|
||||
|
||||
|
||||
def _socks(states):
|
||||
return "proxy-suite-socks" in states
|
||||
|
||||
|
||||
def _enabled(name):
|
||||
return lambda _: ctl.env(name) == "1"
|
||||
|
||||
|
||||
def _zapret_toggle(row, _, states):
|
||||
return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"]
|
||||
|
||||
|
||||
TABS = [
|
||||
Tab(
|
||||
"services",
|
||||
"Services",
|
||||
lambda _: True,
|
||||
[("name", "Unit"), ("state", "State")],
|
||||
service_rows,
|
||||
actions=[
|
||||
Action(
|
||||
"space",
|
||||
"start / stop",
|
||||
toggle_argv,
|
||||
when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX),
|
||||
# proxy off takes tun and tproxy down with it.
|
||||
confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active",
|
||||
),
|
||||
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
|
||||
Action(
|
||||
"ctrl+r",
|
||||
"restart it",
|
||||
lambda r, *_: ["awg", "restart", r["unit"].removeprefix(AWG_PREFIX)],
|
||||
when=lambda r: r["unit"].startswith(AWG_PREFIX) and r["state"] == "active",
|
||||
),
|
||||
Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"routing",
|
||||
"Routing",
|
||||
_socks,
|
||||
[("active", ""), ("key", "Mode"), ("mode", "Meaning")],
|
||||
route_rows,
|
||||
summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.",
|
||||
actions=[Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"])],
|
||||
),
|
||||
Tab(
|
||||
"outbounds",
|
||||
"Outbounds",
|
||||
_socks,
|
||||
[("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source")],
|
||||
outbound_rows,
|
||||
summary=outbound_summary,
|
||||
actions=[
|
||||
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"),
|
||||
Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
|
||||
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
|
||||
Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"subs",
|
||||
"Subs",
|
||||
_socks,
|
||||
[("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")],
|
||||
subscription_rows,
|
||||
summary=lambda: f"proxy-suite-subscription-update: {ctl.svc_state('proxy-suite-subscription-update') or 'unknown'}",
|
||||
actions=[
|
||||
Action("u", "refetch all", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"),
|
||||
Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"),
|
||||
Action("n", "add a runtime subscription…", lambda r, t, _: ["proxy", "subs", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"autoproxy",
|
||||
"autoProxy",
|
||||
_enabled("AUTOPROXY_ENABLED"),
|
||||
[("domain", "Domain"), ("kind", "State"), ("detail", "")],
|
||||
autoproxy_rows,
|
||||
summary=ctl._status_autoproxy,
|
||||
actions=[
|
||||
Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, mode="dialog"),
|
||||
Action("e", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"),
|
||||
Action("p", "probe it through every exit", lambda r, *_: ["proxy", "auto", "probe", r["domain"], "--keep-going"], when=ROW, mode="dialog"),
|
||||
Action("P", "probe a domain…", lambda r, t, _: ["proxy", "auto", "probe", t], prompt="<domain>[/path]", mode="dialog"),
|
||||
Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
|
||||
Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"zapret",
|
||||
"zapret",
|
||||
lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
|
||||
[("host", "Host"), ("kind", "List")],
|
||||
zapret_rows,
|
||||
summary=zapret_summary,
|
||||
actions=[
|
||||
Action("f", "forget it (may be learned again)", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")),
|
||||
Action("x", "exclude it (never learn)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")),
|
||||
Action("u", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")),
|
||||
Action("i", "include it (may be learned again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")),
|
||||
Action("a", "pin a host (always bypass)…", lambda r, t, _: ["zapret", "auto", "add", t], prompt="<domain>"),
|
||||
Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True),
|
||||
Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"),
|
||||
Action("z", "start / stop zapret", _zapret_toggle),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"inbounds",
|
||||
"Inbounds",
|
||||
_enabled("INBOUNDS_ENABLED"),
|
||||
[("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")],
|
||||
inbound_rows,
|
||||
summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}",
|
||||
actions=[
|
||||
Action("l", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"),
|
||||
Action("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"),
|
||||
Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"),
|
||||
Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"),
|
||||
Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"),
|
||||
Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="copy"),
|
||||
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"apps",
|
||||
"Apps",
|
||||
_enabled("PER_APP_ROUTING_ENABLED"),
|
||||
[("profile", "Profile"), ("route", "Route")],
|
||||
app_rows,
|
||||
actions=[
|
||||
Action("x", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="pause"),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
GLOBAL_KEYS = [
|
||||
("enter", "actions for the selected row (or click it)"),
|
||||
("← → ⇥", "switch tab; 1-8 jump to one"),
|
||||
@@ -556,25 +151,6 @@ def _update(widget, content):
|
||||
widget.update(content)
|
||||
|
||||
|
||||
def _capture(argv):
|
||||
try:
|
||||
p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
||||
except OSError as e:
|
||||
return f"cannot run proxy-ctl: {e}"
|
||||
return p.stdout + p.stderr
|
||||
|
||||
|
||||
def _safe(fn, *args, fallback=None):
|
||||
try:
|
||||
return fn(*args)
|
||||
except (Exception, SystemExit):
|
||||
return fallback # Unreadable state: shown empty; a tab's own rows say why in its summary.
|
||||
|
||||
|
||||
def _read_states():
|
||||
return _safe(unit_states, _safe(all_units, fallback=list(ctl.ALL_SERVICES)), fallback={})
|
||||
|
||||
|
||||
# --- dialogs ------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -692,10 +268,6 @@ class Output(Dialog):
|
||||
# --- main screen --------------------------------------------------------------
|
||||
|
||||
|
||||
def _short(label):
|
||||
return label.split(" (")[0].removesuffix("…")
|
||||
|
||||
|
||||
class Table(DataTable):
|
||||
def _on_mouse_move(self, event):
|
||||
event.prevent_default() # Textual would run DataTable's own handler again after this one.
|
||||
@@ -802,7 +374,7 @@ class ProxyTui(App):
|
||||
super().__init__()
|
||||
self.states = _read_states()
|
||||
self.tabs = {t.id: t for t in TABS}
|
||||
self.shown = self.available_tabs(self.states)
|
||||
self.shown = model.available_tabs(self.states)
|
||||
self.rows = {} # tab id -> {row key: row}
|
||||
self.filters = {} # tab id -> text
|
||||
self.sorts = {} # tab id -> (column, descending)
|
||||
@@ -819,9 +391,6 @@ class ProxyTui(App):
|
||||
# Textual drops focus when the terminal loses it, and the table's cursor and footer change with it.
|
||||
event.prevent_default()
|
||||
|
||||
def available_tabs(self, states):
|
||||
return [t.id for t in TABS if _safe(t.available, states, fallback=False)]
|
||||
|
||||
def get_default_screen(self):
|
||||
return MainScreen(self.tabs)
|
||||
|
||||
@@ -874,7 +443,7 @@ class ProxyTui(App):
|
||||
_update(self.main.query_one(f"#{tab_id}-detail", Static), detail(tab, row, actions))
|
||||
width, height = self.size
|
||||
# The detail panel lists the row's actions when it shows; the key line need not repeat them.
|
||||
shown = [] if width >= WIDE or height >= TALL else [(f"act({tab.actions.index(a)})", a.key, _short(a.label)) for a in actions]
|
||||
shown = [] if width >= WIDE or height >= TALL else [(f"act({tab.actions.index(a)})", a.key, model.short(a.label)) for a in actions]
|
||||
# The key keeps its color outside the link: a link's own color would cover it.
|
||||
items = [f"[b ansi_cyan]{escape(k)}[/] [@click=app.{action}]{escape(label)}[/]" for action, k, label in shown + KEY_LINE]
|
||||
_update(self.main.query_one("#keys", Static), pack(items, width - 2))
|
||||
@@ -886,21 +455,11 @@ class ProxyTui(App):
|
||||
|
||||
@work(thread=True, exclusive=True, group="load")
|
||||
def load(self, tab_id):
|
||||
_memo.clear()
|
||||
tab = self.tabs[tab_id]
|
||||
model.new_load()
|
||||
states = _read_states()
|
||||
visible = self.available_tabs(states)
|
||||
visible = model.available_tabs(states)
|
||||
status = _safe(status_text, states, fallback=["status unavailable"])
|
||||
summary = (_safe(tab.summary, fallback="") or "") if tab.summary else ""
|
||||
try:
|
||||
rows = tab.rows(states)
|
||||
except (Exception, SystemExit) as e:
|
||||
rows = []
|
||||
summary = f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "")
|
||||
else:
|
||||
if not rows:
|
||||
hints = " ".join(f"{a.key}: {_short(a.label)}" for a in tab.actions if a.prompt)
|
||||
summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "")
|
||||
rows, summary = model.load_tab(self.tabs[tab_id], states)
|
||||
self.call_from_thread(self.fill, tab_id, states, visible, status, rows, summary)
|
||||
|
||||
def show_status(self):
|
||||
@@ -969,7 +528,7 @@ class ProxyTui(App):
|
||||
# --- acting ---------------------------------------------------------------
|
||||
|
||||
def applicable(self, row):
|
||||
return [a for a in self.tabs[self.active_tab()].actions if a.when is None or (row is not None and a.when(row))]
|
||||
return model.applicable(self.tabs[self.active_tab()], row)
|
||||
|
||||
def check_action(self, action, parameters):
|
||||
# A row action that does not apply: its key does nothing.
|
||||
@@ -994,7 +553,7 @@ class ProxyTui(App):
|
||||
self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row())
|
||||
|
||||
def action_where(self):
|
||||
self.perform(Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog"), None)
|
||||
self.perform(model.WHERE, None)
|
||||
|
||||
def on_data_table_header_selected(self, event):
|
||||
tab_id, name = self.active_tab(), event.column_key.value
|
||||
|
||||
@@ -605,5 +605,48 @@ class WhereTest(EnvTest):
|
||||
self.assertEqual(ctl._where_inbounds(config, "example.org", "")[0], "proxy")
|
||||
|
||||
|
||||
class StatusSnapshotTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.patch("_awg_profiles", lambda: ["home", "work"])
|
||||
self.patch("_route_mode_current", lambda: "default")
|
||||
self.patch("_route_mode_default", lambda: "blacklist")
|
||||
|
||||
def overall(self, **states):
|
||||
units = {f"proxy-suite-{k.replace('_', '-')}": v for k, v in states.items()}
|
||||
return ctl._status_snapshot(units)["overall"]
|
||||
|
||||
def test_base_priority(self):
|
||||
self.assertEqual(self.overall(), {"base": "disabled", "badge": "", "label": "Inactive"})
|
||||
self.assertEqual(self.overall(zapret="active")["base"], "zapret")
|
||||
self.assertEqual(self.overall(socks="active")["label"], "Proxy only")
|
||||
self.assertEqual(self.overall(socks="active", zapret="active")["base"], "active")
|
||||
both = self.overall(socks="active", zapret="active", tun="active")
|
||||
self.assertEqual((both["base"], both["label"]), ("tunnel", "Proxy + traffic + zapret"))
|
||||
self.assertEqual(self.overall(awg_work="active"), {"base": "tunnel", "badge": "", "label": "AmneziaWG"})
|
||||
|
||||
def test_badges(self):
|
||||
self.assertEqual(self.overall(socks="active", tun="failed")["badge"], "failed")
|
||||
self.assertEqual(self.overall(socks="activating", tun="failed")["badge"], "failed")
|
||||
self.assertEqual(self.overall(socks="active", subscription_update="activating")["badge"], "busy")
|
||||
self.assertEqual(ctl._overall_state(None)["badge"], "unknown")
|
||||
|
||||
def test_outputs(self):
|
||||
units = {"proxy-suite-socks": "active", "proxy-suite-awg-work": "active", "proxy-suite-tun": "inactive"}
|
||||
self.patch("_unit_states", lambda names: {u: s for u, s in units.items() if u in names})
|
||||
self.patch("_status_outbound", lambda: "b (pinned)")
|
||||
self.patch("_status_autoproxy", lambda: "")
|
||||
self.patch("_status_zapret", lambda: "")
|
||||
tray = dict(line.split("=", 1) for line in ok(ctl.cmd_status, "--tray").splitlines())
|
||||
self.assertEqual(
|
||||
(tray["socks_active"], tray["tun_available"], tray["tproxy_available"], tray["awg_active"], tray["awg_profiles"]),
|
||||
("true", "true", "false", "work", "home,work"),
|
||||
)
|
||||
data = json.loads(ok(ctl.cmd_status, "--json"))
|
||||
self.assertEqual(data["overall"]["base"], "tunnel")
|
||||
self.assertEqual(data["outbound"], "b (pinned)")
|
||||
self.assertEqual(data["route_mode"], {"available": True, "current": "default", "default": "blacklist"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""proxy_gui and proxy_sni without a display: they import, the tray's D-Bus data is well formed,
|
||||
key names become GTK accelerators, and every icon the tray can ask for is drawn."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import proxy_ctl as ctl
|
||||
import proxy_gui as gui
|
||||
import proxy_model as model
|
||||
import proxy_sni as sni
|
||||
from gi.repository import Gio, GLib
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons"))
|
||||
import badges # noqa: E402
|
||||
|
||||
|
||||
class GuiTest(unittest.TestCase):
|
||||
def test_interfaces_parse(self):
|
||||
item = Gio.DBusNodeInfo.new_for_xml(sni.ITEM_XML).interfaces[0]
|
||||
menu = Gio.DBusNodeInfo.new_for_xml(sni.MENU_XML).interfaces[0]
|
||||
self.assertEqual(item.name, "org.kde.StatusNotifierItem")
|
||||
self.assertEqual(menu.name, "com.canonical.dbusmenu")
|
||||
self.assertIsNotNone(menu.lookup_method("GetLayout"))
|
||||
|
||||
def test_menu_layout(self):
|
||||
tree = [
|
||||
model.MenuItem("status", "Proxy_only", enabled=False),
|
||||
model.MenuItem("proxy", "Proxy", kind="check", checked=True, argv=["proxy", "off"]),
|
||||
model.MenuItem(
|
||||
"mode", "Routing", kind="submenu",
|
||||
children=[model.MenuItem("mode-all", "All", kind="radio", checked=False, argv=["proxy", "mode", "all-proxy"])],
|
||||
),
|
||||
]
|
||||
menu = sni.Menu()
|
||||
self.assertTrue(menu.update(tree))
|
||||
revision = menu.revision
|
||||
self.assertFalse(menu.update(tree)) # same shape: hosts keep their copy
|
||||
self.assertEqual(menu.revision, revision)
|
||||
|
||||
layout = GLib.Variant("(u(ia{sv}av))", (menu.revision, menu.layout(0, -1, [])))
|
||||
_, (root, _, children) = layout.unpack()
|
||||
self.assertEqual(root, 0)
|
||||
labels = [child[1]["label"] for child in children]
|
||||
self.assertEqual(labels, ["Proxy__only", "Proxy", "Routing"]) # "_" would be a mnemonic
|
||||
self.assertEqual(children[1][1]["toggle-state"], 1)
|
||||
self.assertEqual(children[2][2][0][1]["toggle-type"], "radio")
|
||||
|
||||
# Ids stay put when an item goes away and comes back.
|
||||
proxy_id = menu.numbers["proxy"]
|
||||
menu.update(tree[:1])
|
||||
menu.update(tree)
|
||||
self.assertEqual(menu.numbers["proxy"], proxy_id)
|
||||
|
||||
def test_accelerators(self):
|
||||
self.assertEqual(gui.accelerator("space"), "space")
|
||||
self.assertEqual(gui.accelerator("R"), "<Shift>r")
|
||||
self.assertEqual(gui.accelerator("ctrl+r"), "<Control>r")
|
||||
self.assertEqual(gui.display_key("ctrl+space"), "Ctrl+Space")
|
||||
for tab in model.TABS:
|
||||
for action in tab.actions:
|
||||
if action.key:
|
||||
self.assertTrue(gui.accelerator(action.key))
|
||||
|
||||
def test_action_looks(self):
|
||||
for tab in model.TABS:
|
||||
for action in tab.actions:
|
||||
self.assertTrue(gui.action_icon(action).endswith("-symbolic"))
|
||||
self.assertFalse(gui.is_destructive(model.Action("R", "restart everything running", lambda *_: [], confirm=True)))
|
||||
self.assertTrue(gui.is_destructive(model.Action("d", "remove it", lambda *_: [], confirm=True)))
|
||||
self.assertTrue(gui.is_destructive(model.Action("C", "forget all learned hosts", lambda *_: [], confirm=True)))
|
||||
self.assertTrue(gui.is_badge("state", "active"))
|
||||
self.assertTrue(gui.is_badge("status", "ok"))
|
||||
self.assertFalse(gui.is_badge("mark", "★"))
|
||||
|
||||
def test_ansi(self):
|
||||
self.assertEqual(
|
||||
gui.ansi_segments("\x1b[1;31mfailed\x1b[0m ok\x1b[K"),
|
||||
[("failed", ("bold", "red")), (" ok", ())],
|
||||
)
|
||||
|
||||
def test_every_tray_icon_is_drawn(self):
|
||||
here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
badges.main(here, out)
|
||||
drawn = set(os.listdir(out))
|
||||
for base in badges.STATES:
|
||||
for badge in ("", *badges.GLYPHS):
|
||||
name = model.icon_name({"base": base, "badge": badge, "label": ""})
|
||||
self.assertIn(f"{name}.svg", drawn)
|
||||
self.assertIn(f"{name}-symbolic.svg", drawn)
|
||||
self.assertIn(f"{model.icon_name(ctl._overall_state(None))}.svg", drawn)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""proxy_model without a front end: the status line and the tray menu turn state into the right proxy-ctl argv."""
|
||||
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import proxy_ctl as ctl
|
||||
import proxy_model as model
|
||||
|
||||
|
||||
def walk(items):
|
||||
for item in items:
|
||||
yield item
|
||||
yield from walk(item.children)
|
||||
|
||||
|
||||
class ModelTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
for name, value in {
|
||||
"_awg_profiles": lambda: ["home"],
|
||||
"_route_mode_current": lambda: "default",
|
||||
"_route_mode_default": lambda: "whitelist",
|
||||
"_route_mode_effective": lambda: "whitelist",
|
||||
"_status_outbound": lambda: "b (pinned)",
|
||||
"_status_autoproxy": lambda: "",
|
||||
"_status_zapret": lambda: "3",
|
||||
"_outbound_inventory": lambda: {"tags": ["a", "b"], "pinned": "b"},
|
||||
}.items():
|
||||
patcher = mock.patch.object(ctl, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def menu(self, states):
|
||||
snap = model.snapshot(states)
|
||||
return {i.id: i for i in walk(model.tray_menu(snap, model.tray_outbounds(snap)))}
|
||||
|
||||
def test_status_items(self):
|
||||
states = {"proxy-suite-socks": "active", "proxy-suite-zapret": "failed"}
|
||||
items = model.status_items(states)
|
||||
self.assertEqual(items[0], ("", "Proxy only", "bad"))
|
||||
self.assertIn(("mode ", "whitelist (default)", ""), items)
|
||||
self.assertIn(("zapret ", "3 learned", ""), items)
|
||||
self.assertEqual(items[-1], ("", "1 failed", "bad"))
|
||||
self.assertEqual(model.status_items({})[0], ("", "Status unavailable", "bad"))
|
||||
|
||||
def test_services_skip_the_subscription_update(self):
|
||||
rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"})
|
||||
self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"])
|
||||
|
||||
def test_tray_menu(self):
|
||||
states = {
|
||||
"proxy-suite-socks": "active",
|
||||
"proxy-suite-tun": "inactive",
|
||||
"proxy-suite-zapret": "inactive",
|
||||
ctl.SUBSCRIPTION_UPDATE: "activating",
|
||||
ctl._awg_service("home"): "active",
|
||||
}
|
||||
items = self.menu(states)
|
||||
self.assertEqual(items["status"].label, "Proxy + traffic")
|
||||
self.assertEqual((items["proxy"].checked, items["proxy"].argv, items["proxy"].confirm), (True, ["proxy", "off"], True))
|
||||
self.assertEqual(items["tun"].argv, ["proxy", "tun", "on"])
|
||||
self.assertNotIn("tproxy", items) # not installed
|
||||
self.assertTrue(items["mode-default"].checked)
|
||||
self.assertEqual(items["mode-blacklist"].argv, ["proxy", "mode", "blacklist"])
|
||||
self.assertEqual(items["pin"].label, "Outbound: b")
|
||||
self.assertTrue(items["pin-b"].checked)
|
||||
self.assertEqual(items["pin-a"].argv, ["proxy", "pin", "a"])
|
||||
self.assertEqual(items["pin-auto"].argv, ["proxy", "unpin"])
|
||||
self.assertTrue(items["awg-home"].checked)
|
||||
self.assertEqual(items["awg-off"].argv, ["awg", "off"])
|
||||
self.assertEqual(items["zapret"].argv, ["zapret", "on"])
|
||||
self.assertFalse(items["subs"].enabled) # an update already runs
|
||||
self.assertEqual(items["quit"].app, "quit")
|
||||
|
||||
def test_tray_menu_without_proxy(self):
|
||||
items = self.menu({"proxy-suite-zapret": "active"})
|
||||
self.assertEqual(items["status"].label, "Zapret only")
|
||||
for absent in ("proxy", "mode", "pin", "subs"):
|
||||
self.assertNotIn(absent, items)
|
||||
self.assertEqual(model.icon_name(ctl._overall_state(model.snapshot({"proxy-suite-zapret": "active"}))), "proxy-suite-zapret")
|
||||
|
||||
def test_tray_menu_unreadable(self):
|
||||
self.assertEqual([i.id for i in model.tray_menu(None)], ["status", "open", "sep-0", "quit"])
|
||||
self.assertEqual(model.icon_name(ctl._overall_state(None)), "proxy-suite-disabled-unknown")
|
||||
|
||||
def test_load_tab(self):
|
||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||
with mock.patch.object(ctl, "_outbound_current", lambda: "a"), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []):
|
||||
rows, summary = model.load_tab(tab, {})
|
||||
self.assertEqual([(r["tag"], r["mark"]) for r in rows], [("a", "▸"), ("b", "★")])
|
||||
self.assertIn("Pinned: b", summary)
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "T", "n"])
|
||||
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
|
||||
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -7,6 +7,7 @@ import unittest
|
||||
from unittest import mock
|
||||
|
||||
import proxy_ctl as ctl
|
||||
import proxy_model as model
|
||||
import proxy_tui as tui
|
||||
|
||||
|
||||
@@ -21,15 +22,15 @@ class TuiTest(unittest.TestCase):
|
||||
self.capture, self.awg, self.current = "", [], mock.Mock(return_value="")
|
||||
self.env = env = {"ZAPRET_AUTO_ENABLED": "1"}
|
||||
for target, name, value in [
|
||||
(tui, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}),
|
||||
(tui, "_capture", lambda argv: self.capture),
|
||||
(tui, "_lines", lambda name: self.zapret[name]),
|
||||
(model, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}),
|
||||
(model, "_capture", lambda argv: self.capture),
|
||||
(model, "_lines", lambda name: self.zapret[name]),
|
||||
(ctl, "env", lambda name, default="": env.get(name, default)),
|
||||
(ctl, "_awg_profiles", lambda: self.awg),
|
||||
(ctl, "_route_mode_current", lambda: "default"),
|
||||
(ctl, "_route_mode_effective", lambda: "whitelist"),
|
||||
(ctl, "_outbound_inventory", lambda: {"tags": ["a", "b"], "pinned": "b", "sources": {"a": "config"}}),
|
||||
(ctl, "_outbound_current", tui._per_load(self.current)),
|
||||
(ctl, "_outbound_current", model._per_load(self.current)),
|
||||
(ctl, "_reputation_by_tag", lambda: {}),
|
||||
(ctl, "_runtime_tags", lambda kind: []),
|
||||
(ctl, "_sub_tags", lambda: []),
|
||||
@@ -56,7 +57,7 @@ class TuiTest(unittest.TestCase):
|
||||
_subscription_cache=lambda tag: cache.name,
|
||||
_subscription_proxy_count_text=lambda path: "3",
|
||||
):
|
||||
self.assertEqual(tui.subscription_rows({})[0]["updated"], "0m ago")
|
||||
self.assertEqual(model.subscription_rows({})[0]["updated"], "0m ago")
|
||||
|
||||
def test_filter_sort_pack(self):
|
||||
rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}]
|
||||
@@ -128,12 +129,12 @@ class TuiTest(unittest.TestCase):
|
||||
|
||||
# An active AmneziaWG profile restarts on its own; a failed unit shows in the status bar.
|
||||
self.awg = ["p"]
|
||||
self.units[tui.AWG_PREFIX + "p"] = "active"
|
||||
self.units[model.AWG_PREFIX + "p"] = "active"
|
||||
self.units["proxy-suite-ssh-proxy"] = "failed"
|
||||
app.action_reload()
|
||||
await self.settle(app, pilot)
|
||||
self.assertIn("1 failed", tui.pack(tui.status_text(app.states), 100))
|
||||
app.table().move_cursor(row=list(app.rows["services"]).index(tui.AWG_PREFIX + "p"))
|
||||
app.table().move_cursor(row=list(app.rows["services"]).index(model.AWG_PREFIX + "p"))
|
||||
await pilot.press("ctrl+r")
|
||||
self.assertEqual(self.ran.pop(), ["awg", "restart", "p"])
|
||||
app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun"))
|
||||
|
||||