14 Commits
Author SHA1 Message Date
YanJiu 97f2e8387b 合并 网络质量探测 1.1.3
将 GitHub main 合入 main。
署名:言灸
2026-11-21 21:47:50 +08:00
YanJiu d160814ca1 合并 网络质量探测 1.1.2
将 release/1.1.2 合入 main。
署名:言灸
2026-11-20 19:03:57 +08:00
YanJiu fa38806250 发布网络质量探测 1.1.2:保留 Windows 启动脚本的 CRLF 换行
署名:言炙
2026-11-20 19:02:26 +08:00
YanJiu 420eed64f7 发布网络质量探测 1.1.2:更新服务端安全检查
署名:言灸
2026-11-20 19:01:37 +08:00
YanJiu 1d35747b62 发布网络质量探测 1.1.2:更新服务端探测与节点源码
署名:言灸
2026-11-20 19:01:21 +08:00
YanJiu 3e912d4d3c 发布网络质量探测 1.1.2:更新服务端与 Linux 说明(一)
署名:言灸
2026-11-20 19:00:59 +08:00
YanJiu 3776ece7a4 发布网络质量探测 1.1.2:更新测试、版本号与协议说明
署名:言灸
2026-11-20 19:00:36 +08:00
YanJiu c1a60eef43 发布网络质量探测 1.1.2:更新客户端界面与版本文件
署名:言灸
2026-11-20 19:00:07 +08:00
YanJiu 3a6356f4d9 发布网络质量探测 1.1.2:更新客户端探测与说明文件(一)
署名:言灸
2026-11-20 18:59:35 +08:00
YanJiu 4c6472a504 发布网络质量探测 1.1.2:新增说明、选址源码并更新 README
署名:言灸
2026-11-20 18:59:20 +08:00
YanJiu 7cc4e042bd 发布网络质量探测 1.1.2:新增测试与节点选址源文件
署名:言灸
2026-11-20 18:59:06 +08:00
YanJiu d5da03d91b 发布网络质量探测 1.1.2:新增客户端源文件(三)
署名:言灸
2026-11-20 18:58:53 +08:00
YanJiu 6dcc2c4b89 发布网络质量探测 1.1.2:新增客户端源文件(二)
署名:言灸
2026-11-20 18:58:39 +08:00
YanJiu bc39956b6c 发布网络质量探测 1.1.2:新增客户端源文件(一)
署名:言灸
2026-11-20 18:58:20 +08:00
38 changed files with 176 additions and 2738 deletions

No files matched your search

+5 -5
View File
@@ -60,14 +60,14 @@ flutter run -d linux
1. 「探测来源」选「本机」或「远程节点」。 1. 「探测来源」选「本机」或「远程节点」。
2. 远程时点「管理节点」。名称自定。地址写成 `https://你的域名:8443` 这种控制地址,不要把口令写进地址。公开节点的口令留空;私有节点把节点口令填在这一栏。它和目标回显口令不是同一个。 2. 远程时点「管理节点」。名称自定。地址写成 `https://你的域名:8443` 这种控制地址,不要把口令写进地址。公开节点的口令留空;私有节点把节点口令填在这一栏。它和目标回显口令不是同一个。
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。HTTP 不单独填端口:写成 `https://www.cause-by-siky.top:2025/` 这样的完整网址,或只写主机名。只写主机名或 IP 时按 `http://主机/`,端口是 80。HTTP 超时默认 5000 毫秒。 3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。 4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。 本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。 远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。
端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。HTTP 模式不显示这个端口框。 端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。
已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。 已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。
@@ -104,9 +104,9 @@ cd server && go test -race ./...
cd client && flutter analyze && flutter test cd client && flutter analyze && flutter test
``` ```
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.4`,构建号 `7`。应用标识没有改。1.1.3 以及以后的版本必须用仓库里的 [client/android/keystore/debug.keystore](client/android/keystore/debug.keystore) 签名,这样后一版才能覆盖安装。1.1.2 的证书不同,升到 1.1.3 要先卸载。 Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.3`,构建号 `6`。应用标识没有改。1.1.3 以及以后的版本必须用仓库里的 [client/android/keystore/debug.keystore](client/android/keystore/debug.keystore) 签名,这样后一版才能覆盖安装。1.1.2 的证书不同,升到 1.1.3 要先卸载。
从 1.1.3 起,客户端可以检查更新,设置里可以关掉。从 1.1.4 起可以选择更新源,默认先问 YanJiu Git(`https://git.yanjiu.ltd/YanJiu/netquality/releases`),连不上再问 GitHub Releases。结果里会写明这次实际用的是哪一个。桌面安装包的规范名是 `linux-x64` 和 `windows-x64`,更新器也认以前的 `amd64`、`x86_64`、`aarch64`。1.1.3 的桌面更新器认不出单独的 `x64`。Linux 这一版另外提供内容相同的 `linux-x86_64`,1.1.3 的 Linux 会选中它并自己安装。Windows 桌面安装包要在 Windows 上构建,放上内容相同的 `windows-x86_64` 之后,1.1.3 的 Windows 也会自己安装;这份文件还没放上时,Windows 仍要自己安装。1.1.2 没有自更新,升到 1.1.4 仍要自己安装。已经发布的 1.1.2 和 1.1.3 安装包也没有在线更新历史。Windows 和 Linux 会把新文件写回当前安装目录。Android 会弹出系统安装确认,这一步不能跳过。没有真正的新版本时,可以用环境变量 `NQ_UPDATE_GITHUB_API` 和 `NQ_UPDATE_GITEA_API` 指向一份同样格式的测试响应。 从 1.1.3 起,客户端启动后会检查更新,设置里可以关掉。先问 GitHub Releases,连不上再问 `https://git.yanjiu.ltd/YanJiu/netquality/releases`。1.1.2 没有这个功能,所以 1.1.2 升到 1.1.3 仍然要自己安装。Windows 和 Linux 会把新文件写回当前安装目录。Android 会弹出系统安装确认,这一步不能跳过。没有真正的新版本时,可以用环境变量 `NQ_UPDATE_GITHUB_API` 和 `NQ_UPDATE_GITEA_API` 指向一份同样格式的测试响应。
中心也是这个 Go 程序。示例配置在 [server/example-center](server/example-center),里面的口令都是占位。本机可以这样看目录: 中心也是这个 Go 程序。示例配置在 [server/example-center](server/example-center),里面的口令都是占位。本机可以这样看目录:
@@ -118,7 +118,7 @@ go build -o netquality-reflector .
客户端点「一键添加服务器」,中心地址填 `http://127.0.0.1:8443`,账号 `lab`,口令 `example-token`。这只适合本机确认功能。真正给别人用时,控制端口要走 HTTPS。 客户端点「一键添加服务器」,中心地址填 `http://127.0.0.1:8443`,账号 `lab`,口令 `example-token`。这只适合本机确认功能。真正给别人用时,控制端口要走 HTTPS。
这一版的说明在 [docs/release-notes/1.1.4.md](docs/release-notes/1.1.4.md)。 这一版的说明在 [docs/release-notes/1.1.3.md](docs/release-notes/1.1.3.md)。
## 许可 ## 许可
+1 -1
View File
@@ -7,4 +7,4 @@ flutter pub get
flutter run -d linux flutter run -d linux
``` ```
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.4。HTTP 的目标是完整网址,或只写主机名(按 http、端口 80),不再单独填端口,超时默认 5000 毫秒。本机 HTTP 探测需要旁边有 `netquality-reflector`,或设置 `NQ_PROBE_HELPER`;找不到或启动不了时会立刻说明,并建议改用远程节点。Android 安装包不包含这个程序。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。 默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.3。本机 HTTP 探测需要旁边有 `netquality-reflector`,或设置 `NQ_PROBE_HELPER`。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
+3 -59
View File
@@ -11,70 +11,20 @@ class ReleaseEntry {
required this.source, required this.source,
required this.points, required this.points,
this.published, this.published,
this.tag,
}); });
final String version; final String version;
final String title; final String title;
final String source; final String source;
final String? published; final String? published;
/// Release tag, when this entry came from a forge. Bundled entries omit it.
final String? tag;
final List<String> points; final List<String> points;
Map<String, Object?> toJson() => {
'version': version,
'title': title,
'source': source,
'published': published,
'tag': tag,
'points': points,
};
factory ReleaseEntry.fromJson(Map<String, dynamic> json) {
final rawPoints = json['points'];
final points = <String>[];
if (rawPoints is List) {
for (final item in rawPoints) {
if (item is String && item.trim().isNotEmpty) {
points.add(item);
}
}
}
return ReleaseEntry(
version: json['version'] is String ? json['version'] as String : '',
title: json['title'] is String ? json['title'] as String : '',
source: json['source'] is String ? json['source'] as String : '',
published: json['published'] is String
? json['published'] as String
: null,
tag: json['tag'] is String ? json['tag'] as String : null,
points: points,
);
}
} }
const releaseHistory = <ReleaseEntry>[ const releaseHistory = <ReleaseEntry>[
ReleaseEntry(
version: '1.1.4',
title: '网络质量探测 1.1.4',
published: '2026-11-27',
source:
'Git 标签 v1.1.4,以及仓库 docs/release-notes/1.1.4.md。署名言灸。',
points: [
'设置里可以选择更新源,默认是 YanJiu Git,也可以改成 GitHub。检查和下载都先用选中的源,连不上再试另一个,结果里会写明这次实际用的是哪一个。',
'「更新历史」会读取所选源的发布列表,包括比当前安装更新的版本,并在本机留一份。网络失败时用上次保存的列表,没有保存过再用安装包里的说明,并标明可能不是最新。已经发出的 1.1.2 和 1.1.3 没有这份同步。',
'表单里被省略号截断的提示可以点开看全文,再点一次收回。本来就显示得下的短句不用点。',
'HTTP 目标填完整网址,或只写主机名、IP。只写主机名时按 http 和端口 80,不再单独填端口。超时默认 5000 毫秒。本机找不到探测引擎时会立刻说明,并建议改用远程节点。',
'桌面自更新认得 linux-x64、windows-x64,也仍然接受 amd64、x86_64、aarch64。Linux 安装包另有内容相同的 linux-x86_64,1.1.3 的 Linux 会选中它并自己安装。Windows 要等内容相同的 windows-x86_64 放上以后,1.1.3 的 Windows 才会自己安装。1.1.2 没有更新器,仍要手动安装。名字里带 server 或 reflector 的包不会被选中。',
],
),
ReleaseEntry( ReleaseEntry(
version: '1.1.3', version: '1.1.3',
title: '网络质量探测 1.1.3', title: '网络质量探测 1.1.3',
published: '2026-11-21', source: '仓库 docs/release-notes/1.1.3.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
source: 'Git 标签 v1.1.3,以及 GitHub Release「网络质量探测 1.1.3」(发布于 2026-11-21)。',
points: [ points: [
'可以自动检查更新,也能在设置里关掉。先问 GitHub,连不上再用备用 Git。1.1.2 没有这个功能,升到 1.1.3 仍要手动安装。从这一版起,新版本才会自己下载并覆盖安装。', '可以自动检查更新,也能在设置里关掉。先问 GitHub,连不上再用备用 Git。1.1.2 没有这个功能,升到 1.1.3 仍要手动安装。从这一版起,新版本才会自己下载并覆盖安装。',
'Windows 和 Linux 覆盖进现有安装目录。设置、已保存的节点、口令和探测历史仍在应用自己的数据目录里,不会被安装包清掉。', 'Windows 和 Linux 覆盖进现有安装目录。设置、已保存的节点、口令和探测历史仍在应用自己的数据目录里,不会被安装包清掉。',
@@ -87,8 +37,7 @@ const releaseHistory = <ReleaseEntry>[
ReleaseEntry( ReleaseEntry(
version: '1.1.2', version: '1.1.2',
title: '网络质量探测 1.1.2', title: '网络质量探测 1.1.2',
published: '2026-11-20', source: '仓库 docs/release-notes/1.1.2.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
source: 'Git 标签 v1.1.2,以及 GitHub Release「网络质量探测 1.1.2」(发布于 2026-11-20)。',
points: [ points: [
'可以修改已有远程节点的名称、控制地址和口令。节点编号和当前选择保持不变。口令留空表示不改,界面不显示已经保存的口令。', '可以修改已有远程节点的名称、控制地址和口令。节点编号和当前选择保持不变。口令留空表示不改,界面不显示已经保存的口令。',
'端口框标明当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。', '端口框标明当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。',
@@ -116,9 +65,4 @@ const releaseHistory = <ReleaseEntry>[
]; ];
const releaseHistoryNote = const releaseHistoryNote =
'仓库里公开的版本标签有 v1.1.1、v1.1.2、v1.1.3 和 v1.1.4。1.1.1 的发布说明提到过更早的发包行为,但没有单独的标签或 Release,所以这里不写成另一个版本。'; '仓库里目前公开的版本标签只有 v1.1.1。1.1.1 的发布说明提到过更早的发包行为,但没有单独的标签或 Release,所以这里不写成另一个版本。';
/// Already shipped installers cannot grow this screen. The sentence stays
/// visible so the app does not imply that 1.1.2 or 1.1.3 already sync notes.
const onlineHistoryLimitNote =
'已经发布的 1.1.2 和 1.1.3 安装包没有在线更新历史。那些版本不会自己同步以后的发布说明,需要先安装包含这个功能的版本。';
-103
View File
@@ -1,103 +0,0 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
/// An HTTP probe target. The separate port field is not used.
class HttpTarget {
const HttpTarget({
required this.url,
required this.host,
required this.port,
required this.scheme,
});
/// Canonical absolute URL. Default ports are omitted.
final String url;
/// Hostname or IP, without brackets.
final String host;
final int port;
final String scheme;
}
HttpTarget? parseHttpTarget(String raw) => readHttpTarget(raw).target;
String? httpTargetError(String raw) => readHttpTarget(raw).error;
({HttpTarget? target, String? error}) readHttpTarget(String raw) {
final text = raw.trim();
if (text.isEmpty) {
return (target: null, error: '请填写目标地址');
}
if (text.contains('://')) {
final uri = Uri.tryParse(text);
if (uri == null) {
return (target: null, error: _portOrUrlError(text));
}
if ((uri.scheme != 'http' && uri.scheme != 'https') || uri.host.isEmpty) {
return (target: null, error: 'HTTP 目标需要是主机名或 http/https 网址');
}
return _fromUri(uri);
}
final cut = _splitCut(text);
final hostport = cut < 0 ? text : text.substring(0, cut);
final rest = cut < 0 ? '' : text.substring(cut);
if (hostport.isEmpty) {
return (target: null, error: 'HTTP 目标需要是主机名或 http/https 网址');
}
var bracketed = hostport;
if (':'.allMatches(hostport).length >= 2 && !hostport.startsWith('[')) {
bracketed = '[$hostport]';
}
final uri = Uri.tryParse('http://$bracketed$rest');
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
return (target: null, error: _portOrUrlError(text));
}
return _fromUri(uri);
}
({HttpTarget? target, String? error}) _fromUri(Uri uri) {
final port = uri.hasPort ? uri.port : (uri.scheme == 'https' ? 443 : 80);
if (port < 1 || port > 65535) {
return (target: null, error: '端口需要在 1 到 65535 之间');
}
final built = Uri(
scheme: uri.scheme,
host: uri.host,
port: port,
path: uri.path.isEmpty ? '/' : uri.path,
query: uri.hasQuery ? uri.query : null,
fragment: uri.hasFragment ? uri.fragment : null,
);
return (
target: HttpTarget(
url: built.toString(),
host: uri.host,
port: port,
scheme: uri.scheme,
),
error: null,
);
}
int _splitCut(String text) {
final slash = text.indexOf('/');
final query = text.indexOf('?');
if (slash < 0) {
return query;
}
if (query < 0) {
return slash;
}
return slash < query ? slash : query;
}
String _portOrUrlError(String text) {
final match = RegExp(r':(\d+)(?=[/?#]|$)').firstMatch(text);
if (match != null) {
final port = int.tryParse(match.group(1)!);
if (port == null || port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间';
}
}
return 'HTTP 目标需要是主机名或 http/https 网址';
}
+8 -17
View File
@@ -23,29 +23,20 @@ String portHint(ProbeProfile profile) {
return '合作反射 TCP 默认 19090'; return '合作反射 TCP 默认 19090';
case 'nq-udp': case 'nq-udp':
return '合作反射 UDP 默认 19091'; return '合作反射 UDP 默认 19091';
case 'http':
return 'HTTP 默认 443(https)或 80(http)';
default: default:
return '${profile.label} 默认 ${profile.port}'; return '${profile.label} 默认 ${profile.port}';
} }
} }
const nonHttpTimeoutMs = 1000; /// Default port for an HTTP target. A full http:// URL uses 80. Anything else uses 443.
const httpTimeoutMs = 5000; int httpDefaultPort(String target) {
final text = target.trim().toLowerCase();
int timeoutDefaultFor(String profileId) => if (text.startsWith('http://')) {
profileId == 'http' ? httpTimeoutMs : nonHttpTimeoutMs; return 80;
/// An empty timeout, or one that is still the previous profile's default,
/// follows the newly selected profile. A value the user typed stays.
String timeoutAfterProfileChange({
required String current,
required int previousDefault,
required int nextDefault,
}) {
final trimmed = current.trim();
if (trimmed.isEmpty || int.tryParse(trimmed) == previousDefault) {
return '$nextDefault';
} }
return current; return 443;
} }
const portHelperText = const portHelperText =
+2 -1
View File
@@ -68,7 +68,8 @@ class ProbeProfile {
id: 'http', id: 'http',
label: 'HTTP', label: 'HTTP',
port: 443, port: 443,
blurb: '按 HTTP 请求测量。目标填完整网址;只填主机名或 IP 时按 http,端口 80。默认优先 HTTP/2,服务器不支持时降到 HTTP/1.1。强制的版本不支持就失败,不会偷偷降级。4xx 和 5xx 会显示状态码,不算丢包。', blurb:
'按 HTTP 请求测量。默认优先 HTTP/2,服务器不支持时降到 HTTP/1.1。强制的版本不支持就失败,不会偷偷降级。4xx 和 5xx 会显示状态码,不算丢包。',
rateLabel: '失败率', rateLabel: '失败率',
); );
static const customUdp = ProbeProfile( static const customUdp = ProbeProfile(
+12 -32
View File
@@ -1,7 +1,6 @@
import 'dart:convert'; import 'dart:convert';
import '../protocol/probe_packet.dart'; import '../protocol/probe_packet.dart';
import 'http_target.dart';
import 'ip_family.dart'; import 'ip_family.dart';
import 'probe_profile.dart'; import 'probe_profile.dart';
@@ -67,9 +66,7 @@ class RemoteNode {
baseUrl: confidential baseUrl: confidential
? '' ? ''
: (json['baseUrl'] is String ? json['baseUrl'] as String : ''), : (json['baseUrl'] is String ? json['baseUrl'] as String : ''),
visibility: json['visibility'] is String visibility: json['visibility'] is String ? json['visibility'] as String : '',
? json['visibility'] as String
: '',
fromCenter: json['fromCenter'] == true, fromCenter: json['fromCenter'] == true,
confidential: confidential, confidential: confidential,
centerLinkId: json['centerLinkId'] is String centerLinkId: json['centerLinkId'] is String
@@ -91,7 +88,11 @@ class CenterLink {
final String url; final String url;
final String account; final String account;
Map<String, Object?> toJson() => {'id': id, 'url': url, 'account': account}; Map<String, Object?> toJson() => {
'id': id,
'url': url,
'account': account,
};
factory CenterLink.fromJson(Map<String, dynamic> json) { factory CenterLink.fromJson(Map<String, dynamic> json) {
return CenterLink( return CenterLink(
@@ -120,7 +121,6 @@ class SessionConfig {
this.allowIPv4 = true, this.allowIPv4 = true,
this.allowIPv6 = true, this.allowIPv6 = true,
this.autoUpdate = true, this.autoUpdate = true,
this.updateSource = 'gitea',
this.httpVersion = 'auto', this.httpVersion = 'auto',
this.httpResolve = '', this.httpResolve = '',
this.httpMethod = 'GET', this.httpMethod = 'GET',
@@ -164,9 +164,6 @@ class SessionConfig {
final bool allowIPv4; final bool allowIPv4;
final bool allowIPv6; final bool allowIPv6;
final bool autoUpdate; final bool autoUpdate;
/// `gitea` (YanJiu Git, the default) or `github`.
final String updateSource;
final String httpVersion; final String httpVersion;
final String httpResolve; final String httpResolve;
final String httpMethod; final String httpMethod;
@@ -188,10 +185,6 @@ class SessionConfig {
ProbeProfile get profile => ProbeProfile.byId(profileId); ProbeProfile get profile => ProbeProfile.byId(profileId);
/// Parsed HTTP target. Null for other profiles, or when the text is invalid.
HttpTarget? get httpTarget =>
profileId == 'http' ? parseHttpTarget(host) : null;
RemoteNode? get node { RemoteNode? get node {
for (final item in nodes) { for (final item in nodes) {
if (item.id == nodeId) { if (item.id == nodeId) {
@@ -202,15 +195,7 @@ class SessionConfig {
} }
String? validate() { String? validate() {
final http = profileId == 'http' ? readHttpTarget(host) : null; final family = familyRefusal(host, v4: allowIPv4, v6: allowIPv6);
if (http != null && http.error != null) {
return http.error;
}
final family = familyRefusal(
http?.target?.host ?? host,
v4: allowIPv4,
v6: allowIPv6,
);
if (family != null) { if (family != null) {
return family; return family;
} }
@@ -224,7 +209,7 @@ class SessionConfig {
return resolveFamily.replaceFirst('目标', '指定解析'); return resolveFamily.replaceFirst('目标', '指定解析');
} }
} }
if (profileId != 'http' && host.trim().isEmpty) { if (host.trim().isEmpty) {
return '请填写目标地址'; return '请填写目标地址';
} }
if (profileId == 'http') { if (profileId == 'http') {
@@ -239,7 +224,8 @@ class SessionConfig {
if (!versions.contains(httpVersion)) { if (!versions.contains(httpVersion)) {
return 'HTTP 版本需要是自动、1.1、2 或 3'; return 'HTTP 版本需要是自动、1.1、2 或 3';
} }
} else if (port < 1 || port > 65535) { }
if (port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间'; return '端口需要在 1 到 65535 之间';
} }
final minInterval = remote ? 200 : 100; final minInterval = remote ? 200 : 100;
@@ -310,7 +296,6 @@ class SessionConfig {
'allowIPv4': allowIPv4, 'allowIPv4': allowIPv4,
'allowIPv6': allowIPv6, 'allowIPv6': allowIPv6,
'autoUpdate': autoUpdate, 'autoUpdate': autoUpdate,
'updateSource': updateSource == 'github' ? 'github' : 'gitea',
'httpVersion': httpVersion, 'httpVersion': httpVersion,
'httpResolve': httpResolve, 'httpResolve': httpResolve,
'httpMethod': httpMethod, 'httpMethod': httpMethod,
@@ -348,16 +333,11 @@ class SessionConfig {
dnsName: json['dnsName'] is String dnsName: json['dnsName'] is String
? json['dnsName'] as String ? json['dnsName'] as String
: defaults.dnsName, : defaults.dnsName,
payloadHex: json['payloadHex'] is String payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
? json['payloadHex'] as String
: '',
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '', expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
allowIPv4: json['allowIPv4'] is bool ? json['allowIPv4'] as bool : true, allowIPv4: json['allowIPv4'] is bool ? json['allowIPv4'] as bool : true,
allowIPv6: json['allowIPv6'] is bool ? json['allowIPv6'] as bool : true, allowIPv6: json['allowIPv6'] is bool ? json['allowIPv6'] as bool : true,
autoUpdate: json['autoUpdate'] is bool autoUpdate: json['autoUpdate'] is bool ? json['autoUpdate'] as bool : true,
? json['autoUpdate'] as bool
: true,
updateSource: json['updateSource'] == 'github' ? 'github' : 'gitea',
httpVersion: json['httpVersion'] is String httpVersion: json['httpVersion'] is String
? json['httpVersion'] as String ? json['httpVersion'] as String
: 'auto', : 'auto',
+3 -7
View File
@@ -34,14 +34,11 @@ class TargetEntry {
} }
String get label { String get label {
if (profileId == 'http') {
final where = httpUrl.trim().isNotEmpty ? httpUrl.trim() : host.trim(); final where = httpUrl.trim().isNotEmpty ? httpUrl.trim() : host.trim();
final methodText = method.trim().isNotEmpty final methodText = profileId == 'http' && method.trim().isNotEmpty
? ' ${method.trim().toUpperCase()}' ? ' ${method.trim().toUpperCase()}'
: ''; : '';
return '$where · HTTP$methodText'; return '$where:$port · $profileId$methodText';
}
return '${host.trim()}:$port · $profileId';
} }
Map<String, Object?> toJson() => { Map<String, Object?> toJson() => {
@@ -97,8 +94,7 @@ class TargetHistory {
TargetHistory clear() => empty; TargetHistory clear() => empty;
String encode() => String encode() => jsonEncode(entries.map((entry) => entry.toJson()).toList());
jsonEncode(entries.map((entry) => entry.toJson()).toList());
factory TargetHistory.decode(String raw) { factory TargetHistory.decode(String raw) {
if (raw.trim().isEmpty) { if (raw.trim().isEmpty) {
+3 -52
View File
@@ -7,32 +7,9 @@ import 'dart:io';
import '../metrics/sample_book.dart'; import '../metrics/sample_book.dart';
const helperMissingNote = const helperMissingNote =
'本机 HTTP 探测需要 Go 程序 netquality-reflector,现在没有找到,所以探测没有开始。请把探测来源改成「远程节点」。桌面端也可以把 netquality-reflector 放在程序旁边,或设置环境变量 NQ_PROBE_HELPER。'; '本机 HTTP 探测使用和节点相同的 Go 引擎。请把 netquality-reflector 放在程序旁边,或设置环境变量 NQ_PROBE_HELPER。远程节点不受影响。';
const helperStartFailedNote =
'本机 HTTP 探测找到了 netquality-reflector,但没有启动成功,所以探测没有开始。请把探测来源改成「远程节点」。桌面端也可以检查这个程序能否运行,或改用环境变量 NQ_PROBE_HELPER。';
/// Thrown before any sample is recorded when the local HTTP engine cannot run.
class LocalHttpHelperException implements Exception {
const LocalHttpHelperException(this.message);
final String message;
}
bool isLocalHttpHelperFailure(Outcome outcome) {
return outcome.status == Outcome.error &&
(outcome.note == helperMissingNote ||
outcome.note == helperStartFailedNote);
}
/// Tests set this to skip the search next to the executable.
String? Function()? locateProbeHelperOverride;
String? locateProbeHelper() { String? locateProbeHelper() {
final override = locateProbeHelperOverride;
if (override != null) {
return override();
}
final env = Platform.environment['NQ_PROBE_HELPER']; final env = Platform.environment['NQ_PROBE_HELPER'];
if (env != null && env.isNotEmpty && File(env).existsSync()) { if (env != null && env.isNotEmpty && File(env).existsSync()) {
return env; return env;
@@ -50,23 +27,6 @@ String? locateProbeHelper() {
return null; return null;
} }
/// Null when the local Go helper can be started. Otherwise a Chinese reason
/// that already tells the user to switch the source to a remote node.
Future<String?> localHttpBlockedReason({String? binary}) async {
final path = binary ?? locateProbeHelper();
if (path == null || path.isEmpty || !File(path).existsSync()) {
return helperMissingNote;
}
try {
final process = await Process.start(path, const ['-mode', 'helper']);
process.kill();
process.exitCode.ignore();
return null;
} catch (_) {
return helperStartFailedNote;
}
}
Outcome outcomeFromHelper(String line) { Outcome outcomeFromHelper(String line) {
try { try {
final decoded = jsonDecode(line); final decoded = jsonDecode(line);
@@ -147,23 +107,14 @@ class HttpHelperSession {
return null; return null;
} }
final path = binary ?? locateProbeHelper(); final path = binary ?? locateProbeHelper();
if (path == null || path.isEmpty || !File(path).existsSync()) { if (path == null) {
return const Outcome( return const Outcome(
status: Outcome.error, status: Outcome.error,
kind: Outcome.query, kind: Outcome.query,
note: helperMissingNote, note: helperMissingNote,
); );
} }
final Process process; final process = await Process.start(path, const ['-mode', 'helper']);
try {
process = await Process.start(path, const ['-mode', 'helper']);
} catch (_) {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: helperStartFailedNote,
);
}
_process = process; _process = process;
process.stdout process.stdout
.transform(utf8.decoder) .transform(utf8.decoder)
+6 -42
View File
@@ -11,7 +11,6 @@ import '../models/probe_profile.dart';
import '../models/session_config.dart'; import '../models/session_config.dart';
import '../ui/address_text.dart'; import '../ui/address_text.dart';
import 'endpoint_picker.dart'; import 'endpoint_picker.dart';
import 'http_helper.dart';
import 'probe_loop.dart'; import 'probe_loop.dart';
import 'remote_client.dart'; import 'remote_client.dart';
@@ -227,13 +226,6 @@ class ProbeController extends ChangeNotifier {
notifyListeners(); notifyListeners();
return; return;
} }
if (!config.remote && config.profileId == 'http') {
final helperProblem = await localHttpBlockedReason();
if (helperProblem != null) {
_rejectSetup(helperProblem);
return;
}
}
await stop(); await stop();
_nodeToken = nodeToken; _nodeToken = nodeToken;
_remoteMode = config.remote; _remoteMode = config.remote;
@@ -245,9 +237,6 @@ class ProbeController extends ChangeNotifier {
..start(); ..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机'; final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
final profile = ProbeProfile.byId(config.profileId); final profile = ProbeProfile.byId(config.profileId);
final httpTarget = config.httpTarget;
final target = httpTarget?.url ?? config.host.trim();
final port = httpTarget?.port ?? config.port;
view = ProbeView( view = ProbeView(
running: true, running: true,
phase: '探测中', phase: '探测中',
@@ -261,7 +250,7 @@ class ProbeController extends ChangeNotifier {
sessionId: session, sessionId: session,
profileId: config.profileId, profileId: config.profileId,
elapsed: Duration.zero, elapsed: Duration.zero,
targetHost: httpTarget?.url ?? '$target:$port', targetHost: '${config.host.trim()}:${config.port}',
profileLabel: profile.label, profileLabel: profile.label,
startedAt: _startedAt, startedAt: _startedAt,
); );
@@ -281,9 +270,7 @@ class ProbeController extends ChangeNotifier {
baseUrl = link.url; baseUrl = link.url;
token = nodeToken; token = nodeToken;
} }
if (config.profileId == 'http' || if (config.profileId == 'http' || !config.allowIPv4 || !config.allowIPv6) {
!config.allowIPv4 ||
!config.allowIPv6) {
if (!selected.confidential) { if (!selected.confidential) {
final info = await fetchNodeInfo(baseUrl); final info = await fetchNodeInfo(baseUrl);
final upgrade = remoteUpgradeMessage( final upgrade = remoteUpgradeMessage(
@@ -303,8 +290,8 @@ class ProbeController extends ChangeNotifier {
baseUrl: baseUrl, baseUrl: baseUrl,
nodeToken: token, nodeToken: token,
body: ProbeBody( body: ProbeBody(
target: target, target: config.host.trim(),
port: port, port: config.port,
profile: config.profileId, profile: config.profileId,
intervalMs: config.intervalMs, intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs, timeoutMs: config.timeoutMs,
@@ -360,8 +347,8 @@ class ProbeController extends ChangeNotifier {
_local = loop; _local = loop;
await loop.run( await loop.run(
request: ProbeRequest( request: ProbeRequest(
host: target, host: config.host.trim(),
port: port, port: config.port,
profileId: config.profileId, profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs), interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs), timeout: Duration(milliseconds: config.timeoutMs),
@@ -386,8 +373,6 @@ class ProbeController extends ChangeNotifier {
); );
} }
_finish(generation, '已停止'); _finish(generation, '已停止');
} on LocalHttpHelperException catch (error) {
_rejectSetup(error.message, generation: generation);
} on RemoteException catch (error) { } on RemoteException catch (error) {
_finish(generation, '出错', banner: error.message); _finish(generation, '出错', banner: error.message);
} on Object { } on Object {
@@ -431,27 +416,6 @@ class ProbeController extends ChangeNotifier {
} }
} }
void _rejectSetup(String message, {int? generation}) {
if (generation != null && generation != _token) {
return;
}
_clock.stop();
_tick?.cancel();
view = view.copyWith(
running: false,
phase: '无法开始',
banner: message,
note: '',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
elapsed: Duration.zero,
clearReport: true,
clearTrying: true,
);
notifyListeners();
}
void _finish(int generation, String phase, {String? banner}) { void _finish(int generation, String phase, {String? banner}) {
if (generation != _token || !view.running) { if (generation != _token || !view.running) {
return; return;
-5
View File
@@ -119,11 +119,6 @@ class ProbeLoop {
if (!countsAfterStop(outcome, cancelled: cancelled())) { if (!countsAfterStop(outcome, cancelled: cancelled())) {
break; break;
} }
if (request.profileId == 'http' &&
outcome != null &&
isLocalHttpHelperFailure(outcome)) {
throw LocalHttpHelperException(outcome.note);
}
var commit = <Outcome>[outcome!]; var commit = <Outcome>[outcome!];
if (_usesDatagram(request.profileId) && _picker != null) { if (_usesDatagram(request.profileId) && _picker != null) {
_ledger ??= SelectionLedger(_picker!.candidates.length); _ledger ??= SelectionLedger(_picker!.candidates.length);
+1 -3
View File
@@ -6,7 +6,6 @@ import 'package:flutter/material.dart';
import '../center/catalog.dart'; import '../center/catalog.dart';
import '../center/center_client.dart'; import '../center/center_client.dart';
import '../models/session_config.dart'; import '../models/session_config.dart';
import 'expandable_hint.dart';
class AddedCenter { class AddedCenter {
const AddedCenter({ const AddedCenter({
@@ -141,10 +140,9 @@ class _CenterAddDialogState extends State<_CenterAddDialog> {
obscureText: true, obscureText: true,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: '密码', labelText: '密码',
hintText: '还没有口令时填写', hintText: '中心要求密码、手里还没有口令时填写',
), ),
), ),
const ExpandableHint(text: '中心要求密码、手里还没有口令时填写。'),
if (_hint != null) ...[ if (_hint != null) ...[
const SizedBox(height: 8), const SizedBox(height: 8),
Text(_hint!, style: const TextStyle(color: Color(0xFF9A3412))), Text(_hint!, style: const TextStyle(color: Color(0xFF9A3412))),
-90
View File
@@ -1,90 +0,0 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'package:flutter/material.dart';
/// Helper or hint copy that stays one line until it actually overflows.
/// Text that fits is not a button. Text that would end in an ellipsis can be
/// tapped to show the rest, and tapped again to collapse.
class ExpandableHint extends StatefulWidget {
const ExpandableHint({super.key, required this.text});
final String text;
@override
State<ExpandableHint> createState() => _ExpandableHintState();
}
class _ExpandableHintState extends State<ExpandableHint> {
var _expanded = false;
@override
void didUpdateWidget(ExpandableHint oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.text != widget.text) {
_expanded = false;
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = (theme.textTheme.bodySmall ?? const TextStyle(fontSize: 12))
.copyWith(color: theme.colorScheme.onSurfaceVariant, height: 1.3);
return LayoutBuilder(
builder: (context, constraints) {
final overflows = _exceedsOneLine(
text: widget.text,
style: style,
maxWidth: constraints.maxWidth,
textScaler: MediaQuery.textScalerOf(context),
direction: Directionality.of(context),
);
final shown = Text(
widget.text,
style: style,
maxLines: overflows && !_expanded ? 1 : null,
overflow: overflows && !_expanded
? TextOverflow.ellipsis
: TextOverflow.clip,
);
final padded = Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 12, 0),
child: shown,
);
if (!overflows) {
return padded;
}
return Semantics(
button: true,
hint: _expanded ? '点一下收起' : '点一下展开全文',
child: InkWell(
onTap: () => setState(() => _expanded = !_expanded),
child: padded,
),
);
},
);
}
}
bool _exceedsOneLine({
required String text,
required TextStyle style,
required double maxWidth,
required TextScaler textScaler,
required TextDirection direction,
}) {
if (!maxWidth.isFinite || maxWidth <= 0) {
return false;
}
final painter = TextPainter(
text: TextSpan(text: text, style: style),
maxLines: 1,
textDirection: direction,
textScaler: textScaler,
)..layout(maxWidth: maxWidth);
final exceeds = painter.didExceedMaxLines;
painter.dispose();
return exceeds;
}
+3 -80
View File
@@ -4,65 +4,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../content/release_history.dart'; import '../content/release_history.dart';
import '../update/apply_update.dart';
import '../update/release_feed.dart';
import '../update/update_check.dart';
import '../version.dart'; import '../version.dart';
import 'quality_charts.dart'; import 'quality_charts.dart';
class HistoryPage extends StatefulWidget { class HistoryPage extends StatelessWidget {
const HistoryPage({super.key, this.updateSource = UpdateSource.gitea}); const HistoryPage({super.key});
final UpdateSource updateSource;
@override
State<HistoryPage> createState() => _HistoryPageState();
}
class _HistoryPageState extends State<HistoryPage> {
var _entries = const <ReleaseEntry>[];
var _note = '正在读取发布说明…';
var _showBundledNote = false;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final cached = await readStoredReleaseHistory();
if (!mounted) {
return;
}
if (cached != null) {
setState(() {
_entries = cached.entries;
_note = '正在向${updateSourceLabel(widget.updateSource)}核对发布说明…';
_showBundledNote = false;
});
}
try {
final result = await loadReleaseHistory(widget.updateSource);
if (!mounted) {
return;
}
setState(() {
_entries = result.entries;
_note = result.note;
_showBundledNote = result.origin == HistoryOrigin.bundled;
});
} on Object {
if (!mounted) {
return;
}
setState(() {
_entries = releaseHistory;
_note = staleHistoryNote(rateLimited: false, hasCache: false);
_showBundledNote = true;
});
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -92,26 +38,13 @@ class _HistoryPageState extends State<HistoryPage> {
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
const SizedBox(height: 8),
if (_note.isNotEmpty)
Text(
_note,
style: const TextStyle(color: muted, height: 1.4),
),
const SizedBox(height: 8),
const Text(
onlineHistoryLimitNote,
style: TextStyle(color: muted, height: 1.4),
),
if (_showBundledNote) ...[
const SizedBox(height: 8), const SizedBox(height: 8),
const Text( const Text(
releaseHistoryNote, releaseHistoryNote,
style: TextStyle(color: muted, height: 1.4), style: TextStyle(color: muted, height: 1.4),
), ),
],
const SizedBox(height: 12), const SizedBox(height: 12),
for (final entry in _entries) _entry(entry), for (final entry in releaseHistory) _entry(entry),
], ],
), ),
), ),
@@ -121,9 +54,6 @@ class _HistoryPageState extends State<HistoryPage> {
} }
Widget _entry(ReleaseEntry entry) { Widget _entry(ReleaseEntry entry) {
final remote = SemVer.parse(entry.version);
final local = SemVer.parse(appVersion);
final newer = remote != null && local != null && remote.isNewerThan(local);
return Card( return Card(
margin: const EdgeInsets.only(bottom: 12), margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
@@ -139,13 +69,6 @@ class _HistoryPageState extends State<HistoryPage> {
entry.title, entry.title,
style: const TextStyle(fontWeight: FontWeight.w700, color: ink), style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
), ),
if (newer) ...[
const SizedBox(height: 6),
Text(
'比当前安装的 $appVersion 新',
style: const TextStyle(color: Color(0xFF9A3412), fontSize: 13),
),
],
const SizedBox(height: 6), const SizedBox(height: 6),
Text( Text(
entry.published == null entry.published == null
+62 -141
View File
@@ -16,9 +16,7 @@ import '../probe/remote_client.dart';
import '../storage/app_store.dart'; import '../storage/app_store.dart';
import '../storage/token_vault.dart'; import '../storage/token_vault.dart';
import '../update/apply_update.dart'; import '../update/apply_update.dart';
import '../update/update_check.dart';
import 'address_text.dart'; import 'address_text.dart';
import 'expandable_hint.dart';
import 'center_dialog.dart'; import 'center_dialog.dart';
import 'format.dart'; import 'format.dart';
import 'history_page.dart'; import 'history_page.dart';
@@ -59,7 +57,6 @@ class _HomePageState extends State<HomePage> {
var _allow4 = true; var _allow4 = true;
var _allow6 = true; var _allow6 = true;
var _autoUpdate = true; var _autoUpdate = true;
var _updateSource = UpdateSource.gitea;
var _centers = <CenterLink>[]; var _centers = <CenterLink>[];
var _history = TargetHistory.empty; var _history = TargetHistory.empty;
var _centerHint = ''; var _centerHint = '';
@@ -70,29 +67,23 @@ class _HomePageState extends State<HomePage> {
var _ready = false; var _ready = false;
var _idSeq = 0; var _idSeq = 0;
var _formEpoch = 0; var _formEpoch = 0;
String? _portBeforeHttp;
String? _profileBeforeHttp;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_controller.addListener(_rebuild); _controller.addListener(_rebuild);
_host.addListener(_onHostChanged);
_load(); _load();
} }
Future<void> _load() async { Future<void> _load() async {
_vault = await openTokenVault(); _vault = await openTokenVault();
final loaded = await _store.load();
final history = await _store.loadHistory(); final history = await _store.loadHistory();
final echo = await _vault.read(echoTokenKey); final echo = await _vault.read(echoTokenKey);
if (!mounted) { if (!mounted) {
return; return;
} }
// Read settings after the slower startup awaits, so a choice made while
// the vault was opening is not replaced by the older snapshot.
final loaded = await _store.load();
if (!mounted) {
return;
}
final config = loaded.config; final config = loaded.config;
setState(() { setState(() {
_remote = config.remote; _remote = config.remote;
@@ -111,7 +102,6 @@ class _HomePageState extends State<HomePage> {
_allow4 = config.allowIPv4; _allow4 = config.allowIPv4;
_allow6 = config.allowIPv6; _allow6 = config.allowIPv6;
_autoUpdate = config.autoUpdate; _autoUpdate = config.autoUpdate;
_updateSource = parseUpdateSource(config.updateSource);
_httpVersion = config.httpVersion; _httpVersion = config.httpVersion;
_httpMethod = config.httpMethod; _httpMethod = config.httpMethod;
_httpResolve.text = config.httpResolve; _httpResolve.text = config.httpResolve;
@@ -133,6 +123,20 @@ class _HomePageState extends State<HomePage> {
} }
} }
void _onHostChanged() {
if (_profileId != 'http') {
return;
}
final current = int.tryParse(_port.text.trim());
if (_port.text.trim().isNotEmpty && current != 80 && current != 443) {
return;
}
final next = '${httpDefaultPort(_host.text)}';
if (_port.text != next) {
_port.text = next;
}
}
void _rebuild() { void _rebuild() {
if (mounted) { if (mounted) {
setState(() {}); setState(() {});
@@ -144,6 +148,7 @@ class _HomePageState extends State<HomePage> {
unawaited(_controller.stop()); unawaited(_controller.stop());
unawaited(_persist()); unawaited(_persist());
_controller.removeListener(_rebuild); _controller.removeListener(_rebuild);
_host.removeListener(_onHostChanged);
_controller.dispose(); _controller.dispose();
for (final field in [ for (final field in [
_host, _host,
@@ -186,7 +191,6 @@ class _HomePageState extends State<HomePage> {
allowIPv4: _allow4, allowIPv4: _allow4,
allowIPv6: _allow6, allowIPv6: _allow6,
autoUpdate: _autoUpdate, autoUpdate: _autoUpdate,
updateSource: updateSourceId(_updateSource),
httpVersion: _httpVersion, httpVersion: _httpVersion,
httpResolve: _httpResolve.text.trim(), httpResolve: _httpResolve.text.trim(),
httpMethod: _httpMethod, httpMethod: _httpMethod,
@@ -208,13 +212,12 @@ class _HomePageState extends State<HomePage> {
await _persist(); await _persist();
final config = _config(); final config = _config();
if (config.validate() == null) { if (config.validate() == null) {
final httpTarget = config.httpTarget;
_history = _history.add( _history = _history.add(
TargetEntry( TargetEntry(
host: httpTarget?.url ?? config.host, host: config.host,
port: httpTarget?.port ?? config.port, port: config.port,
profileId: config.profileId, profileId: config.profileId,
httpUrl: httpTarget?.url ?? '', httpUrl: config.profileId == 'http' ? config.host : '',
method: config.profileId == 'http' ? config.httpMethod : '', method: config.profileId == 'http' ? config.httpMethod : '',
savedAtMs: DateTime.now().millisecondsSinceEpoch, savedAtMs: DateTime.now().millisecondsSinceEpoch,
), ),
@@ -238,42 +241,23 @@ class _HomePageState extends State<HomePage> {
} }
void _changeProfile(String? id) { void _changeProfile(String? id) {
if (id == null || id == _profileId) { if (id == null) {
return; return;
} }
final previous = ProbeProfile.byId(_profileId); final previous = ProbeProfile.byId(_profileId);
final next = ProbeProfile.byId(id); final next = ProbeProfile.byId(id);
setState(() {
_timeout.text = timeoutAfterProfileChange(
current: _timeout.text,
previousDefault: timeoutDefaultFor(_profileId),
nextDefault: timeoutDefaultFor(id),
);
if (id == 'http') {
_portBeforeHttp = _port.text;
_profileBeforeHttp = _profileId;
} else if (_profileId == 'http' &&
_portBeforeHttp != null &&
_profileBeforeHttp != null) {
_port.text = portAfterProfileChange(
current: _portBeforeHttp!,
previousDefault: ProbeProfile.byId(_profileBeforeHttp!).port,
nextDefault: next.port,
);
_portBeforeHttp = null;
_profileBeforeHttp = null;
} else {
final currentPort = int.tryParse(_port.text.trim()); final currentPort = int.tryParse(_port.text.trim());
var previousDefault = previous.port; var previousDefault = previous.port;
if (_profileId == 'http' && (currentPort == 80 || currentPort == 443)) { if (_profileId == 'http' && (currentPort == 80 || currentPort == 443)) {
previousDefault = currentPort!; previousDefault = currentPort!;
} }
final nextDefault = id == 'http' ? httpDefaultPort(_host.text) : next.port;
setState(() {
_port.text = portAfterProfileChange( _port.text = portAfterProfileChange(
current: _port.text, current: _port.text,
previousDefault: previousDefault, previousDefault: previousDefault,
nextDefault: next.port, nextDefault: nextDefault,
); );
}
_profileId = id; _profileId = id;
}); });
} }
@@ -296,7 +280,7 @@ class _HomePageState extends State<HomePage> {
return; return;
} }
final page = value == 'history' final page = value == 'history'
? HistoryPage(updateSource: _updateSource) ? const HistoryPage()
: const MetricGuidePage(); : const MetricGuidePage();
Navigator.of(context) Navigator.of(context)
.push(MaterialPageRoute<void>(builder: (_) => page)); .push(MaterialPageRoute<void>(builder: (_) => page));
@@ -328,18 +312,22 @@ class _HomePageState extends State<HomePage> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (profile.id == 'http')
_hostRow(
view.running,
'https://example.com:2025/ 或 example.com',
helper:
'只填主机名或 IP 时按 http:// 和端口 80。完整网址使用其中的协议、端口和路径。',
fieldKey: const Key('target-field'),
)
else
_pair( _pair(
wide, wide,
_hostRow(view.running, '域名、IP,或 http(s) 地址'), Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _field(_host, '目标地址', '域名、IP,或 http(s) 地址'),
),
IconButton(
key: const Key('target-history'),
tooltip: '最近目标',
onPressed: view.running ? null : _showHistory,
icon: const Icon(Icons.history),
),
],
),
_field( _field(
_port, _port,
'端口', '端口',
@@ -385,15 +373,7 @@ class _HomePageState extends State<HomePage> {
'间隔(毫秒)', '间隔(毫秒)',
_remote ? '至少 200' : '至少 100', _remote ? '至少 200' : '至少 100',
), ),
_field( _field(_timeout, '超时(毫秒)', '100–15000'),
_timeout,
'超时(毫秒)',
'100–15000',
fieldKey: const Key('timeout-field'),
helper: profile.id == 'http'
? 'HTTP 默认 5000 毫秒'
: null,
),
), ),
if (profile.needsPacketSize) ...[ if (profile.needsPacketSize) ...[
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -408,9 +388,8 @@ class _HomePageState extends State<HomePage> {
_field( _field(
_echo, _echo,
'目标回显口令', '目标回显口令',
'可选', '可选,只放进探测包,和节点口令不是同一个',
secret: true, secret: true,
helper: '只放进探测包,和节点口令不是同一个。',
), ),
], ],
if (profile.id == 'dns') ...[ if (profile.id == 'dns') ...[
@@ -421,12 +400,7 @@ class _HomePageState extends State<HomePage> {
const SizedBox(height: 12), const SizedBox(height: 12),
_field(_payload, '载荷(十六进制)', '例如 0102'), _field(_payload, '载荷(十六进制)', '例如 0102'),
const SizedBox(height: 12), const SizedBox(height: 12),
_field( _field(_expect, '响应需以此开头(十六进制,可空)', '不填则任意响应都算成功'),
_expect,
'响应开头(十六进制)',
'可空',
helper: '不填则任意响应都算成功。',
),
], ],
], ],
), ),
@@ -476,8 +450,7 @@ class _HomePageState extends State<HomePage> {
TextButton( TextButton(
onPressed: () => Navigator.of(context).push( onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>( MaterialPageRoute<void>(
builder: (_) => builder: (_) => const HistoryPage(),
HistoryPage(updateSource: _updateSource),
), ),
), ),
child: const Text('更新历史'), child: const Text('更新历史'),
@@ -605,8 +578,7 @@ class _HomePageState extends State<HomePage> {
_field( _field(
_httpResolve, _httpResolve,
'指定解析', '指定解析',
'可选', '可选。Host 和 SNI 仍用上面的地址,连接改走这里的 IP 或主机名',
helper: 'Host 和 SNI 仍用上面的地址,连接改走这里的 IP 或主机名。',
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
@@ -664,7 +636,6 @@ class _HomePageState extends State<HomePage> {
allowIPv4: _allow4, allowIPv4: _allow4,
allowIPv6: _allow6, allowIPv6: _allow6,
autoUpdate: _autoUpdate, autoUpdate: _autoUpdate,
updateSource: _updateSource,
onAllowIPv4: (value) { onAllowIPv4: (value) {
setState(() => _allow4 = value); setState(() => _allow4 = value);
unawaited(_persist()); unawaited(_persist());
@@ -677,17 +648,13 @@ class _HomePageState extends State<HomePage> {
setState(() => _autoUpdate = value); setState(() => _autoUpdate = value);
unawaited(_persist()); unawaited(_persist());
}, },
onUpdateSource: (value) {
setState(() => _updateSource = value);
unawaited(_persist());
},
), ),
), ),
); );
} }
Future<void> _launchUpdate() async { Future<void> _launchUpdate() async {
final result = await checkForUpdate(preferred: _updateSource); final result = await checkForUpdate();
final offer = result.offer; final offer = result.offer;
if (offer == null || !mounted || !_autoUpdate) { if (offer == null || !mounted || !_autoUpdate) {
return; return;
@@ -772,48 +739,15 @@ class _HomePageState extends State<HomePage> {
void _applyHistory(TargetEntry entry) { void _applyHistory(TargetEntry entry) {
setState(() { setState(() {
_formEpoch += 1; _formEpoch += 1;
_portBeforeHttp = null;
_profileBeforeHttp = null;
_profileId = entry.profileId; _profileId = entry.profileId;
_host.text = entry.profileId == 'http' && entry.httpUrl.isNotEmpty _host.text = entry.httpUrl.isNotEmpty ? entry.httpUrl : entry.host;
? entry.httpUrl
: entry.host;
_port.text = '${entry.port}'; _port.text = '${entry.port}';
if (entry.profileId == 'http' && entry.method.isNotEmpty) { if (entry.profileId == 'http' && entry.method.isNotEmpty) {
_httpMethod = entry.method; _httpMethod = entry.method;
} }
if (entry.profileId == 'http') {
final current = int.tryParse(_timeout.text.trim());
if (current == null || current == timeoutDefaultFor('nq-tcp')) {
_timeout.text = '${timeoutDefaultFor('http')}';
}
}
}); });
} }
Widget _hostRow(bool running, String hint, {String? helper, Key? fieldKey}) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _field(
_host,
'目标地址',
hint,
helper: helper,
fieldKey: fieldKey,
),
),
IconButton(
key: const Key('target-history'),
tooltip: '最近目标',
onPressed: running ? null : _showHistory,
icon: const Icon(Icons.history),
),
],
);
}
String _newId() { String _newId() {
_idSeq += 1; _idSeq += 1;
return '${DateTime.now().microsecondsSinceEpoch}-$_idSeq'; return '${DateTime.now().microsecondsSinceEpoch}-$_idSeq';
@@ -826,18 +760,13 @@ class _HomePageState extends State<HomePage> {
} }
var link = added.link; var link = added.link;
for (final existing in _centers) { for (final existing in _centers) {
if (existing.url == added.link.url && if (existing.url == added.link.url && existing.account == added.link.account) {
existing.account == added.link.account) {
link = existing; link = existing;
break; break;
} }
} }
await _vault.write(centerTokenKey(link.id), added.token); await _vault.write(centerTokenKey(link.id), added.token);
await _applyCatalog( await _applyCatalog(link, added.catalog, '已添加 ${added.catalog.servers.length} 台服务器');
link,
added.catalog,
'已添加 ${added.catalog.servers.length} 台服务器',
);
} }
Future<void> _refreshCenter(CenterLink link) async { Future<void> _refreshCenter(CenterLink link) async {
@@ -860,10 +789,7 @@ class _HomePageState extends State<HomePage> {
} }
await _vault.delete(centerTokenKey(link.id)); await _vault.delete(centerTokenKey(link.id));
setState(() { setState(() {
_centers = [ _centers = [for (final item in _centers) if (item.id != link.id) item];
for (final item in _centers)
if (item.id != link.id) item,
];
_nodes = [ _nodes = [
for (final node in _nodes) for (final node in _nodes)
if (node.centerLinkId != link.id) node, if (node.centerLinkId != link.id) node,
@@ -876,11 +802,7 @@ class _HomePageState extends State<HomePage> {
await _persist(); await _persist();
} }
Future<void> _applyCatalog( Future<void> _applyCatalog(CenterLink link, Catalog catalog, String hint) async {
CenterLink link,
Catalog catalog,
String hint,
) async {
final before = { final before = {
for (final node in _nodes) for (final node in _nodes)
if (node.centerLinkId == link.id) node.id, if (node.centerLinkId == link.id) node.id,
@@ -921,9 +843,7 @@ class _HomePageState extends State<HomePage> {
for (final node in _nodes) for (final node in _nodes)
if (node.centerLinkId == link.id) node, if (node.centerLinkId == link.id) node,
]; ];
final title = link.account.isEmpty final title = link.account.isEmpty ? link.url : '${link.account} · ${link.url}';
? link.url
: '${link.account} · ${link.url}';
return ExpansionTile( return ExpansionTile(
tilePadding: EdgeInsets.zero, tilePadding: EdgeInsets.zero,
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis), title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
@@ -1244,7 +1164,9 @@ class _NodeDialogState extends State<_NodeDialog> {
'${node.name} · ${visibilityLabel(node.visibility)}', '${node.name} · ${visibilityLabel(node.visibility)}',
), ),
subtitle: Text( subtitle: Text(
node.confidential ? '地址由中心代为连接,本机不保存。' : node.baseUrl, node.confidential
? '地址由中心代为连接,本机不保存。'
: node.baseUrl,
maxLines: 2, maxLines: 2,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
@@ -1289,10 +1211,11 @@ class _NodeDialogState extends State<_NodeDialog> {
obscureText: true, obscureText: true,
decoration: InputDecoration( decoration: InputDecoration(
labelText: _editingId == null ? '节点口令(公开节点留空)' : '新口令(留空则保留)', labelText: _editingId == null ? '节点口令(公开节点留空)' : '新口令(留空则保留)',
helperText: _editingId == null
? null
: '留空则保留已保存的口令,不会显示原口令。',
), ),
), ),
if (_editingId != null)
const ExpandableHint(text: '留空则保留已保存的口令,不会显示原口令。'),
if (_hint != null) ...[ if (_hint != null) ...[
const SizedBox(height: 8), const SizedBox(height: 8),
Text(_hint!, style: const TextStyle(fontSize: 13)), Text(_hint!, style: const TextStyle(fontSize: 13)),
@@ -1350,17 +1273,15 @@ Widget _field(
Key? fieldKey, Key? fieldKey,
String? helper, String? helper,
}) { }) {
return Column( return TextField(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
key: fieldKey, key: fieldKey,
controller: controller, controller: controller,
obscureText: secret, obscureText: secret,
decoration: InputDecoration(labelText: label, hintText: hint), decoration: InputDecoration(
labelText: label,
hintText: hint,
helperText: helper,
), ),
if (helper != null && helper.isNotEmpty) ExpandableHint(text: helper),
],
); );
} }
+1 -1
View File
@@ -63,7 +63,7 @@ class MetricGuidePage extends StatelessWidget {
), ),
_Section( _Section(
title: 'HTTP', title: 'HTTP',
body: 'HTTP 探测记下 DNS、连接、TLS、首字节和总时间,以及状态码、最终地址和实际用到的 HTTP 版本(1.1、2 或 3)。曲线上的延迟是总时间。已经收到的响应算成功,4xx 和 5xx 只显示状态码,不叫丢包,也不算进失败率。连不上或强制的版本不被支持,才算失败。\n\n默认先试 HTTP/2,不行再降到 1.1。选了「仅 HTTP/1.1」「仅 HTTP/2」或「仅 HTTP/3」时,服务器不支持就失败,不会悄悄换一种。指定解析只改连接走的地址,Host 和 SNI 仍用目标网址,用来看 CDN。它不是把 1.1.1.1 当成 DNS 服务器。\n\nHTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。目标填完整网址,例如 https://example.com:2025/path,也可以只填主机名。只填主机名或 IP 时按 http://主机/,端口是 80,不会改成 https 或 443。网址里写了端口、路径或查询,就按网址本身探测,HTTP 模式不再单独填端口。超时默认 5000 毫秒。\n\n本机探测和节点用的是同一个 Go 引擎。桌面端需要把 netquality-reflector 放在程序旁边,或设置 NQ_PROBE_HELPER。找不到或启动不了时,探测不会开始,也不会记成一次全部失败;界面会说明原因,并建议把探测来源改成远程节点。Android 安装包不带这个程序,本机 HTTP 会直接这样提示。远程节点不受影响。', body: 'HTTP 探测记下 DNS、连接、TLS、首字节和总时间,以及状态码、最终地址和实际用到的 HTTP 版本(1.1、2 或 3)。曲线上的延迟是总时间。已经收到的响应算成功,4xx 和 5xx 只显示状态码,不叫丢包,也不算进失败率。连不上或强制的版本不被支持,才算失败。\n\n默认先试 HTTP/2,不行再降到 1.1。选了「仅 HTTP/1.1」「仅 HTTP/2」或「仅 HTTP/3」时,服务器不支持就失败,不会悄悄换一种。指定解析只改连接走的地址,Host 和 SNI 仍用目标网址,用来看 CDN。它不是把 1.1.1.1 当成 DNS 服务器。\n\nHTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。本机探测和节点用的是同一个 Go 引擎。桌面端需要把 netquality-reflector 放在程序旁边,或设置 NQ_PROBE_HELPER。Android 上如果系统不允许从应用目录启动这个程序,本机 HTTP 会说明缺引擎;远程节点不受影响。',
), ),
_Section( _Section(
title: '停止以后', title: '停止以后',
+8 -73
View File
@@ -15,21 +15,17 @@ class SettingsPage extends StatefulWidget {
required this.allowIPv4, required this.allowIPv4,
required this.allowIPv6, required this.allowIPv6,
required this.autoUpdate, required this.autoUpdate,
required this.updateSource,
required this.onAllowIPv4, required this.onAllowIPv4,
required this.onAllowIPv6, required this.onAllowIPv6,
required this.onAutoUpdate, required this.onAutoUpdate,
required this.onUpdateSource,
}); });
final bool allowIPv4; final bool allowIPv4;
final bool allowIPv6; final bool allowIPv6;
final bool autoUpdate; final bool autoUpdate;
final UpdateSource updateSource;
final ValueChanged<bool> onAllowIPv4; final ValueChanged<bool> onAllowIPv4;
final ValueChanged<bool> onAllowIPv6; final ValueChanged<bool> onAllowIPv6;
final ValueChanged<bool> onAutoUpdate; final ValueChanged<bool> onAutoUpdate;
final ValueChanged<UpdateSource> onUpdateSource;
@override @override
State<SettingsPage> createState() => _SettingsPageState(); State<SettingsPage> createState() => _SettingsPageState();
@@ -39,7 +35,6 @@ class _SettingsPageState extends State<SettingsPage> {
late bool _allow4; late bool _allow4;
late bool _allow6; late bool _allow6;
late bool _auto; late bool _auto;
late UpdateSource _source;
var _checking = false; var _checking = false;
String _message = ''; String _message = '';
UpdateOffer? _offer; UpdateOffer? _offer;
@@ -50,7 +45,6 @@ class _SettingsPageState extends State<SettingsPage> {
_allow4 = widget.allowIPv4; _allow4 = widget.allowIPv4;
_allow6 = widget.allowIPv6; _allow6 = widget.allowIPv6;
_auto = widget.autoUpdate; _auto = widget.autoUpdate;
_source = widget.updateSource;
} }
Future<void> _check() async { Future<void> _check() async {
@@ -59,7 +53,7 @@ class _SettingsPageState extends State<SettingsPage> {
_message = ''; _message = '';
_offer = null; _offer = null;
}); });
final result = await checkForUpdate(preferred: _source); final result = await checkForUpdate();
if (!mounted) { if (!mounted) {
return; return;
} }
@@ -100,18 +94,11 @@ class _SettingsPageState extends State<SettingsPage> {
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 760), constraints: const BoxConstraints(maxWidth: 760),
child: ListView( child: ListView(
padding: EdgeInsets.fromLTRB( padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
wide ? 24 : 12,
8,
wide ? 24 : 12,
28,
),
children: [ children: [
SwitchListTile( SwitchListTile(
title: const Text('允许 IPv4'), title: const Text('允许 IPv4'),
subtitle: const Text( subtitle: const Text('关掉以后,解析结果里的 IPv4 不会用来发包。直接填写 IPv4 地址也会被拒绝。'),
'关掉以后,解析结果里的 IPv4 不会用来发包。直接填写 IPv4 地址也会被拒绝。',
),
value: _allow4, value: _allow4,
onChanged: (value) { onChanged: (value) {
setState(() => _allow4 = value); setState(() => _allow4 = value);
@@ -120,9 +107,7 @@ class _SettingsPageState extends State<SettingsPage> {
), ),
SwitchListTile( SwitchListTile(
title: const Text('允许 IPv6'), title: const Text('允许 IPv6'),
subtitle: const Text( subtitle: const Text('关掉以后,解析结果里的 IPv6 不会用来发包。直接填写 IPv6 地址也会被拒绝。'),
'关掉以后,解析结果里的 IPv6 不会用来发包。直接填写 IPv6 地址也会被拒绝。',
),
value: _allow6, value: _allow6,
onChanged: (value) { onChanged: (value) {
setState(() => _allow6 = value); setState(() => _allow6 = value);
@@ -133,11 +118,7 @@ class _SettingsPageState extends State<SettingsPage> {
padding: EdgeInsets.fromLTRB(16, 0, 16, 8), padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text( child: Text(
'两个都关掉时不能开始探测。远程节点会收到同样的选择。1.1.2 的节点还不会遵守这个开关,遇到这种情况会提示升级。', '两个都关掉时不能开始探测。远程节点会收到同样的选择。1.1.2 的节点还不会遵守这个开关,遇到这种情况会提示升级。',
style: TextStyle( style: TextStyle(color: Color(0xFF5C656B), fontSize: 13, height: 1.4),
color: Color(0xFF5C656B),
fontSize: 13,
height: 1.4,
),
), ),
), ),
const Divider(), const Divider(),
@@ -150,53 +131,11 @@ class _SettingsPageState extends State<SettingsPage> {
widget.onAutoUpdate(value); widget.onAutoUpdate(value);
}, },
), ),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('更新源'),
const SizedBox(height: 4),
const Text(
'默认是 YanJiu Git。这边的网络经常解析不到 github.com。检查和下载都先用这里选中的源,连不上再试另一个。',
style: TextStyle(
color: Color(0xFF5C656B),
fontSize: 13,
height: 1.4,
),
),
const SizedBox(height: 8),
SegmentedButton<UpdateSource>(
key: const Key('update-source'),
segments: const [
ButtonSegment(
value: UpdateSource.gitea,
label: Text('YanJiu Git'),
),
ButtonSegment(
value: UpdateSource.github,
label: Text('GitHub'),
),
],
selected: {_source},
onSelectionChanged: (value) {
final next = value.first;
setState(() => _source = next);
widget.onUpdateSource(next);
},
),
],
),
),
Padding( Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text( child: Text(
'当前版本 $appVersion(构建 $appBuild)。1.1.2 没有自更新,从 1.1.2 升级仍要手动安装。1.1.3 的桌面更新器认不出 linux-x64、windows-x64。这一版的 Linux 另外提供内容相同的 linux-x86_64,1.1.3 的 Linux 会选中它并自己安装。Windows 要等内容相同的 windows-x86_64 放上以后,1.1.3 的 Windows 才会自己安装。这一版两种名字都认,也仍然接受 amd64、x86_64 和 aarch64。带 server 或 reflector 的包不会被选中。更新源默认是 YanJiu Git,也可以改成 GitHub。检查更新和下载都先用选中的源,连不上再试另一个,结果里会写明这次实际用的是哪一个。\n\n「更新历史」会读取所选源的发布列表,并在本机留一份。网络失败时用上次保存的列表,没有保存过再用安装包里的说明,并标明可能不是最新。已经发出的 1.1.2 和 1.1.3 安装包没有这份同步。\n\n要在没有新版本时试检查更新,可以把环境变量 NQ_UPDATE_GITHUB_API 指到一个同样格式的测试地址,NQ_UPDATE_GITEA_API 是另一个。', '当前版本 $appVersion(构建 $appBuild)。1.1.2 没有自更新,从 1.1.2 升到 1.1.3 仍要手动安装。从这一版起才会自己检查。先试 GitHub,连不上再试言灸的 Git。\n\n要在没有新版本时试这个功能,可以把环境变量 NQ_UPDATE_GITHUB_API 指到一个同样格式的测试地址,NQ_UPDATE_GITEA_API 是备用。',
style: const TextStyle( style: const TextStyle(color: Color(0xFF5C656B), fontSize: 13, height: 1.4),
color: Color(0xFF5C656B),
fontSize: 13,
height: 1.4,
),
), ),
), ),
if (Platform.isAndroid) if (Platform.isAndroid)
@@ -204,11 +143,7 @@ class _SettingsPageState extends State<SettingsPage> {
padding: EdgeInsets.fromLTRB(16, 0, 16, 8), padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text( child: Text(
'在 Android 上安装时,系统会弹出安装确认。这一步不能跳过。', '在 Android 上安装时,系统会弹出安装确认。这一步不能跳过。',
style: TextStyle( style: TextStyle(color: Color(0xFF9A3412), fontSize: 13, height: 1.4),
color: Color(0xFF9A3412),
fontSize: 13,
height: 1.4,
),
), ),
), ),
Padding( Padding(
+16 -89
View File
@@ -1,16 +1,13 @@
// Copyright (C) 2026 言灸 // Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
import 'dart:ffi' show Abi; import 'dart:ffi' show Abi;
import 'dart:io'; import 'dart:io';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../version.dart'; import '../version.dart';
import 'installer.dart'; import 'installer.dart';
import 'release_feed.dart';
import 'update_check.dart'; import 'update_check.dart';
class UpdateResult { class UpdateResult {
@@ -22,63 +19,31 @@ class UpdateResult {
const platformChannel = MethodChannel('dev.netquality/platform'); const platformChannel = MethodChannel('dev.netquality/platform');
UpdateEndpoints endpointsFromEnvironment() { Future<UpdateResult> checkForUpdate() async {
return updateEndpoints(
githubApi: Platform.environment['NQ_UPDATE_GITHUB_API'],
giteaApi: Platform.environment['NQ_UPDATE_GITEA_API'],
);
}
Future<ReleaseCache?> readStoredReleaseHistory() async {
final prefs = await SharedPreferences.getInstance();
return decodeReleaseCache(prefs.getString(releaseHistoryCacheKey));
}
Future<ReleaseSync> loadReleaseHistory(
UpdateSource preferred, {
bool? allowNetwork,
}) async {
final prefs = await SharedPreferences.getInstance();
return syncAndStore(
preferred: preferred,
endpoints: endpointsFromEnvironment(),
fetch: fetchReleaseText,
allowNetwork:
allowNetwork ?? Platform.environment['FLUTTER_TEST'] != 'true',
readCache: () async => prefs.getString(releaseHistoryCacheKey),
writeCache: (json) async {
await prefs.setString(releaseHistoryCacheKey, json);
},
);
}
Future<UpdateResult> checkForUpdate({
UpdateSource preferred = UpdateSource.gitea,
}) async {
final history = loadReleaseHistory(preferred);
final arch = await _arch(); final arch = await _arch();
if (arch.isEmpty) { if (arch.isEmpty) {
await _finishHistory(history);
return const UpdateResult(message: '认不出这台设备的系统或 CPU,没有下载安装包'); return const UpdateResult(message: '认不出这台设备的系统或 CPU,没有下载安装包');
} }
final endpoints = UpdateEndpoints(
github: Platform.environment['NQ_UPDATE_GITHUB_API'] ??
UpdateEndpoints.githubDefault,
gitea: Platform.environment['NQ_UPDATE_GITEA_API'] ??
UpdateEndpoints.giteaDefault,
);
final check = await findUpdate( final check = await findUpdate(
current: appVersion, current: appVersion,
endpoints: endpointsFromEnvironment(), endpoints: endpoints,
preferred: preferred,
os: _os(), os: _os(),
arch: arch, arch: arch,
fetch: fetchReleaseText, fetch: (url) => _getText(url),
); );
await _finishHistory(history); if (check.offer == null) {
return UpdateResult(message: check.message, offer: check.offer); return UpdateResult(message: check.message);
}
Future<void> _finishHistory(Future<ReleaseSync> history) async {
try {
await history;
} on Object {
// A failed history sync still leaves the update check usable.
} }
return UpdateResult(
message: '发现 ${check.offer!.version}。可以下载并覆盖安装。',
offer: check.offer,
);
} }
Future<String> installOffer(UpdateOffer offer) async { Future<String> installOffer(UpdateOffer offer) async {
@@ -190,45 +155,7 @@ Future<String?> _getText(Uri url) async {
if (bytes == null) { if (bytes == null) {
return null; return null;
} }
return utf8.decode(bytes, allowMalformed: true); return String.fromCharCodes(bytes);
}
/// Release JSON, not an installer. A 429, or a 403 that says the quota is
/// gone, is reported as a rate limit so the caller can say so in Chinese.
Future<String?> fetchReleaseText(Uri url) async {
final client = HttpClient();
client.connectionTimeout = const Duration(seconds: 15);
try {
final request = await client.getUrl(url);
request.headers.set(HttpHeaders.userAgentHeader, 'netquality/$appVersion');
request.headers.set(HttpHeaders.acceptHeader, 'application/json');
final response = await request.close().timeout(const Duration(seconds: 20));
final bytes = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 20))) {
bytes.addAll(chunk);
}
final text = utf8.decode(bytes, allowMalformed: true);
if (isReleaseRateLimited(
status: response.statusCode,
rateLimitRemaining: response.headers.value('x-ratelimit-remaining'),
body: text,
)) {
throw UpdateFetchException(
rateLimited: true,
status: response.statusCode,
);
}
if (response.statusCode < 200 || response.statusCode >= 300) {
return null;
}
return text;
} on UpdateFetchException {
rethrow;
} on Object {
return null;
} finally {
client.close(force: true);
}
} }
Future<List<int>?> _getBytes(Uri url) async { Future<List<int>?> _getBytes(Uri url) async {
-558
View File
@@ -1,558 +0,0 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
import '../content/release_history.dart';
import 'update_check.dart';
/// SharedPreferences key for the last release list that a source actually returned.
const releaseHistoryCacheKey = 'netquality.release-history.v1';
enum HistoryOrigin { remote, cache, bundled }
class ReleaseCache {
const ReleaseCache({required this.source, required this.entries});
final String source;
final List<ReleaseEntry> entries;
}
class ReleaseSync {
const ReleaseSync({
required this.entries,
required this.note,
required this.origin,
this.cacheJson,
this.used,
});
final List<ReleaseEntry> entries;
final String note;
final HistoryOrigin origin;
/// Non-null when [origin] is [HistoryOrigin.remote] and the list should be saved.
final String? cacheJson;
final UpdateSource? used;
}
class ReleasePage {
const ReleasePage({required this.entries, required this.complete});
final List<ReleaseEntry> entries;
/// False when this page was full and another page may exist.
final bool complete;
}
/// Turns a `/releases/latest` URL into one page of the release list.
/// GitHub pages with `per_page`; Gitea pages with `limit`. A testing override
/// of the latest URL is reused, so the list follows `NQ_UPDATE_*_API`.
Uri releaseListUri(
String latestUrl, {
required UpdateSource source,
required int page,
required int pageSize,
}) {
final parsed = Uri.parse(latestUrl.trim());
var path = parsed.path;
if (path.endsWith('/latest')) {
path = path.substring(0, path.length - '/latest'.length);
}
final params = Map<String, String>.from(parsed.queryParameters);
if (source == UpdateSource.github) {
params['per_page'] = '$pageSize';
params.remove('limit');
} else {
params['limit'] = '$pageSize';
params.remove('per_page');
}
params['page'] = '$page';
return parsed.replace(path: path, queryParameters: params);
}
/// GitHub and Gitea both return `tag_name`, `name`, `body`, `published_at`,
/// `draft`, `prerelease`, and `assets[].browser_download_url`. A list page is
/// a JSON array. A single release object is accepted so a `/latest` body can
/// still be shown. An error object is not a page.
ReleasePage? parseReleasePage(
String body, {
required String sourceLabel,
required int pageSize,
}) {
Object? decoded;
try {
decoded = jsonDecode(body);
} on FormatException {
return null;
}
if (decoded is Map) {
if (decoded['tag_name'] is! String) {
return null;
}
final entry = _entryFromRelease(
Map<String, dynamic>.from(decoded),
sourceLabel: sourceLabel,
);
return ReleasePage(entries: [?entry], complete: true);
}
if (decoded is! List) {
return null;
}
final entries = <ReleaseEntry>[];
for (final item in decoded) {
if (item is! Map) {
continue;
}
final entry = _entryFromRelease(
Map<String, dynamic>.from(item),
sourceLabel: sourceLabel,
);
if (entry != null) {
entries.add(entry);
}
}
return ReleasePage(entries: entries, complete: decoded.length < pageSize);
}
ReleaseEntry? _entryFromRelease(
Map<String, dynamic> json, {
required String sourceLabel,
}) {
if (json['draft'] == true) {
return null;
}
final tag = json['tag_name'];
if (tag is! String) {
return null;
}
final version = SemVer.parse(tag);
if (version == null) {
return null;
}
final versionText = '${version.major}.${version.minor}.${version.patch}';
final name = json['name'];
final title = name is String && name.trim().isNotEmpty
? name.trim()
: '网络质量探测 $versionText';
final body = json['body'] is String ? json['body'] as String : '';
final points = notesToPoints(body, title: title);
if (points.isEmpty) {
points.add('这次发布没有正文。');
}
final pre = json['prerelease'] == true;
final published = _publishedDay(json['published_at']);
final tagText = tag.trim();
return ReleaseEntry(
version: versionText,
tag: tagText,
title: title,
published: published,
source: '来自 $sourceLabel · 标签 $tagText${pre ? ' · 预发布' : ''}',
points: points,
);
}
String? _publishedDay(Object? raw) {
if (raw is! String || raw.length < 10) {
return null;
}
final day = raw.substring(0, 10);
if (!RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(day)) {
return null;
}
return day;
}
/// Splits a release body into the short points the history page already shows.
/// Headings and bullet items each become one point. A title repeated as the
/// first heading is dropped. Versions that are not in the body are not added.
List<String> notesToPoints(String body, {String title = ''}) {
final points = <String>[];
final buffer = StringBuffer();
void flush() {
final text = _plain(buffer.toString());
buffer.clear();
if (text.isNotEmpty) {
points.add(text);
}
}
for (final raw in body.replaceAll('\r\n', '\n').split('\n')) {
final trimmed = raw.trim();
if (trimmed.isEmpty) {
flush();
continue;
}
if (trimmed.startsWith('```')) {
flush();
continue;
}
final heading = RegExp(r'^#{1,6}\s+').firstMatch(trimmed);
if (heading != null) {
flush();
final text = _plain(trimmed.substring(heading.end));
if (text.isNotEmpty) {
points.add(text);
}
continue;
}
final bullet = RegExp(r'^[-*+]\s+').firstMatch(trimmed);
if (bullet != null) {
flush();
final text = _plain(trimmed.substring(bullet.end));
if (text.isNotEmpty) {
points.add(text);
}
continue;
}
if (buffer.isNotEmpty) {
buffer.write(' ');
}
buffer.write(trimmed);
}
flush();
if (points.isNotEmpty && title.isNotEmpty && points.first == title) {
points.removeAt(0);
}
return points;
}
String _plain(String input) {
var text = input.trim();
text = text.replaceAllMapped(RegExp(r'\[([^\]]+)\]\(([^)]+)\)'), (match) {
final label = match.group(1)!.trim();
final url = match.group(2)!.trim();
if (label.isEmpty) {
return url;
}
if (url.isEmpty || url == label) {
return label;
}
return '$label($url)';
});
text = text.replaceAll('`', '');
text = text.replaceAll(RegExp(r'\s+'), ' ');
return text.trim();
}
String encodeReleaseCache({
required String source,
required List<ReleaseEntry> entries,
}) {
return jsonEncode({
'source': source,
'entries': [for (final entry in entries) entry.toJson()],
});
}
ReleaseCache? decodeReleaseCache(String? raw) {
if (raw == null || raw.trim().isEmpty) {
return null;
}
try {
final decoded = jsonDecode(raw);
if (decoded is! Map) {
return null;
}
final source = decoded['source'];
final rawEntries = decoded['entries'];
if (source is! String || rawEntries is! List) {
return null;
}
final entries = <ReleaseEntry>[];
for (final item in rawEntries) {
if (item is! Map) {
continue;
}
final entry = ReleaseEntry.fromJson(Map<String, dynamic>.from(item));
if (entry.version.isEmpty && entry.title.isEmpty) {
continue;
}
entries.add(entry);
}
return ReleaseCache(source: source, entries: entries);
} on FormatException {
return null;
}
}
String freshHistoryNote({
required String sourceLabel,
required bool fellBack,
required bool preferredRateLimited,
required bool incomplete,
required bool empty,
}) {
final head = !fellBack
? '已从 $sourceLabel 同步。'
: preferredRateLimited
? '所选更新源暂时限制了请求次数,这次改用了 $sourceLabel。'
: '所选更新源连不上,这次改用了 $sourceLabel。';
final tail = empty
? '这个更新源目前没有已发布的版本。'
: incomplete
? '后面的页没有取完,可能不是全部。'
: '比当前安装更新的发布也会列在这里。';
return '$head$tail';
}
String staleHistoryNote({
required bool rateLimited,
required bool hasCache,
String? sourceLabel,
}) {
final reason = rateLimited ? '更新源暂时限制了请求次数' : '网络暂时连不上';
if (!hasCache) {
return '$reason,也没有保存过在线列表。下面是安装包里的说明,可能不是最新。';
}
final from = sourceLabel == null || sourceLabel.isEmpty
? ''
: '从 $sourceLabel ';
return '$reason。下面是上次$from保存的列表,可能不是最新。';
}
String? cacheSourceLabel(String source) {
if (source == updateSourceGithub) {
return updateSourceLabel(UpdateSource.github);
}
if (source == updateSourceGitea) {
return updateSourceLabel(UpdateSource.gitea);
}
return null;
}
/// Reads the chosen source's release list, then the other source if that
/// fails. A network failure keeps [cachedJson], or [bundled] when nothing
/// has been saved. Published releases newer than the installed app stay in
/// the list; versions that the payload does not contain are not added.
Future<ReleaseSync> syncReleaseHistory({
required UpdateSource preferred,
required UpdateEndpoints endpoints,
required Future<String?> Function(Uri url) fetch,
String? cachedJson,
List<ReleaseEntry> bundled = releaseHistory,
int pageLimit = 5,
int githubPageSize = 100,
int giteaPageSize = 50,
}) async {
final order = preferred == UpdateSource.github
? const [UpdateSource.github, UpdateSource.gitea]
: const [UpdateSource.gitea, UpdateSource.github];
var sawRate = false;
var preferredRate = false;
for (var i = 0; i < order.length; i++) {
final source = order[i];
final pageSize = source == UpdateSource.github
? githubPageSize
: giteaPageSize;
try {
final read = await _readSource(
latestUrl: endpoints.latestFor(source),
source: source,
fetch: fetch,
pageLimit: pageLimit,
pageSize: pageSize,
);
if (read == null) {
continue;
}
final entries = _sortedUnique(read.entries);
return ReleaseSync(
entries: entries,
origin: HistoryOrigin.remote,
used: source,
cacheJson: encodeReleaseCache(
source: updateSourceId(source),
entries: entries,
),
note: freshHistoryNote(
sourceLabel: updateSourceLabel(source),
fellBack: i > 0,
preferredRateLimited: i > 0 && preferredRate,
incomplete: read.incomplete,
empty: entries.isEmpty,
),
);
} on UpdateFetchException catch (error) {
if (error.rateLimited) {
sawRate = true;
if (i == 0) {
preferredRate = true;
}
}
}
}
return _offline(
cachedJson: cachedJson,
bundled: bundled,
rateLimited: sawRate,
);
}
class _SourceRead {
const _SourceRead({required this.entries, required this.incomplete});
final List<ReleaseEntry> entries;
final bool incomplete;
}
Future<_SourceRead?> _readSource({
required String latestUrl,
required UpdateSource source,
required Future<String?> Function(Uri url) fetch,
required int pageLimit,
required int pageSize,
}) async {
final entries = <ReleaseEntry>[];
final label = updateSourceLabel(source);
for (var page = 1; page <= pageLimit; page++) {
final uri = releaseListUri(
latestUrl,
source: source,
page: page,
pageSize: pageSize,
);
String? body;
try {
body = await fetch(uri);
} on UpdateFetchException {
if (page == 1) {
rethrow;
}
return _SourceRead(entries: entries, incomplete: true);
} on Object {
if (page == 1) {
return null;
}
return _SourceRead(entries: entries, incomplete: true);
}
if (body == null) {
if (page == 1) {
return null;
}
return _SourceRead(entries: entries, incomplete: true);
}
final parsed = parseReleasePage(
body,
sourceLabel: label,
pageSize: pageSize,
);
if (parsed == null) {
if (page == 1) {
return null;
}
return _SourceRead(entries: entries, incomplete: true);
}
entries.addAll(parsed.entries);
if (parsed.complete) {
return _SourceRead(entries: entries, incomplete: false);
}
if (page == pageLimit) {
return _SourceRead(entries: entries, incomplete: true);
}
}
return _SourceRead(entries: entries, incomplete: true);
}
List<ReleaseEntry> _sortedUnique(List<ReleaseEntry> entries) {
final sorted = [...entries];
sorted.sort((a, b) {
final av = SemVer.parse(a.version);
final bv = SemVer.parse(b.version);
if (av != null && bv != null) {
final compared = bv.compareTo(av);
if (compared != 0) {
return compared;
}
}
final published = (b.published ?? '').compareTo(a.published ?? '');
if (published != 0) {
return published;
}
return (a.tag ?? '').compareTo(b.tag ?? '');
});
final seen = <String>{};
final unique = <ReleaseEntry>[];
for (final entry in sorted) {
final key = (entry.tag == null || entry.tag!.isEmpty)
? entry.version
: entry.tag!;
if (key.isEmpty || !seen.add(key)) {
continue;
}
unique.add(entry);
}
return unique;
}
ReleaseSync _offline({
required String? cachedJson,
required List<ReleaseEntry> bundled,
required bool rateLimited,
}) {
final cache = decodeReleaseCache(cachedJson);
if (cache != null) {
return ReleaseSync(
entries: cache.entries,
origin: HistoryOrigin.cache,
note: staleHistoryNote(
rateLimited: rateLimited,
hasCache: true,
sourceLabel: cacheSourceLabel(cache.source),
),
);
}
return ReleaseSync(
entries: bundled,
origin: HistoryOrigin.bundled,
note: staleHistoryNote(rateLimited: rateLimited, hasCache: false),
);
}
/// Same sync as [syncReleaseHistory], plus reading and writing the local cache.
/// [allowNetwork] is false in widget tests so opening history does not call out.
Future<ReleaseSync> syncAndStore({
required UpdateSource preferred,
required UpdateEndpoints endpoints,
required Future<String?> Function(Uri url) fetch,
required Future<String?> Function() readCache,
required Future<void> Function(String json) writeCache,
bool allowNetwork = true,
List<ReleaseEntry> bundled = releaseHistory,
int pageLimit = 5,
int githubPageSize = 100,
int giteaPageSize = 50,
}) async {
final cached = await readCache();
if (!allowNetwork) {
final stored = decodeReleaseCache(cached);
if (stored != null) {
return ReleaseSync(
entries: stored.entries,
origin: HistoryOrigin.cache,
note: '下面是上次保存的列表。',
);
}
return ReleaseSync(
entries: bundled,
origin: HistoryOrigin.bundled,
note: '',
);
}
final result = await syncReleaseHistory(
preferred: preferred,
endpoints: endpoints,
fetch: fetch,
cachedJson: cached,
bundled: bundled,
pageLimit: pageLimit,
githubPageSize: githubPageSize,
giteaPageSize: giteaPageSize,
);
final json = result.cacheJson;
if (json != null) {
await writeCache(json);
}
return result;
}
+22 -226
View File
@@ -3,65 +3,6 @@
import 'dart:convert'; import 'dart:convert';
/// Where release metadata is downloaded from. YanJiu Git is the default
/// because github.com is often blocked by DNS pollution on the user's network.
enum UpdateSource { gitea, github }
const updateSourceGitea = 'gitea';
const updateSourceGithub = 'github';
UpdateSource parseUpdateSource(String? raw) =>
raw == updateSourceGithub ? UpdateSource.github : UpdateSource.gitea;
String updateSourceId(UpdateSource source) =>
source == UpdateSource.github ? updateSourceGithub : updateSourceGitea;
String updateSourceLabel(UpdateSource source) =>
source == UpdateSource.github ? 'GitHub' : 'YanJiu Git';
/// Environment variables override the live release URLs. Empty values keep
/// the defaults, so a blank test variable does not point the client nowhere.
UpdateEndpoints updateEndpoints({String? githubApi, String? giteaApi}) {
return UpdateEndpoints(
github: githubApi == null || githubApi.trim().isEmpty
? UpdateEndpoints.githubDefault
: githubApi.trim(),
gitea: giteaApi == null || giteaApi.trim().isEmpty
? UpdateEndpoints.giteaDefault
: giteaApi.trim(),
);
}
/// 429, a spent quota header, or a 403 body that says the limit was hit.
bool isReleaseRateLimited({
required int status,
String? rateLimitRemaining,
required String body,
}) {
if (status == 429) {
return true;
}
if (status != 403) {
return false;
}
if (rateLimitRemaining == '0') {
return true;
}
return body.toLowerCase().contains('rate limit');
}
/// The release API refused the request because the caller asked too often.
class UpdateFetchException implements Exception {
const UpdateFetchException({required this.rateLimited, this.status});
final bool rateLimited;
final int? status;
@override
String toString() =>
'UpdateFetchException(rateLimited: $rateLimited, status: $status)';
}
/// Numeric version. A leading v and a +build suffix are ignored. /// Numeric version. A leading v and a +build suffix are ignored.
class SemVer implements Comparable<SemVer> { class SemVer implements Comparable<SemVer> {
const SemVer(this.major, this.minor, this.patch); const SemVer(this.major, this.minor, this.patch);
@@ -127,9 +68,6 @@ class UpdateEndpoints {
final String github; final String github;
final String gitea; final String gitea;
String latestFor(UpdateSource source) =>
source == UpdateSource.github ? github : gitea;
} }
class UpdateOffer { class UpdateOffer {
@@ -149,51 +87,14 @@ class UpdateOffer {
} }
class UpdateCheck { class UpdateCheck {
const UpdateCheck({ const UpdateCheck({this.offer, required this.reachable, this.message = ''});
this.offer,
required this.reachable,
this.message = '',
this.used,
this.fellBack = false,
});
final UpdateOffer? offer; final UpdateOffer? offer;
final bool reachable; final bool reachable;
final String message; final String message;
/// The source that actually answered. Null when neither source could be used.
final UpdateSource? used;
/// True when [used] is the spare source because the chosen one failed.
final bool fellBack;
} }
/// A bare `x64` token, as in `linux-x64`. `x86_64` does not contain this. /// Picks the client archive for this OS and CPU. Server packages are ignored.
final _bareX64 = RegExp(r'(^|[^a-z0-9])x64([^a-z0-9]|$)');
/// Published desktop archives use `linux-x64` and `windows-x64`. Older
/// names used `amd64`, `x86_64`, or `aarch64`. Those still match.
bool _desktopArchMatches(String name, String wantArch) {
if (name.contains(wantArch)) {
return true;
}
switch (wantArch) {
case 'amd64':
case 'x86_64':
case 'x64':
return name.contains('amd64') ||
name.contains('x86_64') ||
_bareX64.hasMatch(name);
case 'arm64':
case 'aarch64':
return name.contains('arm64') || name.contains('aarch64');
default:
return false;
}
}
/// Picks the client archive for this OS and CPU. Server and reflector
/// packages are ignored.
String? pickClientAsset( String? pickClientAsset(
List<ReleaseFile> assets, { List<ReleaseFile> assets, {
required String os, required String os,
@@ -212,11 +113,14 @@ String? pickClientAsset(
} }
continue; continue;
} }
if (!_desktopArchMatches(name, wantArch) || !name.contains(wantOs)) { final archOk =
name.contains(wantArch) ||
(wantArch == 'amd64' && name.contains('x86_64')) ||
(wantArch == 'arm64' && name.contains('aarch64'));
if (!archOk || !name.contains(wantOs)) {
continue; continue;
} }
if (wantOs == 'windows' && if (wantOs == 'windows' && (name.endsWith('.zip') || name.endsWith('.exe'))) {
(name.endsWith('.zip') || name.endsWith('.exe'))) {
return asset.name; return asset.name;
} }
if (wantOs == 'linux' && if (wantOs == 'linux' &&
@@ -278,8 +182,7 @@ UpdateCheck interpretRelease({
if (pickedName == null) { if (pickedName == null) {
return UpdateCheck( return UpdateCheck(
reachable: true, reachable: true,
message: message: '发现 ${remote.major}.${remote.minor}.${remote.patch},但没有适合这台设备的安装包',
'发现 ${remote.major}.${remote.minor}.${remote.patch},但没有适合这台设备的安装包',
); );
} }
final picked = assets.firstWhere((asset) => asset.name == pickedName); final picked = assets.firstWhere((asset) => asset.name == pickedName);
@@ -302,140 +205,33 @@ UpdateCheck interpretRelease({
); );
} }
enum _SourceFailure { down, rate }
/// Asks [preferred] first. A source that answers, even with "already current",
/// is kept. The other source is used only when the chosen one cannot be read,
/// and the message names the source that actually answered.
Future<UpdateCheck> findUpdate({ Future<UpdateCheck> findUpdate({
required String current, required String current,
required UpdateEndpoints endpoints, required UpdateEndpoints endpoints,
required UpdateSource preferred,
required Future<String?> Function(Uri url) fetch, required Future<String?> Function(Uri url) fetch,
required String os, required String os,
required String arch, required String arch,
}) async {
final order = preferred == UpdateSource.github
? const [UpdateSource.github, UpdateSource.gitea]
: const [UpdateSource.gitea, UpdateSource.github];
var sawRate = false;
var sawDown = false;
_SourceFailure? preferredFailure;
for (var i = 0; i < order.length; i++) {
final source = order[i];
final outcome = await _readLatest(
url: endpoints.latestFor(source),
fetch: fetch,
current: current,
os: os,
arch: arch,
);
final failure = outcome.failure;
if (failure == null) {
final check = outcome.check!;
final fellBack = i > 0;
return UpdateCheck(
reachable: true,
offer: check.offer,
used: source,
fellBack: fellBack,
message: _withSource(
check,
_sourceClause(
used: source,
fellBack: fellBack,
preferredFailure: preferredFailure,
),
),
);
}
if (i == 0) {
preferredFailure = failure;
}
if (failure == _SourceFailure.rate) {
sawRate = true;
} else {
sawDown = true;
}
}
return UpdateCheck(reachable: false, message: _bothFailed(sawRate, sawDown));
}
class _LatestOutcome {
const _LatestOutcome.ok(this.check) : failure = null;
const _LatestOutcome.fail(this.failure) : check = null;
final UpdateCheck? check;
final _SourceFailure? failure;
}
Future<_LatestOutcome> _readLatest({
required String url,
required Future<String?> Function(Uri url) fetch,
required String current,
required String os,
required String arch,
}) async { }) async {
String? body; String? body;
try { try {
body = await fetch(Uri.parse(url)); body = await fetch(Uri.parse(endpoints.github));
} on UpdateFetchException catch (error) {
if (error.rateLimited) {
return const _LatestOutcome.fail(_SourceFailure.rate);
}
return const _LatestOutcome.fail(_SourceFailure.down);
} on Object { } on Object {
return const _LatestOutcome.fail(_SourceFailure.down); body = null;
} }
if (body == null) { var check = interpretRelease(current: current, body: body, os: os, arch: arch);
return const _LatestOutcome.fail(_SourceFailure.down);
}
final check = interpretRelease(
current: current,
body: body,
os: os,
arch: arch,
);
if (!check.reachable) { if (!check.reachable) {
return const _LatestOutcome.fail(_SourceFailure.down); try {
body = await fetch(Uri.parse(endpoints.gitea));
} on Object {
body = null;
} }
return _LatestOutcome.ok(check); check = interpretRelease(current: current, body: body, os: os, arch: arch);
} if (!check.reachable) {
return const UpdateCheck(
String _sourceClause({ reachable: false,
required UpdateSource used, message: 'GitHub 和备用源都连不上,没有检查到更新',
required bool fellBack,
required _SourceFailure? preferredFailure,
}) {
final usedLabel = updateSourceLabel(used);
if (!fellBack) {
return '这次用的是 $usedLabel';
}
final preferredLabel = updateSourceLabel(
used == UpdateSource.github ? UpdateSource.gitea : UpdateSource.github,
); );
if (preferredFailure == _SourceFailure.rate) {
return '$preferredLabel 暂时限制了请求次数,这次用的是 $usedLabel';
} }
return '$preferredLabel 连不上,这次用的是 $usedLabel';
} }
return check;
String _withSource(UpdateCheck check, String clause) {
if (check.offer != null) {
return '发现 ${check.offer!.version}。可以下载并覆盖安装。($clause)';
}
if (check.message.isEmpty) {
return clause;
}
return '${check.message}($clause)';
}
String _bothFailed(bool sawRate, bool sawDown) {
if (sawRate && sawDown) {
return '所选更新源暂时限制了请求次数,另一个也连不上,没有检查到更新';
}
if (sawRate) {
return 'YanJiu Git 和 GitHub 都暂时限制了请求次数,请稍后再试';
}
return 'YanJiu Git 和 GitHub 都连不上,没有检查到更新';
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright (C) 2026 言灸 // Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
const appVersion = '1.1.4'; const appVersion = '1.1.3';
const appBuild = 7; const appBuild = 6;
const appAttribution = '言灸'; const appAttribution = '言灸';
const appLicense = 'AGPL-3.0-only'; const appLicense = 'AGPL-3.0-only';
+1 -1
View File
@@ -1,6 +1,6 @@
# 网络质量探测 · Linux 桌面客户端 # 网络质量探测 · Linux 桌面客户端
这是 1.1.4 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。HTTP 探测还需要同一目录里的 `netquality-reflector`。找不到或启动不了时,程序会立刻提示改用远程节点,不会把这次记成全部失败。 这是 1.1.3 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。HTTP 探测还需要同一目录里的 `netquality-reflector`。
## 先安装系统库 ## 先安装系统库
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 1.1.4+7 version: 1.1.3+6
environment: environment:
sdk: ^3.13.7 sdk: ^3.13.7
+2 -4
View File
@@ -84,12 +84,10 @@ void main() {
}); });
test('history only lists the real tag and this version', () { test('history only lists the real tag and this version', () {
expect(appVersion, '1.1.4'); expect(appVersion, '1.1.3');
expect(appBuild, 7); expect(appBuild, 6);
expect(appAttribution, '言灸'); expect(appAttribution, '言灸');
expect(releaseHistory.first.source, contains('言灸'));
expect(releaseHistory.map((entry) => entry.version), [ expect(releaseHistory.map((entry) => entry.version), [
'1.1.4',
'1.1.3', '1.1.3',
'1.1.2', '1.1.2',
'1.1.1', '1.1.1',
-73
View File
@@ -1,73 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/main.dart';
import 'package:netquality/models/port_field.dart';
import 'package:netquality/ui/expandable_hint.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
testWidgets('short hint text is not a button', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: ExpandableHint(text: 'HTTP 默认 5000 毫秒')),
),
);
expect(find.byType(InkWell), findsNothing);
final text = tester.widget<Text>(find.text('HTTP 默认 5000 毫秒'));
expect(text.maxLines, isNull);
expect(text.overflow, TextOverflow.clip);
});
testWidgets('a long hint expands and collapses', (tester) async {
const long =
'only the current port follows the previous default when it is empty or still that default';
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: SizedBox(width: 160, child: ExpandableHint(text: long)),
),
),
);
Text shown() => tester.widget<Text>(find.text(long));
expect(shown().maxLines, 1);
expect(shown().overflow, TextOverflow.ellipsis);
expect(find.byType(InkWell), findsOneWidget);
await tester.tap(find.text(long));
await tester.pump();
expect(shown().maxLines, isNull);
await tester.tap(find.text(long));
await tester.pump();
expect(shown().maxLines, 1);
expect(shown().overflow, TextOverflow.ellipsis);
});
testWidgets('the port helper on a phone can be expanded', (tester) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
final hint = find.text(portHelperText);
await tester.ensureVisible(hint);
await tester.pumpAndSettle();
Text shown() => tester.widget<Text>(hint);
expect(shown().maxLines, 1);
expect(shown().overflow, TextOverflow.ellipsis);
await tester.tap(hint);
await tester.pumpAndSettle();
expect(shown().maxLines, isNull);
expect(shown().overflow, TextOverflow.clip);
expect(find.textContaining('切换类型才会自动更换'), findsOneWidget);
await tester.ensureVisible(hint);
await tester.tap(hint);
await tester.pumpAndSettle();
expect(shown().maxLines, 1);
});
}
-214
View File
@@ -1,214 +0,0 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/models/http_target.dart';
import 'package:netquality/models/port_field.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/probe/http_helper.dart';
import 'package:netquality/probe/probe_controller.dart';
void main() {
test(
'bare hosts become http on port 80 and full URLs keep their own parts',
() {
final bare = parseHttpTarget('rxsend.cn');
expect(bare, isNotNull);
expect(bare!.url, 'http://rxsend.cn/');
expect(bare.port, 80);
expect(bare.scheme, 'http');
final path = parseHttpTarget('example.com/path?q=1');
expect(path!.url, 'http://example.com/path?q=1');
expect(path.port, 80);
final explicit = parseHttpTarget('example.com:8080/a');
expect(explicit!.url, 'http://example.com:8080/a');
expect(explicit.port, 8080);
expect(explicit.scheme, 'http');
final full = parseHttpTarget('https://www.cause-by-siky.top:2025/');
expect(full!.url, 'https://www.cause-by-siky.top:2025/');
expect(full.port, 2025);
expect(full.scheme, 'https');
expect(full.host, 'www.cause-by-siky.top');
final httpsDefault = parseHttpTarget('https://example.com/path');
expect(httpsDefault!.url, 'https://example.com/path');
expect(httpsDefault.port, 443);
final httpDefault = parseHttpTarget('http://example.com/path');
expect(httpDefault!.url, 'http://example.com/path');
expect(httpDefault.port, 80);
final v6 = parseHttpTarget('[2001:db8::1]');
expect(v6!.url, 'http://[2001:db8::1]/');
expect(v6.port, 80);
expect(v6.host, '2001:db8::1');
final v6Port = parseHttpTarget('[2001:db8::1]:8080/a');
expect(v6Port!.url, 'http://[2001:db8::1]:8080/a');
expect(v6Port.port, 8080);
final bareV6 = parseHttpTarget('2001:db8::1');
expect(bareV6!.url, 'http://[2001:db8::1]/');
expect(bareV6.port, 80);
},
);
test('invalid HTTP targets explain the problem in Chinese', () {
expect(httpTargetError(''), '请填写目标地址');
expect(httpTargetError(' '), '请填写目标地址');
expect(httpTargetError('ftp://example.com'), contains('http/https'));
expect(httpTargetError('https://example.com:99999/'), contains('端口'));
expect(httpTargetError('example.com:70000'), contains('端口'));
expect(parseHttpTarget('ftp://example.com'), isNull);
});
test('HTTP validation ignores the separate port and other profiles still require one', () {
final url = _config(
host: 'https://www.cause-by-siky.top:2025/path',
port: 0,
);
expect(url.validate(), isNull);
expect(url.httpTarget!.port, 2025);
expect(url.httpTarget!.url, 'https://www.cause-by-siky.top:2025/path');
final bare = _config(host: 'rxsend.cn', port: 19090);
expect(bare.validate(), isNull);
expect(bare.httpTarget!.url, 'http://rxsend.cn/');
expect(bare.httpTarget!.port, 80);
final bad = _config(host: 'ftp://example.com', port: 443);
expect(bad.validate(), contains('http/https'));
final family = _config(
host: 'https://203.0.113.9/path',
port: 0,
allow4: false,
);
expect(family.validate(), contains('IPv4'));
final tcp = _config(host: '203.0.113.8', port: 0, profileId: 'tcp-connect');
expect(tcp.validate(), contains('端口'));
expect(tcp.httpTarget, isNull);
});
test('HTTP timeout default is 5 seconds and a typed timeout stays', () {
expect(timeoutDefaultFor('http'), 5000);
expect(timeoutDefaultFor('nq-tcp'), 1000);
expect(
timeoutAfterProfileChange(
current: '1000',
previousDefault: 1000,
nextDefault: 5000,
),
'5000',
);
expect(
timeoutAfterProfileChange(
current: '2000',
previousDefault: 1000,
nextDefault: 5000,
),
'2000',
);
expect(
timeoutAfterProfileChange(
current: '5000',
previousDefault: 5000,
nextDefault: 1000,
),
'1000',
);
expect(
timeoutAfterProfileChange(
current: '',
previousDefault: 1000,
nextDefault: 5000,
),
'5000',
);
});
test(
'starting local HTTP without a helper does not open a loss run',
() async {
locateProbeHelperOverride = () => null;
addTearDown(() => locateProbeHelperOverride = null);
final controller = ProbeController();
addTearDown(controller.dispose);
await controller.start(
_config(host: 'rxsend.cn', port: 443),
nodeToken: '',
echoToken: '',
);
expect(controller.view.running, isFalse);
expect(controller.view.phase, '无法开始');
expect(controller.view.banner, helperMissingNote);
expect(controller.view.banner, contains('远程节点'));
expect(controller.view.samples, isEmpty);
expect(controller.view.summary.completed, 0);
expect(controller.view.report, isNull);
final started = DateTime.now();
await controller.start(
_config(host: 'https://www.cause-by-siky.top:2025/', port: 9),
nodeToken: '',
echoToken: '',
);
expect(DateTime.now().difference(started).inSeconds, lessThan(2));
expect(controller.view.running, isFalse);
expect(controller.view.report, isNull);
expect(controller.view.summary.completed, 0);
},
);
test(
'a missing local helper fails immediately and names the remote source',
() async {
final message = await localHttpBlockedReason(
binary: '/no/such/netquality-reflector',
);
expect(message, helperMissingNote);
expect(message, contains('远程节点'));
expect(message, contains('没有开始'));
},
);
test('a helper that cannot be executed fails immediately', () async {
final dir = Directory.systemTemp.createTempSync('nq-helper');
addTearDown(() => dir.deleteSync(recursive: true));
final file = File('${dir.path}/netquality-reflector')
..writeAsStringSync('not a binary');
final message = await localHttpBlockedReason(binary: file.path);
expect(message, helperStartFailedNote);
expect(message, contains('远程节点'));
});
}
SessionConfig _config({
required String host,
required int port,
String profileId = 'http',
bool allow4 = true,
}) {
return SessionConfig(
remote: false,
nodeId: '',
nodes: const [],
host: host,
port: port,
profileId: profileId,
intervalMs: 300,
timeoutMs: 5000,
durationSec: 60,
packetSize: 128,
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
allowIPv4: allow4,
);
}
-32
View File
@@ -6,7 +6,6 @@ import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart'; import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/probe/game_codec.dart'; import 'package:netquality/probe/game_codec.dart';
import 'package:netquality/probe/http_helper.dart';
import 'package:netquality/probe/probe_loop.dart'; import 'package:netquality/probe/probe_loop.dart';
import 'package:netquality/probe/remote_client.dart'; import 'package:netquality/probe/remote_client.dart';
@@ -390,37 +389,6 @@ void main() {
expect(samples.single.detail['httpVersion'], '1.1'); expect(samples.single.detail['httpVersion'], '1.1');
expect(samples.single.summary.failurePct, 0); expect(samples.single.summary.failurePct, 0);
}); });
test('a missing local http helper records no loss sample', () async {
final samples = <ProbeSample>[];
final loop = ProbeLoop(helperPath: '/no/such/netquality-reflector');
await expectLater(
loop.run(
request: const ProbeRequest(
host: 'http://127.0.0.1/health',
port: 80,
profileId: 'http',
interval: Duration(milliseconds: 200),
timeout: Duration(seconds: 1),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
onSample: samples.add,
cancelled: () => false,
),
throwsA(
isA<LocalHttpHelperException>().having(
(error) => error.message,
'message',
contains('远程节点'),
),
),
);
expect(samples, isEmpty);
});
} }
Future<List<ProbeSample>> _collect( Future<List<ProbeSample>> _collect(
-503
View File
@@ -1,503 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/content/release_history.dart';
import 'package:netquality/main.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/storage/app_store.dart';
import 'package:netquality/update/release_feed.dart';
import 'package:netquality/update/update_check.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _endpoints = UpdateEndpoints(
github: 'https://github.example/repos/yanjiu0721/netquality/releases/latest',
gitea: 'https://git.example/api/v1/repos/YanJiu/netquality/releases/latest',
);
const _bundledOnly = ReleaseEntry(
version: '0.9.1',
title: '安装包里的说明',
source: 'bundle',
points: ['只在安装包里'],
);
const _feed = '''
[
{
"tag_name": "v1.1.9",
"name": "网络质量探测 1.1.9",
"draft": false,
"prerelease": false,
"published_at": "2026-12-01T08:00:00Z",
"body": "# 网络质量探测 1.1.9\\n\\n## 在线历史\\n\\n- 可以读取比已安装版本更新的说明\\n\\n见 [发布页](https://example.test/r)。"
},
{
"tag_name": "v1.1.3",
"name": "网络质量探测 1.1.3",
"published_at": "2026-11-21T21:51:01+08:00",
"body": "构建号 6。"
},
{
"tag_name": "v1.2.0-rc.1",
"name": "网络质量探测 1.2.0 rc",
"prerelease": true,
"published_at": "2026-12-02T00:00:00Z",
"body": "预发布说明"
},
{
"tag_name": "v9.9.9",
"name": "不要出现的草稿",
"draft": true,
"body": "秘密"
},
{
"tag_name": "nightly",
"name": "不是版本号",
"body": "跳过"
}
]
''';
const _linuxAsset = '''
{"tag_name":"v1.1.9","assets":[
{"name":"netquality-client-1.1.9-linux-amd64.tar.gz","browser_download_url":"https://example.test/a.tar.gz"}
]}
''';
void main() {
test('the saved update source defaults to YanJiu Git', () {
expect(SessionConfig.defaults.updateSource, 'gitea');
expect(parseUpdateSource(null), UpdateSource.gitea);
expect(parseUpdateSource('github'), UpdateSource.github);
expect(parseUpdateSource('GitHub'), UpdateSource.gitea);
final stored = SessionConfig.fromJson({
...SessionConfig.defaults.toJson(),
'updateSource': 'github',
});
expect(stored.updateSource, 'github');
expect(stored.toJson()['updateSource'], 'github');
final unknown = SessionConfig.fromJson({
...SessionConfig.defaults.toJson(),
'updateSource': 'somewhere-else',
});
expect(unknown.updateSource, 'gitea');
final missing = SessionConfig.defaults.toJson()..remove('updateSource');
expect(SessionConfig.fromJson(missing).updateSource, 'gitea');
});
test('env overrides replace only a non-empty release URL', () {
expect(updateEndpoints().github, UpdateEndpoints.githubDefault);
expect(updateEndpoints().gitea, UpdateEndpoints.giteaDefault);
expect(
updateEndpoints(githubApi: ' ').github,
UpdateEndpoints.githubDefault,
);
final overridden = updateEndpoints(
githubApi: ' https://example.test/latest ',
giteaApi: 'https://git.example/latest',
);
expect(overridden.github, 'https://example.test/latest');
expect(overridden.gitea, 'https://git.example/latest');
});
test(
'a chosen source that answers is named and the other is not called',
() async {
final hosts = <String>[];
final check = await findUpdate(
current: '1.1.3',
preferred: UpdateSource.gitea,
endpoints: _endpoints,
os: 'linux',
arch: 'amd64',
fetch: (url) async {
hosts.add(url.host);
return _linuxAsset;
},
);
expect(hosts, ['git.example']);
expect(check.used, UpdateSource.gitea);
expect(check.fellBack, isFalse);
expect(check.offer?.version, '1.1.9');
expect(check.offer?.assetUrl, 'https://example.test/a.tar.gz');
expect(check.message, contains('这次用的是 YanJiu Git'));
expect(check.message, isNot(contains('改用')));
},
);
test(
'an unreachable chosen source falls back and names the one that worked',
() async {
final check = await findUpdate(
current: '1.1.3',
preferred: UpdateSource.gitea,
endpoints: _endpoints,
os: 'linux',
arch: 'amd64',
fetch: (url) async => url.host == 'git.example' ? null : _linuxAsset,
);
expect(check.used, UpdateSource.github);
expect(check.fellBack, isTrue);
expect(check.message, contains('YanJiu Git 连不上'));
expect(check.message, contains('这次用的是 GitHub'));
},
);
test(
'a rate limit falls back and the message says which source was used',
() async {
final check = await findUpdate(
current: '1.1.3',
preferred: UpdateSource.gitea,
endpoints: _endpoints,
os: 'linux',
arch: 'amd64',
fetch: (url) async {
if (url.host == 'git.example') {
throw const UpdateFetchException(rateLimited: true, status: 429);
}
return _linuxAsset;
},
);
expect(check.used, UpdateSource.github);
expect(check.message, contains('暂时限制了请求次数'));
expect(check.message, contains('这次用的是 GitHub'));
},
);
test('both sources down, or both rate limited, stay unnamed', () async {
final down = await findUpdate(
current: '1.1.3',
preferred: UpdateSource.gitea,
endpoints: _endpoints,
os: 'linux',
arch: 'amd64',
fetch: (_) async => null,
);
expect(down.reachable, isFalse);
expect(down.used, isNull);
expect(down.message, 'YanJiu Git 和 GitHub 都连不上,没有检查到更新');
final limited = await findUpdate(
current: '1.1.3',
preferred: UpdateSource.github,
endpoints: _endpoints,
os: 'linux',
arch: 'amd64',
fetch: (_) async {
throw const UpdateFetchException(rateLimited: true, status: 403);
},
);
expect(limited.message, contains('都暂时限制了请求次数'));
});
test(
'rate-limit responses are recognized without treating every 403 as one',
() {
expect(isReleaseRateLimited(status: 429, body: ''), isTrue);
expect(
isReleaseRateLimited(status: 403, rateLimitRemaining: '0', body: 'no'),
isTrue,
);
expect(
isReleaseRateLimited(
status: 403,
body: 'API rate limit exceeded for 1.2.3.4',
),
isTrue,
);
expect(isReleaseRateLimited(status: 403, body: 'forbidden'), isFalse);
expect(isReleaseRateLimited(status: 200, body: 'rate limit'), isFalse);
},
);
test('list URLs follow the latest override and the forge page size', () {
final gitea = releaseListUri(
_endpoints.gitea,
source: UpdateSource.gitea,
page: 2,
pageSize: 50,
);
expect(gitea.path, '/api/v1/repos/YanJiu/netquality/releases');
expect(gitea.queryParameters['limit'], '50');
expect(gitea.queryParameters['page'], '2');
expect(gitea.queryParameters.containsKey('per_page'), isFalse);
final github = releaseListUri(
_endpoints.github,
source: UpdateSource.github,
page: 1,
pageSize: 100,
);
expect(github.path, '/repos/yanjiu0721/netquality/releases');
expect(github.queryParameters['per_page'], '100');
expect(github.queryParameters.containsKey('limit'), isFalse);
});
test('a release list keeps newer published notes and drops drafts', () async {
final result = await syncReleaseHistory(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
bundled: const [_bundledOnly],
fetch: (url) async {
expect(url.host, 'git.example');
return _feed;
},
);
expect(result.origin, HistoryOrigin.remote);
expect(result.used, UpdateSource.gitea);
expect(result.entries.map((entry) => entry.version), [
'1.2.0',
'1.1.9',
'1.1.3',
]);
expect(result.entries.map((entry) => entry.tag), [
'v1.2.0-rc.1',
'v1.1.9',
'v1.1.3',
]);
final newest = result.entries[1];
expect(newest.title, '网络质量探测 1.1.9');
expect(newest.published, '2026-12-01');
expect(newest.points, contains('可以读取比已安装版本更新的说明'));
expect(newest.points, contains('见 发布页(https://example.test/r)。'));
expect(newest.points, isNot(contains('网络质量探测 1.1.9')));
expect(result.entries.first.source, contains('预发布'));
expect(result.entries.first.published, '2026-12-02');
expect(
result.entries.map((entry) => entry.title),
isNot(contains('不要出现的草稿')),
);
expect(
result.entries.map((entry) => entry.version),
isNot(contains('0.9.1')),
);
expect(
result.entries.map((entry) => entry.version),
isNot(contains('1.1.0')),
);
expect(result.note, contains('已从 YanJiu Git 同步'));
expect(result.note, contains('比当前安装更新的发布也会列在这里'));
final again = decodeReleaseCache(result.cacheJson);
expect(again?.source, 'gitea');
expect(again?.entries.map((entry) => entry.version), [
'1.2.0',
'1.1.9',
'1.1.3',
]);
});
test('pages are followed, and a full last page says the list may be short', () async {
final pages = <int>[];
final result = await syncReleaseHistory(
preferred: UpdateSource.github,
endpoints: _endpoints,
githubPageSize: 1,
fetch: (url) async {
expect(url.host, 'github.example');
expect(url.queryParameters['per_page'], '1');
expect(url.path, isNot(endsWith('/latest')));
final page = int.parse(url.queryParameters['page']!);
pages.add(page);
if (page == 1) {
return '[{"tag_name":"v1.1.9","name":"新","published_at":"2026-12-01T00:00:00Z","body":"新说明"}]';
}
if (page == 2) {
return '[{"tag_name":"v1.1.3","name":"旧","published_at":"2026-11-21T00:00:00Z","body":"旧说明"}]';
}
return '[]';
},
);
expect(pages, [1, 2, 3]);
expect(result.entries.map((entry) => entry.version), ['1.1.9', '1.1.3']);
final capped = await syncReleaseHistory(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
pageLimit: 1,
giteaPageSize: 1,
fetch: (_) async => '[{"tag_name":"v1.1.9","name":"新","body":"只有第一页"}]',
);
expect(capped.entries, hasLength(1));
expect(capped.note, contains('没有取完'));
});
test(
'history uses the spare source when the chosen one cannot be read',
() async {
final result = await syncReleaseHistory(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
bundled: const [_bundledOnly],
fetch: (url) async {
if (url.host == 'git.example') {
throw const UpdateFetchException(rateLimited: true, status: 429);
}
return _feed;
},
);
expect(result.used, UpdateSource.github);
expect(result.note, contains('暂时限制了请求次数'));
expect(result.note, contains('这次改用了 GitHub'));
expect(result.entries.first.version, '1.2.0');
expect(result.entries.any((entry) => entry.version == '0.9.1'), isFalse);
},
);
test(
'a failed sync keeps the cache, then the bundled notes, and says so',
() async {
String? stored;
final fresh = await syncAndStore(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
readCache: () async => null,
writeCache: (json) async => stored = json,
fetch: (url) async => url.host == 'git.example' ? _feed : null,
);
expect(fresh.origin, HistoryOrigin.remote);
expect(stored, isNotNull);
final cached = await syncReleaseHistory(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
cachedJson: stored,
bundled: const [_bundledOnly],
fetch: (_) async => null,
);
expect(cached.origin, HistoryOrigin.cache);
expect(cached.entries.first.version, '1.2.0');
expect(cached.note, contains('可能不是最新'));
expect(cached.note, contains('上次从 YanJiu Git 保存的列表'));
expect(cached.entries.any((entry) => entry.version == '0.9.1'), isFalse);
final bundled = await syncReleaseHistory(
preferred: UpdateSource.github,
endpoints: _endpoints,
cachedJson: '{',
bundled: const [_bundledOnly],
fetch: (_) async => null,
);
expect(bundled.origin, HistoryOrigin.bundled);
expect(bundled.entries, [_bundledOnly]);
expect(bundled.note, contains('没有保存过在线列表'));
expect(bundled.note, contains('安装包里的说明'));
expect(bundled.note, contains('可能不是最新'));
final limited = await syncReleaseHistory(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
cachedJson: null,
bundled: const [_bundledOnly],
fetch: (_) async {
throw const UpdateFetchException(rateLimited: true, status: 429);
},
);
expect(limited.origin, HistoryOrigin.bundled);
expect(limited.note, contains('暂时限制了请求次数'));
expect(limited.note, contains('可能不是最新'));
},
);
test(
'an empty published list is kept and does not invent bundled versions',
() async {
final result = await syncReleaseHistory(
preferred: UpdateSource.gitea,
endpoints: _endpoints,
bundled: const [_bundledOnly],
fetch: (_) async => '[]',
);
expect(result.origin, HistoryOrigin.remote);
expect(result.entries, isEmpty);
expect(result.note, contains('没有已发布的版本'));
expect(result.cacheJson, isNotNull);
},
);
testWidgets('settings defaults to YanJiu Git and remembers GitHub', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(900, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
await _openSettings(tester);
expect(_selectedSource(tester), {UpdateSource.gitea});
expect(find.textContaining('先试 GitHub'), findsNothing);
expect(find.textContaining('先问 GitHub'), findsNothing);
expect(find.textContaining('结果里会写明这次实际用的是哪一个'), findsOneWidget);
await tester.tap(
find.descendant(
of: find.byKey(const Key('update-source')),
matching: find.text('GitHub'),
),
);
await tester.pumpAndSettle();
expect(_selectedSource(tester), {UpdateSource.github});
final prefs = await SharedPreferences.getInstance();
expect(
prefs.getString('netquality.settings.v2'),
contains('"updateSource":"github"'),
);
final loaded = await AppStore().load();
expect(loaded.config.updateSource, 'github');
expect(parseUpdateSource(loaded.config.updateSource), UpdateSource.github);
});
testWidgets('history shows a cached release newer than this install', (
tester,
) async {
final cache = encodeReleaseCache(
source: 'gitea',
entries: const [
ReleaseEntry(
version: '9.9.9',
tag: 'v9.9.9',
title: '网络质量探测 9.9.9',
source: '来自 YanJiu Git · 标签 v9.9.9',
published: '2026-12-01',
points: ['比已安装的版本新'],
),
],
);
SharedPreferences.setMockInitialValues({releaseHistoryCacheKey: cache});
tester.view.physicalSize = const Size(900, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
await tester.tap(find.byType(PopupMenuButton<String>));
await tester.pumpAndSettle();
await tester.tap(find.text('更新历史'));
await tester.pumpAndSettle();
expect(find.text('网络质量探测 9.9.9'), findsOneWidget);
expect(find.text('比当前安装的 1.1.4 新'), findsOneWidget);
expect(find.text('网络质量探测 1.1.1'), findsNothing);
expect(find.textContaining('已经发布的 1.1.2 和 1.1.3'), findsOneWidget);
expect(find.textContaining('可能不是最新'), findsNothing);
});
}
Set<UpdateSource> _selectedSource(WidgetTester tester) {
return tester
.widget<SegmentedButton<UpdateSource>>(
find.byKey(const Key('update-source')),
)
.selected;
}
Future<void> _openSettings(WidgetTester tester) async {
await tester.tap(find.byType(PopupMenuButton<String>));
await tester.pumpAndSettle();
await tester.tap(find.text('设置'));
await tester.pumpAndSettle();
}
-91
View File
@@ -47,96 +47,9 @@ void main() {
expect(check.offer?.checksumName, 'SHA256SUMS'); expect(check.offer?.checksumName, 'SHA256SUMS');
}); });
test('published x64 desktop names match, and server or reflector packages do not', () {
const published = [
ReleaseFile(name: 'netquality-1.1.3-arm64-v8a.apk', url: 'a1'),
ReleaseFile(name: 'netquality-1.1.3-armeabi-v7a.apk', url: 'a2'),
ReleaseFile(name: 'netquality-1.1.3-linux-x64.tar.gz', url: 'linux'),
ReleaseFile(name: 'netquality-1.1.3-release-notes.txt', url: 'notes'),
ReleaseFile(name: 'netquality-1.1.3-SHA256SUMS.txt', url: 'sum'),
ReleaseFile(name: 'netquality-1.1.3-windows-x64.zip', url: 'win'),
ReleaseFile(name: 'netquality-1.1.3-x86_64.apk', url: 'a3'),
ReleaseFile(name: 'netquality-server-1.1.3-linux-amd64.tar.gz', url: 's1'),
ReleaseFile(name: 'netquality-server-1.1.3-linux-arm64.tar.gz', url: 's2'),
ReleaseFile(name: 'netquality-server-1.1.3-windows-amd64.zip', url: 's3'),
ReleaseFile(name: 'netquality-reflector-1.1.3-linux-x64.tar.gz', url: 'r'),
];
expect(
pickClientAsset(published, os: 'linux', arch: 'amd64'),
'netquality-1.1.3-linux-x64.tar.gz',
);
expect(
pickClientAsset(published, os: 'windows', arch: 'amd64'),
'netquality-1.1.3-windows-x64.zip',
);
expect(
pickClientAsset(published, os: 'android', arch: 'arm64-v8a'),
'netquality-1.1.3-arm64-v8a.apk',
);
expect(
pickClientAsset(published, os: 'android', arch: 'armeabi-v7a'),
'netquality-1.1.3-armeabi-v7a.apk',
);
expect(
pickClientAsset(published, os: 'android', arch: 'x86_64'),
'netquality-1.1.3-x86_64.apk',
);
expect(
pickClientAsset(const [
ReleaseFile(name: 'netquality-server-1.1.3-linux-amd64.tar.gz', url: 's'),
ReleaseFile(name: 'netquality-reflector-1.1.3-linux-x64.tar.gz', url: 'r'),
ReleaseFile(name: 'netquality-server-1.1.3-windows-amd64.zip', url: 's'),
], os: 'linux', arch: 'amd64'),
isNull,
);
expect(
pickClientAsset(const [
ReleaseFile(name: 'netquality-client-1.1.4-linux-x86_64.tar.gz', url: 'c'),
], os: 'linux', arch: 'amd64'),
'netquality-client-1.1.4-linux-x86_64.tar.gz',
);
expect(
pickClientAsset(const [
ReleaseFile(name: 'netquality-client-1.1.4-linux-aarch64.tar.gz', url: 'c'),
], os: 'linux', arch: 'arm64'),
'netquality-client-1.1.4-linux-aarch64.tar.gz',
);
expect(
pickClientAsset(const [
ReleaseFile(name: 'netquality-client-1.1.4-windows-amd64.zip', url: 'c'),
], os: 'windows', arch: 'x64'),
'netquality-client-1.1.4-windows-amd64.zip',
);
expect(
pickClientAsset(const [
ReleaseFile(name: 'netquality-1.1.4-linux-box64.tar.gz', url: 'no'),
], os: 'linux', arch: 'amd64'),
isNull,
);
final check = interpretRelease(
current: '1.1.3',
os: 'linux',
arch: 'amd64',
body: '''
{
"tag_name": "v1.1.4",
"assets": [
{"name": "netquality-server-1.1.4-linux-amd64.tar.gz", "browser_download_url": "https://example.test/server.tar.gz"},
{"name": "netquality-1.1.4-linux-x64.tar.gz", "browser_download_url": "https://example.test/linux.tar.gz"},
{"name": "netquality-1.1.4-windows-x64.zip", "browser_download_url": "https://example.test/windows.zip"}
]
}
''',
);
expect(check.offer?.assetName, 'netquality-1.1.4-linux-x64.tar.gz');
expect(check.message, isNot(contains('没有适合这台设备的安装包')));
});
test('github failure falls through to the spare source', () async { test('github failure falls through to the spare source', () async {
final check = await findUpdate( final check = await findUpdate(
current: '1.1.3', current: '1.1.3',
preferred: UpdateSource.github,
endpoints: const UpdateEndpoints( endpoints: const UpdateEndpoints(
github: 'https://github.invalid/latest', github: 'https://github.invalid/latest',
gitea: 'https://git.invalid/latest', gitea: 'https://git.invalid/latest',
@@ -155,10 +68,6 @@ void main() {
}, },
); );
expect(check.offer?.version, '1.1.9'); expect(check.offer?.version, '1.1.9');
expect(check.used, UpdateSource.gitea);
expect(check.fellBack, isTrue);
expect(check.message, contains('GitHub'));
expect(check.message, contains('YanJiu Git'));
}); });
test('history keeps the newest identical target and can delete or clear', () { test('history keeps the newest identical target and can delete or clear', () {
-37
View File
@@ -81,43 +81,6 @@ void main() {
}, },
); );
testWidgets('HTTP mode uses a URL, a 5 second timeout, and no port field', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1280, 1800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
await tester.ensureVisible(find.byKey(const Key('profile')));
await tester.tap(find.byKey(const Key('profile')));
await tester.pumpAndSettle();
await tester.tap(find.text('HTTP').last);
await tester.pumpAndSettle();
expect(find.byKey(const Key('port-field')), findsNothing);
expect(find.text('HTTP 默认 5000 毫秒'), findsOneWidget);
expect(find.text('5000'), findsWidgets);
expect(
find.text('只填主机名或 IP 时按 http:// 和端口 80。完整网址使用其中的协议、端口和路径。'),
findsOneWidget,
);
expect(find.byKey(const Key('target-field')), findsOneWidget);
await tester.enterText(find.byKey(const Key('timeout-field')), '2000');
await tester.tap(find.byKey(const Key('profile')));
await tester.pumpAndSettle();
await tester.tap(find.text('合作反射 UDP').last);
await tester.pumpAndSettle();
expect(find.byKey(const Key('port-field')), findsOneWidget);
expect(find.text('19091'), findsWidgets);
expect(find.text('2000'), findsOneWidget);
expect(find.text('HTTP 默认 5000 毫秒'), findsNothing);
});
testWidgets('editing a node keeps its id and does not reveal the token', ( testWidgets('editing a node keeps its id and does not reveal the token', (
tester, tester,
) async { ) async {
+2 -2
View File
@@ -85,9 +85,9 @@
| `referer` / `userAgent` / `cookies` | 可选,各最长 4KB | | `referer` / `userAgent` / `cookies` | 可选,各最长 4KB |
| `maxRedirects` | 0 到 20,不写时是 5。301/302/303 改为 GET 并丢掉正文;307/308 保持方法和正文。最终状态码是最后一跳的 | | `maxRedirects` | 0 到 20,不写时是 5。301/302/303 改为 GET 并丢掉正文;307/308 保持方法和正文。最终状态码是最后一跳的 |
目标可以是主机名,也可以是完整的 `http://` 或 `https://` URL(可带端口、路径和查询)。没有写协议时按 `http`。没有写端口时,http 用 80,https 用 443。URL 里已经写了端口就用那个端口。请求里的 `port` 可以省略或写 0;如果 URL 自己没有端口,而 `port` 仍是 1 到 65535,就用这个 `port`,以便旧客户端继续工作。非 HTTP 类型仍然必须带 1 到 65535 的端口。 目标可以是主机名,也可以是完整的 `http://` 或 `https://` URL。没写端口时,https 用 443,http 用 80。
本机探测不在 Dart 里另写一套 HTTP。桌面和 Android 都把请求交给同一个 Go 程序的 `-mode helper`,一行 JSON 进、一行结果出。环境变量 `NQ_PROBE_HELPER` 可以指向这个程序;不设置时,客户端在自己的可执行文件旁边找 `netquality-reflector`。找不到或启动不了时,本机 HTTP 立刻失败并说明原因,建议改用远程节点,不会记成一次全部失败的探测。Android 安装包不包含这个程序。 本机探测不在 Dart 里另写一套 HTTP。桌面和 Android 都把请求交给同一个 Go 程序的 `-mode helper`,一行 JSON 进、一行结果出。环境变量 `NQ_PROBE_HELPER` 可以指向这个程序;不设置时,客户端在自己的可执行文件旁边找 `netquality-reflector`。
## 中心 ## 中心
-58
View File
@@ -1,58 +0,0 @@
# 网络质量探测 1.1.4
版本名 `1.1.4`,构建号 `7`。署名:言灸。许可:GNU Affero General Public License v3.0(AGPL-3.0-only)。
应用标识没有改,仍是 `dev.netquality.netquality`。签名也没有改。1.1.3 以及以后的安装包沿用仓库里的同一把调试证书,新的 Android 安装包会覆盖 1.1.3,不用先卸载。安装时 Android 仍会弹出系统安装确认,这一步不能跳过。1.1.2 的证书不同,从 1.1.2 升级仍要先卸载。
Git 标签是 `v1.1.4`。
## 更新源
设置里可以选择更新源:「YanJiu Git」或「GitHub」。默认是 YanJiu Git,因为这边的网络经常解析不到 github.com。检查更新和下载安装都先用选中的源。选中的源连不上,或暂时限制了请求次数时,会自动试另一个,结果里会写明这次实际用的是哪一个。
环境变量 `NQ_UPDATE_GITHUB_API` 和 `NQ_UPDATE_GITEA_API` 仍然可以指向一份同样格式的测试响应。
1.1.2 没有自更新,升级仍要自己安装。
## 更新历史
「更新历史」会向所选更新源读取发布列表,不只看最新一条。已经发布的版本都会列出来,包括比当前安装更新的版本。草稿和不是版本号的标签不会出现。
成功同步后会在本机留一份。网络失败时用上次保存的列表;没有保存过就用安装包里的说明,并标明这份列表可能不是最新。
已经发布的 1.1.2 和 1.1.3 安装包没有这份同步。那些版本不会自己看到以后的发布说明,需要先安装包含这个功能的版本。
## 被截断的说明
表单里放不下一行的提示,末尾会显示省略号。点一下展开全文,再点一下收回。本来就能显示完的短句不用点。
## HTTP 目标
HTTP 探测的目标是完整网址,或只写主机名、IP。完整网址沿用其中的协议、端口和路径。只写主机名或 IP 时按 http,端口 80,不再单独填端口。超时默认 5000 毫秒。
本机找不到或启动不了 `netquality-reflector` 时会立刻说明原因,并建议改用远程节点,不会把这次记成全部失败。Android 安装包不包含这个程序。
## 桌面安装包文件名
规范名仍是:
- `netquality-1.1.4-linux-x64.tar.gz`
- `netquality-1.1.4-windows-x64.zip`
1.1.3 的更新器只在名字里找 `amd64` 或 `x86_64`,认不出单独的 `x64`。Linux 这一版另外放了一份内容相同的兼容名,校验和也相同:
- `netquality-1.1.4-linux-x86_64.tar.gz`(与 `linux-x64` 是同一份文件)
1.1.3 的 Linux 会选中带 `x86_64` 的那一份并自己安装,不必因为认不出 `x64` 而手动升级。Windows 桌面客户端要在 Windows 上构建。构建出来以后,除了规范名 `windows-x64`,再放一份字节相同的 `netquality-1.1.4-windows-x86_64.zip`,1.1.3 的 Windows 才会自己安装。这份文件还没放上时,Windows 仍要自己安装。从这一版起,`linux-x64` 和 `windows-x64` 会被认成当前机器的 64 位包。以前的 `amd64`、`x86_64`、`aarch64` 也仍然接受。1.1.2 没有更新器,升级仍要自己安装。
名字里带 `server` 或 `reflector` 的包继续跳过,不会被客户端下载。Android 的 `arm64-v8a`、`armeabi-v7a`、`x86_64` 本来就能对上。常见手机优先使用 arm64-v8a。
这一版已经附上的客户端文件名:
- `netquality-1.1.4-linux-x64.tar.gz`
- `netquality-1.1.4-linux-x86_64.tar.gz`(与上一份相同)
- `netquality-1.1.4-arm64-v8a.apk`
- `netquality-1.1.4-armeabi-v7a.apk`
- `netquality-1.1.4-x86_64.apk`
Linux 桌面压缩包里,`netquality-reflector` 放在客户端旁边,新装的系统才能做本机 HTTP 探测。Android 安装包不包含这个程序。Windows 桌面压缩包同样应当把 `netquality-reflector.exe` 放在 `netquality.exe` 旁边,但这一次的构建机不是 Windows,没有生成那个压缩包。
+1 -1
View File
@@ -63,7 +63,7 @@ ss -lunp | grep 19091
```bash ```bash
sudo mkdir -p /opt/netquality sudo mkdir -p /opt/netquality
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.4-linux-amd64.tar.gz sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.3-linux-amd64.tar.gz
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl enable --now netquality sudo systemctl enable --now netquality
+1 -1
View File
@@ -111,7 +111,7 @@ sudo firewall-cmd --reload
```bash ```bash
sudo mkdir -p /opt/netquality sudo mkdir -p /opt/netquality
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.4-linux-amd64.tar.gz sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.3-linux-amd64.tar.gz
sudo chmod 755 /opt/netquality/netquality-reflector sudo chmod 755 /opt/netquality/netquality-reflector
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
sudo systemctl daemon-reload sudo systemctl daemon-reload
+7 -17
View File
@@ -460,7 +460,10 @@ func buildHTTPURL(target string, port int) (*url.URL, error) {
} }
raw := target raw := target
if !strings.Contains(raw, "://") { if !strings.Contains(raw, "://") {
// A bare host or IP is HTTP on port 80 unless the text itself has a port. scheme := "https"
if port == 80 {
scheme = "http"
}
hostpart := raw hostpart := raw
path := "" path := ""
if i := strings.Index(raw, "/"); i >= 0 { if i := strings.Index(raw, "/"); i >= 0 {
@@ -469,30 +472,17 @@ func buildHTTPURL(target string, port int) (*url.URL, error) {
if strings.Count(hostpart, ":") >= 2 && !strings.HasPrefix(hostpart, "[") { if strings.Count(hostpart, ":") >= 2 && !strings.HasPrefix(hostpart, "[") {
hostpart = "[" + hostpart + "]" hostpart = "[" + hostpart + "]"
} }
raw = "http://" + hostpart + path raw = scheme + "://" + hostpart + path
} }
u, err := url.Parse(raw) u, err := url.Parse(raw)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") { if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") {
return nil, errors.New("HTTP 目标需要是主机名或 http/https 网址") return nil, errors.New("HTTP 目标需要是主机名或 http/https 网址")
} }
if u.Port() == "" { if u.Port() == "" {
use := port if port < 1 || port > 65535 {
if use == 0 {
if u.Scheme == "https" {
use = 443
} else {
use = 80
}
}
if use < 1 || use > 65535 {
return nil, errors.New("端口需要在 1 到 65535 之间")
}
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(use))
} else {
parsed, err := strconv.Atoi(u.Port())
if err != nil || parsed < 1 || parsed > 65535 {
return nil, errors.New("端口需要在 1 到 65535 之间") return nil, errors.New("端口需要在 1 到 65535 之间")
} }
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(port))
} }
if u.Path == "" { if u.Path == "" {
u.Path = "/" u.Path = "/"
-106
View File
@@ -332,112 +332,6 @@ func TestHelperSpeaksHTTPEngine(t *testing.T) {
} }
} }
func TestBuildHTTPURLDefaults(t *testing.T) {
cases := []struct {
target string
wire int
scheme string
host string
port string
path string
query string
}{
{"example.com", 0, "http", "example.com", "80", "/", ""},
{"example.com", 80, "http", "example.com", "80", "/", ""},
{"example.com", 443, "http", "example.com", "443", "/", ""},
{"rxsend.cn", 0, "http", "rxsend.cn", "80", "/", ""},
{"https://www.cause-by-siky.top:2025/", 80, "https", "www.cause-by-siky.top", "2025", "/", ""},
{"https://www.cause-by-siky.top:2025/a?q=1", 9, "https", "www.cause-by-siky.top", "2025", "/a", "q=1"},
{"http://example.com/path", 0, "http", "example.com", "80", "/path", ""},
{"https://example.com/path", 0, "https", "example.com", "443", "/path", ""},
{"example.com:8080/a", 443, "http", "example.com", "8080", "/a", ""},
{"example.com/path?q=1", 0, "http", "example.com", "80", "/path", "q=1"},
{"[2001:db8::1]", 0, "http", "2001:db8::1", "80", "/", ""},
{"[2001:db8::1]:8080/a", 80, "http", "2001:db8::1", "8080", "/a", ""},
{"2001:db8::1", 0, "http", "2001:db8::1", "80", "/", ""},
}
for _, tc := range cases {
u, err := buildHTTPURL(tc.target, tc.wire)
if err != nil {
t.Fatalf("%s port %d: %v", tc.target, tc.wire, err)
}
if u.Scheme != tc.scheme || u.Hostname() != tc.host || u.Port() != tc.port || u.Path != tc.path || u.RawQuery != tc.query {
t.Fatalf("%s port %d -> %s", tc.target, tc.wire, u.String())
}
}
if _, err := buildHTTPURL("", 80); err == nil || !strings.Contains(err.Error(), "目标地址") {
t.Fatal(err)
}
if _, err := buildHTTPURL("ftp://example.com", 80); err == nil || !strings.Contains(err.Error(), "http/https") {
t.Fatal(err)
}
if _, err := buildHTTPURL("https://example.com:99999/", 80); err == nil || !strings.Contains(err.Error(), "端口") {
t.Fatal(err)
}
if _, err := buildHTTPURL("example.com", 70000); err == nil || !strings.Contains(err.Error(), "端口") {
t.Fatal(err)
}
}
func TestHTTPExplicitURLPortIgnoresField(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/health" {
http.NotFound(w, r)
return
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
out := probeHTTP(context.Background(), HTTPInput{
Target: srv.URL + "/health", Port: 1, Version: "1.1",
Allow4: true, Allow6: true, Timeout: 3 * time.Second,
})
if out.Status != statusOK || out.Detail["statusCode"] != "204" {
t.Fatalf("url port should win: %s %s %+v", out.Status, out.Note, out.Detail)
}
omitted := probeHTTP(context.Background(), HTTPInput{
Target: srv.URL + "/health", Port: 0, Version: "1.1",
Allow4: true, Allow6: true, Timeout: 3 * time.Second,
})
if omitted.Status != statusOK || omitted.Detail["statusCode"] != "204" {
t.Fatalf("omitted port: %s %s %+v", omitted.Status, omitted.Note, omitted.Detail)
}
}
func TestHTTPJobAcceptsURLWithoutPortField(t *testing.T) {
page := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
}))
defer page.Close()
node := newNode("", true, nil, testLimits())
ts := httptest.NewServer(node.Handler())
defer ts.Close()
created := postJSON(t, ts.URL+"/v1/jobs", `{"target":"`+page.URL+`/","port":0,"profile":"http","intervalMs":200,"timeoutMs":1500,"durationSec":2,"http":{"version":"1.1","method":"GET"}}`)
defer created.Body.Close()
if created.StatusCode != http.StatusCreated {
raw, _ := io.ReadAll(created.Body)
t.Fatalf("http without port field %d %s", created.StatusCode, raw)
}
var job map[string]any
if err := json.NewDecoder(created.Body).Decode(&job); err != nil {
t.Fatal(err)
}
id, _ := job["jobId"].(string)
sample := readSampleURL(t, ts.URL+"/v1/jobs/"+id+"/stream")
if sample["status"] != statusOK {
t.Fatalf("sample %+v", sample)
}
detail, _ := sample["detail"].(map[string]any)
if detail["statusCode"] != "202" {
t.Fatalf("detail %+v", detail)
}
tcp := postJSON(t, ts.URL+"/v1/jobs", `{"target":"127.0.0.1","port":0,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1}`)
defer tcp.Body.Close()
if tcp.StatusCode != http.StatusBadRequest {
t.Fatalf("tcp still requires a port, got %d", tcp.StatusCode)
}
}
func tlsInput(target string, port int, version string, pool *x509.CertPool) HTTPInput { func tlsInput(target string, port int, version string, pool *x509.CertPool) HTTPInput {
return HTTPInput{ return HTTPInput{
Target: target, Port: port, Version: version, Resolve: "127.0.0.1", Target: target, Port: port, Version: version, Resolve: "127.0.0.1",
+2 -9
View File
@@ -11,7 +11,6 @@ import (
"io" "io"
"net" "net"
"net/http" "net/http"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -225,7 +224,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
} }
allow4 := flagOrDefault(req.AllowIPv4, true) allow4 := flagOrDefault(req.AllowIPv4, true)
allow6 := flagOrDefault(req.AllowIPv6, true) allow6 := flagOrDefault(req.AllowIPv6, true)
if req.Profile != "http" && (req.Port < 1 || req.Port > 65535) { if req.Port < 1 || req.Port > 65535 {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
} }
interval := time.Duration(req.IntervalMs) * time.Millisecond interval := time.Duration(req.IntervalMs) * time.Millisecond
@@ -280,17 +279,11 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
} }
applyHTTPOptions(&httpIn, req.HTTP) applyHTTPOptions(&httpIn, req.HTTP)
lookupHost := req.Target lookupHost := req.Target
resolvedPort := req.Port
if req.Profile == "http" { if req.Profile == "http" {
page, err := buildHTTPURL(req.Target, req.Port) page, err := buildHTTPURL(req.Target, req.Port)
if err != nil { if err != nil {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", err.Error()} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", err.Error()}
} }
if p, convErr := strconv.Atoi(page.Port()); convErr == nil {
resolvedPort = p
httpIn.Port = p
}
httpIn.Target = page.String()
if _, err := normalizeHTTPVersion(httpIn.Version); err != nil { if _, err := normalizeHTTPVersion(httpIn.Version); err != nil {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", err.Error()} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", err.Error()}
} }
@@ -322,7 +315,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", "地址族不被允许"} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", "地址族不被允许"}
} }
return jobSpec{ return jobSpec{
Host: req.Target, Port: resolvedPort, Profile: req.Profile, IP: ips[0], Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0],
state: &dialState{picker: newEndpointPicker(ips)}, state: &dialState{picker: newEndpointPicker(ips)},
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size, Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect, Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
+1 -1
View File
@@ -13,7 +13,7 @@ import (
"time" "time"
) )
const appVersion = "1.1.4" const appVersion = "1.1.3"
// dialState is shared by the job runner and the prober. Both hold a copy of // dialState is shared by the job runner and the prober. Both hold a copy of
// jobSpec, so the mutable address choice has to live behind a pointer. // jobSpec, so the mutable address choice has to live behind a pointer.