Merge branch 'main' into codex/fix-settings-script-path-picker

This commit is contained in:
Levi authored and GitHub committed 2026-09-09 23:41:17 +08:00
commit f0aa44455c
27 files changed
+1210 -187

No files matched your search

+38 -5
View File
@@ -6,9 +6,15 @@ package main
typedef void (*TaskEventCallback)(char* payload); typedef void (*TaskEventCallback)(char* payload);
typedef void (*InvokeResultCallback)(uint64_t request_id, int success, char* payload);
static void callTaskEventCallback(uintptr_t callback, char* payload) { static void callTaskEventCallback(uintptr_t callback, char* payload) {
((TaskEventCallback)callback)(payload); ((TaskEventCallback)callback)(payload);
} }
static void callInvokeResultCallback(uintptr_t callback, uint64_t request_id, int success, char* payload) {
((InvokeResultCallback)callback)(request_id, success, payload);
}
*/ */
import "C" import "C"
import ( import (
@@ -16,6 +22,7 @@ import (
"fmt" "fmt"
"unsafe" "unsafe"
nativebridge "github.com/GopeedLab/gopeed/bind/native"
"github.com/GopeedLab/gopeed/pkg/rest" "github.com/GopeedLab/gopeed/pkg/rest"
"github.com/GopeedLab/gopeed/pkg/rest/model" "github.com/GopeedLab/gopeed/pkg/rest/model"
) )
@@ -35,12 +42,13 @@ func Start(cfg *C.char) (int, *C.char) {
if err != nil { if err != nil {
return 0, C.CString(err.Error()) return 0, C.CString(err.Error())
} }
nativebridge.ResumeInvokes()
return realPort, nil return realPort, nil
} }
//export Stop //export Stop
func Stop() { func Stop() {
rest.Stop() nativebridge.Stop()
} }
//export GetAPIServerState //export GetAPIServerState
@@ -75,14 +83,39 @@ func apiServerResult(state *model.APIServerState, err error) string {
return string(data) return string(data)
} }
//export Invoke //export InvokeAsync
func Invoke(method *C.char, path *C.char, query *C.char, body *C.char) *C.char { func InvokeAsync(
return C.CString(rest.Invoke( method *C.char,
path *C.char,
query *C.char,
body *C.char,
requestID C.ulonglong,
callback C.uintptr_t,
) {
if callback == 0 {
return
}
complete := func(result string, err error) {
success := C.int(1)
payload := result
if err != nil {
success = 0
payload = err.Error()
}
C.callInvokeResultCallback(
callback,
C.uint64_t(requestID),
success,
C.CString(payload),
)
}
nativebridge.InvokeAsync(
C.GoString(method), C.GoString(method),
C.GoString(path), C.GoString(path),
C.GoString(query), C.GoString(query),
C.GoString(body), C.GoString(body),
)) complete,
)
} }
//export SubscribeTaskEvents //export SubscribeTaskEvents
+22 -4
View File
@@ -5,6 +5,7 @@ import "C"
import ( import (
"encoding/json" "encoding/json"
nativebridge "github.com/GopeedLab/gopeed/bind/native"
"github.com/GopeedLab/gopeed/internal/webview/rpcprovider" "github.com/GopeedLab/gopeed/internal/webview/rpcprovider"
"github.com/GopeedLab/gopeed/pkg/rest" "github.com/GopeedLab/gopeed/pkg/rest"
"github.com/GopeedLab/gopeed/pkg/rest/model" "github.com/GopeedLab/gopeed/pkg/rest/model"
@@ -18,11 +19,15 @@ func Start(cfg string) (int, error) {
config.ProductionMode = true config.ProductionMode = true
config.NativeMode = true config.NativeMode = true
applyWebViewProvider(&config) applyWebViewProvider(&config)
return rest.Start(&config) port, err := rest.Start(&config)
if err == nil {
nativebridge.ResumeInvokes()
}
return port, err
} }
func Stop() { func Stop() {
rest.Stop() nativebridge.Stop()
} }
func GetAPIServerState() string { func GetAPIServerState() string {
@@ -50,8 +55,21 @@ func apiServerResult(state *model.APIServerState, err error) string {
return string(data) return string(data)
} }
func Invoke(method, path, query, body string) string { type InvokeResultListener interface {
return rest.Invoke(method, path, query, body) OnResult(requestID int64, success bool, payload string)
}
func InvokeAsync(method, path, query, body string, requestID int64, listener InvokeResultListener) {
if listener == nil {
return
}
nativebridge.InvokeAsync(method, path, query, body, func(result string, err error) {
if err != nil {
listener.OnResult(requestID, false, err.Error())
return
}
listener.OnResult(requestID, true, result)
})
} }
type TaskEventListener interface { type TaskEventListener interface {
+240
View File
@@ -0,0 +1,240 @@
// Package nativebridge contains transport-neutral behavior shared by the
// Desktop C FFI and gomobile bridge adapters.
package nativebridge
import (
"errors"
"fmt"
"sync"
"time"
"github.com/GopeedLab/gopeed/pkg/rest"
)
// StopTimeout bounds native shutdown even when an in-process request never returns.
const StopTimeout = 3 * time.Second
var errNativeBridgeStopping = errors.New("native bridge is stopping")
type invokeRequest struct {
method string
path string
query string
body string
}
type invokeTask struct {
id uint64
request invokeRequest
complete func(result string, err error)
once sync.Once
}
func (t *invokeTask) finish(result string, err error) {
t.once.Do(func() {
completeCallback(t.complete, result, err)
})
}
// InvokeAsync starts an in-process API request and completes it through the
// supplied callback. Desktop and mobile adapters share this executor.
func InvokeAsync(method, path, query, body string, callback func(result string, err error)) {
if callback == nil {
return
}
task := invokeTask{
request: invokeRequest{
method: method,
path: path,
query: query,
body: body,
},
complete: callback,
}
if !getInvokeExecutor().submit(task) {
completeCallback(callback, "", errNativeBridgeStopping)
}
}
// ResumeInvokes enables request submission after the native runtime starts.
func ResumeInvokes() {
getInvokeExecutor().resume()
}
// PauseInvokesAndWait prevents new submissions and gives running requests a
// bounded opportunity to finish before a native runtime is stopped.
// Requests still pending after StopTimeout are failed and detached so shutdown
// can continue without invoking their callbacks a second time.
func PauseInvokesAndWait() bool {
return getInvokeExecutor().pauseAndWait(StopTimeout)
}
// Stop pauses native requests and shuts down the shared runtime, but never
// keeps the host application waiting longer than StopTimeout. Cleanup that
// cannot finish within the deadline is allowed to continue in the background.
func Stop() {
stopWithin(getInvokeExecutor(), rest.Stop, StopTimeout)
}
func stopWithin(executor *invokeExecutor, cleanup func(), timeout time.Duration) {
deadline := time.Now().Add(timeout)
executor.pauseAndWait(time.Until(deadline))
stopped := make(chan struct{})
go func() {
defer close(stopped)
cleanup()
}()
remaining := time.Until(deadline)
if remaining <= 0 {
return
}
timer := time.NewTimer(remaining)
defer timer.Stop()
select {
case <-stopped:
case <-timer.C:
}
}
var (
invokeExecutorOnce sync.Once
sharedInvoker *invokeExecutor
)
func getInvokeExecutor() *invokeExecutor {
invokeExecutorOnce.Do(func() {
sharedInvoker = newInvokeExecutor(func(request invokeRequest) string {
return rest.Dispatch(request.method, request.path, request.query, request.body)
})
})
return sharedInvoker
}
// invokeExecutor starts every native API request in its own goroutine, matching
// net/http's request concurrency. It only tracks them to support bounded drain
// during shutdown; one stuck request must never prevent another from starting.
type invokeExecutor struct {
mu sync.Mutex
closed bool
accepting bool
nextID uint64
pending map[uint64]*invokeTask
drained chan struct{}
running sync.WaitGroup
handler func(invokeRequest) string
}
func newInvokeExecutor(handler func(invokeRequest) string) *invokeExecutor {
drained := make(chan struct{})
close(drained)
return &invokeExecutor{
handler: handler,
accepting: true,
pending: make(map[uint64]*invokeTask),
drained: drained,
}
}
func (e *invokeExecutor) submit(task invokeTask) bool {
e.mu.Lock()
if e.closed || !e.accepting {
e.mu.Unlock()
return false
}
if len(e.pending) == 0 {
e.drained = make(chan struct{})
}
taskID := e.nextID
e.nextID++
task.id = taskID
taskPtr := &task
e.pending[taskID] = taskPtr
e.running.Add(1)
e.mu.Unlock()
go e.run(taskPtr)
return true
}
func (e *invokeExecutor) resume() {
e.mu.Lock()
e.accepting = true
e.mu.Unlock()
}
func (e *invokeExecutor) pauseAndWait(timeout time.Duration) bool {
e.mu.Lock()
e.accepting = false
if len(e.pending) == 0 {
e.mu.Unlock()
return true
}
drained := e.drained
e.mu.Unlock()
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-drained:
return true
case <-timer.C:
}
e.mu.Lock()
if len(e.pending) == 0 {
e.mu.Unlock()
return true
}
pending := make([]*invokeTask, 0, len(e.pending))
for _, task := range e.pending {
pending = append(pending, task)
}
e.pending = make(map[uint64]*invokeTask)
close(e.drained)
e.mu.Unlock()
for _, task := range pending {
task.finish("", errNativeBridgeStopping)
}
return false
}
func (e *invokeExecutor) close() {
e.mu.Lock()
e.closed = true
e.accepting = false
e.mu.Unlock()
e.running.Wait()
}
func (e *invokeExecutor) run(task *invokeTask) {
defer e.running.Done()
result, err := e.execute(task.request)
task.finish(result, err)
e.mu.Lock()
if _, exists := e.pending[task.id]; exists {
delete(e.pending, task.id)
if len(e.pending) == 0 {
close(e.drained)
}
}
e.mu.Unlock()
}
func (e *invokeExecutor) execute(request invokeRequest) (result string, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = fmt.Errorf("invoke panic: %v", recovered)
}
}()
return e.handler(request), nil
}
func completeCallback(callback func(string, error), result string, err error) {
defer func() {
_ = recover()
}()
callback(result, err)
}
+258
View File
@@ -0,0 +1,258 @@
package nativebridge
import (
"runtime"
"strconv"
"sync"
"testing"
"time"
)
func TestInvokeExecutorStartsEveryRequestIndependently(t *testing.T) {
const taskCount = 64
release := make(chan struct{})
started := make(chan struct{}, taskCount)
executor := newInvokeExecutor(func(request invokeRequest) string {
started <- struct{}{}
<-release
return request.path
})
var completed sync.WaitGroup
completed.Add(taskCount)
for i := range taskCount {
accepted := executor.submit(invokeTask{
request: invokeRequest{path: strconv.Itoa(i)},
complete: func(string, error) {
completed.Done()
},
})
if !accepted {
t.Fatalf("request %d was rejected", i)
}
}
// Every handler must start before any of them is released. A worker pool
// would stall here once all of its workers were occupied.
for range taskCount {
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("a request waited behind other blocked requests")
}
}
close(release)
completed.Wait()
executor.close()
}
func TestInvokeExecutorConvertsPanicsToErrors(t *testing.T) {
executor := newInvokeExecutor(func(invokeRequest) string {
panic("boom")
})
completed := make(chan error, 1)
executor.submit(invokeTask{complete: func(_ string, err error) {
completed <- err
}})
select {
case err := <-completed:
if err == nil || err.Error() != "invoke panic: boom" {
t.Fatalf("unexpected error: %v", err)
}
case <-time.After(time.Second):
t.Fatal("panic result was not completed")
}
executor.close()
}
func TestInvokeExecutorSurvivesCallbackPanic(t *testing.T) {
executor := newInvokeExecutor(func(request invokeRequest) string {
return request.path
})
executor.submit(invokeTask{complete: func(string, error) {
panic("callback failed")
}})
completed := make(chan string, 1)
executor.submit(invokeTask{
request: invokeRequest{path: "next"},
complete: func(result string, _ error) {
completed <- result
},
})
select {
case result := <-completed:
if result != "next" {
t.Fatalf("unexpected result: %q", result)
}
case <-time.After(time.Second):
t.Fatal("worker stopped after callback panic")
}
executor.close()
}
func TestInvokeExecutorPausesAndDrains(t *testing.T) {
release := make(chan struct{})
started := make(chan struct{})
executor := newInvokeExecutor(func(request invokeRequest) string {
if request.path == "running" {
close(started)
<-release
}
return request.path
})
completed := make(chan struct{})
if !executor.submit(invokeTask{
request: invokeRequest{path: "running"},
complete: func(string, error) {
close(completed)
},
}) {
t.Fatal("initial task was rejected")
}
<-started
drained := make(chan struct{})
go func() {
executor.pauseAndWait(time.Second)
close(drained)
}()
deadline := time.Now().Add(time.Second)
for {
executor.mu.Lock()
paused := !executor.accepting
executor.mu.Unlock()
if paused {
break
}
if time.Now().After(deadline) {
t.Fatal("executor did not pause")
}
runtime.Gosched()
}
select {
case <-drained:
t.Fatal("pause returned before the running request completed")
default:
}
if executor.submit(invokeTask{}) {
t.Fatal("paused executor accepted a new request")
}
close(release)
<-completed
select {
case <-drained:
case <-time.After(time.Second):
t.Fatal("pause did not return after pending requests drained")
}
executor.resume()
resumed := make(chan struct{})
if !executor.submit(invokeTask{complete: func(string, error) {
close(resumed)
}}) {
t.Fatal("resumed executor rejected a request")
}
<-resumed
executor.close()
}
func TestInvokeExecutorPauseTimesOutAndFailsPendingRequests(t *testing.T) {
release := make(chan struct{})
started := make(chan struct{})
executor := newInvokeExecutor(func(request invokeRequest) string {
started <- struct{}{}
<-release
return request.path
})
errors := make(chan error, 2)
for _, path := range []string{"first", "second"} {
if !executor.submit(invokeTask{
request: invokeRequest{path: path},
complete: func(_ string, err error) {
errors <- err
},
}) {
t.Fatalf("request %q was rejected", path)
}
}
for range 2 {
<-started
}
const timeout = 30 * time.Millisecond
startedAt := time.Now()
if executor.pauseAndWait(timeout) {
t.Fatal("pause unexpectedly reported a complete drain")
}
if elapsed := time.Since(startedAt); elapsed < timeout || elapsed > 10*timeout {
t.Fatalf("pause returned after %s, want close to %s", elapsed, timeout)
}
for range 2 {
select {
case err := <-errors:
if err == nil || err.Error() != errNativeBridgeStopping.Error() {
t.Fatalf("unexpected timeout error: %v", err)
}
case <-time.After(time.Second):
t.Fatal("pending request was not failed after the timeout")
}
}
close(release)
executor.close()
select {
case err := <-errors:
t.Fatalf("request callback ran more than once: %v", err)
default:
}
}
func TestStopWithinUsesOneDeadlineForRequestsAndCleanup(t *testing.T) {
releaseRequest := make(chan struct{})
requestStarted := make(chan struct{})
executor := newInvokeExecutor(func(invokeRequest) string {
close(requestStarted)
<-releaseRequest
return "done"
})
requestResult := make(chan error, 1)
executor.submit(invokeTask{complete: func(_ string, err error) {
requestResult <- err
}})
<-requestStarted
releaseCleanup := make(chan struct{})
cleanupStarted := make(chan struct{})
cleanup := func() {
close(cleanupStarted)
<-releaseCleanup
}
const timeout = 40 * time.Millisecond
startedAt := time.Now()
stopWithin(executor, cleanup, timeout)
if elapsed := time.Since(startedAt); elapsed < timeout || elapsed > 10*timeout {
t.Fatalf("stop returned after %s, want close to %s", elapsed, timeout)
}
select {
case <-cleanupStarted:
case <-time.After(time.Second):
t.Fatal("cleanup was not started after the request deadline")
}
select {
case err := <-requestResult:
if err == nil || err.Error() != errNativeBridgeStopping.Error() {
t.Fatalf("unexpected request result: %v", err)
}
case <-time.After(time.Second):
t.Fatal("timed-out request was not failed")
}
close(releaseRequest)
close(releaseCleanup)
executor.close()
}
+8 -3
View File
@@ -13,10 +13,13 @@ const (
TaskEventError = uint64(goapi.TaskEventError) TaskEventError = uint64(goapi.TaskEventError)
) )
// Invoke dispatches a Core API request without using an HTTP listener. It is // Dispatch executes one in-process API request. Native scheduling and callback
// the shared entry point for Desktop FFI and gomobile bindings. // behavior belong to bind/native; this function only bridges into the shared
func Invoke(method, path, rawQuery, body string) string { // API Service without opening an HTTP listener.
func Dispatch(method, path, rawQuery, body string) string {
runtimeMu.RLock()
service := APIService service := APIService
runtimeMu.RUnlock()
if service == nil { if service == nil {
return marshalInvokeResult(model.NewErrorResult("service not started")) return marshalInvokeResult(model.NewErrorResult("service not started"))
} }
@@ -29,6 +32,8 @@ func Invoke(method, path, rawQuery, body string) string {
} }
func SubscribeTaskEvents(mask uint64, listener func(payload string)) { func SubscribeTaskEvents(mask uint64, listener func(payload string)) {
runtimeMu.RLock()
defer runtimeMu.RUnlock()
if APIService == nil { if APIService == nil {
return return
} }
+76 -4
View File
@@ -4,9 +4,12 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"testing" "testing"
"time"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/rest/model" "github.com/GopeedLab/gopeed/pkg/rest/model"
@@ -27,7 +30,7 @@ func TestNativeInvokeWithoutRESTListener(t *testing.T) {
} }
var result model.Result[json.RawMessage] var result model.Result[json.RawMessage]
if err := json.Unmarshal([]byte(Invoke(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil { if err := json.Unmarshal([]byte(Dispatch(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result.Code != model.CodeOk { if result.Code != model.CodeOk {
@@ -35,6 +38,75 @@ func TestNativeInvokeWithoutRESTListener(t *testing.T) {
} }
} }
func TestStartAPIServerIsNotBlockedByPendingDispatch(t *testing.T) {
requestStarted := make(chan struct{})
releaseRequest := make(chan struct{})
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(releaseRequest) }) }
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
close(requestStarted)
<-releaseRequest
w.Header().Set("Content-Length", "0")
}))
t.Cleanup(func() {
release()
upstream.Close()
Stop()
})
if _, err := Start(&model.StartConfig{NativeMode: true, Storage: model.StorageMem}); err != nil {
t.Fatal(err)
}
requestBody, err := json.Marshal(&model.ResolveTask{Req: &base.Request{URL: upstream.URL}})
if err != nil {
t.Fatal(err)
}
dispatchDone := make(chan struct{})
go func() {
defer close(dispatchDone)
Dispatch(http.MethodPost, "/api/v1/resolve", "", string(requestBody))
}()
select {
case <-requestStarted:
case <-time.After(time.Second):
t.Fatal("resolve request did not start")
}
config, err := Downloader.GetConfig()
if err != nil {
t.Fatal(err)
}
config.API = &base.APIServerConfig{Enable: true, Network: "tcp", Address: "127.0.0.1:0"}
if err := Downloader.PutConfig(config); err != nil {
t.Fatal(err)
}
started := make(chan *model.APIServerState, 1)
startErrors := make(chan error, 1)
go func() {
state, err := StartAPIServer()
started <- state
startErrors <- err
}()
select {
case state := <-started:
if err := <-startErrors; err != nil {
t.Fatalf("start API server failed: %v", err)
}
if !state.Running || state.RunningPort == 0 {
t.Fatalf("API server did not start: %#v", state)
}
case <-time.After(time.Second):
t.Fatal("pending Resolve blocked API server startup")
}
release()
select {
case <-dispatchDone:
case <-time.After(time.Second):
t.Fatal("resolve request did not finish after release")
}
}
func TestAPIServerLifecycleUsesPersistedConfigWithoutRestartingCore(t *testing.T) { func TestAPIServerLifecycleUsesPersistedConfigWithoutRestartingCore(t *testing.T) {
port, err := Start(&model.StartConfig{NativeMode: true, Storage: model.StorageMem}) port, err := Start(&model.StartConfig{NativeMode: true, Storage: model.StorageMem})
if err != nil { if err != nil {
@@ -106,7 +178,7 @@ func TestAPIServerLifecycleUsesPersistedConfigWithoutRestartingCore(t *testing.T
} }
var result model.Result[json.RawMessage] var result model.Result[json.RawMessage]
if err := json.Unmarshal([]byte(Invoke(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil { if err := json.Unmarshal([]byte(Dispatch(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result.Code != model.CodeOk { if result.Code != model.CodeOk {
@@ -153,7 +225,7 @@ func TestRestartAPIServerFailsFastAndLeavesListenerStopped(t *testing.T) {
} }
var result model.Result[json.RawMessage] var result model.Result[json.RawMessage]
if err := json.Unmarshal([]byte(Invoke(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil { if err := json.Unmarshal([]byte(Dispatch(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result.Code != model.CodeOk { if result.Code != model.CodeOk {
@@ -229,7 +301,7 @@ func TestNativeAPIServerAutoStartFailureKeepsCoreAvailable(t *testing.T) {
} }
var result model.Result[json.RawMessage] var result model.Result[json.RawMessage]
if err := json.Unmarshal([]byte(Invoke(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil { if err := json.Unmarshal([]byte(Dispatch(http.MethodGet, "/api/v1/info", "", "")), &result); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result.Code != model.CodeOk { if result.Code != model.CodeOk {
+1 -1
View File
@@ -29,7 +29,7 @@ import (
) )
var ( var (
runtimeMu sync.Mutex runtimeMu sync.RWMutex
Downloader *download.Downloader Downloader *download.Downloader
APIService *goapi.Service APIService *goapi.Service
@@ -32,6 +32,12 @@
android:name="io.flutter.embedding.android.NormalTheme" android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" android:resource="@style/NormalTheme"
/> />
<!-- app_links and share_handler own external download intents. Letting
Flutter's Router handle the same URI races with the explicit
navigation to the create-task page. -->
<meta-data
android:name="flutter_deeplinking_enabled"
android:value="false" />
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN"/> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/> <category android:name="android.intent.category.LAUNCHER"/>
@@ -1,6 +1,7 @@
package com.gopeed.gopeed package com.gopeed.gopeed
import com.gopeed.libgopeed.Libgopeed import com.gopeed.libgopeed.Libgopeed
import com.gopeed.libgopeed.InvokeResultListener
import com.gopeed.libgopeed.TaskEventListener import com.gopeed.libgopeed.TaskEventListener
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngine
@@ -38,13 +39,23 @@ class MainActivity : FlutterActivity() {
"restartApiServer" -> result.success(Libgopeed.restartAPIServer()) "restartApiServer" -> result.success(Libgopeed.restartAPIServer())
"invoke" -> { "invoke" -> {
try { try {
result.success( Libgopeed.invokeAsync(
Libgopeed.invoke( call.argument<String>("method") ?: "",
call.argument<String>("method") ?: "", call.argument<String>("path") ?: "",
call.argument<String>("path") ?: "", call.argument<String>("query") ?: "",
call.argument<String>("query") ?: "", call.argument<String>("body") ?: "",
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) { } catch (error: Exception) {
result.error("ERROR", error.message, null) result.error("ERROR", error.message, null)
@@ -259,7 +259,7 @@ GetAPIServerState
StartAPIServer StartAPIServer
StopAPIServer StopAPIServer
RestartAPIServer RestartAPIServer
Invoke InvokeAsync
FreeCString FreeCString
SubscribeTaskEvents 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. - 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`. - Memory allocated by Go must be released with `FreeCString`.
- Dart-owned input memory must be released after the synchronous native call returns. - `InvokeAsync` is the only native invocation entry point. Desktop and gomobile adapters both submit to the shared bounded-concurrency executor in `bind/native`.
- `Invoke` returns the same Result JSON as REST; business errors do not use a separate ABI error model. - 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.
- Run blocking Desktop FFI work outside the Flutter UI isolate. Mobile MethodChannel handlers likewise run blocking Go work on a background task queue. - 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. - 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. - 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() StartAPIServer()
StopAPIServer() StopAPIServer()
RestartAPIServer() RestartAPIServer()
Invoke(method, path, query, body) InvokeAsync(method, path, query, body, requestID, listener)
SubscribeTaskEvents(mask, listener) SubscribeTaskEvents(mask, listener)
``` ```
Flutter bridge rules: Flutter bridge rules:
- Normal calls use MethodChannel. - Normal calls use MethodChannel, while `InvokeAsync` completes the pending MethodChannel result through a gomobile listener.
- Android performs normal calls on a background task queue. - 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. - 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. - 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 ### 11.3 Platform smoke tests
- Windows, macOS, Linux: startup, Invoke, events, shutdown, and repeated startup. - Windows, macOS, Linux: startup, InvokeAsync, events, shutdown, and repeated startup.
- Android, iOS: gomobile Invoke, reverse MethodChannel events, and background/foreground transitions. - Android, iOS: gomobile InvokeAsync callbacks, reverse MethodChannel events, and background/foreground transitions.
- Web: REST, login, proxy, and task-file downloads. - Web: REST, login, proxy, and task-file downloads.
- Native: enabling and disabling REST does not interrupt download tasks. - 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 ### Phase 2: Native in-process calls — implemented on this branch
- Integrate the FFI Transport on Desktop. - 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. - 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. - Do not create a socket listener by default on native clients.
+33 -7
View File
@@ -12,6 +12,8 @@
#ifndef GO_CGO_GOSTRING_TYPEDEF #ifndef GO_CGO_GOSTRING_TYPEDEF
typedef struct { const char *p; ptrdiff_t n; } _GoString_; typedef struct { const char *p; ptrdiff_t n; } _GoString_;
extern size_t _GoStringLen(_GoString_ s);
extern const char *_GoStringPtr(_GoString_ s);
#endif #endif
#endif #endif
@@ -19,6 +21,24 @@ typedef struct { const char *p; ptrdiff_t n; } _GoString_;
/* Start of preamble from import "C" comments. */ /* 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. */ /* End of preamble from import "C" comments. */
@@ -44,10 +64,16 @@ typedef size_t GoUintptr;
typedef float GoFloat32; typedef float GoFloat32;
typedef double GoFloat64; typedef double GoFloat64;
#ifdef _MSC_VER #ifdef _MSC_VER
#if !defined(__cplusplus) || _MSVC_LANG <= 201402L
#include <complex.h> #include <complex.h>
typedef _Fcomplex GoComplex64; typedef _Fcomplex GoComplex64;
typedef _Dcomplex GoComplex128; typedef _Dcomplex GoComplex128;
#else #else
#include <complex>
typedef std::complex<float> GoComplex64;
typedef std::complex<double> GoComplex128;
#endif
#else
typedef float _Complex GoComplex64; typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128; typedef double _Complex GoComplex128;
#endif #endif
@@ -81,13 +107,13 @@ struct Start_return {
char* r1; char* r1;
}; };
extern struct Start_return Start(char* cfg); extern struct Start_return Start(char* cfg);
extern void Stop(); extern void Stop(void);
extern char* GetAPIServerState(); extern char* GetAPIServerState(void);
extern char* StartAPIServer(); extern char* StartAPIServer(void);
extern char* StopAPIServer(); extern char* StopAPIServer(void);
extern char* RestartAPIServer(); extern char* RestartAPIServer(void);
extern char* Invoke(char* method, char* path, char* query, char* body); extern void InvokeAsync(char* method, char* path, char* query, char* body, long long unsigned int requestID, uintptr_t callback);
extern void SubscribeTaskEvents(GoUint64 mask, GoUintptr callback); extern void SubscribeTaskEvents(long long unsigned int mask, uintptr_t callback);
extern void FreeCString(char* value); extern void FreeCString(char* value);
#ifdef __cplusplus #ifdef __cplusplus
+6 -2
View File
@@ -14,10 +14,13 @@ import UIKit
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
let messenger = engineBridge.applicationRegistrar.messenger() let messenger = engineBridge.applicationRegistrar.messenger()
let libgopeedTaskQueue = messenger.makeBackgroundTaskQueue?()
let libgopeedChannel = FlutterMethodChannel( let libgopeedChannel = FlutterMethodChannel(
name: "gopeed.com/libgopeed", name: "gopeed.com/libgopeed",
binaryMessenger: messenger binaryMessenger: messenger,
codec: FlutterStandardMethodCodec.sharedInstance(),
taskQueue: libgopeedTaskQueue
) )
let taskEventForwarder = GopeedTaskEventForwarder(channel: libgopeedChannel) let taskEventForwarder = GopeedTaskEventForwarder(channel: libgopeedChannel)
libgopeedChannel.setMethodCallHandler { call, result in libgopeedChannel.setMethodCallHandler { call, result in
@@ -56,7 +59,8 @@ import UIKit
let path = arguments?["path"] as? String ?? "" let path = arguments?["path"] as? String ?? ""
let query = arguments?["query"] as? String ?? "" let query = arguments?["query"] as? String ?? ""
let body = arguments?["body"] 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": case "subscribeTaskEvents":
let arguments = call.arguments as? [String: Any] let arguments = call.arguments as? [String: Any]
let mask = (arguments?["mask"] as? NSNumber)?.int64Value ?? 0 let mask = (arguments?["mask"] as? NSNumber)?.int64Value ?? 0
@@ -13,4 +13,12 @@ FOUNDATION_EXPORT void GopeedSubscribeTaskEventsWithForwarder(
int64_t mask, int64_t mask,
GopeedTaskEventForwarder * _Nullable listener); GopeedTaskEventForwarder * _Nullable listener);
FOUNDATION_EXPORT void GopeedInvokeAsyncWithResult(
NSString *method,
NSString *path,
NSString *query,
NSString *body,
int64_t requestID,
FlutterResult result);
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
@@ -8,6 +8,45 @@
@end @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 @implementation GopeedTaskEventForwarder
- (instancetype)initWithChannel:(FlutterMethodChannel *)channel { - (instancetype)initWithChannel:(FlutterMethodChannel *)channel {
@@ -33,3 +72,15 @@ void GopeedSubscribeTaskEventsWithForwarder(
GopeedTaskEventForwarder * _Nullable listener) { GopeedTaskEventForwarder * _Nullable listener) {
LibgopeedSubscribeTaskEvents(mask, 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);
}
@@ -37,10 +37,15 @@ class AppDeepLinkController extends AsyncNotifier<AppDeepLinkState> {
@override @override
Future<AppDeepLinkState> build() async { Future<AppDeepLinkState> build() async {
final runtime = ref.watch(appRuntimeControllerProvider).value; if (_started || kIsWeb) {
if (runtime == null || _started || kIsWeb) {
return AppDeepLinkState(started: _started); return AppDeepLinkState(started: _started);
} }
// Deep-link handling depends on the runtime being ready, but it must not
// rebuild whenever runtime settings change. A rebuild disposes the active
// platform subscriptions while `_started` remains true, leaving Android
// unable to receive later browser takeover intents (for example after the
// API server is started or stopped from Settings).
await ref.read(appRuntimeControllerProvider.future);
_started = true; _started = true;
final appLinks = AppLinks(); final appLinks = AppLinks();
_subscription = appLinks.uriLinkStream.listen((uri) { _subscription = appLinks.uriLinkStream.listen((uri) {
@@ -11,6 +11,7 @@ import 'task_event.dart';
class LibgopeedChannel implements LibgopeedInterface { class LibgopeedChannel implements LibgopeedInterface {
static const _channel = MethodChannel('gopeed.com/libgopeed'); static const _channel = MethodChannel('gopeed.com/libgopeed');
final _taskEvents = StreamController<TaskEvent>.broadcast(); final _taskEvents = StreamController<TaskEvent>.broadcast();
int _requestID = 0;
LibgopeedChannel() { LibgopeedChannel() {
_channel.setMethodCallHandler((call) async { _channel.setMethodCallHandler((call) async {
@@ -50,7 +51,9 @@ class LibgopeedChannel implements LibgopeedInterface {
@override @override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async { Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final requestID = _requestID++;
final result = await _channel.invokeMethod<String>('invoke', { final result = await _channel.invokeMethod<String>('invoke', {
'requestID': requestID,
'method': method, 'method': method,
'path': path, 'path': path,
'query': query, 'query': query,
+10 -64
View File
@@ -1,10 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import '../ffi/libgopeed_bind.dart';
import '../ffi/libgopeed_worker.dart'; import '../ffi/libgopeed_worker.dart';
import 'api_server_state.dart'; import 'api_server_state.dart';
import 'libgopeed_interface.dart'; import 'libgopeed_interface.dart';
@@ -12,51 +8,22 @@ import 'start_config.dart';
import 'task_event.dart'; import 'task_event.dart';
class LibgopeedFFi implements LibgopeedInterface { class LibgopeedFFi implements LibgopeedInterface {
late LibgopeedBind _libgopeed; LibgopeedFFi() {
_worker.taskEvents.listen(_onTaskEvent, onError: _taskEvents.addError);
}
final _taskEvents = StreamController<TaskEvent>.broadcast(); final _taskEvents = StreamController<TaskEvent>.broadcast();
final _worker = LibgopeedWorker(); final _worker = LibgopeedWorker();
late final NativeCallable<Void Function(Pointer<Char>)> _taskEventCallback;
LibgopeedFFi(LibgopeedBind libgopeed) { void _onTaskEvent(Map<String, dynamic> payload) {
_libgopeed = libgopeed; _taskEvents.add(TaskEvent.fromJson(payload));
_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);
}
} }
@override @override
Future<int> start(StartConfig cfg) { Future<int> start(StartConfig cfg) => _worker.start(jsonEncode(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;
}
@override @override
Future<void> stop() { Future<void> stop() => _worker.stop();
var completer = Completer<void>();
_libgopeed.Stop();
completer.complete();
return completer.future;
}
Future<ApiServerOperationResult> _apiServerOperation(String operation) async { Future<ApiServerOperationResult> _apiServerOperation(String operation) async {
final payload = await _worker.apiServer(operation); final payload = await _worker.apiServer(operation);
@@ -77,33 +44,12 @@ class LibgopeedFFi implements LibgopeedInterface {
@override @override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async { Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final methodPtr = method.toNativeUtf8(); return jsonEncode(await _worker.invoke(method, path, query, body));
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);
}
}
} }
@override @override
Stream<TaskEvent> get taskEvents => _taskEvents.stream; Stream<TaskEvent> get taskEvents => _taskEvents.stream;
@override @override
Future<void> subscribeTaskEvents(Set<TaskEventType> events) async { Future<void> subscribeTaskEvents(Set<TaskEventType> events) => _worker.subscribeTaskEvents(events.mask);
_libgopeed.SubscribeTaskEvents(events.mask, events.isEmpty ? 0 : _taskEventCallback.nativeFunction.address);
}
} }
@@ -1,6 +1,4 @@
import 'dart:async'; import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import '../../util/util.dart'; import '../../util/util.dart';
import '../common/libgopeed_channel.dart'; import '../common/libgopeed_channel.dart';
@@ -9,7 +7,6 @@ import '../common/libgopeed_interface.dart';
import '../common/api_server_state.dart'; import '../common/api_server_state.dart';
import '../common/start_config.dart'; import '../common/start_config.dart';
import '../common/task_event.dart'; import '../common/task_event.dart';
import '../ffi/libgopeed_bind.dart';
import '../libgopeed_boot.dart'; import '../libgopeed_boot.dart';
LibgopeedBoot create() => LibgopeedBootNative(); LibgopeedBoot create() => LibgopeedBootNative();
@@ -19,17 +16,7 @@ class LibgopeedBootNative implements LibgopeedBoot {
LibgopeedBootNative() { LibgopeedBootNative() {
if (Util.isDesktop()) { if (Util.isDesktop()) {
var libName = "libgopeed."; _libgopeed = LibgopeedFFi();
if (Platform.isWindows) {
libName += "dll";
}
if (Platform.isMacOS) {
libName += "dylib";
}
if (Platform.isLinux) {
libName += "so";
}
_libgopeed = LibgopeedFFi(LibgopeedBind(DynamicLibrary.open(libName)));
} else { } else {
_libgopeed = LibgopeedChannel(); _libgopeed = LibgopeedChannel();
} }
+28 -15
View File
@@ -30,53 +30,67 @@ class LibgopeedBind {
late final _StopPtr = _lookup<ffi.NativeFunction<ffi.Void Function()>>('Stop'); late final _StopPtr = _lookup<ffi.NativeFunction<ffi.Void Function()>>('Stop');
late final _Stop = _StopPtr.asFunction<void Function()>(); 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 _GetAPIServerStatePtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('GetAPIServerState');
late final _GetAPIServerState = _GetAPIServerStatePtr.asFunction<ffi.Pointer<ffi.Char> Function()>(); 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 _StartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('StartAPIServer');
late final _StartAPIServer = _StartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>(); 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 _StopAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('StopAPIServer');
late final _StopAPIServer = _StopAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>(); 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 _RestartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('RestartAPIServer');
late final _RestartAPIServer = _RestartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>(); 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> method,
ffi.Pointer<ffi.Char> path, ffi.Pointer<ffi.Char> path,
ffi.Pointer<ffi.Char> query, ffi.Pointer<ffi.Char> query,
ffi.Pointer<ffi.Char> body, 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< _lookup<
ffi.NativeFunction< 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.Pointer<ffi.Char>, ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>, ffi.Pointer<ffi.Char>,
ffi.UnsignedLongLong,
ffi.UintPtr,
) )
> >
>('Invoke'); >('InvokeAsync');
late final _Invoke = late final _InvokeAsync =
_InvokePtr.asFunction< _InvokeAsyncPtr.asFunction<
ffi.Pointer<ffi.Char> Function( void Function(
ffi.Pointer<ffi.Char>, ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>, ffi.Pointer<ffi.Char>,
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); return _SubscribeTaskEvents(mask, callback);
} }
late final _SubscribeTaskEventsPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Uint64, ffi.UintPtr)>>( late final _SubscribeTaskEventsPtr =
'SubscribeTaskEvents', _lookup<ffi.NativeFunction<ffi.Void Function(ffi.UnsignedLongLong, ffi.UintPtr)>>('SubscribeTaskEvents');
);
late final _SubscribeTaskEvents = _SubscribeTaskEventsPtr.asFunction<void Function(int, int)>(); late final _SubscribeTaskEvents = _SubscribeTaskEventsPtr.asFunction<void Function(int, int)>();
void FreeCString(ffi.Pointer<ffi.Char> value) { void FreeCString(ffi.Pointer<ffi.Char> value) {
+161 -37
View File
@@ -1,4 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'dart:ffi'; import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'dart:isolate'; import 'dart:isolate';
@@ -7,38 +8,74 @@ import 'package:ffi/ffi.dart';
import 'libgopeed_bind.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 { class LibgopeedWorker {
LibgopeedWorker() { factory LibgopeedWorker() => _instance;
LibgopeedWorker._() {
_receivePort.listen(_handleWorkerMessage); _receivePort.listen(_handleWorkerMessage);
_errorPort.listen(_handleWorkerError); _errorPort.listen(_handleWorkerError);
_isolateReady = Isolate.spawn(_workerMain, _receivePort.sendPort, onError: _errorPort.sendPort); _isolateReady = Isolate.spawn(_workerMain, _receivePort.sendPort, onError: _errorPort.sendPort);
} }
static final LibgopeedWorker _instance = LibgopeedWorker._();
final ReceivePort _receivePort = ReceivePort(); final ReceivePort _receivePort = ReceivePort();
final ReceivePort _errorPort = 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; late final Future<Isolate> _isolateReady;
final Completer<SendPort> _sendPort = Completer<SendPort>(); final Completer<SendPort> _sendPort = Completer<SendPort>();
Future<void>? _stopFuture;
int _requestID = 0; int _requestID = 0;
bool _stopping = false;
bool _stopped = false;
Future<String> invoke(String method, String path, String query, String body) async { Stream<Map<String, dynamic>> get taskEvents => _taskEvents.stream;
await _isolateReady;
final sendPort = await _sendPort.future; Future<int> start(String config) => _request<int>('start', [config]);
final requestID = _requestID++;
final completer = Completer<String>(); Future<void> stop() => _stopFuture ??= _stop();
_pending[requestID] = completer;
sendPort.send(['invoke', requestID, method, path, query, body]); Future<void> _stop() async {
return completer.future; _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; await _isolateReady;
final sendPort = await _sendPort.future; final sendPort = await _sendPort.future;
final requestID = _requestID++; final requestID = _requestID++;
final completer = Completer<String>(); final completer = Completer<Object?>();
_pending[requestID] = completer; _pending[requestID] = completer;
sendPort.send(['apiServer', requestID, operation]); sendPort.send([type, requestID, ...arguments]);
return completer.future; return (await completer.future) as T;
} }
void _handleWorkerMessage(dynamic message) { void _handleWorkerMessage(dynamic message) {
@@ -47,13 +84,18 @@ class LibgopeedWorker {
return; return;
} }
final response = message as List<dynamic>; final response = message as List<dynamic>;
final requestID = response[0] as int; switch (response[0] as String) {
final completer = _pending.remove(requestID); case 'response':
if (completer == null) return; final requestID = response[1] as int;
if (response[1] as bool) { final completer = _pending.remove(requestID);
completer.complete(response[2] as String); if (completer == null) return;
} else { if (response[2] as bool) {
completer.completeError(StateError(response[2] as String)); 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); completer.completeError(error);
} }
_pending.clear(); _pending.clear();
_taskEvents.addError(error);
} }
static void _workerMain(SendPort mainSendPort) { static void _workerMain(SendPort mainSendPort) {
final requests = ReceivePort(); final requests = ReceivePort();
final bindings = LibgopeedBind(DynamicLibrary.open(_libraryName())); 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); mainSendPort.send(requests.sendPort);
requests.listen((dynamic message) { requests.listen((dynamic message) {
final request = message as List<dynamic>; final request = message as List<dynamic>;
final type = request[0] as String; final type = request[0] as String;
final requestID = request[1] as int; final requestID = request[1] as int;
try { if (type == 'invoke') {
final response = switch (type) { try {
'invoke' => _invoke( _invokeAsync(
bindings, bindings,
invokeResultCallback.nativeFunction.address,
requestID,
request[2] as String, request[2] as String,
request[3] as String, request[3] as String,
request[4] as String, request[4] as String,
request[5] 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), 'apiServer' => _apiServer(bindings, request[2] as String),
'subscribeTaskEvents' => _subscribeTaskEvents(
bindings,
taskEventCallback.nativeFunction.address,
request[2] as int,
),
_ => throw StateError('Unknown libgopeed worker request: $type'), _ => 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) { } 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) { static String _apiServer(LibgopeedBind bindings, String operation) {
final resultPtr = switch (operation) { final resultPtr = switch (operation) {
'get' => bindings.GetAPIServerState(), '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 methodPtr = method.toNativeUtf8();
final pathPtr = path.toNativeUtf8(); final pathPtr = path.toNativeUtf8();
final queryPtr = query.toNativeUtf8(); final queryPtr = query.toNativeUtf8();
final bodyPtr = body.toNativeUtf8(); final bodyPtr = body.toNativeUtf8();
Pointer<Char>? resultPtr;
try { try {
resultPtr = bindings.Invoke(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast()); bindings.InvokeAsync(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast(), requestID, callback);
if (resultPtr == nullptr) {
throw StateError('Gopeed Invoke returned a null response');
}
return resultPtr.cast<Utf8>().toDartString();
} finally { } finally {
malloc.free(methodPtr); malloc.free(methodPtr);
malloc.free(pathPtr); malloc.free(pathPtr);
malloc.free(queryPtr); malloc.free(queryPtr);
malloc.free(bodyPtr); malloc.free(bodyPtr);
if (resultPtr != null && resultPtr != nullptr) {
bindings.FreeCString(resultPtr);
}
} }
} }
@@ -2,9 +2,9 @@ import 'dart:convert';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import '../../../libgopeed_boot.dart';
import '../../../ffi/libgopeed_worker.dart';
import '../../../../util/util.dart'; import '../../../../util/util.dart';
import '../../../ffi/libgopeed_worker.dart';
import '../../../libgopeed_boot.dart';
import '../gopeed_transport.dart'; import '../gopeed_transport.dart';
GopeedTransport createTransport(GopeedTransportConfig config) => NativeGopeedTransport(); GopeedTransport createTransport(GopeedTransportConfig config) => NativeGopeedTransport();
@@ -32,14 +32,16 @@ class NativeGopeedTransport implements GopeedTransport {
}) async { }) async {
final request = _RequestParts.from(path, queryParameters); final request = _RequestParts.from(path, queryParameters);
final requestBody = data == null ? '' : jsonEncode(data); final requestBody = data == null ? '' : jsonEncode(data);
final payload = _ffiWorker != null final worker = _ffiWorker;
? await _ffiWorker.invoke(method.toUpperCase(), request.path, request.query, requestBody) if (worker != null) {
: await LibgopeedBoot.instance.invoke( return worker.invoke(method.toUpperCase(), request.path, request.query, requestBody);
method.toUpperCase(), }
request.path, final payload = await LibgopeedBoot.instance.invoke(
query: request.query, method.toUpperCase(),
body: requestBody, request.path,
); query: request.query,
body: requestBody,
);
return jsonDecode(payload); return jsonDecode(payload);
} }
@@ -93,11 +93,21 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
super.initState(); super.initState();
_urlController.addListener(_handleUrlChanged); _urlController.addListener(_handleUrlChanged);
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final task = widget.initialTask ?? ref.read(pendingCreateTaskProvider); final task = widget.initialTask ?? ref.read(pendingCreateTaskProvider);
_applyInitialTask(task); _applyInitialTask(task);
if (widget.initialTask == null) { if (widget.initialTask == null) {
ref.read(pendingCreateTaskProvider.notifier).clear(); 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) { if (task == null || _urlController.text.trim().isEmpty) {
unawaited(_loadClipboardUrl()); unawaited(_loadClipboardUrl());
} }
@@ -174,6 +184,13 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
final opts = task.opts; final opts = task.opts;
setState(() { setState(() {
if (req?.url.isNotEmpty == true) { 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; _urlController.text = req!.url;
_initialRawUrl = req.rawUrl; _initialRawUrl = req.rawUrl;
_initialLabels = req.labels == null ? null : Map<String, String>.of(req.labels!); _initialLabels = req.labels == null ? null : Map<String, String>.of(req.labels!);
@@ -307,6 +324,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
SizedBox( SizedBox(
height: 120, height: 120,
child: AppTextField( child: AppTextField(
key: const ValueKey('create-task-url-input'),
controller: _urlController, controller: _urlController,
hintText: context.l10n.pasteDownloadLinks, hintText: context.l10n.pasteDownloadLinks,
keyboardType: TextInputType.multiline, keyboardType: TextInputType.multiline,
+1 -1
View File
@@ -50,7 +50,7 @@ packages:
source: hosted source: hosted
version: "1.0.3" version: "1.0.3"
app_links_platform_interface: app_links_platform_interface:
dependency: transitive dependency: "direct dev"
description: description:
name: app_links_platform_interface name: app_links_platform_interface
sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f" sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f"
+2 -1
View File
@@ -108,6 +108,7 @@ dependency_overrides:
path: permission_handler_windows path: permission_handler_windows
dev_dependencies: dev_dependencies:
app_links_platform_interface: ^2.0.2
flutter_test: flutter_test:
sdk: flutter sdk: flutter
@@ -211,7 +212,7 @@ ffigen:
- "StartAPIServer" - "StartAPIServer"
- "StopAPIServer" - "StopAPIServer"
- "RestartAPIServer" - "RestartAPIServer"
- "Invoke" - "InvokeAsync"
- "SubscribeTaskEvents" - "SubscribeTaskEvents"
- "FreeCString" - "FreeCString"
structs: structs:
@@ -1,5 +1,13 @@
import 'dart:async';
import 'package:app_links_platform_interface/app_links_platform_interface.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/downloader_config.dart';
import 'package:gopeed/app/application/app_runtime_controller.dart';
import 'package:gopeed/app/application/app_deep_link_controller.dart'; import 'package:gopeed/app/application/app_deep_link_controller.dart';
import 'package:gopeed/core/common/api_server_state.dart';
import 'package:gopeed/core/common/start_config.dart';
import 'package:share_handler/share_handler.dart'; import 'package:share_handler/share_handler.dart';
void main() { void main() {
@@ -27,4 +35,71 @@ void main() {
expect(sharedMediaUri(media), Uri.parse('magnet:?xt=urn:btih:example')); expect(sharedMediaUri(media), Uri.parse('magnet:?xt=urn:btih:example'));
}); });
test('keeps listening for browser takeover links after runtime settings change', () async {
final originalPlatform = AppLinksPlatform.instance;
final appLinksPlatform = _FakeAppLinksPlatform();
AppLinksPlatform.instance = appLinksPlatform;
final container = ProviderContainer(
overrides: [appRuntimeControllerProvider.overrideWith(_FakeRuntimeController.new)],
);
try {
await container.read(appDeepLinkControllerProvider.future);
expect(appLinksPlatform.hasListener, isTrue);
container.read(appRuntimeControllerProvider.notifier).replaceDownloaderConfig(DownloaderConfig());
await Future<void>.delayed(Duration.zero);
await Future<void>.delayed(Duration.zero);
expect(appLinksPlatform.hasListener, isTrue);
} finally {
container.dispose();
await Future<void>.delayed(Duration.zero);
AppLinksPlatform.instance = originalPlatform;
await appLinksPlatform.close();
}
});
}
class _FakeAppLinksPlatform extends AppLinksPlatform {
final _links = StreamController<Uri>.broadcast();
bool get hasListener => _links.hasListener;
@override
Future<Uri?> getInitialLink() async => null;
@override
Stream<Uri> get uriLinkStream => _links.stream;
Future<void> close() => _links.close();
}
class _FakeRuntimeController extends AppRuntimeController {
@override
Future<AppRuntimeState> build() async {
final config = StartConfig()
..network = 'tcp'
..address = '127.0.0.1:9999'
..apiEnable = true
..apiToken = ''
..storage = 'bolt'
..storageDir = ''
..refreshInterval = 0;
return AppRuntimeState(
startConfig: config,
apiServerState: const ApiServerState(
enabled: true,
mcpEnabled: false,
running: true,
network: 'tcp',
address: '127.0.0.1:9999',
runningPort: 9999,
pendingApply: false,
lastError: '',
),
downloaderConfig: DownloaderConfig(),
);
}
} }
@@ -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]);
});
}
@@ -14,6 +14,7 @@ import 'package:gopeed/core/capabilities/capability_rpc.dart';
import 'package:gopeed/core/capabilities/gopeed_capability.dart'; import 'package:gopeed/core/capabilities/gopeed_capability.dart';
import 'package:gopeed/core/capabilities/storage_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/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/services/download_directory_picker.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart'; import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_design_tokens.dart'; import 'package:gopeed/shared/theme/app_design_tokens.dart';
@@ -22,6 +23,90 @@ import 'package:gopeed/shared/widgets/app_tooltip.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad; import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() { 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 { testWidgets('mobile create task page starts below the system status bar', (WidgetTester tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.android; debugDefaultTargetPlatformOverride = TargetPlatform.android;
tester.view.physicalSize = const Size(700, 760); tester.view.physicalSize = const Size(700, 760);