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,12 @@
|
||||
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
@@ -0,0 +1,62 @@
|
||||
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);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/create_controller.dart';
|
||||
|
||||
class CreateBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<CreateController>(
|
||||
() => CreateController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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 = "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
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
@@ -0,0 +1,12 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/extension_controller.dart';
|
||||
|
||||
class ExtensionBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<ExtensionController>(
|
||||
() => ExtensionController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
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
@@ -0,0 +1,110 @@
|
||||
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),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/home_controller.dart';
|
||||
|
||||
class HomeBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<HomeController>(
|
||||
() => HomeController(),
|
||||
fenix: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class HomeController extends GetxController {
|
||||
var currentIndex = 0.obs;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
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(),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/login_controller.dart';
|
||||
|
||||
class LoginBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<LoginController>(
|
||||
() => LoginController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
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,
|
||||
),
|
||||
),
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/redirect_controller.dart';
|
||||
|
||||
class RedirectBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<RedirectController>(
|
||||
() => RedirectController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class RedirectController extends GetxController {}
|
||||
@@ -0,0 +1,27 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/root_controller.dart';
|
||||
|
||||
class RootBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<RootController>(() => RootController(), fenix: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class RootController extends GetxController {}
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
// },
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/setting_controller.dart';
|
||||
|
||||
class SettingBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<SettingController>(
|
||||
() => SettingController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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
@@ -0,0 +1,20 @@
|
||||
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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/task_files_controller.dart';
|
||||
|
||||
class TaskFilesBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<TaskFilesController>(
|
||||
() => TaskFilesController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
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));
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
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,
|
||||
),
|
||||
)
|
||||
],
|
||||
);
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
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,95 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../modules/create/bindings/create_binding.dart';
|
||||
import '../modules/create/views/create_dialog_view.dart';
|
||||
import '../modules/create/views/create_view.dart';
|
||||
import '../modules/extension/bindings/extension_binding.dart';
|
||||
import '../modules/extension/views/extension_view.dart';
|
||||
import '../modules/home/bindings/home_binding.dart';
|
||||
import '../modules/home/views/home_view.dart';
|
||||
import '../modules/login/bindings/login_binding.dart';
|
||||
import '../modules/login/views/login_view.dart';
|
||||
import '../modules/redirect/bindings/redirect_binding.dart';
|
||||
import '../modules/redirect/views/redirect_view.dart';
|
||||
import '../modules/root/bindings/root_binding.dart';
|
||||
import '../modules/root/views/root_view.dart';
|
||||
import '../modules/setting/bindings/setting_binding.dart';
|
||||
import '../modules/setting/views/setting_view.dart';
|
||||
import '../modules/task/bindings/task_binding.dart';
|
||||
import '../modules/task/bindings/task_files_binding.dart';
|
||||
import '../modules/task/views/task_files_view.dart';
|
||||
import '../modules/task/views/task_view.dart';
|
||||
|
||||
part 'app_routes.dart';
|
||||
|
||||
class AppPages {
|
||||
AppPages._();
|
||||
|
||||
static final routes = [
|
||||
GetPage(
|
||||
name: _Paths.ROOT,
|
||||
participatesInRootNavigator: true,
|
||||
transition: Transition.topLevel,
|
||||
// preventDuplicates: true,
|
||||
page: () => const RootView(),
|
||||
binding: RootBinding(),
|
||||
children: [
|
||||
GetPage(
|
||||
name: _Paths.HOME,
|
||||
// participatesInRootNavigator: true,
|
||||
// transition: Transition.topLevel,
|
||||
// preventDuplicates: true,
|
||||
page: () => const HomeView(),
|
||||
binding: HomeBinding(),
|
||||
children: [
|
||||
GetPage(
|
||||
name: _Paths.TASK,
|
||||
page: () => const TaskView(),
|
||||
transition: Transition.noTransition,
|
||||
binding: TaskBinding(),
|
||||
children: [
|
||||
GetPage(
|
||||
name: _Paths.TASK_FILES,
|
||||
page: () => const TaskFilesView(),
|
||||
transition: Transition.noTransition,
|
||||
binding: TaskFilesBinding()),
|
||||
]),
|
||||
GetPage(
|
||||
name: _Paths.EXTENSION,
|
||||
page: () => ExtensionView(),
|
||||
transition: Transition.noTransition,
|
||||
binding: ExtensionBinding()),
|
||||
GetPage(
|
||||
name: _Paths.SETTING,
|
||||
page: () => const SettingView(),
|
||||
transition: Transition.noTransition,
|
||||
binding: SettingBinding(),
|
||||
),
|
||||
]),
|
||||
GetPage(
|
||||
name: _Paths.LOGIN,
|
||||
page: () => const LoginView(),
|
||||
binding: LoginBinding(),
|
||||
transition: Transition.fadeIn,
|
||||
),
|
||||
GetPage(
|
||||
name: _Paths.CREATE,
|
||||
transition: Transition.downToUp,
|
||||
// preventDuplicates: true,
|
||||
page: () => CreateView(),
|
||||
binding: CreateBinding(),
|
||||
),
|
||||
GetPage(
|
||||
name: _Paths.QUICK_CREATE,
|
||||
transition: Transition.noTransition,
|
||||
page: () => const CreateDialogView(),
|
||||
binding: CreateBinding(),
|
||||
),
|
||||
GetPage(
|
||||
name: _Paths.REDIRECT,
|
||||
page: () => const RedirectView(),
|
||||
binding: RedirectBinding(),
|
||||
),
|
||||
]),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
part of 'app_pages.dart';
|
||||
// DO NOT EDIT. This is code generated via package:get_cli/get_cli.dart
|
||||
|
||||
abstract class Routes {
|
||||
Routes._();
|
||||
|
||||
static const ROOT = _Paths.ROOT;
|
||||
static const HOME = _Paths.HOME;
|
||||
static const CREATE = _Paths.CREATE;
|
||||
static const QUICK_CREATE = _Paths.QUICK_CREATE;
|
||||
static const LOGIN = _Paths.LOGIN;
|
||||
static const TASK = _Paths.HOME + _Paths.TASK;
|
||||
static const TASK_FILES = TASK + _Paths.TASK_FILES;
|
||||
static const EXTENSION = _Paths.HOME + _Paths.EXTENSION;
|
||||
static const SETTING = _Paths.HOME + _Paths.SETTING;
|
||||
static const REDIRECT = _Paths.REDIRECT;
|
||||
}
|
||||
|
||||
abstract class _Paths {
|
||||
_Paths._();
|
||||
|
||||
static const ROOT = '/';
|
||||
static const HOME = '/home';
|
||||
static const CREATE = '/create';
|
||||
static const QUICK_CREATE = '/quick-create';
|
||||
static const LOGIN = '/login';
|
||||
static const TASK = '/task';
|
||||
static const TASK_FILES = '/files';
|
||||
static const EXTENSION = '/extension';
|
||||
static const SETTING = '/setting';
|
||||
static const REDIRECT = '/redirect';
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/result.dart';
|
||||
import 'server.dart';
|
||||
|
||||
typedef HostCreateHandler = Future<void> Function(
|
||||
CreateTask createTask,
|
||||
bool silent,
|
||||
);
|
||||
|
||||
typedef HostForwardHandler = Future<dynamic> Function({
|
||||
required String path,
|
||||
required String method,
|
||||
dynamic data,
|
||||
Map<String, dynamic>? query,
|
||||
});
|
||||
|
||||
class HostRpcService {
|
||||
HostRpcService._();
|
||||
|
||||
static final HostRpcService instance = HostRpcService._();
|
||||
|
||||
RpcServerHandle? _server;
|
||||
|
||||
Future<void> start({
|
||||
required HostCreateHandler onCreate,
|
||||
required HostForwardHandler onForward,
|
||||
}) async {
|
||||
if (_server != null) {
|
||||
return;
|
||||
}
|
||||
_server = await startRpcServer(
|
||||
routes: {
|
||||
'/create': (ctx) async {
|
||||
final meta =
|
||||
ctx.request.headers['X-Gopeed-Host-Meta']?.firstOrNull ?? '{}';
|
||||
final jsonMeta = jsonDecode(meta);
|
||||
final silent = jsonMeta['silent'] as bool? ?? false;
|
||||
final params = await ctx.readText();
|
||||
final createTask = CreateTask.fromJson(_decodeParams(params));
|
||||
await onCreate(createTask, silent);
|
||||
},
|
||||
'/forward': (ctx) async {
|
||||
try {
|
||||
final body = await ctx.readJSON();
|
||||
final method = (body['method'] as String?)?.toUpperCase() ?? 'GET';
|
||||
final path = (body['path'] as String?) ?? '/';
|
||||
final data = body['data'];
|
||||
final query = body['query'] as Map<String, dynamic>?;
|
||||
final response = await onForward(
|
||||
path: path,
|
||||
method: method,
|
||||
data: data,
|
||||
query: query,
|
||||
);
|
||||
if (response is Map<String, dynamic>) {
|
||||
await ctx.writeJSON(response);
|
||||
} else {
|
||||
await ctx.writeJSON((response as dynamic).data);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e is DioException && e.response != null) {
|
||||
await ctx.writeJSON(e.response!.data);
|
||||
} else {
|
||||
await ctx.writeJSON(Result(code: 1, msg: e.toString()).toJson());
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
final server = _server;
|
||||
_server = null;
|
||||
if (server != null) {
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeParams(String params) {
|
||||
final safeParams = params.replaceAll('"', '').replaceAll(' ', '+');
|
||||
final paramsJson =
|
||||
String.fromCharCodes(base64Decode(base64.normalize(safeParams)));
|
||||
return jsonDecode(paramsJson);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dart_ipc/dart_ipc.dart';
|
||||
|
||||
import '../../util/util.dart';
|
||||
|
||||
/// RPC context class that contains request information and response methods
|
||||
class RpcContext {
|
||||
final HttpRequest request;
|
||||
final HttpResponse response;
|
||||
String? _bodyCache;
|
||||
|
||||
RpcContext(this.request, this.response);
|
||||
|
||||
/// Read and parse JSON request body
|
||||
Future<Map<String, dynamic>> readJSON() async {
|
||||
if (_bodyCache == null) {
|
||||
final content = <int>[];
|
||||
await for (var data in request) {
|
||||
content.addAll(data);
|
||||
}
|
||||
_bodyCache = String.fromCharCodes(content);
|
||||
}
|
||||
|
||||
if (_bodyCache!.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return jsonDecode(_bodyCache!) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<String> readText() async {
|
||||
if (_bodyCache == null) {
|
||||
final content = <int>[];
|
||||
await for (var data in request) {
|
||||
content.addAll(data);
|
||||
}
|
||||
_bodyCache = String.fromCharCodes(content);
|
||||
}
|
||||
|
||||
return _bodyCache ?? '';
|
||||
}
|
||||
|
||||
/// Write JSON response
|
||||
Future<void> writeJSON(Map<String, dynamic> data) async {
|
||||
response.headers.contentType = ContentType.json;
|
||||
response.write(jsonEncode(data));
|
||||
await response.close();
|
||||
}
|
||||
|
||||
/// Write error response
|
||||
Future<void> writeError(String message, [int statusCode = 500]) async {
|
||||
response.statusCode = statusCode;
|
||||
await writeJSON({'error': message});
|
||||
}
|
||||
}
|
||||
|
||||
/// Route handler type definition
|
||||
typedef RouteHandler = Future<void> Function(RpcContext ctx);
|
||||
|
||||
/// Route registry
|
||||
class RouteRegistry {
|
||||
final Map<String, RouteHandler> _routes = {};
|
||||
|
||||
/// Register a route
|
||||
void register(String path, RouteHandler handler) {
|
||||
_routes[path] = handler;
|
||||
}
|
||||
|
||||
/// Get route handler
|
||||
RouteHandler? getHandler(String path) {
|
||||
return _routes[path];
|
||||
}
|
||||
|
||||
/// Get all registered routes
|
||||
List<String> get routes => _routes.keys.toList();
|
||||
}
|
||||
|
||||
/// Start RPC server
|
||||
Future<void> startRpcServer([Map<String, RouteHandler>? routes]) async {
|
||||
String path;
|
||||
if (Util.isWindows()) {
|
||||
path = r'\\.\pipe\gopeed_host';
|
||||
} else {
|
||||
path = await Util.homePathJoin("gopeed_host.sock");
|
||||
// try to delete existing socket file
|
||||
final socketFile = File(path);
|
||||
if (await socketFile.exists()) {
|
||||
try {
|
||||
await socketFile.delete();
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create route registry
|
||||
final registry = RouteRegistry();
|
||||
|
||||
// Register provided routes
|
||||
if (routes != null) {
|
||||
routes.forEach((path, handler) {
|
||||
registry.register(path, handler);
|
||||
});
|
||||
}
|
||||
|
||||
final serverSocket = await bind(path);
|
||||
final httpServer = HttpServer.listenOn(serverSocket);
|
||||
|
||||
httpServer.forEach((HttpRequest request) async {
|
||||
final ctx = RpcContext(request, request.response);
|
||||
|
||||
try {
|
||||
// Get request path
|
||||
final requestPath = request.uri.path;
|
||||
// Find route handler
|
||||
final handler = registry.getHandler(requestPath);
|
||||
if (handler != null) {
|
||||
// Execute route handler
|
||||
await handler(ctx);
|
||||
} else {
|
||||
// 404 Route not found
|
||||
await ctx.writeError('Route not found: $requestPath', 404);
|
||||
}
|
||||
} catch (e) {
|
||||
await ctx.writeError('Internal server error: $e', 500);
|
||||
} finally {
|
||||
await request.response.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dart_ipc/dart_ipc.dart';
|
||||
|
||||
import '../../util/util.dart';
|
||||
|
||||
class RpcContext {
|
||||
final HttpRequest request;
|
||||
final HttpResponse response;
|
||||
String? _bodyCache;
|
||||
|
||||
RpcContext(this.request, this.response);
|
||||
|
||||
Future<Map<String, dynamic>> readJSON() async {
|
||||
if (_bodyCache == null) {
|
||||
final content = <int>[];
|
||||
await for (final data in request) {
|
||||
content.addAll(data);
|
||||
}
|
||||
_bodyCache = String.fromCharCodes(content);
|
||||
}
|
||||
|
||||
if (_bodyCache!.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return jsonDecode(_bodyCache!) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<String> readText() async {
|
||||
if (_bodyCache == null) {
|
||||
final content = <int>[];
|
||||
await for (final data in request) {
|
||||
content.addAll(data);
|
||||
}
|
||||
_bodyCache = String.fromCharCodes(content);
|
||||
}
|
||||
|
||||
return _bodyCache ?? '';
|
||||
}
|
||||
|
||||
Future<void> writeJSON(Map<String, dynamic> data) async {
|
||||
response.headers.contentType = ContentType.json;
|
||||
response.write(jsonEncode(data));
|
||||
}
|
||||
|
||||
Future<void> writeError(String message, [int statusCode = 500]) async {
|
||||
response.statusCode = statusCode;
|
||||
await writeJSON({'error': message});
|
||||
}
|
||||
}
|
||||
|
||||
typedef RouteHandler = Future<void> Function(RpcContext ctx);
|
||||
|
||||
class RouteRegistry {
|
||||
final Map<String, RouteHandler> _routes = {};
|
||||
|
||||
void register(String path, RouteHandler handler) {
|
||||
_routes[path] = handler;
|
||||
}
|
||||
|
||||
RouteHandler? getHandler(String path) {
|
||||
return _routes[path];
|
||||
}
|
||||
}
|
||||
|
||||
class RpcBinding {
|
||||
final String network;
|
||||
final String address;
|
||||
|
||||
const RpcBinding({
|
||||
required this.network,
|
||||
required this.address,
|
||||
});
|
||||
}
|
||||
|
||||
class RpcServerHandle {
|
||||
final RpcBinding binding;
|
||||
final HttpServer server;
|
||||
final Future<void> Function()? _cleanup;
|
||||
|
||||
RpcServerHandle({
|
||||
required this.binding,
|
||||
required this.server,
|
||||
Future<void> Function()? cleanup,
|
||||
}) : _cleanup = cleanup;
|
||||
|
||||
Future<void> close({bool force = true}) async {
|
||||
await server.close(force: force);
|
||||
if (_cleanup != null) {
|
||||
await _cleanup!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<RpcBinding> defaultHostRpcBinding() async {
|
||||
if (Util.isWindows()) {
|
||||
return const RpcBinding(
|
||||
network: 'pipe',
|
||||
address: r'\\.\pipe\gopeed_host',
|
||||
);
|
||||
}
|
||||
return RpcBinding(
|
||||
network: 'unix',
|
||||
address: await Util.homePathJoin('gopeed_host.sock'),
|
||||
);
|
||||
}
|
||||
|
||||
Future<RpcBinding> defaultWebViewRpcBinding() async {
|
||||
if (Util.supportUnixSocket()) {
|
||||
return RpcBinding(
|
||||
network: 'unix',
|
||||
address: await Util.homePathJoin('gopeed_webview.sock'),
|
||||
);
|
||||
}
|
||||
return const RpcBinding(
|
||||
network: 'tcp',
|
||||
address: '127.0.0.1:0',
|
||||
);
|
||||
}
|
||||
|
||||
Future<RpcServerHandle> startRpcServer({
|
||||
RpcBinding? binding,
|
||||
Map<String, RouteHandler>? routes,
|
||||
}) async {
|
||||
final rpcBinding = binding ?? await defaultHostRpcBinding();
|
||||
Future<void> Function()? cleanup;
|
||||
late final HttpServer httpServer;
|
||||
|
||||
switch (rpcBinding.network) {
|
||||
case 'pipe':
|
||||
final serverSocket = await bind(rpcBinding.address);
|
||||
httpServer = HttpServer.listenOn(serverSocket);
|
||||
break;
|
||||
case 'unix':
|
||||
final socketFile = File(rpcBinding.address);
|
||||
if (await socketFile.exists()) {
|
||||
try {
|
||||
await socketFile.delete();
|
||||
} catch (_) {}
|
||||
}
|
||||
final serverSocket = await bind(rpcBinding.address);
|
||||
httpServer = HttpServer.listenOn(serverSocket);
|
||||
cleanup = () async {
|
||||
if (await socketFile.exists()) {
|
||||
try {
|
||||
await socketFile.delete();
|
||||
} catch (_) {}
|
||||
}
|
||||
};
|
||||
break;
|
||||
case 'tcp':
|
||||
final separator = rpcBinding.address.lastIndexOf(':');
|
||||
if (separator <= 0 || separator == rpcBinding.address.length - 1) {
|
||||
throw ArgumentError('invalid tcp rpc address: ${rpcBinding.address}');
|
||||
}
|
||||
final host = rpcBinding.address.substring(0, separator);
|
||||
final port = int.parse(rpcBinding.address.substring(separator + 1));
|
||||
httpServer = await HttpServer.bind(host, port);
|
||||
break;
|
||||
default:
|
||||
throw ArgumentError('unsupported rpc network: ${rpcBinding.network}');
|
||||
}
|
||||
|
||||
final registry = RouteRegistry();
|
||||
routes?.forEach(registry.register);
|
||||
|
||||
httpServer.forEach((request) async {
|
||||
final ctx = RpcContext(request, request.response);
|
||||
try {
|
||||
final handler = registry.getHandler(request.uri.path);
|
||||
if (handler != null) {
|
||||
await handler(ctx);
|
||||
} else {
|
||||
await ctx.writeError('Route not found: ${request.uri.path}', 404);
|
||||
}
|
||||
} catch (e) {
|
||||
await ctx.writeError('Internal server error: $e', 500);
|
||||
} finally {
|
||||
await request.response.close();
|
||||
}
|
||||
});
|
||||
|
||||
var resolvedBinding = rpcBinding;
|
||||
if (rpcBinding.network == 'tcp') {
|
||||
resolvedBinding = RpcBinding(
|
||||
network: rpcBinding.network,
|
||||
address: '${httpServer.address.address}:${httpServer.port}',
|
||||
);
|
||||
}
|
||||
|
||||
return RpcServerHandle(
|
||||
binding: resolvedBinding,
|
||||
server: httpServer,
|
||||
cleanup: cleanup,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'webview_rpc_service.dart';
|
||||
|
||||
class WebViewRpcOverlay extends StatefulWidget {
|
||||
const WebViewRpcOverlay({super.key});
|
||||
|
||||
@override
|
||||
State<WebViewRpcOverlay> createState() => _WebViewRpcOverlayState();
|
||||
}
|
||||
|
||||
class _WebViewRpcOverlayState extends State<WebViewRpcOverlay> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
WebViewRpcService.instance.markOverlayReady();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<List<WebViewRpcPageSession>>(
|
||||
valueListenable: WebViewRpcService.instance.pages,
|
||||
builder: (context, pages, _) {
|
||||
if (pages.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return IgnorePointer(
|
||||
ignoring: false,
|
||||
child: Stack(
|
||||
children: pages
|
||||
.map((page) => _WebViewRpcPageView(page: page))
|
||||
.toList(growable: false),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WebViewRpcPageView extends StatefulWidget {
|
||||
const _WebViewRpcPageView({required this.page});
|
||||
|
||||
final WebViewRpcPageSession page;
|
||||
|
||||
@override
|
||||
State<_WebViewRpcPageView> createState() => _WebViewRpcPageViewState();
|
||||
}
|
||||
|
||||
class _WebViewRpcPageViewState extends State<_WebViewRpcPageView> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final page = widget.page;
|
||||
final content = page.buildWebView();
|
||||
|
||||
return Positioned.fill(
|
||||
child: Material(
|
||||
color: Colors.black54,
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: page.width > 0 ? page.width.toDouble() : 960,
|
||||
height: page.height > 0 ? page.height.toDouble() : 720,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
blurRadius: 24,
|
||||
color: Colors.black26,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
height: 44,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
alignment: Alignment.centerLeft,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: Text(
|
||||
page.title.isNotEmpty ? page.title : 'WebView',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
),
|
||||
Expanded(child: content),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,32 @@
|
||||
//for ios
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class LocationKeepAlive {
|
||||
static const _channel = MethodChannel('gopeed/location_keep_alive');
|
||||
|
||||
static Future<bool> requestPermission() async {
|
||||
if (!Platform.isIOS) return false;
|
||||
|
||||
try {
|
||||
final result = await _channel.invokeMethod<bool>('requestPermission');
|
||||
|
||||
return result ?? false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> start() async {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
await _channel.invokeMethod('start');
|
||||
}
|
||||
|
||||
static Future<void> stop() async {
|
||||
if (!Platform.isIOS) return;
|
||||
|
||||
await _channel.invokeMethod('stop');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'dart:async';
|
||||
import 'package:get/get.dart';
|
||||
import '../../../api/api.dart' as api;
|
||||
import '../../../api/model/task.dart';
|
||||
import '../modules/app/controllers/app_controller.dart';
|
||||
import 'location_keep_alive.dart';
|
||||
|
||||
class LocationKeepAliveCoordinator extends GetxService {
|
||||
Timer? _pollTimer;
|
||||
bool _reconciling = false;
|
||||
|
||||
/// Overridable for testing, defaults to reading from AppController.
|
||||
bool Function() keepAliveEnabledProvider = () => Get.find<AppController>()
|
||||
.downloaderConfig
|
||||
.value
|
||||
.extra
|
||||
.backgroundLocationKeepAlive;
|
||||
|
||||
/// Overridable for testing so polling tests don't need to wait 10s.
|
||||
Duration pollInterval = const Duration(seconds: 10);
|
||||
|
||||
bool get _keepAliveEnabled => keepAliveEnabledProvider();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
api.setTaskChangedListener(() {
|
||||
reconcile();
|
||||
});
|
||||
}
|
||||
|
||||
Future<int> _fetchGlobalRunningCount() async {
|
||||
try {
|
||||
final tasks = await api.getTasks([Status.running]);
|
||||
return tasks.length;
|
||||
} catch (_) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> reconcile() async {
|
||||
if (_reconciling) return;
|
||||
_reconciling = true;
|
||||
try {
|
||||
if (!_keepAliveEnabled) {
|
||||
await LocationKeepAlive.stop();
|
||||
return;
|
||||
}
|
||||
final count = await _fetchGlobalRunningCount();
|
||||
if (count < 0) return;
|
||||
if (count > 0) {
|
||||
await LocationKeepAlive.start();
|
||||
} else {
|
||||
await LocationKeepAlive.stop();
|
||||
}
|
||||
} finally {
|
||||
_reconciling = false;
|
||||
}
|
||||
}
|
||||
|
||||
void startPolling() {
|
||||
_pollTimer?.cancel();
|
||||
_pollTimer = Timer.periodic(pollInterval, (_) => reconcile());
|
||||
}
|
||||
|
||||
void stopPolling() {
|
||||
_pollTimer?.cancel();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
stopPolling();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../api/api.dart';
|
||||
import '../../api/model/task.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../modules/app/controllers/app_controller.dart';
|
||||
|
||||
class NotificationService extends GetxService {
|
||||
Timer? _timer;
|
||||
final Map<String, Status> _previousStatus = {};
|
||||
|
||||
final AppController appController = Get.find<AppController>();
|
||||
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_initNotifications();
|
||||
_startPolling();
|
||||
}
|
||||
|
||||
Future<void> _initNotifications() async {
|
||||
const DarwinInitializationSettings initializationSettingsDarwin =
|
||||
DarwinInitializationSettings(
|
||||
requestAlertPermission: false,
|
||||
requestBadgePermission: false,
|
||||
requestSoundPermission: false);
|
||||
|
||||
final LinuxInitializationSettings initializationSettingsLinux =
|
||||
LinuxInitializationSettings(
|
||||
defaultActionName: 'Open notification',
|
||||
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 (e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
final WindowsInitializationSettings initializationSettingsWindows =
|
||||
WindowsInitializationSettings(
|
||||
appName: 'Gopeed',
|
||||
appUserModelId: 'com.gopeed.gopeed',
|
||||
guid: '3c1bf3f4-3d91-4eaa-a33f-8705e71cf1ce', // unique guid
|
||||
iconPath: windowsIconPath,
|
||||
);
|
||||
|
||||
final InitializationSettings initializationSettings =
|
||||
InitializationSettings(
|
||||
macOS: initializationSettingsDarwin,
|
||||
linux: initializationSettingsLinux,
|
||||
windows: initializationSettingsWindows,
|
||||
);
|
||||
|
||||
await flutterLocalNotificationsPlugin.initialize(
|
||||
settings: initializationSettings,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_timer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
void _startPolling() {
|
||||
_timer = Timer.periodic(const Duration(seconds: 2), (timer) async {
|
||||
try {
|
||||
final config = appController.downloaderConfig.value;
|
||||
if (!config.extra.desktopNotification) {
|
||||
return;
|
||||
}
|
||||
|
||||
final tasks = await getTasks([
|
||||
Status.ready,
|
||||
Status.running,
|
||||
Status.pause,
|
||||
Status.wait,
|
||||
Status.error,
|
||||
Status.done,
|
||||
]);
|
||||
|
||||
for (var task in tasks) {
|
||||
final prevStatus = _previousStatus[task.id];
|
||||
final currentStatus = task.status;
|
||||
|
||||
if (prevStatus != null && prevStatus != currentStatus) {
|
||||
if (currentStatus == Status.done) {
|
||||
_showNotification(
|
||||
title: 'notificationTaskDone'.tr,
|
||||
body: task.name,
|
||||
);
|
||||
} else if (currentStatus == Status.error) {
|
||||
_showNotification(
|
||||
title: 'notificationTaskError'.tr,
|
||||
body: task.name,
|
||||
);
|
||||
}
|
||||
}
|
||||
_previousStatus[task.id] = currentStatus;
|
||||
}
|
||||
|
||||
// Clean up deleted tasks from map
|
||||
final currentTaskIds = tasks.map((t) => t.id).toSet();
|
||||
_previousStatus
|
||||
.removeWhere((id, status) => !currentTaskIds.contains(id));
|
||||
} catch (e) {
|
||||
// Ignored
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
int _notificationId = 0;
|
||||
|
||||
Future<void> _showNotification(
|
||||
{required String title, required String body}) async {
|
||||
const NotificationDetails notificationDetails = NotificationDetails(
|
||||
macOS: DarwinNotificationDetails(),
|
||||
linux: LinuxNotificationDetails(),
|
||||
windows: WindowsNotificationDetails(),
|
||||
);
|
||||
|
||||
await flutterLocalNotificationsPlugin.show(
|
||||
id: _notificationId++,
|
||||
title: title,
|
||||
body: body,
|
||||
notificationDetails: notificationDetails,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class Breadcrumb extends StatelessWidget {
|
||||
final List<String> items;
|
||||
final Function(int)? onItemTap;
|
||||
final TextStyle textStyle;
|
||||
final TextStyle activeTextStyle;
|
||||
|
||||
const Breadcrumb({
|
||||
super.key,
|
||||
required this.items,
|
||||
this.onItemTap,
|
||||
this.textStyle = const TextStyle(fontSize: 16),
|
||||
this.activeTextStyle =
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
List<Widget> children = [];
|
||||
for (int i = 0; i < items.length; i++) {
|
||||
children.add(
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
if (onItemTap != null) {
|
||||
onItemTap!(i);
|
||||
}
|
||||
},
|
||||
child: Text(
|
||||
items[i],
|
||||
style: i == items.length - 1 ? activeTextStyle : textStyle,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (i != items.length - 1) {
|
||||
children.add(const Text(" > "));
|
||||
}
|
||||
}
|
||||
return Row(
|
||||
children: [
|
||||
...(children.length == 1
|
||||
? children.sublist(0, 1)
|
||||
: children.sublist(0, 2)),
|
||||
children.length > 2
|
||||
? Expanded(
|
||||
child: SingleChildScrollView(
|
||||
reverse: true,
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: children.sublist(2),
|
||||
),
|
||||
),
|
||||
)
|
||||
: null,
|
||||
].where((e) => e != null).map((e) => e!).toList(),
|
||||
).paddingOnly(right: 12);
|
||||
}
|
||||
}
|
||||
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