mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-18 22:33:42 +00:00
feat: new ui (#1455)
This commit is contained in:
742 files changed
+59951
-5934
No files matched your search
@@ -0,0 +1,49 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
/// Keeps the Android process alive while Gopeed is available for downloads.
|
||||
class AndroidForegroundService {
|
||||
const AndroidForegroundService._();
|
||||
|
||||
static Future<void> ensureRunning(AppLocalizations l10n) async {
|
||||
if (!Platform.isAndroid) return;
|
||||
|
||||
FlutterForegroundTask.init(
|
||||
androidNotificationOptions: AndroidNotificationOptions(
|
||||
channelId: 'gopeed_service',
|
||||
channelName: l10n.androidForegroundServiceChannel,
|
||||
channelImportance: NotificationChannelImportance.LOW,
|
||||
showWhen: true,
|
||||
priority: NotificationPriority.LOW,
|
||||
),
|
||||
iosNotificationOptions: const IOSNotificationOptions(showNotification: false, playSound: false),
|
||||
foregroundTaskOptions: ForegroundTaskOptions(
|
||||
eventAction: ForegroundTaskEventAction.nothing(),
|
||||
autoRunOnBoot: true,
|
||||
allowWakeLock: true,
|
||||
allowWifiLock: true,
|
||||
),
|
||||
);
|
||||
|
||||
if (await FlutterForegroundTask.isRunningService) {
|
||||
_throwOnFailure(await FlutterForegroundTask.restartService());
|
||||
return;
|
||||
}
|
||||
|
||||
_throwOnFailure(
|
||||
await FlutterForegroundTask.startService(
|
||||
notificationTitle: l10n.androidForegroundNotificationTitle,
|
||||
notificationText: l10n.androidForegroundNotificationText,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static void _throwOnFailure(ServiceRequestResult result) {
|
||||
if (result case ServiceRequestFailure(:final error)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../shared/theme/app_theme_color.dart';
|
||||
|
||||
enum AppThemeMode {
|
||||
system('system'),
|
||||
light('light'),
|
||||
dark('dark');
|
||||
|
||||
const AppThemeMode(this.key);
|
||||
|
||||
final String key;
|
||||
|
||||
static AppThemeMode fromKey(String? key) {
|
||||
return values.where((mode) => mode.key == key).firstOrNull ?? AppThemeMode.system;
|
||||
}
|
||||
}
|
||||
|
||||
class AppAppearanceState {
|
||||
const AppAppearanceState({this.themeMode = AppThemeMode.system, this.themeColor = AppThemeColor.green});
|
||||
|
||||
final AppThemeMode themeMode;
|
||||
final AppThemeColor themeColor;
|
||||
|
||||
bool resolveIsLight(Brightness systemBrightness) {
|
||||
return switch (themeMode) {
|
||||
AppThemeMode.system => systemBrightness == Brightness.light,
|
||||
AppThemeMode.light => true,
|
||||
AppThemeMode.dark => false,
|
||||
};
|
||||
}
|
||||
|
||||
AppAppearanceState copyWith({AppThemeMode? themeMode, AppThemeColor? themeColor}) {
|
||||
return AppAppearanceState(themeMode: themeMode ?? this.themeMode, themeColor: themeColor ?? this.themeColor);
|
||||
}
|
||||
}
|
||||
|
||||
final appAppearanceControllerProvider = NotifierProvider<AppAppearanceController, AppAppearanceState>(
|
||||
AppAppearanceController.new,
|
||||
);
|
||||
|
||||
class AppAppearanceController extends Notifier<AppAppearanceState> {
|
||||
bool _initialized = false;
|
||||
|
||||
@override
|
||||
AppAppearanceState build() => const AppAppearanceState();
|
||||
|
||||
void initialize(ExtraConfig config) {
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
state = AppAppearanceState(
|
||||
themeMode: AppThemeMode.fromKey(config.themeMode),
|
||||
themeColor: AppThemeColor.fromKey(config.themeColor),
|
||||
);
|
||||
}
|
||||
|
||||
void setThemeMode(AppThemeMode mode) {
|
||||
_initialized = true;
|
||||
state = state.copyWith(themeMode: mode);
|
||||
}
|
||||
|
||||
void setThemeColor(AppThemeColor color) {
|
||||
_initialized = true;
|
||||
state = state.copyWith(themeColor: color);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:app_links/app_links.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:share_handler/share_handler.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/install_extension.dart';
|
||||
import '../../api/model/request.dart';
|
||||
import '../../core/entry/app_startup_options.dart';
|
||||
import '../../core/utils/content_uri_resolver.dart';
|
||||
import '../../core/window/app_window_launcher.dart';
|
||||
import '../../features/extensions/application/pending_extension_install.dart';
|
||||
import '../../features/tasks/application/pending_create_task.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../router/app_router.dart';
|
||||
import 'app_runtime_controller.dart';
|
||||
|
||||
final appDeepLinkControllerProvider = AsyncNotifierProvider<AppDeepLinkController, AppDeepLinkState>(
|
||||
AppDeepLinkController.new,
|
||||
);
|
||||
|
||||
class AppDeepLinkState {
|
||||
const AppDeepLinkState({this.started = false});
|
||||
|
||||
final bool started;
|
||||
}
|
||||
|
||||
class AppDeepLinkController extends AsyncNotifier<AppDeepLinkState> {
|
||||
StreamSubscription<Uri>? _subscription;
|
||||
StreamSubscription<SharedMedia>? _sharedMediaSubscription;
|
||||
bool _started = false;
|
||||
|
||||
@override
|
||||
Future<AppDeepLinkState> build() async {
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime == null || _started || kIsWeb) {
|
||||
return AppDeepLinkState(started: _started);
|
||||
}
|
||||
_started = true;
|
||||
final appLinks = AppLinks();
|
||||
_subscription = appLinks.uriLinkStream.listen((uri) {
|
||||
unawaited(_handleUri(uri));
|
||||
});
|
||||
if (Util.isMobile()) {
|
||||
final shareHandler = ShareHandlerPlatform.instance;
|
||||
_sharedMediaSubscription = shareHandler.sharedMediaStream.listen((media) {
|
||||
unawaited(_handleSharedMedia(media, ignoreContentUri: true));
|
||||
});
|
||||
try {
|
||||
final media = await shareHandler.getInitialSharedMedia();
|
||||
if (media != null) {
|
||||
await _handleSharedMedia(media);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
ref.onDispose(() {
|
||||
_subscription?.cancel();
|
||||
_sharedMediaSubscription?.cancel();
|
||||
});
|
||||
try {
|
||||
final initial = await appLinks.getInitialLink();
|
||||
if (initial != null) {
|
||||
await _handleUri(initial);
|
||||
}
|
||||
} catch (_) {}
|
||||
return const AppDeepLinkState(started: true);
|
||||
}
|
||||
|
||||
Future<void> _handleSharedMedia(SharedMedia media, {bool ignoreContentUri = false}) async {
|
||||
final uri = sharedMediaUri(media);
|
||||
if (uri == null || (ignoreContentUri && uri.scheme == 'content')) return;
|
||||
await _handleUri(uri);
|
||||
}
|
||||
|
||||
Future<void> _handleUri(Uri uri) async {
|
||||
if (uri.scheme == 'gopeed') {
|
||||
await _handleGopeedUri(uri);
|
||||
return;
|
||||
}
|
||||
final createTask = CreateTask(req: Request(url: await _uriToTaskUrl(uri)));
|
||||
await _openCreate(createTask);
|
||||
}
|
||||
|
||||
Future<void> _handleGopeedUri(Uri uri) async {
|
||||
if (isSilentGopeedWakeUri(uri)) {
|
||||
return;
|
||||
}
|
||||
final route = gopeedDeepLinkRoute(uri);
|
||||
if (route == '/create') {
|
||||
final params = uri.queryParameters['params'];
|
||||
if (params?.isNotEmpty == true) {
|
||||
await _openCreate(CreateTask.fromJson(_decodeParams(params!)));
|
||||
return;
|
||||
}
|
||||
await _openCreate(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (route == '/extension') {
|
||||
final params = uri.queryParameters['params'];
|
||||
if (params?.isNotEmpty == true) {
|
||||
ref.read(pendingExtensionInstallProvider.notifier).set(InstallExtension.fromJson(_decodeParams(params!)));
|
||||
}
|
||||
await _go('/extensions');
|
||||
return;
|
||||
}
|
||||
|
||||
await _go('/');
|
||||
}
|
||||
|
||||
Future<void> _openCreate(CreateTask? createTask) async {
|
||||
if (Util.isDesktop()) {
|
||||
final opened = await AppWindowLauncher.openCreateTaskWindow(createTask: createTask);
|
||||
if (!opened) {
|
||||
ref.read(pendingCreateTaskProvider.notifier).set(createTask);
|
||||
await _go('/create');
|
||||
}
|
||||
return;
|
||||
}
|
||||
ref.read(pendingCreateTaskProvider.notifier).set(createTask);
|
||||
await _go('/create');
|
||||
}
|
||||
|
||||
Future<void> _go(String route) async {
|
||||
if (Util.isDesktop()) {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
}
|
||||
final context = AppRouter.rootNavigatorKey.currentContext;
|
||||
if (context != null && context.mounted) {
|
||||
context.go(route);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeParams(String params) {
|
||||
final safeParams = params.replaceAll('"', '').replaceAll(' ', '+');
|
||||
final paramsJson = String.fromCharCodes(base64Decode(base64.normalize(safeParams)));
|
||||
return jsonDecode(paramsJson) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<String> _uriToTaskUrl(Uri uri) async {
|
||||
if (uri.scheme == 'magnet' || uri.scheme == 'http' || uri.scheme == 'https') {
|
||||
return uri.toString();
|
||||
}
|
||||
if (uri.scheme == 'file') {
|
||||
return Util.isWindows() ? Uri.decodeFull(uri.path.substring(1)) : uri.path;
|
||||
}
|
||||
if (uri.scheme == 'content' && Util.isAndroid()) {
|
||||
return ContentUriResolver.copyToCache(uri);
|
||||
}
|
||||
throw ArgumentError.value(uri, 'uri', 'Unsupported task URI scheme');
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks the actionable URI from content received through the platform share UI.
|
||||
///
|
||||
/// File attachments take precedence over an optional text caption. Both the
|
||||
/// Android and iOS share-handler implementations expose attachments as local
|
||||
/// paths that are ready for the app to read.
|
||||
Uri? sharedMediaUri(SharedMedia media) {
|
||||
final attachments = media.attachments;
|
||||
if (attachments != null) {
|
||||
for (final attachment in attachments) {
|
||||
final path = attachment?.path.trim();
|
||||
if (path != null && path.isNotEmpty) return Uri.file(path);
|
||||
}
|
||||
}
|
||||
|
||||
final content = media.content?.trim();
|
||||
if (content == null || content.isEmpty) return null;
|
||||
return Uri.tryParse(content);
|
||||
}
|
||||
|
||||
/// Gopeed's established links use `gopeed:///create`, where the action is the
|
||||
/// URI path. Do not interpret the URI host as an action: the host-style
|
||||
/// `gopeed://create` form is intentionally unsupported.
|
||||
String gopeedDeepLinkRoute(Uri uri) {
|
||||
return uri.path;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../api/model/task.dart';
|
||||
import '../../core/capabilities/app_capabilities.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../util/util.dart';
|
||||
import 'app_runtime_controller.dart';
|
||||
|
||||
final appNotificationControllerProvider = AsyncNotifierProvider<AppNotificationController, AppNotificationState>(
|
||||
AppNotificationController.new,
|
||||
);
|
||||
|
||||
class AppNotificationState {
|
||||
const AppNotificationState({this.started = false});
|
||||
|
||||
final bool started;
|
||||
}
|
||||
|
||||
class AppNotificationController extends AsyncNotifier<AppNotificationState> {
|
||||
final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
|
||||
final Map<String, Status> _previousStatus = {};
|
||||
Timer? _timer;
|
||||
var _notificationId = 0;
|
||||
|
||||
@override
|
||||
Future<AppNotificationState> build() async {
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime == null || kIsWeb || !Util.isDesktop()) {
|
||||
return const AppNotificationState();
|
||||
}
|
||||
await _initNotifications(appLocalizationsFor(runtime.downloaderConfig.extra.locale));
|
||||
_startPolling();
|
||||
ref.onDispose(() {
|
||||
_timer?.cancel();
|
||||
});
|
||||
return const AppNotificationState(started: true);
|
||||
}
|
||||
|
||||
Future<void> _initNotifications(AppLocalizations locale) async {
|
||||
const darwin = DarwinInitializationSettings(
|
||||
requestAlertPermission: false,
|
||||
requestBadgePermission: false,
|
||||
requestSoundPermission: false,
|
||||
);
|
||||
final linux = LinuxInitializationSettings(
|
||||
defaultActionName: locale.open,
|
||||
defaultIcon: AssetsLinuxIcon('assets/icon/icon.png'),
|
||||
);
|
||||
|
||||
String? windowsIconPath;
|
||||
try {
|
||||
if (Util.isWindows()) {
|
||||
final byteData = await rootBundle.load('assets/icon/icon.ico');
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final file = File('${tempDir.path}/notification_icon.ico');
|
||||
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
|
||||
windowsIconPath = file.path;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
final windows = WindowsInitializationSettings(
|
||||
appName: 'Gopeed',
|
||||
appUserModelId: 'com.gopeed.gopeed',
|
||||
guid: '3c1bf3f4-3d91-4eaa-a33f-8705e71cf1ce',
|
||||
iconPath: windowsIconPath,
|
||||
);
|
||||
|
||||
await _plugin.initialize(
|
||||
settings: InitializationSettings(macOS: darwin, linux: linux, windows: windows),
|
||||
);
|
||||
}
|
||||
|
||||
void _startPolling() {
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 2), (_) async {
|
||||
try {
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
if (runtime?.downloaderConfig.extra.desktopNotification == false) {
|
||||
return;
|
||||
}
|
||||
final tasks = await ref.read(gopeedServiceProvider).getTasks(Status.values);
|
||||
final locale = appLocalizationsFor(runtime?.downloaderConfig.extra.locale ?? '');
|
||||
for (final task in tasks) {
|
||||
final previous = _previousStatus[task.id];
|
||||
if (previous != null && previous != task.status) {
|
||||
if (task.status == Status.done) {
|
||||
await _showNotification(title: locale.notificationTaskDone, body: task.name);
|
||||
} else if (task.status == Status.error) {
|
||||
await _showNotification(title: locale.notificationTaskError, body: task.name);
|
||||
}
|
||||
}
|
||||
_previousStatus[task.id] = task.status;
|
||||
}
|
||||
final currentIds = tasks.map((task) => task.id).toSet();
|
||||
_previousStatus.removeWhere((id, _) => !currentIds.contains(id));
|
||||
} catch (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _showNotification({required String title, required String body}) async {
|
||||
const details = NotificationDetails(
|
||||
macOS: DarwinNotificationDetails(),
|
||||
linux: LinuxNotificationDetails(),
|
||||
windows: WindowsNotificationDetails(),
|
||||
);
|
||||
await _plugin.show(id: _notificationId++, title: title, body: body, notificationDetails: details);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:launch_at_startup/launch_at_startup.dart';
|
||||
import 'package:tray_manager/tray_manager.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../core/libgopeed_boot.dart';
|
||||
import '../../core/capabilities/app_capabilities.dart';
|
||||
import '../../core/window/app_window_launcher.dart';
|
||||
import '../../core/window/window_capability_transport.dart';
|
||||
import '../../database/database.dart';
|
||||
import '../../database/entity.dart';
|
||||
import '../../features/tasks/application/pending_create_task.dart';
|
||||
import '../../features/tasks/application/pending_update_task.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../util/package_info.dart';
|
||||
import '../../util/updater.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../../util/browser_extension_host/browser_extension_host.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../../util/scheme_register/scheme_register.dart';
|
||||
import '../rpc/host_rpc_service.dart';
|
||||
import '../router/app_router.dart';
|
||||
import 'app_runtime_controller.dart';
|
||||
|
||||
final appPlatformControllerProvider = AsyncNotifierProvider<AppPlatformController, AppPlatformState>(
|
||||
AppPlatformController.new,
|
||||
);
|
||||
|
||||
class AppPlatformState {
|
||||
const AppPlatformState({
|
||||
this.started = false,
|
||||
this.launchAtStartup = false,
|
||||
this.runAsMenubarApp = false,
|
||||
this.updateStatus = AppUpdateStatus.idle,
|
||||
this.latestVersion,
|
||||
this.updateError,
|
||||
});
|
||||
|
||||
final bool started;
|
||||
final bool launchAtStartup;
|
||||
final bool runAsMenubarApp;
|
||||
final AppUpdateStatus updateStatus;
|
||||
final VersionInfo? latestVersion;
|
||||
final String? updateError;
|
||||
}
|
||||
|
||||
enum AppUpdateStatus { idle, checking, upToDate, available, failed }
|
||||
|
||||
class AppPlatformController extends AsyncNotifier<AppPlatformState> with WindowListener, TrayListener {
|
||||
bool _started = false;
|
||||
String? _trayLocaleConfig;
|
||||
bool _updateInitialized = false;
|
||||
bool _launchAtStartup = false;
|
||||
bool _runAsMenubarApp = false;
|
||||
AppUpdateStatus _updateStatus = AppUpdateStatus.idle;
|
||||
VersionInfo? _latestVersion;
|
||||
String? _updateError;
|
||||
Future<VersionInfo?>? _checkUpdateFuture;
|
||||
final _windowsResizeSave = Util.debounce(() async {
|
||||
final size = await windowManager.getSize();
|
||||
Database.instance.saveWindowState(WindowStateEntity(width: size.width, height: size.height));
|
||||
}, 500);
|
||||
|
||||
@override
|
||||
Future<AppPlatformState> build() async {
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime == null || kIsWeb) {
|
||||
return _snapshot();
|
||||
}
|
||||
if (!Util.isDesktop()) {
|
||||
_scheduleInitialUpdateCheck();
|
||||
return _snapshot();
|
||||
}
|
||||
if (_started) {
|
||||
final localeConfig = runtime.downloaderConfig.extra.locale;
|
||||
if (_trayLocaleConfig != localeConfig) await _initTray();
|
||||
return _snapshot();
|
||||
}
|
||||
await _start();
|
||||
_scheduleInitialUpdateCheck();
|
||||
ref.onDispose(() {
|
||||
windowManager.removeListener(this);
|
||||
trayManager.removeListener(this);
|
||||
unawaited(HostRpcService.instance.stop());
|
||||
unawaited(AppWindowCapabilityHost.instance.stop());
|
||||
});
|
||||
return _snapshot();
|
||||
}
|
||||
|
||||
void _scheduleInitialUpdateCheck() {
|
||||
if (_updateInitialized) return;
|
||||
_updateInitialized = true;
|
||||
Timer.run(() => unawaited(_initCheckUpdate()));
|
||||
}
|
||||
|
||||
Future<void> _start() async {
|
||||
_started = true;
|
||||
await AppWindowCapabilityHost.instance.start(LocalAppCapabilities.instance.registry);
|
||||
windowManager.addListener(this);
|
||||
await windowManager.setPreventClose(true);
|
||||
if (Util.isMacos()) {
|
||||
_runAsMenubarApp = Database.instance.getRunAsMenubarApp();
|
||||
await windowManager.setSkipTaskbar(_runAsMenubarApp);
|
||||
}
|
||||
await _initTray();
|
||||
await _initHostRpc();
|
||||
unawaited(_initDesktopIntegrations());
|
||||
await _initLaunchAtStartup();
|
||||
}
|
||||
|
||||
Future<void> _initTray() async {
|
||||
final localeConfig = ref.read(appRuntimeControllerProvider).value?.downloaderConfig.extra.locale ?? '';
|
||||
final locale = appLocalizationsFor(localeConfig);
|
||||
if (Util.isWindows()) {
|
||||
await trayManager.setIcon('assets/tray_icon/icon.ico');
|
||||
} else if (Util.isMacos()) {
|
||||
await trayManager.setIcon('assets/tray_icon/icon_mac.png', isTemplate: true);
|
||||
} else if (Platform.environment.containsKey('FLATPAK_ID') || Platform.environment.containsKey('SNAP')) {
|
||||
await trayManager.setIcon('com.gopeed.Gopeed');
|
||||
} else {
|
||||
await trayManager.setIcon('assets/tray_icon/icon.png');
|
||||
}
|
||||
|
||||
final version = _safeVersionLabel(locale.version);
|
||||
final menu = Menu(
|
||||
items: [
|
||||
MenuItem(label: locale.show, onClick: (_) => _showMainWindow()),
|
||||
MenuItem.separator(),
|
||||
MenuItem(label: locale.create, onClick: (_) => _openCreateTask()),
|
||||
MenuItem(
|
||||
label: locale.startAll,
|
||||
onClick: (_) => unawaited(ref.read(gopeedServiceProvider).continueAllTasks(null)),
|
||||
),
|
||||
MenuItem(
|
||||
label: locale.pauseAll,
|
||||
onClick: (_) => unawaited(ref.read(gopeedServiceProvider).pauseAllTasks(null)),
|
||||
),
|
||||
MenuItem(label: locale.setting, onClick: (_) => _go('/settings')),
|
||||
MenuItem.separator(),
|
||||
MenuItem(
|
||||
label: locale.donate,
|
||||
onClick: (_) => unawaited(launchUrl(Uri.parse('https://gopeed.com/docs/donate'))),
|
||||
),
|
||||
MenuItem(label: version),
|
||||
MenuItem.separator(),
|
||||
MenuItem(label: locale.exit, onClick: (_) => _exit()),
|
||||
],
|
||||
);
|
||||
|
||||
if (!Util.isLinux()) {
|
||||
await trayManager.setToolTip('Gopeed');
|
||||
}
|
||||
await trayManager.setContextMenu(menu);
|
||||
trayManager.removeListener(this);
|
||||
trayManager.addListener(this);
|
||||
_trayLocaleConfig = localeConfig;
|
||||
}
|
||||
|
||||
Future<void> _initHostRpc() async {
|
||||
await HostRpcService.instance.start(
|
||||
onCreate: (createTask, silent) async {
|
||||
final pendingUpdate = ref.read(pendingUpdateTaskProvider);
|
||||
if (pendingUpdate != null && createTask.req != null) {
|
||||
ref
|
||||
.read(pendingUpdateRequestProvider.notifier)
|
||||
.set(PendingUpdateRequest(task: pendingUpdate, createTask: createTask));
|
||||
await _showMainWindow();
|
||||
return;
|
||||
}
|
||||
if (silent) {
|
||||
await ref.read(gopeedServiceProvider).createTask(createTask);
|
||||
return;
|
||||
}
|
||||
final opened = await AppWindowLauncher.openCreateTaskWindow(createTask: createTask);
|
||||
if (!opened) {
|
||||
ref.read(pendingCreateTaskProvider.notifier).set(createTask);
|
||||
await _go('/create');
|
||||
}
|
||||
},
|
||||
onForward: ({required path, required method, data, query}) {
|
||||
return api.forward(path, method: method, data: data, queryParameters: query);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _initDesktopIntegrations() async {
|
||||
try {
|
||||
registerUrlScheme('gopeed');
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
if (runtime?.downloaderConfig.extra.defaultBtClient == true) {
|
||||
registerDefaultTorrentClient();
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('register scheme failed', error, stackTrace);
|
||||
}
|
||||
|
||||
try {
|
||||
await installHost();
|
||||
for (final browser in Browser.values) {
|
||||
await installManifest(browser);
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('browser extension host integration failed', error, stackTrace);
|
||||
}
|
||||
|
||||
try {
|
||||
await installUpdater();
|
||||
} catch (error, stackTrace) {
|
||||
// Native helper assets are generated by release builds, so their absence
|
||||
// in a source/debug bundle must not prevent the app from starting.
|
||||
logger.w('updater integration failed', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _initLaunchAtStartup() async {
|
||||
if (!Util.isWindows() && !Util.isLinux()) {
|
||||
return;
|
||||
}
|
||||
launchAtStartup.setup(appName: packageInfo.appName, appPath: Platform.resolvedExecutable, args: const ['--hidden']);
|
||||
_launchAtStartup = await launchAtStartup.isEnabled();
|
||||
}
|
||||
|
||||
Future<void> setLaunchAtStartup(bool enabled) async {
|
||||
if (!Util.isWindows() && !Util.isLinux()) {
|
||||
return;
|
||||
}
|
||||
if (enabled) {
|
||||
await launchAtStartup.enable();
|
||||
} else {
|
||||
await launchAtStartup.disable();
|
||||
}
|
||||
_launchAtStartup = enabled;
|
||||
_emit();
|
||||
}
|
||||
|
||||
Future<void> setRunAsMenubarApp(bool enabled) async {
|
||||
if (!Util.isMacos()) {
|
||||
return;
|
||||
}
|
||||
Database.instance.saveRunAsMenubarApp(enabled);
|
||||
_runAsMenubarApp = enabled;
|
||||
await windowManager.setSkipTaskbar(enabled);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await _showMainWindow();
|
||||
_emit();
|
||||
}
|
||||
|
||||
Future<void> _initCheckUpdate() async {
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
if (runtime?.downloaderConfig.extra.notifyWhenNewVersion == false) return;
|
||||
await checkForUpdate();
|
||||
}
|
||||
|
||||
Future<VersionInfo?> checkForUpdate() {
|
||||
return _checkUpdateFuture ??= _performUpdateCheck().whenComplete(() => _checkUpdateFuture = null);
|
||||
}
|
||||
|
||||
Future<VersionInfo?> _performUpdateCheck() async {
|
||||
_updateStatus = AppUpdateStatus.checking;
|
||||
_updateError = null;
|
||||
_emit();
|
||||
try {
|
||||
_latestVersion = await checkUpdate();
|
||||
_updateStatus = _latestVersion == null ? AppUpdateStatus.upToDate : AppUpdateStatus.available;
|
||||
_emit();
|
||||
return _latestVersion;
|
||||
} catch (error, stackTrace) {
|
||||
_latestVersion = null;
|
||||
_updateStatus = AppUpdateStatus.failed;
|
||||
_updateError = error.toString();
|
||||
_emit();
|
||||
logger.w('check update failed', error, stackTrace);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> startUpdate(VersionInfo versionInfo, UpdateProgressCallback onProgress) async {
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
await updateApp(
|
||||
versionInfo,
|
||||
githubMirror: runtime?.downloaderConfig.extra.githubMirror ?? ExtraConfigGithubMirror(enabled: false),
|
||||
onProgress: onProgress,
|
||||
);
|
||||
}
|
||||
|
||||
AppPlatformState _snapshot() => AppPlatformState(
|
||||
started: _started,
|
||||
launchAtStartup: _launchAtStartup,
|
||||
runAsMenubarApp: _runAsMenubarApp,
|
||||
updateStatus: _updateStatus,
|
||||
latestVersion: _latestVersion,
|
||||
updateError: _updateError,
|
||||
);
|
||||
|
||||
void _emit() {
|
||||
state = AsyncValue.data(_snapshot());
|
||||
}
|
||||
|
||||
String _safeVersionLabel(String label) {
|
||||
try {
|
||||
return '$label($appVersion)';
|
||||
} catch (_) {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showMainWindow() async {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
}
|
||||
|
||||
Future<void> _openCreateTask() async {
|
||||
await _showMainWindow();
|
||||
final opened = await AppWindowLauncher.openCreateTaskWindow();
|
||||
if (!opened) {
|
||||
_go('/create');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _go(String route) async {
|
||||
final context = AppRouter.rootNavigatorKey.currentContext;
|
||||
await _showMainWindow();
|
||||
if (context != null && context.mounted) {
|
||||
context.go(route);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exit() async {
|
||||
try {
|
||||
await HostRpcService.instance.stop();
|
||||
await AppWindowCapabilityHost.instance.stop();
|
||||
await LibgopeedBoot.instance.stop();
|
||||
} catch (_) {}
|
||||
await windowManager.destroy();
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowClose() async {
|
||||
final isPreventClose = await windowManager.isPreventClose();
|
||||
if (isPreventClose) {
|
||||
await windowManager.hide();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowFocus() {
|
||||
if (Util.isMacos() && _runAsMenubarApp) {
|
||||
unawaited(windowManager.setSkipTaskbar(true));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconMouseDown() {
|
||||
unawaited(_showMainWindow());
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconRightMouseDown() {
|
||||
trayManager.popUpContextMenu();
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowMaximize() {
|
||||
Database.instance.saveWindowState(WindowStateEntity(isMaximized: true));
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowUnmaximize() {
|
||||
Database.instance.saveWindowState(WindowStateEntity(isMaximized: false));
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowResize() {
|
||||
_windowsResizeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../core/capabilities/app_capabilities.dart';
|
||||
import '../../core/common/start_config.dart';
|
||||
import '../../core/entry/app_initializer.dart';
|
||||
import '../../core/libgopeed_boot.dart';
|
||||
import '../../database/database.dart';
|
||||
import '../../database/entity.dart';
|
||||
import '../../features/auth/application/web_auth_controller.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../../util/package_info.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../rpc/webview_rpc_service.dart';
|
||||
import 'android_foreground_service.dart';
|
||||
import 'location_keep_alive.dart';
|
||||
|
||||
const unixSocketPath = 'gopeed.sock';
|
||||
|
||||
final appRuntimeControllerProvider = AsyncNotifierProvider<AppRuntimeController, AppRuntimeState>(
|
||||
AppRuntimeController.new,
|
||||
);
|
||||
|
||||
class AppRuntimeState {
|
||||
const AppRuntimeState({
|
||||
required this.startConfig,
|
||||
required this.runningPort,
|
||||
required this.downloaderConfig,
|
||||
this.localBackendStarted = false,
|
||||
this.startupError,
|
||||
});
|
||||
|
||||
final StartConfig startConfig;
|
||||
final int runningPort;
|
||||
final DownloaderConfig downloaderConfig;
|
||||
final bool localBackendStarted;
|
||||
final Object? startupError;
|
||||
|
||||
String runningAddress() {
|
||||
if (startConfig.network == 'unix') {
|
||||
return startConfig.address;
|
||||
}
|
||||
return '${startConfig.address.split(':').first}:$runningPort';
|
||||
}
|
||||
}
|
||||
|
||||
class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
|
||||
static StartConfig? _defaultStartConfig;
|
||||
|
||||
@override
|
||||
Future<AppRuntimeState> build() async {
|
||||
ref.onDispose(() => unawaited(WebViewRpcService.instance.stop()));
|
||||
return _init();
|
||||
}
|
||||
|
||||
Future<void> reloadConfig() async {
|
||||
final current = state.value;
|
||||
if (current == null) return;
|
||||
state = AsyncValue.data(
|
||||
AppRuntimeState(
|
||||
startConfig: current.startConfig,
|
||||
runningPort: current.runningPort,
|
||||
downloaderConfig: await ref.read(gopeedServiceProvider).getConfig(),
|
||||
localBackendStarted: current.localBackendStarted,
|
||||
startupError: current.startupError,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void replaceDownloaderConfig(DownloaderConfig config) {
|
||||
final current = state.value;
|
||||
if (current == null) return;
|
||||
state = AsyncValue.data(
|
||||
AppRuntimeState(
|
||||
startConfig: current.startConfig,
|
||||
runningPort: current.runningPort,
|
||||
downloaderConfig: DownloaderConfig.fromJson(config.toJson()),
|
||||
localBackendStarted: current.localBackendStarted,
|
||||
startupError: current.startupError,
|
||||
),
|
||||
);
|
||||
unawaited(LocationKeepAliveCoordinator.instance.reconcile(enabled: config.extra.backgroundLocationKeepAlive));
|
||||
}
|
||||
|
||||
Future<AppRuntimeState> _init() async {
|
||||
await AppInitializer.ensureDatabaseInitialized();
|
||||
try {
|
||||
await initPackageInfo();
|
||||
} catch (_) {}
|
||||
initLogger();
|
||||
|
||||
final startConfig = await _loadStartConfig();
|
||||
try {
|
||||
startConfig.webViewRpcConfig = await WebViewRpcService.instance.start();
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('webview RPC initialization failed', error, stackTrace);
|
||||
}
|
||||
Object? startupError;
|
||||
var runningPort = 0;
|
||||
var localBackendStarted = false;
|
||||
try {
|
||||
// Go's rest.Start is already idempotent: when its server is running it
|
||||
// returns the existing port before rebuilding or touching the Unix
|
||||
// socket. This is also what keeps Riverpod hot reload safe.
|
||||
runningPort = await LibgopeedBoot.instance.start(startConfig);
|
||||
localBackendStarted = true;
|
||||
} catch (error, stackTrace) {
|
||||
startupError = error;
|
||||
logger.w('libgopeed init failed, falling back to external API', error, stackTrace);
|
||||
if (startConfig.network == 'unix') {
|
||||
startConfig.network = 'tcp';
|
||||
startConfig.address = '127.0.0.1:9999';
|
||||
}
|
||||
runningPort = int.tryParse(startConfig.address.split(':').last) ?? 9999;
|
||||
}
|
||||
|
||||
api.init(
|
||||
startConfig.network,
|
||||
_runningAddress(startConfig, runningPort),
|
||||
startConfig.apiToken,
|
||||
onUnauthorized: ref.read(webAuthControllerProvider).requireLogin,
|
||||
);
|
||||
|
||||
final config = await _loadDownloaderConfig();
|
||||
unawaited(_initTrackerUpdate(config));
|
||||
unawaited(_initAndroidForegroundService(appLocalizationsFor(config.extra.locale)));
|
||||
|
||||
final result = AppRuntimeState(
|
||||
startConfig: startConfig,
|
||||
runningPort: runningPort,
|
||||
downloaderConfig: config,
|
||||
localBackendStarted: localBackendStarted,
|
||||
startupError: startupError,
|
||||
);
|
||||
if (Util.isIOS()) {
|
||||
LocationKeepAliveCoordinator.instance.start(
|
||||
() =>
|
||||
state.value?.downloaderConfig.extra.backgroundLocationKeepAlive ?? config.extra.backgroundLocationKeepAlive,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> _initAndroidForegroundService(AppLocalizations l10n) async {
|
||||
try {
|
||||
await AndroidForegroundService.ensureRunning(l10n);
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('Android foreground service initialization failed', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<StartConfig> _loadStartConfig() async {
|
||||
final defaultCfg = await _initDefaultStartConfig();
|
||||
final saved = Database.instance.getStartConfig();
|
||||
final cfg = StartConfig()
|
||||
..network = saved?.network ?? defaultCfg.network
|
||||
..address = saved?.address ?? defaultCfg.address
|
||||
..apiToken = saved?.apiToken ?? defaultCfg.apiToken
|
||||
..storage = defaultCfg.storage
|
||||
..storageDir = defaultCfg.storageDir
|
||||
..refreshInterval = defaultCfg.refreshInterval;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
Future<StartConfig> _initDefaultStartConfig() async {
|
||||
if (_defaultStartConfig != null) {
|
||||
return _defaultStartConfig!;
|
||||
}
|
||||
final cfg = StartConfig()
|
||||
..storage = 'bolt'
|
||||
..storageDir = Util.getStorageDir()
|
||||
..refreshInterval = 0
|
||||
..apiToken = '';
|
||||
if (!Util.supportUnixSocket()) {
|
||||
cfg
|
||||
..network = 'tcp'
|
||||
..address = '127.0.0.1:0';
|
||||
} else {
|
||||
cfg
|
||||
..network = 'unix'
|
||||
..address = '${(await getTemporaryDirectory()).path}/$unixSocketPath';
|
||||
}
|
||||
_defaultStartConfig = cfg;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
Future<DownloaderConfig> _loadDownloaderConfig() async {
|
||||
DownloaderConfig config;
|
||||
try {
|
||||
config = await ref.read(gopeedServiceProvider).getConfig();
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('load downloader config failed', error, stackTrace);
|
||||
config = DownloaderConfig();
|
||||
}
|
||||
await _initDownloaderConfig(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
Future<void> _initDownloaderConfig(DownloaderConfig config) async {
|
||||
final extra = config.extra;
|
||||
if (extra.themeMode.isEmpty) {
|
||||
extra.themeMode = 'system';
|
||||
}
|
||||
if (extra.themeColor.isEmpty) {
|
||||
extra.themeColor = 'green';
|
||||
}
|
||||
if (extra.bt.trackerSubscribeUrls.isEmpty) {
|
||||
extra.bt.trackerSubscribeUrls.addAll(allTrackerSubscribeUrls);
|
||||
}
|
||||
if (config.proxy.scheme.isEmpty) {
|
||||
config.proxy.scheme = 'http';
|
||||
}
|
||||
if (config.downloadDir.isEmpty) {
|
||||
config.downloadDir = await _defaultDownloadDir();
|
||||
}
|
||||
if (extra.downloadCategories.isEmpty) {
|
||||
extra.downloadCategories = [
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Music'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryMusic',
|
||||
),
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Video'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryVideo',
|
||||
),
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Document'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryDocument',
|
||||
),
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Program'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryProgram',
|
||||
),
|
||||
];
|
||||
}
|
||||
if (extra.githubMirror.mirrors.isEmpty) {
|
||||
extra.githubMirror.mirrors = [
|
||||
GithubMirror(type: GithubMirrorType.jsdelivr, url: 'https://fastly.jsdelivr.net/gh', isBuiltIn: true),
|
||||
GithubMirror(type: GithubMirrorType.ghProxy, url: 'https://fastgit.cc', isBuiltIn: true),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _initTrackerUpdate(DownloaderConfig config) async {
|
||||
final btExtra = config.extra.bt;
|
||||
final lastUpdateTime = btExtra.lastTrackerUpdateTime;
|
||||
if (!btExtra.autoUpdateTrackers ||
|
||||
(lastUpdateTime != null && !lastUpdateTime.isBefore(DateTime.now().subtract(const Duration(days: 1))))) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateTrackers(config);
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('tracker update failed', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateTrackers(DownloaderConfig config) async {
|
||||
final btExtra = config.extra.bt;
|
||||
final trackers = <String>[];
|
||||
for (final url in btExtra.trackerSubscribeUrls) {
|
||||
final resp = await api.proxyRequest(url);
|
||||
final data = resp.data;
|
||||
if (resp.statusCode == 200 && data != null && data.isNotEmpty) {
|
||||
trackers.addAll(const LineSplitter().convert(data).where((line) => line.trim().isNotEmpty));
|
||||
}
|
||||
}
|
||||
btExtra.subscribeTrackers = trackers;
|
||||
btExtra.lastTrackerUpdateTime = DateTime.now();
|
||||
config.protocolConfig.bt.trackers = {...btExtra.subscribeTrackers, ...btExtra.customTrackers}.toList();
|
||||
await ref.read(gopeedServiceProvider).putConfig(config);
|
||||
|
||||
final current = state.value;
|
||||
if (current != null) {
|
||||
state = AsyncValue.data(
|
||||
AppRuntimeState(
|
||||
startConfig: current.startConfig,
|
||||
runningPort: current.runningPort,
|
||||
downloaderConfig: config,
|
||||
localBackendStarted: current.localBackendStarted,
|
||||
startupError: current.startupError,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _defaultDownloadDir() async {
|
||||
if (kIsWeb) {
|
||||
return './';
|
||||
}
|
||||
if (Util.isDesktop()) {
|
||||
return (await getDownloadsDirectory())?.path ?? './';
|
||||
}
|
||||
if (Util.isAndroid()) {
|
||||
return (await getExternalStorageDirectory())?.path ?? (await getApplicationDocumentsDirectory()).path;
|
||||
}
|
||||
if (Util.isIOS()) {
|
||||
return (await getApplicationDocumentsDirectory()).path;
|
||||
}
|
||||
return './';
|
||||
}
|
||||
|
||||
String _runningAddress(StartConfig config, int runningPort) {
|
||||
if (config.network == 'unix') {
|
||||
return config.address;
|
||||
}
|
||||
return '${config.address.split(':').first}:$runningPort';
|
||||
}
|
||||
|
||||
Future<void> saveStartConfig(StartConfig config) async {
|
||||
Database.instance.saveStartConfig(
|
||||
StartConfigEntity(network: config.network, address: config.address, apiToken: config.apiToken),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const allTrackerSubscribeUrls = [
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_http.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_https.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_ip.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_udp.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_ws.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best_ip.txt',
|
||||
'https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/all.txt',
|
||||
'https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/best.txt',
|
||||
'https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/http.txt',
|
||||
];
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
class LocaleController extends ChangeNotifier {
|
||||
Locale _locale = const Locale('en');
|
||||
|
||||
Locale get locale => _locale;
|
||||
|
||||
void setLocale(Locale locale) {
|
||||
if (_locale == locale) return;
|
||||
_locale = locale;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/task.dart';
|
||||
|
||||
class LocationKeepAlive {
|
||||
const LocationKeepAlive._();
|
||||
|
||||
static const _channel = MethodChannel('gopeed/location_keep_alive');
|
||||
|
||||
static Future<bool> requestPermission() async {
|
||||
if (!Platform.isIOS) return false;
|
||||
try {
|
||||
return await _channel.invokeMethod<bool>('requestPermission') ?? false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> start() async {
|
||||
if (Platform.isIOS) await _channel.invokeMethod<void>('start');
|
||||
}
|
||||
|
||||
static Future<void> stop() async {
|
||||
if (Platform.isIOS) await _channel.invokeMethod<void>('stop');
|
||||
}
|
||||
}
|
||||
|
||||
class LocationKeepAliveCoordinator {
|
||||
LocationKeepAliveCoordinator._();
|
||||
|
||||
static final instance = LocationKeepAliveCoordinator._();
|
||||
|
||||
Timer? _timer;
|
||||
bool Function()? _enabled;
|
||||
bool _reconciling = false;
|
||||
|
||||
void start(bool Function() enabled) {
|
||||
if (!Platform.isIOS) return;
|
||||
_enabled = enabled;
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 10), (_) => unawaited(reconcile()));
|
||||
unawaited(reconcile());
|
||||
}
|
||||
|
||||
Future<void> reconcile({bool? enabled}) async {
|
||||
if (!Platform.isIOS || _reconciling) return;
|
||||
_reconciling = true;
|
||||
try {
|
||||
if (!(enabled ?? _enabled?.call() ?? false)) {
|
||||
await LocationKeepAlive.stop();
|
||||
return;
|
||||
}
|
||||
final running = await api.getTasks([Status.running]);
|
||||
running.isEmpty ? await LocationKeepAlive.stop() : await LocationKeepAlive.start();
|
||||
} catch (_) {
|
||||
// Keep the current native state when task status cannot be queried.
|
||||
} finally {
|
||||
_reconciling = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user