Merge branch 'main' into fix/create-task-panel-mobile-ui

This commit is contained in:
Levi authored and GitHub committed 2026-09-09 23:27:11 +08:00
commit 9b9fd12884
36 files changed
+1884 -263

No files matched your search

@@ -1,6 +1,7 @@
package com.gopeed.gopeed
import com.gopeed.libgopeed.Libgopeed
import com.gopeed.libgopeed.InvokeResultListener
import com.gopeed.libgopeed.TaskEventListener
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
@@ -38,13 +39,23 @@ class MainActivity : FlutterActivity() {
"restartApiServer" -> result.success(Libgopeed.restartAPIServer())
"invoke" -> {
try {
result.success(
Libgopeed.invoke(
call.argument<String>("method") ?: "",
call.argument<String>("path") ?: "",
call.argument<String>("query") ?: "",
call.argument<String>("body") ?: "",
),
Libgopeed.invokeAsync(
call.argument<String>("method") ?: "",
call.argument<String>("path") ?: "",
call.argument<String>("query") ?: "",
call.argument<String>("body") ?: "",
call.argument<Number>("requestID")?.toLong() ?: 0L,
object : InvokeResultListener {
override fun onResult(requestID: Long, success: Boolean, payload: String?) {
runOnUiThread {
if (success) {
result.success(payload ?: "")
} else {
result.error("ERROR", payload ?: "InvokeAsync failed", null)
}
}
}
},
)
} catch (error: Exception) {
result.error("ERROR", error.message, null)
@@ -259,7 +259,7 @@ GetAPIServerState
StartAPIServer
StopAPIServer
RestartAPIServer
Invoke
InvokeAsync
FreeCString
SubscribeTaskEvents
```
@@ -268,9 +268,12 @@ Requirements:
- Use the cgo C-string ABI in the first phase. Reconsider pointer-and-length parameters only during a future ABI-breaking revision.
- Memory allocated by Go must be released with `FreeCString`.
- Dart-owned input memory must be released after the synchronous native call returns.
- `Invoke` returns the same Result JSON as REST; business errors do not use a separate ABI error model.
- Run blocking Desktop FFI work outside the Flutter UI isolate. Mobile MethodChannel handlers likewise run blocking Go work on a background task queue.
- `InvokeAsync` is the only native invocation entry point. Desktop and gomobile adapters both submit to the shared bounded-concurrency executor in `bind/native`.
- The shared executor uses `clamp(GOMAXPROCS * 2, 4, 32)` workers. Requests wait in FIFO order when every worker is busy; pool saturation is backpressure, not an API error.
- The Desktop adapter copies every Dart-owned input string before returning and completes through a `NativeCallable.listener` callback.
- Dart-owned input memory must be released after the non-blocking `InvokeAsync` native entry returns. Go-owned callback payloads remain valid until Dart copies them and calls `FreeCString`.
- `InvokeAsync` returns the same Result JSON as REST through its callback; business errors do not use a separate ABI error model.
- The Desktop bridge isolate owns the dynamic library and native callbacks, decodes callback JSON, and forwards sendable Dart values to the UI isolate. Mobile MethodChannel handlers run on background task queues, while invoke completion is delivered through the shared Go callback flow.
- Dart bindings are generated from `include/libgopeed.h` with `ffigen`. Every exported Desktop symbol must be added to the `ffigen.functions.include` allowlist.
- Never hand-edit `lib/core/ffi/libgopeed_bind.dart`; regenerate it with `flutter pub run ffigen` after changing the C header.
@@ -285,14 +288,14 @@ GetAPIServerState()
StartAPIServer()
StopAPIServer()
RestartAPIServer()
Invoke(method, path, query, body)
InvokeAsync(method, path, query, body, requestID, listener)
SubscribeTaskEvents(mask, listener)
```
Flutter bridge rules:
- Normal calls use MethodChannel.
- Android performs normal calls on a background task queue.
- Normal calls use MethodChannel, while `InvokeAsync` completes the pending MethodChannel result through a gomobile listener.
- Android and iOS run the Libgopeed MethodChannel handler on a serial background task queue; callback adapters marshal completion back to the platform UI thread.
- Events reuse the same MethodChannel through the reverse `taskEvent` message.
- Kotlin and Swift contain no business logic. They only forward arguments, dispatch callbacks to the UI thread, and translate errors.
@@ -589,8 +592,8 @@ Flutter converts all of them into `GopeedException`. Components do not handle Di
### 11.3 Platform smoke tests
- Windows, macOS, Linux: startup, Invoke, events, shutdown, and repeated startup.
- Android, iOS: gomobile Invoke, reverse MethodChannel events, and background/foreground transitions.
- Windows, macOS, Linux: startup, InvokeAsync, events, shutdown, and repeated startup.
- Android, iOS: gomobile InvokeAsync callbacks, reverse MethodChannel events, and background/foreground transitions.
- Web: REST, login, proxy, and task-file downloads.
- Native: enabling and disabling REST does not interrupt download tasks.
@@ -605,7 +608,7 @@ Flutter converts all of them into `GopeedException`. Components do not handle Di
### Phase 2: Native in-process calls — implemented on this branch
- Integrate the FFI Transport on Desktop.
- Extend gomobile Invoke and MethodChannel on Mobile.
- Extend gomobile InvokeAsync callbacks and MethodChannel on Mobile.
- Move Flutter API calls to the unified Transport so each typed method is maintained once.
- Do not create a socket listener by default on native clients.
+33 -7
View File
@@ -12,6 +12,8 @@
#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
extern size_t _GoStringLen(_GoString_ s);
extern const char *_GoStringPtr(_GoString_ s);
#endif
#endif
@@ -19,6 +21,24 @@ typedef struct { const char *p; ptrdiff_t n; } _GoString_;
/* Start of preamble from import "C" comments. */
#line 3 "main.go"
#include <stdlib.h>
#include <stdint.h>
typedef void (*TaskEventCallback)(char* payload);
typedef void (*InvokeResultCallback)(uint64_t request_id, int success, char* payload);
static void callTaskEventCallback(uintptr_t callback, char* payload) {
((TaskEventCallback)callback)(payload);
}
static void callInvokeResultCallback(uintptr_t callback, uint64_t request_id, int success, char* payload) {
((InvokeResultCallback)callback)(request_id, success, payload);
}
#line 1 "cgo-generated-wrapper"
/* End of preamble from import "C" comments. */
@@ -44,10 +64,16 @@ typedef size_t GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
#ifdef _MSC_VER
#if !defined(__cplusplus) || _MSVC_LANG <= 201402L
#include <complex.h>
typedef _Fcomplex GoComplex64;
typedef _Dcomplex GoComplex128;
#else
#include <complex>
typedef std::complex<float> GoComplex64;
typedef std::complex<double> GoComplex128;
#endif
#else
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;
#endif
@@ -81,13 +107,13 @@ struct Start_return {
char* r1;
};
extern struct Start_return Start(char* cfg);
extern void Stop();
extern char* GetAPIServerState();
extern char* StartAPIServer();
extern char* StopAPIServer();
extern char* RestartAPIServer();
extern char* Invoke(char* method, char* path, char* query, char* body);
extern void SubscribeTaskEvents(GoUint64 mask, GoUintptr callback);
extern void Stop(void);
extern char* GetAPIServerState(void);
extern char* StartAPIServer(void);
extern char* StopAPIServer(void);
extern char* RestartAPIServer(void);
extern void InvokeAsync(char* method, char* path, char* query, char* body, long long unsigned int requestID, uintptr_t callback);
extern void SubscribeTaskEvents(long long unsigned int mask, uintptr_t callback);
extern void FreeCString(char* value);
#ifdef __cplusplus
+1 -1
View File
@@ -1,4 +1,4 @@
platform :ios, '13.0'
platform :ios, '14.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
@@ -693,7 +693,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
@@ -823,7 +823,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -874,7 +874,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
+6 -2
View File
@@ -14,10 +14,13 @@ import UIKit
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
let messenger = engineBridge.applicationRegistrar.messenger()
let libgopeedTaskQueue = messenger.makeBackgroundTaskQueue?()
let libgopeedChannel = FlutterMethodChannel(
name: "gopeed.com/libgopeed",
binaryMessenger: messenger
binaryMessenger: messenger,
codec: FlutterStandardMethodCodec.sharedInstance(),
taskQueue: libgopeedTaskQueue
)
let taskEventForwarder = GopeedTaskEventForwarder(channel: libgopeedChannel)
libgopeedChannel.setMethodCallHandler { call, result in
@@ -56,7 +59,8 @@ import UIKit
let path = arguments?["path"] as? String ?? ""
let query = arguments?["query"] as? String ?? ""
let body = arguments?["body"] as? String ?? ""
result(LibgopeedInvoke(method, path, query, body))
let requestID = (arguments?["requestID"] as? NSNumber)?.int64Value ?? 0
GopeedInvokeAsyncWithResult(method, path, query, body, requestID, result)
case "subscribeTaskEvents":
let arguments = call.arguments as? [String: Any]
let mask = (arguments?["mask"] as? NSNumber)?.int64Value ?? 0
@@ -13,4 +13,12 @@ FOUNDATION_EXPORT void GopeedSubscribeTaskEventsWithForwarder(
int64_t mask,
GopeedTaskEventForwarder * _Nullable listener);
FOUNDATION_EXPORT void GopeedInvokeAsyncWithResult(
NSString *method,
NSString *path,
NSString *query,
NSString *body,
int64_t requestID,
FlutterResult result);
NS_ASSUME_NONNULL_END
@@ -8,6 +8,45 @@
@end
@interface GopeedInvokeResultForwarder : NSObject <LibgopeedInvokeResultListener>
@property(nonatomic, copy, nullable) FlutterResult result;
- (instancetype)initWithResult:(FlutterResult)result;
@end
@implementation GopeedInvokeResultForwarder
- (instancetype)initWithResult:(FlutterResult)result {
self = [super init];
if (self) {
_result = [result copy];
}
return self;
}
- (void)onResult:(int64_t)requestID
success:(BOOL)success
payload:(NSString * _Nullable)payload {
FlutterResult result = self.result;
self.result = nil;
if (result == nil) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
if (success) {
result(payload ?: @"");
} else {
result([FlutterError errorWithCode:@"ERROR"
message:payload ?: @"InvokeAsync failed"
details:nil]);
}
});
}
@end
@implementation GopeedTaskEventForwarder
- (instancetype)initWithChannel:(FlutterMethodChannel *)channel {
@@ -33,3 +72,15 @@ void GopeedSubscribeTaskEventsWithForwarder(
GopeedTaskEventForwarder * _Nullable listener) {
LibgopeedSubscribeTaskEvents(mask, listener);
}
void GopeedInvokeAsyncWithResult(
NSString *method,
NSString *path,
NSString *query,
NSString *body,
int64_t requestID,
FlutterResult result) {
GopeedInvokeResultForwarder *forwarder =
[[GopeedInvokeResultForwarder alloc] initWithResult:result];
LibgopeedInvokeAsync(method, path, query, body, requestID, forwarder);
}
@@ -11,6 +11,7 @@ import 'task_event.dart';
class LibgopeedChannel implements LibgopeedInterface {
static const _channel = MethodChannel('gopeed.com/libgopeed');
final _taskEvents = StreamController<TaskEvent>.broadcast();
int _requestID = 0;
LibgopeedChannel() {
_channel.setMethodCallHandler((call) async {
@@ -50,7 +51,9 @@ class LibgopeedChannel implements LibgopeedInterface {
@override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final requestID = _requestID++;
final result = await _channel.invokeMethod<String>('invoke', {
'requestID': requestID,
'method': method,
'path': path,
'query': query,
+10 -64
View File
@@ -1,10 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import '../ffi/libgopeed_bind.dart';
import '../ffi/libgopeed_worker.dart';
import 'api_server_state.dart';
import 'libgopeed_interface.dart';
@@ -12,51 +8,22 @@ import 'start_config.dart';
import 'task_event.dart';
class LibgopeedFFi implements LibgopeedInterface {
late LibgopeedBind _libgopeed;
LibgopeedFFi() {
_worker.taskEvents.listen(_onTaskEvent, onError: _taskEvents.addError);
}
final _taskEvents = StreamController<TaskEvent>.broadcast();
final _worker = LibgopeedWorker();
late final NativeCallable<Void Function(Pointer<Char>)> _taskEventCallback;
LibgopeedFFi(LibgopeedBind libgopeed) {
_libgopeed = libgopeed;
_taskEventCallback = NativeCallable<Void Function(Pointer<Char>)>.listener(_onTaskEvent);
}
void _onTaskEvent(Pointer<Char> payload) {
try {
final decoded = jsonDecode(payload.cast<Utf8>().toDartString()) as Map<String, dynamic>;
_taskEvents.add(TaskEvent.fromJson(decoded));
} finally {
_libgopeed.FreeCString(payload);
}
void _onTaskEvent(Map<String, dynamic> payload) {
_taskEvents.add(TaskEvent.fromJson(payload));
}
@override
Future<int> start(StartConfig cfg) {
var completer = Completer<int>();
final cfgPtr = jsonEncode(cfg).toNativeUtf8();
try {
final result = _libgopeed.Start(cfgPtr.cast());
if (result.r1 != nullptr) {
final message = result.r1.cast<Utf8>().toDartString();
_libgopeed.FreeCString(result.r1);
completer.completeError(Exception(message));
} else {
completer.complete(result.r0);
}
} finally {
malloc.free(cfgPtr);
}
return completer.future;
}
Future<int> start(StartConfig cfg) => _worker.start(jsonEncode(cfg));
@override
Future<void> stop() {
var completer = Completer<void>();
_libgopeed.Stop();
completer.complete();
return completer.future;
}
Future<void> stop() => _worker.stop();
Future<ApiServerOperationResult> _apiServerOperation(String operation) async {
final payload = await _worker.apiServer(operation);
@@ -77,33 +44,12 @@ class LibgopeedFFi implements LibgopeedInterface {
@override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final methodPtr = method.toNativeUtf8();
final pathPtr = path.toNativeUtf8();
final queryPtr = query.toNativeUtf8();
final bodyPtr = body.toNativeUtf8();
Pointer<Char>? resultPtr;
try {
resultPtr = _libgopeed.Invoke(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast());
if (resultPtr == nullptr) {
throw StateError('Gopeed Invoke returned a null response');
}
return resultPtr.cast<Utf8>().toDartString();
} finally {
malloc.free(methodPtr);
malloc.free(pathPtr);
malloc.free(queryPtr);
malloc.free(bodyPtr);
if (resultPtr != null && resultPtr != nullptr) {
_libgopeed.FreeCString(resultPtr);
}
}
return jsonEncode(await _worker.invoke(method, path, query, body));
}
@override
Stream<TaskEvent> get taskEvents => _taskEvents.stream;
@override
Future<void> subscribeTaskEvents(Set<TaskEventType> events) async {
_libgopeed.SubscribeTaskEvents(events.mask, events.isEmpty ? 0 : _taskEventCallback.nativeFunction.address);
}
Future<void> subscribeTaskEvents(Set<TaskEventType> events) => _worker.subscribeTaskEvents(events.mask);
}
@@ -1,6 +1,4 @@
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import '../../util/util.dart';
import '../common/libgopeed_channel.dart';
@@ -9,7 +7,6 @@ import '../common/libgopeed_interface.dart';
import '../common/api_server_state.dart';
import '../common/start_config.dart';
import '../common/task_event.dart';
import '../ffi/libgopeed_bind.dart';
import '../libgopeed_boot.dart';
LibgopeedBoot create() => LibgopeedBootNative();
@@ -19,17 +16,7 @@ class LibgopeedBootNative implements LibgopeedBoot {
LibgopeedBootNative() {
if (Util.isDesktop()) {
var libName = "libgopeed.";
if (Platform.isWindows) {
libName += "dll";
}
if (Platform.isMacOS) {
libName += "dylib";
}
if (Platform.isLinux) {
libName += "so";
}
_libgopeed = LibgopeedFFi(LibgopeedBind(DynamicLibrary.open(libName)));
_libgopeed = LibgopeedFFi();
} else {
_libgopeed = LibgopeedChannel();
}
+28 -15
View File
@@ -30,53 +30,67 @@ class LibgopeedBind {
late final _StopPtr = _lookup<ffi.NativeFunction<ffi.Void Function()>>('Stop');
late final _Stop = _StopPtr.asFunction<void Function()>();
ffi.Pointer<ffi.Char> GetAPIServerState() => _GetAPIServerState();
ffi.Pointer<ffi.Char> GetAPIServerState() {
return _GetAPIServerState();
}
late final _GetAPIServerStatePtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('GetAPIServerState');
late final _GetAPIServerState = _GetAPIServerStatePtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> StartAPIServer() => _StartAPIServer();
ffi.Pointer<ffi.Char> StartAPIServer() {
return _StartAPIServer();
}
late final _StartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('StartAPIServer');
late final _StartAPIServer = _StartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> StopAPIServer() => _StopAPIServer();
ffi.Pointer<ffi.Char> StopAPIServer() {
return _StopAPIServer();
}
late final _StopAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('StopAPIServer');
late final _StopAPIServer = _StopAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> RestartAPIServer() => _RestartAPIServer();
ffi.Pointer<ffi.Char> RestartAPIServer() {
return _RestartAPIServer();
}
late final _RestartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('RestartAPIServer');
late final _RestartAPIServer = _RestartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> Invoke(
void InvokeAsync(
ffi.Pointer<ffi.Char> method,
ffi.Pointer<ffi.Char> path,
ffi.Pointer<ffi.Char> query,
ffi.Pointer<ffi.Char> body,
int requestID,
int callback,
) {
return _Invoke(method, path, query, body);
return _InvokeAsync(method, path, query, body, requestID, callback);
}
late final _InvokePtr =
late final _InvokeAsyncPtr =
_lookup<
ffi.NativeFunction<
ffi.Pointer<ffi.Char> Function(
ffi.Void Function(
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.UnsignedLongLong,
ffi.UintPtr,
)
>
>('Invoke');
late final _Invoke =
_InvokePtr.asFunction<
ffi.Pointer<ffi.Char> Function(
>('InvokeAsync');
late final _InvokeAsync =
_InvokeAsyncPtr.asFunction<
void Function(
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
int,
int,
)
>();
@@ -84,9 +98,8 @@ class LibgopeedBind {
return _SubscribeTaskEvents(mask, callback);
}
late final _SubscribeTaskEventsPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Uint64, ffi.UintPtr)>>(
'SubscribeTaskEvents',
);
late final _SubscribeTaskEventsPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.UnsignedLongLong, ffi.UintPtr)>>('SubscribeTaskEvents');
late final _SubscribeTaskEvents = _SubscribeTaskEventsPtr.asFunction<void Function(int, int)>();
void FreeCString(ffi.Pointer<ffi.Char> value) {
+161 -37
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
@@ -7,38 +8,74 @@ import 'package:ffi/ffi.dart';
import 'libgopeed_bind.dart';
typedef _InvokeResultNative = Void Function(Uint64 requestID, Int32 success, Pointer<Char> payload);
typedef _TaskEventNative = Void Function(Pointer<Char> payload);
class LibgopeedWorker {
LibgopeedWorker() {
factory LibgopeedWorker() => _instance;
LibgopeedWorker._() {
_receivePort.listen(_handleWorkerMessage);
_errorPort.listen(_handleWorkerError);
_isolateReady = Isolate.spawn(_workerMain, _receivePort.sendPort, onError: _errorPort.sendPort);
}
static final LibgopeedWorker _instance = LibgopeedWorker._();
final ReceivePort _receivePort = ReceivePort();
final ReceivePort _errorPort = ReceivePort();
final Map<int, Completer<String>> _pending = {};
final Map<int, Completer<Object?>> _pending = {};
final StreamController<Map<String, dynamic>> _taskEvents = StreamController<Map<String, dynamic>>.broadcast();
late final Future<Isolate> _isolateReady;
final Completer<SendPort> _sendPort = Completer<SendPort>();
Future<void>? _stopFuture;
int _requestID = 0;
bool _stopping = false;
bool _stopped = false;
Future<String> invoke(String method, String path, String query, String body) async {
await _isolateReady;
final sendPort = await _sendPort.future;
final requestID = _requestID++;
final completer = Completer<String>();
_pending[requestID] = completer;
sendPort.send(['invoke', requestID, method, path, query, body]);
return completer.future;
Stream<Map<String, dynamic>> get taskEvents => _taskEvents.stream;
Future<int> start(String config) => _request<int>('start', [config]);
Future<void> stop() => _stopFuture ??= _stop();
Future<void> _stop() async {
_stopping = true;
// The native bridge owns the bounded drain. Sending Stop immediately is
// important because an InvokeAsync handler such as Resolve may never return.
await _request<Object?>('stop', const [], allowWhileStopping: true);
_stopped = true;
final stoppingError = StateError('libgopeed worker stopped before the request completed');
for (final completer in _pending.values) {
completer.completeError(stoppingError);
}
_pending.clear();
await _taskEvents.close();
_receivePort.close();
_errorPort.close();
}
Future<String> apiServer(String operation) async {
Future<Object?> invoke(String method, String path, String query, String body) {
return _request<Object?>('invoke', [method, path, query, body]);
}
Future<String> apiServer(String operation) => _request<String>('apiServer', [operation]);
Future<void> subscribeTaskEvents(int mask) async {
await _request<Object?>('subscribeTaskEvents', [mask]);
}
Future<T> _request<T>(String type, List<Object?> arguments, {bool allowWhileStopping = false}) async {
if (_stopped || (_stopping && !allowWhileStopping)) {
throw StateError('libgopeed worker is stopping');
}
await _isolateReady;
final sendPort = await _sendPort.future;
final requestID = _requestID++;
final completer = Completer<String>();
final completer = Completer<Object?>();
_pending[requestID] = completer;
sendPort.send(['apiServer', requestID, operation]);
return completer.future;
sendPort.send([type, requestID, ...arguments]);
return (await completer.future) as T;
}
void _handleWorkerMessage(dynamic message) {
@@ -47,13 +84,18 @@ class LibgopeedWorker {
return;
}
final response = message as List<dynamic>;
final requestID = response[0] as int;
final completer = _pending.remove(requestID);
if (completer == null) return;
if (response[1] as bool) {
completer.complete(response[2] as String);
} else {
completer.completeError(StateError(response[2] as String));
switch (response[0] as String) {
case 'response':
final requestID = response[1] as int;
final completer = _pending.remove(requestID);
if (completer == null) return;
if (response[2] as bool) {
completer.complete(response[3]);
} else {
completer.completeError(StateError(response[3] as String));
}
case 'taskEvent':
_taskEvents.add((response[1] as Map<Object?, Object?>).cast<String, dynamic>());
}
}
@@ -65,35 +107,117 @@ class LibgopeedWorker {
completer.completeError(error);
}
_pending.clear();
_taskEvents.addError(error);
}
static void _workerMain(SendPort mainSendPort) {
final requests = ReceivePort();
final bindings = LibgopeedBind(DynamicLibrary.open(_libraryName()));
late final NativeCallable<_InvokeResultNative> invokeResultCallback;
late final NativeCallable<_TaskEventNative> taskEventCallback;
invokeResultCallback = NativeCallable<_InvokeResultNative>.listener((
int requestID,
int success,
Pointer<Char> payload,
) {
if (payload == nullptr) {
mainSendPort.send(['response', requestID, false, 'Gopeed InvokeAsync returned a null response']);
return;
}
try {
final result = payload.cast<Utf8>().toDartString();
mainSendPort.send(['response', requestID, success != 0, success != 0 ? jsonDecode(result) : result]);
} catch (error) {
mainSendPort.send(['response', requestID, false, error.toString()]);
} finally {
bindings.FreeCString(payload);
}
});
taskEventCallback = NativeCallable<_TaskEventNative>.listener((Pointer<Char> payload) {
if (payload == nullptr) return;
try {
final event = jsonDecode(payload.cast<Utf8>().toDartString()) as Map<String, dynamic>;
mainSendPort.send(['taskEvent', event]);
} finally {
bindings.FreeCString(payload);
}
});
mainSendPort.send(requests.sendPort);
requests.listen((dynamic message) {
final request = message as List<dynamic>;
final type = request[0] as String;
final requestID = request[1] as int;
try {
final response = switch (type) {
'invoke' => _invoke(
if (type == 'invoke') {
try {
_invokeAsync(
bindings,
invokeResultCallback.nativeFunction.address,
requestID,
request[2] as String,
request[3] as String,
request[4] as String,
request[5] as String,
),
);
} catch (error) {
mainSendPort.send(['response', requestID, false, error.toString()]);
}
return;
}
try {
final response = switch (type) {
'start' => _start(bindings, request[2] as String),
'stop' => _stopNative(bindings),
'apiServer' => _apiServer(bindings, request[2] as String),
'subscribeTaskEvents' => _subscribeTaskEvents(
bindings,
taskEventCallback.nativeFunction.address,
request[2] as int,
),
_ => throw StateError('Unknown libgopeed worker request: $type'),
};
mainSendPort.send([requestID, true, response]);
mainSendPort.send(['response', requestID, true, response]);
if (type == 'stop') {
invokeResultCallback.close();
taskEventCallback.close();
requests.close();
}
} catch (error) {
mainSendPort.send([requestID, false, error.toString()]);
mainSendPort.send(['response', requestID, false, error.toString()]);
}
});
}
static int _start(LibgopeedBind bindings, String config) {
final configPtr = config.toNativeUtf8();
try {
final result = bindings.Start(configPtr.cast());
if (result.r1 != nullptr) {
try {
throw StateError(result.r1.cast<Utf8>().toDartString());
} finally {
bindings.FreeCString(result.r1);
}
}
return result.r0;
} finally {
malloc.free(configPtr);
}
}
static Object? _stopNative(LibgopeedBind bindings) {
bindings.Stop();
return null;
}
static Object? _subscribeTaskEvents(LibgopeedBind bindings, int callback, int mask) {
bindings.SubscribeTaskEvents(mask, mask == 0 ? 0 : callback);
return null;
}
static String _apiServer(LibgopeedBind bindings, String operation) {
final resultPtr = switch (operation) {
'get' => bindings.GetAPIServerState(),
@@ -112,26 +236,26 @@ class LibgopeedWorker {
}
}
static String _invoke(LibgopeedBind bindings, String method, String path, String query, String body) {
static void _invokeAsync(
LibgopeedBind bindings,
int callback,
int requestID,
String method,
String path,
String query,
String body,
) {
final methodPtr = method.toNativeUtf8();
final pathPtr = path.toNativeUtf8();
final queryPtr = query.toNativeUtf8();
final bodyPtr = body.toNativeUtf8();
Pointer<Char>? resultPtr;
try {
resultPtr = bindings.Invoke(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast());
if (resultPtr == nullptr) {
throw StateError('Gopeed Invoke returned a null response');
}
return resultPtr.cast<Utf8>().toDartString();
bindings.InvokeAsync(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast(), requestID, callback);
} finally {
malloc.free(methodPtr);
malloc.free(pathPtr);
malloc.free(queryPtr);
malloc.free(bodyPtr);
if (resultPtr != null && resultPtr != nullptr) {
bindings.FreeCString(resultPtr);
}
}
}
@@ -2,9 +2,9 @@ import 'dart:convert';
import 'package:dio/dio.dart';
import '../../../libgopeed_boot.dart';
import '../../../ffi/libgopeed_worker.dart';
import '../../../../util/util.dart';
import '../../../ffi/libgopeed_worker.dart';
import '../../../libgopeed_boot.dart';
import '../gopeed_transport.dart';
GopeedTransport createTransport(GopeedTransportConfig config) => NativeGopeedTransport();
@@ -32,14 +32,16 @@ class NativeGopeedTransport implements GopeedTransport {
}) async {
final request = _RequestParts.from(path, queryParameters);
final requestBody = data == null ? '' : jsonEncode(data);
final payload = _ffiWorker != null
? await _ffiWorker.invoke(method.toUpperCase(), request.path, request.query, requestBody)
: await LibgopeedBoot.instance.invoke(
method.toUpperCase(),
request.path,
query: request.query,
body: requestBody,
);
final worker = _ffiWorker;
if (worker != null) {
return worker.invoke(method.toUpperCase(), request.path, request.query, requestBody);
}
final payload = await LibgopeedBoot.instance.invoke(
method.toUpperCase(),
request.path,
query: request.query,
body: requestBody,
);
return jsonDecode(payload);
}
@@ -210,7 +210,7 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
}
Future<void> _installFromFolder() async {
final folder = await FilePicker.platform.getDirectoryPath();
final folder = await FilePicker.getDirectoryPath();
if (folder == null || folder.isEmpty) return;
await _runAction(() => ref.read(extensionsControllerProvider.notifier).installFromUrl(folder, devInstall: true));
}
@@ -1378,8 +1378,8 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
initialValue: index == null ? '' : paths[index],
pickPath: Util.isDesktop()
? () async {
final result = await FilePicker.platform.pickFiles();
return result?.files.firstOrNull?.path;
final file = await FilePicker.pickFile();
return file?.path;
}
: null,
);
@@ -95,11 +95,21 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
super.initState();
_urlController.addListener(_handleUrlChanged);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final task = widget.initialTask ?? ref.read(pendingCreateTaskProvider);
_applyInitialTask(task);
if (widget.initialTask == null) {
ref.read(pendingCreateTaskProvider.notifier).clear();
}
if (widget.windowController == null && widget.initialTask == null) {
// Navigating to /create again reuses this page, so consume subsequent
// browser/share requests as well as the initial pending task.
ref.listenManual(pendingCreateTaskProvider, (_, next) {
if (next == null) return;
ref.read(pendingCreateTaskProvider.notifier).clear();
_applyInitialTask(next);
});
}
if (task == null || _urlController.text.trim().isEmpty) {
unawaited(_loadClipboardUrl());
}
@@ -181,6 +191,13 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
final opts = task.opts;
setState(() {
if (req?.url.isNotEmpty == true) {
_fileDataUri = '';
_renameController.clear();
_httpMethod = 'GET';
_httpBody = '';
_replaceHttpHeaders(const {'User-Agent': '', 'Cookie': '', 'Referer': ''});
_trackersController.clear();
_protocolTab = 0;
_urlController.text = req!.url;
_initialRawUrl = req.rawUrl;
_initialLabels = req.labels == null ? null : Map<String, String>.of(req.labels!);
@@ -754,15 +771,10 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}
Future<void> _pickTorrentFile() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: const ['torrent'],
withData: kIsWeb,
);
final file = result?.files.single;
final file = await FilePicker.pickFile(type: FileType.custom, allowedExtensions: const ['torrent']);
if (file == null) return;
await _applyTorrentFile(name: file.name, filePath: file.path, bytes: file.bytes);
await _applyTorrentFile(name: file.name, filePath: file.path, readBytes: file.readAsBytes);
}
Future<void> _handleDroppedTorrent(DropDoneDetails details) async {
@@ -109,7 +109,7 @@ class _TaskFileManagerViewState extends State<TaskFileManagerView> {
try {
final renderBox = actionContext.findRenderObject();
final origin = renderBox is RenderBox ? renderBox.localToGlobal(Offset.zero) & renderBox.size : null;
await Share.shareXFiles([XFile(_localPath(entry))], sharePositionOrigin: origin);
await SharePlus.instance.share(ShareParams(files: [XFile(_localPath(entry))], sharePositionOrigin: origin));
} catch (error) {
if (mounted) showAppToast(context, error.toString(), type: AppToastType.error);
}
File diff suppressed because it is too large. Load diff
@@ -58,7 +58,7 @@ class DownloadDirectoryPicker {
return _pickAndroid(context, currentPath: currentPath);
}
if (_platform == TargetPlatform.iOS) return null;
return FilePicker.platform.getDirectoryPath();
return FilePicker.getDirectoryPath();
}
static Future<String?> _pickAndroid(BuildContext context, {required String currentPath}) async {
@@ -251,7 +251,7 @@ Future<String?> _getManifestPath(Browser browser) async {
Future<bool> _checkWindowsRegistry(String keyPath) async {
try {
final key = Registry.openPath(RegistryHive.localMachine, path: keyPath);
final key = LOCAL_MACHINE.open(keyPath);
key.close();
return true;
} catch (e) {
@@ -26,7 +26,7 @@ void doRegisterUrlScheme(String scheme) {
void doUnregisterUrlScheme(String scheme) {
if (Util.isWindows()) {
Registry.currentUser.deleteKey('Software\\Classes\\$scheme', recursive: true);
CURRENT_USER.removeSubkey('Software\\Classes\\$scheme');
return;
}
@@ -66,8 +66,8 @@ void doUnregisterDefaultTorrentClient() {
if (Util.isWindows()) {
doUnregisterUrlScheme("magnet");
Registry.currentUser.deleteKey(_torrentRegKey, recursive: true);
Registry.currentUser.deleteKey(_torrentAppRegKey, recursive: true);
CURRENT_USER.removeSubkey(_torrentRegKey);
CURRENT_USER.removeSubkey(_torrentAppRegKey);
return;
}
+14 -12
View File
@@ -3,12 +3,14 @@ import 'package:win32_registry/win32_registry.dart';
/// Check registry key
/// If the key does not exist or the value is different, return false
bool checkRegistry(String keyPath, String valueName, String value) {
RegistryKey regKey;
RegistryKey? regKey;
try {
regKey = Registry.openPath(RegistryHive.currentUser, path: keyPath);
return regKey.getValueAsString(valueName) == value;
regKey = CURRENT_USER.open(keyPath);
return regKey.getString(valueName) == value;
} catch (e) {
return false;
} finally {
regKey?.close();
}
}
@@ -16,15 +18,15 @@ bool checkRegistry(String keyPath, String valueName, String value) {
/// If the key does not exist, create it
/// If the value does not exist or is different, update it
void upsertRegistry(String keyPath, String valueName, String value) {
RegistryKey regKey;
final regKey = CURRENT_USER.create(
keyPath,
config: const RegistryOpenConfig(access: RegistryAccess.all, create: true),
);
try {
regKey = Registry.openPath(RegistryHive.currentUser, path: keyPath, desiredAccessRights: AccessRights.allAccess);
} catch (e) {
regKey = Registry.currentUser.createKey(keyPath);
if (regKey.getString(valueName) != value) {
regKey.setValue(valueName, RegistryValue.string(value));
}
} finally {
regKey.close();
}
if (regKey.getValueAsString(valueName) != value) {
regKey.createValue(RegistryValue(valueName, RegistryValueType.string, value));
}
regKey.close();
}
+94 -37
View File
@@ -17,6 +17,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "10.0.1"
android_file_picker:
dependency: transitive
description:
name: android_file_picker
sha256: "0d84bb91fb78af33756107f00cf71ee084474169d481b882b335c3006077a913"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
animation_kit:
dependency: transitive
description:
@@ -245,10 +253,10 @@ packages:
dependency: "direct main"
description:
name: dart_ipc
sha256: "6cad558cda5304017c1f581df4c96fd4f8e4ee212aae7bfa4357716236faa9ba"
sha256: "3b372078dcc542b97189da4df2b08c1fc5ab0123ecdce37d400ce85ab651b273"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
version: "2.0.2"
dart_style:
dependency: transitive
description:
@@ -293,18 +301,18 @@ packages:
dependency: "direct main"
description:
name: device_info_plus
sha256: "72d146c6d7098689ff5c5f66bcf593ac11efc530095385356e131070333e64da"
sha256: "0891702f96b2e465fe567b7ec448380e6b1c14f60af552a8536d9f583b6b8442"
url: "https://pub.dev"
source: hosted
version: "11.3.0"
version: "13.2.0"
device_info_plus_platform_interface:
dependency: transitive
description:
name: device_info_plus_platform_interface
sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f
sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46"
url: "https://pub.dev"
source: hosted
version: "7.0.3"
version: "8.1.0"
dio:
dependency: "direct main"
description:
@@ -361,30 +369,70 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
ffi_leak_tracker:
dependency: transitive
description:
name: ffi_leak_tracker
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
ffigen:
dependency: "direct dev"
description:
name: ffigen
sha256: d3e76c2ad48a4e7f93a29a162006f00eba46ce7c08194a77bb5c5e97d1b5ff0a
sha256: "56fc0be88937409839a59c133dfdee4165e80da324c9e39f59013060249ffb44"
url: "https://pub.dev"
source: hosted
version: "8.0.2"
version: "21.0.0"
file:
dependency: transitive
description:
name: file
sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d"
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "6.1.4"
version: "7.0.1"
file_picker:
dependency: "direct main"
description:
name: file_picker
sha256: "7423298f08f6fc8cce05792bae329f9a93653fc9c08712831b1a55540127995d"
sha256: "0631f51bbc2e1184bdc9e79384db158dc7830e15b3001feeca700e86563f4d24"
url: "https://pub.dev"
source: hosted
version: "9.0.2"
version: "12.2.0"
file_picker_darwin:
dependency: transitive
description:
name: file_picker_darwin
sha256: "5c32c9400f5c8976c9dd7aa34693c7d2f0c853c28704a1c1409029cb760f5251"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
file_picker_linux:
dependency: transitive
description:
name: file_picker_linux
sha256: bd52ff1e0048f29df95f913c55ad2991c72791d93e6c42241912c4bdee946cb9
url: "https://pub.dev"
source: hosted
version: "1.1.0"
file_picker_platform_interface:
dependency: transitive
description:
name: file_picker_platform_interface
sha256: d35d8cb68446fae921335bb61501d66cb2469d74c8f3103b8c6ccdbe3fe5afd8
url: "https://pub.dev"
source: hosted
version: "3.3.0"
file_picker_web:
dependency: transitive
description:
name: file_picker_web
sha256: "935560a9d29fa6f006f2855addebb88e88d438e13627d4cc24187033c106f227"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
fixnum:
dependency: transitive
description:
@@ -541,14 +589,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.12"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
url: "https://pub.dev"
source: hosted
version: "2.0.35"
flutter_riverpod:
dependency: "direct main"
description:
@@ -755,11 +795,12 @@ packages:
launch_at_startup:
dependency: "direct main"
description:
name: launch_at_startup
sha256: "1f8a75520913d1038630049e6c44a2575a23ffd28cc8b14fdf37401d1d21de84"
url: "https://pub.dev"
source: hosted
version: "0.3.1"
path: "."
ref: "7ac6f842be974aa08dcd21cab6efa66a3749f2b2"
resolved-ref: "7ac6f842be974aa08dcd21cab6efa66a3749f2b2"
url: "https://github.com/GopeedLab/launch_at_startup.git"
source: git
version: "0.6.0"
leak_tracker:
dependency: transitive
description:
@@ -856,6 +897,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: f9c168717100ae6d9fee9ffb0be379bf1f8b26b0f6bcbd4fdddcd931993a6a72
url: "https://pub.dev"
source: hosted
version: "0.19.2"
node_preamble:
dependency: transitive
description:
@@ -932,18 +981,18 @@ packages:
dependency: "direct main"
description:
name: package_info_plus
sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968"
sha256: "127e1751e37ffb2ff4658beeaca77bad0c27bf5f932bd3a501c2296926d4b481"
url: "https://pub.dev"
source: hosted
version: "8.3.1"
version: "10.2.1"
package_info_plus_platform_interface:
dependency: transitive
description:
name: package_info_plus_platform_interface
sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086"
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
url: "https://pub.dev"
source: hosted
version: "3.2.1"
version: "4.1.0"
path:
dependency: "direct main"
description:
@@ -1237,18 +1286,18 @@ packages:
dependency: "direct main"
description:
name: share_plus
sha256: fce43200aa03ea87b91ce4c3ac79f0cecd52e2a7a56c7a4185023c271fbfa6da
sha256: "34f00f9becd2743c1fb05363d624f9f70d37f7ccdcdda47450bc0b8c9d327b8c"
url: "https://pub.dev"
source: hosted
version: "10.1.4"
version: "13.3.0"
share_plus_platform_interface:
dependency: transitive
description:
name: share_plus_platform_interface
sha256: cc012a23fc2d479854e6c80150696c4a5f5bb62cb89af4de1c505cf78d0a5d0b
sha256: "365ef7379fc22507256adda3385152942ffce08935452bc972c2e52a0bebae41"
url: "https://pub.dev"
source: hosted
version: "5.0.2"
version: "7.2.0"
shared_preferences:
dependency: transitive
description:
@@ -1659,18 +1708,18 @@ packages:
dependency: transitive
description:
name: win32
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d
url: "https://pub.dev"
source: hosted
version: "5.15.0"
version: "6.4.0"
win32_registry:
dependency: "direct main"
description:
name: win32_registry
sha256: "21ec76dfc731550fd3e2ce7a33a9ea90b828fdf19a5c3bcf556fa992cfa99852"
sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904"
url: "https://pub.dev"
source: hosted
version: "1.1.5"
version: "3.0.3"
window_manager:
dependency: "direct main"
description:
@@ -1679,6 +1728,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.5.2"
windows_file_picker:
dependency: transitive
description:
name: windows_file_picker
sha256: d999c1c085374724668af0b674a9758d96255c50933faa2ac1cc51eff8308caf
url: "https://pub.dev"
source: hosted
version: "1.2.0"
xdg_directories:
dependency: transitive
description:
+12 -9
View File
@@ -44,21 +44,24 @@ dependencies:
ffi: ^2.1.3
crypto: ^3.0.6
logger: ^1.4.0
package_info_plus: ^8.1.0
package_info_plus: ^10.2.1
pub_semver: ^2.2.0
device_info_plus: ^11.1.0
win32_registry: ^1.1.5
launch_at_startup: ^0.3.1
device_info_plus: ^13.2.0
win32_registry: ^3.0.3
launch_at_startup:
git:
url: https://github.com/GopeedLab/launch_at_startup.git
ref: 7ac6f842be974aa08dcd21cab6efa66a3749f2b2
app_links: ^6.3.3
share_handler: ^0.0.22
share_plus: ^10.1.0
share_plus: ^13.3.0
uri_content: ^3.1.3
dart_ipc: ^1.0.1
dart_ipc: ^2.0.2
flutter_inappwebview: ^6.1.5
flutter_local_notifications: 20.1.0
desktop_drop: ^0.4.4
external_path: ^2.2.0
file_picker: 9.0.2
file_picker: 12.2.0
open_dir: ^0.0.2+1
open_filex: ^4.7.0
permission_handler: ^11.3.1
@@ -114,7 +117,7 @@ dev_dependencies:
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^6.0.0
ffigen: ^8.0.2
ffigen: ^21.0.0
build_runner: ^2.15.1
json_serializable: ^6.14.1
flutter_launcher_icons: ^0.14.4
@@ -208,7 +211,7 @@ ffigen:
- "StartAPIServer"
- "StopAPIServer"
- "RestartAPIServer"
- "Invoke"
- "InvokeAsync"
- "SubscribeTaskEvents"
- "FreeCString"
structs:
@@ -0,0 +1,29 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/common/libgopeed_channel.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('gopeed.com/libgopeed');
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
tearDown(() {
messenger.setMockMethodCallHandler(channel, null);
});
test('mobile invokes carry unique request IDs for async callbacks', () async {
final requestIDs = <int>[];
messenger.setMockMethodCallHandler(channel, (call) async {
expect(call.method, 'invoke');
final arguments = (call.arguments as Map<Object?, Object?>).cast<String, Object?>();
requestIDs.add(arguments['requestID']! as int);
return '{"code":0}';
});
final bridge = LibgopeedChannel();
await Future.wait([bridge.invoke('GET', '/api/v1/info'), bridge.invoke('GET', '/api/v1/config')]);
expect(requestIDs, [0, 1]);
});
}
@@ -16,6 +16,7 @@ import 'package:gopeed/core/capabilities/capability_rpc.dart';
import 'package:gopeed/core/capabilities/gopeed_capability.dart';
import 'package:gopeed/core/capabilities/storage_capability.dart';
import 'package:gopeed/features/tasks/presentation/pages/create_task_window_page.dart';
import 'package:gopeed/features/tasks/application/pending_create_task.dart';
import 'package:gopeed/shared/services/download_directory_picker.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_design_tokens.dart';
@@ -25,6 +26,90 @@ import 'package:gopeed/shared/widgets/app_tooltip.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
testWidgets('repeated external tasks update the open create route and replace request metadata', (tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
try {
tester.view.physicalSize = const Size(700, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
CreateTask? submitted;
final registry = CapabilityRegistry(createAppCapabilityCodecs())
..bind(GopeedMethods.getConfig, (_) => DownloaderConfig(downloadDir: '/downloads'))
..bind(GopeedMethods.createTask, (task) {
submitted = task;
return 'created-id';
})
..bind(StorageMethods.saveCreateHistory, (_) => const RpcUnit());
final container = ProviderContainer(
overrides: [appCapabilitiesProvider.overrideWithValue(AppCapabilities(LocalCapabilityInvoker(registry)))],
);
addTearDown(container.dispose);
final pending = container.read(pendingCreateTaskProvider.notifier);
pending.set(
CreateTask(
req: Request(
url: 'https://example.com/first.zip',
rawUrl: 'https://example.com/first',
labels: {'source': 'first'},
extra: ReqExtraHttp(method: 'POST', body: 'old-body', header: {'Cookie': 'old-cookie'}).toJson(),
proxy: RequestProxy(mode: RequestProxyMode.custom, host: 'localhost:8080'),
skipVerifyCert: true,
),
),
);
final router = GoRouter(
initialLocation: '/create',
routes: [
GoRoute(path: '/', builder: (_, _) => const SizedBox()),
GoRoute(path: '/create', builder: (_, _) => const CreateTaskWindowPage()),
],
);
addTearDown(router.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: shad.ShadcnApp.router(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
routerConfig: router,
builder: (_, child) => AppComponentThemes(child: child!),
),
),
);
await tester.pumpAndSettle();
expect(_fieldText(tester, 'create-task-url-input'), 'https://example.com/first.zip');
expect(container.read(pendingCreateTaskProvider), isNull);
final pageState = tester.state(find.byType(CreateTaskWindowPage));
for (final url in [
'https://example.com/second.zip',
'https://example.com/third.zip',
'https://example.com/third.zip',
]) {
pending.set(CreateTask(req: Request(url: url)));
router.go('/create');
await tester.pumpAndSettle();
expect(tester.state(find.byType(CreateTaskWindowPage)), same(pageState));
expect(_fieldText(tester, 'create-task-url-input'), url);
expect(container.read(pendingCreateTaskProvider), isNull);
}
await tester.tap(find.byKey(const ValueKey('create-task-direct-download-toggle')));
await tester.tap(find.text('Confirm'));
await tester.pumpAndSettle();
expect(submitted?.req?.url, 'https://example.com/third.zip');
expect(submitted?.req?.rawUrl, isNull);
expect(submitted?.req?.labels, isNull);
expect(submitted?.req?.extra, isNull);
expect(submitted?.req?.proxy?.mode, RequestProxyMode.follow);
expect(submitted?.req?.skipVerifyCert, isFalse);
expect(tester.takeException(), isNull);
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
testWidgets('mobile create task page starts below the system status bar', (WidgetTester tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
tester.view.physicalSize = const Size(700, 760);