feat: new ui (#1455)

This commit is contained in:
Levi authored and GitHub committed 2026-09-05 19:53:41 +08:00
1 parent 3be8db664c
commit 177c225f16
742 files changed
+59951 -5934

No files matched your search

+58 -81
View File
@@ -4,73 +4,92 @@ import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:gopeed/database/database.dart';
import 'package:gopeed/util/package_info.dart';
import '../database/database.dart';
import 'log_util.dart';
import 'package_info.dart';
/// GA4 Measurement Protocol configuration from dart-define
class Config {
static const String measurementId =
String.fromEnvironment('GA4_MEASUREMENT_ID');
static const String apiSecret = String.fromEnvironment('GA4_API_SECRET');
/// GA4 Measurement Protocol configuration supplied by the release build.
class AnalyticsConfig {
const AnalyticsConfig._();
static bool get isConfigured =>
measurementId.isNotEmpty && apiSecret.isNotEmpty;
static const measurementId = String.fromEnvironment('GA4_MEASUREMENT_ID');
static const apiSecret = String.fromEnvironment('GA4_API_SECRET');
static bool get isConfigured => measurementId.isNotEmpty && apiSecret.isNotEmpty;
}
/// GA4 Measurement Protocol Analytics
/// Sends only anonymous application events. The preference is stored outside
/// downloader configuration so it remains local to the current installation.
class Analytics {
static final Analytics _instance = Analytics._internal();
static Analytics get instance => _instance;
Analytics._();
Analytics._internal();
static final instance = Analytics._();
late String _clientId;
late int _sessionId;
late Dio _dio;
late final String _clientId;
late final int _sessionId;
late final Dio _dio;
bool _initialized = false;
Future<void> init() async {
if (_initialized) return;
if (!Config.isConfigured) return;
if (_initialized || !AnalyticsConfig.isConfigured) return;
_clientId = await _getDeviceId();
_dio = Dio(BaseOptions(
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
));
_sessionId = DateTime.now().millisecondsSinceEpoch ~/ 1000;
_dio = Dio(BaseOptions(connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10)));
_initialized = true;
}
Future<void> logAppOpen() => logEvent('app_open');
Future<void> logEvent(String name, [Map<String, dynamic>? params]) async {
if (!_initialized) return;
final payload = {
'client_id': _clientId,
'timestamp_micros': DateTime.now().microsecondsSinceEpoch,
'events': [
{
'name': name,
'params': {
'session_id': _sessionId.toString(),
'engagement_time_msec': 100,
'platform': _platformName(),
'app_version': appVersion,
...?params,
},
},
],
};
try {
await _dio.post(
'https://www.google-analytics.com/mp/collect',
queryParameters: {'measurement_id': AnalyticsConfig.measurementId, 'api_secret': AnalyticsConfig.apiSecret},
data: payload,
);
} catch (error) {
logger.w('GA4Analytics: failed to send event "$name": $error');
}
}
Future<String> _getDeviceId() async {
final deviceInfo = DeviceInfoPlugin();
String? deviceId;
try {
final info = DeviceInfoPlugin();
if (kIsWeb) {
deviceId = null;
} else if (Platform.isAndroid) {
final androidInfo = await deviceInfo.androidInfo;
deviceId = androidInfo.id;
deviceId = (await info.androidInfo).id;
} else if (Platform.isIOS) {
final iosInfo = await deviceInfo.iosInfo;
deviceId = iosInfo.identifierForVendor;
deviceId = (await info.iosInfo).identifierForVendor;
} else if (Platform.isMacOS) {
final macInfo = await deviceInfo.macOsInfo;
deviceId = macInfo.systemGUID;
deviceId = (await info.macOsInfo).systemGUID;
} else if (Platform.isWindows) {
final windowsInfo = await deviceInfo.windowsInfo;
deviceId = windowsInfo.deviceId;
deviceId = (await info.windowsInfo).deviceId;
} else if (Platform.isLinux) {
final linuxInfo = await deviceInfo.linuxInfo;
deviceId = linuxInfo.machineId;
deviceId = (await info.linuxInfo).machineId;
}
} catch (e) {
debugPrint('GA4Analytics: Failed to get device id: $e');
} catch (error) {
logger.w('GA4Analytics: failed to read device id: $error');
}
// Fallback to persisted client id
if (deviceId == null || deviceId.isEmpty) {
deviceId = Database.instance.getAnalyticsClientId();
if (deviceId == null || deviceId.isEmpty) {
@@ -83,7 +102,7 @@ class Analytics {
return deviceId;
}
String _getPlatform() {
String _platformName() {
if (kIsWeb) return 'web';
if (Platform.isAndroid) return 'android';
if (Platform.isIOS) return 'ios';
@@ -92,46 +111,4 @@ class Analytics {
if (Platform.isLinux) return 'linux';
return 'unknown';
}
Future<void> logAppOpen() async {
await logEvent('app_open');
}
Future<void> logEvent(String name, [Map<String, dynamic>? params]) async {
if (!_initialized) {
return;
}
final eventParams = <String, dynamic>{
'session_id': _sessionId.toString(),
'engagement_time_msec': 100,
'platform': _getPlatform(),
'app_version': packageInfo.version,
...?params,
};
final payload = {
'client_id': _clientId,
'timestamp_micros': DateTime.now().microsecondsSinceEpoch,
'events': [
{
'name': name,
'params': eventParams,
}
],
};
try {
await _dio.post(
'https://www.google-analytics.com/mp/collect',
queryParameters: {
'measurement_id': Config.measurementId,
'api_secret': Config.apiSecret,
},
data: payload,
);
} catch (e) {
logger.w('GA4Analytics: Failed to send event "$name": $e');
}
}
}
+3 -12
View File
@@ -1,15 +1,6 @@
import 'arch_stub.dart'
if (dart.library.io) 'entry/arch_native.dart'
if (dart.library.html) 'entry/arch_web.dart';
import 'arch_stub.dart' if (dart.library.io) 'entry/arch_native.dart' if (dart.library.html) 'entry/arch_web.dart';
// Copy from pkg/sky_engine/lib/ffi/abi.dart
enum Architecture {
arm,
arm64,
ia32,
x64,
riscv32,
riscv64,
}
// These names match the architecture suffixes used by Gopeed release assets.
enum Architecture { arm, arm64, ia32, x64, riscv32, riscv64 }
Architecture getArch() => doGetArch();
@@ -1,13 +1,11 @@
// ignore: avoid_web_libraries_in_flutter
import 'dart:ffi';
import '../arch.dart';
Architecture doGetArch() {
final currentAbi = Abi.current().toString();
final archName = currentAbi.split("_")[1];
final arch = Architecture.values.firstWhere(
(element) => element.name == archName,
orElse: () => Architecture.x64);
return arch;
final archName = Abi.current().toString().split('_')[1];
return Architecture.values.firstWhere(
(architecture) => architecture.name == archName,
orElse: () => Architecture.x64,
);
}
+1 -3
View File
@@ -1,5 +1,3 @@
import '../arch.dart';
Architecture doGetArch() {
return Architecture.x64;
}
Architecture doGetArch() => Architecture.x64;
@@ -1,4 +1,3 @@
import 'browser_download_stub.dart'
if (dart.library.html) 'entry/browser_download_browser.dart';
import 'browser_download_stub.dart' if (dart.library.html) 'entry/browser_download_browser.dart';
void download(String url, String name) => doDownload(url, name);
@@ -1 +1 @@
void doDownload(String url, String name) => throw UnimplementedError();
void doDownload(String url, String name) => throw UnsupportedError('Browser downloads are only available on web');
@@ -1,9 +1,9 @@
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;
import 'package:web/web.dart' as web;
void doDownload(String url, String name) {
final anchorElement = html.AnchorElement(href: url);
anchorElement.download = name;
anchorElement.target = '_blank';
anchorElement.click();
final anchor = web.document.createElement('a') as web.HTMLAnchorElement
..href = url
..download = name
..target = '_blank';
anchor.click();
}
@@ -1,5 +1,4 @@
import 'browser_extension_host_stub.dart'
if (dart.library.io) 'entry/browser_extension_host_native.dart';
import 'browser_extension_host_stub.dart' if (dart.library.io) 'entry/browser_extension_host_native.dart';
enum Browser { chrome, edge, firefox }
@@ -7,12 +6,10 @@ enum Browser { chrome, edge, firefox }
Future<void> installHost() => doInstallHost();
/// Check if specified browser is installed
Future<bool> checkBrowserInstalled(Browser browser) =>
doCheckBrowserInstalled(browser);
Future<bool> checkBrowserInstalled(Browser browser) => doCheckBrowserInstalled(browser);
/// Check if browser extension manifest is properly installed
Future<bool> checkManifestInstalled(Browser browser) =>
doCheckManifestInstalled(browser);
Future<bool> checkManifestInstalled(Browser browser) => doCheckManifestInstalled(browser);
/// Install browser extension manifest
Future<void> installManifest(Browser browser) => doInstallManifest(browser);
@@ -1,8 +1,6 @@
import 'browser_extension_host.dart';
Future<void> doInstallHost() => throw UnimplementedError();
Future<bool> doCheckBrowserInstalled(Browser browser) =>
throw UnimplementedError();
Future<bool> doCheckManifestInstalled(Browser browser) =>
throw UnimplementedError();
Future<bool> doCheckBrowserInstalled(Browser browser) => throw UnimplementedError();
Future<bool> doCheckManifestInstalled(Browser browser) => throw UnimplementedError();
Future<void> doInstallManifest(Browser browser) => throw UnimplementedError();
@@ -31,8 +31,7 @@ const _firefoxNativeHostsKey = r'Software\Mozilla\NativeMessagingHosts';
/// Install host binary for browser extension
Future<void> doInstallHost() async {
final hostPath = await Util.homePathJoin(_hostExecName);
await Util.installAsset('assets/exec/$_hostExecName', hostPath,
executable: true);
await Util.installAsset('assets/exec/$_hostExecName', hostPath, executable: true);
}
/// Check if specified browser is installed
@@ -40,21 +39,16 @@ Future<bool> doCheckBrowserInstalled(Browser browser) async {
if (Platform.isWindows) {
switch (browser) {
case Browser.chrome:
return await _checkWindowsRegistry(
r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe') ||
await _checkWindowsRegistry(
r'SOFTWARE\WOW6432Node\Google\Chrome') ||
return await _checkWindowsRegistry(r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe') ||
await _checkWindowsRegistry(r'SOFTWARE\WOW6432Node\Google\Chrome') ||
await _checkWindowsExecutable(browser);
case Browser.edge:
return await _checkWindowsRegistry(
r'SOFTWARE\Microsoft\Edge\BLBeacon') ||
await _checkWindowsRegistry(
r'SOFTWARE\WOW6432Node\Microsoft\Edge\BLBeacon') ||
return await _checkWindowsRegistry(r'SOFTWARE\Microsoft\Edge\BLBeacon') ||
await _checkWindowsRegistry(r'SOFTWARE\WOW6432Node\Microsoft\Edge\BLBeacon') ||
await _checkWindowsExecutable(browser);
case Browser.firefox:
return await _checkWindowsRegistry(r'SOFTWARE\Mozilla\Firefox') ||
await _checkWindowsRegistry(
r'SOFTWARE\WOW6432Node\Mozilla\Firefox') ||
await _checkWindowsRegistry(r'SOFTWARE\WOW6432Node\Mozilla\Firefox') ||
await _checkWindowsRegistry(r'SOFTWARE\BrowserWorks\Waterfox') ||
await _checkWindowsExecutable(browser);
}
@@ -121,38 +115,22 @@ List<String> _getWindowsExecutablePaths(Browser browser) {
switch (browser) {
case Browser.chrome:
return [
if (programFiles != null)
path.join(
programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
if (programFilesX86 != null)
path.join(
programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
if (localAppData != null)
path.join(
localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),
if (programFiles != null) path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
if (programFilesX86 != null) path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
if (localAppData != null) path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),
];
case Browser.edge:
return [
if (programFiles != null)
path.join(
programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
if (programFilesX86 != null)
path.join(programFilesX86, 'Microsoft', 'Edge', 'Application',
'msedge.exe'),
if (localAppData != null)
path.join(
localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
if (programFiles != null) path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
if (programFilesX86 != null) path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
if (localAppData != null) path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
];
case Browser.firefox:
return [
if (programFiles != null)
path.join(programFiles, 'Mozilla Firefox', 'firefox.exe'),
if (programFilesX86 != null)
path.join(programFilesX86, 'Mozilla Firefox', 'firefox.exe'),
if (programFiles != null)
path.join(programFiles, 'Waterfox', 'waterfox.exe'),
if (programFilesX86 != null)
path.join(programFilesX86, 'Waterfox', 'waterfox.exe'),
if (programFiles != null) path.join(programFiles, 'Mozilla Firefox', 'firefox.exe'),
if (programFilesX86 != null) path.join(programFilesX86, 'Mozilla Firefox', 'firefox.exe'),
if (programFiles != null) path.join(programFiles, 'Waterfox', 'waterfox.exe'),
if (programFilesX86 != null) path.join(programFilesX86, 'Waterfox', 'waterfox.exe'),
];
}
}
@@ -175,13 +153,13 @@ List<String> _getUnixExecutablePaths(Browser browser) {
return [
'/Applications/Google Chrome.app',
'~/Applications/Google Chrome.app',
'/Users/${Platform.environment['USER']}/Applications/Google Chrome.app'
'/Users/${Platform.environment['USER']}/Applications/Google Chrome.app',
];
case Browser.edge:
return [
'/Applications/Microsoft Edge.app',
'~/Applications/Microsoft Edge.app',
'/Users/${Platform.environment['USER']}/Applications/Microsoft Edge.app'
'/Users/${Platform.environment['USER']}/Applications/Microsoft Edge.app',
];
case Browser.firefox:
return [
@@ -190,7 +168,7 @@ List<String> _getUnixExecutablePaths(Browser browser) {
'/Users/${Platform.environment['USER']}/Applications/Firefox.app',
'/Applications/Waterfox.app',
'~/Applications/Waterfox.app',
'/Users/${Platform.environment['USER']}/Applications/Waterfox.app'
'/Users/${Platform.environment['USER']}/Applications/Waterfox.app',
];
}
} else {
@@ -201,14 +179,14 @@ List<String> _getUnixExecutablePaths(Browser browser) {
'/usr/bin/google-chrome-stable',
'/usr/bin/chrome',
'/snap/bin/google-chrome',
'/opt/google/chrome/google-chrome'
'/opt/google/chrome/google-chrome',
];
case Browser.edge:
return [
'/usr/bin/microsoft-edge',
'/usr/bin/microsoft-edge-stable',
'/snap/bin/microsoft-edge',
'/opt/microsoft/msedge/msedge'
'/opt/microsoft/msedge/msedge',
];
case Browser.firefox:
return [
@@ -219,46 +197,53 @@ List<String> _getUnixExecutablePaths(Browser browser) {
'/usr/bin/waterfox',
'/snap/bin/waterfox',
'/usr/lib/waterfox/waterfox',
'/opt/waterfox/waterfox'
'/opt/waterfox/waterfox',
];
}
}
}
Future<String?> _getManifestPath(Browser browser) async {
final manifestName =
browser == Browser.firefox ? '$_hostName.moz.json' : '$_hostName.json';
final manifestName = browser == Browser.firefox ? '$_hostName.moz.json' : '$_hostName.json';
if (Platform.isWindows) {
return await Util.homePathJoin(manifestName);
}
final home =
Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
final home = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
if (home == null) return null;
if (Platform.isMacOS) {
switch (browser) {
case Browser.chrome:
return path.join(home, 'Library', 'Application Support', 'Google',
'Chrome', 'NativeMessagingHosts', manifestName);
return path.join(
home,
'Library',
'Application Support',
'Google',
'Chrome',
'NativeMessagingHosts',
manifestName,
);
case Browser.edge:
return path.join(home, 'Library', 'Application Support',
'Microsoft Edge', 'NativeMessagingHosts', manifestName);
return path.join(
home,
'Library',
'Application Support',
'Microsoft Edge',
'NativeMessagingHosts',
manifestName,
);
case Browser.firefox:
return path.join(home, 'Library', 'Application Support', 'Mozilla',
'NativeMessagingHosts', manifestName);
return path.join(home, 'Library', 'Application Support', 'Mozilla', 'NativeMessagingHosts', manifestName);
}
} else if (Platform.isLinux) {
switch (browser) {
case Browser.chrome:
return path.join(home, '.config', 'google-chrome',
'NativeMessagingHosts', manifestName);
return path.join(home, '.config', 'google-chrome', 'NativeMessagingHosts', manifestName);
case Browser.edge:
return path.join(home, '.config', 'microsoft-edge',
'NativeMessagingHosts', manifestName);
return path.join(home, '.config', 'microsoft-edge', 'NativeMessagingHosts', manifestName);
case Browser.firefox:
return path.join(
home, '.mozilla', 'native-messaging-hosts', manifestName);
return path.join(home, '.mozilla', 'native-messaging-hosts', manifestName);
}
}
return null;
-76
View File
@@ -1,76 +0,0 @@
import 'dart:core';
import 'package:checkable_treeview/checkable_treeview.dart';
import 'package:flutter/material.dart';
import '../api/model/resource.dart';
import '../app/views/file_icon.dart';
import 'util.dart';
extension ListFileInfoExtension on List<FileInfo> {
List<TreeNode<int>> toTreeNodes() {
final List<TreeNode<int>> rootNodes = [];
final Map<String, TreeNode<int>> dirNodes = {};
var nodeIndex = 0;
for (var i = 0; i < length; i++) {
final file = this[i];
final parts = file.path.split('/');
String currentPath = '';
TreeNode<int>? parentNode;
// Create or get directory nodes
for (final part in parts) {
if (part.isEmpty) continue;
currentPath += '/$part';
if (!dirNodes.containsKey(currentPath)) {
final node = TreeNode<int>(
value: nodeIndex++,
label: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(file.name),
Text(Util.fmtByte(file.size)),
],
),
icon: Icon(
fileIcon(part, isFolder: true),
size: 18,
),
children: [],
);
dirNodes[currentPath] = node;
if (parentNode == null) {
rootNodes.add(node);
} else {
parentNode.children.add(node);
}
}
parentNode = dirNodes[currentPath];
}
// Create file node using file.name
final fileNode = TreeNode<int>(
value: nodeIndex++,
label: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(file.name),
Text(Util.fmtByte(file.size)),
],
),
icon: Icon(fileIcon(file.name, isFolder: false), size: 18),
children: [],
);
// Add file node to parent or root
if (parentNode != null) {
parentNode.children.add(fileNode);
} else {
rootNodes.add(fileNode);
}
}
return rootNodes;
}
}
-37
View File
@@ -1,37 +0,0 @@
import 'dart:io';
import 'package:open_dir/open_dir.dart';
import 'package:path/path.dart' as path;
import 'package:url_launcher/url_launcher_string.dart';
class FileExplorer {
static Future<void> openAndSelectFile(String filePath) async {
if (await FileSystemEntity.isFile(filePath)) {
_openFile(filePath);
} else if (await FileSystemEntity.isDirectory(filePath)) {
await _openDirectory(filePath);
} else {
// If file does not exist, open its parent directory
final parentPath = path.dirname(filePath);
if (await FileSystemEntity.isDirectory(parentPath)) {
await _openDirectory(parentPath);
}
}
}
static Future<void> _openDirectory(String directoryPath) async {
if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
await OpenDir().openNativeDir(path: directoryPath);
} else {
await launchUrlString("file://$directoryPath");
}
}
static Future<void> _openFile(String filePath) async {
if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
final fileName = path.basename(filePath);
final parentPath = path.dirname(filePath);
await OpenDir()
.openNativeDir(path: parentPath, highlightedFileName: fileName);
}
}
}
+37 -91
View File
@@ -1,104 +1,50 @@
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import '../api/model/downloader_config.dart';
import '../app/modules/app/controllers/app_controller.dart';
enum MirrorType {
githubSource,
githubRelease,
}
enum MirrorType { githubSource, githubRelease }
/// Get the configured mirrors
List<GithubMirror> _getConfiguredMirrors() {
try {
final appController = Get.find<AppController>();
final config = appController.downloaderConfig.value.extra.githubMirror;
Future<String> githubAutoMirror(String rawUrl, MirrorType type, {required ExtraConfigGithubMirror config}) async {
final mirrorUrls = githubMirrorUrls(rawUrl, type, config: config);
if (mirrorUrls.isEmpty) return rawUrl;
if (!config.enabled) {
return [];
}
// Return configured mirrors (filtering not deleted ones)
return config.mirrors.where((m) => !m.isDeleted).toList();
} catch (e) {
// Fallback to empty list if controller not found
return [];
}
}
/// Auto detect the best mirror for the given [rawUrl] and [type]
Future<String> githubAutoMirror(String rawUrl, MirrorType type) async {
final mirrorUrls = githubMirrorUrls(rawUrl, type);
// If no mirrors, return original URL
if (mirrorUrls.isEmpty) {
return rawUrl;
}
// Ping all mirrors and get the fastest one
final pingResult = await Future.wait(mirrorUrls.map((e) async {
final client = Dio()
..options.sendTimeout = const Duration(seconds: 3)
..options.connectTimeout = const Duration(seconds: 3);
var time = DateTime.now().millisecondsSinceEpoch;
try {
final response = await client.head(e);
if (response.statusCode == 200) {
time = DateTime.now().millisecondsSinceEpoch - time;
return (e, time);
final results = await Future.wait(
mirrorUrls.map((url) async {
final client = Dio(
BaseOptions(connectTimeout: const Duration(seconds: 3), sendTimeout: const Duration(seconds: 3)),
);
final startedAt = DateTime.now();
try {
final response = await client.head<void>(url);
if (response.statusCode == 200) return (url, DateTime.now().difference(startedAt));
} catch (_) {
// A failed mirror probe must never prevent the original download.
} finally {
client.close();
}
} catch (e) {
// ignore
} finally {
client.close();
}
return (e, -1);
}));
return (url, null);
}),
);
var list = pingResult.where((e) => e.$2 != -1).toList()
..sort((a, b) => a.$2.compareTo(b.$2));
if (list.isNotEmpty) {
return list.first.$1;
}
return rawUrl;
final available = results.where((result) => result.$2 != null).toList()
..sort((left, right) => left.$2!.compareTo(right.$2!));
return available.isEmpty ? rawUrl : available.first.$1;
}
List<String> githubMirrorUrls(String rawUrl, MirrorType type) {
final mirrors = _getConfiguredMirrors();
final ret = <String>[];
for (final mirror in mirrors) {
String? mirrorUrl;
if (mirror.type == GithubMirrorType.jsdelivr) {
// jsdelivr only supports source files
if (type != MirrorType.githubSource) {
continue;
}
// Transform: https://raw.githubusercontent.com/user/repo/master/path
// To: https://fastly.jsdelivr.net/gh/user/repo/path
final jsDelivrPattern = RegExp(
r'.*raw\.githubusercontent\.com(/[^/]+)(/[^/]+)/(?:master|main)(/.*)');
final match = jsDelivrPattern.firstMatch(rawUrl);
if (match != null) {
final user = match.group(1);
final repo = match.group(2);
final path = match.group(3);
mirrorUrl = '${mirror.url}$user$repo$path';
}
} else if (mirror.type == GithubMirrorType.ghProxy) {
// gh-proxy supports both source and release
// Simply prepend the mirror URL to the original URL
mirrorUrl = '${mirror.url}/$rawUrl';
}
if (mirrorUrl != null) {
ret.add(mirrorUrl);
List<String> githubMirrorUrls(String rawUrl, MirrorType type, {required ExtraConfigGithubMirror config}) {
if (!config.enabled) return const [];
final urls = <String>[];
for (final mirror in config.mirrors.where((item) => !item.isDeleted)) {
switch (mirror.type) {
case GithubMirrorType.jsdelivr:
if (type != MirrorType.githubSource) continue;
final match = RegExp(r'.*raw\.githubusercontent\.com(/[^/]+)(/[^/]+)/(?:master|main)(/.*)').firstMatch(rawUrl);
if (match != null) {
urls.add('${mirror.url}${match.group(1)}${match.group(2)}${match.group(3)}');
}
case GithubMirrorType.ghProxy:
urls.add('${mirror.url}/$rawUrl');
}
}
return ret;
return urls;
}
-30
View File
@@ -1,30 +0,0 @@
import 'package:flutter/services.dart';
/// A [TextInputFormatter] that restricts input to a numerical range between [min] and [max].
class NumericalRangeFormatter extends TextInputFormatter {
final int min;
final int max;
NumericalRangeFormatter({required this.min, required this.max});
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
if (newValue.text.isEmpty) {
return newValue;
}
var intVal = int.tryParse(newValue.text);
if (intVal == null) {
return oldValue;
}
if (intVal < min) {
return newValue.copyWith(text: min.toString());
} else if (intVal > max) {
return oldValue.copyWith(text: max.toString());
} else {
return newValue;
}
}
}
-13
View File
@@ -1,13 +0,0 @@
import 'package:flutter/material.dart';
Locale toLocale(String key) {
final arr = key.split('_');
return Locale(arr[0], arr[1]);
}
String getLocaleKey(Locale locale) {
return '${locale.languageCode}_${locale.countryCode}';
}
const debugLocale = Locale('zh', 'CN');
const fallbackLocale = Locale('en', 'US');
+2 -2
View File
@@ -6,7 +6,7 @@ import 'util.dart';
late final Logger logger;
initLogger() {
void initLogger() {
// if is debug mode, don't log to file
logger = Logger(
filter: ProductionFilter(),
@@ -19,7 +19,7 @@ String logsDir() {
return path.join(Util.getStorageDir(), 'logs');
}
_buildOutput() {
LogOutput? _buildOutput() {
// if is debug mode, don't log to file
if (!kDebugMode && Util.isDesktop()) {
final logDirPath = logsDir();
-35
View File
@@ -1,35 +0,0 @@
import 'package:get/get.dart';
import '../api/model/result.dart';
void showErrorMessage(msg) {
final title = 'error'.tr;
if (msg is Result) {
Get.snackbar(title, msg.msg!);
return;
}
if (msg is Exception) {
final message = (msg as dynamic).message;
if (message is Result) {
Get.snackbar(title, ((msg as dynamic).message as Result).msg!);
return;
}
if (message is String) {
Get.snackbar(title, message);
return;
}
}
Get.snackbar(title, msg.toString());
}
var _showMessageFlag = true;
void showMessage(title, msg) {
if (_showMessageFlag) {
_showMessageFlag = false;
Get.snackbar(title, msg);
Future.delayed(const Duration(seconds: 3), () {
_showMessageFlag = true;
});
}
}
+9
View File
@@ -2,6 +2,15 @@ import 'package:package_info_plus/package_info_plus.dart';
late PackageInfo packageInfo;
String get appVersion => normalizeAppVersion(packageInfo.version);
String normalizeAppVersion(String platformVersion) {
final version = platformVersion.trim();
final parts = version.split('.');
if (parts.length != 4 || parts.any((part) => int.tryParse(part) == null)) return version;
return '${parts[0]}.${parts[1]}.${parts[2]}-beta.${parts[3]}';
}
Future<void> initPackageInfo() async {
packageInfo = await PackageInfo.fromPlatform();
}
@@ -1,32 +1,37 @@
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:win32_registry/win32_registry.dart';
import '../../util.dart';
import '../../win32.dart';
doRegisterUrlScheme(String scheme) {
const _linuxDesktopFileName = 'com.gopeed.Gopeed.desktop';
void doRegisterUrlScheme(String scheme) {
if (Util.isWindows()) {
final schemeKey = 'Software\\Classes\\$scheme';
final appPath = Platform.resolvedExecutable;
upsertRegistry(
schemeKey,
'URL Protocol',
'',
);
upsertRegistry(
'$schemeKey\\shell\\open\\command',
'',
'"$appPath" "%1"',
);
upsertRegistry(schemeKey, 'URL Protocol', '');
upsertRegistry('$schemeKey\\shell\\open\\command', '', '"$appPath" "%1"');
return;
}
if (Util.isLinux()) {
_installLinuxDesktopEntry(mimeTypes: {'x-scheme-handler/$scheme'});
_setLinuxDefaultMime('x-scheme-handler/$scheme');
}
}
doUnregisterUrlScheme(String scheme) {
void doUnregisterUrlScheme(String scheme) {
if (Util.isWindows()) {
Registry.currentUser
.deleteKey('Software\\Classes\\$scheme', recursive: true);
Registry.currentUser.deleteKey('Software\\Classes\\$scheme', recursive: true);
return;
}
if (Util.isLinux()) {
return;
}
}
@@ -37,41 +42,87 @@ const _torrentAppRegKey = 'Software\\Classes\\$_torrentRegValue';
/// Register as the system's default torrent client
/// 1. Register the scheme "magnet"
/// 2. Register the file type ".torrent"
doRegisterDefaultTorrentClient() {
void doRegisterDefaultTorrentClient() {
if (Util.isWindows()) {
doRegisterUrlScheme("magnet");
final appPath = Platform.resolvedExecutable;
final iconPath =
'${File(appPath).parent.path}\\data\\flutter_assets\\assets\\tray_icon\\icon.ico';
upsertRegistry(
_torrentRegKey,
'',
_torrentRegValue,
);
upsertRegistry(
_torrentAppRegKey,
'',
'Torrent file',
);
upsertRegistry(
'$_torrentAppRegKey\\DefaultIcon',
'',
iconPath,
);
upsertRegistry(
'$_torrentAppRegKey\\shell\\open\\command',
'',
'"$appPath" "file:///%1"',
);
final iconPath = '${File(appPath).parent.path}\\data\\flutter_assets\\assets\\tray_icon\\icon.ico';
upsertRegistry(_torrentRegKey, '', _torrentRegValue);
upsertRegistry(_torrentAppRegKey, '', 'Torrent file');
upsertRegistry('$_torrentAppRegKey\\DefaultIcon', '', iconPath);
upsertRegistry('$_torrentAppRegKey\\shell\\open\\command', '', '"$appPath" "file:///%1"');
return;
}
if (Util.isLinux()) {
_installLinuxDesktopEntry(mimeTypes: {'x-scheme-handler/magnet', 'application/x-bittorrent'});
_setLinuxDefaultMime('x-scheme-handler/magnet');
_setLinuxDefaultMime('application/x-bittorrent');
}
}
doUnregisterDefaultTorrentClient() {
void doUnregisterDefaultTorrentClient() {
if (Util.isWindows()) {
doUnregisterUrlScheme("magnet");
Registry.currentUser.deleteKey(_torrentRegKey, recursive: true);
Registry.currentUser.deleteKey(_torrentAppRegKey, recursive: true);
return;
}
if (Util.isLinux()) {
return;
}
}
void _installLinuxDesktopEntry({required Set<String> mimeTypes}) {
final applicationsDir = path.join(Platform.environment['HOME'] ?? '', '.local', 'share', 'applications');
if (applicationsDir.startsWith('.local')) {
return;
}
final desktopFile = File(path.join(applicationsDir, _linuxDesktopFileName));
final existingMimeTypes = _readLinuxDesktopMimeTypes(desktopFile);
final allMimeTypes = <String>{'x-scheme-handler/gopeed', ...existingMimeTypes, ...mimeTypes};
desktopFile.parent.createSync(recursive: true);
desktopFile.writeAsStringSync('''
[Desktop Entry]
Name=Gopeed
GenericName=Download Manager
Comment=A modern download manager for all platforms
Terminal=false
Exec=${Platform.resolvedExecutable} %U
Icon=com.gopeed.Gopeed
Type=Application
Categories=Utility;Network;
Keywords=Bittorrent;Downloader;
MimeType=${allMimeTypes.join(';')};
''');
Process.runSync('update-desktop-database', [applicationsDir]);
}
Set<String> _readLinuxDesktopMimeTypes(File desktopFile) {
if (!desktopFile.existsSync()) {
return {};
}
for (final line in desktopFile.readAsLinesSync()) {
if (line.startsWith('MimeType=')) {
return line
.substring('MimeType='.length)
.split(';')
.map((value) => value.trim())
.where((value) => value.isNotEmpty)
.toSet();
}
}
return {};
}
void _setLinuxDefaultMime(String mimeType) {
Process.runSync('xdg-mime', ['default', _linuxDesktopFileName, mimeType]);
}
@@ -1,10 +1,9 @@
import 'scheme_register_stub.dart'
if (dart.library.io) 'entry/scheme_register_native.dart';
import 'scheme_register_stub.dart' if (dart.library.io) 'entry/scheme_register_native.dart';
registerUrlScheme(String scheme) => doRegisterUrlScheme(scheme);
void registerUrlScheme(String scheme) => doRegisterUrlScheme(scheme);
unregisterUrlScheme(String scheme) => doUnregisterUrlScheme(scheme);
void unregisterUrlScheme(String scheme) => doUnregisterUrlScheme(scheme);
registerDefaultTorrentClient() => doRegisterDefaultTorrentClient();
void registerDefaultTorrentClient() => doRegisterDefaultTorrentClient();
unregisterDefaultTorrentClient() => doUnregisterDefaultTorrentClient();
void unregisterDefaultTorrentClient() => doUnregisterDefaultTorrentClient();
@@ -1,7 +1,7 @@
doRegisterUrlScheme(String scheme) => throw UnimplementedError();
void doRegisterUrlScheme(String scheme) => throw UnimplementedError();
doUnregisterUrlScheme(String scheme) => throw UnimplementedError();
void doUnregisterUrlScheme(String scheme) => throw UnimplementedError();
doRegisterDefaultTorrentClient() => throw UnimplementedError();
void doRegisterDefaultTorrentClient() => throw UnimplementedError();
doUnregisterDefaultTorrentClient() => throw UnimplementedError();
void doUnregisterDefaultTorrentClient() => throw UnimplementedError();
File diff suppressed because it is too large. Load diff
+29 -43
View File
@@ -8,6 +8,8 @@ import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../core/utils/byte_size_formatter.dart';
class Util {
static String? _storageDir;
@@ -30,32 +32,15 @@ class Util {
}
static String safePathJoin(List<String> paths) {
return paths
.where((e) => e.isNotEmpty)
.map((e) => safeDir(e))
.join("/")
.replaceAll(RegExp(r'//'), "/");
return paths.where((e) => e.isNotEmpty).map((e) => safeDir(e)).join("/").replaceAll(RegExp(r'//'), "/");
}
static String fmtByte(int byte) {
if (byte < 0) {
return "0 B";
} else if (byte < 1024) {
return "$byte B";
} else if (byte < 1024 * 1024) {
return "${(byte / 1024).toStringAsFixed(2)} KB";
} else if (byte < 1024 * 1024 * 1024) {
return "${(byte / 1024 / 1024).toStringAsFixed(2)} MB";
} else {
return "${(byte / 1024 / 1024 / 1024).toStringAsFixed(2)} GB";
}
}
static String fmtByte(int byte) => ByteSizeFormatter.format(byte);
static Future<void> initStorageDir() async {
var storageDir = "";
if (Util.isWindows()) {
storageDir =
path.join(File(Platform.resolvedExecutable).parent.path, "storage");
storageDir = path.join(File(Platform.resolvedExecutable).parent.path, "storage");
} else if (!Util.isWeb()) {
if (Util.isLinux()) {
storageDir = File(Platform.resolvedExecutable).parent.path;
@@ -78,42 +63,42 @@ class Util {
return _storageDir!;
}
static isAndroid() {
static bool isAndroid() {
return !kIsWeb && Platform.isAndroid;
}
static isIOS() {
static bool isIOS() {
return !kIsWeb && Platform.isIOS;
}
static isMobile() {
static bool isMobile() {
return !kIsWeb && (Platform.isAndroid || Platform.isIOS);
}
static isDesktop() {
static bool isDesktop() {
if (kIsWeb) {
return false;
}
return Platform.isWindows || Platform.isLinux || Platform.isMacOS;
}
static isWindows() {
static bool isWindows() {
return !kIsWeb && Platform.isWindows;
}
static isMacos() {
static bool isMacos() {
return !kIsWeb && Platform.isMacOS;
}
static isLinux() {
static bool isLinux() {
return !kIsWeb && Platform.isLinux;
}
static isWeb() {
static bool isWeb() {
return kIsWeb;
}
static supportUnixSocket() {
static bool supportUnixSocket() {
if (kIsWeb) {
return false;
}
@@ -129,22 +114,24 @@ class Util {
}
// if one future complete, return the result, only all future error, return the last error
static anyOk<T>(Iterable<Future<T>> futures) {
static Future<T> anyOk<T>(Iterable<Future<T>> futures) {
final completer = Completer<T>();
Object lastError;
var count = futures.length;
for (var future in futures) {
future.then((value) {
if (!completer.isCompleted) {
completer.complete(value);
}
}).catchError((e) {
lastError = e;
count--;
if (count == 0) {
completer.completeError(lastError);
}
});
future
.then((value) {
if (!completer.isCompleted) {
completer.complete(value);
}
})
.catchError((e) {
lastError = e;
count--;
if (count == 0) {
completer.completeError(lastError);
}
});
}
return completer.future;
}
@@ -168,8 +155,7 @@ class Util {
return path.join(dir.path, fileName);
}
static Future<void> installAsset(String assetPath, String targetPath,
{bool executable = false}) async {
static Future<void> installAsset(String assetPath, String targetPath, {bool executable = false}) async {
Future<List<int>> getAssetData() async {
final asset = await rootBundle.load(assetPath);
return asset.buffer.asUint8List(asset.offsetInBytes, asset.lengthInBytes);
+4 -6
View File
@@ -2,7 +2,7 @@ import 'package:win32_registry/win32_registry.dart';
/// Check registry key
/// If the key does not exist or the value is different, return false
checkRegistry(String keyPath, String valueName, String value) {
bool checkRegistry(String keyPath, String valueName, String value) {
RegistryKey regKey;
try {
regKey = Registry.openPath(RegistryHive.currentUser, path: keyPath);
@@ -15,18 +15,16 @@ checkRegistry(String keyPath, String valueName, String value) {
/// Upsert registry key
/// If the key does not exist, create it
/// If the value does not exist or is different, update it
upsertRegistry(String keyPath, String valueName, String value) {
void upsertRegistry(String keyPath, String valueName, String value) {
RegistryKey regKey;
try {
regKey = Registry.openPath(RegistryHive.currentUser,
path: keyPath, desiredAccessRights: AccessRights.allAccess);
regKey = Registry.openPath(RegistryHive.currentUser, path: keyPath, desiredAccessRights: AccessRights.allAccess);
} catch (e) {
regKey = Registry.currentUser.createKey(keyPath);
}
if (regKey.getValueAsString(valueName) != value) {
regKey
.createValue(RegistryValue(valueName, RegistryValueType.string, value));
regKey.createValue(RegistryValue(valueName, RegistryValueType.string, value));
}
regKey.close();
}