mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-19 06:43: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,104 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
||||
|
||||
import '../core/window/app_window_frame.dart';
|
||||
import '../core/window/app_window_appearance.dart';
|
||||
import '../core/window/window_capability_transport.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../shared/theme/app_component_themes.dart';
|
||||
import '../shared/theme/app_theme.dart';
|
||||
import '../features/auth/application/web_auth_controller.dart';
|
||||
import 'application/app_appearance_controller.dart';
|
||||
import 'application/app_runtime_controller.dart';
|
||||
import 'rpc/webview_rpc_overlay.dart';
|
||||
import 'rpc/webview_rpc_service.dart';
|
||||
import 'router/app_router.dart';
|
||||
|
||||
class GopeedApp extends ConsumerStatefulWidget {
|
||||
const GopeedApp({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<GopeedApp> createState() => _GopeedAppState();
|
||||
}
|
||||
|
||||
class _GopeedAppState extends ConsumerState<GopeedApp> with WidgetsBindingObserver {
|
||||
late final GoRouter _router;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_router = AppRouter.build(ref.read(webAuthControllerProvider));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_router.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangePlatformBrightness() {
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.listen(appRuntimeControllerProvider, (_, next) {
|
||||
final runtime = next.value;
|
||||
if (runtime != null) {
|
||||
ref.read(appAppearanceControllerProvider.notifier).initialize(runtime.downloaderConfig.extra);
|
||||
}
|
||||
});
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ref.read(appAppearanceControllerProvider.notifier).initialize(runtime.downloaderConfig.extra);
|
||||
});
|
||||
}
|
||||
|
||||
final appearance = ref.watch(appAppearanceControllerProvider);
|
||||
final themeColor = appearance.themeColor;
|
||||
final isLightTheme = appearance.resolveIsLight(WidgetsBinding.instance.platformDispatcher.platformBrightness);
|
||||
final themeMode = switch (appearance.themeMode) {
|
||||
AppThemeMode.system => shad.ThemeMode.system,
|
||||
AppThemeMode.light => shad.ThemeMode.light,
|
||||
AppThemeMode.dark => shad.ThemeMode.dark,
|
||||
};
|
||||
AppWindowCapabilityHost.instance.updateAppearance(
|
||||
AppWindowAppearance(
|
||||
themeMode: appearance.themeMode.key,
|
||||
themeColor: appearance.themeColor.key,
|
||||
locale: runtime?.downloaderConfig.extra.locale ?? '',
|
||||
),
|
||||
);
|
||||
|
||||
return shad.ShadcnApp.router(
|
||||
debugShowCheckedModeBanner: false,
|
||||
onGenerateTitle: (context) => context.l10n.appTitle,
|
||||
theme: AppTheme.light(themeColor),
|
||||
darkTheme: AppTheme.dark(themeColor),
|
||||
materialTheme: isLightTheme ? AppTheme.materialLight(themeColor) : AppTheme.materialDark(themeColor),
|
||||
themeMode: themeMode,
|
||||
locale: supportedLocaleFromConfig(runtime?.downloaderConfig.extra.locale ?? ''),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
builder: (context, child) {
|
||||
final content = AppComponentThemes(child: AppWindowFrame(child: child ?? const SizedBox.shrink()));
|
||||
if (!WebViewRpcService.instance.supported) {
|
||||
return content;
|
||||
}
|
||||
return Overlay(
|
||||
initialEntries: [
|
||||
OverlayEntry(builder: (_) => content),
|
||||
OverlayEntry(builder: (_) => const WebViewRpcOverlay()),
|
||||
],
|
||||
);
|
||||
},
|
||||
routerConfig: _router,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
||||
|
||||
import '../api/model/create_task.dart';
|
||||
import '../app/application/app_appearance_controller.dart';
|
||||
import '../core/window/app_window_bootstrap.dart';
|
||||
import '../core/window/app_window_frame.dart';
|
||||
import '../core/window/app_window_payload.dart';
|
||||
import '../core/window/window_capability_transport.dart';
|
||||
import '../features/tasks/presentation/pages/create_task_window_page.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../shared/theme/app_component_themes.dart';
|
||||
import '../shared/theme/app_theme.dart';
|
||||
import '../shared/theme/app_theme_color.dart';
|
||||
|
||||
class ChildWindowApp extends StatefulWidget {
|
||||
const ChildWindowApp({super.key, required this.payload, required this.session});
|
||||
|
||||
final AppWindowPayload payload;
|
||||
final ChildWindowSession session;
|
||||
|
||||
@override
|
||||
State<ChildWindowApp> createState() => _ChildWindowAppState();
|
||||
}
|
||||
|
||||
class _ChildWindowAppState extends State<ChildWindowApp> with WidgetsBindingObserver {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
widget.session.appearance.addListener(_appearanceChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
widget.session.appearance.removeListener(_appearanceChanged);
|
||||
widget.session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangePlatformBrightness() {
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
void _appearanceChanged() {
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appearance = widget.session.appearance.value;
|
||||
final themeColor = AppThemeColor.fromKey(appearance.themeColor);
|
||||
final themeMode = AppThemeMode.fromKey(appearance.themeMode);
|
||||
final isLightTheme = switch (themeMode) {
|
||||
AppThemeMode.system => WidgetsBinding.instance.platformDispatcher.platformBrightness == Brightness.light,
|
||||
AppThemeMode.light => true,
|
||||
AppThemeMode.dark => false,
|
||||
};
|
||||
final shadThemeMode = switch (themeMode) {
|
||||
AppThemeMode.system => shad.ThemeMode.system,
|
||||
AppThemeMode.light => shad.ThemeMode.light,
|
||||
AppThemeMode.dark => shad.ThemeMode.dark,
|
||||
};
|
||||
final locale = supportedLocaleFromConfig(appearance.locale);
|
||||
|
||||
return shad.ShadcnApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
onGenerateTitle: (context) => AppWindowBootstrap.subWindowTitle(widget.payload.type, context.l10n),
|
||||
theme: AppTheme.light(themeColor),
|
||||
darkTheme: AppTheme.dark(themeColor),
|
||||
materialTheme: isLightTheme ? AppTheme.materialLight(themeColor) : AppTheme.materialDark(themeColor),
|
||||
themeMode: shadThemeMode,
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
builder: (context, child) => AppComponentThemes(child: child ?? const SizedBox.shrink()),
|
||||
home: AppWindowFrame(child: Builder(builder: _buildPage)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPage(BuildContext context) {
|
||||
return switch (widget.payload.type) {
|
||||
AppWindowType.createTask => CreateTaskWindowPage(
|
||||
windowController: widget.session.controller,
|
||||
initialTask: widget.payload.createTask == null ? null : CreateTask.fromJson(widget.payload.createTask!),
|
||||
),
|
||||
_ => shad.Scaffold(child: Center(child: Text(context.l10n.unsupportedWindowPayload))),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/app_controller.dart';
|
||||
|
||||
class AppBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<AppController>(
|
||||
() => AppController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,62 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:window_manager/window_manager.dart'; // Import the required packages
|
||||
|
||||
import '../../../../i18n/message.dart';
|
||||
import '../../../../theme/theme.dart';
|
||||
import '../../../../util/locale_manager.dart';
|
||||
import '../../../../util/util.dart'; // Import the required packages
|
||||
import '../../../rpc/webview_rpc_overlay.dart';
|
||||
import '../../../rpc/webview_rpc_service.dart';
|
||||
import '../../../routes/app_pages.dart';
|
||||
import '../controllers/app_controller.dart';
|
||||
|
||||
class AppView extends GetView<AppController> {
|
||||
const AppView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final config = controller.downloaderConfig.value;
|
||||
return WithForegroundTask(
|
||||
child: GetMaterialApp.router(
|
||||
useInheritedMediaQuery: true,
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: GopeedTheme.light,
|
||||
darkTheme: GopeedTheme.dark,
|
||||
themeMode: ThemeMode.values.byName(config.extra.themeMode),
|
||||
translations: messages,
|
||||
locale: toLocale(config.extra.locale),
|
||||
fallbackLocale: fallbackLocale,
|
||||
localizationsDelegates: const [
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: messages.keys.keys.map((e) => toLocale(e)).toList(),
|
||||
getPages: AppPages.routes,
|
||||
|
||||
// Add listening to theme changes, set the title bar color according to the current system theme.
|
||||
builder: (context, child) {
|
||||
// if platform is desktop
|
||||
if (Util.isDesktop()) {
|
||||
// actual brightness of the UI
|
||||
Brightness brightness = Theme.of(context).brightness;
|
||||
// Set the title bar to use the actual brightness of the UI
|
||||
windowManager.setBrightness(brightness);
|
||||
}
|
||||
// Fix for GetX Overlay issue with Flutter 3.38.1+
|
||||
// Reference: https://github.com/jonataslaw/getx/issues/3425
|
||||
final entries = <OverlayEntry>[
|
||||
OverlayEntry(builder: (_) => child!),
|
||||
];
|
||||
if (WebViewRpcService.instance.supported) {
|
||||
entries.add(OverlayEntry(builder: (_) => const WebViewRpcOverlay()));
|
||||
}
|
||||
return Overlay(initialEntries: entries);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/create_controller.dart';
|
||||
|
||||
class CreateBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<CreateController>(
|
||||
() => CreateController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/model/request.dart';
|
||||
|
||||
import '../../app/controllers/app_controller.dart';
|
||||
|
||||
class CreateController extends GetxController
|
||||
with GetSingleTickerProviderStateMixin {
|
||||
final RxList fileInfos = [].obs;
|
||||
final RxList openedFolders = [].obs;
|
||||
final selectedIndexes = <int>[].obs;
|
||||
final isConfirming = false.obs;
|
||||
final showAdvanced = false.obs;
|
||||
final directDownload = false.obs;
|
||||
final proxyConfig = Rx<RequestProxy?>(null);
|
||||
late TabController advancedTabController;
|
||||
final oldUrl = "".obs;
|
||||
final fileDataUri = "".obs;
|
||||
|
||||
/// Flag to prevent handling pending create task from deep link multiple times
|
||||
bool pendingCreateHandled = false;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
advancedTabController = TabController(length: 2, vsync: this);
|
||||
directDownload.value = Get.find<AppController>()
|
||||
.downloaderConfig
|
||||
.value
|
||||
.extra
|
||||
.defaultDirectDownload;
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
advancedTabController.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
void setFileDataUri(Uint8List bytes) {
|
||||
fileDataUri.value =
|
||||
"data:application/x-bittorrent;base64,${base64.encode(bytes)}";
|
||||
}
|
||||
|
||||
void clearFileDataUri() {
|
||||
fileDataUri.value = "";
|
||||
}
|
||||
}
|
||||
@@ -1,299 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
import '../../../../api/api.dart';
|
||||
import '../../../../api/model/create_task.dart';
|
||||
import '../../../../api/model/create_task_batch.dart';
|
||||
import '../../../../api/model/options.dart';
|
||||
import '../../../../api/model/resolve_result.dart';
|
||||
import '../../../../api/model/resolve_task.dart';
|
||||
import '../../../../util/message.dart';
|
||||
import '../../../views/directory_selector.dart';
|
||||
import '../../app/controllers/app_controller.dart';
|
||||
|
||||
class CreateDialogView extends StatefulWidget {
|
||||
const CreateDialogView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<CreateDialogView> createState() => _CreateDialogViewState();
|
||||
}
|
||||
|
||||
class _CreateDialogViewState extends State<CreateDialogView> {
|
||||
final _pathController = TextEditingController();
|
||||
final _nameController = TextEditingController();
|
||||
|
||||
CreateTask? _createTask;
|
||||
ResolveResult? _resolveResult;
|
||||
Object? _error;
|
||||
bool _resolving = true;
|
||||
bool _creating = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final appController = Get.find<AppController>();
|
||||
_pathController.text = renderPathPlaceholders(
|
||||
appController.downloaderConfig.value.downloadDir,
|
||||
);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _loadArguments());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pathController.dispose();
|
||||
_nameController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadArguments() async {
|
||||
final args = Get.rootDelegate.arguments();
|
||||
if (args is! CreateTask || args.req?.url.isNotEmpty != true) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_resolving = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
_createTask = args;
|
||||
if (args.opts?.path.isNotEmpty == true) {
|
||||
_pathController.text = args.opts!.path;
|
||||
}
|
||||
if (args.opts?.name.isNotEmpty == true) {
|
||||
_nameController.text = args.opts!.name;
|
||||
} else {
|
||||
_nameController.text = _fallbackName(args.req!.url);
|
||||
}
|
||||
|
||||
await _resolve(args);
|
||||
}
|
||||
|
||||
Future<void> _resolve(CreateTask createTask) async {
|
||||
setState(() {
|
||||
_resolving = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final opt = Options(
|
||||
name: createTask.opts?.name ?? '',
|
||||
path: _pathController.text,
|
||||
selectFiles: const [],
|
||||
extra: _optsExtra(),
|
||||
);
|
||||
final result = await resolve(
|
||||
ResolveTask(req: createTask.req!, opts: opt),
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_resolveResult = result;
|
||||
if (_nameController.text.trim().isEmpty ||
|
||||
_nameController.text == _fallbackName(createTask.req!.url)) {
|
||||
_nameController.text = _resolvedName(result, createTask.req!.url);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e;
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_resolving = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _confirm() async {
|
||||
final createTaskParams = _createTask;
|
||||
if (createTaskParams?.req == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_creating = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final rr = _resolveResult;
|
||||
final optExtra = _optsExtra();
|
||||
if (rr == null) {
|
||||
await createTask(
|
||||
CreateTask(
|
||||
req: createTaskParams!.req,
|
||||
opts: Options(
|
||||
name: _nameController.text.trim(),
|
||||
path: _pathController.text,
|
||||
selectFiles: const [],
|
||||
extra: optExtra,
|
||||
),
|
||||
),
|
||||
);
|
||||
} else if (rr.id.isEmpty) {
|
||||
final reqs = rr.res.files.map((file) {
|
||||
return CreateTaskBatchItem(
|
||||
req: file.req ?? createTaskParams!.req,
|
||||
opts: Options(
|
||||
name: file.name,
|
||||
path: path.join(_pathController.text, rr.res.name, file.path),
|
||||
selectFiles: const [],
|
||||
extra: optExtra,
|
||||
),
|
||||
);
|
||||
}).toList();
|
||||
await createTaskBatch(CreateTaskBatch(reqs: reqs));
|
||||
} else {
|
||||
await createTask(
|
||||
CreateTask(
|
||||
rid: rr.id,
|
||||
opts: Options(
|
||||
name: _nameController.text.trim(),
|
||||
path: _pathController.text,
|
||||
selectFiles: rr.res.files.asMap().keys.toList(),
|
||||
extra: optExtra,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
await SystemNavigator.pop();
|
||||
} catch (e) {
|
||||
showErrorMessage(e);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_creating = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Object _optsExtra() {
|
||||
final httpConfig =
|
||||
Get.find<AppController>().downloaderConfig.value.protocolConfig.http;
|
||||
return OptsExtraHttp(connections: httpConfig.connections);
|
||||
}
|
||||
|
||||
String _resolvedName(ResolveResult result, String url) {
|
||||
if (result.res.name.trim().isNotEmpty) {
|
||||
return result.res.name;
|
||||
}
|
||||
if (result.res.files.length == 1) {
|
||||
return result.res.files.first.name;
|
||||
}
|
||||
return _fallbackName(url);
|
||||
}
|
||||
|
||||
String _fallbackName(String url) {
|
||||
final uri = Uri.tryParse(url);
|
||||
final uriName = uri == null ? '' : path.basename(uri.path);
|
||||
if (uriName.isNotEmpty && uriName != '.') {
|
||||
return uriName;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: Material(
|
||||
color: theme.colorScheme.surface,
|
||||
elevation: 16,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 420),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'create'.tr,
|
||||
style: theme.textTheme.titleMedium,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: _creating ? null : SystemNavigator.pop,
|
||||
tooltip: 'cancel'.tr,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (_resolving)
|
||||
const LinearProgressIndicator(minHeight: 2)
|
||||
else
|
||||
const SizedBox(height: 2),
|
||||
const SizedBox(height: 14),
|
||||
TextField(
|
||||
controller: _nameController,
|
||||
enabled: !_creating,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'rename'.tr,
|
||||
prefixIcon: const Icon(Icons.insert_drive_file),
|
||||
),
|
||||
maxLines: 1,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DirectorySelector(
|
||||
controller: _pathController,
|
||||
showAndoirdToggle: true,
|
||||
allowEdit: true,
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_error.toString(),
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 18),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: _creating ? null : SystemNavigator.pop,
|
||||
child: Text('cancel'.tr),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton(
|
||||
onPressed:
|
||||
(_resolving || _creating) ? null : _confirm,
|
||||
child: _creating
|
||||
? const SizedBox.square(
|
||||
dimension: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: Text('download'.tr),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/extension_controller.dart';
|
||||
|
||||
class ExtensionBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<ExtensionController>(
|
||||
() => ExtensionController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../../api/api.dart';
|
||||
import '../../../../api/gopeed_site_api.dart';
|
||||
import '../../../../api/model/extension.dart';
|
||||
import '../../../../api/model/install_extension.dart';
|
||||
import '../../../../api/model/store_extension.dart';
|
||||
import '../../../../api/model/switch_extension.dart';
|
||||
|
||||
enum ExtensionListFilter {
|
||||
market,
|
||||
installed,
|
||||
}
|
||||
|
||||
class ExtensionListItem {
|
||||
final Extension? installed;
|
||||
final StoreExtension? store;
|
||||
|
||||
const ExtensionListItem({this.installed, this.store});
|
||||
|
||||
bool get isInstalled => installed != null;
|
||||
|
||||
String get id => installed?.identity ?? store!.id;
|
||||
|
||||
String get title => installed?.title ?? store?.title ?? '';
|
||||
|
||||
String get author => installed?.author ?? store?.author ?? '';
|
||||
|
||||
String get description => installed?.description ?? store?.description ?? '';
|
||||
|
||||
String get version => installed?.version ?? store?.version ?? '0.0.0';
|
||||
|
||||
String? get homepage {
|
||||
final installedHomepage = installed?.homepage;
|
||||
if (installedHomepage != null && installedHomepage.isNotEmpty) {
|
||||
return installedHomepage;
|
||||
}
|
||||
return store?.homepage;
|
||||
}
|
||||
|
||||
String? get repoUrl {
|
||||
final installedRepo = installed?.repository?.url;
|
||||
if (installedRepo != null && installedRepo.isNotEmpty) {
|
||||
return installedRepo;
|
||||
}
|
||||
return store?.repoUrl;
|
||||
}
|
||||
|
||||
int get stars => store?.stars ?? 0;
|
||||
|
||||
int get installCount => store?.installCount ?? 0;
|
||||
|
||||
String? get icon => store?.icon;
|
||||
}
|
||||
|
||||
class ExtensionController extends GetxController {
|
||||
static const manualInstallBusyKey = '__manual_install__';
|
||||
|
||||
final installedExtensions = <Extension>[].obs;
|
||||
final updateFlags = <String, String>{}.obs;
|
||||
|
||||
final storeExtensions = <StoreExtension>[].obs;
|
||||
final storePagination = Rxn<StorePagination>();
|
||||
final storeQuery = ''.obs;
|
||||
final storeSort = StoreExtensionSort.stars.obs;
|
||||
|
||||
final listFilter = ExtensionListFilter.market.obs;
|
||||
|
||||
final loadingInstalled = false.obs;
|
||||
final loadingStore = false.obs;
|
||||
final loadingMoreStore = false.obs;
|
||||
final busyExtensionIds = <String>{}.obs;
|
||||
final showInstallTools = false.obs;
|
||||
|
||||
final devMode = false.obs;
|
||||
var _devModeCount = 0;
|
||||
|
||||
bool pendingInstallHandled = false;
|
||||
|
||||
UnmodifiableMapView<String, Extension> get installedMap =>
|
||||
UnmodifiableMapView(
|
||||
{for (final ext in installedExtensions) ext.identity: ext});
|
||||
|
||||
UnmodifiableMapView<String, StoreExtension> get storeMap =>
|
||||
UnmodifiableMapView({for (final ext in storeExtensions) ext.id: ext});
|
||||
|
||||
List<ExtensionListItem> get displayItems {
|
||||
if (listFilter.value == ExtensionListFilter.installed) {
|
||||
return installedExtensions
|
||||
.map((ext) =>
|
||||
ExtensionListItem(installed: ext, store: storeMap[ext.identity]))
|
||||
.toList();
|
||||
}
|
||||
|
||||
return storeExtensions
|
||||
.map((ext) =>
|
||||
ExtensionListItem(installed: installedMap[ext.id], store: ext))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> onInit() async {
|
||||
super.onInit();
|
||||
await loadInitialData();
|
||||
}
|
||||
|
||||
Future<void> loadInitialData() async {
|
||||
await Future.wait([loadInstalled(refreshUpdates: true), refreshStore()]);
|
||||
}
|
||||
|
||||
Future<void> loadInstalled({bool refreshUpdates = false}) async {
|
||||
loadingInstalled.value = true;
|
||||
try {
|
||||
installedExtensions.value = await getExtensions();
|
||||
if (refreshUpdates) {
|
||||
await checkUpdate();
|
||||
}
|
||||
} finally {
|
||||
loadingInstalled.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> checkUpdate() async {
|
||||
final nextFlags = <String, String>{};
|
||||
for (final ext in installedExtensions) {
|
||||
try {
|
||||
final resp = await upgradeCheckExtension(ext.identity);
|
||||
if (resp.newVersion.isNotEmpty) {
|
||||
nextFlags[ext.identity] = resp.newVersion;
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignore single extension check failures to avoid breaking the whole list.
|
||||
}
|
||||
}
|
||||
updateFlags.assignAll(nextFlags);
|
||||
}
|
||||
|
||||
Future<void> refreshStore() async {
|
||||
loadingStore.value = true;
|
||||
try {
|
||||
final page = await GopeedSiteApi.instance.getExtensions(
|
||||
page: 1,
|
||||
limit: 20,
|
||||
sort: storeSort.value,
|
||||
query: storeQuery.value,
|
||||
);
|
||||
storeExtensions.assignAll(page.data);
|
||||
storePagination.value = page.pagination;
|
||||
} finally {
|
||||
loadingStore.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> loadMoreStore() async {
|
||||
final pagination = storePagination.value;
|
||||
if (pagination == null || !pagination.hasNext || loadingMoreStore.value) {
|
||||
return;
|
||||
}
|
||||
loadingMoreStore.value = true;
|
||||
try {
|
||||
final page = await GopeedSiteApi.instance.getExtensions(
|
||||
page: pagination.page + 1,
|
||||
limit: pagination.limit,
|
||||
sort: storeSort.value,
|
||||
query: storeQuery.value,
|
||||
);
|
||||
storeExtensions.addAll(page.data);
|
||||
storePagination.value = page.pagination;
|
||||
} finally {
|
||||
loadingMoreStore.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> searchStore(String query) async {
|
||||
storeQuery.value = query.trim();
|
||||
await refreshStore();
|
||||
}
|
||||
|
||||
Future<void> changeSort(StoreExtensionSort sort) async {
|
||||
if (storeSort.value == sort) {
|
||||
await refreshStore();
|
||||
return;
|
||||
}
|
||||
storeSort.value = sort;
|
||||
await refreshStore();
|
||||
}
|
||||
|
||||
void changeFilter(ExtensionListFilter filter) {
|
||||
listFilter.value = filter;
|
||||
}
|
||||
|
||||
void toggleInstallTools() {
|
||||
showInstallTools.value = !showInstallTools.value;
|
||||
}
|
||||
|
||||
Extension? findInstalled(StoreExtension extension) {
|
||||
return installedMap[extension.id];
|
||||
}
|
||||
|
||||
bool canUpdateFromStore(StoreExtension extension) {
|
||||
final installed = findInstalled(extension);
|
||||
if (installed == null) return false;
|
||||
return _compareVersion(extension.version, installed.version) > 0;
|
||||
}
|
||||
|
||||
bool canUpdateItem(ExtensionListItem item) {
|
||||
if (item.installed == null) return false;
|
||||
if (listFilter.value == ExtensionListFilter.market && item.store != null) {
|
||||
return canUpdateFromStore(item.store!);
|
||||
}
|
||||
return updateFlags.containsKey(item.installed!.identity);
|
||||
}
|
||||
|
||||
Future<void> installFromStore(StoreExtension extension) async {
|
||||
await _runBusy(extension.id, () async {
|
||||
final installUrl = (extension.directory ?? '').trim().isEmpty
|
||||
? extension.repoUrl
|
||||
: '${extension.repoUrl}#${extension.directory!.trim()}';
|
||||
|
||||
final installedId =
|
||||
await installExtension(InstallExtension(url: installUrl));
|
||||
final statsId = installedId.isNotEmpty ? installedId : extension.id;
|
||||
await loadInstalled(refreshUpdates: false);
|
||||
_backgroundCheckUpdate();
|
||||
_bumpStoreInstallCount(statsId);
|
||||
_reportInstallSafe(statsId);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> installFromUrl(String url,
|
||||
{bool devInstall = false, String? statsId}) async {
|
||||
await _runBusy(manualInstallBusyKey, () async {
|
||||
final installedId = await installExtension(
|
||||
InstallExtension(devMode: devInstall, url: url));
|
||||
await loadInstalled(refreshUpdates: false);
|
||||
_backgroundCheckUpdate();
|
||||
if (installedId.isNotEmpty) {
|
||||
_bumpStoreInstallCount(installedId);
|
||||
_reportInstallSafe(installedId);
|
||||
} else if (statsId != null && statsId.isNotEmpty) {
|
||||
_bumpStoreInstallCount(statsId);
|
||||
_reportInstallSafe(statsId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> toggleExtension(Extension extension, bool enabled) async {
|
||||
await _runBusy(extension.identity, () async {
|
||||
await switchExtension(
|
||||
extension.identity, SwitchExtension(status: enabled));
|
||||
await loadInstalled(refreshUpdates: false);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> removeExtension(Extension extension) async {
|
||||
await _runBusy(extension.identity, () async {
|
||||
await deleteExtension(extension.identity);
|
||||
await loadInstalled(refreshUpdates: false);
|
||||
updateFlags.remove(extension.identity);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> upgradeExtension(Extension extension) async {
|
||||
await _runBusy(extension.identity, () async {
|
||||
await updateExtension(extension.identity);
|
||||
await loadInstalled(refreshUpdates: false);
|
||||
_backgroundCheckUpdate();
|
||||
_bumpStoreInstallCount(extension.identity);
|
||||
_reportInstallSafe(extension.identity);
|
||||
});
|
||||
}
|
||||
|
||||
void tryOpenDevMode() {
|
||||
if (_devModeCount == 0) {
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
if (devMode.value) return;
|
||||
devMode.value = false;
|
||||
_devModeCount = 0;
|
||||
});
|
||||
}
|
||||
_devModeCount++;
|
||||
if (_devModeCount >= 5) {
|
||||
devMode.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
static int _compareVersion(String a, String b) {
|
||||
final aNums = _toVersionNumbers(a);
|
||||
final bNums = _toVersionNumbers(b);
|
||||
final maxLen = aNums.length > bNums.length ? aNums.length : bNums.length;
|
||||
|
||||
for (var i = 0; i < maxLen; i++) {
|
||||
final left = i < aNums.length ? aNums[i] : 0;
|
||||
final right = i < bNums.length ? bNums[i] : 0;
|
||||
if (left > right) return 1;
|
||||
if (left < right) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static List<int> _toVersionNumbers(String version) {
|
||||
return version
|
||||
.split(RegExp(r'[^0-9]+'))
|
||||
.where((part) => part.isNotEmpty)
|
||||
.map((part) => int.tryParse(part) ?? 0)
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> _runBusy(String id, Future<void> Function() action) async {
|
||||
if (busyExtensionIds.contains(id)) return;
|
||||
busyExtensionIds.add(id);
|
||||
try {
|
||||
await action();
|
||||
} finally {
|
||||
busyExtensionIds.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
void _backgroundCheckUpdate() {
|
||||
unawaited(checkUpdate());
|
||||
}
|
||||
|
||||
void _reportInstallSafe(String id) {
|
||||
unawaited(() async {
|
||||
try {
|
||||
await GopeedSiteApi.instance.reportExtensionInstall(id);
|
||||
} catch (_) {
|
||||
// Ignore stats reporting failures.
|
||||
}
|
||||
}());
|
||||
}
|
||||
|
||||
void _bumpStoreInstallCount(String id) {
|
||||
final index = storeExtensions.indexWhere((e) => e.id == id);
|
||||
if (index < 0) return;
|
||||
final ext = storeExtensions[index];
|
||||
storeExtensions[index] = StoreExtension(
|
||||
id: ext.id,
|
||||
repoFullName: ext.repoFullName,
|
||||
repoUrl: ext.repoUrl,
|
||||
directory: ext.directory,
|
||||
commitSha: ext.commitSha,
|
||||
name: ext.name,
|
||||
author: ext.author,
|
||||
title: ext.title,
|
||||
description: ext.description,
|
||||
icon: ext.icon,
|
||||
version: ext.version,
|
||||
homepage: ext.homepage,
|
||||
readme: ext.readme,
|
||||
installCount: ext.installCount + 1,
|
||||
stars: ext.stars,
|
||||
topics: ext.topics,
|
||||
createdAt: ext.createdAt,
|
||||
updatedAt: ext.updatedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../../api/api.dart';
|
||||
import '../../../../database/database.dart';
|
||||
import '../../../../util/util.dart';
|
||||
import '../controllers/extension_controller.dart';
|
||||
|
||||
class ExtensionCard extends StatelessWidget {
|
||||
const ExtensionCard({
|
||||
super.key,
|
||||
required this.item,
|
||||
required this.busy,
|
||||
required this.canUpdate,
|
||||
this.onTap,
|
||||
this.onToggle,
|
||||
this.onOpenSetting,
|
||||
this.onUpdate,
|
||||
this.onDelete,
|
||||
this.onInstall,
|
||||
});
|
||||
|
||||
final ExtensionListItem item;
|
||||
final bool busy;
|
||||
final bool canUpdate;
|
||||
final VoidCallback? onTap;
|
||||
final Future<void> Function(bool value)? onToggle;
|
||||
final VoidCallback? onOpenSetting;
|
||||
final VoidCallback? onUpdate;
|
||||
final VoidCallback? onDelete;
|
||||
final VoidCallback? onInstall;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final installed = item.installed;
|
||||
final store = item.store;
|
||||
final installedFlag = item.isInstalled;
|
||||
|
||||
final content = Stack(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Theme.of(context).dividerColor.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildCardIcon(item),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'${item.author} · v${item.version}',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (installed != null) ...[
|
||||
Transform.scale(
|
||||
scale: 0.82,
|
||||
child: Switch(
|
||||
value: !installed.disabled,
|
||||
onChanged: busy || onToggle == null
|
||||
? null
|
||||
: (value) async {
|
||||
await onToggle!(value);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
item.description,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const Spacer(),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
if (store != null) ...[
|
||||
_metricItem(
|
||||
context, Icons.star_rounded, item.stars.toString()),
|
||||
const SizedBox(width: 10),
|
||||
_metricItem(context, Icons.download_outlined,
|
||||
item.installCount.toString()),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (installed != null && canUpdate)
|
||||
IconButton.filledTonal(
|
||||
tooltip: 'newVersionUpdate'.tr,
|
||||
onPressed: busy ? null : onUpdate,
|
||||
icon: busy
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded),
|
||||
),
|
||||
if (!installedFlag && store != null)
|
||||
IconButton.filledTonal(
|
||||
tooltip: 'extensionInstall'.tr,
|
||||
onPressed: busy ? null : onInstall,
|
||||
icon: busy
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.download),
|
||||
),
|
||||
if ((item.homepage ?? '').isNotEmpty)
|
||||
IconButton(
|
||||
tooltip: 'homepage'.tr,
|
||||
onPressed: () => launchUrl(Uri.parse(item.homepage!)),
|
||||
icon: const Icon(Icons.home_outlined),
|
||||
),
|
||||
if ((item.repoUrl ?? '').isNotEmpty)
|
||||
IconButton(
|
||||
tooltip: 'GitHub',
|
||||
onPressed: () => launchUrl(Uri.parse(item.repoUrl!)),
|
||||
icon: const Icon(Icons.code),
|
||||
),
|
||||
if (installed != null &&
|
||||
installed.settings?.isNotEmpty == true)
|
||||
IconButton(
|
||||
tooltip: 'setting'.tr,
|
||||
onPressed: busy ? null : onOpenSetting,
|
||||
icon: const Icon(Icons.settings),
|
||||
),
|
||||
if (installed != null)
|
||||
IconButton(
|
||||
tooltip: 'delete'.tr,
|
||||
onPressed: busy ? null : onDelete,
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (installedFlag && canUpdate)
|
||||
Positioned(
|
||||
top: 10,
|
||||
right: 10,
|
||||
child: _updateDot(),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
if (onTap == null) return content;
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: onTap,
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCardIcon(ExtensionListItem item) {
|
||||
final storeIcon = item.icon;
|
||||
if (storeIcon != null && storeIcon.isNotEmpty) {
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Image.network(
|
||||
storeIcon,
|
||||
width: 42,
|
||||
height: 42,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => Image.asset(
|
||||
'assets/extension/default_icon.png',
|
||||
width: 42,
|
||||
height: 42),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final extension = item.installed;
|
||||
if (extension == null) {
|
||||
return Image.asset('assets/extension/default_icon.png',
|
||||
width: 42, height: 42);
|
||||
}
|
||||
|
||||
final image = extension.icon.isEmpty
|
||||
? Image.asset('assets/extension/default_icon.png',
|
||||
width: 42, height: 42)
|
||||
: Util.isWeb()
|
||||
? Image.network(
|
||||
join('/fs/extensions/${extension.identity}/${extension.icon}'),
|
||||
width: 42,
|
||||
height: 42,
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${Database.instance.getWebToken()}'
|
||||
},
|
||||
errorBuilder: (_, __, ___) => Image.asset(
|
||||
'assets/extension/default_icon.png',
|
||||
width: 42,
|
||||
height: 42),
|
||||
)
|
||||
: Image.file(
|
||||
extension.devMode
|
||||
? File(path.join(extension.devPath, extension.icon))
|
||||
: File(path.join(Util.getStorageDir(), 'extensions',
|
||||
extension.identity, extension.icon)),
|
||||
width: 42,
|
||||
height: 42,
|
||||
errorBuilder: (_, __, ___) => Image.asset(
|
||||
'assets/extension/default_icon.png',
|
||||
width: 42,
|
||||
height: 42),
|
||||
);
|
||||
|
||||
return ClipRRect(borderRadius: BorderRadius.circular(8), child: image);
|
||||
}
|
||||
|
||||
Widget _metricItem(BuildContext context, IconData icon, String text) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 18, color: Theme.of(context).hintColor),
|
||||
const SizedBox(width: 4),
|
||||
Text(text, style: Theme.of(context).textTheme.bodyMedium),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _updateDot() {
|
||||
return Container(
|
||||
width: 9,
|
||||
height: 9,
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.redAccent,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../../api/model/extension.dart';
|
||||
import '../../../../api/model/store_extension.dart';
|
||||
import '../../../../util/message.dart';
|
||||
import '../../../../util/util.dart';
|
||||
import '../controllers/extension_controller.dart';
|
||||
|
||||
class ExtensionDetailDrawer extends GetView<ExtensionController> {
|
||||
const ExtensionDetailDrawer({
|
||||
super.key,
|
||||
required this.extension,
|
||||
required this.onClose,
|
||||
this.installed,
|
||||
});
|
||||
|
||||
final StoreExtension extension;
|
||||
final Extension? installed;
|
||||
final VoidCallback onClose;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 12, 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
extension.title,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: onClose,
|
||||
icon: const Icon(Icons.close),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: Obx(() {
|
||||
final localInstalled =
|
||||
installed ?? controller.findInstalled(extension);
|
||||
final canUpdate = controller.canUpdateFromStore(extension);
|
||||
final busy =
|
||||
controller.busyExtensionIds.contains(extension.id) ||
|
||||
(localInstalled != null &&
|
||||
controller.busyExtensionIds
|
||||
.contains(localInstalled.identity));
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildIcon(),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${extension.author} • v${extension.version}'),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
extension.description,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
if (localInstalled == null)
|
||||
ElevatedButton.icon(
|
||||
onPressed: busy
|
||||
? null
|
||||
: () async {
|
||||
try {
|
||||
await controller
|
||||
.installFromStore(extension);
|
||||
showMessage('tip'.tr,
|
||||
'extensionInstallSuccess'.tr);
|
||||
} catch (e) {
|
||||
showErrorMessage(e);
|
||||
}
|
||||
},
|
||||
icon: busy
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.download),
|
||||
label: Text('extensionInstall'.tr),
|
||||
),
|
||||
if (localInstalled != null && canUpdate)
|
||||
ElevatedButton.icon(
|
||||
onPressed: busy
|
||||
? null
|
||||
: () async {
|
||||
try {
|
||||
await controller
|
||||
.upgradeExtension(localInstalled);
|
||||
showMessage('tip'.tr,
|
||||
'extensionUpdateSuccess'.tr);
|
||||
} catch (e) {
|
||||
showErrorMessage(e);
|
||||
}
|
||||
},
|
||||
icon: busy
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded),
|
||||
label: Text('newVersionUpdate'.tr),
|
||||
),
|
||||
if ((extension.homepage ?? '').isNotEmpty)
|
||||
OutlinedButton.icon(
|
||||
onPressed: () =>
|
||||
launchUrl(Uri.parse(extension.homepage!)),
|
||||
icon: const Icon(Icons.home_outlined),
|
||||
label: Text('homepage'.tr),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: () =>
|
||||
launchUrl(Uri.parse(extension.repoUrl)),
|
||||
icon: const Icon(Icons.code),
|
||||
label: const Text('GitHub'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
const Divider(height: 1),
|
||||
const SizedBox(height: 12),
|
||||
_buildReadme(context, localInstalled),
|
||||
],
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildReadme(BuildContext context, Extension? installed) {
|
||||
return FutureBuilder<_ReadmeInfo>(
|
||||
future: _loadReadme(installed),
|
||||
builder: (context, snapshot) {
|
||||
final info = snapshot.data;
|
||||
final markdown = info?.content ?? extension.readme ?? '';
|
||||
if (markdown.trim().isEmpty) {
|
||||
return Text('No README',
|
||||
style: Theme.of(context).textTheme.bodyMedium);
|
||||
}
|
||||
|
||||
return MarkdownBody(
|
||||
data: markdown,
|
||||
selectable: true,
|
||||
onTapLink: (text, href, title) {
|
||||
if (href == null || href.isEmpty) return;
|
||||
final resolved = _resolvePath(href, info, forImage: false);
|
||||
if (resolved == null) return;
|
||||
launchUrl(Uri.parse(resolved),
|
||||
mode: LaunchMode.externalApplication);
|
||||
},
|
||||
imageBuilder: (uri, title, alt) {
|
||||
final resolved = _resolvePath(uri.toString(), info, forImage: true);
|
||||
if (resolved == null) return const SizedBox.shrink();
|
||||
if (resolved.startsWith('file://')) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Image.file(
|
||||
File(Uri.parse(resolved).toFilePath()),
|
||||
fit: BoxFit.contain,
|
||||
errorBuilder: (_, __, ___) => const SizedBox.shrink(),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Image.network(
|
||||
resolved,
|
||||
fit: BoxFit.contain,
|
||||
errorBuilder: (_, __, ___) => const SizedBox.shrink(),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<_ReadmeInfo> _loadReadme(Extension? installed) async {
|
||||
if (installed == null) {
|
||||
return _ReadmeInfo(
|
||||
content: extension.readme ?? '',
|
||||
mode: _ReadmeMode.remote,
|
||||
localReadmePath: null,
|
||||
);
|
||||
}
|
||||
|
||||
final rootDir = installed.devMode
|
||||
? installed.devPath
|
||||
: path.join(Util.getStorageDir(), 'extensions', installed.identity);
|
||||
final candidates = [
|
||||
path.join(rootDir, 'README.md'),
|
||||
path.join(rootDir, 'readme.md'),
|
||||
path.join(rootDir, 'README.MD'),
|
||||
];
|
||||
for (final filePath in candidates) {
|
||||
final file = File(filePath);
|
||||
if (await file.exists()) {
|
||||
return _ReadmeInfo(
|
||||
content: await file.readAsString(),
|
||||
mode: _ReadmeMode.local,
|
||||
localReadmePath: filePath,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return _ReadmeInfo(
|
||||
content: extension.readme ?? '',
|
||||
mode: _ReadmeMode.remote,
|
||||
localReadmePath: null,
|
||||
);
|
||||
}
|
||||
|
||||
String? _resolvePath(String raw, _ReadmeInfo? info,
|
||||
{required bool forImage}) {
|
||||
final value = raw.trim();
|
||||
if (value.isEmpty) return null;
|
||||
final uri = Uri.tryParse(value);
|
||||
if (uri != null && uri.hasScheme) {
|
||||
return uri.toString();
|
||||
}
|
||||
|
||||
if (info?.mode == _ReadmeMode.local &&
|
||||
info?.localReadmePath != null &&
|
||||
forImage) {
|
||||
final readmeDir = path.dirname(info!.localReadmePath!);
|
||||
final clean = value.split('#').first;
|
||||
final absolute = path.normalize(path.join(readmeDir, clean));
|
||||
return Uri.file(absolute).toString();
|
||||
}
|
||||
|
||||
final ref =
|
||||
extension.commitSha?.isNotEmpty == true ? extension.commitSha! : 'HEAD';
|
||||
final dir = (extension.directory ?? '').trim();
|
||||
final baseSegments = [
|
||||
if (dir.isNotEmpty) ...dir.split('/').where((e) => e.isNotEmpty),
|
||||
'',
|
||||
];
|
||||
|
||||
final base = forImage
|
||||
? Uri.https('raw.githubusercontent.com',
|
||||
'/${extension.repoFullName}/$ref/${baseSegments.join('/')}')
|
||||
: Uri.https('github.com',
|
||||
'/${extension.repoFullName}/blob/$ref/${baseSegments.join('/')}');
|
||||
return base.resolve(value).toString();
|
||||
}
|
||||
|
||||
Widget _buildIcon() {
|
||||
if ((extension.icon ?? '').isEmpty) {
|
||||
return Image.asset('assets/extension/default_icon.png',
|
||||
width: 56, height: 56);
|
||||
}
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Image.network(
|
||||
extension.icon!,
|
||||
width: 56,
|
||||
height: 56,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) {
|
||||
return Image.asset('assets/extension/default_icon.png',
|
||||
width: 56, height: 56);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum _ReadmeMode {
|
||||
remote,
|
||||
local,
|
||||
}
|
||||
|
||||
class _ReadmeInfo {
|
||||
final String content;
|
||||
final _ReadmeMode mode;
|
||||
final String? localReadmePath;
|
||||
|
||||
_ReadmeInfo({
|
||||
required this.content,
|
||||
required this.mode,
|
||||
required this.localReadmePath,
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,110 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/database/database.dart';
|
||||
|
||||
class HistoryView extends StatefulWidget {
|
||||
const HistoryView({
|
||||
super.key,
|
||||
required this.isHistoryListEmpty,
|
||||
required this.historyList,
|
||||
});
|
||||
|
||||
final bool isHistoryListEmpty;
|
||||
final Widget historyList;
|
||||
|
||||
@override
|
||||
State<HistoryView> createState() => _HistoryViewState();
|
||||
}
|
||||
|
||||
class _HistoryViewState extends State<HistoryView> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Size size = MediaQuery.sizeOf(context);
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.transparent,
|
||||
child: Container(
|
||||
width: size.width * 0.8,
|
||||
height: size.height * 0.8,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Icon(
|
||||
Icons.history_rounded,
|
||||
size: Theme.of(context)
|
||||
.textTheme
|
||||
.headlineSmall
|
||||
?.fontSize,
|
||||
),
|
||||
const SizedBox(width: 8.0),
|
||||
Text(
|
||||
'history'.tr,
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
Database.instance.clearCreateHistory();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
tooltip: "clearHistory".tr,
|
||||
icon: const Icon(
|
||||
Icons.history_toggle_off_rounded,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
icon: const Icon(
|
||||
Icons.close_rounded,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: widget.isHistoryListEmpty
|
||||
? <Widget>[
|
||||
const Icon(
|
||||
Icons.manage_history_rounded,
|
||||
),
|
||||
const SizedBox(height: 10.0),
|
||||
Text(
|
||||
'noHistoryFound'.tr,
|
||||
),
|
||||
]
|
||||
: <Widget>[
|
||||
Expanded(child: widget.historyList),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/home_controller.dart';
|
||||
|
||||
class HomeBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<HomeController>(
|
||||
() => HomeController(),
|
||||
fenix: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class HomeController extends GetxController {
|
||||
var currentIndex = 0.obs;
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../routes/app_pages.dart';
|
||||
import '../../../views/responsive_builder.dart';
|
||||
import '../controllers/home_controller.dart';
|
||||
|
||||
class HomeView extends GetView<HomeController> {
|
||||
const HomeView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GetRouterOutlet.builder(builder: (context, delegate, currentRoute) {
|
||||
switch (currentRoute?.uri.path) {
|
||||
case Routes.EXTENSION:
|
||||
controller.currentIndex.value = 1;
|
||||
break;
|
||||
case Routes.SETTING:
|
||||
controller.currentIndex.value = 2;
|
||||
break;
|
||||
default:
|
||||
controller.currentIndex.value = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
// extendBody: true,
|
||||
body: Row(
|
||||
// crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
!ResponsiveBuilder.isNarrow(context)
|
||||
? NavigationRail(
|
||||
extended: true,
|
||||
labelType: NavigationRailLabelType.none,
|
||||
minExtendedWidth: 170,
|
||||
groupAlignment: 0,
|
||||
// useIndicator: false,
|
||||
onDestinationSelected: (int index) {
|
||||
controller.currentIndex.value = index;
|
||||
switch (index) {
|
||||
case 0:
|
||||
delegate.offAndToNamed(Routes.TASK);
|
||||
break;
|
||||
case 1:
|
||||
delegate.offAndToNamed(Routes.EXTENSION);
|
||||
break;
|
||||
case 2:
|
||||
delegate.offAndToNamed(Routes.SETTING);
|
||||
break;
|
||||
}
|
||||
},
|
||||
destinations: [
|
||||
NavigationRailDestination(
|
||||
icon: const Icon(Icons.task),
|
||||
selectedIcon: const Icon(Icons.task),
|
||||
label: Text('task'.tr),
|
||||
),
|
||||
NavigationRailDestination(
|
||||
icon: const Icon(Icons.extension),
|
||||
selectedIcon: const Icon(Icons.extension),
|
||||
label: Text('extensions'.tr),
|
||||
),
|
||||
NavigationRailDestination(
|
||||
icon: const Icon(Icons.settings),
|
||||
selectedIcon: const Icon(Icons.settings),
|
||||
label: Text('setting'.tr),
|
||||
),
|
||||
],
|
||||
selectedIndex: controller.currentIndex.value,
|
||||
leading: const Icon(Icons.menu),
|
||||
// trailing: const Icon(Icons.info_outline),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
Expanded(
|
||||
child: GetRouterOutlet(
|
||||
initialRoute: Routes.TASK,
|
||||
// anchorRoute: '/',
|
||||
// filterPages: (afterAnchor) {
|
||||
// logger.w(afterAnchor);
|
||||
// logger.w(afterAnchor.take(1));
|
||||
// return afterAnchor.take(1);
|
||||
// },
|
||||
))
|
||||
]),
|
||||
bottomNavigationBar: ResponsiveBuilder.isNarrow(context)
|
||||
? BottomNavigationBar(
|
||||
items: <BottomNavigationBarItem>[
|
||||
BottomNavigationBarItem(
|
||||
icon: const Icon(Icons.task),
|
||||
label: 'task'.tr,
|
||||
),
|
||||
BottomNavigationBarItem(
|
||||
icon: const Icon(Icons.extension),
|
||||
label: 'extensions'.tr,
|
||||
),
|
||||
BottomNavigationBarItem(
|
||||
icon: const Icon(Icons.settings),
|
||||
label: 'setting'.tr,
|
||||
),
|
||||
],
|
||||
currentIndex: controller.currentIndex.value,
|
||||
// selectedItemColor: Get.theme.highlightColor,
|
||||
onTap: (index) {
|
||||
controller.currentIndex.value = index;
|
||||
switch (index) {
|
||||
case 0:
|
||||
delegate.offAndToNamed(Routes.TASK);
|
||||
break;
|
||||
case 1:
|
||||
delegate.offAndToNamed(Routes.EXTENSION);
|
||||
break;
|
||||
case 2:
|
||||
delegate.offAndToNamed(Routes.SETTING);
|
||||
break;
|
||||
}
|
||||
},
|
||||
)
|
||||
// StylishBottomBar(
|
||||
// option: AnimatedBarOptions(
|
||||
// iconSize: 32,
|
||||
// barAnimation: BarAnimation.blink,
|
||||
// iconStyle: IconStyle.Default,
|
||||
// opacity: 0.3,
|
||||
// ),
|
||||
// items: [
|
||||
// BottomBarItem(
|
||||
// icon: const Icon(Icons.file_download),
|
||||
// selectedColor: Get.theme.primaryColor,
|
||||
// title: Text('downloading'.tr)),
|
||||
// BottomBarItem(
|
||||
// icon: const Icon(Icons.done),
|
||||
// selectedColor: Get.theme.primaryColor,
|
||||
// title: Text('downloaded'.tr)),
|
||||
// BottomBarItem(
|
||||
// icon: const Icon(Icons.settings),
|
||||
// selectedColor: Get.theme.primaryColor,
|
||||
// title: Text('setting'.tr)),
|
||||
// ],
|
||||
// // hasNotch: true,
|
||||
// currentIndex: controller.currentIndex.value,
|
||||
// onTap: (index) {
|
||||
// switch (index) {
|
||||
// case 0:
|
||||
// delegate.toNamed(Routes.DOWNLOADING);
|
||||
// controller.currentIndex.value = 0;
|
||||
// break;
|
||||
// case 1:
|
||||
// delegate.toNamed(Routes.DOWNLOADED);
|
||||
// controller.currentIndex.value = 1;
|
||||
// break;
|
||||
// case 2:
|
||||
// delegate.toNamed(Routes.SETTING);
|
||||
// controller.currentIndex.value = 2;
|
||||
// break;
|
||||
// }
|
||||
// },
|
||||
// )
|
||||
: const SizedBox.shrink(),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/login_controller.dart';
|
||||
|
||||
class LoginBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<LoginController>(
|
||||
() => LoginController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../../api/api.dart' as api;
|
||||
import '../../../../api/api.dart';
|
||||
import '../../../../api/model/login.dart';
|
||||
import '../../../../database/database.dart';
|
||||
import '../../../../util/message.dart';
|
||||
import '../../../routes/app_pages.dart';
|
||||
import '../../app/controllers/app_controller.dart';
|
||||
|
||||
class LoginController extends GetxController {
|
||||
final formKey = GlobalKey<FormState>();
|
||||
final usernameController = TextEditingController();
|
||||
final passwordController = TextEditingController();
|
||||
|
||||
final isLoading = false.obs;
|
||||
final passwordVisible = false.obs;
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
usernameController.dispose();
|
||||
passwordController.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
void togglePasswordVisibility() {
|
||||
passwordVisible.value = !passwordVisible.value;
|
||||
}
|
||||
|
||||
Future<void> login() async {
|
||||
if (!formKey.currentState!.validate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
try {
|
||||
final loginReq = LoginReq(
|
||||
username: usernameController.text.trim(),
|
||||
password: passwordController.text,
|
||||
);
|
||||
|
||||
final token = await api.login(loginReq);
|
||||
// Login successful, save the token
|
||||
Database.instance.saveWebToken(token);
|
||||
// Reload config
|
||||
final controller = Get.put(AppController());
|
||||
await controller.loadDownloaderConfig();
|
||||
// Navigate to home page
|
||||
Get.rootDelegate.offAndToNamed(Routes.HOME);
|
||||
} catch (e) {
|
||||
if (e is TimeoutException) {
|
||||
showMessage('error'.tr, 'login_failed_network'.tr);
|
||||
} else {
|
||||
showMessage('error'.tr, 'login_failed'.tr);
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../views/responsive_builder.dart';
|
||||
import '../controllers/login_controller.dart';
|
||||
|
||||
class LoginView extends GetView<LoginController> {
|
||||
const LoginView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isNarrow = ResponsiveBuilder.isNarrow(context);
|
||||
|
||||
return Scaffold(
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [
|
||||
Get.theme.colorScheme.surface,
|
||||
Get.theme.colorScheme.surface.withOpacity(0.8),
|
||||
Get.theme.colorScheme.surface.withOpacity(0.9),
|
||||
],
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: isNarrow ? 16.0 : 32.0,
|
||||
vertical: isNarrow ? 24.0 : 32.0,
|
||||
),
|
||||
child: Card(
|
||||
elevation: 12,
|
||||
shadowColor: Get.theme.colorScheme.shadow.withOpacity(0.3),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(isNarrow ? 20 : 24),
|
||||
),
|
||||
color: Get.theme.colorScheme.surface,
|
||||
child: Container(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: isNarrow ? double.infinity : 420,
|
||||
),
|
||||
padding: EdgeInsets.all(isNarrow ? 24.0 : 40.0),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(isNarrow ? 20 : 24),
|
||||
border: Border.all(
|
||||
color: Get.theme.colorScheme.outline.withOpacity(0.1),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: FocusTraversalGroup(
|
||||
policy: OrderedTraversalPolicy(),
|
||||
child: Form(
|
||||
key: controller.formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Logo/Title Section
|
||||
Container(
|
||||
alignment: Alignment.center,
|
||||
margin: EdgeInsets.only(bottom: isNarrow ? 32 : 48),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(isNarrow ? 8 : 12),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius:
|
||||
BorderRadius.circular(isNarrow ? 20 : 24),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Get.theme.colorScheme.primary
|
||||
.withOpacity(0.2),
|
||||
blurRadius: isNarrow ? 16 : 24,
|
||||
offset: Offset(0, isNarrow ? 8 : 12),
|
||||
spreadRadius: isNarrow ? 1 : 2,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius:
|
||||
BorderRadius.circular(isNarrow ? 16 : 20),
|
||||
child: SvgPicture.asset(
|
||||
'assets/icon/icon.svg',
|
||||
width: isNarrow ? 56 : 72,
|
||||
height: isNarrow ? 56 : 72,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Gopeed',
|
||||
style: Get.textTheme.headlineLarge?.copyWith(
|
||||
fontWeight: FontWeight.w900,
|
||||
color: Get.theme.colorScheme.onSurface,
|
||||
letterSpacing: 2.0,
|
||||
fontSize: isNarrow ? 28 : 36,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Username Field
|
||||
FocusTraversalOrder(
|
||||
order: const NumericFocusOrder(1.0),
|
||||
child: TextFormField(
|
||||
controller: controller.usernameController,
|
||||
autofillHints: const [
|
||||
AutofillHints.username,
|
||||
],
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) => controller.login(),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'username'.tr,
|
||||
labelStyle: TextStyle(
|
||||
color: Get.theme.colorScheme.onSurface
|
||||
.withOpacity(0.7),
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 16,
|
||||
),
|
||||
prefixIcon: Container(
|
||||
margin: const EdgeInsets.all(12),
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Get.theme.colorScheme.primary
|
||||
.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.person_outline_rounded,
|
||||
color: Get.theme.colorScheme.primary,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.outline
|
||||
.withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.outline
|
||||
.withOpacity(0.3),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.primary,
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.error,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
focusedErrorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.error,
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: Get
|
||||
.theme.colorScheme.surfaceContainerHighest
|
||||
.withOpacity(0.8),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 24,
|
||||
vertical: 20,
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'username_required'.tr;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(height: isNarrow ? 16 : 24),
|
||||
|
||||
// Password Field
|
||||
FocusTraversalOrder(
|
||||
order: const NumericFocusOrder(2.0),
|
||||
child: Obx(() => TextFormField(
|
||||
controller: controller.passwordController,
|
||||
autofillHints: const [
|
||||
AutofillHints.password,
|
||||
],
|
||||
obscureText: !controller.passwordVisible.value,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'password'.tr,
|
||||
labelStyle: TextStyle(
|
||||
color: Get.theme.colorScheme.onSurface
|
||||
.withOpacity(0.7),
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 16,
|
||||
),
|
||||
prefixIcon: Container(
|
||||
margin: const EdgeInsets.all(12),
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Get.theme.colorScheme.primary
|
||||
.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.lock_outline_rounded,
|
||||
color: Get.theme.colorScheme.primary,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
controller.passwordVisible.value
|
||||
? Icons.visibility_off_rounded
|
||||
: Icons.visibility_rounded,
|
||||
color: Get.theme.colorScheme.onSurface
|
||||
.withOpacity(0.6),
|
||||
),
|
||||
onPressed:
|
||||
controller.togglePasswordVisibility,
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.outline
|
||||
.withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.outline
|
||||
.withOpacity(0.3),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.primary,
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.error,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
focusedErrorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
borderSide: BorderSide(
|
||||
color: Get.theme.colorScheme.error,
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: Get
|
||||
.theme.colorScheme.surfaceContainerHighest
|
||||
.withOpacity(0.8),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 24,
|
||||
vertical: 20,
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'password_required'.tr;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) => controller.login(),
|
||||
)),
|
||||
),
|
||||
|
||||
SizedBox(height: isNarrow ? 24 : 32),
|
||||
|
||||
// Login Button
|
||||
Obx(() => ElevatedButton(
|
||||
onPressed: controller.isLoading.value
|
||||
? null
|
||||
: controller.login,
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: EdgeInsets.symmetric(
|
||||
vertical: isNarrow ? 16 : 18,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
backgroundColor: controller.isLoading.value
|
||||
? Get.theme.disabledColor
|
||||
: Get.theme.colorScheme.primary,
|
||||
foregroundColor:
|
||||
Get.theme.colorScheme.onPrimary,
|
||||
elevation: controller.isLoading.value ? 0 : 4,
|
||||
shadowColor: Get.theme.colorScheme.primary
|
||||
.withOpacity(0.4),
|
||||
),
|
||||
child: controller.isLoading.value
|
||||
? SizedBox(
|
||||
height: 24,
|
||||
width: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2.5,
|
||||
valueColor:
|
||||
AlwaysStoppedAnimation<Color>(Get
|
||||
.theme.colorScheme.onPrimary),
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
'login'.tr,
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/redirect_controller.dart';
|
||||
|
||||
class RedirectBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<RedirectController>(
|
||||
() => RedirectController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class RedirectController extends GetxController {}
|
||||
@@ -1,27 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/redirect_controller.dart';
|
||||
|
||||
class RedirectArgs {
|
||||
final String page;
|
||||
final dynamic arguments;
|
||||
|
||||
RedirectArgs(this.page, {this.arguments});
|
||||
}
|
||||
|
||||
class RedirectView extends GetView<RedirectController> {
|
||||
const RedirectView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final redirectArgs = Get.rootDelegate.arguments() as RedirectArgs;
|
||||
// Waiting for previous page controller to delete, avoid deleting controller that route page after redirect
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
await Future.delayed(const Duration(milliseconds: 350));
|
||||
Get.rootDelegate
|
||||
.offAndToNamed(redirectArgs.page, arguments: redirectArgs.arguments);
|
||||
});
|
||||
return const SizedBox();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/root_controller.dart';
|
||||
|
||||
class RootBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<RootController>(() => RootController(), fenix: true);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class RootController extends GetxController {}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../routes/app_pages.dart';
|
||||
import '../controllers/root_controller.dart';
|
||||
|
||||
class RootView extends GetView<RootController> {
|
||||
const RootView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GetRouterOutlet.builder(
|
||||
builder: (context, delegate, current) {
|
||||
return GetRouterOutlet(
|
||||
initialRoute: Routes.HOME,
|
||||
// anchorRoute: '/',
|
||||
// filterPages: (afterAnchor) {
|
||||
// return afterAnchor.take(1);
|
||||
// },
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/setting_controller.dart';
|
||||
|
||||
class SettingBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<SettingController>(
|
||||
() => SettingController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../../util/updater.dart';
|
||||
|
||||
class SettingController extends GetxController {
|
||||
final tapStatues = <String, bool>{}.obs;
|
||||
final latestVersion = Rxn<VersionInfo>();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchLatestVersion();
|
||||
}
|
||||
|
||||
// set all tap status to false
|
||||
void clearTap() {
|
||||
tapStatues.updateAll((key, value) => false);
|
||||
}
|
||||
|
||||
// set one tap status to true
|
||||
void onTap(String key) {
|
||||
clearTap();
|
||||
tapStatues[key] = true;
|
||||
}
|
||||
|
||||
// fetch latest version
|
||||
void fetchLatestVersion() async {
|
||||
latestVersion.value = await checkUpdate();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,20 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/task_controller.dart';
|
||||
import '../controllers/task_downloaded_controller.dart';
|
||||
import '../controllers/task_downloading_controller.dart';
|
||||
|
||||
class TaskBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<TaskController>(
|
||||
() => TaskController(),
|
||||
);
|
||||
Get.lazyPut<TaskDownloadingController>(
|
||||
() => TaskDownloadingController(),
|
||||
);
|
||||
Get.lazyPut<TaskDownloadedController>(
|
||||
() => TaskDownloadedController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/task_files_controller.dart';
|
||||
|
||||
class TaskFilesBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<TaskFilesController>(
|
||||
() => TaskFilesController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/model/task.dart';
|
||||
|
||||
class TaskController extends GetxController {
|
||||
final tabIndex = 0.obs;
|
||||
final scaffoldKey = GlobalKey<ScaffoldState>();
|
||||
final selectTask = Rx<Task?>(null);
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
if (kIsWeb) {
|
||||
BrowserContextMenu.disableContextMenu();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
super.onClose();
|
||||
if (kIsWeb) {
|
||||
BrowserContextMenu.enableContextMenu();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import 'package:gopeed/app/modules/task/controllers/task_list_controller.dart';
|
||||
|
||||
import '../../../../api/model/task.dart';
|
||||
|
||||
class TaskDownloadedController extends TaskListController {
|
||||
TaskDownloadedController()
|
||||
: super([Status.done], (a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import '../../../../api/model/task.dart';
|
||||
import 'task_list_controller.dart';
|
||||
|
||||
class TaskDownloadingController extends TaskListController {
|
||||
TaskDownloadingController()
|
||||
: super([
|
||||
Status.ready,
|
||||
Status.running,
|
||||
Status.pause,
|
||||
Status.wait,
|
||||
Status.error
|
||||
], (a, b) {
|
||||
if (a.status == Status.running && b.status != Status.running) {
|
||||
return -1;
|
||||
} else if (a.status != Status.running && b.status == Status.running) {
|
||||
return 1;
|
||||
} else {
|
||||
return b.updatedAt.compareTo(a.updatedAt);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
import '../../../../api/api.dart';
|
||||
import '../../../../api/model/resource.dart';
|
||||
import '../../../../api/model/task.dart';
|
||||
|
||||
class FileItem {
|
||||
final bool isDirectory;
|
||||
final String path;
|
||||
final String name;
|
||||
final int size;
|
||||
|
||||
FileItem(this.isDirectory, this.path, this.name, this.size);
|
||||
|
||||
String get fullPath => "${path == "/" ? path : "$path/"}$name";
|
||||
|
||||
String filePath(String optName) {
|
||||
return optName.isEmpty
|
||||
? fullPath
|
||||
: "${path == "/" ? path : "$path/"}$optName";
|
||||
}
|
||||
}
|
||||
|
||||
class TaskFilesController extends GetxController {
|
||||
final Map<String, List<FileItem>> _dirMap = {};
|
||||
|
||||
final task = Rx<Task?>(null);
|
||||
final fileList = <FileItem>[].obs;
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
super.onInit();
|
||||
|
||||
final taskId = Get.rootDelegate.parameters['id'];
|
||||
final tasks = await getTasks([]);
|
||||
task.value = tasks.firstWhere((element) => element.id == taskId);
|
||||
parseDirMap(task.value!.meta.res!.files);
|
||||
toDir("/");
|
||||
}
|
||||
|
||||
void parseDirMap(List<FileInfo> fileList) {
|
||||
for (final file in fileList) {
|
||||
String dir = file.path;
|
||||
if (!dir.startsWith("/")) {
|
||||
dir = "/$dir";
|
||||
}
|
||||
if (!_dirMap.containsKey(dir)) {
|
||||
_dirMap[dir] = [];
|
||||
}
|
||||
|
||||
_dirMap[dir]!.add(FileItem(false, dir, file.name, file.size));
|
||||
|
||||
void findParent(String dir) {
|
||||
final parentDirIndex = dir.lastIndexOf("/");
|
||||
String parentDir =
|
||||
parentDirIndex == 0 ? "/" : dir.substring(0, parentDirIndex);
|
||||
if (!_dirMap.containsKey(parentDir)) {
|
||||
_dirMap[parentDir] = [];
|
||||
}
|
||||
String dirName = dir.substring(dir.lastIndexOf("/") + 1);
|
||||
if (!_dirMap[parentDir]!.any((element) => element.name == dirName)) {
|
||||
_dirMap[parentDir]!.add(FileItem(true, parentDir, dirName, 0));
|
||||
}
|
||||
}
|
||||
|
||||
while (dir != "/" && dir != "") {
|
||||
findParent(dir);
|
||||
dir = dir.substring(0, dir.lastIndexOf("/"));
|
||||
}
|
||||
}
|
||||
|
||||
// sort children, directories first then files, alphabetically
|
||||
_dirMap.forEach((key, value) {
|
||||
value.sort((a, b) {
|
||||
if (a.isDirectory && !b.isDirectory) {
|
||||
return -1;
|
||||
} else if (!a.isDirectory && b.isDirectory) {
|
||||
return 1;
|
||||
} else {
|
||||
return a.name.compareTo(b.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void toDir(String dir) {
|
||||
fileList.value = _dirMap[dir]?.toList() ?? [];
|
||||
}
|
||||
|
||||
int dirItemCount(String dir) {
|
||||
return _dirMap[dir]?.length ?? 0;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../../api/api.dart';
|
||||
import '../../../../api/model/task.dart';
|
||||
|
||||
abstract class TaskListController extends GetxController {
|
||||
List<Status> statuses;
|
||||
int Function(Task a, Task b) compare;
|
||||
|
||||
TaskListController(this.statuses, this.compare);
|
||||
|
||||
final tasks = <Task>[].obs;
|
||||
final selectedTaskIds = <String>[].obs;
|
||||
final isRunning = false.obs;
|
||||
|
||||
late final Timer _timer;
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
super.onInit();
|
||||
|
||||
start();
|
||||
_timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) async {
|
||||
if (isRunning.value) {
|
||||
await getTasksState();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
super.onClose();
|
||||
_timer.cancel();
|
||||
}
|
||||
|
||||
void start() async {
|
||||
await getTasksState();
|
||||
isRunning.value = true;
|
||||
}
|
||||
|
||||
void stop() {
|
||||
isRunning.value = false;
|
||||
}
|
||||
|
||||
getTasksState() async {
|
||||
final tasks = await getTasks(statuses);
|
||||
// sort tasks by create time
|
||||
tasks.sort(compare);
|
||||
this.tasks.value = tasks;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../views/buid_task_list_view.dart';
|
||||
import '../controllers/task_downloaded_controller.dart';
|
||||
|
||||
class TaskDownloadedView extends GetView<TaskDownloadedController> {
|
||||
const TaskDownloadedView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BuildTaskListView(
|
||||
tasks: controller.tasks, selectedTaskIds: controller.selectedTaskIds);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../views/buid_task_list_view.dart';
|
||||
import '../controllers/task_downloading_controller.dart';
|
||||
|
||||
class TaskDownloadingView extends GetView<TaskDownloadingController> {
|
||||
const TaskDownloadingView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BuildTaskListView(
|
||||
tasks: controller.tasks, selectedTaskIds: controller.selectedTaskIds);
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:open_filex/open_filex.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../../api/api.dart' as api;
|
||||
import '../../../../util/browser_download/browser_download.dart';
|
||||
import '../../../../util/util.dart';
|
||||
import '../../../views/breadcrumb_view.dart';
|
||||
import '../../../views/file_icon.dart';
|
||||
import '../controllers/task_files_controller.dart';
|
||||
|
||||
class TaskFilesView extends GetView<TaskFilesController> {
|
||||
const TaskFilesView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => Get.rootDelegate.popRoute()),
|
||||
// actions: [],
|
||||
title: Obx(() => Text(controller.task.value?.meta.res?.name ?? "")),
|
||||
),
|
||||
body: Obx(() {
|
||||
final fileList = controller.fileList;
|
||||
final breadcrumbItems = ["/"];
|
||||
if (fileList.isNotEmpty) {
|
||||
final file = fileList.first;
|
||||
final path = file.path.substring(1);
|
||||
if (path.isNotEmpty) {
|
||||
final pathArr = path.split("/");
|
||||
for (int i = 0; i < pathArr.length; i++) {
|
||||
breadcrumbItems.add(pathArr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Column(
|
||||
children: [
|
||||
Breadcrumb(
|
||||
items: breadcrumbItems,
|
||||
onItemTap: (index) {
|
||||
final targetDirArr = <String>[];
|
||||
for (int i = 0; i <= index; i++) {
|
||||
targetDirArr.add(breadcrumbItems[i]);
|
||||
}
|
||||
controller
|
||||
.toDir(targetDirArr.join("/").replaceFirst('//', '/'));
|
||||
}).paddingOnly(left: 16, top: 16, bottom: 8),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemBuilder: (context, index) {
|
||||
final meta = controller.task.value!.meta;
|
||||
final file = fileList[index];
|
||||
// if resource is single file, use opts.name as file name
|
||||
final realFileName = meta.res!.name.isEmpty
|
||||
? (meta.opts.name.isEmpty ? file.name : meta.opts.name)
|
||||
: "";
|
||||
final fileRelativePath = file.filePath(realFileName);
|
||||
final filePath = Util.safePathJoin(
|
||||
[meta.opts.path, meta.res!.name, fileRelativePath]);
|
||||
final fileName = basename(filePath);
|
||||
return ListTile(
|
||||
leading:
|
||||
Icon(fileIcon(fileName, isFolder: file.isDirectory)),
|
||||
title: Text(fileName),
|
||||
subtitle: file.isDirectory
|
||||
? Text('items'.trParams({
|
||||
'count': controller
|
||||
.dirItemCount(file.fullPath)
|
||||
.toString()
|
||||
}))
|
||||
: Text(Util.fmtByte(file.size)),
|
||||
trailing: file.isDirectory
|
||||
? null
|
||||
: SizedBox(
|
||||
width: 100,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: Util.isWeb()
|
||||
? () {
|
||||
final accessUrl = api.join(
|
||||
"/fs/tasks/${controller.task.value!.id}$fileRelativePath");
|
||||
return [
|
||||
IconButton(
|
||||
icon:
|
||||
const Icon(Icons.open_in_new),
|
||||
onPressed: () {
|
||||
launchUrl(Uri.parse(accessUrl),
|
||||
webOnlyWindowName:
|
||||
"_blank");
|
||||
}),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.download),
|
||||
onPressed: () {
|
||||
download(accessUrl, fileName);
|
||||
})
|
||||
];
|
||||
}()
|
||||
: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.open_in_new),
|
||||
onPressed: () async {
|
||||
await OpenFilex.open(filePath);
|
||||
}),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.share),
|
||||
onPressed: () {
|
||||
final xfile = XFile(filePath);
|
||||
Share.shareXFiles([xfile]);
|
||||
})
|
||||
],
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
if (file.isDirectory) {
|
||||
controller.toDir(file.fullPath);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
itemCount: controller.fileList.length,
|
||||
),
|
||||
)
|
||||
],
|
||||
);
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:open_filex/open_filex.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
import '../../../../api/model/task.dart';
|
||||
import '../../../../util/file_explorer.dart';
|
||||
import '../../../../util/util.dart';
|
||||
import '../../../routes/app_pages.dart';
|
||||
import '../../../views/copy_button.dart';
|
||||
import '../controllers/task_controller.dart';
|
||||
import '../controllers/task_downloaded_controller.dart';
|
||||
import '../controllers/task_downloading_controller.dart';
|
||||
import 'task_downloaded_view.dart';
|
||||
import 'task_downloading_view.dart';
|
||||
|
||||
class TaskView extends GetView<TaskController> {
|
||||
const TaskView({Key? key}) : super(key: key);
|
||||
|
||||
String? _displayTaskUrl(Task? task) {
|
||||
final rawUrl = task?.meta.req.rawUrl;
|
||||
if (rawUrl != null && rawUrl.isNotEmpty) {
|
||||
return rawUrl;
|
||||
}
|
||||
return task?.meta.req.url;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selectTask = controller.selectTask;
|
||||
|
||||
return DefaultTabController(
|
||||
length: 2,
|
||||
child: Scaffold(
|
||||
key: controller.scaffoldKey,
|
||||
appBar: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(56),
|
||||
child: AppBar(
|
||||
bottom: TabBar(
|
||||
tabs: const [
|
||||
Tab(
|
||||
icon: Icon(Icons.file_download),
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.done),
|
||||
),
|
||||
],
|
||||
onTap: (index) {
|
||||
if (controller.tabIndex.value != index) {
|
||||
controller.tabIndex.value = index;
|
||||
final downloadingController =
|
||||
Get.find<TaskDownloadingController>();
|
||||
final downloadedController =
|
||||
Get.find<TaskDownloadedController>();
|
||||
switch (index) {
|
||||
case 0:
|
||||
downloadingController.start();
|
||||
downloadedController.stop();
|
||||
break;
|
||||
case 1:
|
||||
downloadingController.stop();
|
||||
downloadedController.start();
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
)),
|
||||
body: const TabBarView(
|
||||
children: [
|
||||
TaskDownloadingView(),
|
||||
TaskDownloadedView(),
|
||||
],
|
||||
),
|
||||
endDrawer: Drawer(
|
||||
// Add a ListView to the drawer. This ensures the user can scroll
|
||||
// through the options in the drawer if there isn't enough vertical
|
||||
// space to fit everything.
|
||||
child: Obx(() => ListView(
|
||||
// Important: Remove any padding from the ListView.
|
||||
padding: EdgeInsets.zero,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: MediaQuery.of(context).padding.top + 65,
|
||||
child: DrawerHeader(
|
||||
child: Text(
|
||||
'taskDetail'.tr,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
)),
|
||||
),
|
||||
ListTile(
|
||||
title: Text('taskName'.tr),
|
||||
subtitle: buildTooltipSubtitle(selectTask.value?.name)),
|
||||
ListTile(
|
||||
title: Text('taskUrl'.tr),
|
||||
subtitle: buildTooltipSubtitle(_displayTaskUrl(selectTask.value)),
|
||||
trailing: CopyButton(_displayTaskUrl(selectTask.value)),
|
||||
),
|
||||
ListTile(
|
||||
title: Text('downloadPath'.tr),
|
||||
subtitle:
|
||||
buildTooltipSubtitle(selectTask.value?.explorerUrl),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.folder_open),
|
||||
onPressed: () {
|
||||
selectTask.value?.explorer();
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget buildTooltipSubtitle(String? text) {
|
||||
final showText = text ?? "";
|
||||
return Tooltip(
|
||||
message: showText,
|
||||
child: Text(
|
||||
showText,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension TaskEnhance on Task {
|
||||
bool get isFolder {
|
||||
return meta.res?.name.isNotEmpty ?? false;
|
||||
}
|
||||
|
||||
String get explorerUrl {
|
||||
return path.join(Util.safeDir(meta.opts.path), Util.safeDir(name));
|
||||
}
|
||||
|
||||
Future<void> explorer() async {
|
||||
if (Util.isDesktop()) {
|
||||
await FileExplorer.openAndSelectFile(explorerUrl);
|
||||
} else {
|
||||
Get.rootDelegate.toNamed(Routes.TASK_FILES, parameters: {'id': id});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> open() async {
|
||||
if (status != Status.done) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isFolder) {
|
||||
await explorer();
|
||||
} else {
|
||||
await OpenFilex.open(explorerUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../features/extensions/presentation/pages/extensions_page.dart';
|
||||
import '../../features/extensions/presentation/pages/extension_details_page.dart';
|
||||
import '../../features/extensions/application/extensions_controller.dart';
|
||||
import '../../features/auth/application/web_auth_controller.dart';
|
||||
import '../../features/auth/presentation/pages/login_page.dart';
|
||||
import '../../features/home/presentation/pages/home_page.dart';
|
||||
import '../../features/settings/presentation/pages/settings_page.dart';
|
||||
import '../../features/tasks/presentation/pages/create_task_window_page.dart';
|
||||
import '../../features/tasks/domain/task_record.dart';
|
||||
import '../../features/tasks/presentation/pages/task_details_page.dart';
|
||||
import '../../features/tasks/presentation/pages/task_files_page.dart';
|
||||
import 'shells/main_shell.dart';
|
||||
|
||||
class AppRouter {
|
||||
static final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
static GoRouter build(WebAuthController webAuthController) {
|
||||
return GoRouter(
|
||||
navigatorKey: rootNavigatorKey,
|
||||
refreshListenable: webAuthController,
|
||||
redirect: (context, state) {
|
||||
final onLoginPage = state.matchedLocation == '/login';
|
||||
if (webAuthController.loginRequired) {
|
||||
if (onLoginPage) return null;
|
||||
return Uri(path: '/login', queryParameters: {'from': state.uri.toString()}).toString();
|
||||
}
|
||||
if (onLoginPage) {
|
||||
return _safeReturnLocation(state.uri.queryParameters['from']);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
routes: [
|
||||
GoRoute(path: '/login', parentNavigatorKey: rootNavigatorKey, builder: (context, state) => const LoginPage()),
|
||||
ShellRoute(
|
||||
builder: (context, state, child) => MainShell(child: child),
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: '/',
|
||||
builder: (context, state) => const HomePage(),
|
||||
routes: [
|
||||
GoRoute(path: 'create', builder: (context, state) => const CreateTaskWindowPage()),
|
||||
GoRoute(
|
||||
path: 'tasks/:id',
|
||||
builder: (context, state) => TaskDetailsPage(
|
||||
taskId: state.pathParameters['id'] ?? '',
|
||||
initialTask: state.extra is TaskRecord ? state.extra as TaskRecord : null,
|
||||
),
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: 'files',
|
||||
builder: (context, state) => TaskFilesPage(
|
||||
taskId: state.pathParameters['id'] ?? '',
|
||||
initialTask: state.extra is TaskRecord ? state.extra as TaskRecord : null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
GoRoute(
|
||||
path: '/extensions',
|
||||
builder: (context, state) => const ExtensionsPage(),
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: ':id',
|
||||
builder: (context, state) => ExtensionDetailsPage(
|
||||
extensionId: state.pathParameters['id'] ?? '',
|
||||
initialItem: state.extra is ExtensionListItem ? state.extra as ExtensionListItem : null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
GoRoute(
|
||||
path: '/settings',
|
||||
builder: (context, state) => const SettingsPage(),
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: ':section',
|
||||
builder: (context, state) => SettingsPage(sectionKey: state.pathParameters['section']),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static String _safeReturnLocation(String? location) {
|
||||
if (location == null || location.isEmpty) return '/';
|
||||
final uri = Uri.tryParse(location);
|
||||
if (uri == null || uri.hasScheme || uri.host.isNotEmpty || !location.startsWith('/') || uri.path == '/login') {
|
||||
return '/';
|
||||
}
|
||||
return location;
|
||||
}
|
||||
}
|
||||
Loaded 50 of 742 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user