Compare commits

..
36 changed files with 286 additions and 413 deletions

No files matched your search

-259
View File
@@ -1,259 +0,0 @@
package download
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/GopeedLab/gopeed/internal/fetcher"
"github.com/GopeedLab/gopeed/pkg/base"
)
type deleteResolveManager struct {
*generationTestManager
returned chan struct{}
}
func (m *deleteResolveManager) Build() fetcher.Fetcher {
return &deleteResolveFetcher{generationTestFetcher: m.generationTestManager.Build().(*generationTestFetcher), returned: m.returned}
}
type deleteResolveFetcher struct {
*generationTestFetcher
returned chan struct{}
}
func (f *deleteResolveFetcher) Resolve(req *base.Request) error {
defer close(f.returned)
return f.generationTestFetcher.Resolve(req)
}
func waitDeleteTest(t *testing.T, ch <-chan struct{}) {
t.Helper()
select {
case <-ch:
case <-time.After(3 * time.Second):
t.Fatal("operation did not finish")
}
}
func TestDeleteDuringResolveCannotRestartOrPersist(t *testing.T) {
for _, force := range []bool{false, true} {
for _, resolveErr := range []error{nil, errors.New("late resolve error")} {
t.Run(fmt.Sprintf("force=%v/error=%v", force, resolveErr != nil), func(t *testing.T) {
release := make(chan struct{})
var once sync.Once
defer once.Do(func() { close(release) })
m := &deleteResolveManager{generationTestManager: &generationTestManager{resolveStarted: make(chan struct{}), resolveRelease: release, resolveErr: resolveErr}, returned: make(chan struct{})}
d := NewDownloader(&DownloaderConfig{Storage: NewMemStorage(), StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{m}})
if err := d.Setup(); err != nil {
t.Fatal(err)
}
defer d.Close()
id, err := d.CreateDirect(&base.Request{URL: "generation://delete"}, &base.Options{Path: t.TempDir(), Name: "delete.bin"})
if err != nil {
t.Fatal(err)
}
waitDeleteTest(t, m.resolveStarted)
task := d.GetTask(id)
if err := d.Delete(&TaskFilter{IDs: []string{id}}, force); err != nil {
t.Fatal(err)
}
once.Do(func() { close(release) })
waitDeleteTest(t, m.returned)
task.lock.Lock()
task.lock.Unlock()
// A stale error callback can run immediately after the startup handler exits.
d.doOnError(task, errors.New("late callback"))
if got := m.starts.Load(); got != 0 {
t.Errorf("deleted task started %d time(s)", got)
}
if d.GetTask(id) != nil {
t.Error("deleted task is still listed")
}
for _, bucket := range []string{bucketTask, bucketSave, bucketTaskStats} {
var value any
present, err := d.storage.Get(bucket, id, &value)
if err != nil {
t.Fatal(err)
}
if present {
t.Errorf("deleted task resurrected in %s", bucket)
}
}
})
}
}
}
type blockedTaskStorage struct {
Storage
entered chan struct{}
release chan struct{}
blockID string
once sync.Once
}
func (s *blockedTaskStorage) Put(bucket, key string, value any) error {
if bucket == bucketTask && key == s.blockID {
s.once.Do(func() { close(s.entered); <-s.release })
}
return s.Storage.Put(bucket, key, value)
}
func TestDeleteSerializesInFlightTaskCheckpoint(t *testing.T) {
s := &blockedTaskStorage{Storage: NewMemStorage(), entered: make(chan struct{}), release: make(chan struct{})}
d := NewDownloader(&DownloaderConfig{Storage: s, StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{&generationTestManager{}}})
if err := d.Setup(); err != nil {
t.Fatal(err)
}
defer d.Close()
d.cfg.MaxRunning = 0
id, err := d.CreateDirect(&base.Request{URL: "generation://checkpoint"}, &base.Options{Path: t.TempDir()})
if err != nil {
t.Fatal(err)
}
task := d.GetTask(id)
s.blockID = id
saved := make(chan struct{})
go func() { defer close(saved); _ = d.saveTask(task) }()
waitDeleteTest(t, s.entered)
deleted := make(chan struct{})
go func() { defer close(deleted); _ = d.Delete(&TaskFilter{IDs: []string{id}}, false) }()
deadline := time.Now().Add(3 * time.Second)
for d.GetTask(id) != nil && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
close(s.release)
waitDeleteTest(t, saved)
waitDeleteTest(t, deleted)
var value any
present, err := s.Get(bucketTask, id, &value)
if err != nil {
t.Fatal(err)
}
if present {
t.Fatal("in-flight checkpoint restored a deleted task")
}
}
func TestDeleteDuringPreparationCannotStartOrPersist(t *testing.T) {
s := &blockedTaskStorage{Storage: NewMemStorage(), entered: make(chan struct{}), release: make(chan struct{})}
m := &generationTestManager{}
d := NewDownloader(&DownloaderConfig{Storage: s, StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{m}})
if err := d.Setup(); err != nil {
t.Fatal(err)
}
defer d.Close()
d.cfg.MaxRunning = 0
id, err := d.CreateDirect(&base.Request{URL: "generation://preparation"}, &base.Options{Path: t.TempDir()})
if err != nil {
t.Fatal(err)
}
task := d.GetTask(id)
s.blockID = id
d.cfg.MaxRunning = 1
if err := d.Continue(&TaskFilter{IDs: []string{id}}); err != nil {
t.Fatal(err)
}
waitDeleteTest(t, s.entered)
done := make(chan struct{})
go func() { defer close(done); _ = d.Delete(&TaskFilter{IDs: []string{id}}, true) }()
deadline := time.Now().Add(2 * time.Second)
for d.GetTask(id) != nil && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
close(s.release)
waitDeleteTest(t, done)
task.lock.Lock()
task.lock.Unlock()
if m.starts.Load() != 0 {
t.Fatal("deleted preparation started downloading")
}
var saved Task
if exists, err := s.Get(bucketTask, id, &saved); err != nil || exists {
t.Fatalf("deleted preparation persisted: exists=%v err=%v", exists, err)
}
}
func TestDeletedTaskRejectsLateSnapshotsAndCompletion(t *testing.T) {
d := NewDownloader(&DownloaderConfig{Storage: NewMemStorage(), StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{&generationTestManager{}}})
if err := d.Setup(); err != nil {
t.Fatal(err)
}
defer d.Close()
d.cfg.MaxRunning = 0
id, err := d.CreateDirect(&base.Request{URL: "generation://late"}, &base.Options{Path: t.TempDir()})
if err != nil {
t.Fatal(err)
}
task := d.GetTask(id)
snapshot := task.clone()
task.fetcher.(*generationTestFetcher).stats = &fetcher.Stats{Snapshot: map[string]any{"bytes": 1}}
if err := d.Delete(&TaskFilter{IDs: []string{id}}, false); err != nil {
t.Fatal(err)
}
if err := d.putTaskRecord(task, snapshot); err != nil {
t.Fatal(err)
}
if err := d.captureTaskStats(task, false, true); err != nil {
t.Fatal(err)
}
if err := d.saveTask(task); err != nil {
t.Fatal(err)
}
if d.markTaskDone(task) {
t.Error("deleted task accepted a late completion")
}
for _, bucket := range []string{bucketTask, bucketSave, bucketTaskStats} {
var value any
if exists, err := d.storage.Get(bucket, id, &value); err != nil || exists {
t.Errorf("late callback restored %s: exists=%v err=%v", bucket, exists, err)
}
}
}
type singleFailureTaskDeleteStorage struct {
Storage
fail atomic.Bool
}
func (s *singleFailureTaskDeleteStorage) Delete(bucket, key string) error {
if bucket == bucketTask && s.fail.Swap(false) {
return errors.New("task deletion failed")
}
return s.Storage.Delete(bucket, key)
}
func TestFailedDeleteCanBeRetriedWithoutRevivingOldRun(t *testing.T) {
s := &singleFailureTaskDeleteStorage{Storage: NewMemStorage()}
m := &generationTestManager{holdOpen: true}
d := NewDownloader(&DownloaderConfig{Storage: s, StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{m}})
if err := d.Setup(); err != nil {
t.Fatal(err)
}
defer d.Close()
d.cfg.MaxRunning = 0
id, err := d.CreateDirect(&base.Request{URL: "generation://failed-delete"}, &base.Options{Path: t.TempDir()})
if err != nil {
t.Fatal(err)
}
s.fail.Store(true)
if err := d.Delete(&TaskFilter{IDs: []string{id}}, false); err == nil {
t.Fatal("expected storage deletion failure")
}
task := d.GetTask(id)
if task == nil || d.taskStatus(task) != base.DownloadStatusWait {
t.Fatal("failed deletion did not restore queued task")
}
d.cfg.MaxRunning = 1
if err := d.Continue(&TaskFilter{IDs: []string{id}}); err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(time.Second)
for m.starts.Load() < 1 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if m.starts.Load() != 1 {
t.Fatal("failed deletion could not be retried")
}
}
+23 -73
View File
@@ -508,31 +508,7 @@ func (d *Downloader) setupFetcher(fm fetcher.FetcherManager, fetcher fetcher.Fet
fetcher.Setup(ctl)
}
// putTaskValue serializes late progress/completion callbacks with deletion.
// A snapshot may have been captured before Delete removed the task.
func (d *Downloader) putTaskValue(task *Task, bucket string, value any) error {
if task.lifetime != nil {
task.lifetime.mu.Lock()
defer task.lifetime.mu.Unlock()
if task.lifetime.deleted.Load() {
return nil
}
}
return d.storage.Put(bucket, task.ID, value)
}
func (d *Downloader) putTaskRecord(task *Task, snapshot *Task) error {
return d.putTaskValue(task, bucketTask, snapshot)
}
func (d *Downloader) saveTask(task *Task) error {
if task.lifetime != nil {
task.lifetime.mu.Lock()
defer task.lifetime.mu.Unlock()
if task.lifetime.deleted.Load() {
return nil
}
}
data, err := task.fetcherManager.Store(task.fetcher)
if err != nil {
d.Logger.Error().Stack().Err(err).Msgf("serialize fetcher failed: %s", task.ID)
@@ -1244,7 +1220,7 @@ func (d *Downloader) Delete(filter *TaskFilter, force bool) error {
for _, task := range tasks {
if err := d.doDelete(task, force); err != nil {
// Deletion can fail after removing bucketTask. Keep recovery durable.
if saveErr := d.putTaskRecord(task, task.clone()); saveErr != nil {
if saveErr := d.storage.Put(bucketTask, task.ID, task.clone()); saveErr != nil {
d.Logger.Error().Err(saveErr).Msg("restore failed task deletion failed")
if firstErr == nil {
firstErr = saveErr
@@ -1436,7 +1412,7 @@ func (d *Downloader) captureTaskStats(task *Task, live, force bool) error {
return nil
}
if err := d.putTaskValue(task, bucketTaskStats, &storedTaskStats{Snapshot: snapshot}); err != nil {
if err := d.storage.Put(bucketTaskStats, task.ID, &storedTaskStats{Snapshot: snapshot}); err != nil {
return err
}
task.statsSnapshot = append(task.statsSnapshot[:0], snapshot...)
@@ -1542,18 +1518,6 @@ func (d *Downloader) RuntimeStatus(id string) (*TaskRuntimeStatus, error) {
}
func (d *Downloader) doDelete(task *Task, force bool) (err error) {
task.lifetime.deleted.Store(true)
task.statusLock.Lock()
task.runGeneration++
task.statusLock.Unlock()
task.lifetime.mu.Lock()
defer task.lifetime.mu.Unlock()
defer func() {
if err != nil {
// Keep failed deletions recoverable without validating the old run.
task.lifetime.deleted.Store(false)
}
}()
defer d.releaseBlobTask(task)
err = func() error {
if err := d.storage.Delete(bucketTask, task.ID); err != nil {
@@ -1911,7 +1875,7 @@ func (d *Downloader) watch(task *Task) {
// Check if the task is deleted
if d.GetTask(task.ID) != nil {
task.Uploading = false
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
}
}()
}
@@ -1966,7 +1930,7 @@ func (d *Downloader) watch(task *Task) {
task.statusLock.Lock()
snapshot := task.clone()
task.statusLock.Unlock()
d.putTaskRecord(task, snapshot)
d.storage.Put(bucketTask, task.ID, snapshot)
d.emit(EventKeyDone, task)
d.emit(EventKeyFinally, task, err)
d.notifyRunning()
@@ -2109,7 +2073,7 @@ func (d *Downloader) handleOnError(task *Task, err error, resetFetcher bool) {
d.Logger.Warn().Err(statsErr).Msgf("persist failed task stats failed, task id: %s", task.ID)
}
if d.taskStatus(task) == base.DownloadStatusError {
if persistErr := d.putTaskRecord(task, task.clone()); persistErr != nil {
if persistErr := d.storage.Put(bucketTask, task.ID, task.clone()); persistErr != nil {
d.Logger.Error().Stack().Err(persistErr).Msgf("persist failed task failed, task id: %s", task.ID)
}
}
@@ -2237,7 +2201,7 @@ func (d *Downloader) doCreate(f fetcher.Fetcher, opts *base.Options, groupID str
return
}
}
if err = d.putTaskRecord(task, task.clone()); err != nil {
if err = d.storage.Put(bucketTask, task.ID, task.clone()); err != nil {
return
}
taskId = task.ID
@@ -2404,7 +2368,7 @@ func (d *Downloader) prepareTask(task *Task) error {
func (d *Downloader) doStart(task *Task) (err error) {
var generation uint64
isReturn, err := d.statusMut(task, func() (isReturn bool, err error) {
if task.lifetime.deleted.Load() || task.Status == base.DownloadStatusRunning || task.Status == base.DownloadStatusDone {
if task.Status == base.DownloadStatusRunning || task.Status == base.DownloadStatusDone {
isReturn = true
return
}
@@ -2459,9 +2423,6 @@ func (d *Downloader) doStart(task *Task) (err error) {
if err != nil {
return err
}
if !d.taskIsRunningGeneration(task, generation) {
return nil
}
task.Meta.Res = task.fetcher.Meta().Res
}
@@ -2486,24 +2447,16 @@ func (d *Downloader) doStart(task *Task) (err error) {
return err
}
task.lifetime.mu.Lock()
if task.lifetime.deleted.Load() {
task.lifetime.mu.Unlock()
return nil
}
task.statusLock.Lock()
if task.Status != base.DownloadStatusRunning || task.runGeneration != generation {
task.lifetime.mu.Unlock()
task.statusLock.Unlock()
return nil
}
task.Progress.Speed = 0
task.timer.Start()
task.statusLock.Unlock()
startErr := task.fetcher.Start()
task.lifetime.mu.Unlock()
if startErr != nil {
return startErr
if err := task.fetcher.Start(); err != nil {
return err
}
started = true
if err := d.captureTaskStats(task, true, true); err != nil {
@@ -2614,7 +2567,7 @@ func (d *Downloader) runPauseHandler(task *Task, generation uint64, pauseFetcher
return false, err
}
} else {
if err := d.putTaskRecord(task, task.clone()); err != nil {
if err := d.storage.Put(bucketTask, task.ID, task.clone()); err != nil {
return false, err
}
}
@@ -2627,7 +2580,7 @@ func (d *Downloader) taskIsRunningGeneration(task *Task, generation uint64) bool
}
task.statusLock.Lock()
defer task.statusLock.Unlock()
return !task.lifetime.deleted.Load() && task.Status == base.DownloadStatusRunning && task.runGeneration == generation
return task.Status == base.DownloadStatusRunning && task.runGeneration == generation
}
func (d *Downloader) taskIsPausedGeneration(task *Task, generation uint64) bool {
@@ -2636,7 +2589,7 @@ func (d *Downloader) taskIsPausedGeneration(task *Task, generation uint64) bool
}
task.statusLock.Lock()
defer task.statusLock.Unlock()
return !task.lifetime.deleted.Load() && (task.Status == base.DownloadStatusPause || task.Status == base.DownloadStatusWait) && task.runGeneration == generation
return (task.Status == base.DownloadStatusPause || task.Status == base.DownloadStatusWait) && task.runGeneration == generation
}
func (d *Downloader) taskStatus(task *Task) base.Status {
@@ -2656,7 +2609,7 @@ func (d *Downloader) markTaskDone(task *Task) bool {
defer task.lock.Unlock()
task.statusLock.Lock()
defer task.statusLock.Unlock()
if task.lifetime.deleted.Load() || task.Status != base.DownloadStatusRunning {
if task.Status != base.DownloadStatusRunning {
return false
}
task.Progress.Used = task.timer.Used()
@@ -2684,7 +2637,7 @@ func (d *Downloader) markTaskError(task *Task) bool {
}
task.statusLock.Lock()
defer task.statusLock.Unlock()
if task.lifetime.deleted.Load() || task.Status != base.DownloadStatusRunning {
if task.Status != base.DownloadStatusRunning {
return false
}
task.updateStatus(base.DownloadStatusError)
@@ -2745,7 +2698,7 @@ func (d *Downloader) enqueueSingleExtraction(task *Task, downloadFilePath string
// Set extraction status to queued
task.Progress.ExtractStatus = ExtractStatusQueued
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
d.Logger.Info().Msgf("extraction queued, task id: %s, job id: %s", task.ID, jobID)
// Create and enqueue the extraction job
@@ -2774,7 +2727,7 @@ func (d *Downloader) enqueueMultiPartExtraction(task *Task, downloadFilePath str
// Not all parts are ready yet - just set status to waiting, don't queue anything
task.Progress.ExtractStatus = ExtractStatusWaitingParts
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
d.Logger.Info().Msgf("multi-part archive waiting for other parts, task id: %s, missing: %v", task.ID, missingParts)
return
}
@@ -2790,14 +2743,14 @@ func (d *Downloader) enqueueMultiPartExtraction(task *Task, downloadFilePath str
task.Progress.ExtractStatus = ExtractStatusDone
task.Progress.ExtractProgress = 100
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
d.Logger.Info().Msgf("multi-part archive extraction already handled by another part, task id: %s", task.ID)
return
}
// This task claimed the extraction - status already set to queued in tryClaimMultiPartExtraction
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
jobID := "multipart:" + fullBaseName
d.Logger.Info().Msgf("multi-part extraction queued, task id: %s, job id: %s", task.ID, jobID)
@@ -2886,7 +2839,7 @@ func (d *Downloader) performExtraction(task *Task, archivePath string, destDir s
task.Progress.ExtractStatus = ExtractStatusExtracting
task.Progress.ExtractProgress = 0
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
// Extract the archive
extractErr := extractArchive(archivePath, destDir, opts.ArchivePassword, func(extractedFiles int, totalFiles int, progress int) {
@@ -2906,7 +2859,7 @@ func (d *Downloader) performMultiPartExtraction(task *Task, firstPartPath string
task.Progress.ExtractStatus = ExtractStatusExtracting
task.Progress.ExtractProgress = 0
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
d.Logger.Info().Msgf("starting multi-part archive extraction, first part: %s, task id: %s", firstPartPath, task.ID)
@@ -3050,13 +3003,13 @@ func (d *Downloader) handleExtractionResult(task *Task, extractErr error, archiv
d.Logger.Error().Err(extractErr).Msgf("auto extract archive failed, task id: %s", task.ID)
task.Progress.ExtractStatus = ExtractStatusError
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
} else {
d.Logger.Info().Msgf("auto extract archive completed, task id: %s", task.ID)
task.Progress.ExtractStatus = ExtractStatusDone
task.Progress.ExtractProgress = 100
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
// Delete archive files after successful extraction if enabled
if deleteAfterExtract {
@@ -3096,15 +3049,12 @@ func (d *Downloader) updateMultiPartTasksStatus(sourceTask *Task, extractErr err
task.Progress.ExtractStatus = status
task.Progress.ExtractProgress = progress
d.emit(EventKeyProgress, task)
d.putTaskRecord(task, task.clone())
d.storage.Put(bucketTask, task.ID, task.clone())
}
}
}
func initTask(task *Task) {
if task.lifetime == nil {
task.lifetime = &taskLifetime{}
}
task.timer = util.NewTimer(task.Progress.Used)
task.statusLock = &sync.Mutex{}
-11
View File
@@ -3,7 +3,6 @@ package download
import (
"encoding/json"
"sync"
"sync/atomic"
"time"
"github.com/GopeedLab/gopeed/internal/controller"
@@ -47,14 +46,6 @@ type CreateTaskBatchResult struct {
// Task represents a download unit.
// Options flow path:
// REST Request (model.CreateTask/ResolveTask) -> pkg/download Downloader -> Task.Meta.Opts (base.Options) -> Fetcher.Resolve/Start (e.g. internal/protocol/http/fetcher.go)
// taskLifetime is shared with preparation candidates. Its mutex serializes
// physical starts and persistence with deletion; the tombstone also invalidates
// work that is currently outside that mutex (for example Resolve).
type taskLifetime struct {
mu sync.Mutex
deleted atomic.Bool
}
type Task struct {
ID string `json:"id"`
Protocol string `json:"protocol"`
@@ -96,7 +87,6 @@ type Task struct {
blobRefLock *sync.Mutex
blobURL string
runGeneration uint64
lifetime *taskLifetime
speedArr []int64
uploadSpeedArr []int64
}
@@ -133,7 +123,6 @@ func NewTask() *Task {
}
return &Task{
ID: id,
lifetime: &taskLifetime{},
Status: base.DownloadStatusReady,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
@@ -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);
}
}