mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-16 13:23:41 +00:00
refactor: remove proxy API (#1596)
This commit is contained in:
98 files changed
+5958
-1225
No files matched your search
@@ -0,0 +1,147 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:pub_semver/pub_semver.dart';
|
||||
|
||||
import '../../api/gopeed_site_api.dart';
|
||||
|
||||
class VersionInfo {
|
||||
const VersionInfo({
|
||||
required this.version,
|
||||
required this.changeLog,
|
||||
required this.releaseUrl,
|
||||
this.assetSha256 = const {},
|
||||
});
|
||||
|
||||
final String version;
|
||||
final String changeLog;
|
||||
final String releaseUrl;
|
||||
// Populated only from official release metadata, never from a download mirror.
|
||||
final Map<String, String> assetSha256;
|
||||
}
|
||||
|
||||
/// Query the official GitHub API directly, then the independent website API
|
||||
/// only if the GitHub request or its response validation fails.
|
||||
class AppUpdateClient {
|
||||
AppUpdateClient({Dio? client, GopeedSiteApi? site})
|
||||
: _client =
|
||||
client ??
|
||||
Dio(BaseOptions(connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 30))),
|
||||
_site = site ?? GopeedSiteApi.instance;
|
||||
|
||||
static const releasesUrl = 'https://api.github.com/repos/GopeedLab/gopeed/releases?per_page=10';
|
||||
final Dio _client;
|
||||
final GopeedSiteApi _site;
|
||||
|
||||
Future<List<_Release>> _fetchGithubReleases() async {
|
||||
final cancel = CancelToken();
|
||||
try {
|
||||
final response = await _client
|
||||
.get<dynamic>(releasesUrl, cancelToken: cancel, options: Options(followRedirects: false))
|
||||
.timeout(const Duration(seconds: 30));
|
||||
return _decodeReleases(response.data);
|
||||
} finally {
|
||||
cancel.cancel('GitHub release request completed');
|
||||
}
|
||||
}
|
||||
|
||||
Future<VersionInfo?> check(String currentVersion) async {
|
||||
final current = _parseVersion(currentVersion);
|
||||
if (current == null) throw FormatException('Invalid current application version', currentVersion);
|
||||
List<_Release> releases;
|
||||
try {
|
||||
releases = await _fetchGithubReleases();
|
||||
} catch (_) {
|
||||
releases = _decodeReleases(await _site.getReleases());
|
||||
}
|
||||
_Release? selected;
|
||||
for (final release in releases) {
|
||||
final version = release.version;
|
||||
if (release.draft || version.compareTo(current) <= 0) continue;
|
||||
final preview = release.prerelease || version.isPreRelease;
|
||||
if (!current.isPreRelease && preview) continue;
|
||||
if (current.isPreRelease &&
|
||||
preview &&
|
||||
(version.major != current.major || version.minor != current.minor || version.patch != current.patch)) {
|
||||
continue;
|
||||
}
|
||||
if (selected == null || version.compareTo(selected.version) > 0) selected = release;
|
||||
}
|
||||
if (selected == null) return null;
|
||||
return VersionInfo(
|
||||
version: selected.tag.replaceFirst(RegExp(r'^v'), ''),
|
||||
changeLog: selected.body,
|
||||
assetSha256: Map.unmodifiable(selected.assetSha256),
|
||||
releaseUrl: selected.url.isEmpty
|
||||
? 'https://github.com/GopeedLab/gopeed/releases/tag/${selected.tag}'
|
||||
: selected.url,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Build metadata does not affect SemVer precedence.
|
||||
Version? _parseVersion(String raw) {
|
||||
try {
|
||||
final version = Version.parse(raw.replaceFirst(RegExp(r'^v'), ''));
|
||||
return Version(version.major, version.minor, version.patch, pre: version.preRelease.join('.'));
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
List<_Release> _decodeReleases(dynamic data) {
|
||||
if (data is! List) throw const FormatException('Invalid release list');
|
||||
final releases = <_Release>[];
|
||||
for (final entry in data) {
|
||||
if (entry is! Map || entry['tag_name'] is! String) continue;
|
||||
final tag = entry['tag_name'] as String;
|
||||
final version = _parseVersion(tag);
|
||||
if (version == null) continue;
|
||||
releases.add(
|
||||
_Release(
|
||||
tag: tag,
|
||||
version: version,
|
||||
draft: entry['draft'] == true,
|
||||
prerelease: entry['prerelease'] == true,
|
||||
body: entry['body'] as String? ?? '',
|
||||
url: entry['html_url'] as String? ?? '',
|
||||
assetSha256: _decodeAssetSha256(entry['assets']),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.isNotEmpty && releases.isEmpty) throw const FormatException('Response contains no valid releases');
|
||||
return releases;
|
||||
}
|
||||
|
||||
Map<String, String> _decodeAssetSha256(dynamic assets) {
|
||||
if (assets == null) return {};
|
||||
if (assets is! List) throw const FormatException('Invalid release assets');
|
||||
final result = <String, String>{};
|
||||
for (final asset in assets) {
|
||||
if (asset is! Map || asset['name'] is! String || asset['digest'] is! String) continue;
|
||||
final digest = asset['digest'] as String;
|
||||
final match = RegExp(r'^sha256:([a-fA-F0-9]{64})$').firstMatch(digest);
|
||||
if (match == null || match.end != digest.length) continue;
|
||||
final name = asset['name'] as String;
|
||||
if (result.containsKey(name)) throw const FormatException('Duplicate release asset');
|
||||
result[name] = match.group(1)!.toLowerCase();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class _Release {
|
||||
const _Release({
|
||||
required this.tag,
|
||||
required this.version,
|
||||
required this.draft,
|
||||
required this.prerelease,
|
||||
required this.body,
|
||||
required this.url,
|
||||
required this.assetSha256,
|
||||
});
|
||||
final String tag;
|
||||
final Version version;
|
||||
final bool draft;
|
||||
final bool prerelease;
|
||||
final String body;
|
||||
final String url;
|
||||
final Map<String, String> assetSha256;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
class DownloadChecksumException implements Exception {
|
||||
const DownloadChecksumException();
|
||||
@override
|
||||
String toString() => 'Update package checksum verification failed';
|
||||
}
|
||||
|
||||
/// Probes backend-provided URLs concurrently, then downloads the fastest usable
|
||||
/// candidate. Other candidates remain available if HEAD is unsupported or the
|
||||
/// actual download fails. This layer has no GitHub URL or mirror-config rules.
|
||||
Future<void> downloadFromCandidates(
|
||||
List<String> candidates,
|
||||
String savePath, {
|
||||
required ProgressCallback onReceiveProgress,
|
||||
required String expectedSha256,
|
||||
Dio? client,
|
||||
Duration probeTimeout = const Duration(seconds: 3),
|
||||
}) async {
|
||||
// Reject missing or malformed trusted metadata before any network request.
|
||||
if (expectedSha256.length != 64 || !RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(expectedSha256)) {
|
||||
throw const DownloadChecksumException();
|
||||
}
|
||||
final urls = candidates.toSet().toList(growable: false);
|
||||
if (urls.isEmpty) throw ArgumentError.value(candidates, 'candidates', 'No download candidates');
|
||||
final dio = client ?? Dio(BaseOptions(connectTimeout: const Duration(seconds: 10)));
|
||||
try {
|
||||
final probes = await Future.wait(
|
||||
urls.map((url) async {
|
||||
final watch = Stopwatch()..start();
|
||||
final cancel = CancelToken();
|
||||
try {
|
||||
final response = await dio
|
||||
.head<void>(
|
||||
url,
|
||||
cancelToken: cancel,
|
||||
options: Options(receiveTimeout: probeTimeout, validateStatus: (status) => status == 200),
|
||||
)
|
||||
.timeout(probeTimeout);
|
||||
if (_isPackageResponse(response.headers)) return (url: url, latency: watch.elapsed);
|
||||
} catch (_) {
|
||||
// HEAD failure does not prove that a normal GET will fail.
|
||||
} finally {
|
||||
cancel.cancel();
|
||||
}
|
||||
return (url: url, latency: null);
|
||||
}),
|
||||
);
|
||||
final available = probes.where((probe) => probe.latency != null).toList()
|
||||
..sort((a, b) => a.latency!.compareTo(b.latency!));
|
||||
final ordered = [
|
||||
...available.map((probe) => probe.url),
|
||||
...probes.where((p) => p.latency == null).map((p) => p.url),
|
||||
];
|
||||
Object? lastError;
|
||||
StackTrace? lastStack;
|
||||
for (final url in ordered) {
|
||||
try {
|
||||
onReceiveProgress(0, 0);
|
||||
final response = await dio.download(
|
||||
url,
|
||||
savePath,
|
||||
onReceiveProgress: onReceiveProgress,
|
||||
deleteOnError: true,
|
||||
options: Options(receiveTimeout: const Duration(seconds: 30), validateStatus: (status) => status == 200),
|
||||
);
|
||||
if (!_isPackageResponse(response.headers) || await File(savePath).length() == 0) {
|
||||
throw StateError('Invalid download response from $url');
|
||||
}
|
||||
final actual = await sha256.bind(File(savePath).openRead()).first;
|
||||
if (actual.toString() != expectedSha256.toLowerCase()) throw const DownloadChecksumException();
|
||||
return;
|
||||
} catch (error, stack) {
|
||||
lastError = error;
|
||||
lastStack = stack;
|
||||
final file = File(savePath);
|
||||
if (await file.exists()) await file.delete();
|
||||
}
|
||||
}
|
||||
Error.throwWithStackTrace(lastError!, lastStack!);
|
||||
} finally {
|
||||
if (client == null) dio.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
bool _isPackageResponse(Headers headers) {
|
||||
final contentType = headers.value(Headers.contentTypeHeader)?.split(';').first.trim().toLowerCase();
|
||||
return contentType != 'text/html' && contentType != 'application/xhtml+xml' && contentType != 'application/json';
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../util/util.dart';
|
||||
import '../../../ffi/libgopeed_worker.dart';
|
||||
import '../../../libgopeed_boot.dart';
|
||||
@@ -10,17 +8,6 @@ import '../gopeed_transport.dart';
|
||||
GopeedTransport createTransport(GopeedTransportConfig config) => NativeGopeedTransport();
|
||||
|
||||
class NativeGopeedTransport implements GopeedTransport {
|
||||
NativeGopeedTransport()
|
||||
: _externalDio = Dio(
|
||||
BaseOptions(
|
||||
contentType: Headers.jsonContentType,
|
||||
sendTimeout: const Duration(seconds: 5),
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 120),
|
||||
),
|
||||
);
|
||||
|
||||
final Dio _externalDio;
|
||||
final LibgopeedWorker? _ffiWorker = Util.isDesktop() ? LibgopeedWorker() : null;
|
||||
|
||||
@override
|
||||
@@ -45,15 +32,6 @@ class NativeGopeedTransport implements GopeedTransport {
|
||||
return jsonDecode(payload);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<String>> proxyRequest(String uri, {dynamic data, Options? options}) {
|
||||
return _externalDio.request<String>(
|
||||
uri,
|
||||
data: data,
|
||||
options: (options ?? Options()).copyWith(responseType: ResponseType.plain),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String join(String path) => path;
|
||||
}
|
||||
|
||||
@@ -8,8 +8,7 @@ class RestGopeedTransport implements GopeedTransport {
|
||||
RestGopeedTransport(GopeedTransportConfig config)
|
||||
: _dio = Dio(
|
||||
BaseOptions(
|
||||
// Keep release requests relative so deployments under a reverse
|
||||
// proxy path continue to work, matching the legacy Web client.
|
||||
// Keep requests relative for deployments under a reverse proxy path.
|
||||
baseUrl: webTransportBaseUrl(config.address, Uri.base),
|
||||
contentType: Headers.jsonContentType,
|
||||
sendTimeout: const Duration(seconds: 5),
|
||||
@@ -53,18 +52,6 @@ class RestGopeedTransport implements GopeedTransport {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<String>> proxyRequest(String uri, {dynamic data, Options? options}) {
|
||||
options ??= Options();
|
||||
options.headers ??= {};
|
||||
options.headers!['X-Target-Uri'] = uri;
|
||||
return _dio.request<String>(
|
||||
'/api/web/proxy?t=${DateTime.now().millisecondsSinceEpoch}',
|
||||
data: data,
|
||||
options: options.copyWith(responseType: ResponseType.plain),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String join(String path) {
|
||||
final baseUrl = _dio.options.baseUrl;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'entry/gopeed_transport_stub.dart'
|
||||
@@ -60,8 +59,6 @@ String normalizeWebApiBaseUrl(String address, Uri pageUri) {
|
||||
abstract interface class GopeedTransport {
|
||||
Future<dynamic> request(String path, {String method = 'GET', dynamic data, Map<String, dynamic>? queryParameters});
|
||||
|
||||
Future<Response<String>> proxyRequest(String uri, {dynamic data, Options? options});
|
||||
|
||||
String join(String path);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../capabilities/gopeed_capability.dart';
|
||||
|
||||
/// Mirror requests use backend-generated candidates, without forwarding the
|
||||
/// Downloader's authentication headers to resource providers or their mirrors.
|
||||
class MirrorClient {
|
||||
MirrorClient({
|
||||
required GopeedService service,
|
||||
required this.provider,
|
||||
Dio? client,
|
||||
this.timeout = const Duration(seconds: 30),
|
||||
}) : _service = service,
|
||||
_client = client ?? Dio(BaseOptions(connectTimeout: const Duration(seconds: 10), receiveTimeout: timeout));
|
||||
|
||||
final String provider;
|
||||
final GopeedService _service;
|
||||
final Dio _client;
|
||||
final Duration timeout;
|
||||
|
||||
/// The first complete response accepted by [decode] wins. HTTP 200 alone is
|
||||
/// insufficient: a mirror's HTML error page must not hide a usable response.
|
||||
Future<T> getJson<T>(String url, {required T Function(dynamic) decode}) async {
|
||||
final urls = (await _service.getMirrorCandidates(provider, url)).toSet();
|
||||
if (urls.isEmpty) throw StateError('No mirror candidates');
|
||||
final result = Completer<T>();
|
||||
final tokens = <CancelToken>[];
|
||||
var pending = urls.length;
|
||||
Future<void> attempt(String candidate, CancelToken token) async {
|
||||
try {
|
||||
final response = await _client
|
||||
.get<dynamic>(candidate, cancelToken: token)
|
||||
.timeout(
|
||||
timeout,
|
||||
onTimeout: () {
|
||||
token.cancel('Mirror candidate timed out');
|
||||
throw TimeoutException('Mirror candidate timed out', timeout);
|
||||
},
|
||||
);
|
||||
final value = decode(response.data);
|
||||
if (!result.isCompleted) result.complete(value);
|
||||
} catch (error, stack) {
|
||||
if (--pending == 0 && !result.isCompleted) result.completeError(error, stack);
|
||||
}
|
||||
}
|
||||
|
||||
for (final candidate in urls) {
|
||||
final token = CancelToken();
|
||||
tokens.add(token);
|
||||
unawaited(attempt(candidate, token));
|
||||
}
|
||||
try {
|
||||
return await result.future;
|
||||
} finally {
|
||||
for (final token in tokens) {
|
||||
token.cancel('Mirror candidate race completed');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user