Compare commits

..
40 changed files with 280 additions and 360 deletions

No files matched your search

+1 -3
View File
@@ -2405,9 +2405,7 @@ func (d *Downloader) doStart(task *Task) (err error) {
return err
}
}
if err := d.triggerOnStart(task); err != nil {
return err
}
d.triggerOnStart(task)
if !d.taskIsRunningGeneration(task, generation) {
return nil
}
-47
View File
@@ -1,47 +0,0 @@
package engine
import (
"context"
"errors"
"github.com/dop251/goja"
"testing"
"time"
)
func TestCloseUnblocksPendingPromise(t *testing.T) {
e := NewEngine(nil)
entered := make(chan struct{})
_, err := e.runOnLoop(func(r *goja.Runtime) (goja.Value, error) {
return goja.Undefined(), r.Set("entered", func() { close(entered) })
})
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() { _, err := e.RunString(`entered(); new Promise(()=>{});`); done <- err }()
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("script did not enter")
}
e.Close()
select {
case err := <-done:
if err == nil {
t.Fatal("closed execution returned success")
}
case <-time.After(300 * time.Millisecond):
t.Fatal("Engine.Close left the Promise waiter blocked")
}
}
func TestExecutionDeadlineInterruptsSynchronousScript(t *testing.T) {
e := NewEngine(nil)
defer e.Close()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
_, err := e.RunStringContext(ctx, `while (true) {}`)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("got %v, want deadline exceeded", err)
}
}
+6 -49
View File
@@ -1,7 +1,6 @@
package engine
import (
"context"
_ "embed"
"errors"
"fmt"
@@ -27,7 +26,6 @@ var polyfillScript string
type Engine struct {
loop *eventloop.EventLoop
done chan struct{}
closeOnce sync.Once
cleanupMu sync.Mutex
@@ -41,13 +39,7 @@ type JSFunction func(goja.FunctionCall) goja.Value
// RunString executes the script and returns the go type value
// if script result is promise, it will be resolved
func (e *Engine) RunString(script string) (value any, err error) {
return e.RunStringContext(context.Background(), script)
}
// RunStringContext bounds an execution, including awaited promises. Cancelling
// an execution closes its engine so outstanding operations cannot outlive it.
func (e *Engine) RunStringContext(ctx context.Context, script string) (any, error) {
return e.runOnLoopContext(ctx, func(runtime *goja.Runtime) (goja.Value, error) {
return e.runOnLoop(func(runtime *goja.Runtime) (goja.Value, error) {
return runtime.RunString(script)
})
}
@@ -55,11 +47,7 @@ func (e *Engine) RunStringContext(ctx context.Context, script string) (any, erro
// CallFunction calls the function and returns the go type value
// if function result is promise, it will be resolved
func (e *Engine) CallFunction(fn any, args ...any) (value any, err error) {
return e.CallFunctionContext(context.Background(), fn, args...)
}
func (e *Engine) CallFunctionContext(ctx context.Context, fn any, args ...any) (value any, err error) {
return e.runOnLoopContext(ctx, func(runtime *goja.Runtime) (goja.Value, error) {
return e.runOnLoop(func(runtime *goja.Runtime) (goja.Value, error) {
var jsArgs []goja.Value
for _, arg := range args {
jsArgs = append(jsArgs, runtime.ToValue(arg))
@@ -81,20 +69,6 @@ func (e *Engine) CallFunctionContext(ctx context.Context, fn any, args ...any) (
}
func (e *Engine) runOnLoop(fn func(runtime *goja.Runtime) (goja.Value, error)) (any, error) {
return e.runOnLoopContext(context.Background(), fn)
}
var ErrClosed = errors.New("engine closed")
func (e *Engine) runOnLoopContext(ctx context.Context, fn func(runtime *goja.Runtime) (goja.Value, error)) (any, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
select {
case <-e.done:
return nil, ErrClosed
default:
}
type result struct {
value any
err error
@@ -158,31 +132,15 @@ func (e *Engine) runOnLoopContext(ctx context.Context, fn func(runtime *goja.Run
if !ok {
return nil, errors.New("engine loop terminated")
}
select {
case res := <-ch:
return res.value, res.err
case <-ctx.Done():
// Interrupt synchronous JS too; a select alone only stops Promise waiting.
e.Close()
return nil, ctx.Err()
case <-e.done:
return nil, ErrClosed
res := <-ch
if res.err != nil {
return nil, res.err
}
return res.value, nil
}
func (e *Engine) Close() {
e.closeOnce.Do(func() {
close(e.done)
e.Runtime.Interrupt(ErrClosed)
// Wait for interrupted JS to leave the loop, then allow cleanup hooks
// to execute their JS cancellation callbacks before terminating it.
cleared := make(chan struct{})
if e.loop.RunOnLoop(func(runtime *goja.Runtime) {
runtime.ClearInterrupt()
close(cleared)
}) {
<-cleared
}
e.cleanupMu.Lock()
cleanups := e.cleanups
e.cleanups = nil
@@ -219,7 +177,6 @@ func NewEngine(cfg *Config) *Engine {
loop := eventloop.NewEventLoop()
engine := &Engine{
loop: loop,
done: make(chan struct{}),
}
loop.Start()
done := make(chan struct{})
+4 -15
View File
@@ -3,7 +3,6 @@ package download
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
@@ -328,8 +327,8 @@ func (d *Downloader) triggerOnResolve(req *base.Request) (res *base.Resource, er
return
}
func (d *Downloader) triggerOnStart(task *Task) error {
return doTrigger(d,
func (d *Downloader) triggerOnStart(task *Task) {
doTrigger(d,
EventOnStart,
task.Meta.Req,
&OnStartContext{
@@ -414,13 +413,6 @@ func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, c
}
engine, session := d.newExtensionEngine()
defer session.CloseIfIdle()
eventCtx, cancelEvent := context.WithTimeout(d.backgroundCtx, d.cfg.ExtensionEventTimeout)
defer cancelEvent()
defer func() {
if eventCtx.Err() != nil {
session.Close()
}
}()
gopeed.Runtime = &InstanceRuntime{
WebView: d.newExtensionWebViewRuntime(session, ext.buildIdentity()),
}
@@ -429,13 +421,13 @@ func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, c
gopeed.Logger.logger.Error().Err(err).Msgf("[%s] engine inject failed", ext.buildIdentity())
return
}
_, err = engine.RunStringContext(eventCtx, string(scriptBuf))
_, err = engine.RunString(string(scriptBuf))
if err != nil {
gopeed.Logger.logger.Error().Err(err).Msgf("[%s] run script failed", ext.buildIdentity())
return
}
if fn, ok := gopeed.Events[event]; ok {
_, err = engine.CallFunctionContext(eventCtx, fn, ctx)
_, err = engine.CallFunction(fn, ctx)
if err != nil {
gopeed.Logger.logger.Error().Err(err).Msgf("[%s] call function failed: %s", ext.buildIdentity(), event)
return
@@ -445,9 +437,6 @@ func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, c
}
}
}()
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return err
}
}
}
}
-149
View File
@@ -1,149 +0,0 @@
package download
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/GopeedLab/gopeed/internal/fetcher"
"github.com/GopeedLab/gopeed/pkg/base"
)
func installCancellationExtension(t *testing.T, d *Downloader, event, script string) {
t.Helper()
dir := t.TempDir()
manifest := fmt.Sprintf(`{"name":"cancel-%s","author":"test","title":"Cancel","version":"1.0.0","scripts":[{"event":%q,"match":{"urls":["*://example.com/*"]},"entry":"index.js"}]}`, event, event)
for name, body := range map[string]string{"manifest.json": manifest, "index.js": script} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
t.Fatal(err)
}
}
if _, err := d.InstallExtensionByFolder(dir, true); err != nil {
t.Fatal(err)
}
}
func newCancellationDownloader(t *testing.T) *Downloader {
t.Helper()
d := NewDownloader(&DownloaderConfig{Storage: NewMemStorage(), StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{&generationTestManager{holdOpen: true}}})
if err := d.Setup(); err != nil {
t.Fatal(err)
}
return d
}
func TestResolveExtensionStopsOnShutdown(t *testing.T) {
entered, release := make(chan struct{}), make(chan struct{})
var once sync.Once
defer once.Do(func() { close(release) })
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(entered)
select {
case <-release:
case <-r.Context().Done():
}
w.Write([]byte("ok"))
}))
defer server.Close()
d := newCancellationDownloader(t)
defer d.Close()
installCancellationExtension(t, d, "onResolve", fmt.Sprintf(`gopeed.events.onResolve(async ctx=>{await fetch(%q);});`, server.URL))
done := make(chan error, 1)
go func() { _, err := d.Resolve(&base.Request{URL: "https://example.com/cancel"}); done <- err }()
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("handler did not enter")
}
if err := d.Close(); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Errorf("got %v, want cancellation", err)
}
case <-time.After(300 * time.Millisecond):
once.Do(func() { close(release) })
t.Fatal("shutdown did not cancel extension Resolve")
}
}
func TestOnErrorCancellationReleasesTaskAPIs(t *testing.T) {
entered, release := make(chan struct{}), make(chan struct{})
var once sync.Once
defer once.Do(func() { close(release) })
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(entered)
select {
case <-release:
case <-r.Context().Done():
}
w.Write([]byte("ok"))
}))
defer server.Close()
d := newCancellationDownloader(t)
defer d.Close()
parent, cancel := context.WithCancel(d.backgroundCtx)
d.backgroundCtx = parent
defer cancel()
installCancellationExtension(t, d, "onError", fmt.Sprintf(`gopeed.events.onError(async ctx=>{await fetch(%q);});`, server.URL))
d.cfg.MaxRunning = 0
id, err := d.CreateDirect(&base.Request{URL: "generation://example.com/task"}, &base.Options{Path: t.TempDir()})
if err != nil {
t.Fatal(err)
}
task := d.GetTask(id)
task.statusLock.Lock()
task.Status = base.DownloadStatusRunning
task.statusLock.Unlock()
handled := make(chan struct{})
go func() { d.doOnError(task, errors.New("source failed")); close(handled) }()
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("onError did not enter")
}
status, stats := make(chan struct{}), make(chan struct{})
go func() { d.RuntimeStatus(id); close(status) }()
go func() { d.Stats(id); close(stats) }()
cancel()
for name, ch := range map[string]<-chan struct{}{"onError": handled, "RuntimeStatus": status, "Stats": stats} {
select {
case <-ch:
case <-time.After(300 * time.Millisecond):
once.Do(func() { close(release) })
<-handled
t.Fatalf("%s stayed blocked after cancellation", name)
}
}
}
func TestExtensionEventDeadlineRejectsUnsettledResolve(t *testing.T) {
d := newCancellationDownloader(t)
defer d.Close()
d.cfg.ExtensionEventTimeout = 30 * time.Millisecond
installCancellationExtension(t, d, "onResolve", `gopeed.events.onResolve(async ctx=>{await new Promise(()=>{});});`)
_, err := d.Resolve(&base.Request{URL: "https://example.com/timeout"})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("got %v, want event deadline exceeded", err)
}
}
func TestExtensionStartDeadlinePreventsFetcherStart(t *testing.T) {
d := newCancellationDownloader(t)
defer d.Close()
d.cfg.ExtensionEventTimeout = 30 * time.Millisecond
installCancellationExtension(t, d, "onStart", `gopeed.events.onStart(async ctx=>{await new Promise(()=>{});});`)
id, err := d.CreateDirect(&base.Request{URL: "generation://example.com/timeout"}, &base.Options{Path: t.TempDir()})
if err != nil {
t.Fatal(err)
}
waitForTaskStatus(t, d, id, base.DownloadStatusError, 2*time.Second)
if starts := d.cfg.FetchManagers[0].(*generationTestManager).starts.Load(); starts != 0 {
t.Fatalf("timed out onStart still started fetcher %d times", starts)
}
}
-15
View File
@@ -59,21 +59,6 @@ func (s *engineSession) Release() {
}
}
// Close releases retained resources when the owning event is cancelled.
func (s *engineSession) Close() {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return
}
s.closed = true
s.mu.Unlock()
s.runClosers()
if s.engine != nil {
s.engine.Close()
}
}
func (s *engineSession) CloseIfIdle() {
s.mu.Lock()
shouldClose := s.refs == 0 && !s.closed
+6 -12
View File
@@ -232,15 +232,12 @@ type DownloaderConfig struct {
Controller *controller.Controller
FetchManagers []fetcher.FetcherManager
// ExtensionEventTimeout bounds one script load and its awaited event handler.
// Zero uses one minute. Embedders may increase it for long-running handlers.
ExtensionEventTimeout time.Duration
RefreshInterval int // RefreshInterval time duration to refresh task progress(ms)
Storage Storage
StorageDir string
TempDir string
WhiteDownloadDirs []string
WebViewProvider enginewebview.Provider
RefreshInterval int // RefreshInterval time duration to refresh task progress(ms)
Storage Storage
StorageDir string
TempDir string
WhiteDownloadDirs []string
WebViewProvider enginewebview.Provider
ProductionMode bool
@@ -263,9 +260,6 @@ func (cfg *DownloaderConfig) Init() *DownloaderConfig {
new(ed2k.FetcherManager),
}
}
if cfg.ExtensionEventTimeout <= 0 {
cfg.ExtensionEventTimeout = time.Minute
}
if cfg.RefreshInterval == 0 {
cfg.RefreshInterval = 350
}
@@ -53,6 +53,7 @@ class AppRuntimeState {
class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
static StartConfig? _defaultStartConfig;
Future<void> _preferenceWrites = Future<void>.value();
bool _analyticsStarted = false;
@override
Future<AppRuntimeState> build() async {
@@ -73,6 +74,7 @@ class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
startConfig
..apiEnable = true
..mcpEnable = config.api.mcpEnable;
await _initAnalytics(config);
} else {
startConfig
..apiEnable = config.api.enable
@@ -253,7 +255,8 @@ class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
}
Future<void> _initAnalytics(DownloaderConfig config) async {
if (!AnalyticsConfig.isConfigured || !config.extra.analyticsEnabled) return;
if (_analyticsStarted || !AnalyticsConfig.isConfigured || !config.extra.analyticsEnabled) return;
_analyticsStarted = true;
try {
final generatedClientId = await Analytics.instance.init(fallbackClientId: config.extra.deviceId);
if (generatedClientId != null) {
@@ -262,6 +265,7 @@ class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
}
unawaited(Analytics.instance.logAppOpen());
} catch (error, stackTrace) {
_analyticsStarted = false;
logger.w('GA4 init failed', error, stackTrace);
}
}
@@ -19,7 +19,7 @@ Future<DownloaderConfig> loadDownloaderConfig({
config = await load();
} catch (error, stackTrace) {
onLoadError?.call(error, stackTrace);
config = DownloaderConfig();
config = DownloaderConfig()..extra.analyticsEnabled = false;
loaded = false;
}
final changed = await initDownloaderConfig(config, defaultDownloadDir: defaultDownloadDir);
@@ -19,6 +19,12 @@ class SettingsState {
}
}
class SettingsSaveResult {
const SettingsSaveResult({required this.btRestartRequired});
final bool btRestartRequired;
}
class SettingsController extends AsyncNotifier<SettingsState> {
Future<void> _saveTail = Future<void>.value();
int _saveRevision = 0;
@@ -36,7 +42,7 @@ class SettingsController extends AsyncNotifier<SettingsState> {
state = AsyncValue.data(SettingsState(config: config));
}
Future<void> save(DownloaderConfig config) {
Future<SettingsSaveResult> save(DownloaderConfig config) {
final snapshot = DownloaderConfig.fromJson(config.toJson());
final revision = ++_saveRevision;
state = AsyncValue.data(SettingsState(config: config, saving: true));
@@ -47,10 +53,15 @@ class SettingsController extends AsyncNotifier<SettingsState> {
return result;
}
Future<void> _save(DownloaderConfig config, int revision) async {
Future<SettingsSaveResult> _save(DownloaderConfig config, int revision) async {
try {
final service = ref.read(gopeedServiceProvider);
final latest = await service.getConfig();
final previousBt = (
latest.protocolConfig.bt.listenPort,
latest.protocolConfig.bt.disableDht,
latest.protocolConfig.bt.disablePex,
);
config.extra
..windowState = latest.extra.windowState
..bookmarks = latest.extra.bookmarks
@@ -64,6 +75,12 @@ class SettingsController extends AsyncNotifier<SettingsState> {
ref.read(appRuntimeControllerProvider.notifier).replaceDownloaderConfig(saved);
if (revision == _saveRevision) state = AsyncValue.data(SettingsState(config: saved));
}
final savedBt = (
saved.protocolConfig.bt.listenPort,
saved.protocolConfig.bt.disableDht,
saved.protocolConfig.bt.disablePex,
);
return SettingsSaveResult(btRestartRequired: previousBt != savedBt);
} finally {
if (ref.mounted && revision == _saveRevision && state.value?.saving == true) {
state = AsyncValue.data(state.requireValue.copyWith(saving: false));
@@ -625,7 +625,6 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
),
SettingsItem(
title: context.l10n.enableDht,
subtitle: context.l10n.restartRequired,
child: shad.Switch(
value: !config.protocolConfig.bt.disableDht,
onChanged: (value) => _mutateConfig((next) => next.protocolConfig.bt.disableDht = !value),
@@ -633,7 +632,6 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
),
SettingsItem(
title: context.l10n.enablePex,
subtitle: context.l10n.restartRequired,
child: shad.Switch(
value: !config.protocolConfig.bt.disablePex,
onChanged: (value) => _mutateConfig((next) => next.protocolConfig.bt.disablePex = !value),
@@ -1204,7 +1202,10 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
final snapshot = DownloaderConfig.fromJson(config.toJson());
_loadedSignature = _signature(snapshot);
try {
await ref.read(settingsControllerProvider.notifier).save(snapshot);
final result = await ref.read(settingsControllerProvider.notifier).save(snapshot);
if (mounted && result.btRestartRequired) {
_toast(context.l10n.restartRequired, type: AppToastType.info);
}
return true;
} catch (error) {
if (mounted) _toast(error.toString());
@@ -41,6 +41,7 @@ import '../../application/pending_download.dart';
import '../../application/task_list_navigation.dart';
import '../widgets/history_search_field.dart';
import '../widgets/create_task_action_buttons.dart';
import '../widgets/create_task_advanced_toggle.dart';
import '../widgets/resolve_download_dialog.dart';
class CreateTaskWindowPage extends ConsumerStatefulWidget {
@@ -560,20 +561,11 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
),
const SizedBox(height: 20),
Align(
alignment: Alignment.centerLeft,
child: GestureDetector(
onTap: _toggleAdvanced,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.advanced,
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w600),
),
const SizedBox(width: 8),
_TripleChevronIcon(expanded: _showAdvanced, color: palette.textSecondary),
],
),
alignment: AlignmentDirectional.centerStart,
child: CreateTaskAdvancedToggle(
key: const ValueKey('create-task-advanced-toggle'),
expanded: _showAdvanced,
onPressed: _toggleAdvanced,
),
),
AnimatedCrossFade(
@@ -1933,30 +1925,6 @@ class _MiniInputAction extends StatelessWidget {
}
}
class _TripleChevronIcon extends StatelessWidget {
const _TripleChevronIcon({required this.expanded, required this.color});
final bool expanded;
final Color color;
@override
Widget build(BuildContext context) {
final icon = expanded ? Icons.expand_less : Icons.expand_more;
return SizedBox(
width: 14,
height: 18,
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned(top: 0, left: 0, child: Icon(icon, size: 14, color: color)),
Positioned(top: 4, left: 0, child: Icon(icon, size: 14, color: color)),
Positioned(top: 8, left: 0, child: Icon(icon, size: 14, color: color)),
],
),
);
}
}
class _SegmentButton extends StatelessWidget {
const _SegmentButton({required this.label, required this.active, required this.onTap});
@@ -0,0 +1,49 @@
import 'package:shadcn_flutter/shadcn_flutter.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
/// A quiet disclosure control with the same keyboard behavior as other buttons.
class CreateTaskAdvancedToggle extends StatelessWidget {
const CreateTaskAdvancedToggle({super.key, required this.expanded, required this.onPressed});
final bool expanded;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final reduceMotion = MediaQuery.disableAnimationsOf(context);
return Semantics(
expanded: expanded,
child: ButtonStyleOverride.inherit(
padding: (context, states, value) => const EdgeInsets.symmetric(vertical: AppDesignTokens.space12),
child: GhostButton(
onPressed: onPressed,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 20),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
context.l10n.advanced,
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w600),
),
),
const SizedBox(width: AppDesignTokens.space8),
AnimatedRotation(
turns: expanded ? 0.5 : 0,
duration: reduceMotion ? Duration.zero : const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
child: Icon(Icons.keyboard_arrow_down, size: 16, color: palette.textSecondary),
),
],
),
),
),
),
);
}
}
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "اسم الفئة",
"categoryPath": "مسار الفئة",
"autoCategorizeByExtension": "تصنيف تلقائي حسب نوع الملف",
"autoCategorizeByExtensionDescription": "توجيه التنزيلات إلى مجلد الفئة تلقائيًا حسب امتداد الملف عند الحفظ في مجلد التنزيل الافتراضي.",
"autoCategorizeByExtensionDescription": "توجيه التنزيلات إلى مجلد الفئة تلقائيًا حسب امتداد الملف عند الحفظ في مجلد التنزيل الافتراضي",
"categoryExtensions": "امتدادات الملفات",
"categoryExtensionsUsageHint": "افصل الامتدادات بفواصل أو مسافات ثم اضغط Enter.",
"categoryExtensionsEmptyHint": "بدون الامتدادات، لن تُحفظ الملفات في هذا التصنيف تلقائيًا.",
+1 -1
View File
@@ -215,7 +215,7 @@
"categoryName": "Kateqoriyanın Adı",
"categoryPath": "Kateqoriyanın Yolu",
"autoCategorizeByExtension": "Fayl tipinə görə avtomatik kateqoriyalaşdırma",
"autoCategorizeByExtensionDescription": "Standart yükləmə qovluğuna yadda saxlanarkən yükləmələr fayl uzantısına görə avtomatik olaraq kateqoriya qovluğuna yönləndirilir.",
"autoCategorizeByExtensionDescription": "Standart yükləmə qovluğuna yadda saxlanarkən yükləmələr fayl uzantısına görə avtomatik olaraq kateqoriya qovluğuna yönləndirilir",
"categoryExtensions": "Fayl uzantıları",
"categoryExtensionsUsageHint": "Uzantıları vergül və ya boşluqla ayırın, sonra Enter-a basın.",
"categoryExtensionsEmptyHint": "Uzantı yoxdursa, fayllar bu kateqoriyaya avtomatik olaraq saxlanmır.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nom de la categoria",
"categoryPath": "Ruta de la categoria",
"autoCategorizeByExtension": "Categoritza automàticament segons el tipus de fitxer",
"autoCategorizeByExtensionDescription": "Les baixades es desen a la carpeta de categoria segons l'extensió del fitxer en utilitzar la carpeta de baixades predeterminada.",
"autoCategorizeByExtensionDescription": "Les baixades es desen a la carpeta de categoria segons l'extensió del fitxer en utilitzar la carpeta de baixades predeterminada",
"categoryExtensions": "Extensions de fitxer",
"categoryExtensionsUsageHint": "Separa les extensions amb comes o espais i prem Retorn.",
"categoryExtensionsEmptyHint": "Sense extensions, els fitxers no es desaran aquí automàticament.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Kategoriename",
"categoryPath": "Kategoriepfad",
"autoCategorizeByExtension": "Nach Dateityp automatisch kategorisieren",
"autoCategorizeByExtensionDescription": "Downloads werden beim Speichern im Standard-Download-Ordner anhand der Dateiendung automatisch einem Kategorieordner zugeordnet.",
"autoCategorizeByExtensionDescription": "Downloads werden beim Speichern im Standard-Download-Ordner anhand der Dateiendung automatisch einem Kategorieordner zugeordnet",
"categoryExtensions": "Dateiendungen",
"categoryExtensionsUsageHint": "Trenne Endungen mit Kommas oder Leerzeichen und drücke Enter.",
"categoryExtensionsEmptyHint": "Ohne Endungen werden Dateien nicht automatisch dieser Kategorie zugeordnet.",
+1 -1
View File
@@ -222,7 +222,7 @@
"categoryName": "Category Name",
"categoryPath": "Category Path",
"autoCategorizeByExtension": "Auto-categorize by file type",
"autoCategorizeByExtensionDescription": "Automatically route downloads into a category folder based on the file name when saving to the default download folder.",
"autoCategorizeByExtensionDescription": "Automatically route downloads into a category folder based on the file name when saving to the default download folder",
"categoryExtensions": "Associated Extensions",
"categoryExtensionsUsageHint": "Separate suffixes with commas or spaces, then press Enter.",
"categoryExtensionsEmptyHint": "Without extensions, files won't be saved into this category automatically.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nombre de categoría",
"categoryPath": "Ruta de categoría",
"autoCategorizeByExtension": "Categorizar automáticamente por tipo de archivo",
"autoCategorizeByExtensionDescription": "Las descargas se guardan automáticamente en la carpeta de categoría según la extensión del archivo al usar la carpeta de descargas predeterminada.",
"autoCategorizeByExtensionDescription": "Las descargas se guardan automáticamente en la carpeta de categoría según la extensión del archivo al usar la carpeta de descargas predeterminada",
"categoryExtensions": "Extensiones de archivo",
"categoryExtensionsUsageHint": "Separa las extensiones con comas o espacios y pulsa Intro.",
"categoryExtensionsEmptyHint": "Sin extensiones, los archivos no se guardarán automáticamente en esta categoría.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "نام دسته‌بندی",
"categoryPath": "مسیر دسته‌بندی",
"autoCategorizeByExtension": "دسته‌بندی خودکار بر اساس نوع فایل",
"autoCategorizeByExtensionDescription": "هنگام ذخیره در پوشه پیش‌فرض دانلود، دانلودها بر اساس پسوند فایل به پوشه دسته مربوطه منتقل می‌شوند.",
"autoCategorizeByExtensionDescription": "هنگام ذخیره در پوشه پیش‌فرض دانلود، دانلودها بر اساس پسوند فایل به پوشه دسته مربوطه منتقل می‌شوند",
"categoryExtensions": "پسوندهای فایل",
"categoryExtensionsUsageHint": "پسوندها را با ویرگول یا فاصله جدا کنید و Enter را بزنید.",
"categoryExtensionsEmptyHint": "بدون پسوندها، فایل‌ها به‌صورت خودکار در این دسته ذخیره نمی‌شوند.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nom de la catégorie",
"categoryPath": "Chemin de la catégorie",
"autoCategorizeByExtension": "Catégoriser automatiquement selon le type de fichier",
"autoCategorizeByExtensionDescription": "Les téléchargements sont placés dans un dossier de catégorie selon l'extension du fichier lors de l'enregistrement dans le dossier de téléchargement par défaut.",
"autoCategorizeByExtensionDescription": "Les téléchargements sont placés dans un dossier de catégorie selon l'extension du fichier lors de l'enregistrement dans le dossier de téléchargement par défaut",
"categoryExtensions": "Extensions de fichier",
"categoryExtensionsUsageHint": "Séparez les extensions par virgules ou espaces, puis appuyez sur Entrée.",
"categoryExtensionsEmptyHint": "Sans extensions, les fichiers ne seront pas enregistrés ici automatiquement.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Kategória neve",
"categoryPath": "Kategória útvonala",
"autoCategorizeByExtension": "Automatikus kategorizálás fájltípus szerint",
"autoCategorizeByExtensionDescription": "Az alapértelmezett letöltési mappa használatakor a letöltések a fájl kiterjesztése alapján automatikusan a kategória mappájába kerülnek.",
"autoCategorizeByExtensionDescription": "Az alapértelmezett letöltési mappa használatakor a letöltések a fájl kiterjesztése alapján automatikusan a kategória mappájába kerülnek",
"categoryExtensions": "Fájlkiterjesztések",
"categoryExtensionsUsageHint": "A kiterjesztéseket vesszővel vagy szóközzel válaszd el, majd nyomd le az Enter billentyűt.",
"categoryExtensionsEmptyHint": "Kiterjesztések nélkül a fájlok nem kerülnek automatikusan ebbe a kategóriába.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nama Kategori",
"categoryPath": "Path Kategori",
"autoCategorizeByExtension": "Kategorikan otomatis berdasarkan jenis file",
"autoCategorizeByExtensionDescription": "Unduhan dialihkan ke folder kategori berdasarkan ekstensi file saat disimpan ke folder unduhan bawaan.",
"autoCategorizeByExtensionDescription": "Unduhan dialihkan ke folder kategori berdasarkan ekstensi file saat disimpan ke folder unduhan bawaan",
"categoryExtensions": "Ekstensi file",
"categoryExtensionsUsageHint": "Pisahkan ekstensi dengan koma atau spasi, lalu tekan Enter.",
"categoryExtensionsEmptyHint": "Tanpa ekstensi, file tidak akan otomatis disimpan ke kategori ini.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nome categoria",
"categoryPath": "Percorso categoria",
"autoCategorizeByExtension": "Categorizza automaticamente per tipo di file",
"autoCategorizeByExtensionDescription": "Il download viene instradato automaticamente nella cartella della categoria in base all'estensione quando si salva nella cartella di download predefinita.",
"autoCategorizeByExtensionDescription": "Il download viene instradato automaticamente nella cartella della categoria in base all'estensione quando si salva nella cartella di download predefinita",
"categoryExtensions": "Estensioni file",
"categoryExtensionsUsageHint": "Separa le estensioni con virgole o spazi e premi Invio.",
"categoryExtensionsEmptyHint": "Senza estensioni, i file non verranno salvati qui automaticamente.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "カテゴリ名",
"categoryPath": "カテゴリパス",
"autoCategorizeByExtension": "ファイル種別で自動分類",
"autoCategorizeByExtensionDescription": "既定のダウンロードフォルダーに保存する際、拡張子に基づいて分類フォルダーへ自動的に振り分けます。",
"autoCategorizeByExtensionDescription": "既定のダウンロードフォルダーに保存する際、拡張子に基づいて分類フォルダーへ自動的に振り分けます",
"categoryExtensions": "ファイル拡張子",
"categoryExtensionsUsageHint": "カンマやスペースで拡張子を区切り、Enterで追加します。",
"categoryExtensionsEmptyHint": "拡張子が未設定の場合、ファイルは自動的にこの分類へ保存されません。",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "카테고리 이름",
"categoryPath": "카테고리 경로",
"autoCategorizeByExtension": "파일 형식별 자동 분류",
"autoCategorizeByExtensionDescription": "기본 다운로드 폴더에 저장할 때 확장자에 따라 분류 폴더로 자동 이동합니다.",
"autoCategorizeByExtensionDescription": "기본 다운로드 폴더에 저장할 때 확장자에 따라 분류 폴더로 자동 이동합니다",
"categoryExtensions": "파일 확장자",
"categoryExtensionsUsageHint": "쉼표나 공백으로 확장자를 구분하고 Enter를 눌러 추가하세요.",
"categoryExtensionsEmptyHint": "확장자가 없으면 파일이 이 분류로 자동 저장되지 않습니다.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nazwa kategorii",
"categoryPath": "Ścieżka kategorii",
"autoCategorizeByExtension": "Automatyczna kategorizacja według typu pliku",
"autoCategorizeByExtensionDescription": "Pobierane pliki są automatycznie zapisywane w folderze kategorii na podstawie rozszerzenia, gdy używany jest domyślny folder pobierania.",
"autoCategorizeByExtensionDescription": "Pobierane pliki są automatycznie zapisywane w folderze kategorii na podstawie rozszerzenia, gdy używany jest domyślny folder pobierania",
"categoryExtensions": "Rozszerzenia plików",
"categoryExtensionsUsageHint": "Rozdzielaj rozszerzenia przecinkami lub spacjami i naciskaj Enter.",
"categoryExtensionsEmptyHint": "Bez rozszerzeń pliki nie będą automatycznie zapisywane w tej kategorii.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Nome da Categoria",
"categoryPath": "Caminho da Categoria",
"autoCategorizeByExtension": "Categorizar automaticamente por tipo de arquivo",
"autoCategorizeByExtensionDescription": "Envia os downloads para a pasta da categoria com base na extensão ao salvar na pasta de download padrão.",
"autoCategorizeByExtensionDescription": "Envia os downloads para a pasta da categoria com base na extensão ao salvar na pasta de download padrão",
"categoryExtensions": "Extensões de arquivo",
"categoryExtensionsUsageHint": "Separe as extensões com vírgulas ou espaços e prima Enter.",
"categoryExtensionsEmptyHint": "Sem extensões, os ficheiros não serão guardados aqui automaticamente.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Название категории",
"categoryPath": "Путь категории",
"autoCategorizeByExtension": "Автокатегоризация по типу файла",
"autoCategorizeByExtensionDescription": "Загрузки автоматически сохраняются в папку категории по расширению файла, если выбрана папка загрузки по умолчанию.",
"autoCategorizeByExtensionDescription": "Загрузки автоматически сохраняются в папку категории по расширению файла, если выбрана папка загрузки по умолчанию",
"categoryExtensions": "Расширения файлов",
"categoryExtensionsUsageHint": "Разделяйте расширения запятыми или пробелами и нажимайте Enter.",
"categoryExtensionsEmptyHint": "Без расширений файлы не будут автоматически сохранены в эту категорию.",
+1 -1
View File
@@ -222,7 +222,7 @@
"categoryName": "Názov kategórie",
"categoryPath": "Cesta kategórie",
"autoCategorizeByExtension": "Automatická kategorizácia podľa typu súboru",
"autoCategorizeByExtensionDescription": "Sťahovania sa pri ukladaní do predvoleného priečinka sťahovania automaticky presúvajú do priečinka kategórie podľa prípony súboru.",
"autoCategorizeByExtensionDescription": "Sťahovania sa pri ukladaní do predvoleného priečinka sťahovania automaticky presúvajú do priečinka kategórie podľa prípony súboru",
"categoryExtensions": "Prípony súborov",
"categoryExtensionsUsageHint": "Oddeľujte prípony čiarkami alebo medzerami a stlačte Enter.",
"categoryExtensionsEmptyHint": "Bez prípon sa súbory automaticky neuložia do tejto kategórie.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "வகை பெயர்",
"categoryPath": "வகை பாதை",
"autoCategorizeByExtension": "கோப்பு வகை வாரியாக தானாக வகைப்படுத்து",
"autoCategorizeByExtensionDescription": "இயல்புநிலை பதிவிறக்கக் கோப்புறையில் சேமிக்கும்போது, கோப்பு நீட்டிப்பின் அடிப்படையில் வகைக் கோப்புறைக்கு தானாக அனுப்பப்படும்.",
"autoCategorizeByExtensionDescription": "இயல்புநிலை பதிவிறக்கக் கோப்புறையில் சேமிக்கும்போது, கோப்பு நீட்டிப்பின் அடிப்படையில் வகைக் கோப்புறைக்கு தானாக அனுப்பப்படும்",
"categoryExtensions": "கோப்பு நீட்டிப்புகள்",
"categoryExtensionsUsageHint": "நீட்டிப்புகளை காற்புள்ளிகள் அல்லது இடைவெளிகளால் பிரித்து Enter அழுத்தவும்.",
"categoryExtensionsEmptyHint": "நீட்டிப்புகள் இல்லாததால், கோப்புகள் இந்த வகைப்பாட்டில் தானாகச் சேமிக்கப்படாது.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Kategori Adı",
"categoryPath": "Kategori Yolu",
"autoCategorizeByExtension": "Dosya tipine göre otomatik sınıflandır",
"autoCategorizeByExtensionDescription": "Varsayılan indirme klasörüne kaydedilirken dosya uzantısına göre ilgili klasöre otomatik yönlendirir.",
"autoCategorizeByExtensionDescription": "Varsayılan indirme klasörüne kaydedilirken dosya uzantısına göre ilgili klasöre otomatik yönlendirir",
"categoryExtensions": "Dosya uzantıları",
"categoryExtensionsUsageHint": "Sonekleri virgül veya boşlukla ayırıp Enter'a basın.",
"categoryExtensionsEmptyHint": "Uzantı yoksa dosyalar bu kategoriye otomatik olarak kaydedilmez.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Назва категорії",
"categoryPath": "Шлях категорії",
"autoCategorizeByExtension": "Автокатегоризація за типом файлу",
"autoCategorizeByExtensionDescription": "Завантаження автоматично зберігаються в папку категорії за розширенням файлу, якщо вибрано папку завантаження за замовчуванням.",
"autoCategorizeByExtensionDescription": "Завантаження автоматично зберігаються в папку категорії за розширенням файлу, якщо вибрано папку завантаження за замовчуванням",
"categoryExtensions": "Розширення файлів",
"categoryExtensionsUsageHint": "Розділяйте розширення комами або пробілами та натискайте Enter.",
"categoryExtensionsEmptyHint": "Без розширень файли не зберігатимуться в цю категорію автоматично.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "Tên danh mục",
"categoryPath": "Đường dẫn danh mục",
"autoCategorizeByExtension": "Tự động phân loại theo loại tệp",
"autoCategorizeByExtensionDescription": "Tải xuống sẽ được chuyển vào thư mục danh mục dựa trên phần mở rộng tệp khi lưu vào thư mục tải xuống mặc định.",
"autoCategorizeByExtensionDescription": "Tải xuống sẽ được chuyển vào thư mục danh mục dựa trên phần mở rộng tệp khi lưu vào thư mục tải xuống mặc định",
"categoryExtensions": "Phần mở rộng tệp",
"categoryExtensionsUsageHint": "Phân tách phần mở rộng bằng dấu phẩy hoặc khoảng trắng rồi nhấn Enter.",
"categoryExtensionsEmptyHint": "Không có phần mở rộng, tệp sẽ không tự động được lưu vào danh mục này.",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "分类名称",
"categoryPath": "分类路径",
"autoCategorizeByExtension": "按文件类型自动分类",
"autoCategorizeByExtensionDescription": "保存到默认下载目录时,根据文件后缀自动归入对应分类文件夹。",
"autoCategorizeByExtensionDescription": "保存到默认下载目录时,根据文件后缀自动归入对应分类文件夹",
"categoryExtensions": "文件后缀关联",
"categoryExtensionsUsageHint": "支持逗号/空格分隔后缀,按回车添加。",
"categoryExtensionsEmptyHint": "未设置后缀,文件不会自动归入此分类。",
+1 -1
View File
@@ -208,7 +208,7 @@
"categoryName": "分類名稱",
"categoryPath": "分類路徑",
"autoCategorizeByExtension": "按檔案類型自動分類",
"autoCategorizeByExtensionDescription": "儲存至預設下載目錄時,根據檔案副檔名自動歸入對應分類資料夾。",
"autoCategorizeByExtensionDescription": "儲存至預設下載目錄時,根據檔案副檔名自動歸入對應分類資料夾",
"categoryExtensions": "檔案副檔名",
"categoryExtensionsUsageHint": "支援逗號/空白分隔後綴,按回車新增。",
"categoryExtensionsEmptyHint": "未設定後綴,檔案不會自動歸入此分類。",
@@ -32,8 +32,22 @@ void main() {
// The in-memory fallback still gets usable defaults.
expect(config.downloadDir, '/downloads');
expect(config.categories, hasLength(4));
expect(config.extra.analyticsEnabled, isFalse);
});
for (final analyticsEnabled in [false, true]) {
test('preserves the saved analytics preference ($analyticsEnabled)', () async {
final stored = configWith()..extra.analyticsEnabled = analyticsEnabled;
final config = await loadDownloaderConfig(
load: () async => stored,
save: (_) async {},
defaultDownloadDir: () async => '/downloads',
);
expect(config.extra.analyticsEnabled, analyticsEnabled);
});
}
test('skips persist when init changed nothing', () async {
var saved = 0;
await loadDownloaderConfig(
@@ -99,6 +99,43 @@ void main() {
expect(saved.saving, isFalse);
});
for (final field in ['port', 'DHT', 'PEX']) {
test('$field restart notice follows successful persisted changes only', () async {
var backend = DownloaderConfig();
var failNextSave = false;
final registry = CapabilityRegistry(createAppCapabilityCodecs())
..bind(GopeedMethods.getConfig, (_) => DownloaderConfig.fromJson(backend.toJson()))
..bind(GopeedMethods.putConfig, (config) {
if (failNextSave) {
failNextSave = false;
throw StateError('offline');
}
backend = DownloaderConfig.fromJson(config.toJson());
return const RpcUnit();
});
final container = _settingsContainer(registry);
addTearDown(container.dispose);
final initial = await container.read(settingsControllerProvider.future);
final controller = container.read(settingsControllerProvider.notifier);
final draft = DownloaderConfig.fromJson(initial.config.toJson());
switch (field) {
case 'port':
draft.protocolConfig.bt.listenPort = 6881;
case 'DHT':
draft.protocolConfig.bt.disableDht = true;
case 'PEX':
draft.protocolConfig.bt.disablePex = true;
}
failNextSave = true;
await expectLater(controller.save(draft), throwsStateError);
expect((await controller.save(draft)).btRestartRequired, isTrue);
expect((await controller.save(draft)).btRestartRequired, isFalse);
draft.protocolConfig.bt.seedRatio = 2;
expect((await controller.save(draft)).btRestartRequired, isFalse);
expect((await controller.save(initial.config)).btRestartRequired, isTrue);
});
}
test('rapid full config saves run in order and keep the latest user edits', () async {
final backend = DownloaderConfig();
final entered = Completer<void>();
@@ -127,7 +164,8 @@ void main() {
final savingSecond = controller.save(second);
expect(puts.length, 1);
release.complete();
await Future.wait([savingFirst, savingSecond]);
final results = await Future.wait([savingFirst, savingSecond]);
expect(results.map((result) => result.btRestartRequired), [true, false]);
expect(puts, hasLength(2));
expect(puts[0].protocolConfig.bt.listenPort, 6881);
expect(puts[1].protocolConfig.bt.listenPort, 6881);
@@ -0,0 +1,59 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/features/tasks/presentation/widgets/create_task_advanced_toggle.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
for (final width in [360.0, 768.0, 1024.0]) {
testWidgets('advanced disclosure supports keyboard and touch at width $width', (tester) async {
tester.view.physicalSize = Size(width, 768);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
var expanded = false;
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
home: AppComponentThemes(
child: StatefulBuilder(
builder: (context, setState) => Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: CreateTaskAdvancedToggle(
expanded: expanded,
onPressed: () => setState(() => expanded = !expanded),
),
),
),
),
),
),
);
await tester.pumpAndSettle();
expect(tester.getSize(find.byType(shad.GhostButton)).height, greaterThanOrEqualTo(44));
expect(
find.byWidgetPredicate((widget) => widget is Semantics && widget.properties.expanded == false),
findsOneWidget,
);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(expanded, isTrue);
expect(
find.byWidgetPredicate((widget) => widget is Semantics && widget.properties.expanded == true),
findsOneWidget,
);
await tester.tap(find.text('Advanced'));
await tester.pumpAndSettle();
expect(expanded, isFalse);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
});
}
}
+44 -1
View File
@@ -1636,6 +1636,46 @@ void main() {
expect(tester.takeException(), isNull);
});
testWidgets('BT settings show a restart message only after an affected auto-save', (tester) async {
await _setTestSize(tester, const Size(1024, 900));
final controller = FakeSettingsController()..btRestartRequired = true;
await tester.pumpWidget(
ProviderScope(
overrides: [
appRuntimeControllerProvider.overrideWith(FakeRuntimeController.new),
appPlatformControllerProvider.overrideWith(FakePlatformController.new),
settingsControllerProvider.overrideWith(() => controller),
],
child: const _SettingsTestApp(),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Downloads'));
await tester.pumpAndSettle();
const message = 'This setting takes effect after restarting the app';
expect(find.text(message), findsNothing);
final port = find.byKey(const ValueKey('bt-listen-port-input'));
await tester.ensureVisible(port);
await tester.pumpAndSettle();
await tester.enterText(port, '6881');
await tester.pump(const Duration(milliseconds: 500));
expect(find.text(message), findsNothing);
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 300));
expect(find.text(message), findsOneWidget);
expect(tester.widget<AppToastContent>(find.byType(AppToastContent)).type, AppToastType.info);
await tester.pump(const Duration(seconds: 6));
await tester.pumpAndSettle();
controller.btRestartRequired = false;
final seedRatio = find.byKey(const ValueKey('bt-seed-ratio-input'));
await tester.ensureVisible(seedRatio);
await tester.enterText(seedRatio, '2');
await tester.pump(const Duration(milliseconds: 700));
await tester.pumpAndSettle();
expect(find.text(message), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('settings FTP connections save into the FTP protocol config', (WidgetTester tester) async {
await _setTestSize(tester, const Size(1024, 900));
final settingsController = FakeSettingsController();
@@ -6181,12 +6221,15 @@ ApiServerState _testApiServerState({
}
class FakeSettingsController extends SettingsController {
bool btRestartRequired = false;
@override
Future<SettingsState> build() async => SettingsState(config: DownloaderConfig());
@override
Future<void> save(DownloaderConfig config) async {
Future<SettingsSaveResult> save(DownloaderConfig config) async {
state = AsyncValue.data(SettingsState(config: config));
return SettingsSaveResult(btRestartRequired: btRestartRequired);
}
}