网络质量探测 1.1.3:自更新、HTTP/3 与中心节点
版本名 1.1.3,构建号 6。应用标识和签名未改。包含自动更新、覆盖安装、目标历史、IPv4/IPv6 开关、HTTP(含 HTTP/3)以及中心服务端一键添加节点。
This commit is contained in:
1 parent
943259774f
commit
8cdc0f436f
66 files changed
+5489
-78
No files matched your search
@@ -0,0 +1,179 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import 'dart:ffi' show Abi;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../version.dart';
|
||||
import 'installer.dart';
|
||||
import 'update_check.dart';
|
||||
|
||||
class UpdateResult {
|
||||
const UpdateResult({required this.message, this.offer});
|
||||
|
||||
final String message;
|
||||
final UpdateOffer? offer;
|
||||
}
|
||||
|
||||
const platformChannel = MethodChannel('dev.netquality/platform');
|
||||
|
||||
Future<UpdateResult> checkForUpdate() async {
|
||||
final arch = await _arch();
|
||||
if (arch.isEmpty) {
|
||||
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(
|
||||
current: appVersion,
|
||||
endpoints: endpoints,
|
||||
os: _os(),
|
||||
arch: arch,
|
||||
fetch: (url) => _getText(url),
|
||||
);
|
||||
if (check.offer == null) {
|
||||
return UpdateResult(message: check.message);
|
||||
}
|
||||
return UpdateResult(
|
||||
message: '发现 ${check.offer!.version}。可以下载并覆盖安装。',
|
||||
offer: check.offer,
|
||||
);
|
||||
}
|
||||
|
||||
Future<String> installOffer(UpdateOffer offer) async {
|
||||
final bytes = await _getBytes(Uri.parse(offer.assetUrl));
|
||||
if (bytes == null) {
|
||||
return '安装包没有下载下来';
|
||||
}
|
||||
var checksumNote = '';
|
||||
if (offer.checksumUrl != null && offer.checksumUrl!.isNotEmpty) {
|
||||
final sums = await _getText(Uri.parse(offer.checksumUrl!));
|
||||
if (sums == null || !checksumMatches(sums, offer.assetName, bytes)) {
|
||||
return '校验和没有对上,已停止安装';
|
||||
}
|
||||
checksumNote = '校验通过。';
|
||||
} else {
|
||||
checksumNote = '这次发布没有校验和文件,已按下载的包继续。';
|
||||
}
|
||||
if (Platform.isAndroid) {
|
||||
final temp = await Directory.systemTemp.createTemp('nq-update-');
|
||||
final file = File('${temp.path}/updates/${offer.assetName}');
|
||||
await file.parent.create(recursive: true);
|
||||
await file.writeAsBytes(bytes, flush: true);
|
||||
await platformChannel.invokeMethod<void>('installApk', {'path': file.path});
|
||||
return '$checksumNote安装包已交给系统。请在系统弹出的确认里完成安装,这一步不能跳过。';
|
||||
}
|
||||
final extracted = await Directory.systemTemp.createTemp('nq-update-');
|
||||
extractArchive(bytes, offer.assetName, extracted);
|
||||
final installDir = File(Platform.resolvedExecutable).parent;
|
||||
if (Platform.isWindows) {
|
||||
await _windowsReplace(extracted, installDir);
|
||||
return '$checksumNote已下载。程序即将退出,随后覆盖安装并重新打开。';
|
||||
}
|
||||
copyIntoInstall(extracted, installDir);
|
||||
try {
|
||||
await Process.run('chmod', ['755', Platform.resolvedExecutable]);
|
||||
} on ProcessException {
|
||||
// The existing file is often already executable.
|
||||
}
|
||||
await Process.start(
|
||||
Platform.resolvedExecutable,
|
||||
const [],
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
Future<void> _windowsReplace(Directory extracted, Directory installDir) async {
|
||||
final script = File(
|
||||
'${Directory.systemTemp.path}${Platform.pathSeparator}nq-update-$pid.ps1',
|
||||
);
|
||||
final from = _ps(extracted.path);
|
||||
final to = _ps(installDir.path);
|
||||
final exe = _ps(Platform.resolvedExecutable);
|
||||
await script.writeAsString('''
|
||||
\$target = $pid
|
||||
\$from = $from
|
||||
\$to = $to
|
||||
while (Get-Process -Id \$target -ErrorAction SilentlyContinue) {
|
||||
Start-Sleep -Milliseconds 200
|
||||
}
|
||||
Copy-Item -Path (Join-Path \$from '*') -Destination \$to -Recurse -Force
|
||||
Start-Process -FilePath $exe
|
||||
''');
|
||||
await Process.start('powershell', [
|
||||
'-NoProfile',
|
||||
'-ExecutionPolicy',
|
||||
'Bypass',
|
||||
'-File',
|
||||
script.path,
|
||||
]);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
String _ps(String path) => "'${path.replaceAll("'", "''")}'";
|
||||
|
||||
String _os() {
|
||||
if (Platform.isAndroid) {
|
||||
return 'android';
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return 'windows';
|
||||
}
|
||||
return 'linux';
|
||||
}
|
||||
|
||||
Future<String> _arch() async {
|
||||
if (Platform.isAndroid) {
|
||||
try {
|
||||
final abi = await platformChannel.invokeMethod<String>('abi');
|
||||
return abi ?? '';
|
||||
} on PlatformException {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
switch (Abi.current()) {
|
||||
case Abi.linuxX64:
|
||||
case Abi.windowsX64:
|
||||
return 'amd64';
|
||||
case Abi.linuxArm64:
|
||||
case Abi.windowsArm64:
|
||||
return 'arm64';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _getText(Uri url) async {
|
||||
final bytes = await _getBytes(url);
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return String.fromCharCodes(bytes);
|
||||
}
|
||||
|
||||
Future<List<int>?> _getBytes(Uri url) async {
|
||||
final client = HttpClient();
|
||||
try {
|
||||
final request = await client.getUrl(url);
|
||||
final response = await request.close().timeout(const Duration(minutes: 2));
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
return null;
|
||||
}
|
||||
final chunks = <int>[];
|
||||
await for (final chunk in response) {
|
||||
chunks.addAll(chunk);
|
||||
}
|
||||
return chunks;
|
||||
} on Object {
|
||||
return null;
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
/// True when [sums] publishes a matching SHA-256 line for [fileName].
|
||||
/// A published file that does not mention the asset is a failure, not a skip.
|
||||
bool checksumMatches(String sums, String fileName, List<int> bytes) {
|
||||
final want = sha256.convert(bytes).toString().toLowerCase();
|
||||
final base = fileName.split(RegExp(r'[\\/]')).last;
|
||||
var mentioned = false;
|
||||
for (final raw in const LineSplitter().convert(sums)) {
|
||||
final line = raw.trim();
|
||||
if (line.isEmpty || line.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
final match = RegExp(r'^([0-9a-fA-F]{64})\s+\*?(\S+)\s*$').firstMatch(line);
|
||||
if (match == null) {
|
||||
continue;
|
||||
}
|
||||
final name = match.group(2)!.split(RegExp(r'[\\/]')).last;
|
||||
if (name != base) {
|
||||
continue;
|
||||
}
|
||||
mentioned = true;
|
||||
if (match.group(1)!.toLowerCase() == want) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!mentioned) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Extracts a zip or tar.gz into [dest]. Paths that climb out of [dest] are skipped.
|
||||
void extractArchive(List<int> bytes, String fileName, Directory dest) {
|
||||
final Archive archive;
|
||||
final lower = fileName.toLowerCase();
|
||||
if (lower.endsWith('.tar.gz') || lower.endsWith('.tgz')) {
|
||||
archive = TarDecoder().decodeBytes(GZipDecoder().decodeBytes(bytes));
|
||||
} else if (lower.endsWith('.zip')) {
|
||||
archive = ZipDecoder().decodeBytes(bytes);
|
||||
} else {
|
||||
throw const FormatException('只支持 zip 和 tar.gz');
|
||||
}
|
||||
final root = _singleRoot(archive);
|
||||
for (final file in archive) {
|
||||
if (!file.isFile) {
|
||||
continue;
|
||||
}
|
||||
var name = file.name.replaceAll('\\', '/');
|
||||
while (name.startsWith('./')) {
|
||||
name = name.substring(2);
|
||||
}
|
||||
if (root.isNotEmpty && name.startsWith('$root/')) {
|
||||
name = name.substring(root.length + 1);
|
||||
}
|
||||
if (name.isEmpty || name.startsWith('/') || name.contains('../')) {
|
||||
continue;
|
||||
}
|
||||
final out = File('${dest.path}/$name');
|
||||
final parent = out.parent.path;
|
||||
if (!_inside(dest.path, parent) && parent != dest.path) {
|
||||
continue;
|
||||
}
|
||||
out.parent.createSync(recursive: true);
|
||||
out.writeAsBytesSync(file.content as List<int>);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies extracted files onto the existing install directory.
|
||||
/// Files already there and not in the archive are left in place, so a data
|
||||
/// file sitting beside the program is not wiped. Nothing outside [installDir]
|
||||
/// is written.
|
||||
void copyIntoInstall(Directory extracted, Directory installDir) {
|
||||
if (!_inside(installDir.path, extracted.path) &&
|
||||
extracted.path != installDir.path) {
|
||||
// The source may be a temp directory. That is allowed.
|
||||
}
|
||||
for (final entity in extracted.listSync(recursive: true)) {
|
||||
if (entity is! File) {
|
||||
continue;
|
||||
}
|
||||
final relative = entity.path.substring(extracted.path.length);
|
||||
final trimmed = relative.replaceAll('\\', '/').replaceFirst(RegExp(r'^/'), '');
|
||||
if (trimmed.isEmpty || trimmed.contains('../')) {
|
||||
continue;
|
||||
}
|
||||
final target = File('${installDir.path}/$trimmed');
|
||||
if (!_inside(installDir.path, target.parent.path) &&
|
||||
target.parent.path != installDir.path) {
|
||||
continue;
|
||||
}
|
||||
target.parent.createSync(recursive: true);
|
||||
entity.copySync(target.path);
|
||||
}
|
||||
}
|
||||
|
||||
String _singleRoot(Archive archive) {
|
||||
String? root;
|
||||
for (final file in archive) {
|
||||
final name = file.name.replaceAll('\\', '/');
|
||||
final slash = name.indexOf('/');
|
||||
if (slash <= 0) {
|
||||
return '';
|
||||
}
|
||||
final top = name.substring(0, slash);
|
||||
if (root == null) {
|
||||
root = top;
|
||||
} else if (root != top) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
return root ?? '';
|
||||
}
|
||||
|
||||
bool _inside(String root, String child) {
|
||||
final prefix = root.endsWith(Platform.pathSeparator)
|
||||
? root
|
||||
: '$root${Platform.pathSeparator}';
|
||||
return child == root || child.startsWith(prefix);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
/// Numeric version. A leading v and a +build suffix are ignored.
|
||||
class SemVer implements Comparable<SemVer> {
|
||||
const SemVer(this.major, this.minor, this.patch);
|
||||
|
||||
final int major;
|
||||
final int minor;
|
||||
final int patch;
|
||||
|
||||
static SemVer? parse(String raw) {
|
||||
var text = raw.trim();
|
||||
if (text.startsWith('v') || text.startsWith('V')) {
|
||||
text = text.substring(1);
|
||||
}
|
||||
final plus = text.indexOf('+');
|
||||
if (plus >= 0) {
|
||||
text = text.substring(0, plus);
|
||||
}
|
||||
final dash = text.indexOf('-');
|
||||
if (dash >= 0) {
|
||||
text = text.substring(0, dash);
|
||||
}
|
||||
final parts = text.split('.');
|
||||
if (parts.length < 3) {
|
||||
return null;
|
||||
}
|
||||
final major = int.tryParse(parts[0]);
|
||||
final minor = int.tryParse(parts[1]);
|
||||
final patch = int.tryParse(parts[2]);
|
||||
if (major == null || minor == null || patch == null) {
|
||||
return null;
|
||||
}
|
||||
return SemVer(major, minor, patch);
|
||||
}
|
||||
|
||||
bool isNewerThan(SemVer other) => compareTo(other) > 0;
|
||||
|
||||
@override
|
||||
int compareTo(SemVer other) {
|
||||
if (major != other.major) {
|
||||
return major.compareTo(other.major);
|
||||
}
|
||||
if (minor != other.minor) {
|
||||
return minor.compareTo(other.minor);
|
||||
}
|
||||
return patch.compareTo(other.patch);
|
||||
}
|
||||
}
|
||||
|
||||
class ReleaseFile {
|
||||
const ReleaseFile({required this.name, required this.url});
|
||||
|
||||
final String name;
|
||||
final String url;
|
||||
}
|
||||
|
||||
class UpdateEndpoints {
|
||||
const UpdateEndpoints({required this.github, required this.gitea});
|
||||
|
||||
static const githubDefault =
|
||||
'https://api.github.com/repos/yanjiu0721/netquality/releases/latest';
|
||||
static const giteaDefault =
|
||||
'https://git.yanjiu.ltd/api/v1/repos/YanJiu/netquality/releases/latest';
|
||||
|
||||
final String github;
|
||||
final String gitea;
|
||||
}
|
||||
|
||||
class UpdateOffer {
|
||||
const UpdateOffer({
|
||||
required this.version,
|
||||
required this.assetName,
|
||||
required this.assetUrl,
|
||||
this.checksumName,
|
||||
this.checksumUrl,
|
||||
});
|
||||
|
||||
final String version;
|
||||
final String assetName;
|
||||
final String assetUrl;
|
||||
final String? checksumName;
|
||||
final String? checksumUrl;
|
||||
}
|
||||
|
||||
class UpdateCheck {
|
||||
const UpdateCheck({this.offer, required this.reachable, this.message = ''});
|
||||
|
||||
final UpdateOffer? offer;
|
||||
final bool reachable;
|
||||
final String message;
|
||||
}
|
||||
|
||||
/// Picks the client archive for this OS and CPU. Server packages are ignored.
|
||||
String? pickClientAsset(
|
||||
List<ReleaseFile> assets, {
|
||||
required String os,
|
||||
required String arch,
|
||||
}) {
|
||||
final wantOs = os.toLowerCase();
|
||||
final wantArch = arch.toLowerCase();
|
||||
for (final asset in assets) {
|
||||
final name = asset.name.toLowerCase();
|
||||
if (name.contains('server') || name.contains('reflector')) {
|
||||
continue;
|
||||
}
|
||||
if (wantOs == 'android') {
|
||||
if (name.endsWith('.apk') && name.contains(wantArch)) {
|
||||
return asset.name;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
final archOk =
|
||||
name.contains(wantArch) ||
|
||||
(wantArch == 'amd64' && name.contains('x86_64')) ||
|
||||
(wantArch == 'arm64' && name.contains('aarch64'));
|
||||
if (!archOk || !name.contains(wantOs)) {
|
||||
continue;
|
||||
}
|
||||
if (wantOs == 'windows' && (name.endsWith('.zip') || name.endsWith('.exe'))) {
|
||||
return asset.name;
|
||||
}
|
||||
if (wantOs == 'linux' &&
|
||||
(name.endsWith('.tar.gz') || name.endsWith('.tgz'))) {
|
||||
return asset.name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool looksLikeChecksum(String name) {
|
||||
final lower = name.toLowerCase();
|
||||
return lower.contains('sha256') || lower.contains('checksum');
|
||||
}
|
||||
|
||||
UpdateCheck interpretRelease({
|
||||
required String current,
|
||||
required String? body,
|
||||
required String os,
|
||||
required String arch,
|
||||
}) {
|
||||
if (body == null || body.trim().isEmpty) {
|
||||
return const UpdateCheck(reachable: false, message: '检查更新失败');
|
||||
}
|
||||
Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(body);
|
||||
} on FormatException {
|
||||
return const UpdateCheck(reachable: false, message: '检查更新失败');
|
||||
}
|
||||
if (decoded is! Map) {
|
||||
return const UpdateCheck(reachable: false, message: '检查更新失败');
|
||||
}
|
||||
final tag = decoded['tag_name'];
|
||||
final remote = tag is String ? SemVer.parse(tag) : null;
|
||||
final local = SemVer.parse(current);
|
||||
if (remote == null || local == null) {
|
||||
return const UpdateCheck(reachable: true, message: '发布说明里的版本号无法比较');
|
||||
}
|
||||
if (!remote.isNewerThan(local)) {
|
||||
return UpdateCheck(reachable: true, message: '当前已经是 $current');
|
||||
}
|
||||
final assets = <ReleaseFile>[];
|
||||
final rawAssets = decoded['assets'];
|
||||
if (rawAssets is List) {
|
||||
for (final item in rawAssets) {
|
||||
if (item is! Map) {
|
||||
continue;
|
||||
}
|
||||
final name = item['name'];
|
||||
final url = item['browser_download_url'];
|
||||
final link = url is String ? url : '';
|
||||
if (name is String && link.isNotEmpty) {
|
||||
assets.add(ReleaseFile(name: name, url: link));
|
||||
}
|
||||
}
|
||||
}
|
||||
final pickedName = pickClientAsset(assets, os: os, arch: arch);
|
||||
if (pickedName == null) {
|
||||
return UpdateCheck(
|
||||
reachable: true,
|
||||
message: '发现 ${remote.major}.${remote.minor}.${remote.patch},但没有适合这台设备的安装包',
|
||||
);
|
||||
}
|
||||
final picked = assets.firstWhere((asset) => asset.name == pickedName);
|
||||
ReleaseFile? sums;
|
||||
for (final asset in assets) {
|
||||
if (looksLikeChecksum(asset.name)) {
|
||||
sums = asset;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return UpdateCheck(
|
||||
reachable: true,
|
||||
offer: UpdateOffer(
|
||||
version: '${remote.major}.${remote.minor}.${remote.patch}',
|
||||
assetName: picked.name,
|
||||
assetUrl: picked.url,
|
||||
checksumName: sums?.name,
|
||||
checksumUrl: sums?.url,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<UpdateCheck> findUpdate({
|
||||
required String current,
|
||||
required UpdateEndpoints endpoints,
|
||||
required Future<String?> Function(Uri url) fetch,
|
||||
required String os,
|
||||
required String arch,
|
||||
}) async {
|
||||
String? body;
|
||||
try {
|
||||
body = await fetch(Uri.parse(endpoints.github));
|
||||
} on Object {
|
||||
body = null;
|
||||
}
|
||||
var check = interpretRelease(current: current, body: body, os: os, arch: arch);
|
||||
if (!check.reachable) {
|
||||
try {
|
||||
body = await fetch(Uri.parse(endpoints.gitea));
|
||||
} on Object {
|
||||
body = null;
|
||||
}
|
||||
check = interpretRelease(current: current, body: body, os: os, arch: arch);
|
||||
if (!check.reachable) {
|
||||
return const UpdateCheck(
|
||||
reachable: false,
|
||||
message: 'GitHub 和备用源都连不上,没有检查到更新',
|
||||
);
|
||||
}
|
||||
}
|
||||
return check;
|
||||
}
|
||||
Reference in new issue
Block a user