fix: proxy tools improvements
This commit is contained in:
10 files changed
+295
-24
No files matched your search
@@ -140,6 +140,9 @@ Secrets and changes need root, or the userControl group.
|
|||||||
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
|
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
|
||||||
chained through another outbound with --detour; the tag first,
|
chained through another outbound with --detour; the tag first,
|
||||||
or left out to name it after the link
|
or left out to name it after the link
|
||||||
|
proxy outbounds chain <tag> <through-tag> [new tag]
|
||||||
|
add a copy of an existing outbound that dials through
|
||||||
|
another one; the original keeps dialing the way it did
|
||||||
proxy outbounds rm <tag> remove a runtime outbound
|
proxy outbounds rm <tag> remove a runtime outbound
|
||||||
proxy outbounds disable|enable <tag> keep an outbound out of automatic use (selection, autoProxy, pins),
|
proxy outbounds disable|enable <tag> keep an outbound out of automatic use (selection, autoProxy, pins),
|
||||||
or let it back in; declared ones too
|
or let it back in; declared ones too
|
||||||
|
|||||||
@@ -378,6 +378,8 @@ in
|
|||||||
has --download proxy outbounds test own-vps --ping
|
has --download proxy outbounds test own-vps --ping
|
||||||
has own-vps proxy auto probe example.com --via
|
has own-vps proxy auto probe example.com --via
|
||||||
has community-de proxy outbounds add hop https://example.com --detour
|
has community-de proxy outbounds add hop https://example.com --detour
|
||||||
|
# chain takes the outbound to copy, then the hop it dials through.
|
||||||
|
has community-de proxy outbounds chain own-vps
|
||||||
has outbound inbounds stats --by
|
has outbound inbounds stats --by
|
||||||
# Unreadable state loses the values, not the flags.
|
# Unreadable state loses the values, not the flags.
|
||||||
has --qr inbounds sub
|
has --qr inbounds sub
|
||||||
|
|||||||
@@ -62,6 +62,9 @@ Secrets and changes need root, or the userControl group.
|
|||||||
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
|
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
|
||||||
chained through another outbound with --detour; the tag first,
|
chained through another outbound with --detour; the tag first,
|
||||||
or left out to name it after the link
|
or left out to name it after the link
|
||||||
|
proxy outbounds chain <tag> <through-tag> [new tag]
|
||||||
|
add a copy of an existing outbound that dials through
|
||||||
|
another one; the original keeps dialing the way it did
|
||||||
proxy outbounds rm <tag> remove a runtime outbound
|
proxy outbounds rm <tag> remove a runtime outbound
|
||||||
proxy outbounds disable|enable <tag> keep an outbound out of automatic use (selection, autoProxy, pins),
|
proxy outbounds disable|enable <tag> keep an outbound out of automatic use (selection, autoProxy, pins),
|
||||||
or let it back in; declared ones too
|
or let it back in; declared ones too
|
||||||
@@ -492,6 +495,7 @@ COMPLETE = {
|
|||||||
"words": {
|
"words": {
|
||||||
"list": "outbounds, where each came from, and the pick",
|
"list": "outbounds, where each came from, and the pick",
|
||||||
"add": "add an outbound at runtime: [tag] <url or JSON>",
|
"add": "add an outbound at runtime: [tag] <url or JSON>",
|
||||||
|
"chain": "copy an outbound so it dials through another one",
|
||||||
"rm": "remove a runtime outbound",
|
"rm": "remove a runtime outbound",
|
||||||
"disable": "keep it out of automatic use",
|
"disable": "keep it out of automatic use",
|
||||||
"enable": "let a disabled outbound back in",
|
"enable": "let a disabled outbound back in",
|
||||||
@@ -504,6 +508,8 @@ COMPLETE = {
|
|||||||
"args": _outbound_choices,
|
"args": _outbound_choices,
|
||||||
"flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"},
|
"flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"},
|
||||||
},
|
},
|
||||||
|
# The outbound to copy, then the hop; the third word is the new tag, which nothing can suggest.
|
||||||
|
"proxy outbounds chain": {"args": _outbound_choices, "repeat": True},
|
||||||
"proxy outbounds rm": {"args": lambda: _names(_runtime_tags("outbound"))},
|
"proxy outbounds rm": {"args": lambda: _names(_runtime_tags("outbound"))},
|
||||||
"proxy outbounds disable": {"args": lambda: {t: d for t, d in _outbound_choices().items() if t not in _outbound_disabled()}},
|
"proxy outbounds disable": {"args": lambda: {t: d for t, d in _outbound_choices().items() if t not in _outbound_disabled()}},
|
||||||
"proxy outbounds enable": {"args": lambda: _names(_outbound_disabled())},
|
"proxy outbounds enable": {"args": lambda: _names(_outbound_disabled())},
|
||||||
@@ -941,6 +947,8 @@ def cmd_outbounds(verb="list", *args):
|
|||||||
if not detour:
|
if not detour:
|
||||||
usage("proxy outbounds add [tag] <url|json|-> [--detour <tag>]")
|
usage("proxy outbounds add [tag] <url|json|-> [--detour <tag>]")
|
||||||
_runtime_entry_add("outbound", *args, detour=detour)
|
_runtime_entry_add("outbound", *args, detour=detour)
|
||||||
|
elif verb == "chain":
|
||||||
|
cmd_outbound_chain(*args)
|
||||||
elif verb in ("rm", "remove", "del"):
|
elif verb in ("rm", "remove", "del"):
|
||||||
_runtime_entry_rm("outbound", *args)
|
_runtime_entry_rm("outbound", *args)
|
||||||
elif verb == "disable":
|
elif verb == "disable":
|
||||||
@@ -952,7 +960,7 @@ def cmd_outbounds(verb="list", *args):
|
|||||||
elif verb == "link":
|
elif verb == "link":
|
||||||
_outbound_link(*args)
|
_outbound_link(*args)
|
||||||
else:
|
else:
|
||||||
usage("proxy outbounds [list|add [tag] <url|json|->|rm <tag>|disable <tag>|enable <tag>|test [tag...]|link <tag>]")
|
usage("proxy outbounds [list|add [tag] <url|json|->|chain <tag> <through-tag>|rm <tag>|disable <tag>|enable <tag>|test [tag...]|link <tag>]")
|
||||||
|
|
||||||
|
|
||||||
def _outbound_inventory():
|
def _outbound_inventory():
|
||||||
@@ -1217,14 +1225,20 @@ def _json_text(value):
|
|||||||
return json.dumps(value, indent=2, ensure_ascii=False)
|
return json.dumps(value, indent=2, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _outbound_share_entry(tag):
|
||||||
|
"""What the socks start script recorded for an outbound: the URL it was given, and its backend JSON."""
|
||||||
|
entry = (_read_root_json(_runtime_file("outbound-share.json"), "outbounds").get("outbounds") or {}).get(tag)
|
||||||
|
if entry is None:
|
||||||
|
die(f"Unknown outbound: {tag}")
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
def _outbound_link(*args):
|
def _outbound_link(*args):
|
||||||
tag, flag = _share_args(args, ("--qr", "--json", "--config"), "proxy outbounds")
|
tag, flag = _share_args(args, ("--qr", "--json", "--config"), "proxy outbounds")
|
||||||
if flag == "--config":
|
if flag == "--config":
|
||||||
_config_export(only=tag)
|
_config_export(only=tag)
|
||||||
return
|
return
|
||||||
entry = (_read_root_json(_runtime_file("outbound-share.json"), "outbounds").get("outbounds") or {}).get(tag)
|
entry = _outbound_share_entry(tag)
|
||||||
if entry is None:
|
|
||||||
die(f"Unknown outbound: {tag}")
|
|
||||||
if flag == "--json":
|
if flag == "--json":
|
||||||
print(_json_text(_proxy_export().portable_outbound(entry.get("outbound") or {})))
|
print(_json_text(_proxy_export().portable_outbound(entry.get("outbound") or {})))
|
||||||
elif not entry.get("url"):
|
elif not entry.get("url"):
|
||||||
@@ -1427,8 +1441,12 @@ def _runtime_tag_for(kind, source):
|
|||||||
if not name and host:
|
if not name and host:
|
||||||
label = _host_label(host)
|
label = _host_label(host)
|
||||||
name = label if kind == "subscription" else f"{parts.scheme.lower()}-{label}"
|
name = label if kind == "subscription" else f"{parts.scheme.lower()}-{label}"
|
||||||
base = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:RUNTIME_TAG_MAX].strip("-._")
|
return _unique_runtime_tag(kind, name, "sub" if kind == "subscription" else "outbound")
|
||||||
base = base or ("sub" if kind == "subscription" else "outbound")
|
|
||||||
|
|
||||||
|
def _unique_runtime_tag(kind, name, fallback):
|
||||||
|
"""`name` as a tag nothing else has taken: -2, -3... after it."""
|
||||||
|
base = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:RUNTIME_TAG_MAX].strip("-._") or fallback
|
||||||
taken = {"proxy", "direct", "block", *_runtime_tags(kind), *(_outbound_tags() if kind == "outbound" else _sub_tags())}
|
taken = {"proxy", "direct", "block", *_runtime_tags(kind), *(_outbound_tags() if kind == "outbound" else _sub_tags())}
|
||||||
tag, n = base, 1
|
tag, n = base, 1
|
||||||
while tag in taken:
|
while tag in taken:
|
||||||
@@ -1487,6 +1505,39 @@ def _runtime_entry_add(kind, *args, detour=""):
|
|||||||
_runtime_entry_verify(kind, tag)
|
_runtime_entry_verify(kind, tag)
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_outbound_chain(tag="", hop="", new_tag="", *_):
|
||||||
|
"""A runtime copy of an existing outbound that dials through another one.
|
||||||
|
|
||||||
|
A detour belongs to the outbound that carries it, so chaining two that already exist
|
||||||
|
means a third: the original keeps dialing the way it did.
|
||||||
|
"""
|
||||||
|
if not tag or not hop:
|
||||||
|
usage("proxy outbounds chain <tag> <through-tag> [new tag]")
|
||||||
|
_require_outbound_inventory()
|
||||||
|
tags = _outbound_tags()
|
||||||
|
if tag not in tags:
|
||||||
|
die(f"Unknown outbound: {tag}")
|
||||||
|
if hop not in tags:
|
||||||
|
die(f"Cannot chain through '{hop}': not an outbound. See: proxy-ctl proxy outbounds")
|
||||||
|
if tag == hop:
|
||||||
|
die(f"'{tag}' cannot chain through itself; name another outbound as the hop.")
|
||||||
|
entry = _outbound_share_entry(tag)
|
||||||
|
source = _s(entry.get("url") or "")
|
||||||
|
if not source:
|
||||||
|
ob = entry.get("outbound") or {}
|
||||||
|
if not ob:
|
||||||
|
die(f"Nothing to copy from '{tag}': the backend recorded neither a URL nor JSON for it.")
|
||||||
|
source = _json_text(_proxy_export().portable_outbound(ob))
|
||||||
|
if new_tag:
|
||||||
|
_check_runtime_tag("outbound", new_tag)
|
||||||
|
else:
|
||||||
|
new_tag = _unique_runtime_tag("outbound", f"{tag}-via-{hop}", "chain")
|
||||||
|
print(f"Tag: {new_tag} (none given; pass one after the hop to choose it)")
|
||||||
|
if own_hop := _s((_outbound_inventory().get("detours") or {}).get(tag) or ""):
|
||||||
|
print(f"Note: '{tag}' chains through {own_hop}; the copy chains through {hop} instead.")
|
||||||
|
_runtime_entry_add("outbound", new_tag, source, detour=hop)
|
||||||
|
|
||||||
|
|
||||||
def _runtime_entry_rm(kind, tag="", *_):
|
def _runtime_entry_rm(kind, tag="", *_):
|
||||||
if not tag:
|
if not tag:
|
||||||
usage(f"proxy {_runtime_noun(kind)} rm <tag>")
|
usage(f"proxy {_runtime_noun(kind)} rm <tag>")
|
||||||
|
|||||||
+73
-15
@@ -59,12 +59,14 @@ TAB_ICONS = {
|
|||||||
"apps": "view-app-grid-symbolic",
|
"apps": "view-app-grid-symbolic",
|
||||||
}
|
}
|
||||||
STATUS_ICONS = {"ok": "emblem-ok-symbolic", "warn": "dialog-warning-symbolic", "bad": "dialog-error-symbolic", "": "network-wired-symbolic"}
|
STATUS_ICONS = {"ok": "emblem-ok-symbolic", "warn": "dialog-warning-symbolic", "bad": "dialog-error-symbolic", "": "network-wired-symbolic"}
|
||||||
|
TOAST_LINES = 4 # a toast says this much of what ran; the Output button, and `o`, have the whole of it
|
||||||
|
|
||||||
GLOBAL_SHORTCUTS = [
|
GLOBAL_SHORTCUTS = [
|
||||||
("<Control>f slash", "Filter the rows (list:learned for one column)"),
|
("<Control>f slash", "Filter the rows (list:learned for one column)"),
|
||||||
("Escape", "Clear the filter"),
|
("Escape", "Clear the filter"),
|
||||||
("Menu <Shift>F10", "Actions for the selected row (or right-click it)"),
|
("Menu <Shift>F10", "Actions for the selected row (or right-click it)"),
|
||||||
("<Alt>1...<Alt>8", "Jump to a tab"),
|
("<Alt>1...<Alt>8", "Jump to a tab"),
|
||||||
|
("<Control>v", "Paste a link: it is added to this tab"),
|
||||||
("w", "How is a domain routed"),
|
("w", "How is a domain routed"),
|
||||||
("<Shift>l", "Follow all logs"),
|
("<Shift>l", "Follow all logs"),
|
||||||
("o", "Output of the last command"),
|
("o", "Output of the last command"),
|
||||||
@@ -297,6 +299,7 @@ class Page(Gtk.Box):
|
|||||||
self.rows = [] # the last load, unfiltered
|
self.rows = [] # the last load, unfiltered
|
||||||
self.summary_text = ""
|
self.summary_text = ""
|
||||||
self.detail_shape = None
|
self.detail_shape = None
|
||||||
|
self.loaded = False # whether a load has landed here: before that the tab is not empty, it is unread
|
||||||
|
|
||||||
self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"])
|
self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"])
|
||||||
|
|
||||||
@@ -353,6 +356,12 @@ class Page(Gtk.Box):
|
|||||||
self.empty = Adw.StatusPage(title="Nothing here yet", icon_name=self.tab_icon, visible=False, vexpand=True)
|
self.empty = Adw.StatusPage(title="Nothing here yet", icon_name=self.tab_icon, visible=False, vexpand=True)
|
||||||
self.empty.set_child(self.tab_actions_box())
|
self.empty.set_child(self.tab_actions_box())
|
||||||
self.append(self.empty)
|
self.append(self.empty)
|
||||||
|
# Until this tab has loaded once there is nothing to keep on screen: say it is coming,
|
||||||
|
# rather than claim the tab is empty.
|
||||||
|
self.loading = Adw.StatusPage(title="Loading…", visible=True, vexpand=True)
|
||||||
|
self.loading.set_child(Adw.Spinner(width_request=32, height_request=32, halign=Gtk.Align.CENTER))
|
||||||
|
self.append(self.loading)
|
||||||
|
self.split.set_visible(False)
|
||||||
self.popover = None
|
self.popover = None
|
||||||
|
|
||||||
# --- cells ---------------------------------------------------------------------
|
# --- cells ---------------------------------------------------------------------
|
||||||
@@ -438,7 +447,7 @@ class Page(Gtk.Box):
|
|||||||
# --- filling ------------------------------------------------------------------------
|
# --- filling ------------------------------------------------------------------------
|
||||||
|
|
||||||
def fill(self, rows, summary):
|
def fill(self, rows, summary):
|
||||||
self.rows, self.summary_text = rows, summary
|
self.rows, self.summary_text, self.loaded = rows, summary, True
|
||||||
self.refill()
|
self.refill()
|
||||||
|
|
||||||
def refill(self):
|
def refill(self):
|
||||||
@@ -468,10 +477,12 @@ class Page(Gtk.Box):
|
|||||||
self.selection.set_selected(pos)
|
self.selection.set_selected(pos)
|
||||||
break
|
break
|
||||||
empty = not self.rows and not text
|
empty = not self.rows and not text
|
||||||
|
loading = empty and not self.loaded
|
||||||
self.split.set_visible(not empty)
|
self.split.set_visible(not empty)
|
||||||
self.empty.set_visible(empty)
|
self.empty.set_visible(empty and not loading)
|
||||||
|
self.loading.set_visible(loading)
|
||||||
self.summary.set_visible(bool(summary) and not empty)
|
self.summary.set_visible(bool(summary) and not empty)
|
||||||
if empty:
|
if empty and not loading:
|
||||||
unreadable = summary.startswith("✗")
|
unreadable = summary.startswith("✗")
|
||||||
self.empty.set_title("Cannot read this" if unreadable else "Nothing here yet")
|
self.empty.set_title("Cannot read this" if unreadable else "Nothing here yet")
|
||||||
self.empty.set_icon_name("dialog-error-symbolic" if unreadable else self.tab_icon)
|
self.empty.set_icon_name("dialog-error-symbolic" if unreadable else self.tab_icon)
|
||||||
@@ -761,6 +772,7 @@ class Window(Adw.ApplicationWindow):
|
|||||||
header.pack_start(self.root_badge)
|
header.pack_start(self.root_badge)
|
||||||
menu = Gio.Menu()
|
menu = Gio.Menu()
|
||||||
section = Gio.Menu()
|
section = Gio.Menu()
|
||||||
|
section.append("Paste a link into this tab", "win.paste")
|
||||||
section.append("How is a domain routed…", "win.where")
|
section.append("How is a domain routed…", "win.where")
|
||||||
section.append("Follow all logs", "win.logs")
|
section.append("Follow all logs", "win.logs")
|
||||||
section.append("Output of the last command", "win.last-output")
|
section.append("Output of the last command", "win.last-output")
|
||||||
@@ -809,6 +821,7 @@ class Window(Adw.ApplicationWindow):
|
|||||||
|
|
||||||
for name, callback, param in (
|
for name, callback, param in (
|
||||||
("where", lambda *_: self.where(), None),
|
("where", lambda *_: self.where(), None),
|
||||||
|
("paste", lambda *_: self.paste(), None),
|
||||||
("logs", lambda *_: self.follow_logs(), None),
|
("logs", lambda *_: self.follow_logs(), None),
|
||||||
("last-output", lambda *_: self.show_last_output(), None),
|
("last-output", lambda *_: self.show_last_output(), None),
|
||||||
("shortcuts", lambda *_: self.show_shortcuts(), None),
|
("shortcuts", lambda *_: self.show_shortcuts(), None),
|
||||||
@@ -821,6 +834,7 @@ class Window(Adw.ApplicationWindow):
|
|||||||
action.connect("activate", callback)
|
action.connect("activate", callback)
|
||||||
self.add_action(action)
|
self.add_action(action)
|
||||||
app.set_accels_for_action("win.filter", ["<Control>f"])
|
app.set_accels_for_action("win.filter", ["<Control>f"])
|
||||||
|
app.set_accels_for_action("win.paste", ["<Control>v"])
|
||||||
app.set_accels_for_action("app.elevated", ["<Control>e"])
|
app.set_accels_for_action("app.elevated", ["<Control>e"])
|
||||||
app.set_accels_for_action("win.shortcuts", ["<Control>question"])
|
app.set_accels_for_action("win.shortcuts", ["<Control>question"])
|
||||||
app.set_accels_for_action("app.reload", ["F5"])
|
app.set_accels_for_action("app.reload", ["F5"])
|
||||||
@@ -896,7 +910,13 @@ class Window(Adw.ApplicationWindow):
|
|||||||
chip.append(Gtk.Label(label=value, css_classes=["chip-value"], ellipsize=Pango.EllipsizeMode.END))
|
chip.append(Gtk.Label(label=value, css_classes=["chip-value"], ellipsize=Pango.EllipsizeMode.END))
|
||||||
self.status.append(chip)
|
self.status.append(chip)
|
||||||
|
|
||||||
def fill(self, states, visible, status, tab_id, rows, summary):
|
def fill(self, states, visible, status, tab_id, rows, summary, stale=False):
|
||||||
|
# A read that came back empty after a good one keeps what is on screen: every tab
|
||||||
|
# and row blinking out and back is worse than a banner saying the read failed.
|
||||||
|
if stale:
|
||||||
|
self.banner.set_title("Cannot read service states: showing the last good read")
|
||||||
|
self.banner.set_revealed(True)
|
||||||
|
return
|
||||||
self.show_status(status)
|
self.show_status(status)
|
||||||
unreadable = not states
|
unreadable = not states
|
||||||
self.banner.set_title("Cannot read service states: is systemd reachable?" if unreadable else "")
|
self.banner.set_title("Cannot read service states: is systemd reachable?" if unreadable else "")
|
||||||
@@ -919,6 +939,27 @@ class Window(Adw.ApplicationWindow):
|
|||||||
self.perform(model.WHERE, None)
|
self.perform(model.WHERE, None)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def paste(self):
|
||||||
|
"""Ctrl+V anywhere but a text field: whatever is in the clipboard is added to this tab."""
|
||||||
|
if isinstance(self.get_focus(), Gtk.Editable) or self.get_visible_dialog() is not None:
|
||||||
|
return False
|
||||||
|
page = self.page()
|
||||||
|
if page is not None:
|
||||||
|
self.get_clipboard().read_text_async(None, lambda clipboard, result: self.pasted(page, clipboard, result))
|
||||||
|
return True
|
||||||
|
|
||||||
|
def pasted(self, page, clipboard, result):
|
||||||
|
try:
|
||||||
|
text = clipboard.read_text_finish(result)
|
||||||
|
except GLib.Error as e:
|
||||||
|
self.toast(f"Cannot read the clipboard: {e.message}")
|
||||||
|
return
|
||||||
|
argv, what = model.paste_argv(page.tab.id, text)
|
||||||
|
if argv is None:
|
||||||
|
self.toast(what)
|
||||||
|
else:
|
||||||
|
self.app.run_argv("run", argv, self)
|
||||||
|
|
||||||
def follow_logs(self):
|
def follow_logs(self):
|
||||||
self.app.run_argv("suspend", ["logs"], self)
|
self.app.run_argv("suspend", ["logs"], self)
|
||||||
return True
|
return True
|
||||||
@@ -969,7 +1010,20 @@ class Window(Adw.ApplicationWindow):
|
|||||||
entry.grab_focus()
|
entry.grab_focus()
|
||||||
|
|
||||||
def toast(self, message, output=None, retry=None):
|
def toast(self, message, output=None, retry=None):
|
||||||
toast = Adw.Toast(title=GLib.markup_escape_text(message), timeout=6)
|
# A toast title is one ellipsized line, which hides most of what a command said:
|
||||||
|
# wrap it over a few lines instead, and keep the rest one button (or `o`) away.
|
||||||
|
label = Gtk.Label(
|
||||||
|
label=message,
|
||||||
|
wrap=True,
|
||||||
|
wrap_mode=Pango.WrapMode.WORD_CHAR,
|
||||||
|
natural_wrap_mode=Gtk.NaturalWrapMode.WORD,
|
||||||
|
lines=TOAST_LINES,
|
||||||
|
ellipsize=Pango.EllipsizeMode.END,
|
||||||
|
xalign=0,
|
||||||
|
justify=Gtk.Justification.LEFT,
|
||||||
|
max_width_chars=64,
|
||||||
|
)
|
||||||
|
toast = Adw.Toast(custom_title=label, timeout=8)
|
||||||
if retry: # one button: the output stays a keypress away (o)
|
if retry: # one button: the output stays a keypress away (o)
|
||||||
toast.set_button_label("Retry as Root")
|
toast.set_button_label("Retry as Root")
|
||||||
toast.connect("button-clicked", lambda *_: retry())
|
toast.connect("button-clicked", lambda *_: retry())
|
||||||
@@ -1171,16 +1225,19 @@ class ProxySuiteGui(Adw.Application):
|
|||||||
if self.window:
|
if self.window:
|
||||||
self.window.set_busy(False)
|
self.window.set_busy(False)
|
||||||
if generation == self.generation:
|
if generation == self.generation:
|
||||||
self.states = result["states"]
|
# Nothing read, after a read that worked: keep the last good one, tray and all.
|
||||||
snap = result["snap"]
|
stale = not result["states"] and bool(self.states)
|
||||||
tree, overall, outbound = result["tray"]
|
if not stale:
|
||||||
if self.tray:
|
self.states = result["states"]
|
||||||
failed = snap["failed"] if snap else []
|
snap = result["snap"]
|
||||||
tooltip = overall["label"] + (f"\nOutbound: {outbound}" if outbound else "") + (f"\nFailed: {', '.join(failed)}" if failed else "")
|
tree, overall, outbound = result["tray"]
|
||||||
self.tray.update(model.icon_name(overall), tooltip, tree, attention=bool(failed))
|
if self.tray:
|
||||||
self.notify_failures(snap)
|
failed = snap["failed"] if snap else []
|
||||||
|
tooltip = overall["label"] + (f"\nOutbound: {outbound}" if outbound else "") + (f"\nFailed: {', '.join(failed)}" if failed else "")
|
||||||
|
self.tray.update(model.icon_name(overall), tooltip, tree, attention=bool(failed))
|
||||||
|
self.notify_failures(snap)
|
||||||
if "tab" in result and self.window:
|
if "tab" in result and self.window:
|
||||||
self.window.fill(self.states, result["visible"], result["status"], *result["tab"])
|
self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale)
|
||||||
if self.pending:
|
if self.pending:
|
||||||
self.pending = False
|
self.pending = False
|
||||||
self.reload()
|
self.reload()
|
||||||
@@ -1280,7 +1337,8 @@ class ProxySuiteGui(Adw.Application):
|
|||||||
win.copy_text(last, f"Copied: {last}")
|
win.copy_text(last, f"Copied: {last}")
|
||||||
else:
|
else:
|
||||||
message = f"{last} ({command})" if last else command
|
message = f"{last} ({command})" if last else command
|
||||||
win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status else None, retry)
|
# Anything it printed is worth a button: the toast shows a few lines of it at most.
|
||||||
|
win.toast(f"exit {status}: {message}" if status else message, output if out else None, retry)
|
||||||
elif status:
|
elif status:
|
||||||
# From the tray: nothing else would say it failed.
|
# From the tray: nothing else would say it failed.
|
||||||
note = Gio.Notification.new(f"{command} failed")
|
note = Gio.Notification.new(f"{command} failed")
|
||||||
|
|||||||
@@ -471,6 +471,13 @@ TABS = [
|
|||||||
when=ROW,
|
when=ROW,
|
||||||
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
||||||
),
|
),
|
||||||
|
Action(
|
||||||
|
"H",
|
||||||
|
"chain it through another outbound…",
|
||||||
|
lambda r, t, _: ["proxy", "outbounds", "chain", r["tag"], *t.split()],
|
||||||
|
when=ROW,
|
||||||
|
prompt="<hop tag> [new tag] - a copy of this one dialing through the hop",
|
||||||
|
),
|
||||||
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
||||||
Action(
|
Action(
|
||||||
"x",
|
"x",
|
||||||
@@ -589,6 +596,39 @@ TABS = [
|
|||||||
|
|
||||||
WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog")
|
WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog")
|
||||||
|
|
||||||
|
# The share-link schemes scripts/proxy_url_parsers.py parses. http(s) is both an HTTP proxy
|
||||||
|
# and how a subscription is spelled, so for those the tab pasted into decides.
|
||||||
|
PROXY_SCHEMES = ("vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic", "socks5", "socks5h", "socks4", "socks4a")
|
||||||
|
HOST = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))+")
|
||||||
|
# A bare host means something only where a tab collects hosts.
|
||||||
|
HOST_ARGV = {"zapret": ["zapret", "auto", "add"], "autoproxy": ["proxy", "auto", "learn"]}
|
||||||
|
OUTBOUND_ADD = ["proxy", "outbounds", "add"]
|
||||||
|
|
||||||
|
|
||||||
|
def paste_argv(tab_id, text):
|
||||||
|
"""What pasting the clipboard onto a tab runs: (argv, ""), or (None, why it runs nothing).
|
||||||
|
|
||||||
|
Dumb on purpose: a share link becomes an outbound, a subscription URL a subscription,
|
||||||
|
a bare host a pinned or learned one. The tag comes from the link, as `add` derives it.
|
||||||
|
"""
|
||||||
|
text = (text or "").strip()
|
||||||
|
if not text:
|
||||||
|
return None, "Nothing to paste."
|
||||||
|
if text.startswith("{"):
|
||||||
|
return [*OUTBOUND_ADD, text], "" # only outbounds take JSON
|
||||||
|
if len(text.splitlines()) > 1:
|
||||||
|
return None, "Paste one link at a time."
|
||||||
|
scheme = text.split("://", 1)[0].lower() if "://" in text else ""
|
||||||
|
if scheme in PROXY_SCHEMES:
|
||||||
|
return [*OUTBOUND_ADD, text], ""
|
||||||
|
if scheme in ("http", "https"):
|
||||||
|
return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), ""
|
||||||
|
if scheme:
|
||||||
|
return None, f"Nothing takes a {scheme}:// link."
|
||||||
|
if HOST.fullmatch(text) and tab_id in HOST_ARGV:
|
||||||
|
return [*HOST_ARGV[tab_id], text], ""
|
||||||
|
return None, "Not a share link, a subscription URL or a host."
|
||||||
|
|
||||||
|
|
||||||
def available_tabs(states):
|
def available_tabs(states):
|
||||||
return [t.id for t in TABS if _safe(t.available, states, fallback=False)]
|
return [t.id for t in TABS if _safe(t.available, states, fallback=False)]
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ GLOBAL_KEYS = [
|
|||||||
("← → ⇥", "switch tab; 1-8 jump to one"),
|
("← → ⇥", "switch tab; 1-8 jump to one"),
|
||||||
("/", "filter the rows (list:learned for one column); esc clears"),
|
("/", "filter the rows (list:learned for one column); esc clears"),
|
||||||
("click", "a column heading sorts by it, again reverses, a third time unsorts"),
|
("click", "a column heading sorts by it, again reverses, a third time unsorts"),
|
||||||
|
("paste", "a link in the clipboard is added to this tab"),
|
||||||
("w", "how is a domain routed"),
|
("w", "how is a domain routed"),
|
||||||
("L", "follow all logs"),
|
("L", "follow all logs"),
|
||||||
("o", "output of the last command"),
|
("o", "output of the last command"),
|
||||||
@@ -501,7 +502,13 @@ class ProxyTui(App):
|
|||||||
# --- reading --------------------------------------------------------------
|
# --- reading --------------------------------------------------------------
|
||||||
|
|
||||||
def action_reload(self):
|
def action_reload(self):
|
||||||
self.load(self.active_tab())
|
tab_id = self.active_tab()
|
||||||
|
if tab_id not in self.loaded:
|
||||||
|
# Nothing has landed here yet, and an empty table reads as an empty tab.
|
||||||
|
widget = self.main.query_one(f"#{tab_id}-summary", Static)
|
||||||
|
_update(widget, Text("loading…"))
|
||||||
|
widget.display = True
|
||||||
|
self.load(tab_id)
|
||||||
|
|
||||||
@work(thread=True, exclusive=True, group="load")
|
@work(thread=True, exclusive=True, group="load")
|
||||||
def load(self, tab_id):
|
def load(self, tab_id):
|
||||||
@@ -535,6 +542,11 @@ class ProxyTui(App):
|
|||||||
widget.display = True
|
widget.display = True
|
||||||
|
|
||||||
def fill_table(self, tab_id, states, visible, status, rows, summary):
|
def fill_table(self, tab_id, states, visible, status, rows, summary):
|
||||||
|
# Nothing read, after a read that worked: keep the last good view, so one bad refresh
|
||||||
|
# does not blink every tab and row out and back.
|
||||||
|
if not states and self.states:
|
||||||
|
self.feedback("cannot read service states: showing the last good read", False)
|
||||||
|
return
|
||||||
rows = model.unique_keys(rows)
|
rows = model.unique_keys(rows)
|
||||||
self.loaded[tab_id] = (states, visible, status, rows, summary)
|
self.loaded[tab_id] = (states, visible, status, rows, summary)
|
||||||
self.states, self.status = states, status
|
self.states, self.status = states, status
|
||||||
@@ -623,6 +635,18 @@ class ProxyTui(App):
|
|||||||
def action_act(self, index):
|
def action_act(self, index):
|
||||||
self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row())
|
self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row())
|
||||||
|
|
||||||
|
def on_paste(self, event):
|
||||||
|
"""The terminal's paste, bracketed: whatever it carries is added to the tab it lands on.
|
||||||
|
A prompt or a dialog takes its own paste, so this only fires on the table."""
|
||||||
|
if self.screen is not self.main:
|
||||||
|
return
|
||||||
|
event.stop()
|
||||||
|
argv, what = model.paste_argv(self.active_tab(), event.text)
|
||||||
|
if argv is None:
|
||||||
|
self.feedback(what, False)
|
||||||
|
else:
|
||||||
|
self.run_argv("run", argv)
|
||||||
|
|
||||||
def action_where(self):
|
def action_where(self):
|
||||||
self.perform(model.WHERE, None)
|
self.perform(model.WHERE, None)
|
||||||
|
|
||||||
|
|||||||
@@ -580,6 +580,47 @@ class RuntimeEntryTest(EnvTest):
|
|||||||
self.assertIn("Cannot see the entry for 'de'", err)
|
self.assertIn("Cannot see the entry for 'de'", err)
|
||||||
self.assertNotIn("No runtime outbound", err)
|
self.assertNotIn("No runtime outbound", err)
|
||||||
|
|
||||||
|
def share(self, outbounds):
|
||||||
|
"""outbound-share.json as the socks start script writes it, beside the inventory."""
|
||||||
|
self.write("outbound-share.json", {"outbounds": outbounds})
|
||||||
|
|
||||||
|
def test_chain_copies_an_existing_outbound_through_a_hop(self):
|
||||||
|
self.share({"primary": {"url": "vless://u@de.test:443"}, "vless-example": {"url": "vless://u@nl.test:443"}})
|
||||||
|
out = ok(ctl.cmd_outbounds, "chain", "primary", "vless-example")
|
||||||
|
self.assertIn("Tag: primary-via-vless-example", out)
|
||||||
|
self.assertEqual(ctl.read_text(self.path("outbounds.d/primary-via-vless-example.url")), "vless://u@de.test:443\n")
|
||||||
|
self.assertEqual(ctl.read_text(self.path("outbounds.d/primary-via-vless-example.detour")), "vless-example\n")
|
||||||
|
# The original is untouched: a detour belongs to the outbound carrying it.
|
||||||
|
self.assertFalse(os.path.exists(self.path("outbounds.d/primary.detour")))
|
||||||
|
self.assertEqual(self.started, ["proxy-suite-outbound-reload.service"])
|
||||||
|
# A name of one's own, and a second copy of the same pair gets its own tag.
|
||||||
|
ok(ctl.cmd_outbounds, "chain", "primary", "vless-example", "de-via-nl")
|
||||||
|
self.assertTrue(os.path.exists(self.path("outbounds.d/de-via-nl.url")))
|
||||||
|
self.assertIn("Tag: primary-via-vless-example-2", ok(ctl.cmd_outbounds, "chain", "primary", "vless-example"))
|
||||||
|
|
||||||
|
def test_chain_without_a_url_copies_the_backend_json(self):
|
||||||
|
self.share({"primary": {"outbound": {"tag": "primary", "type": "socks", "server": "1.2.3.4", "routing_mark": 99}}})
|
||||||
|
ok(ctl.cmd_outbounds, "chain", "primary", "vless-example", "hop")
|
||||||
|
written = json.loads(ctl.read_text(self.path("outbounds.d/hop.json")))
|
||||||
|
# Portable and untagged: the entry's name is the tag, and the host's mark is not shared.
|
||||||
|
self.assertEqual(written, {"type": "socks", "server": "1.2.3.4"})
|
||||||
|
|
||||||
|
def test_chain_refuses_what_it_cannot_chain(self):
|
||||||
|
self.share({"primary": {"url": "vless://u@de.test:443"}, "vless-example": {}})
|
||||||
|
for args, message in (
|
||||||
|
(("chain",), "proxy outbounds chain"),
|
||||||
|
(("chain", "primary"), "proxy outbounds chain"),
|
||||||
|
(("chain", "primary", "primary"), "cannot chain through itself"),
|
||||||
|
(("chain", "nope", "primary"), "Unknown outbound: nope"),
|
||||||
|
(("chain", "primary", "nope"), "Cannot chain through 'nope'"),
|
||||||
|
(("chain", "vless-example", "primary"), "Nothing to copy from 'vless-example'"),
|
||||||
|
):
|
||||||
|
with self.subTest(args=args):
|
||||||
|
status, _, err = run(ctl.cmd_outbounds, *args)
|
||||||
|
self.assertNotEqual(status, 0)
|
||||||
|
self.assertIn(message, err)
|
||||||
|
self.assertEqual(os.listdir(self.path("outbounds.d")), [])
|
||||||
|
|
||||||
def test_rm_takes_the_marker_along(self):
|
def test_rm_takes_the_marker_along(self):
|
||||||
ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443")
|
ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443")
|
||||||
ok(ctl.cmd_outbounds, "disable", "de")
|
ok(ctl.cmd_outbounds, "disable", "de")
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import proxy_ctl as ctl
|
|||||||
import proxy_gui as gui
|
import proxy_gui as gui
|
||||||
import proxy_model as model
|
import proxy_model as model
|
||||||
import proxy_sni as sni
|
import proxy_sni as sni
|
||||||
from gi.repository import Gio, GLib
|
from gi.repository import Adw, Gio, GLib, Gtk
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons"))
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons"))
|
||||||
import badges # noqa: E402
|
import badges # noqa: E402
|
||||||
@@ -77,6 +77,14 @@ class GuiTest(unittest.TestCase):
|
|||||||
self.assertTrue(gui.is_badge("status", "ok"))
|
self.assertTrue(gui.is_badge("status", "ok"))
|
||||||
self.assertFalse(gui.is_badge("mark", "★"))
|
self.assertFalse(gui.is_badge("mark", "★"))
|
||||||
|
|
||||||
|
def test_toast_title_is_a_wrapping_label(self):
|
||||||
|
"""A toast's own title is one ellipsized line; the properties the wrapping one needs are there.
|
||||||
|
Widgets cannot be built here: GTK segfaults without a display."""
|
||||||
|
self.assertIsNotNone(Adw.Toast.find_property("custom-title"))
|
||||||
|
for name in ("wrap", "wrap-mode", "natural-wrap-mode", "lines", "ellipsize", "max-width-chars"):
|
||||||
|
self.assertIsNotNone(Gtk.Label.find_property(name), name)
|
||||||
|
self.assertGreater(gui.TOAST_LINES, 1)
|
||||||
|
|
||||||
def test_ansi(self):
|
def test_ansi(self):
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
gui.ansi_segments("\x1b[1;31mfailed\x1b[0m ok\x1b[K"),
|
gui.ansi_segments("\x1b[1;31mfailed\x1b[0m ok\x1b[K"),
|
||||||
|
|||||||
@@ -158,6 +158,31 @@ class ModelTest(unittest.TestCase):
|
|||||||
self.assertEqual([i.id for i in model.tray_menu(None)], ["status", "open", "sep-0", "quit"])
|
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")
|
self.assertEqual(model.icon_name(ctl._overall_state(None)), "proxy-suite-disabled-unknown")
|
||||||
|
|
||||||
|
def test_paste_argv(self):
|
||||||
|
paste = model.paste_argv
|
||||||
|
self.assertEqual(paste("outbounds", " vless://u@de.test:443#DE\n")[0], ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"])
|
||||||
|
# The tab pasted onto does not matter for an unambiguous link.
|
||||||
|
self.assertEqual(paste("services", "ss://x@a.test:8388")[0], ["proxy", "outbounds", "add", "ss://x@a.test:8388"])
|
||||||
|
self.assertEqual(paste("services", '{"type": "socks",\n "server": "1.2.3.4"}')[0][:3], ["proxy", "outbounds", "add"])
|
||||||
|
# http(s) is both a subscription and an HTTP proxy: the tab decides.
|
||||||
|
self.assertEqual(paste("subs", "https://sub.test/s")[0], ["proxy", "subs", "add", "https://sub.test/s"])
|
||||||
|
self.assertEqual(paste("services", "https://sub.test/s")[0], ["proxy", "subs", "add", "https://sub.test/s"])
|
||||||
|
self.assertEqual(paste("outbounds", "https://u:p@proxy.test:8443")[0], ["proxy", "outbounds", "add", "https://u:p@proxy.test:8443"])
|
||||||
|
# A bare host means something only where a tab collects hosts.
|
||||||
|
self.assertEqual(paste("zapret", "blocked.example")[0], ["zapret", "auto", "add", "blocked.example"])
|
||||||
|
self.assertEqual(paste("autoproxy", "blocked.example")[0], ["proxy", "auto", "learn", "blocked.example"])
|
||||||
|
for tab, text, why in [
|
||||||
|
("outbounds", "", "Nothing to paste."),
|
||||||
|
("outbounds", "vless://a\nvless://b", "one link at a time"),
|
||||||
|
("outbounds", "ftp://a.test/x", "ftp:// link"),
|
||||||
|
("outbounds", "blocked.example", "Not a share link"),
|
||||||
|
("zapret", "not a host", "Not a share link"),
|
||||||
|
]:
|
||||||
|
with self.subTest(text=text):
|
||||||
|
argv, message = paste(tab, text)
|
||||||
|
self.assertIsNone(argv)
|
||||||
|
self.assertIn(why, message)
|
||||||
|
|
||||||
def test_load_tab(self):
|
def test_load_tab(self):
|
||||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||||
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
|
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
|
||||||
@@ -166,7 +191,7 @@ class ModelTest(unittest.TestCase):
|
|||||||
self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")])
|
self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")])
|
||||||
self.assertIn("Pinned: b", summary)
|
self.assertIn("Pinned: b", summary)
|
||||||
with mock.patch.object(ctl, "env", lambda name, default="": ""):
|
with mock.patch.object(ctl, "env", lambda name, default="": ""):
|
||||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "x", "l", "c", "Q", "J", "F", "X"])
|
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "H", "x", "l", "c", "Q", "J", "F", "X"])
|
||||||
chain = next(a for a in tab.actions if a.key == "h")
|
chain = next(a for a in tab.actions if a.key == "h")
|
||||||
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
|
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
|
||||||
# Probe exits go by the backend's tag.
|
# Probe exits go by the backend's tag.
|
||||||
|
|||||||
@@ -121,6 +121,25 @@ class TuiTest(unittest.TestCase):
|
|||||||
|
|
||||||
asyncio.run(run())
|
asyncio.run(run())
|
||||||
|
|
||||||
|
def test_paste_lands_on_the_tab_it_was_pasted_onto(self):
|
||||||
|
async def run():
|
||||||
|
self.units = {"proxy-suite-socks": "active", **self.units}
|
||||||
|
app = tui.ProxyTui()
|
||||||
|
async with app.run_test(size=(100, 30)) as pilot:
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
app.main.query_one("#tabs", tui.TabbedContent).active = "outbounds"
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
app.post_message(tui.events.Paste("vless://u@de.test:443#DE"))
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"])
|
||||||
|
# Whatever else was in the clipboard runs nothing, and the bar says why.
|
||||||
|
app.post_message(tui.events.Paste("ftp://a.test/x"))
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran, [])
|
||||||
|
self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content))
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
def test_ui(self):
|
def test_ui(self):
|
||||||
# Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl.
|
# Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl.
|
||||||
asyncio.run(self.ui())
|
asyncio.run(self.ui())
|
||||||
|
|||||||
Reference in new issue
Block a user