Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Last active September 2, 2026 15:00
Show Gist options
  • Select an option

  • Save qianlifeng/dd2735f0aedb12b99c0aa0e226771a8f to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/dd2735f0aedb12b99c0aa0e226771a8f to your computer and use it in GitHub Desktop.
Wox.Plugin.Speedtest
# {
# "Id": "e6c4a8b1-2f7d-4c19-9a5e-8d3b1f0e6a24",
# "Name": "i18n:plugin_name",
# "Author": "qianlifeng",
# "Version": "1.2.0",
# "MinWoxVersion": "2.4.2",
# "Runtime": "PYTHON",
# "Description": "i18n:plugin_description",
# "Icon": "emoji:🚀",
# "TriggerKeywords": ["speedtest"],
# "SupportedOS": ["Windows", "Linux", "Macos"],
# "Commands": [
# { "Command": "start", "Description": "i18n:cmd_start" },
# { "Command": "history", "Description": "i18n:cmd_history" },
# { "Command": "ip", "Description": "i18n:cmd_ip" }
# ],
# "Features": [
# { "Name": "debounce", "Params": { "IntervalMs": 250 } },
# { "Name": "ignoreAutoScore" }
# ],
# "SettingDefinitions": [
# {
# "Type": "textbox",
# "Value": {
# "Key": "max_history",
# "Label": "i18n:setting_max_history",
# "Tooltip": "i18n:setting_max_history_tip",
# "DefaultValue": "20",
# "Style": { "Width": 120 },
# "Validators": [
# { "Type": "is_number", "Value": { "IsInteger": true, "IsFloat": false } }
# ]
# }
# }
# ],
# "I18n": {
# "en_US": {
# "plugin_name": "Speedtest",
# "plugin_description": "Test internet speed over HTTP download, upload, and ping",
# "cmd_start": "Run a speed test",
# "cmd_history": "View past test results",
# "cmd_ip": "Show internal and public IP",
# "setting_max_history": "History size",
# "setting_max_history_tip": "How many past results to keep (1-100)",
# "menu_start": "Start speed test",
# "menu_start_sub": "HTTP download, upload, and ping",
# "menu_history": "History",
# "menu_history_sub": "Browse previous speed test results",
# "menu_ip": "IP addresses",
# "menu_ip_sub": "Internal and public IP",
# "menu_last": "Latest result",
# "hint_commands": "start • history • ip",
# "testing": "Testing your internet speed...",
# "testing_sub": "Results update automatically",
# "connecting": "Connecting...",
# "progress_download": "Download %s Mbps (%s%%)",
# "progress_upload": "Upload %s Mbps (%s%%)",
# "progress_ping": "Testing ping...",
# "just_now": "just now",
# "action_refresh": "Refresh",
# "action_cancel": "Cancel test",
# "action_start": "Start test",
# "action_retest": "Test again",
# "action_copy": "Copy",
# "action_copy_summary": "Copy summary",
# "action_open_result": "Open result page",
# "action_copy_ip": "Copy IP",
# "cancelled": "Speed test cancelled",
# "cancelled_sub": "Press Enter to start a new test",
# "failed": "Speed test failed",
# "retry": "Enter to retry",
# "download": "Download",
# "upload": "Upload",
# "ping": "Ping",
# "server": "Endpoint",
# "isp": "ISP",
# "jitter": "Jitter",
# "latency": "Latency",
# "view_online": "View detailed results online",
# "history_empty": "No history yet",
# "history_empty_sub": "Run speedtest start to record the first result",
# "ip_internal": "Internal IP",
# "ip_public": "Public IP",
# "ip_unknown": "unknown",
# "ip_unknown_sub": "Network may be offline"
# },
# "zh_CN": {
# "plugin_name": "Speedtest",
# "plugin_description": "通过 HTTP 下载、上传和延迟测试网速",
# "cmd_start": "开始测速",
# "cmd_history": "查看历史测速结果",
# "cmd_ip": "查看内网和公网 IP",
# "setting_max_history": "历史条数",
# "setting_max_history_tip": "保留的历史结果数量(1-100)",
# "menu_start": "开始测速",
# "menu_start_sub": "HTTP 下载、上传和延迟",
# "menu_history": "历史记录",
# "menu_history_sub": "查看以前的测速结果",
# "menu_ip": "IP 地址",
# "menu_ip_sub": "内网和公网 IP",
# "menu_last": "最近一次结果",
# "hint_commands": "start • history • ip",
# "testing": "正在测试网速...",
# "testing_sub": "结果会自动更新",
# "connecting": "正在连接...",
# "progress_download": "下载 %s Mbps(%s%%)",
# "progress_upload": "上传 %s Mbps(%s%%)",
# "progress_ping": "正在测试延迟...",
# "just_now": "刚刚",
# "action_refresh": "刷新",
# "action_cancel": "取消测速",
# "action_start": "开始测速",
# "action_retest": "重新测速",
# "action_copy": "复制",
# "action_copy_summary": "复制摘要",
# "action_open_result": "打开结果页",
# "action_copy_ip": "复制 IP",
# "cancelled": "已取消测速",
# "cancelled_sub": "按回车开始新的测试",
# "failed": "测速失败",
# "retry": "按回车重试",
# "download": "下载",
# "upload": "上传",
# "ping": "延迟",
# "server": "测速地址",
# "isp": "运营商",
# "jitter": "抖动",
# "latency": "延迟",
# "view_online": "在线查看详细结果",
# "history_empty": "还没有历史记录",
# "history_empty_sub": "运行 speedtest start 记录第一次结果",
# "ip_internal": "内网 IP",
# "ip_public": "公网 IP",
# "ip_unknown": "未知",
# "ip_unknown_sub": "网络可能离线"
# }
# }
# }
"""
Wox Speedtest single-file SDK plugin.
HTTP download, upload, and ping run on a background thread in the shared Python host.
History stays in cache/netspeed-script-plugin so previous results are reused.
Usage:
speedtest command menu
speedtest start run a speed test
speedtest history past results
"""
from __future__ import annotations
import asyncio
import datetime
import http.client
import json
import os
import socket
import ssl
import tempfile
import threading
import time
import webbrowser
from typing import Any
from urllib.error import URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from wox_plugin import (
ActionContext,
ChangeQueryParam,
Context,
CopyParams,
CopyType,
LogLevel,
PluginInitParams,
Query,
QueryResponse,
QueryType,
Result,
ResultAction,
ResultTail,
ResultTailType,
UpdatableResult,
WoxImage,
)
def _svg(data: str) -> WoxImage:
if data.startswith("svg:"):
data = data[4:]
return WoxImage.new_svg(data)
class _Runtime:
"""Process-wide settings and worker handles for this plugin instance."""
max_history = 20
cancel = threading.Event()
worker: threading.Thread | None = None
loop: asyncio.AbstractEventLoop | None = None
api: Any = None
state: dict[str, Any] = {}
state_lock = threading.Lock()
RUNTIME = _Runtime()
_I18N: dict[str, str] = {}
def _parse_max_history(raw: str | None) -> int:
try:
return min(100, max(1, int((raw or "20").strip() or "20")))
except ValueError:
return 20
PLUGIN_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><defs><linearGradient id=\"nsIconBg\" x1=\"6\" y1=\"2\" "
"x2=\"44\" y2=\"46\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#2563eb\"/>"
"<stop offset=\".55\" stop-color=\"#06b6d4\"/><stop offset=\"1\" stop-color=\"#22c55e\"/>"
"</linearGradient></defs><rect width=\"48\" height=\"48\" rx=\"13\" fill=\"url(#nsIconBg)\"/>"
"<path d=\"M14 30a12 12 0 1 1 20 0\" fill=\"none\" stroke=\"#fff\" stroke-width=\"3.2\" "
"stroke-linecap=\"round\"/><circle cx=\"24\" cy=\"30\" r=\"3.2\" fill=\"#fbbf24\"/>"
"<path d=\"M24 30l8-10\" stroke=\"#f97316\" stroke-width=\"3\" stroke-linecap=\"round\"/>"
"<circle cx=\"24\" cy=\"30\" r=\"1.4\" fill=\"#fff\"/></svg>"
)
START_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#22c55e\"/>"
"<path d=\"M20 16.5v15l13-7.5z\" fill=\"#fff\"/></svg>"
)
HISTORY_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#8b5cf6\"/>"
"<path d=\"M24 14v11l7 4\" fill=\"none\" stroke=\"#fff\" stroke-width=\"3\" "
"stroke-linecap=\"round\" stroke-linejoin=\"round\"/>"
"<path d=\"M13 18.5A12 12 0 1 1 12 24\" fill=\"none\" stroke=\"#fde68a\" "
"stroke-width=\"2.6\" stroke-linecap=\"round\"/></svg>"
)
IP_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#0ea5e9\"/>"
"<ellipse cx=\"24\" cy=\"24\" rx=\"8\" ry=\"20\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"2.4\"/><path d=\"M6 24h36M10 16h28M10 32h28\" fill=\"none\" "
"stroke=\"#fff\" stroke-width=\"2.2\" stroke-linecap=\"round\"/></svg>"
)
SERVER_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><rect x=\"8\" y=\"8\" width=\"32\" height=\"12\" rx=\"3\" "
"fill=\"#3b82f6\"/><rect x=\"8\" y=\"28\" width=\"32\" height=\"12\" rx=\"3\" "
"fill=\"#1d4ed8\"/><circle cx=\"14\" cy=\"14\" r=\"2\" fill=\"#4ade80\"/>"
"<circle cx=\"14\" cy=\"34\" r=\"2\" fill=\"#fbbf24\"/>"
"<path d=\"M20 14h14M20 34h14\" stroke=\"#dbeafe\" stroke-width=\"2.2\" "
"stroke-linecap=\"round\"/></svg>"
)
DOWNLOAD_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#16a34a\"/>"
"<path d=\"M24 12v18M16 24l8 10 8-10\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"3.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>"
)
UPLOAD_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#f97316\"/>"
"<path d=\"M24 36V18M16 24l8-10 8 10\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"3.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>"
)
PING_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#06b6d4\"/>"
"<path d=\"M14 30a12 12 0 0 1 20 0M17.5 26a7.5 7.5 0 0 1 13 0\" fill=\"none\" "
"stroke=\"#fff\" stroke-width=\"2.8\" stroke-linecap=\"round\"/>"
"<circle cx=\"24\" cy=\"33\" r=\"2.4\" fill=\"#fde68a\"/></svg>"
)
COPY_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"80\" height=\"80\" "
"viewBox=\"0 0 80 80\"><g fill=\"none\"><path fill=\"#f2c94c\" fill-rule=\"evenodd\" "
"d=\"M30 55V39.57a4 4 0 0 1 1.158-2.816l10.47-10.568a4 4 0 0 1 2.84-1.185H50v-8a4 "
"4 0 0 0-4-4h-8.19L22 13a4 4 0 0 0-4 4v34a4 4 0 0 0 4 4z\" clip-rule=\"evenodd\"/>"
"<path fill=\"#f2994a\" fill-rule=\"evenodd\" d=\"M41.73 26.087a4 4 0 0 1 2.739-1.085"
"L57.999 25A4 4 0 0 1 62 29v34a4 4 0 0 1-4 4H34a4 4 0 0 1-4-4V39.57a4 4 0 0 1 "
"1.08-2.734a.667.667 0 0 0 .52 1.086h7.2a4 4 0 0 0 4-4v-7.308a.665.665 0 0 0-1.07"
"-.527\" clip-rule=\"evenodd\"/><path fill=\"#f2f2f2\" d=\"m31.126 36.785l10.537-10.64"
"a.665.665 0 0 1 1.137.468v7.308a4 4 0 0 1-4 4h-7.2a.667.667 0 0 1-.474-1.136\"/>"
"</g></svg>"
)
OPEN_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"64\" "
"viewBox=\"0 0 32 32\"><polygon fill=\"#0f518c\" points=\"30,30 2,30 2,2 17,2 17,6 "
"6,6 6,26 26,26 26,15 30,15\"/><polygon fill=\"#ed0049\" points=\"19,2 19,6 23.172,6 "
"14.586,14.586 17.414,17.414 26,8.828 26,13 30,13 30,2\"/></svg>"
)
REFRESH_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#2563eb\"/>"
"<path d=\"M16 20a9 9 0 0 1 16 3M32 28a9 9 0 0 1-16-3\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"2.8\" stroke-linecap=\"round\"/>"
"<path d=\"M16 14v7h7M32 34v-7h-7\" fill=\"none\" stroke=\"#fbbf24\" "
"stroke-width=\"2.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>"
)
CANCEL_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#ef4444\"/>"
"<path d=\"M17 17l14 14M31 17L17 31\" stroke=\"#fff\" stroke-width=\"3.2\" "
"stroke-linecap=\"round\"/></svg>"
)
CHECK_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#16a34a\"/>"
"<path d=\"M15 25l6 6 13-14\" fill=\"none\" stroke=\"#fff\" stroke-width=\"3.2\" "
"stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>"
)
WARN_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><path d=\"M24 8l18 32H6z\" fill=\"#f59e0b\"/>"
"<path d=\"M24 20v10\" stroke=\"#fff\" stroke-width=\"3.2\" stroke-linecap=\"round\"/>"
"<circle cx=\"24\" cy=\"35\" r=\"2.1\" fill=\"#fff\"/></svg>"
)
AUTO_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#7c3aed\"/>"
"<path d=\"M24 12l2.4 7.4H34l-6 4.4 2.3 7.2L24 26.8l-6.3 4.2 2.3-7.2-6-4.4h7.6z\" "
"fill=\"#fde68a\"/></svg>"
)
HOME_ICON = _svg(
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><path fill=\"#38bdf8\" d=\"M8 22L24 8l16 14v18a2 2 0 0 1-2 "
"2H10a2 2 0 0 1-2-2z\"/><path fill=\"#0369a1\" d=\"M20 40V28h8v12\"/></svg>"
)
def _t(key: str) -> str:
return _I18N.get(key) or key
def _parse_icon(value: Any) -> WoxImage:
if isinstance(value, WoxImage):
return value
text = str(value or "")
if text.startswith("svg:"):
return WoxImage.new_svg(text[4:])
if text.startswith("emoji:"):
return WoxImage.new_emoji(text[6:])
return PLUGIN_ICON
def _fmt_i18n(key: str, *args: Any) -> str:
template = _t(key)
for arg in args:
template = template.replace("%s", str(arg), 1)
return template.replace("%%", "%")
COMMANDS = ("start", "history", "ip", "result")
LIVE_RESULT_ID = "speedtest-live"
ACTION_START = "ns-start"
ACTION_CANCEL = "ns-cancel"
ACTION_COPY_SUMMARY = "ns-copy-summary"
DOWNLOAD_HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
),
"Accept": "*/*",
}
HTTP_DOWNLOAD_URLS = (
"https://mirrors.cloud.tencent.com/ubuntu/ls-lR.gz",
"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.0/min/vs/editor/editor.main.js",
"https://mirrors.aliyun.com/ubuntu/ls-lR.gz",
)
HTTP_UPLOAD_URLS = ("https://httpbin.org/post",)
HTTP_PING_URLS = (
"https://www.gstatic.com/generate_204",
"https://www.baidu.com",
"https://httpbin.org/get",
)
HTTP_DOWNLOAD_BYTES = 8 * 1024 * 1024
HTTP_UPLOAD_BYTES = 1 * 1024 * 1024
def _plugin_data_dir() -> str:
base = os.environ.get("WOX_DIRECTORY_USER_DATA") or os.path.join(
os.path.expanduser("~"), ".wox", "wox-user"
)
path = os.path.join(base, "cache", "netspeed-script-plugin")
os.makedirs(path, exist_ok=True)
return path
def _path(*parts: str) -> str:
return os.path.join(_plugin_data_dir(), *parts)
def _read_json(path: str) -> dict[str, Any]:
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _write_json(path: str, data: dict[str, Any]) -> None:
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", suffix=".tmp", dir=directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(data, handle, ensure_ascii=False, indent=2)
os.replace(tmp, path)
except Exception:
try:
os.remove(tmp)
except OSError:
pass
raise
def _state() -> dict[str, Any]:
with RUNTIME.state_lock:
if RUNTIME.state:
return dict(RUNTIME.state)
return _read_json(_path("state.json"))
def _write_state(data: dict[str, Any], persist: bool = True) -> None:
snapshot = dict(data)
with RUNTIME.state_lock:
RUNTIME.state = snapshot
if not persist:
return
try:
_write_json(_path("state.json"), snapshot)
except OSError:
pass
def _history() -> list[dict[str, Any]]:
data = _read_json(_path("history.json"))
items = data.get("items")
return items if isinstance(items, list) else []
def _max_history() -> int:
return RUNTIME.max_history
def _append_history(entry: dict[str, Any]) -> None:
items = _history()
items.append(entry)
limit = _max_history()
if len(items) > limit:
items = items[-limit:]
_write_json(_path("history.json"), {"items": items})
def _ssl_context() -> ssl.SSLContext:
context = ssl.create_default_context()
try:
context.minimum_version = ssl.TLSVersion.TLSv1_2
except Exception:
pass
return context
def _host_label(url: str) -> str:
host = urlparse(url).netloc or url
return host.split(":")[0]
def _http_open(url: str, data: bytes | None = None, timeout: int = 30):
headers = dict(DOWNLOAD_HEADERS)
if data is not None:
headers["Content-Type"] = "application/octet-stream"
request = Request(url, data=data, headers=headers, method="POST" if data is not None else "GET")
return urlopen(request, timeout=timeout, context=_ssl_context())
def _raise_if_cancelled() -> None:
if RUNTIME.cancel.is_set():
raise RuntimeError("cancelled")
def _measure_ping(state: dict[str, Any]) -> tuple[float, float]:
state["status"] = "running"
state["message"] = "Testing ping..."
_write_state(state)
samples: list[float] = []
for url in HTTP_PING_URLS:
_raise_if_cancelled()
try:
started = time.perf_counter()
with _http_open(url, timeout=8) as response:
response.read(64)
sample = (time.perf_counter() - started) * 1000
samples.append(sample)
state["ping"] = sample
_write_state(state, persist=False)
if len(samples) >= 3:
break
except Exception:
continue
if not samples:
return 0.0, 0.0
samples.sort()
ping = samples[len(samples) // 2]
jitter = (samples[-1] - samples[0]) / 2 if len(samples) > 1 else 0.0
state["ping"] = ping
_write_state(state, persist=False)
return ping, jitter
def _http_download(state: dict[str, Any]) -> tuple[float, str]:
last_error = "no download URL worked"
chunk_size = 64 * 1024
for url in HTTP_DOWNLOAD_URLS:
_raise_if_cancelled()
try:
state["message"] = "Testing download..."
state["download_progress"] = 0
_write_state(state)
started = time.perf_counter()
got = 0
last_ui = 0.0
with _http_open(url, timeout=45) as response:
while got < HTTP_DOWNLOAD_BYTES:
_raise_if_cancelled()
chunk = response.read(min(chunk_size, HTTP_DOWNLOAD_BYTES - got))
if not chunk:
break
got += len(chunk)
elapsed = time.perf_counter() - started
if elapsed > 0 and elapsed - last_ui >= 0.08:
last_ui = elapsed
state["download_progress"] = min(100.0, got / HTTP_DOWNLOAD_BYTES * 100)
state["download_speed"] = (got * 8) / elapsed / 1_000_000
_write_state(state, persist=False)
elapsed = time.perf_counter() - started
if got < 512 * 1024 or elapsed <= 0:
raise RuntimeError("download too small")
speed = (got * 8) / elapsed / 1_000_000
state["download_progress"] = 100.0
state["download_speed"] = speed
_write_state(state, persist=False)
return speed, url
except RuntimeError as exc:
if str(exc) == "cancelled":
raise
last_error = str(exc)
except Exception as exc:
last_error = str(exc)
raise RuntimeError(last_error)
def _http_upload(state: dict[str, Any]) -> float:
last_error = "no upload URL worked"
chunk_size = 64 * 1024
block = b"0" * chunk_size
for url in HTTP_UPLOAD_URLS:
_raise_if_cancelled()
parsed = urlparse(url)
host = parsed.hostname
if not host:
continue
port = parsed.port or (443 if parsed.scheme == "https" else 80)
path = parsed.path or "/"
if parsed.query:
path = f"{path}?{parsed.query}"
conn: http.client.HTTPConnection | None = None
try:
state["message"] = "Testing upload..."
state["upload_progress"] = 0
state["upload_speed"] = 0
_write_state(state)
if parsed.scheme == "https":
conn = http.client.HTTPSConnection(host, port, timeout=45, context=_ssl_context())
else:
conn = http.client.HTTPConnection(host, port, timeout=45)
conn.putrequest("POST", path)
conn.putheader("Content-Type", "application/octet-stream")
conn.putheader("Content-Length", str(HTTP_UPLOAD_BYTES))
for key, value in DOWNLOAD_HEADERS.items():
conn.putheader(key, value)
conn.endheaders()
sent = 0
started = time.perf_counter()
last_ui = 0.0
while sent < HTTP_UPLOAD_BYTES:
_raise_if_cancelled()
n = min(chunk_size, HTTP_UPLOAD_BYTES - sent)
conn.send(block[:n])
sent += n
elapsed = time.perf_counter() - started
if elapsed > 0 and elapsed - last_ui >= 0.08:
last_ui = elapsed
state["upload_progress"] = sent / HTTP_UPLOAD_BYTES * 100
state["upload_speed"] = (sent * 8) / elapsed / 1_000_000
_write_state(state, persist=False)
response = conn.getresponse()
response.read(256)
elapsed = time.perf_counter() - started
if elapsed <= 0:
raise RuntimeError("upload too fast to measure")
speed = (HTTP_UPLOAD_BYTES * 8) / elapsed / 1_000_000
state["upload_progress"] = 100
state["upload_speed"] = speed
_write_state(state, persist=False)
return speed
except RuntimeError as exc:
if str(exc) == "cancelled":
raise
last_error = str(exc)
except Exception as exc:
last_error = str(exc)
finally:
if conn is not None:
try:
conn.close()
except Exception:
pass
raise RuntimeError(last_error)
def _run_http_speedtest(state: dict[str, Any]) -> dict[str, Any]:
ping, jitter = _measure_ping(state)
download, source = _http_download(state)
try:
upload = _http_upload(state)
except RuntimeError as exc:
if str(exc) == "cancelled":
raise
upload = 0.0
host = _host_label(source)
return {
"download": download,
"upload": upload,
"ping": ping,
"download_jitter": jitter,
"download_latency": ping,
"upload_jitter": jitter,
"upload_latency": ping,
"server_id": 0,
"server_name": host,
"server_location": source,
"isp": "",
"result_url": "",
"external_ip": "",
"internal_ip": "",
"time": datetime.datetime.now().isoformat(timespec="seconds"),
}
def _num(value: Any) -> float:
try:
return float(value or 0)
except (TypeError, ValueError):
return 0.0
def _log_worker(message: str) -> None:
api = RUNTIME.api
loop = RUNTIME.loop
if api is None or loop is None:
return
async def _emit() -> None:
try:
await api.log(Context.new(), LogLevel.ERROR, message)
except Exception:
pass
try:
loop.call_soon_threadsafe(lambda: loop.create_task(_emit()))
except RuntimeError:
pass
def _worker_start() -> int:
try:
return _run_start_job()
except Exception as exc:
_log_worker(f"speed test worker crashed: {exc}")
current = _state()
if RUNTIME.cancel.is_set() or current.get("status") == "cancelled":
return 0
_write_state({**current, "status": "error", "error": str(exc)})
return 1
def _run_start_job() -> int:
state = {
"status": "starting",
"started_at": datetime.datetime.now().isoformat(timespec="seconds"),
"message": "Connecting...",
"download_progress": 0,
"upload_progress": 0,
"download_speed": 0,
"upload_speed": 0,
}
_write_state(state)
try:
result = _run_http_speedtest(state)
if RUNTIME.cancel.is_set() or _state().get("status") == "cancelled":
return 0
current = _state()
current["status"] = "done"
current["result"] = result
current["finished_at"] = datetime.datetime.now().isoformat(timespec="seconds")
_write_state(current)
_append_history(
{
"time": result.get("time"),
"download": result.get("download"),
"upload": result.get("upload"),
"ping": result.get("ping"),
"server_name": result.get("server_name"),
"result_url": result.get("result_url"),
}
)
return 0
except Exception as exc:
current = _state()
if RUNTIME.cancel.is_set() or current.get("status") == "cancelled" or str(exc) == "cancelled":
if current.get("status") != "cancelled":
_write_state({**current, "status": "cancelled"})
return 0
_log_worker(f"speed test failed: {exc}")
_write_state({**current, "status": "error", "error": str(exc)})
return 1
def _busy_statuses() -> set[str]:
return {"starting", "running"}
def _is_test_active(state: dict[str, Any]) -> bool:
worker = RUNTIME.worker
if worker is not None and worker.is_alive():
return True
if state.get("status") not in _busy_statuses():
return False
started = str(state.get("started_at") or "")
try:
started_at = datetime.datetime.fromisoformat(started)
except ValueError:
return False
return (datetime.datetime.now() - started_at).total_seconds() < 3
def _spawn_worker() -> None:
if RUNTIME.worker is not None and RUNTIME.worker.is_alive():
return
RUNTIME.cancel.clear()
RUNTIME.worker = threading.Thread(target=_worker_start, name="speedtest-start", daemon=True)
RUNTIME.worker.start()
def _fmt(value: Any, digits: int = 1) -> str:
return f"{_num(value):.{digits}f}"
def _relative_time(text: str) -> str:
if not text:
return ""
try:
moment = datetime.datetime.fromisoformat(text)
except ValueError:
return text
delta = datetime.datetime.now() - moment
seconds = int(delta.total_seconds())
if seconds < 5:
return _t("just_now")
if seconds < 60:
return f"{seconds}s"
if seconds < 3600:
return f"{seconds // 60}m"
if seconds < 86400:
return f"{seconds // 3600}h"
return moment.strftime("%Y-%m-%d %H:%M")
def _summary(result: dict[str, Any]) -> str:
return (
f"↓ {_fmt(result.get('download'))} Mbps "
f"↑ {_fmt(result.get('upload'))} Mbps "
f"ping {_fmt(result.get('ping'), 0)} ms"
)
def _command_query(trigger: str, command: str, search: str = "") -> str:
"""Build a query that Wox treats as an entered command (command + space)."""
search = (search or "").strip()
if search:
return f"{trigger} {command} {search}"
return f"{trigger} {command} "
def _copy_action(text: str, name: str = "i18n:action_copy") -> dict[str, Any]:
return {
"name": name,
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": text,
}
def _internal_ip() -> str:
try:
hostname = socket.gethostname()
for info in socket.getaddrinfo(hostname, None):
ip = info[4][0]
if isinstance(ip, str) and "." in ip and not ip.startswith("127."):
return ip
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("8.8.8.8", 80))
return sock.getsockname()[0]
finally:
sock.close()
except Exception:
return ""
def _public_ip() -> str:
endpoints = (
"https://api.ipify.org",
"https://ipv4.icanhazip.com",
)
for url in endpoints:
try:
request = Request(url, headers={"User-Agent": "Wox.Plugin.Speedtest/1.2"})
with urlopen(request, timeout=3) as response:
text = response.read().decode("utf-8", errors="ignore").strip()
if text:
return text
except (URLError, TimeoutError, OSError):
continue
return ""
def _to_tail(raw: dict[str, Any]) -> ResultTail:
return ResultTail(type=ResultTailType.TEXT, text=str(raw.get("text") or ""))
def _to_action(plugin: "SpeedtestPlugin", raw: dict[str, Any]) -> ResultAction:
action_id = str(raw.get("id") or "")
name = str(raw.get("name") or "")
icon = _parse_icon(raw.get("icon"))
prevent_hide = bool(raw.get("preventHideAfterAction"))
if action_id == "change-query":
query_text = str(raw.get("query") or "")
async def _change(ctx: Context, _ac: ActionContext, text: str = query_text) -> None:
await plugin.api.change_query(
ctx, ChangeQueryParam(query_type=QueryType.INPUT, query_text=text)
)
return ResultAction(
id=action_id,
name=name,
icon=icon,
prevent_hide_after_action=True,
action=_change,
)
if action_id == "copy-to-clipboard":
text = str(raw.get("text") or "")
async def _copy(ctx: Context, _ac: ActionContext, value: str = text) -> None:
await plugin.api.copy(ctx, CopyParams(type=CopyType.TEXT, text=value))
return ResultAction(id=action_id, name=name, icon=icon, action=_copy)
if action_id == "open-url":
url = str(raw.get("url") or "")
async def _open(_ctx: Context, _ac: ActionContext, target: str = url) -> None:
webbrowser.open(target)
return ResultAction(id=action_id, name=name, icon=icon, action=_open)
if action_id == ACTION_START:
return ResultAction(
id=ACTION_START,
name=name,
icon=icon,
prevent_hide_after_action=True,
action=plugin._on_start,
)
if action_id == ACTION_CANCEL:
return ResultAction(
id=ACTION_CANCEL,
name=name,
icon=icon,
prevent_hide_after_action=True,
action=plugin._on_cancel,
)
if action_id == ACTION_COPY_SUMMARY:
return ResultAction(
id=ACTION_COPY_SUMMARY,
name=name,
icon=icon,
action=plugin._on_copy_summary,
)
return ResultAction(
id=action_id,
name=name,
icon=icon,
prevent_hide_after_action=prevent_hide,
)
def _to_result(plugin: "SpeedtestPlugin", raw: dict[str, Any]) -> Result:
tails = [_to_tail(item) for item in raw.get("tails") or [] if isinstance(item, dict)]
actions = [_to_action(plugin, item) for item in raw.get("actions") or [] if isinstance(item, dict)]
if actions:
actions[0].is_default = True
return Result(
id=str(raw.get("id") or ""),
title=str(raw.get("title") or ""),
sub_title=str(raw.get("subtitle") or ""),
icon=_parse_icon(raw.get("icon")),
score=float(_num(raw.get("score"))),
tails=tails,
actions=actions,
)
class SpeedtestPlugin:
def __init__(self) -> None:
self.api: Any = None
self._watch_task: asyncio.Task[None] | None = None
async def init(self, ctx: Context, params: PluginInitParams) -> None:
self.api = params.api
RUNTIME.api = params.api
RUNTIME.loop = asyncio.get_running_loop()
RUNTIME.max_history = _parse_max_history(await self.api.get_setting(ctx, "max_history"))
self._recover_interrupted_test()
await self.api.on_setting_changed(ctx, self._on_setting_changed)
await self.api.on_unload(ctx, self._on_unload)
await self.api.log(ctx, LogLevel.INFO, "Speedtest single-file plugin initialized")
async def query(self, ctx: Context, query: Query) -> QueryResponse:
await self._load_i18n(ctx)
trigger = query.trigger_keyword or "speedtest"
command, search = self._normalize(query.command, query.search)
if command == "ip":
items = await asyncio.to_thread(self._ip_results)
else:
items = self._query_items(trigger, command, search)
if _is_test_active(_state()):
self._ensure_watch(ctx, LIVE_RESULT_ID)
return QueryResponse(results=[_to_result(self, item) for item in items])
async def _load_i18n(self, ctx: Context) -> None:
keys = (
"jitter",
"latency",
"ping",
"server",
"action_retest",
"progress_download",
"progress_upload",
"progress_ping",
"just_now",
)
for key in keys:
_I18N[key] = await self.api.get_translation(ctx, key)
async def _on_setting_changed(self, _ctx: Context, key: str, value: str) -> None:
if key == "max_history":
RUNTIME.max_history = _parse_max_history(value)
async def _on_unload(self, ctx: Context) -> None:
RUNTIME.cancel.set()
watch = self._watch_task
if watch is not None and not watch.done():
watch.cancel()
await self.api.log(ctx, LogLevel.INFO, "Speedtest plugin unloaded")
def _recover_interrupted_test(self) -> None:
stale_tmp = _path("state.json.tmp")
try:
if os.path.isfile(stale_tmp):
os.remove(stale_tmp)
except OSError:
pass
stored = _read_json(_path("state.json"))
if stored.get("status") in _busy_statuses():
stored["status"] = "error"
stored["error"] = "Previous test was interrupted. Press Enter to start again."
_write_state(stored)
elif stored:
with RUNTIME.state_lock:
RUNTIME.state = stored
async def _on_start(self, ctx: Context, ac: ActionContext) -> None:
result_id = ac.result_id or LIVE_RESULT_ID
if not _is_test_active(_state()):
self._begin_test()
await self.api.update_result(ctx, self._updatable_from_state(result_id, _state()))
await self._ensure_watch(ctx, result_id)
async def _on_cancel(self, ctx: Context, ac: ActionContext) -> None:
RUNTIME.cancel.set()
cancelled = {**_state(), "status": "cancelled"}
_write_state(cancelled)
await self.api.update_result(
ctx, self._updatable_from_state(ac.result_id or LIVE_RESULT_ID, cancelled)
)
async def _on_copy_summary(self, ctx: Context, _ac: ActionContext) -> None:
state = _state()
result = state.get("result") if isinstance(state.get("result"), dict) else None
text = _summary(result) if result else self._progress_text(state)
if text.startswith("i18n:"):
text = await self.api.get_translation(ctx, text[5:])
if text:
await self.api.copy(ctx, CopyParams(type=CopyType.TEXT, text=text))
def _begin_test(self) -> None:
RUNTIME.cancel.clear()
_write_state(
{
"status": "starting",
"started_at": datetime.datetime.now().isoformat(timespec="seconds"),
"message": "Connecting...",
"download_progress": 0,
"upload_progress": 0,
"download_speed": 0,
"upload_speed": 0,
}
)
_spawn_worker()
def _ensure_watch(self, ctx: Context, result_id: str) -> asyncio.Task[None]:
if self._watch_task is not None and not self._watch_task.done():
return self._watch_task
self._watch_task = asyncio.create_task(self._watch_live(ctx, result_id or LIVE_RESULT_ID))
return self._watch_task
async def _watch_live(self, ctx: Context, result_id: str) -> None:
last: tuple[Any, ...] | None = None
try:
while True:
state = _state()
fingerprint = self._progress_fingerprint(state)
if fingerprint != last:
last = fingerprint
await self.api.update_result(
ctx, self._updatable_from_state(result_id, state)
)
if not _is_test_active(state):
await self.api.update_result(
ctx, self._updatable_from_state(result_id, state)
)
return
await asyncio.sleep(0.12)
except asyncio.CancelledError:
return
except Exception as exc:
await self.api.log(ctx, LogLevel.ERROR, f"live speed test update failed: {exc}")
def _progress_fingerprint(self, state: dict[str, Any]) -> tuple[Any, ...]:
return (
str(state.get("status") or ""),
round(_num(state.get("download_progress")), 0),
round(_num(state.get("upload_progress")), 0),
round(_num(state.get("download_speed")), 2),
round(_num(state.get("upload_speed")), 2),
round(_num(state.get("ping")), 0),
str(state.get("error") or ""),
str(state.get("message") or ""),
bool(state.get("result")),
)
def _live_action_updates(self, state: dict[str, Any]) -> list[ResultAction]:
status = str(state.get("status") or "")
start_name = "i18n:action_retest" if status in {"done", "error"} else "i18n:action_start"
return [
ResultAction(
id=ACTION_START,
name=start_name,
icon=START_ICON,
prevent_hide_after_action=True,
is_default=True,
),
ResultAction(
id=ACTION_CANCEL,
name="i18n:action_cancel",
icon=CANCEL_ICON,
prevent_hide_after_action=True,
),
ResultAction(
id=ACTION_COPY_SUMMARY,
name="i18n:action_copy_summary",
icon=COPY_ICON,
),
]
def _updatable_from_state(self, result_id: str, state: dict[str, Any]) -> UpdatableResult:
title, subtitle, icon, tails = self._live_view(state)
return UpdatableResult(
id=result_id,
title=title,
sub_title=subtitle,
icon=icon,
tails=tails,
actions=self._live_action_updates(state),
)
def _live_view(
self, state: dict[str, Any]
) -> tuple[str, str, WoxImage, list[ResultTail]]:
status = str(state.get("status") or "")
if status == "cancelled":
return "i18n:cancelled", "i18n:cancelled_sub", CANCEL_ICON, []
if status == "error":
return "i18n:failed", str(state.get("error") or "i18n:retry"), WARN_ICON, []
if status == "done" and isinstance(state.get("result"), dict):
result = state["result"]
server_name = str(result.get("server_name") or "")
return _summary(result), server_name or "i18n:action_retest", PLUGIN_ICON, [
ResultTail(
type=ResultTailType.TEXT,
text=_relative_time(str(result.get("time") or "")),
)
]
title, subtitle = self._progress_title_subtitle(state)
return title, subtitle, PLUGIN_ICON, [self._speed_tail(state)]
def _speed_tail(self, state: dict[str, Any]) -> ResultTail:
return ResultTail(
type=ResultTailType.TEXT,
text=f"↓ {_fmt(state.get('download_speed'))} ↑ {_fmt(state.get('upload_speed'))}",
)
def _live_actions(self) -> list[dict[str, Any]]:
return [
{
"name": "i18n:action_start",
"id": ACTION_START,
"icon": START_ICON,
"preventHideAfterAction": True,
},
{
"name": "i18n:action_cancel",
"id": ACTION_CANCEL,
"icon": CANCEL_ICON,
"preventHideAfterAction": True,
},
{
"name": "i18n:action_copy_summary",
"id": ACTION_COPY_SUMMARY,
"icon": COPY_ICON,
},
]
def _query_items(self, trigger: str, command: str, search: str) -> list[dict[str, Any]]:
if command == "start":
return self._start_results(trigger, search)
if command == "result":
return self._result_results(trigger)
if command == "history":
return self._history_results(trigger)
return self._menu_results(trigger, search)
def _normalize(self, command: str, search: str) -> tuple[str, str]:
command = (command or "").strip().lower()
search = (search or "").strip()
if command in COMMANDS:
return command, search
return "", search
def _command_entries(self) -> list[tuple[str, str, str, WoxImage, int]]:
return [
("start", "i18n:menu_start", "i18n:menu_start_sub", START_ICON, 110),
("history", "i18n:menu_history", "i18n:menu_history_sub", HISTORY_ICON, 100),
]
def _command_score(self, name: str, needle: str, base: int) -> int:
if not needle:
return base
if name == needle:
return 300
if name.startswith(needle):
return 250
if needle in name:
return 180
return 0
def _menu_results(
self, trigger: str, search: str = ""
) -> list[dict[str, Any]]:
needle = search.lower()
if not needle:
state = _state()
if _is_test_active(state):
return self._progress_results(trigger, state) + [self._history_menu_item(trigger)]
return [self._start_menu_item(), self._history_menu_item(trigger)]
items: list[dict[str, Any]] = []
for name, title, subtitle, icon, base in self._command_entries():
score = self._command_score(name, needle, base)
if score <= 0:
continue
if name == "start":
items.append(self._start_menu_item(score=score, title=name))
else:
items.append(self._history_menu_item(trigger, score=score, title=name))
return items
def _start_menu_item(self, score: int = 110, title: str = "i18n:menu_start") -> dict[str, Any]:
return {
"id": LIVE_RESULT_ID,
"title": title,
"subtitle": "i18n:menu_start_sub",
"icon": START_ICON,
"score": score,
"actions": self._live_actions(),
}
def _history_menu_item(
self, trigger: str, score: int = 100, title: str = "i18n:menu_history"
) -> dict[str, Any]:
return {
"title": title,
"subtitle": "i18n:menu_history_sub",
"icon": HISTORY_ICON,
"score": score,
"actions": [
{
"name": "i18n:menu_history",
"id": "change-query",
"icon": HISTORY_ICON,
"query": _command_query(trigger, "history"),
"preventHideAfterAction": True,
}
],
}
def _start_results(self, trigger: str, search: str) -> list[dict[str, Any]]:
force = search.lower() in {"again", "now", "new", "retry"}
state = _state()
if _is_test_active(state):
return self._progress_results(trigger, state)
if state.get("status") == "cancelled" and not force:
title, subtitle, icon, _tails = self._live_view(state)
return [
{
"id": LIVE_RESULT_ID,
"title": title,
"subtitle": subtitle,
"icon": icon,
"score": 100,
"actions": self._live_actions(),
}
]
if state.get("status") == "error" and not force:
title, subtitle, icon, _tails = self._live_view(state)
return [
{
"id": LIVE_RESULT_ID,
"title": title,
"subtitle": subtitle,
"icon": icon,
"score": 100,
"actions": self._live_actions(),
}
]
if state.get("status") == "done" and state.get("result") and not force:
return self._result_results(trigger)
self._begin_test()
return self._progress_results(trigger, _state())
def _progress_results(
self, _trigger: str, state: dict[str, Any]
) -> list[dict[str, Any]]:
title, subtitle, icon, tails = self._live_view(state)
return [
{
"id": LIVE_RESULT_ID,
"title": title,
"subtitle": subtitle,
"icon": icon,
"score": 100,
"tails": [{"type": "text", "text": tail.text} for tail in tails],
"actions": self._live_actions(),
}
]
def _progress_title_subtitle(self, state: dict[str, Any]) -> tuple[str, str]:
progress = self._progress_text(state)
message = str(state.get("message") or "").lower()
if "download" in message or "upload" in message:
return progress, "i18n:testing"
return "i18n:testing", progress
def _progress_text(self, state: dict[str, Any]) -> str:
message = str(state.get("message") or "").lower()
if "upload" in message:
return _fmt_i18n(
"progress_upload",
_fmt(state.get("upload_speed")),
_fmt(state.get("upload_progress"), 0),
)
if "download" in message:
return _fmt_i18n(
"progress_download",
_fmt(state.get("download_speed")),
_fmt(state.get("download_progress"), 0),
)
ping = _num(state.get("ping"))
if ping > 0:
return f"{_t('ping')} {_fmt(ping, 0)} ms"
return "i18n:progress_ping"
def _result_results(self, trigger: str) -> list[dict[str, Any]]:
state = _state()
result = state.get("result") if isinstance(state.get("result"), dict) else None
if not result:
history = _history()
result = history[-1] if history else None
if not result:
return [
{
"title": "i18n:menu_start",
"subtitle": "i18n:hint_commands",
"icon": PLUGIN_ICON,
"score": 100,
"actions": [
{
"name": "i18n:action_start",
"id": "change-query",
"icon": START_ICON,
"query": _command_query(trigger, "start"),
"preventHideAfterAction": True,
}
],
}
]
summary = _summary(result)
server_name = str(result.get("server_name") or "")
location = str(result.get("server_location") or "")
isp = str(result.get("isp") or "")
server_sub = " • ".join(part for part in (location, isp) if part)
result_url = str(result.get("result_url") or "")
items: list[dict[str, Any]] = [
{
"title": summary,
"subtitle": server_name or "i18n:action_retest",
"icon": PLUGIN_ICON,
"score": 120,
"actions": [
{
"name": "i18n:action_retest",
"id": "change-query",
"icon": START_ICON,
"query": _command_query(trigger, "start", "again"),
"preventHideAfterAction": True,
},
_copy_action(summary, "i18n:action_copy_summary"),
],
},
{
"title": f"↓ {_fmt(result.get('download'), 2)} Mbps",
"subtitle": self._jitter_latency(
result.get("download_jitter"), result.get("download_latency")
),
"icon": DOWNLOAD_ICON,
"score": 110,
"actions": [_copy_action(f"{_fmt(result.get('download'), 2)} Mbps")],
},
{
"title": f"↑ {_fmt(result.get('upload'), 2)} Mbps",
"subtitle": self._jitter_latency(
result.get("upload_jitter"), result.get("upload_latency")
),
"icon": UPLOAD_ICON,
"score": 100,
"actions": [_copy_action(f"{_fmt(result.get('upload'), 2)} Mbps")],
},
{
"title": f"{_fmt(result.get('ping'), 0)} ms",
"subtitle": "i18n:ping",
"icon": PING_ICON,
"score": 90,
"actions": [_copy_action(f"{_fmt(result.get('ping'), 0)} ms")],
},
{
"title": server_name or "i18n:server",
"subtitle": server_sub,
"icon": SERVER_ICON,
"score": 80,
"actions": [_copy_action(" • ".join(part for part in (server_name, location, isp) if part))],
},
]
if result_url:
items.append(
{
"title": "i18n:view_online",
"subtitle": result_url,
"icon": OPEN_ICON,
"score": 70,
"actions": [
{
"name": "i18n:action_open_result",
"id": "open-url",
"icon": OPEN_ICON,
"url": result_url,
},
_copy_action(result_url),
],
}
)
return items
def _jitter_latency(self, jitter: Any, latency: Any) -> str:
return (
f"{_t('jitter')} {_fmt(jitter)} ms • "
f"{_t('latency')} {_fmt(latency)} ms"
)
def _history_results(self, trigger: str) -> list[dict[str, Any]]:
items = list(reversed(_history()))
if not items:
return [
{
"title": "i18n:history_empty",
"subtitle": "i18n:history_empty_sub",
"icon": HISTORY_ICON,
"score": 100,
"actions": [
{
"name": "i18n:action_start",
"id": "change-query",
"icon": START_ICON,
"query": _command_query(trigger, "start"),
"preventHideAfterAction": True,
}
],
}
]
results: list[dict[str, Any]] = []
for index, entry in enumerate(items):
summary = _summary(entry)
when = str(entry.get("time") or "")
url = str(entry.get("result_url") or "")
actions: list[dict[str, Any]] = [
_copy_action(summary, "i18n:action_copy_summary")
]
if url:
actions.append(
{
"name": "i18n:action_open_result",
"id": "open-url",
"icon": OPEN_ICON,
"url": url,
}
)
results.append(
{
"title": summary,
"subtitle": " • ".join(
part
for part in (
when,
f"{_t('ping')} {_fmt(entry.get('ping'), 0)} ms",
str(entry.get("server_name") or ""),
)
if part
),
"icon": HISTORY_ICON,
"score": 100 - index,
"tails": [{"type": "text", "text": _relative_time(when)}],
"actions": actions,
}
)
return results
def _ip_results(self) -> list[dict[str, Any]]:
internal = _internal_ip() or "i18n:ip_unknown"
public = _public_ip() or "i18n:ip_unknown"
return [
{
"title": "i18n:ip_internal",
"subtitle": internal,
"icon": HOME_ICON,
"score": 100,
"actions": [_copy_action(internal, "i18n:action_copy_ip")],
},
{
"title": "i18n:ip_public",
"subtitle": public if public != "i18n:ip_unknown" else "i18n:ip_unknown_sub",
"icon": IP_ICON,
"score": 90,
"actions": [_copy_action(public, "i18n:action_copy_ip")],
},
]
plugin = SpeedtestPlugin()
@qianlifeng

Copy link
Copy Markdown
Author
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment