mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-18 06:13:42 +00:00
feat(tasks): group extension folder downloads (#1594)
This commit is contained in:
1 parent
fc0a1e0ef9
commit
1e36599d52
84 files changed
+6690
-881
No files matched your search
@@ -0,0 +1,52 @@
|
|||||||
|
# Batch task creation
|
||||||
|
|
||||||
|
`POST /api/v1/tasks/batch` accepts ordinary and grouped batches:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group": true,
|
||||||
|
"groupName": "album",
|
||||||
|
"opts": {"path": "/downloads"},
|
||||||
|
"reqs": [
|
||||||
|
{"rid": "resolved-resource-id", "opts": {"selectFiles": [1]}},
|
||||||
|
{"req": {"url": "https://example.com/cover.jpg"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each member accepts `rid` or `req`. A nonempty `rid` takes priority and creates a
|
||||||
|
task from the cached resolve result. A member's `opts`, when present, replaces
|
||||||
|
batch `opts` as a whole; omitted fields do not inherit individual batch values.
|
||||||
|
Members without `opts` use batch `opts`. BT file selections use the indexes from
|
||||||
|
the resolve result. Requests without `rid` continue to work.
|
||||||
|
|
||||||
|
For groups, batch `opts.path` selects the parent directory. Members inheriting
|
||||||
|
batch options, or with an empty path, use the reserved group directory. Explicit
|
||||||
|
relative member paths are resolved under that directory; do not prefix them with
|
||||||
|
the batch parent path. For example, parent `downloads` and member path `nested`
|
||||||
|
place the member in `downloads/<group name>/nested`. Absolute paths under the
|
||||||
|
parent directory preserve their relative structure within the group. In ordinary
|
||||||
|
batches, an empty member path uses the configured default download directory.
|
||||||
|
|
||||||
|
All members are attempted. If at least one task is persisted, the response is
|
||||||
|
successful and contains the created task IDs. A task that fails to start after
|
||||||
|
being persisted is included; use the existing task controls to retry it.
|
||||||
|
Successful tasks are kept when other members fail. If every member fails, the
|
||||||
|
API returns an error and removes any newly reserved empty group and directory.
|
||||||
|
|
||||||
|
Both ordinary and grouped batches now return an object in `data`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"code": 0, "msg": "", "data": {"taskIds": ["task-1", "task-2"], "parentId": "group-id"}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ordinary batches omit `parentId`. **This replaces the former array response for
|
||||||
|
ordinary batches.** The outer `code`/`msg`/`data` envelope is unchanged. Clients
|
||||||
|
must read `data.taskIds`; there are no per-member results. A successful response
|
||||||
|
completes the batch, including partial success, so clients must not automatically
|
||||||
|
resubmit missing members.
|
||||||
|
|
||||||
|
With `group: true`, the server generates the group ID and reserves its directory.
|
||||||
|
Creation does not accept a client group ID or append to an existing group. Group
|
||||||
|
metadata remains available through the existing task list and detail responses;
|
||||||
|
`parentId` identifies membership for group operations.
|
||||||
+2
-2
@@ -180,11 +180,11 @@ func (s *Service) createTaskBatch(ctx *Context) *Response {
|
|||||||
if len(request.Reqs) == 0 {
|
if len(request.Reqs) == 0 {
|
||||||
return newErrorResponse("param invalid: reqs", restmodel.CodeInvalidParam)
|
return newErrorResponse("param invalid: reqs", restmodel.CodeInvalidParam)
|
||||||
}
|
}
|
||||||
taskIDs, err := s.Downloader.CreateDirectBatch(&request)
|
result, err := s.Downloader.CreateDirectBatchWithResult(&request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return newErrorResponse(err.Error())
|
return newErrorResponse(err.Error())
|
||||||
}
|
}
|
||||||
return newOKResponse(taskIDs)
|
return newOKResponse(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) patchTask(ctx *Context) *Response {
|
func (s *Service) patchTask(ctx *Context) *Response {
|
||||||
|
|||||||
@@ -267,3 +267,65 @@ func TestFullConfigAndJobTriggerShareProtectedProtocolState(t *testing.T) {
|
|||||||
t.Fatalf("job state overwritten: %s", raw)
|
t.Fatalf("job state overwritten: %s", raw)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBatchResolvedAndDirectCreation(t *testing.T) {
|
||||||
|
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.Header().Set("Content-Length", "4")
|
||||||
|
_, _ = w.Write([]byte("test"))
|
||||||
|
}))
|
||||||
|
t.Cleanup(upstream.Close)
|
||||||
|
d := download.NewDownloader(&download.DownloaderConfig{StorageDir: t.TempDir(), TempDir: t.TempDir(), FetchManagers: []fetcher.FetcherManager{&httpProtocol.FetcherManager{}}})
|
||||||
|
if err := d.Setup(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { d.Close() })
|
||||||
|
cfg, err := d.GetConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg.MaxRunning = 0
|
||||||
|
if err := d.PutConfig(cfg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
service, err := NewService(d)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, grouped := range []bool{false, true} {
|
||||||
|
resolved := serviceTestRequest[*download.ResolveResult](t, service, http.MethodPost, "/api/v1/resolve", &restmodel.ResolveTask{Req: &base.Request{URL: upstream.URL + "/resolved"}})
|
||||||
|
result := serviceTestRequest[map[string]json.RawMessage](t, service, http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{
|
||||||
|
Group: grouped, GroupName: "folder", Opts: &base.Options{Path: t.TempDir()},
|
||||||
|
Reqs: []*base.CreateTaskBatchItem{
|
||||||
|
{Rid: "invalid"},
|
||||||
|
{Rid: resolved.ID, Req: &base.Request{URL: "unsupported://ignored"}, Opts: &base.Options{SelectFiles: []int{0}}},
|
||||||
|
{Req: &base.Request{URL: upstream.URL + "/direct"}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
var ids []string
|
||||||
|
if err := json.Unmarshal(result["taskIds"], &ids); err != nil || len(ids) != 2 {
|
||||||
|
t.Fatalf("unexpected task IDs: %+v, %v", result, err)
|
||||||
|
}
|
||||||
|
wantFields := 1
|
||||||
|
if grouped {
|
||||||
|
wantFields = 2
|
||||||
|
}
|
||||||
|
if len(result) != wantFields {
|
||||||
|
t.Fatalf("unexpected response fields: %+v", result)
|
||||||
|
}
|
||||||
|
var parentID string
|
||||||
|
if grouped {
|
||||||
|
if err := json.Unmarshal(result["parentId"], &parentID); err != nil || parentID == "" {
|
||||||
|
t.Fatalf("missing parent ID: %+v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task := serviceTestRequest[*download.Task](t, service, http.MethodGet, "/api/v1/tasks/"+ids[0], nil)
|
||||||
|
if task.ParentID != parentID || !reflect.DeepEqual(task.Meta.Opts.SelectFiles, []int{0}) {
|
||||||
|
t.Fatalf("resolved task lost membership or selection: %+v", task)
|
||||||
|
}
|
||||||
|
status, response := service.JSON(http.MethodPost, "/api/v1/tasks/batch", nil, []byte(`{"reqs":[{"rid":"missing"},{"req":{"url":"unsupported://bad"}}]}`), nil)
|
||||||
|
var failed restmodel.Result[any]
|
||||||
|
if err := json.Unmarshal(response, &failed); err != nil || status != http.StatusOK || failed.Code == restmodel.CodeOk {
|
||||||
|
t.Fatalf("all-failed batch succeeded: %d %s", status, response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-2
@@ -200,11 +200,14 @@ func ParseOptExtra[E any](opts *Options) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CreateTaskBatch struct {
|
type CreateTaskBatch struct {
|
||||||
Reqs []*CreateTaskBatchItem `json:"reqs"`
|
Reqs []*CreateTaskBatchItem `json:"reqs"`
|
||||||
Opts *Options `json:"opts"`
|
Opts *Options `json:"opts"`
|
||||||
|
Group bool `json:"group"`
|
||||||
|
GroupName string `json:"groupName"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateTaskBatchItem struct {
|
type CreateTaskBatchItem struct {
|
||||||
|
Rid string `json:"rid,omitempty"`
|
||||||
Req *Request `json:"req"`
|
Req *Request `json:"req"`
|
||||||
Opts *Options `json:"opts"`
|
Opts *Options `json:"opts"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ func categoryForResource(cfg *base.DownloaderStoreConfig, res *base.Resource) *b
|
|||||||
// runs on the result, so a category directory the white list rejects falls
|
// runs on the result, so a category directory the white list rejects falls
|
||||||
// back to the base directory of this task instead of failing it.
|
// back to the base directory of this task instead of failing it.
|
||||||
func (d *Downloader) decideDownloadDir(opts *base.Options, res *base.Resource) (string, error) {
|
func (d *Downloader) decideDownloadDir(opts *base.Options, res *base.Resource) (string, error) {
|
||||||
|
return d.decideDownloadDirForTask(opts, res, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Downloader) decideDownloadDirForTask(opts *base.Options, res *base.Resource, group *TaskGroup) (string, error) {
|
||||||
if opts == nil {
|
if opts == nil {
|
||||||
opts = &base.Options{}
|
opts = &base.Options{}
|
||||||
}
|
}
|
||||||
@@ -48,6 +52,9 @@ func (d *Downloader) decideDownloadDir(opts *base.Options, res *base.Resource) (
|
|||||||
if base == "" {
|
if base == "" {
|
||||||
return "", errors.New("download directory is empty")
|
return "", errors.New("download directory is empty")
|
||||||
}
|
}
|
||||||
|
if group != nil && opts.SkipAutoCategorize {
|
||||||
|
return d.initDownloadPathForTask(base, group)
|
||||||
|
}
|
||||||
target := base
|
target := base
|
||||||
if !opts.SkipAutoCategorize {
|
if !opts.SkipAutoCategorize {
|
||||||
if category := categoryForResource(cfg, res); category != nil {
|
if category := categoryForResource(cfg, res); category != nil {
|
||||||
|
|||||||
@@ -234,6 +234,38 @@ func TestDecideDownloadDirWhiteList(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDecideGroupDownloadDirWhiteList(t *testing.T) {
|
||||||
|
parent := t.TempDir()
|
||||||
|
root := filepath.Join(parent, "folder")
|
||||||
|
nested := filepath.Join(root, "nested")
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
group *TaskGroup
|
||||||
|
allowed string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "group root", path: root, group: &TaskGroup{Path: root}, allowed: filepath.Join(parent, "*")},
|
||||||
|
{name: "nested member", path: nested, group: &TaskGroup{Path: root}, allowed: filepath.Join(parent, "*")},
|
||||||
|
{name: "ordinary nested task", path: nested, allowed: filepath.Join(parent, "*"), wantErr: true},
|
||||||
|
{name: "member outside group", path: filepath.Join(parent, "other"), group: &TaskGroup{Path: root}, allowed: filepath.Join(parent, "*"), wantErr: true},
|
||||||
|
{name: "group permission revoked", path: nested, group: &TaskGroup{Path: root}, allowed: nested, wantErr: true},
|
||||||
|
{name: "literal group name", path: filepath.Join(parent, "%year%", "nested"), group: &TaskGroup{Path: filepath.Join(parent, "%year%")}, allowed: filepath.Join(parent, "*")},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
d := newUnitCategoryDownloader(newTestCategoryConfig())
|
||||||
|
d.cfg.WhiteDownloadDirs = []string{test.allowed}
|
||||||
|
got, err := d.decideDownloadDirForTask(&base.Options{Path: test.path, SkipAutoCategorize: true}, singleFileResource("file.txt"), test.group)
|
||||||
|
if (err != nil) != test.wantErr {
|
||||||
|
t.Fatalf("decideDownloadDirForTask() = %q, %v; want error = %v", got, err, test.wantErr)
|
||||||
|
}
|
||||||
|
if err == nil && got != test.path {
|
||||||
|
t.Fatalf("path = %q, want %q", got, test.path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSuggestedDownloadDir(t *testing.T) {
|
func TestSuggestedDownloadDir(t *testing.T) {
|
||||||
programDir := filepath.Join("./downloads", "Program")
|
programDir := filepath.Join("./downloads", "Program")
|
||||||
|
|
||||||
|
|||||||
+490
-122
File diff suppressed because it is too large.
Load diff
+1099
-1
File diff suppressed because it is too large.
Load diff
@@ -70,10 +70,11 @@ func TestExtensionResolveSizeThroughTaskCreation(t *testing.T) {
|
|||||||
if err := json.Unmarshal(wire, &submitted); err != nil {
|
if err := json.Unmarshal(wire, &submitted); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
ids, err := d.CreateDirectBatch(&submitted)
|
batchResult, err := d.CreateDirectBatch(&submitted)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
ids := batchResult
|
||||||
for i, id := range ids {
|
for i, id := range ids {
|
||||||
task := d.GetTask(id)
|
task := d.GetTask(id)
|
||||||
if task.Meta.Res != nil {
|
if task.Meta.Res != nil {
|
||||||
|
|||||||
@@ -2044,8 +2044,13 @@ func waitForTaskStatus(t *testing.T, downloader *Downloader, id string, status b
|
|||||||
deadline := time.Now().Add(timeout)
|
deadline := time.Now().Add(timeout)
|
||||||
for time.Now().Before(deadline) {
|
for time.Now().Before(deadline) {
|
||||||
task := downloader.GetTask(id)
|
task := downloader.GetTask(id)
|
||||||
if task != nil && task.Status == status {
|
if task != nil && downloader.taskStatus(task) == status {
|
||||||
return
|
if status != base.DownloadStatusDone {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, watching := downloader.watchedTasks.Load(id); !watching {
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
time.Sleep(10 * time.Millisecond)
|
time.Sleep(10 * time.Millisecond)
|
||||||
}
|
}
|
||||||
@@ -2053,9 +2058,6 @@ func waitForTaskStatus(t *testing.T, downloader *Downloader, id string, status b
|
|||||||
if task == nil {
|
if task == nil {
|
||||||
t.Fatalf("timeout waiting for task %s status %s: task not found", id, status)
|
t.Fatalf("timeout waiting for task %s status %s: task not found", id, status)
|
||||||
}
|
}
|
||||||
total := int64(0)
|
snapshot, err := downloader.RuntimeStatus(id)
|
||||||
if task.Meta != nil && task.Meta.Res != nil {
|
t.Fatalf("timeout waiting for task %s status %s: got %+v, error=%v", id, status, snapshot, err)
|
||||||
total = task.Meta.Res.Size
|
|
||||||
}
|
|
||||||
t.Fatalf("timeout waiting for task %s status %s: got %s downloaded=%d total=%d", id, status, task.Status, task.Progress.Downloaded, total)
|
|
||||||
}
|
}
|
||||||
+29
-9
@@ -29,18 +29,34 @@ type ResolveResult struct {
|
|||||||
SuggestedDownloadDir string `json:"suggestedDownloadDir,omitempty"`
|
SuggestedDownloadDir string `json:"suggestedDownloadDir,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TaskGroup stores the directory shared by independently scheduled tasks.
|
||||||
|
type TaskGroup struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateTaskBatchResult is shared by ordinary and grouped batches.
|
||||||
|
type CreateTaskBatchResult struct {
|
||||||
|
TaskIDs []string `json:"taskIds"`
|
||||||
|
ParentID string `json:"parentId,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// Task represents a download unit.
|
// Task represents a download unit.
|
||||||
// Options flow path:
|
// 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)
|
// REST Request (model.CreateTask/ResolveTask) -> pkg/download Downloader -> Task.Meta.Opts (base.Options) -> Fetcher.Resolve/Start (e.g. internal/protocol/http/fetcher.go)
|
||||||
type Task struct {
|
type Task struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Protocol string `json:"protocol"`
|
Protocol string `json:"protocol"`
|
||||||
Meta *fetcher.FetcherMeta `json:"meta"`
|
Meta *fetcher.FetcherMeta `json:"meta"`
|
||||||
Status base.Status `json:"status"`
|
// ParentID identifies the independently stored group.
|
||||||
Uploading bool `json:"uploading"`
|
ParentID string `json:"parentId,omitempty"`
|
||||||
Progress *Progress `json:"progress"`
|
Status base.Status `json:"status"`
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
Uploading bool `json:"uploading"`
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
Progress *Progress `json:"progress"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
// DoneAt is the time when the task completed; nil if it has never
|
// DoneAt is the time when the task completed; nil if it has never
|
||||||
// finished. A done task never leaves the done state, so the value is
|
// finished. A done task never leaves the done state, so the value is
|
||||||
// written once and kept.
|
// written once and kept.
|
||||||
@@ -54,6 +70,8 @@ type Task struct {
|
|||||||
// does not have it and keeps its directory and name.
|
// does not have it and keeps its directory and name.
|
||||||
NeedsPreparation bool `json:"needsPreparation,omitempty"`
|
NeedsPreparation bool `json:"needsPreparation,omitempty"`
|
||||||
|
|
||||||
|
group *TaskGroup
|
||||||
|
|
||||||
producer production.Source
|
producer production.Source
|
||||||
producerReceived int64
|
producerReceived int64
|
||||||
|
|
||||||
@@ -144,10 +162,12 @@ func (t *Task) MarshalJSON() ([]byte, error) {
|
|||||||
type rawTaskType Task
|
type rawTaskType Task
|
||||||
jsonTask := struct {
|
jsonTask := struct {
|
||||||
*rawTaskType
|
*rawTaskType
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
Group *TaskGroup `json:"group,omitempty"`
|
||||||
}{
|
}{
|
||||||
(*rawTaskType)(t),
|
(*rawTaskType)(t),
|
||||||
t.Name(),
|
t.Name(),
|
||||||
|
t.group,
|
||||||
}
|
}
|
||||||
return json.Marshal(jsonTask)
|
return json.Marshal(jsonTask)
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -63,7 +63,7 @@ func CreateTaskBatch(w http.ResponseWriter, r *http.Request) {
|
|||||||
WriteJson(w, model.NewErrorResult("param invalid: reqs", model.CodeInvalidParam))
|
WriteJson(w, model.NewErrorResult("param invalid: reqs", model.CodeInvalidParam))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
taskIds, err := Downloader.CreateDirectBatch(&req)
|
taskIds, err := Downloader.CreateDirectBatchWithResult(&req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
WriteJson(w, model.NewErrorResult(err.Error()))
|
WriteJson(w, model.NewErrorResult(err.Error()))
|
||||||
return
|
return
|
||||||
|
|||||||
+38
-2
@@ -197,9 +197,10 @@ func TestCreateDirectTaskBatch(t *testing.T) {
|
|||||||
Req: createReq.Req,
|
Req: createReq.Req,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
taskIds := httpRequestCheckOk[[]string](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{
|
result := httpRequestCheckOk[download.CreateTaskBatchResult](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{
|
||||||
Reqs: reqs,
|
Reqs: reqs,
|
||||||
})
|
})
|
||||||
|
taskIds := result.TaskIDs
|
||||||
if len(taskIds) != len(reqs) {
|
if len(taskIds) != len(reqs) {
|
||||||
t.Errorf("CreateDirectTaskBatch() got = %v, want %v", len(taskIds), len(reqs))
|
t.Errorf("CreateDirectTaskBatch() got = %v, want %v", len(taskIds), len(reqs))
|
||||||
}
|
}
|
||||||
@@ -220,12 +221,13 @@ func TestCreateDirectTaskBatchWithOpt(t *testing.T) {
|
|||||||
}
|
}
|
||||||
reqs = append(reqs, item)
|
reqs = append(reqs, item)
|
||||||
}
|
}
|
||||||
taskIds := httpRequestCheckOk[[]string](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{
|
result := httpRequestCheckOk[download.CreateTaskBatchResult](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{
|
||||||
Reqs: reqs,
|
Reqs: reqs,
|
||||||
Opts: &base.Options{
|
Opts: &base.Options{
|
||||||
Name: "default_opt.data",
|
Name: "default_opt.data",
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
taskIds := result.TaskIDs
|
||||||
if len(taskIds) != len(reqs) {
|
if len(taskIds) != len(reqs) {
|
||||||
t.Errorf("CreateDirectTaskBatch() got = %v, want %v", len(taskIds), len(reqs))
|
t.Errorf("CreateDirectTaskBatch() got = %v, want %v", len(taskIds), len(reqs))
|
||||||
}
|
}
|
||||||
@@ -245,6 +247,40 @@ func TestCreateDirectTaskBatchWithOpt(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateDirectTaskBatchWithGroup(t *testing.T) {
|
||||||
|
doTest(func() {
|
||||||
|
cfg, err := Downloader.GetConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg.MaxRunning = 0
|
||||||
|
if err := Downloader.PutConfig(cfg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
parent := t.TempDir()
|
||||||
|
result := httpRequestCheckOk[download.CreateTaskBatchResult](http.MethodPost, "/api/v1/tasks/batch", &base.CreateTaskBatch{
|
||||||
|
Reqs: []*base.CreateTaskBatchItem{{Req: createReq.Req}, {Req: createReq.Req}},
|
||||||
|
Opts: &base.Options{Path: parent}, Group: true, GroupName: "folder",
|
||||||
|
})
|
||||||
|
if result.ParentID == "" || len(result.TaskIDs) != 2 {
|
||||||
|
t.Fatalf("unexpected group result: %+v", result)
|
||||||
|
}
|
||||||
|
all := httpRequestCheckOk[[]map[string]any](http.MethodGet, "/api/v1/tasks", nil)
|
||||||
|
if len(all) != 2 {
|
||||||
|
t.Fatalf("expected real tasks only, got %d", len(all))
|
||||||
|
}
|
||||||
|
for _, task := range all {
|
||||||
|
if task["parentId"] != result.ParentID || task["type"] != nil {
|
||||||
|
t.Fatalf("invalid member: %+v", task)
|
||||||
|
}
|
||||||
|
metadata, ok := task["group"].(map[string]any)
|
||||||
|
if !ok || metadata["path"] != filepath.Join(parent, "folder") || metadata["name"] != "folder" {
|
||||||
|
t.Fatalf("missing group metadata: %+v", task)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func TestPauseAndContinueTask(t *testing.T) {
|
func TestPauseAndContinueTask(t *testing.T) {
|
||||||
doTest(func() {
|
doTest(func() {
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
|||||||
@@ -94,6 +94,8 @@ State broadcasting must observe the owning Riverpod state centrally. Do not broa
|
|||||||
- Storage RPC methods expose business capabilities such as create-history operations, not raw `box.get` or `box.put` access.
|
- Storage RPC methods expose business capabilities such as create-history operations, not raw `box.get` or `box.put` access.
|
||||||
- Prefer batch mutations across the window boundary. For example, save all parsed URLs in one `saveCreateHistory(List<String>)` call.
|
- Prefer batch mutations across the window boundary. For example, save all parsed URLs in one `saveCreateHistory(List<String>)` call.
|
||||||
- New child-window storage requirements must be added to `StorageMethods` and bound in the main registry.
|
- New child-window storage requirements must be added to `StorageMethods` and bound in the main registry.
|
||||||
|
- Config reads, full config saves, and create-history mutations share one main-window queue. Each history mutation reads, changes, and writes the config within that queue. History reads wait for earlier saves.
|
||||||
|
- `StorageMethods` owns `extra.createHistory`; full config saves preserve its latest value inside the queue so stale settings or child-window snapshots cannot overwrite history.
|
||||||
|
|
||||||
## 7. Gopeed Backend Migration
|
## 7. Gopeed Backend Migration
|
||||||
|
|
||||||
@@ -128,3 +130,16 @@ Child-window code must not:
|
|||||||
- Parse RPC JSON directly inside a page or widget.
|
- Parse RPC JSON directly inside a page or widget.
|
||||||
|
|
||||||
These constraints keep all backend and persistence ownership in the main window and allow multiple child windows to operate concurrently without database locks or duplicated Gopeed runtimes.
|
These constraints keep all backend and persistence ownership in the main window and allow multiple child windows to operate concurrently without database locks or duplicated Gopeed runtimes.
|
||||||
|
|
||||||
|
## 10. Batch Task Creation
|
||||||
|
|
||||||
|
`GopeedMethods.createTaskBatch` carries `CreateTaskBatch` through the existing
|
||||||
|
codec registry. Each member accepts either `rid` from resolve or `req`, plus
|
||||||
|
creation `opts`. A nonempty `rid` takes priority. BT selections retain their
|
||||||
|
original file indexes in `opts.selectFiles`.
|
||||||
|
|
||||||
|
Both ordinary and grouped creation return `CreateTaskBatchResult`, an object
|
||||||
|
with `taskIds` and an optional `parentId`. A successful response completes the
|
||||||
|
batch, including partial success. The preview tracks completed batches so a
|
||||||
|
failed batch can be retried without repeating successful batches. Creation does
|
||||||
|
not accept a group ID to append members to an existing group.
|
||||||
@@ -85,10 +85,10 @@ Future<String> createTask(CreateTask createTask) {
|
|||||||
return _parse<String>(() => _request('api/v1/tasks', method: 'POST', data: createTask), (data) => data as String);
|
return _parse<String>(() => _request('api/v1/tasks', method: 'POST', data: createTask), (data) => data as String);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<String>> createTaskBatch(CreateTaskBatch createTaskBatch) {
|
Future<CreateTaskBatchResult> createTaskBatch(CreateTaskBatch createTaskBatch) {
|
||||||
return _parse<List<String>>(
|
return _parse<CreateTaskBatchResult>(
|
||||||
() => _request('api/v1/tasks/batch', method: 'POST', data: createTaskBatch),
|
() => _request('api/v1/tasks/batch', method: 'POST', data: createTaskBatch),
|
||||||
(data) => (data as List<dynamic>).map((e) => e as String).toList(),
|
(json) => CreateTaskBatchResult.fromJson(json as Map<String, dynamic>),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ class CreateTaskBatch {
|
|||||||
List<CreateTaskBatchItem>? reqs;
|
List<CreateTaskBatchItem>? reqs;
|
||||||
Options? opts;
|
Options? opts;
|
||||||
|
|
||||||
CreateTaskBatch({this.reqs, this.opts});
|
bool group;
|
||||||
|
String groupName;
|
||||||
|
|
||||||
|
CreateTaskBatch({this.reqs, this.opts, this.group = false, this.groupName = ''});
|
||||||
|
|
||||||
factory CreateTaskBatch.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchFromJson(json);
|
factory CreateTaskBatch.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchFromJson(json);
|
||||||
|
|
||||||
@@ -19,11 +22,23 @@ class CreateTaskBatch {
|
|||||||
|
|
||||||
@JsonSerializable()
|
@JsonSerializable()
|
||||||
class CreateTaskBatchItem {
|
class CreateTaskBatchItem {
|
||||||
|
String? rid;
|
||||||
Request? req;
|
Request? req;
|
||||||
Options? opts;
|
Options? opts;
|
||||||
|
|
||||||
CreateTaskBatchItem({this.req, this.opts});
|
CreateTaskBatchItem({this.rid, this.req, this.opts});
|
||||||
|
|
||||||
factory CreateTaskBatchItem.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchItemFromJson(json);
|
factory CreateTaskBatchItem.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchItemFromJson(json);
|
||||||
Map<String, dynamic> toJson() => _$CreateTaskBatchItemToJson(this);
|
Map<String, dynamic> toJson() => _$CreateTaskBatchItemToJson(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@JsonSerializable()
|
||||||
|
class CreateTaskBatchResult {
|
||||||
|
final List<String> taskIds;
|
||||||
|
final String? parentId;
|
||||||
|
|
||||||
|
CreateTaskBatchResult({required this.taskIds, this.parentId});
|
||||||
|
|
||||||
|
factory CreateTaskBatchResult.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchResultFromJson(json);
|
||||||
|
Map<String, dynamic> toJson() => _$CreateTaskBatchResultToJson(this);
|
||||||
|
}
|
||||||
@@ -6,22 +6,55 @@ part of 'create_task_batch.dart';
|
|||||||
// JsonSerializableGenerator
|
// JsonSerializableGenerator
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
|
|
||||||
CreateTaskBatch _$CreateTaskBatchFromJson(Map<String, dynamic> json) => CreateTaskBatch(
|
CreateTaskBatch _$CreateTaskBatchFromJson(Map<String, dynamic> json) =>
|
||||||
reqs: (json['reqs'] as List<dynamic>?)?.map((e) => CreateTaskBatchItem.fromJson(e as Map<String, dynamic>)).toList(),
|
CreateTaskBatch(
|
||||||
opts: json['opts'] == null ? null : Options.fromJson(json['opts'] as Map<String, dynamic>),
|
reqs: (json['reqs'] as List<dynamic>?)
|
||||||
);
|
?.map((e) => CreateTaskBatchItem.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList(),
|
||||||
|
opts: json['opts'] == null
|
||||||
|
? null
|
||||||
|
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||||
|
group: json['group'] as bool? ?? false,
|
||||||
|
groupName: json['groupName'] as String? ?? '',
|
||||||
|
);
|
||||||
|
|
||||||
Map<String, dynamic> _$CreateTaskBatchToJson(CreateTaskBatch instance) => <String, dynamic>{
|
Map<String, dynamic> _$CreateTaskBatchToJson(CreateTaskBatch instance) =>
|
||||||
'reqs': ?instance.reqs?.map((e) => e.toJson()).toList(),
|
<String, dynamic>{
|
||||||
'opts': ?instance.opts?.toJson(),
|
'reqs': ?instance.reqs?.map((e) => e.toJson()).toList(),
|
||||||
};
|
'opts': ?instance.opts?.toJson(),
|
||||||
|
'group': instance.group,
|
||||||
|
'groupName': instance.groupName,
|
||||||
|
};
|
||||||
|
|
||||||
CreateTaskBatchItem _$CreateTaskBatchItemFromJson(Map<String, dynamic> json) => CreateTaskBatchItem(
|
CreateTaskBatchItem _$CreateTaskBatchItemFromJson(Map<String, dynamic> json) =>
|
||||||
req: json['req'] == null ? null : Request.fromJson(json['req'] as Map<String, dynamic>),
|
CreateTaskBatchItem(
|
||||||
opts: json['opts'] == null ? null : Options.fromJson(json['opts'] as Map<String, dynamic>),
|
rid: json['rid'] as String?,
|
||||||
);
|
req: json['req'] == null
|
||||||
|
? null
|
||||||
|
: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||||
|
opts: json['opts'] == null
|
||||||
|
? null
|
||||||
|
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||||
|
);
|
||||||
|
|
||||||
Map<String, dynamic> _$CreateTaskBatchItemToJson(CreateTaskBatchItem instance) => <String, dynamic>{
|
Map<String, dynamic> _$CreateTaskBatchItemToJson(
|
||||||
|
CreateTaskBatchItem instance,
|
||||||
|
) => <String, dynamic>{
|
||||||
|
'rid': ?instance.rid,
|
||||||
'req': ?instance.req,
|
'req': ?instance.req,
|
||||||
'opts': ?instance.opts,
|
'opts': ?instance.opts,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
CreateTaskBatchResult _$CreateTaskBatchResultFromJson(
|
||||||
|
Map<String, dynamic> json,
|
||||||
|
) => CreateTaskBatchResult(
|
||||||
|
taskIds: (json['taskIds'] as List<dynamic>).map((e) => e as String).toList(),
|
||||||
|
parentId: json['parentId'] as String?,
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> _$CreateTaskBatchResultToJson(
|
||||||
|
CreateTaskBatchResult instance,
|
||||||
|
) => <String, dynamic>{
|
||||||
|
'taskIds': instance.taskIds,
|
||||||
|
'parentId': ?instance.parentId,
|
||||||
|
};
|
||||||
@@ -28,7 +28,10 @@ enum ExtractStatus {
|
|||||||
class Task {
|
class Task {
|
||||||
String id;
|
String id;
|
||||||
String name;
|
String name;
|
||||||
|
@JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue)
|
||||||
Protocol? protocol;
|
Protocol? protocol;
|
||||||
|
TaskGroup? group;
|
||||||
|
String parentId;
|
||||||
Meta meta;
|
Meta meta;
|
||||||
Status status;
|
Status status;
|
||||||
bool uploading;
|
bool uploading;
|
||||||
@@ -47,6 +50,8 @@ class Task {
|
|||||||
required this.createdAt,
|
required this.createdAt,
|
||||||
required this.updatedAt,
|
required this.updatedAt,
|
||||||
this.doneAt,
|
this.doneAt,
|
||||||
|
this.group,
|
||||||
|
this.parentId = '',
|
||||||
});
|
});
|
||||||
|
|
||||||
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
|
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
|
||||||
@@ -54,6 +59,18 @@ class Task {
|
|||||||
Map<String, dynamic> toJson() => _$TaskToJson(this);
|
Map<String, dynamic> toJson() => _$TaskToJson(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@JsonSerializable()
|
||||||
|
class TaskGroup {
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final String path;
|
||||||
|
final DateTime createdAt;
|
||||||
|
|
||||||
|
TaskGroup({required this.id, required this.name, required this.path, required this.createdAt});
|
||||||
|
factory TaskGroup.fromJson(Map<String, dynamic> json) => _$TaskGroupFromJson(json);
|
||||||
|
Map<String, dynamic> toJson() => _$TaskGroupToJson(this);
|
||||||
|
}
|
||||||
|
|
||||||
@JsonSerializable()
|
@JsonSerializable()
|
||||||
class Progress {
|
class Progress {
|
||||||
int used;
|
int used;
|
||||||
|
|||||||
@@ -16,12 +16,16 @@ Task _$TaskFromJson(Map<String, dynamic> json) => Task(
|
|||||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||||
updatedAt: DateTime.parse(json['updatedAt'] as String),
|
updatedAt: DateTime.parse(json['updatedAt'] as String),
|
||||||
doneAt: json['doneAt'] == null ? null : DateTime.parse(json['doneAt'] as String),
|
doneAt: json['doneAt'] == null ? null : DateTime.parse(json['doneAt'] as String),
|
||||||
)..protocol = $enumDecodeNullable(_$ProtocolEnumMap, json['protocol']);
|
group: json['group'] == null ? null : TaskGroup.fromJson(json['group'] as Map<String, dynamic>),
|
||||||
|
parentId: json['parentId'] as String? ?? '',
|
||||||
|
)..protocol = $enumDecodeNullable(_$ProtocolEnumMap, json['protocol'], unknownValue: JsonKey.nullForUndefinedEnumValue);
|
||||||
|
|
||||||
Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
|
Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
|
||||||
'id': instance.id,
|
'id': instance.id,
|
||||||
'name': instance.name,
|
'name': instance.name,
|
||||||
'protocol': ?_$ProtocolEnumMap[instance.protocol],
|
'protocol': ?_$ProtocolEnumMap[instance.protocol],
|
||||||
|
'group': ?instance.group?.toJson(),
|
||||||
|
'parentId': instance.parentId,
|
||||||
'meta': instance.meta.toJson(),
|
'meta': instance.meta.toJson(),
|
||||||
'status': _$StatusEnumMap[instance.status]!,
|
'status': _$StatusEnumMap[instance.status]!,
|
||||||
'uploading': instance.uploading,
|
'uploading': instance.uploading,
|
||||||
@@ -48,6 +52,20 @@ const _$ProtocolEnumMap = {
|
|||||||
Protocol.ftp: 'ftp',
|
Protocol.ftp: 'ftp',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
TaskGroup _$TaskGroupFromJson(Map<String, dynamic> json) => TaskGroup(
|
||||||
|
id: json['id'] as String,
|
||||||
|
name: json['name'] as String,
|
||||||
|
path: json['path'] as String,
|
||||||
|
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> _$TaskGroupToJson(TaskGroup instance) => <String, dynamic>{
|
||||||
|
'id': instance.id,
|
||||||
|
'name': instance.name,
|
||||||
|
'path': instance.path,
|
||||||
|
'createdAt': instance.createdAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
|
||||||
Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress(
|
Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress(
|
||||||
used: (json['used'] as num).toInt(),
|
used: (json['used'] as num).toInt(),
|
||||||
speed: (json['speed'] as num).toInt(),
|
speed: (json['speed'] as num).toInt(),
|
||||||
|
|||||||
@@ -34,8 +34,9 @@ class AppCapabilities {
|
|||||||
class LocalAppCapabilities {
|
class LocalAppCapabilities {
|
||||||
LocalAppCapabilities._() : codecs = createAppCapabilityCodecs() {
|
LocalAppCapabilities._() : codecs = createAppCapabilityCodecs() {
|
||||||
registry = CapabilityRegistry(codecs);
|
registry = CapabilityRegistry(codecs);
|
||||||
_bindGopeed(registry);
|
final config = _ConfigStore();
|
||||||
_bindStorage(registry);
|
_bindGopeed(registry, config);
|
||||||
|
_bindStorage(registry, config);
|
||||||
registry.bind(NavigationMethods.showDownloadingTasks, (_) {
|
registry.bind(NavigationMethods.showDownloadingTasks, (_) {
|
||||||
AppRouter.showDownloadingTasks();
|
AppRouter.showDownloadingTasks();
|
||||||
return const RpcUnit();
|
return const RpcUnit();
|
||||||
@@ -62,6 +63,7 @@ RpcCodecRegistry createAppCapabilityCodecs() {
|
|||||||
..register<ResolveResult>((json) => ResolveResult.fromJson(json! as Map<String, dynamic>))
|
..register<ResolveResult>((json) => ResolveResult.fromJson(json! as Map<String, dynamic>))
|
||||||
..register<CreateTask>((json) => CreateTask.fromJson(json! as Map<String, dynamic>))
|
..register<CreateTask>((json) => CreateTask.fromJson(json! as Map<String, dynamic>))
|
||||||
..register<CreateTaskBatch>((json) => CreateTaskBatch.fromJson(json! as Map<String, dynamic>))
|
..register<CreateTaskBatch>((json) => CreateTaskBatch.fromJson(json! as Map<String, dynamic>))
|
||||||
|
..register<CreateTaskBatchResult>((json) => CreateTaskBatchResult.fromJson(json! as Map<String, dynamic>))
|
||||||
..register<DownloaderConfig>((json) => DownloaderConfig.fromJson(json! as Map<String, dynamic>))
|
..register<DownloaderConfig>((json) => DownloaderConfig.fromJson(json! as Map<String, dynamic>))
|
||||||
..register<TaskRuntimeStatus>((json) => TaskRuntimeStatus.fromJson(json! as Map<String, dynamic>))
|
..register<TaskRuntimeStatus>((json) => TaskRuntimeStatus.fromJson(json! as Map<String, dynamic>))
|
||||||
..register<List<Task>>(
|
..register<List<Task>>(
|
||||||
@@ -80,7 +82,7 @@ RpcCodecRegistry createAppCapabilityCodecs() {
|
|||||||
return codecs;
|
return codecs;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _bindGopeed(CapabilityRegistry registry) {
|
void _bindGopeed(CapabilityRegistry registry, _ConfigStore configStore) {
|
||||||
registry
|
registry
|
||||||
..bind(GopeedMethods.triggerProtocolJob, (p) async {
|
..bind(GopeedMethods.triggerProtocolJob, (p) async {
|
||||||
await api.triggerProtocolJob(p['protocol'] as String, p['name'] as String);
|
await api.triggerProtocolJob(p['protocol'] as String, p['name'] as String);
|
||||||
@@ -127,9 +129,9 @@ void _bindGopeed(CapabilityRegistry registry) {
|
|||||||
await api.deleteTasks(_optionalStringList(params['ids']), params['force'] as bool? ?? false);
|
await api.deleteTasks(_optionalStringList(params['ids']), params['force'] as bool? ?? false);
|
||||||
return const RpcUnit();
|
return const RpcUnit();
|
||||||
})
|
})
|
||||||
..bind(GopeedMethods.getConfig, (_) => api.getConfig())
|
..bind(GopeedMethods.getConfig, (_) => configStore.get())
|
||||||
..bind(GopeedMethods.putConfig, (config) async {
|
..bind(GopeedMethods.putConfig, (config) async {
|
||||||
await api.putConfig(config);
|
await configStore.put(config);
|
||||||
return const RpcUnit();
|
return const RpcUnit();
|
||||||
})
|
})
|
||||||
..bind(GopeedMethods.installExtension, api.installExtension)
|
..bind(GopeedMethods.installExtension, api.installExtension)
|
||||||
@@ -163,35 +165,59 @@ void _bindGopeed(CapabilityRegistry registry) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _bindStorage(CapabilityRegistry registry) {
|
// Shared by local and child-window handlers. History owns its config field;
|
||||||
|
// full config snapshots must preserve the latest history inside the same queue.
|
||||||
|
class _ConfigStore {
|
||||||
|
Future<void> _tail = Future<void>.value();
|
||||||
|
|
||||||
|
Future<T> _run<T>(Future<T> Function() operation) {
|
||||||
|
final result = _tail.then((_) => operation());
|
||||||
|
_tail = result.then<void>((_) {}, onError: (Object _, StackTrace _) {});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<DownloaderConfig> get() => _run(api.getConfig);
|
||||||
|
|
||||||
|
Future<void> put(DownloaderConfig config) {
|
||||||
|
final snapshot = DownloaderConfig.fromJson(config.toJson());
|
||||||
|
return _run(() async {
|
||||||
|
final latest = await api.getConfig();
|
||||||
|
snapshot.extra.createHistory = latest.extra.createHistory;
|
||||||
|
await api.putConfig(snapshot);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> updateHistory(void Function(List<String>) mutation) => _run(() async {
|
||||||
|
final config = await api.getConfig();
|
||||||
|
final history = List<String>.of(config.extra.createHistory);
|
||||||
|
mutation(history);
|
||||||
|
config.extra.createHistory = history;
|
||||||
|
await api.putConfig(config);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _bindStorage(CapabilityRegistry registry, _ConfigStore configStore) {
|
||||||
registry
|
registry
|
||||||
..bind(StorageMethods.getCreateHistory, (_) async {
|
..bind(StorageMethods.getCreateHistory, (_) async {
|
||||||
final config = await api.getConfig();
|
final config = await configStore.get();
|
||||||
return config.extra.createHistory;
|
return config.extra.createHistory;
|
||||||
})
|
})
|
||||||
..bind(StorageMethods.saveCreateHistory, (urls) async {
|
..bind(StorageMethods.saveCreateHistory, (urls) async {
|
||||||
final config = await api.getConfig();
|
await configStore.updateHistory((history) {
|
||||||
final history = List<String>.of(config.extra.createHistory);
|
for (final url in urls) {
|
||||||
for (final url in urls) {
|
history.remove(url);
|
||||||
history.remove(url);
|
history.insert(0, url);
|
||||||
history.insert(0, url);
|
if (history.length > 64) history.removeLast();
|
||||||
if (history.length > 64) history.removeLast();
|
}
|
||||||
}
|
});
|
||||||
config.extra.createHistory = history;
|
|
||||||
await api.putConfig(config);
|
|
||||||
return const RpcUnit();
|
return const RpcUnit();
|
||||||
})
|
})
|
||||||
..bind(StorageMethods.removeCreateHistory, (url) async {
|
..bind(StorageMethods.removeCreateHistory, (url) async {
|
||||||
final config = await api.getConfig();
|
await configStore.updateHistory((history) => history.remove(url));
|
||||||
final history = List<String>.of(config.extra.createHistory)..remove(url);
|
|
||||||
config.extra.createHistory = history;
|
|
||||||
await api.putConfig(config);
|
|
||||||
return const RpcUnit();
|
return const RpcUnit();
|
||||||
})
|
})
|
||||||
..bind(StorageMethods.clearCreateHistory, (_) async {
|
..bind(StorageMethods.clearCreateHistory, (_) async {
|
||||||
final config = await api.getConfig();
|
await configStore.updateHistory((history) => history.clear());
|
||||||
config.extra.createHistory = const [];
|
|
||||||
await api.putConfig(config);
|
|
||||||
return const RpcUnit();
|
return const RpcUnit();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ abstract final class GopeedMethods {
|
|||||||
static const getMirrorCandidates = RpcMethod<Map<String, dynamic>, List<String>>('gopeed.mirrors.candidates');
|
static const getMirrorCandidates = RpcMethod<Map<String, dynamic>, List<String>>('gopeed.mirrors.candidates');
|
||||||
static const resolve = RpcMethod<ResolveTask, ResolveResult>('gopeed.resolve');
|
static const resolve = RpcMethod<ResolveTask, ResolveResult>('gopeed.resolve');
|
||||||
static const createTask = RpcMethod<CreateTask, String>('gopeed.task.create');
|
static const createTask = RpcMethod<CreateTask, String>('gopeed.task.create');
|
||||||
static const createTaskBatch = RpcMethod<CreateTaskBatch, List<String>>('gopeed.task.createBatch');
|
static const createTaskBatch = RpcMethod<CreateTaskBatch, CreateTaskBatchResult>('gopeed.task.createBatch');
|
||||||
static const patchTask = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.patch');
|
static const patchTask = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.patch');
|
||||||
static const getTasks = RpcMethod<List<String>, List<Task>>('gopeed.task.list');
|
static const getTasks = RpcMethod<List<String>, List<Task>>('gopeed.task.list');
|
||||||
static const getTaskStatus = RpcMethod<String, TaskRuntimeStatus>('gopeed.task.status');
|
static const getTaskStatus = RpcMethod<String, TaskRuntimeStatus>('gopeed.task.status');
|
||||||
@@ -53,7 +53,7 @@ class GopeedService {
|
|||||||
|
|
||||||
Future<String> createTask(CreateTask request) => _invoker.invoke(GopeedMethods.createTask, request);
|
Future<String> createTask(CreateTask request) => _invoker.invoke(GopeedMethods.createTask, request);
|
||||||
|
|
||||||
Future<List<String>> createTaskBatch(CreateTaskBatch request) =>
|
Future<CreateTaskBatchResult> createTaskBatch(CreateTaskBatch request) =>
|
||||||
_invoker.invoke(GopeedMethods.createTaskBatch, request);
|
_invoker.invoke(GopeedMethods.createTaskBatch, request);
|
||||||
|
|
||||||
Future<void> patchTask(String id, PatchTask request) async {
|
Future<void> patchTask(String id, PatchTask request) async {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform;
|
||||||
import 'package:flutter/material.dart' show Colors, Icons;
|
import 'package:flutter/material.dart' show Colors, Icons;
|
||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||||
@@ -48,10 +49,10 @@ class _BatchActionAvailability {
|
|||||||
_BatchActionAvailability _batchActionAvailability(Iterable<TaskRecord> tasks, TaskBatchSelectionController selection) {
|
_BatchActionAvailability _batchActionAvailability(Iterable<TaskRecord> tasks, TaskBatchSelectionController selection) {
|
||||||
var canPause = false;
|
var canPause = false;
|
||||||
var canResume = false;
|
var canResume = false;
|
||||||
for (final task in tasks) {
|
for (final task in tasks.expand((task) => [task, ...task.members])) {
|
||||||
if (!selection.contains(task.id)) continue;
|
if (!selection.contains(task.id)) continue;
|
||||||
canPause = canPause || task.status == TaskStatus.downloading;
|
canPause = canPause || task.canPause;
|
||||||
canResume = canResume || task.status == TaskStatus.paused || task.status == TaskStatus.failed;
|
canResume = canResume || task.canResume;
|
||||||
if (canPause && canResume) break;
|
if (canPause && canResume) break;
|
||||||
}
|
}
|
||||||
return _BatchActionAvailability(canPause: canPause, canResume: canResume);
|
return _BatchActionAvailability(canPause: canPause, canResume: canResume);
|
||||||
@@ -69,6 +70,7 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
_TaskFilter _activeFilter = _TaskFilter.downloading;
|
_TaskFilter _activeFilter = _TaskFilter.downloading;
|
||||||
TaskRecord? _selectedTask;
|
TaskRecord? _selectedTask;
|
||||||
bool _batchMode = false;
|
bool _batchMode = false;
|
||||||
|
final Set<String> _expandedGroupIds = {};
|
||||||
final TaskBatchSelectionController _batchSelection = TaskBatchSelectionController();
|
final TaskBatchSelectionController _batchSelection = TaskBatchSelectionController();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -96,11 +98,16 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
final tasksState = tasksAsync.value;
|
final tasksState = tasksAsync.value;
|
||||||
final tasks = tasksState?.tasks ?? const <TaskRecord>[];
|
final tasks = tasksState?.tasks ?? const <TaskRecord>[];
|
||||||
final filteredTasks = _filteredTasks(tasks);
|
final filteredTasks = _filteredTasks(tasks);
|
||||||
|
final visibleTasks = _visibleTasks(filteredTasks);
|
||||||
|
final memberIds = {
|
||||||
|
for (final task in tasks)
|
||||||
|
for (final member in task.members) member.id,
|
||||||
|
};
|
||||||
final emptyStateMessage = _searchController.text.trim().isEmpty
|
final emptyStateMessage = _searchController.text.trim().isEmpty
|
||||||
? context.l10n.emptyTaskList
|
? context.l10n.emptyTaskList
|
||||||
: context.l10n.noMatchingTasks;
|
: context.l10n.noMatchingTasks;
|
||||||
final selectedTask = _latestSelectedTask(tasks);
|
final selectedTask = _latestSelectedTask();
|
||||||
final visibleTaskIds = filteredTasks.map((task) => task.id).toList(growable: false);
|
final visibleTaskIds = visibleTasks.map((task) => task.id).toList(growable: false);
|
||||||
final pendingUpdateTask = ref.watch(pendingUpdateTaskProvider);
|
final pendingUpdateTask = ref.watch(pendingUpdateTaskProvider);
|
||||||
final navigationItems = _taskNavigationItems(tasks);
|
final navigationItems = _taskNavigationItems(tasks);
|
||||||
final desktopBody = shad.Scaffold(
|
final desktopBody = shad.Scaffold(
|
||||||
@@ -158,7 +165,7 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
listenable: _batchSelection,
|
listenable: _batchSelection,
|
||||||
builder: (context, _) => _TaskBatchRow(
|
builder: (context, _) => _TaskBatchRow(
|
||||||
selectedCount: _batchSelection.count,
|
selectedCount: _batchSelection.count,
|
||||||
totalCount: filteredTasks.length,
|
totalCount: visibleTasks.length,
|
||||||
allSelected: _batchSelection.areAllSelected(visibleTaskIds),
|
allSelected: _batchSelection.areAllSelected(visibleTaskIds),
|
||||||
someSelected:
|
someSelected:
|
||||||
_batchSelection.isNotEmpty &&
|
_batchSelection.isNotEmpty &&
|
||||||
@@ -179,16 +186,19 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
)
|
)
|
||||||
: ListView.separated(
|
: ListView.separated(
|
||||||
padding: const EdgeInsets.only(bottom: 16),
|
padding: const EdgeInsets.only(bottom: 16),
|
||||||
itemCount: filteredTasks.length,
|
itemCount: visibleTasks.length,
|
||||||
separatorBuilder: (_, _) => const SizedBox(height: 8),
|
separatorBuilder: (_, _) => const SizedBox(height: 8),
|
||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
final task = filteredTasks[index];
|
final task = visibleTasks[index];
|
||||||
return TaskBatchSelectionBuilder(
|
return TaskBatchSelectionBuilder(
|
||||||
|
key: ValueKey(task.id),
|
||||||
controller: _batchSelection,
|
controller: _batchSelection,
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
visibleTaskIds: visibleTaskIds,
|
visibleTaskIds: visibleTaskIds,
|
||||||
builder: (context, selectedInBatch, allSelected) => TaskCard(
|
builder: (context, selectedInBatch, allSelected) => TaskCard(
|
||||||
task: task,
|
task: task,
|
||||||
|
nested: memberIds.contains(task.id),
|
||||||
|
expanded: _expandedGroupIds.contains(task.id),
|
||||||
selected: _selectedTask?.id == task.id,
|
selected: _selectedTask?.id == task.id,
|
||||||
batchMode: _batchMode,
|
batchMode: _batchMode,
|
||||||
selectedInBatch: selectedInBatch,
|
selectedInBatch: selectedInBatch,
|
||||||
@@ -242,6 +252,8 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
final mobileBody = tasksAsync.when(
|
final mobileBody = tasksAsync.when(
|
||||||
loading: () => _MobileTasksView(
|
loading: () => _MobileTasksView(
|
||||||
tasks: const [],
|
tasks: const [],
|
||||||
|
memberIds: const {},
|
||||||
|
expandedGroupIds: _expandedGroupIds,
|
||||||
batchMode: _batchMode,
|
batchMode: _batchMode,
|
||||||
batchSelection: _batchSelection,
|
batchSelection: _batchSelection,
|
||||||
loading: true,
|
loading: true,
|
||||||
@@ -262,7 +274,9 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
),
|
),
|
||||||
error: (error, _) => ColoredBox(color: palette.bg, child: const TaskEmptyState()),
|
error: (error, _) => ColoredBox(color: palette.bg, child: const TaskEmptyState()),
|
||||||
data: (_) => _MobileTasksView(
|
data: (_) => _MobileTasksView(
|
||||||
tasks: filteredTasks,
|
tasks: visibleTasks,
|
||||||
|
memberIds: memberIds,
|
||||||
|
expandedGroupIds: _expandedGroupIds,
|
||||||
emptyStateMessage: emptyStateMessage,
|
emptyStateMessage: emptyStateMessage,
|
||||||
onCreateTask: _searchController.text.trim().isEmpty ? _handleAddTask : null,
|
onCreateTask: _searchController.text.trim().isEmpty ? _handleAddTask : null,
|
||||||
batchMode: _batchMode,
|
batchMode: _batchMode,
|
||||||
@@ -331,20 +345,20 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
_TaskFilter.completed => task.status == TaskStatus.completed,
|
_TaskFilter.completed => task.status == TaskStatus.completed,
|
||||||
_TaskFilter.failed => task.status == TaskStatus.failed,
|
_TaskFilter.failed => task.status == TaskStatus.failed,
|
||||||
};
|
};
|
||||||
final passesSearch =
|
final passesSearch = task.matchesSearch(query);
|
||||||
query.isEmpty || task.name.toLowerCase().contains(query) || task.url.toLowerCase().contains(query);
|
|
||||||
return passesFilter && passesSearch;
|
return passesFilter && passesSearch;
|
||||||
})
|
})
|
||||||
.toList(growable: false);
|
.toList(growable: false);
|
||||||
}
|
}
|
||||||
|
|
||||||
TaskRecord? _latestSelectedTask(List<TaskRecord> tasks) {
|
List<TaskRecord> _visibleTasks(List<TaskRecord> tasks) => [
|
||||||
|
for (final task in tasks) ...[task, if (_expandedGroupIds.contains(task.id)) ...task.members],
|
||||||
|
];
|
||||||
|
|
||||||
|
TaskRecord? _latestSelectedTask() {
|
||||||
final selectedTask = _selectedTask;
|
final selectedTask = _selectedTask;
|
||||||
if (selectedTask == null) return null;
|
if (selectedTask == null) return null;
|
||||||
for (final task in tasks) {
|
return ref.read(tasksControllerProvider).value?.findTask(selectedTask.id);
|
||||||
if (task.id == selectedTask.id) return task;
|
|
||||||
}
|
|
||||||
return selectedTask;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
List<ResponsiveNavigationItem<_TaskFilter>> _taskNavigationItems(List<TaskRecord> tasks) {
|
List<ResponsiveNavigationItem<_TaskFilter>> _taskNavigationItems(List<TaskRecord> tasks) {
|
||||||
@@ -376,7 +390,13 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
if (_batchMode) {
|
if (_batchMode) {
|
||||||
_toggleBatchTask(task.id);
|
_toggleBatchTask(task.id);
|
||||||
} else {
|
} else {
|
||||||
_showTaskDetails(task);
|
if (task.isGroup) {
|
||||||
|
setState(() {
|
||||||
|
if (!_expandedGroupIds.remove(task.id)) _expandedGroupIds.add(task.id);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
_showTaskDetails(task);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,8 +426,8 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
void _toggleBatchTask(String taskId) => _batchSelection.toggle(taskId);
|
void _toggleBatchTask(String taskId) => _batchSelection.toggle(taskId);
|
||||||
|
|
||||||
void _toggleSelectAll() {
|
void _toggleSelectAll() {
|
||||||
final visibleIds = _filteredTasks(
|
final visibleIds = _visibleTasks(
|
||||||
ref.read(tasksControllerProvider).value?.tasks ?? const [],
|
_filteredTasks(ref.read(tasksControllerProvider).value?.tasks ?? const []),
|
||||||
).map((task) => task.id).toList(growable: false);
|
).map((task) => task.id).toList(growable: false);
|
||||||
if (_batchSelection.areAllSelected(visibleIds)) {
|
if (_batchSelection.areAllSelected(visibleIds)) {
|
||||||
_batchSelection.clear();
|
_batchSelection.clear();
|
||||||
@@ -430,22 +450,20 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
|
|
||||||
void _pauseSelectedTasks() {
|
void _pauseSelectedTasks() {
|
||||||
if (_batchMode && _batchSelection.isEmpty) return;
|
if (_batchMode && _batchSelection.isEmpty) return;
|
||||||
final ids = _batchMode ? _selectedTaskIdsFor((task) => task.status == TaskStatus.downloading) : null;
|
final ids = _batchMode ? _selectedTaskIdsFor((task) => task.canPause) : null;
|
||||||
if (_batchMode && ids!.isEmpty) return;
|
if (_batchMode && ids!.isEmpty) return;
|
||||||
unawaited(_runTaskAction(() => ref.read(tasksControllerProvider.notifier).pauseAll(ids)));
|
unawaited(_runTaskAction(() => ref.read(tasksControllerProvider.notifier).pauseAll(ids)));
|
||||||
}
|
}
|
||||||
|
|
||||||
void _resumeSelectedTasks() {
|
void _resumeSelectedTasks() {
|
||||||
if (_batchMode && _batchSelection.isEmpty) return;
|
if (_batchMode && _batchSelection.isEmpty) return;
|
||||||
final ids = _batchMode
|
final ids = _batchMode ? _selectedTaskIdsFor((task) => task.canResume) : null;
|
||||||
? _selectedTaskIdsFor((task) => task.status == TaskStatus.paused || task.status == TaskStatus.failed)
|
|
||||||
: null;
|
|
||||||
if (_batchMode && ids!.isEmpty) return;
|
if (_batchMode && ids!.isEmpty) return;
|
||||||
unawaited(_runTaskAction(() => ref.read(tasksControllerProvider.notifier).resumeAll(ids)));
|
unawaited(_runTaskAction(() => ref.read(tasksControllerProvider.notifier).resumeAll(ids)));
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _selectedTaskIdsFor(bool Function(TaskRecord task) test) {
|
List<String> _selectedTaskIdsFor(bool Function(TaskRecord task) test) {
|
||||||
final tasks = ref.read(tasksControllerProvider).value?.tasks ?? const <TaskRecord>[];
|
final tasks = ref.read(tasksControllerProvider).value?.allTasks ?? const <TaskRecord>[];
|
||||||
return tasks.where((task) => _batchSelection.contains(task.id) && test(task)).map((task) => task.id).toList();
|
return tasks.where((task) => _batchSelection.contains(task.id) && test(task)).map((task) => task.id).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -479,8 +497,8 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<String> _contextTaskIds(TaskRecord task) {
|
List<String> _contextTaskIds(TaskRecord task) {
|
||||||
final visibleIds = _filteredTasks(
|
final visibleIds = _visibleTasks(
|
||||||
ref.read(tasksControllerProvider).value?.tasks ?? const [],
|
_filteredTasks(ref.read(tasksControllerProvider).value?.tasks ?? const []),
|
||||||
).map((item) => item.id).toSet();
|
).map((item) => item.id).toSet();
|
||||||
return <String>{..._batchSelection.where(visibleIds.contains), task.id}.toList(growable: false);
|
return <String>{..._batchSelection.where(visibleIds.contains), task.id}.toList(growable: false);
|
||||||
}
|
}
|
||||||
@@ -502,9 +520,27 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
if (ids.isEmpty) return;
|
if (ids.isEmpty) return;
|
||||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||||
final config = runtime?.downloaderConfig;
|
final config = runtime?.downloaderConfig;
|
||||||
|
final selected =
|
||||||
|
ref.read(tasksControllerProvider).value?.allTasks.where((task) => ids.contains(task.id)).toList() ??
|
||||||
|
<TaskRecord>[];
|
||||||
|
final groupedMemberIds = {
|
||||||
|
for (final task in selected)
|
||||||
|
for (final member in task.members) member.id,
|
||||||
|
};
|
||||||
|
ids = ids.where((id) => !groupedMemberIds.contains(id)).toList();
|
||||||
|
selected.removeWhere((task) => groupedMemberIds.contains(task.id));
|
||||||
|
final hasGroups = selected.any((task) => task.isGroup);
|
||||||
final keepFiles = await showTaskDeleteDialog(
|
final keepFiles = await showTaskDeleteDialog(
|
||||||
context,
|
context,
|
||||||
taskCount: ids.length,
|
taskCount: ids.length,
|
||||||
|
memberCount: !hasGroups
|
||||||
|
? null
|
||||||
|
: selected.fold<int>(0, (total, task) => total + (task.isGroup ? task.members.length : 1)),
|
||||||
|
// A task always downloads at least one file; records whose resource
|
||||||
|
// has no file list (plain single-file downloads) still count as one.
|
||||||
|
fileCount: !hasGroups
|
||||||
|
? null
|
||||||
|
: selected.fold<int>(0, (total, task) => total + (task.files.isEmpty ? 1 : task.files.length)),
|
||||||
keepFiles: config?.extra.lastDeleteTaskKeep ?? false,
|
keepFiles: config?.extra.lastDeleteTaskKeep ?? false,
|
||||||
);
|
);
|
||||||
if (keepFiles == null || !mounted) return;
|
if (keepFiles == null || !mounted) return;
|
||||||
@@ -518,10 +554,11 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
await ref.read(appRuntimeControllerProvider.notifier).reloadConfig();
|
await ref.read(appRuntimeControllerProvider.notifier).reloadConfig();
|
||||||
});
|
});
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
_batchSelection.removeAll(ids);
|
_batchSelection.removeAll({...ids, ...groupedMemberIds});
|
||||||
setState(() {
|
setState(() {
|
||||||
_batchMode = false;
|
_batchMode = false;
|
||||||
if (_selectedTask != null && ids.contains(_selectedTask!.id)) {
|
_expandedGroupIds.removeAll(ids);
|
||||||
|
if (_selectedTask != null && (ids.contains(_selectedTask!.id) || groupedMemberIds.contains(_selectedTask!.id))) {
|
||||||
_selectedTask = null;
|
_selectedTask = null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -569,14 +606,8 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
Future<void> _updateTaskUrl(String id, String url, {Map<String, String> headers = const {}}) async {
|
Future<void> _updateTaskUrl(String id, String url, {Map<String, String> headers = const {}}) async {
|
||||||
try {
|
try {
|
||||||
await ref.read(tasksControllerProvider.notifier).updateUrl(id, url, headers: headers);
|
await ref.read(tasksControllerProvider.notifier).updateUrl(id, url, headers: headers);
|
||||||
final updatedTasks = ref.read(tasksControllerProvider).value?.tasks ?? const <TaskRecord>[];
|
if (mounted) {
|
||||||
for (final task in updatedTasks) {
|
setState(() => _selectedTask = ref.read(tasksControllerProvider).value?.findTask(id));
|
||||||
if (task.id == id) {
|
|
||||||
if (mounted) {
|
|
||||||
setState(() => _selectedTask = task);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!mounted) rethrow;
|
if (!mounted) rethrow;
|
||||||
@@ -586,6 +617,16 @@ class _HomePageState extends ConsumerState<HomePage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openTask(TaskRecord task) async {
|
Future<void> _openTask(TaskRecord task) async {
|
||||||
|
final nativeDirectory =
|
||||||
|
!Util.isWeb() &&
|
||||||
|
switch (defaultTargetPlatform) {
|
||||||
|
TargetPlatform.windows || TargetPlatform.macOS || TargetPlatform.linux => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if (task.isGroup && !nativeDirectory) {
|
||||||
|
await browseTaskFiles(context, task, mobile: MediaQuery.sizeOf(context).width < Breakpoints.mobile);
|
||||||
|
return;
|
||||||
|
}
|
||||||
final opened = task.isFolder
|
final opened = task.isFolder
|
||||||
? await FileExplorer.reveal(task.storagePath)
|
? await FileExplorer.reveal(task.storagePath)
|
||||||
: await FileExplorer.open(task.storagePath);
|
: await FileExplorer.open(task.storagePath);
|
||||||
@@ -674,6 +715,8 @@ class _TaskBatchRow extends StatelessWidget {
|
|||||||
class _MobileTasksView extends StatelessWidget {
|
class _MobileTasksView extends StatelessWidget {
|
||||||
const _MobileTasksView({
|
const _MobileTasksView({
|
||||||
required this.tasks,
|
required this.tasks,
|
||||||
|
required this.memberIds,
|
||||||
|
required this.expandedGroupIds,
|
||||||
required this.batchMode,
|
required this.batchMode,
|
||||||
required this.batchSelection,
|
required this.batchSelection,
|
||||||
required this.onToggleSelectAll,
|
required this.onToggleSelectAll,
|
||||||
@@ -695,6 +738,8 @@ class _MobileTasksView extends StatelessWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
final List<TaskRecord> tasks;
|
final List<TaskRecord> tasks;
|
||||||
|
final Set<String> memberIds;
|
||||||
|
final Set<String> expandedGroupIds;
|
||||||
final bool batchMode;
|
final bool batchMode;
|
||||||
final TaskBatchSelectionController batchSelection;
|
final TaskBatchSelectionController batchSelection;
|
||||||
final VoidCallback onToggleSelectAll;
|
final VoidCallback onToggleSelectAll;
|
||||||
@@ -760,11 +805,14 @@ class _MobileTasksView extends StatelessWidget {
|
|||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
final task = tasks[index];
|
final task = tasks[index];
|
||||||
return TaskBatchSelectionBuilder(
|
return TaskBatchSelectionBuilder(
|
||||||
|
key: ValueKey(task.id),
|
||||||
controller: batchSelection,
|
controller: batchSelection,
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
visibleTaskIds: visibleTaskIds,
|
visibleTaskIds: visibleTaskIds,
|
||||||
builder: (context, selectedInBatch, allSelected) => TaskCard(
|
builder: (context, selectedInBatch, allSelected) => TaskCard(
|
||||||
task: task,
|
task: task,
|
||||||
|
nested: memberIds.contains(task.id),
|
||||||
|
expanded: expandedGroupIds.contains(task.id),
|
||||||
selected: false,
|
selected: false,
|
||||||
batchMode: batchMode,
|
batchMode: batchMode,
|
||||||
selectedInBatch: selectedInBatch,
|
selectedInBatch: selectedInBatch,
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
import 'package:path/path.dart' as path;
|
||||||
|
|
||||||
|
import '../../../api/model/create_task_batch.dart';
|
||||||
|
import '../../../api/model/options.dart';
|
||||||
|
import '../../../api/model/request.dart';
|
||||||
|
import '../../../api/model/resource.dart';
|
||||||
|
import '../../../api/model/resolve_result.dart';
|
||||||
|
import '../../../api/model/resolve_task.dart';
|
||||||
|
import '../../../core/capabilities/gopeed_capability.dart';
|
||||||
|
|
||||||
|
/// IDs identify sources within one preview and are never sent as group IDs.
|
||||||
|
class PendingDownload {
|
||||||
|
PendingDownload({required this.id, required this.request, required this.options});
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final Request request;
|
||||||
|
final Options options;
|
||||||
|
ResolveResult? result;
|
||||||
|
String? resolveError;
|
||||||
|
String? createError;
|
||||||
|
final Set<int> selected = {};
|
||||||
|
bool created = false;
|
||||||
|
bool resolving = false;
|
||||||
|
|
||||||
|
bool get loading => result == null && resolveError == null;
|
||||||
|
bool get isGroup => result != null && result!.id.isEmpty && result!.res.name.trim().isNotEmpty && files.length > 1;
|
||||||
|
bool get isFtp => RegExp(r'^(ftps?|ftpes):', caseSensitive: false).hasMatch(request.url.trim());
|
||||||
|
bool get isBt {
|
||||||
|
if (result?.id.isEmpty == true) return false;
|
||||||
|
final url = request.url.trim().toLowerCase();
|
||||||
|
if (url.startsWith('http:') || url.startsWith('https:') || isFtp) return false;
|
||||||
|
return url.startsWith('magnet:') ||
|
||||||
|
url.startsWith('data:application/x-bittorrent;base64,') ||
|
||||||
|
url.split(RegExp(r'[?#]')).first.endsWith('.torrent');
|
||||||
|
}
|
||||||
|
|
||||||
|
String get name {
|
||||||
|
if (!isBt &&
|
||||||
|
(!isFtp || result?.res.name.trim().isEmpty == true) &&
|
||||||
|
result?.id.isNotEmpty == true &&
|
||||||
|
files.length == 1 &&
|
||||||
|
files.single.name.isNotEmpty) {
|
||||||
|
return files.single.name;
|
||||||
|
}
|
||||||
|
if (result?.res.name.trim().isNotEmpty == true) return result!.res.name;
|
||||||
|
return request.url;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<FileInfo> get files => result?.res.files ?? const [];
|
||||||
|
bool get hasSelection => !created && result != null && selected.isNotEmpty;
|
||||||
|
|
||||||
|
Future<void> resolve(GopeedService service) async {
|
||||||
|
if (result != null || resolving) return;
|
||||||
|
resolving = true;
|
||||||
|
resolveError = null;
|
||||||
|
try {
|
||||||
|
result = await service.resolve(ResolveTask(req: request));
|
||||||
|
selected.addAll(List.generate(files.isEmpty ? 1 : files.length, (index) => index));
|
||||||
|
} catch (error) {
|
||||||
|
resolveError = error.toString();
|
||||||
|
} finally {
|
||||||
|
resolving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<CreateTaskBatchItem> creationItems() {
|
||||||
|
final indexes = selected.toList()..sort();
|
||||||
|
if (result!.id.isNotEmpty || files.isEmpty) {
|
||||||
|
final opts = Options.fromJson(options.toJson());
|
||||||
|
if (files.isNotEmpty) opts.selectFiles = indexes;
|
||||||
|
if (indexes.length > 1) _omitChecksum(opts);
|
||||||
|
return [
|
||||||
|
CreateTaskBatchItem(
|
||||||
|
rid: result!.id.isEmpty ? null : result!.id,
|
||||||
|
req: result!.id.isEmpty ? request : null,
|
||||||
|
opts: opts,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
final group = isGroup;
|
||||||
|
final resourceName = result!.res.name;
|
||||||
|
final parentSegments = [
|
||||||
|
if (!group && options.path.isNotEmpty) options.path,
|
||||||
|
if (!group && resourceName.trim().isNotEmpty) resourceName,
|
||||||
|
];
|
||||||
|
final skipAutoCategorize = options.skipAutoCategorize || resourceName.isNotEmpty || files.length > 1;
|
||||||
|
final httpUrl = RegExp(r'^https?:', caseSensitive: false);
|
||||||
|
return indexes.map((index) {
|
||||||
|
final file = files[index];
|
||||||
|
final member = Options.fromJson(options.toJson());
|
||||||
|
member.name = files.length == 1 && options.name.isNotEmpty ? options.name : file.name;
|
||||||
|
final segments = [...parentSegments, if (file.path.isNotEmpty) file.path];
|
||||||
|
member.path = segments.isEmpty ? '' : path.joinAll(segments);
|
||||||
|
// The selected parent directory is persisted separately from members.
|
||||||
|
member.asDefaultPath = false;
|
||||||
|
member.skipAutoCategorize = skipAutoCategorize;
|
||||||
|
final req = file.req ?? request;
|
||||||
|
member.size = httpUrl.hasMatch(req.url) ? file.size : 0;
|
||||||
|
if (RegExp(r'^(ftps?|ftpes):', caseSensitive: false).hasMatch(req.url)) {
|
||||||
|
final extra = OptsExtraFtp.fromJson(Map<String, dynamic>.from(member.extra as Map? ?? const {}));
|
||||||
|
extra.connections = extra.connections.clamp(0, 32);
|
||||||
|
member.extra = extra.toJson();
|
||||||
|
}
|
||||||
|
if (indexes.length > 1) _omitChecksum(member);
|
||||||
|
return CreateTaskBatchItem(req: req, opts: member);
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _omitChecksum(Options opts) {
|
||||||
|
if (opts.extra is Map) opts.extra = Map<String, dynamic>.from(opts.extra! as Map)..remove('checksum');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A successful response completes the entire batch, including partial success.
|
||||||
|
class DownloadSubmission {
|
||||||
|
DownloadSubmission({required this.sources, required this.request});
|
||||||
|
|
||||||
|
final List<PendingDownload> sources;
|
||||||
|
final CreateTaskBatch request;
|
||||||
|
|
||||||
|
Future<void> submit(GopeedService service) async {
|
||||||
|
for (final source in sources) {
|
||||||
|
source.createError = null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await service.createTaskBatch(request);
|
||||||
|
for (final source in sources) {
|
||||||
|
source.created = true;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
for (final source in sources) {
|
||||||
|
source.createError = error.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<DownloadSubmission> planDownloads(List<PendingDownload> sources) {
|
||||||
|
final groups = <DownloadSubmission>[];
|
||||||
|
final independent = <PendingDownload>[];
|
||||||
|
for (final source in sources.where((source) => source.hasSelection)) {
|
||||||
|
if (source.isGroup) {
|
||||||
|
groups.add(
|
||||||
|
DownloadSubmission(
|
||||||
|
sources: [source],
|
||||||
|
request: CreateTaskBatch(
|
||||||
|
group: true,
|
||||||
|
groupName: source.options.name.isNotEmpty ? source.options.name : source.result!.res.name.trim(),
|
||||||
|
opts: source.options,
|
||||||
|
reqs: source.creationItems(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
independent.add(source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
...groups,
|
||||||
|
if (independent.isNotEmpty)
|
||||||
|
DownloadSubmission(
|
||||||
|
sources: independent,
|
||||||
|
request: CreateTaskBatch(reqs: [for (final source in independent) ...source.creationItems()]),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -23,6 +23,10 @@ class TasksState {
|
|||||||
final int uploadSpeedBytesPerSecond;
|
final int uploadSpeedBytesPerSecond;
|
||||||
final Object? lastError;
|
final Object? lastError;
|
||||||
|
|
||||||
|
Iterable<TaskRecord> get allTasks => tasks.expand((task) => [task, ...task.members]);
|
||||||
|
|
||||||
|
TaskRecord? findTask(String id) => allTasks.where((task) => task.id == id).firstOrNull;
|
||||||
|
|
||||||
TasksState copyWith({
|
TasksState copyWith({
|
||||||
List<TaskRecord>? tasks,
|
List<TaskRecord>? tasks,
|
||||||
int? downloadSpeedBytesPerSecond,
|
int? downloadSpeedBytesPerSecond,
|
||||||
@@ -122,13 +126,14 @@ class TasksController extends AsyncNotifier<TasksState> {
|
|||||||
Future<TasksState> _fetch() async {
|
Future<TasksState> _fetch() async {
|
||||||
final tasks = await ref.read(gopeedServiceProvider).getTasks(api_model.Status.values);
|
final tasks = await ref.read(gopeedServiceProvider).getTasks(api_model.Status.values);
|
||||||
final transferSpeeds = aggregateTaskTransferSpeeds(tasks);
|
final transferSpeeds = aggregateTaskTransferSpeeds(tasks);
|
||||||
tasks.sort((a, b) {
|
|
||||||
if (a.status == api_model.Status.running && b.status != api_model.Status.running) return -1;
|
|
||||||
if (a.status != api_model.Status.running && b.status == api_model.Status.running) return 1;
|
|
||||||
return b.updatedAt.compareTo(a.updatedAt);
|
|
||||||
});
|
|
||||||
return TasksState(
|
return TasksState(
|
||||||
tasks: tasks.map(TaskRecord.fromApi).toList(growable: false),
|
tasks: taskRecordsFromApi(tasks)
|
||||||
|
..sort((a, b) {
|
||||||
|
final aRunning = a.status == TaskStatus.downloading && !a.waiting;
|
||||||
|
final bRunning = b.status == TaskStatus.downloading && !b.waiting;
|
||||||
|
if (aRunning != bRunning) return aRunning ? -1 : 1;
|
||||||
|
return (b.updatedAt ?? b.createdAt!).compareTo(a.updatedAt ?? a.createdAt!);
|
||||||
|
}),
|
||||||
downloadSpeedBytesPerSecond: transferSpeeds.downloadBytesPerSecond,
|
downloadSpeedBytesPerSecond: transferSpeeds.downloadBytesPerSecond,
|
||||||
uploadSpeedBytesPerSecond: transferSpeeds.uploadBytesPerSecond,
|
uploadSpeedBytesPerSecond: transferSpeeds.uploadBytesPerSecond,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -42,6 +42,10 @@ class TaskFileNode {
|
|||||||
required this.sizeBytes,
|
required this.sizeBytes,
|
||||||
this.downloadedBytes,
|
this.downloadedBytes,
|
||||||
this.resourceIndex,
|
this.resourceIndex,
|
||||||
|
this.status,
|
||||||
|
this.taskId,
|
||||||
|
this.accessPath,
|
||||||
|
this.localPath,
|
||||||
});
|
});
|
||||||
|
|
||||||
final int? resourceIndex;
|
final int? resourceIndex;
|
||||||
@@ -49,6 +53,10 @@ class TaskFileNode {
|
|||||||
final String name;
|
final String name;
|
||||||
final int sizeBytes;
|
final int sizeBytes;
|
||||||
final int? downloadedBytes;
|
final int? downloadedBytes;
|
||||||
|
final TaskStatus? status;
|
||||||
|
final String? taskId;
|
||||||
|
final String? accessPath;
|
||||||
|
final String? localPath;
|
||||||
|
|
||||||
double? get progress {
|
double? get progress {
|
||||||
final downloaded = downloadedBytes;
|
final downloaded = downloadedBytes;
|
||||||
@@ -68,6 +76,8 @@ class TaskRecord {
|
|||||||
required this.files,
|
required this.files,
|
||||||
required this.uploading,
|
required this.uploading,
|
||||||
this.isFolder = false,
|
this.isFolder = false,
|
||||||
|
this.isGroup = false,
|
||||||
|
this.members = const [],
|
||||||
this.protocol,
|
this.protocol,
|
||||||
this.requestHeaders = const {},
|
this.requestHeaders = const {},
|
||||||
this.total,
|
this.total,
|
||||||
@@ -84,6 +94,8 @@ class TaskRecord {
|
|||||||
this.totalBytes,
|
this.totalBytes,
|
||||||
this.speedBytes,
|
this.speedBytes,
|
||||||
this.uploadedBytes,
|
this.uploadedBytes,
|
||||||
|
this.uploadSpeedBytes,
|
||||||
|
this.updatedAt,
|
||||||
this.remainingSeconds,
|
this.remainingSeconds,
|
||||||
this.waiting = false,
|
this.waiting = false,
|
||||||
}) : assert(!uploading || uploadSpeed != null);
|
}) : assert(!uploading || uploadSpeed != null);
|
||||||
@@ -108,16 +120,31 @@ class TaskRecord {
|
|||||||
final int? totalBytes;
|
final int? totalBytes;
|
||||||
final int? speedBytes;
|
final int? speedBytes;
|
||||||
final int? uploadedBytes;
|
final int? uploadedBytes;
|
||||||
|
final int? uploadSpeedBytes;
|
||||||
|
final DateTime? updatedAt;
|
||||||
final int? remainingSeconds;
|
final int? remainingSeconds;
|
||||||
final bool waiting;
|
final bool waiting;
|
||||||
final List<TaskFileNode> files;
|
final List<TaskFileNode> files;
|
||||||
final bool uploading;
|
final bool uploading;
|
||||||
final bool isFolder;
|
final bool isFolder;
|
||||||
|
final bool isGroup;
|
||||||
|
final List<TaskRecord> members;
|
||||||
final api_task.Protocol? protocol;
|
final api_task.Protocol? protocol;
|
||||||
final Map<String, String> requestHeaders;
|
final Map<String, String> requestHeaders;
|
||||||
|
|
||||||
bool get canUpdateUrl =>
|
bool get canUpdateUrl =>
|
||||||
protocol == api_task.Protocol.http && (status == TaskStatus.paused || status == TaskStatus.failed);
|
!isGroup && protocol == api_task.Protocol.http && (status == TaskStatus.paused || status == TaskStatus.failed);
|
||||||
|
|
||||||
|
bool get canPause => isGroup ? members.any((task) => task.canPause) : status == TaskStatus.downloading;
|
||||||
|
bool get canResume =>
|
||||||
|
isGroup ? members.any((task) => task.canResume) : status == TaskStatus.paused || status == TaskStatus.failed;
|
||||||
|
|
||||||
|
bool matchesSearch(String query) =>
|
||||||
|
query.isEmpty ||
|
||||||
|
name.toLowerCase().contains(query) ||
|
||||||
|
url.toLowerCase().contains(query) ||
|
||||||
|
files.any((file) => '${file.path}/${file.name}'.toLowerCase().contains(query)) ||
|
||||||
|
members.any((member) => member.matchesSearch(query));
|
||||||
|
|
||||||
bool get isIndeterminate => status == TaskStatus.downloading && !waiting && total == null;
|
bool get isIndeterminate => status == TaskStatus.downloading && !waiting && total == null;
|
||||||
|
|
||||||
@@ -147,6 +174,7 @@ class TaskRecord {
|
|||||||
remainingSeconds: _remainingSeconds(task, totalBytes, downloadedBytes),
|
remainingSeconds: _remainingSeconds(task, totalBytes, downloadedBytes),
|
||||||
downloadDuration: task.progress.used > 0 ? Duration(microseconds: (task.progress.used + 999) ~/ 1000) : null,
|
downloadDuration: task.progress.used > 0 ? Duration(microseconds: (task.progress.used + 999) ~/ 1000) : null,
|
||||||
createdAt: task.createdAt,
|
createdAt: task.createdAt,
|
||||||
|
updatedAt: task.updatedAt,
|
||||||
doneAt: task.doneAt,
|
doneAt: task.doneAt,
|
||||||
waiting: task.status == api_task.Status.wait,
|
waiting: task.status == api_task.Status.wait,
|
||||||
progress: progress,
|
progress: progress,
|
||||||
@@ -156,6 +184,7 @@ class TaskRecord {
|
|||||||
totalBytes: totalBytes > 0 ? totalBytes : null,
|
totalBytes: totalBytes > 0 ? totalBytes : null,
|
||||||
speedBytes: task.progress.speed,
|
speedBytes: task.progress.speed,
|
||||||
uploadedBytes: task.progress.uploaded,
|
uploadedBytes: task.progress.uploaded,
|
||||||
|
uploadSpeedBytes: task.progress.uploadSpeed,
|
||||||
files: _fileNodes(task.meta.res?.files, task.meta.opts.selectFiles),
|
files: _fileNodes(task.meta.res?.files, task.meta.opts.selectFiles),
|
||||||
uploading: task.uploading,
|
uploading: task.uploading,
|
||||||
isFolder: task.meta.res?.name.isNotEmpty ?? false,
|
isFolder: task.meta.res?.name.isNotEmpty ?? false,
|
||||||
@@ -165,6 +194,186 @@ class TaskRecord {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<TaskRecord> taskRecordsFromApi(List<api_task.Task> tasks) {
|
||||||
|
final members = <String, List<TaskRecord>>{};
|
||||||
|
final metadata = <String, api_task.TaskGroup>{};
|
||||||
|
final records = <String, TaskRecord>{};
|
||||||
|
for (final task in tasks) {
|
||||||
|
final record = TaskRecord.fromApi(task);
|
||||||
|
records[task.id] = record;
|
||||||
|
if (task.parentId.isNotEmpty) {
|
||||||
|
members.putIfAbsent(task.parentId, () => []).add(record);
|
||||||
|
if (task.group != null) metadata[task.parentId] = task.group!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final emitted = <String>{};
|
||||||
|
return [
|
||||||
|
for (final task in tasks)
|
||||||
|
if (task.parentId.isEmpty || !metadata.containsKey(task.parentId))
|
||||||
|
records[task.id]!
|
||||||
|
else if (emitted.add(task.parentId))
|
||||||
|
_groupRecord(metadata[task.parentId]!, members[task.parentId]!),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
TaskRecord _groupRecord(api_task.TaskGroup group, List<TaskRecord> members) {
|
||||||
|
final running = members.any((task) => task.status == TaskStatus.downloading && !task.waiting);
|
||||||
|
final failed = members.any((task) => task.status == TaskStatus.failed);
|
||||||
|
final paused = members.isEmpty || members.any((task) => task.status == TaskStatus.paused);
|
||||||
|
final completed = members.isNotEmpty && members.every((task) => task.status == TaskStatus.completed);
|
||||||
|
final status = running
|
||||||
|
? TaskStatus.downloading
|
||||||
|
: failed
|
||||||
|
? TaskStatus.failed
|
||||||
|
: paused
|
||||||
|
? TaskStatus.paused
|
||||||
|
: completed
|
||||||
|
? TaskStatus.completed
|
||||||
|
: TaskStatus.downloading;
|
||||||
|
final downloaded = members.fold(0, (total, task) => total + (task.downloadedBytes ?? 0));
|
||||||
|
final total = members.every((task) => task.totalBytes != null || task.status == TaskStatus.completed)
|
||||||
|
? members.fold(0, (total, task) => total + (task.totalBytes ?? 0))
|
||||||
|
: null;
|
||||||
|
final speed = members.fold(
|
||||||
|
0,
|
||||||
|
(total, task) => total + (task.status == TaskStatus.downloading && !task.waiting ? task.speedBytes ?? 0 : 0),
|
||||||
|
);
|
||||||
|
// The backend freezes a finished single task's speed at bytes over active
|
||||||
|
// time (markTaskDone); a finished group reports the same ratio across its
|
||||||
|
// members instead of collapsing to "0 B/s" when the last member completes.
|
||||||
|
final reportedSpeed = speed > 0 ? speed : (completed ? _averageSpeed(members) ?? 0 : 0);
|
||||||
|
final uploadSpeed = members.fold(0, (total, task) => total + (task.uploading ? task.uploadSpeedBytes ?? 0 : 0));
|
||||||
|
final uploading = members.any((task) => task.uploading);
|
||||||
|
final uploaded = members.fold(0, (total, task) => total + (task.uploadedBytes ?? 0));
|
||||||
|
final pathContext = path.Context(
|
||||||
|
style: group.path.contains('\\') || members.any((task) => task.storagePath.contains('\\'))
|
||||||
|
? path.Style.windows
|
||||||
|
: path.Style.posix,
|
||||||
|
);
|
||||||
|
final root = group.path;
|
||||||
|
final files = <TaskFileNode>[];
|
||||||
|
for (final member in members) {
|
||||||
|
final sourceFiles = member.isFolder
|
||||||
|
? member.files
|
||||||
|
: [TaskFileNode(path: '', name: member.name, sizeBytes: member.totalBytes ?? 0)];
|
||||||
|
// Folder members do not carry per-file progress from the backend; spread
|
||||||
|
// the member's overall ratio over its files so the tree keeps moving
|
||||||
|
// instead of showing flat zeros.
|
||||||
|
final folderTotal = member.isFolder ? member.files.fold<int>(0, (total, file) => total + file.sizeBytes) : 0;
|
||||||
|
final folderRatio = folderTotal > 0 && member.downloadedBytes != null
|
||||||
|
? (member.downloadedBytes! / folderTotal).clamp(0.0, 1.0)
|
||||||
|
: null;
|
||||||
|
for (final file in sourceFiles) {
|
||||||
|
final fullPath = member.isFolder
|
||||||
|
? pathContext.join(member.storagePath, file.path, file.name)
|
||||||
|
: member.storagePath;
|
||||||
|
final relative = pathContext.relative(fullPath, from: root).replaceAll('\\', '/');
|
||||||
|
final String nodePath;
|
||||||
|
final String nodeName;
|
||||||
|
if (pathContext.isAbsolute(relative) || relative == '..' || relative.startsWith('../')) {
|
||||||
|
// Keep unexpected stored paths within the displayed tree.
|
||||||
|
if (member.isFolder) {
|
||||||
|
nodePath = path.posix.join(pathContext.basename(member.storagePath), file.path.replaceAll('\\', '/'));
|
||||||
|
nodeName = file.name;
|
||||||
|
} else {
|
||||||
|
nodePath = '';
|
||||||
|
nodeName = member.name;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
nodePath = path.posix.dirname(relative) == '.' ? '' : path.posix.dirname(relative);
|
||||||
|
nodeName = path.posix.basename(relative);
|
||||||
|
}
|
||||||
|
files.add(
|
||||||
|
TaskFileNode(
|
||||||
|
resourceIndex: files.length,
|
||||||
|
path: nodePath,
|
||||||
|
name: nodeName,
|
||||||
|
sizeBytes: file.sizeBytes,
|
||||||
|
downloadedBytes: member.isFolder
|
||||||
|
? folderRatio != null && file.sizeBytes > 0
|
||||||
|
? (file.sizeBytes * folderRatio).round()
|
||||||
|
: null
|
||||||
|
: member.downloadedBytes,
|
||||||
|
status: member.status,
|
||||||
|
taskId: member.id,
|
||||||
|
localPath: fullPath,
|
||||||
|
accessPath: member.isFolder
|
||||||
|
? path.posix.join(file.path.replaceAll('\\', '/'), file.name)
|
||||||
|
: pathContext.relative(fullPath, from: pathContext.dirname(member.storagePath)).replaceAll('\\', '/'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var updatedAt = group.createdAt;
|
||||||
|
DateTime? doneAt;
|
||||||
|
for (final member in members) {
|
||||||
|
final update = member.updatedAt;
|
||||||
|
if (update != null && update.isAfter(updatedAt)) updatedAt = update;
|
||||||
|
if (completed) {
|
||||||
|
final done = member.doneAt;
|
||||||
|
if (done != null && (doneAt == null || done.isAfter(doneAt))) doneAt = done;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The folder card answers "how long did this download take end to end", so
|
||||||
|
// a completed group reports its wall-clock span; single tasks keep their
|
||||||
|
// active-time semantics.
|
||||||
|
final createdAt = group.createdAt;
|
||||||
|
final downloadDuration = doneAt != null && doneAt.isAfter(createdAt) ? doneAt.difference(createdAt) : null;
|
||||||
|
return TaskRecord(
|
||||||
|
id: group.id,
|
||||||
|
name: group.name,
|
||||||
|
status: status,
|
||||||
|
downloaded: _formatBytes(downloaded),
|
||||||
|
total: total == null ? null : _formatBytes(total),
|
||||||
|
downloadedBytes: downloaded,
|
||||||
|
totalBytes: total,
|
||||||
|
speed: TransferRateFormatter.format(reportedSpeed).text,
|
||||||
|
speedBytes: reportedSpeed,
|
||||||
|
uploadSpeed: uploading ? TransferRateFormatter.format(uploadSpeed).text : null,
|
||||||
|
uploadedBytes: uploaded,
|
||||||
|
uploadSpeedBytes: uploadSpeed,
|
||||||
|
uploading: uploading,
|
||||||
|
progress: completed
|
||||||
|
? 1
|
||||||
|
: total != null && total > 0
|
||||||
|
? (downloaded / total).clamp(0.0, 1.0)
|
||||||
|
: null,
|
||||||
|
remainingSeconds: total != null && speed > 0 && total > downloaded ? ((total - downloaded) / speed).ceil() : null,
|
||||||
|
waiting: status == TaskStatus.downloading && !running,
|
||||||
|
downloadDuration: downloadDuration,
|
||||||
|
url: '',
|
||||||
|
storagePath: root,
|
||||||
|
files: files,
|
||||||
|
isFolder: true,
|
||||||
|
isGroup: true,
|
||||||
|
members: members,
|
||||||
|
createdAt: group.createdAt,
|
||||||
|
updatedAt: updatedAt,
|
||||||
|
doneAt: doneAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The combined average rate of a set of members: downloaded bytes over active
|
||||||
|
// download time, the same ratio the backend freezes into a finished single
|
||||||
|
// task's progress. Members without a measurable duration are skipped because
|
||||||
|
// they would inflate the rate.
|
||||||
|
int? _averageSpeed(List<TaskRecord> members) {
|
||||||
|
var downloaded = 0;
|
||||||
|
var microseconds = 0;
|
||||||
|
for (final member in members) {
|
||||||
|
final duration = member.downloadDuration;
|
||||||
|
if (duration == null || duration.inMicroseconds <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
downloaded += member.downloadedBytes ?? 0;
|
||||||
|
microseconds += duration.inMicroseconds;
|
||||||
|
}
|
||||||
|
if (microseconds <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (downloaded * Duration.microsecondsPerSecond / microseconds).round();
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, String> _requestHeaders(Object? extra) {
|
Map<String, String> _requestHeaders(Object? extra) {
|
||||||
if (extra is! Map) return const {};
|
if (extra is! Map) return const {};
|
||||||
final header = extra['header'];
|
final header = extra['header'];
|
||||||
|
|||||||
@@ -19,8 +19,6 @@ import '../../../../api/model/create_task_batch.dart';
|
|||||||
import '../../../../api/model/downloader_config.dart';
|
import '../../../../api/model/downloader_config.dart';
|
||||||
import '../../../../api/model/options.dart' as api_options;
|
import '../../../../api/model/options.dart' as api_options;
|
||||||
import '../../../../api/model/request.dart';
|
import '../../../../api/model/request.dart';
|
||||||
import '../../../../api/model/resolve_result.dart';
|
|
||||||
import '../../../../api/model/resolve_task.dart';
|
|
||||||
import '../../../../core/capabilities/app_capabilities.dart';
|
import '../../../../core/capabilities/app_capabilities.dart';
|
||||||
import '../../../../core/utils/breakpoints.dart';
|
import '../../../../core/utils/breakpoints.dart';
|
||||||
import '../../../../core/utils/text_wrap.dart';
|
import '../../../../core/utils/text_wrap.dart';
|
||||||
@@ -39,10 +37,11 @@ import '../../../../shared/widgets/app_toast.dart';
|
|||||||
import '../../../../l10n/l10n.dart';
|
import '../../../../l10n/l10n.dart';
|
||||||
import '../../../../util/util.dart';
|
import '../../../../util/util.dart';
|
||||||
import '../../application/pending_create_task.dart';
|
import '../../application/pending_create_task.dart';
|
||||||
|
import '../../application/pending_download.dart';
|
||||||
import '../../application/task_list_navigation.dart';
|
import '../../application/task_list_navigation.dart';
|
||||||
import '../widgets/history_search_field.dart';
|
import '../widgets/history_search_field.dart';
|
||||||
import '../widgets/create_task_action_buttons.dart';
|
import '../widgets/create_task_action_buttons.dart';
|
||||||
import '../widgets/resolve_file_tree.dart';
|
import '../widgets/resolve_download_dialog.dart';
|
||||||
|
|
||||||
class CreateTaskWindowPage extends ConsumerStatefulWidget {
|
class CreateTaskWindowPage extends ConsumerStatefulWidget {
|
||||||
const CreateTaskWindowPage({super.key, this.windowController, this.initialTask});
|
const CreateTaskWindowPage({super.key, this.windowController, this.initialTask});
|
||||||
@@ -92,6 +91,8 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
bool _directDownload = false;
|
bool _directDownload = false;
|
||||||
int _protocolTab = 0;
|
int _protocolTab = 0;
|
||||||
bool _creating = false;
|
bool _creating = false;
|
||||||
|
final Map<String, int> _completedSubmissionCounts = {};
|
||||||
|
int _createSession = 0;
|
||||||
bool _draggingTorrent = false;
|
bool _draggingTorrent = false;
|
||||||
bool _asDefaultPath = false;
|
bool _asDefaultPath = false;
|
||||||
String _configuredDownloadDirectory = '';
|
String _configuredDownloadDirectory = '';
|
||||||
@@ -248,6 +249,8 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
if (task == null || !mounted) return;
|
if (task == null || !mounted) return;
|
||||||
final req = task.req;
|
final req = task.req;
|
||||||
final opts = task.opts ?? api_options.Options();
|
final opts = task.opts ?? api_options.Options();
|
||||||
|
_createSession++;
|
||||||
|
_completedSubmissionCounts.clear();
|
||||||
setState(() {
|
setState(() {
|
||||||
_initialSize = 0;
|
_initialSize = 0;
|
||||||
_checksumAlgorithm = 'md5';
|
_checksumAlgorithm = 'md5';
|
||||||
@@ -871,7 +874,20 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
await windowManager.close();
|
await windowManager.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _finishCreation() async {
|
Future<void> _finishCreation(int session) async {
|
||||||
|
if (!mounted || session != _createSession) return;
|
||||||
|
if (_asDefaultPath && _directoryManuallySet && _directoryController.text.trim().isNotEmpty) {
|
||||||
|
try {
|
||||||
|
final service = ref.read(gopeedServiceProvider);
|
||||||
|
final config = await service.getConfig();
|
||||||
|
if (!mounted || session != _createSession) return;
|
||||||
|
config.downloadDir = _directoryController.text.trim();
|
||||||
|
await service.putConfig(config);
|
||||||
|
} catch (error) {
|
||||||
|
if (mounted && session == _createSession) _showToast(error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mounted || session != _createSession) return;
|
||||||
if (widget.windowController != null) {
|
if (widget.windowController != null) {
|
||||||
// Navigation is best-effort after a successful submission. A navigation
|
// Navigation is best-effort after a successful submission. A navigation
|
||||||
// failure must not leave a completed form available for resubmission.
|
// failure must not leave a completed form available for resubmission.
|
||||||
@@ -883,6 +899,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
} else {
|
} else {
|
||||||
ref.read(taskListNavigationProvider.notifier).showDownloading();
|
ref.read(taskListNavigationProvider.notifier).showDownloading();
|
||||||
}
|
}
|
||||||
|
if (!mounted || session != _createSession) return;
|
||||||
await _closeWindow();
|
await _closeWindow();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -989,53 +1006,74 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
_showToast(context.l10n.downloadLinkValid);
|
_showToast(context.l10n.downloadLinkValid);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!_validateAdvancedOptions()) {
|
final occurrences = <String, int>{};
|
||||||
|
final pendingUrls = <String>[];
|
||||||
|
for (final url in urls) {
|
||||||
|
final occurrence = (occurrences[url] ?? 0) + 1;
|
||||||
|
occurrences[url] = occurrence;
|
||||||
|
if (occurrence > (_completedSubmissionCounts[url] ?? 0)) {
|
||||||
|
pendingUrls.add(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pendingUrls.isNotEmpty && !_validateAdvancedOptions()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
final session = _createSession;
|
||||||
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_creating = true;
|
_creating = true;
|
||||||
_draggingTorrent = false;
|
_draggingTorrent = false;
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
await _saveCreateHistory(urls);
|
unawaited(
|
||||||
final isDirect = _directDownload || urls.length > 1;
|
_saveCreateHistory(urls).catchError((Object error) {
|
||||||
if (isDirect) {
|
if (mounted && session == _createSession) _showToast(error.toString());
|
||||||
await Future.wait(
|
}),
|
||||||
urls.map((url) {
|
);
|
||||||
return ref
|
if (pendingUrls.isEmpty) {
|
||||||
.read(gopeedServiceProvider)
|
await _finishCreation(session);
|
||||||
.createTask(
|
return;
|
||||||
CreateTask(
|
}
|
||||||
req: _buildRequest(url, protocolUrl: _protocolUrlFor(url)),
|
final sources = [
|
||||||
opts: _buildOptions(
|
for (final entry in pendingUrls.indexed)
|
||||||
url: _protocolUrlFor(url),
|
PendingDownload(
|
||||||
name: urls.length > 1 ? '' : _renameController.text.trim(),
|
id: 'source-${entry.$1}',
|
||||||
),
|
request: _buildRequest(entry.$2, protocolUrl: _protocolUrlFor(entry.$2)),
|
||||||
),
|
options: _buildOptions(
|
||||||
);
|
url: _protocolUrlFor(entry.$2),
|
||||||
}),
|
name: urls.length == 1 ? _renameController.text.trim() : '',
|
||||||
|
omitChecksum: urls.length > 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
final service = ref.read(gopeedServiceProvider);
|
||||||
|
if (_directDownload) {
|
||||||
|
await service.createTaskBatch(
|
||||||
|
CreateTaskBatch(
|
||||||
|
reqs: [for (final source in sources) CreateTaskBatchItem(req: source.request, opts: source.options)],
|
||||||
|
),
|
||||||
);
|
);
|
||||||
await _finishCreation();
|
await _finishCreation(session);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final request = _buildRequest(urls.first, protocolUrl: _protocolUrlFor(urls.first));
|
|
||||||
final result = await ref.read(gopeedServiceProvider).resolve(ResolveTask(req: request));
|
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
final created = await _showResolveDialog(request, result);
|
final created = await showResolveDownloadsDialog(
|
||||||
if (!created) {
|
context,
|
||||||
if (mounted) {
|
sources: sources,
|
||||||
setState(() => _creating = false);
|
service: service,
|
||||||
}
|
onBatchCreated: (sources) {
|
||||||
return;
|
if (!mounted || session != _createSession) return;
|
||||||
}
|
for (final source in sources) {
|
||||||
await _finishCreation();
|
_completedSubmissionCounts.update(source.request.url, (count) => count + 1, ifAbsent: () => 1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!mounted || session != _createSession || !created) return;
|
||||||
|
await _finishCreation(session);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (mounted) {
|
if (mounted && session == _createSession) _showToast(error.toString());
|
||||||
_showToast(error.toString());
|
} finally {
|
||||||
setState(() => _creating = false);
|
if (mounted) setState(() => _creating = false);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1298,190 +1336,6 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
_applyCategoryHighlight();
|
_applyCategoryHighlight();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _submitResolved(Request request, ResolveResult result, List<int> selectedIndexes) async {
|
|
||||||
final selected = (selectedIndexes.isEmpty ? result.res.files.asMap().keys.toList() : selectedIndexes.toList())
|
|
||||||
..sort();
|
|
||||||
final isMultiFile = selected.length > 1;
|
|
||||||
if (result.id.isNotEmpty) {
|
|
||||||
await ref
|
|
||||||
.read(gopeedServiceProvider)
|
|
||||||
.createTask(
|
|
||||||
CreateTask(
|
|
||||||
rid: result.id,
|
|
||||||
opts: _buildOptions(url: request.url, selectFiles: selected, omitChecksum: isMultiFile),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.res.files.isNotEmpty) {
|
|
||||||
// The extension returned a file list, so the resource keeps a directory
|
|
||||||
// structure. The split tasks must not be classified into a category, the
|
|
||||||
// structure of the resolved resource is kept. The decision is based on
|
|
||||||
// the resolved resource, not on the number of selected files.
|
|
||||||
final keepStructure = _directoryManuallySet || result.res.name.isNotEmpty || result.res.files.length > 1;
|
|
||||||
final reqs = selected.map((index) {
|
|
||||||
final file = result.res.files[index];
|
|
||||||
final fileRequest = file.req ?? request;
|
|
||||||
return CreateTaskBatchItem(
|
|
||||||
req: fileRequest,
|
|
||||||
opts: api_options.Options(
|
|
||||||
size: _parseProtocol(fileRequest.url) == _TaskProtocol.http ? file.size : 0,
|
|
||||||
name: file.name,
|
|
||||||
path: path.join(_directoryController.text.trim(), result.res.name, file.path),
|
|
||||||
skipAutoCategorize: keepStructure,
|
|
||||||
extra: _buildOptions(url: fileRequest.url, omitChecksum: isMultiFile).extra,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}).toList();
|
|
||||||
await ref
|
|
||||||
.read(gopeedServiceProvider)
|
|
||||||
.createTaskBatch(
|
|
||||||
CreateTaskBatch(
|
|
||||||
reqs: reqs,
|
|
||||||
opts: _buildOptions(url: request.url, omitChecksum: isMultiFile, skipAutoCategorize: keepStructure),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await ref
|
|
||||||
.read(gopeedServiceProvider)
|
|
||||||
.createTask(
|
|
||||||
CreateTask(
|
|
||||||
req: request,
|
|
||||||
opts: _buildOptions(url: request.url),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> _showResolveDialog(Request request, ResolveResult result) async {
|
|
||||||
final initialSelection = List<int>.generate(result.res.files.length, (index) => index);
|
|
||||||
var selectedIndexes = List<int>.of(initialSelection);
|
|
||||||
var submitting = false;
|
|
||||||
String? errorText;
|
|
||||||
// The directory the task will be saved to. A directory the user named
|
|
||||||
// wins over the category suggestion of the resolve response, the backend
|
|
||||||
// keeps it and does not classify the task.
|
|
||||||
final effectiveDownloadDir = _directoryManuallySet
|
|
||||||
? _directoryController.text.trim()
|
|
||||||
: (result.suggestedDownloadDir.isNotEmpty ? result.suggestedDownloadDir : _directoryController.text.trim());
|
|
||||||
|
|
||||||
final dialog = const DialogOverlayHandler().show<bool>(
|
|
||||||
context: context,
|
|
||||||
alignment: Alignment.center,
|
|
||||||
barrierDismissable: !submitting,
|
|
||||||
builder: (dialogContext) {
|
|
||||||
final palette = AppPalette.of(dialogContext);
|
|
||||||
final screenSize = MediaQuery.sizeOf(dialogContext);
|
|
||||||
final dialogWidth = screenSize.width < 760 ? screenSize.width - 32 : 720.0;
|
|
||||||
final treeHeight = screenSize.height < 700 ? screenSize.height * 0.55 : 440.0;
|
|
||||||
|
|
||||||
return StatefulBuilder(
|
|
||||||
builder: (dialogContext, setDialogState) {
|
|
||||||
Future<void> submit() async {
|
|
||||||
if (result.res.files.isNotEmpty && selectedIndexes.isEmpty) {
|
|
||||||
setDialogState(() => errorText = dialogContext.l10n.selectAtLeastOneFile);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setDialogState(() {
|
|
||||||
submitting = true;
|
|
||||||
errorText = null;
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
await _submitResolved(request, result, selectedIndexes);
|
|
||||||
if (dialogContext.mounted) {
|
|
||||||
await closeOverlay(dialogContext, true);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (!dialogContext.mounted) return;
|
|
||||||
setDialogState(() {
|
|
||||||
submitting = false;
|
|
||||||
errorText = error.toString();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return AlertDialog(
|
|
||||||
padding: const EdgeInsets.all(18),
|
|
||||||
title: Text(
|
|
||||||
result.res.name.trim().isEmpty ? dialogContext.l10n.resolvedFiles : result.res.name,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
content: SizedBox(
|
|
||||||
width: dialogWidth,
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
result.res.files.isEmpty
|
|
||||||
? dialogContext.l10n.resourceHasNoFiles
|
|
||||||
: dialogContext.l10n.resolvedFileCount(result.res.files.length),
|
|
||||||
style: TextStyle(color: palette.textSecondary, fontSize: 12),
|
|
||||||
),
|
|
||||||
if (effectiveDownloadDir.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
dialogContext.l10n.resolvedCategoryDirectory(effectiveDownloadDir),
|
|
||||||
key: const ValueKey('resolve-category-directory'),
|
|
||||||
style: TextStyle(color: palette.textSecondary, fontSize: 12),
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
SizedBox(
|
|
||||||
height: treeHeight.clamp(260.0, 460.0),
|
|
||||||
child: result.res.files.isEmpty
|
|
||||||
? Container(
|
|
||||||
alignment: Alignment.center,
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: palette.cardBg,
|
|
||||||
border: Border.all(color: palette.border),
|
|
||||||
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
dialogContext.l10n.noFiles,
|
|
||||||
style: TextStyle(color: palette.textMuted, fontSize: 13),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: ResolveFileTree(
|
|
||||||
files: result.res.files,
|
|
||||||
initialSelection: initialSelection,
|
|
||||||
onSelectionChanged: (values) => selectedIndexes = values,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (errorText != null) ...[
|
|
||||||
const SizedBox(height: 10),
|
|
||||||
Text(errorText!, style: TextStyle(color: palette.error, fontSize: 12)),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
flutter.Flexible(
|
|
||||||
child: CreateTaskActionButtons(
|
|
||||||
submitting: submitting,
|
|
||||||
onCancel: () => closeOverlay(dialogContext, false),
|
|
||||||
onSubmit: submit,
|
|
||||||
cancelLabel: dialogContext.l10n.cancel,
|
|
||||||
submitLabel: dialogContext.l10n.createAction,
|
|
||||||
cancelButtonKey: const ValueKey('resolve-cancel-button'),
|
|
||||||
submitButtonKey: const ValueKey('resolve-create-button'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
final created = await dialog.future;
|
|
||||||
return created == true;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _showCreateHistory() async {
|
Future<void> _showCreateHistory() async {
|
||||||
List<String> histories;
|
List<String> histories;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -21,13 +21,8 @@ class TaskDetailsPage extends ConsumerWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context, WidgetRef ref) {
|
Widget build(BuildContext context, WidgetRef ref) {
|
||||||
final tasksAsync = ref.watch(tasksControllerProvider);
|
final tasksAsync = ref.watch(tasksControllerProvider);
|
||||||
TaskRecord? task = initialTask;
|
final state = tasksAsync.value;
|
||||||
for (final item in tasksAsync.value?.tasks ?? const <TaskRecord>[]) {
|
final task = state == null ? initialTask : state.findTask(taskId);
|
||||||
if (item.id == taskId) {
|
|
||||||
task = item;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final palette = AppPalette.of(context);
|
final palette = AppPalette.of(context);
|
||||||
|
|
||||||
return AppDetailPage(
|
return AppDetailPage(
|
||||||
@@ -43,12 +38,12 @@ class TaskDetailsPage extends ConsumerWidget {
|
|||||||
key: ValueKey(task.id),
|
key: ValueKey(task.id),
|
||||||
task: task,
|
task: task,
|
||||||
mobile: true,
|
mobile: true,
|
||||||
onOpenStorage: () => FileExplorer.reveal(task!.storagePath),
|
onOpenStorage: () => FileExplorer.reveal(task.storagePath),
|
||||||
onUpdateUrl: (url) async {
|
onUpdateUrl: (url) async {
|
||||||
try {
|
try {
|
||||||
await ref
|
await ref
|
||||||
.read(tasksControllerProvider.notifier)
|
.read(tasksControllerProvider.notifier)
|
||||||
.updateUrl(task!.id, url, headers: task.requestHeaders);
|
.updateUrl(task.id, url, headers: task.requestHeaders);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (context.mounted) {
|
if (context.mounted) {
|
||||||
showAppToast(context, error.toString(), type: AppToastType.error);
|
showAppToast(context, error.toString(), type: AppToastType.error);
|
||||||
|
|||||||
@@ -20,13 +20,8 @@ class TaskFilesPage extends ConsumerWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context, WidgetRef ref) {
|
Widget build(BuildContext context, WidgetRef ref) {
|
||||||
final tasksAsync = ref.watch(tasksControllerProvider);
|
final tasksAsync = ref.watch(tasksControllerProvider);
|
||||||
TaskRecord? task = initialTask;
|
final state = tasksAsync.value;
|
||||||
for (final item in tasksAsync.value?.tasks ?? const <TaskRecord>[]) {
|
final task = state == null ? initialTask : state.findTask(taskId);
|
||||||
if (item.id == taskId) {
|
|
||||||
task = item;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final palette = AppPalette.of(context);
|
final palette = AppPalette.of(context);
|
||||||
|
|
||||||
return shad.Scaffold(
|
return shad.Scaffold(
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class CreateTaskActionButtons extends StatelessWidget {
|
|||||||
|
|
||||||
final bool submitting;
|
final bool submitting;
|
||||||
final VoidCallback onCancel;
|
final VoidCallback onCancel;
|
||||||
final VoidCallback onSubmit;
|
final VoidCallback? onSubmit;
|
||||||
final String cancelLabel;
|
final String cancelLabel;
|
||||||
final String submitLabel;
|
final String submitLabel;
|
||||||
final Key? cancelButtonKey;
|
final Key? cancelButtonKey;
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
||||||
|
import 'package:flutter/widgets.dart' as flutter show Flexible;
|
||||||
|
|
||||||
|
import '../../../../core/capabilities/gopeed_capability.dart';
|
||||||
|
import '../../../../l10n/l10n.dart';
|
||||||
|
import '../../../../shared/theme/app_palette.dart';
|
||||||
|
import '../../../../shared/widgets/app_tooltip.dart';
|
||||||
|
import '../../application/pending_download.dart';
|
||||||
|
import 'create_task_action_buttons.dart';
|
||||||
|
import 'resolve_file_tree.dart';
|
||||||
|
|
||||||
|
Future<bool> showResolveDownloadsDialog(
|
||||||
|
BuildContext context, {
|
||||||
|
required List<PendingDownload> sources,
|
||||||
|
required GopeedService service,
|
||||||
|
ValueChanged<List<PendingDownload>>? onBatchCreated,
|
||||||
|
}) async {
|
||||||
|
final dialog = const DialogOverlayHandler().show<bool>(
|
||||||
|
context: context,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
barrierDismissable: false,
|
||||||
|
builder: (_) => _ResolveDownloadsDialog(sources: sources, service: service, onBatchCreated: onBatchCreated),
|
||||||
|
);
|
||||||
|
return await dialog.future == true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ResolveDownloadsDialog extends StatefulWidget {
|
||||||
|
const _ResolveDownloadsDialog({required this.sources, required this.service, required this.onBatchCreated});
|
||||||
|
|
||||||
|
final List<PendingDownload> sources;
|
||||||
|
final GopeedService service;
|
||||||
|
final ValueChanged<List<PendingDownload>>? onBatchCreated;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_ResolveDownloadsDialog> createState() => _ResolveDownloadsDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ResolveDownloadsDialogState extends State<_ResolveDownloadsDialog> {
|
||||||
|
bool _cancelled = false;
|
||||||
|
bool _submitting = false;
|
||||||
|
String? _errorText;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) => _resolveAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_cancelled = true;
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _resolveAll() async {
|
||||||
|
for (final source in widget.sources) {
|
||||||
|
if (_cancelled || !mounted) return;
|
||||||
|
if (source.result != null || source.resolveError != null) continue;
|
||||||
|
final resolving = source.resolve(widget.service);
|
||||||
|
setState(() {});
|
||||||
|
await resolving;
|
||||||
|
if (_cancelled || !mounted) return;
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _cancel() {
|
||||||
|
_cancelled = true;
|
||||||
|
closeOverlay(context, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _submit() async {
|
||||||
|
if (_submitting || widget.sources.any((source) => source.loading)) return;
|
||||||
|
final batches = planDownloads(widget.sources);
|
||||||
|
if (batches.isEmpty) return;
|
||||||
|
setState(() {
|
||||||
|
_submitting = true;
|
||||||
|
_errorText = null;
|
||||||
|
for (final source in widget.sources) {
|
||||||
|
source.createError = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (final batch in batches) {
|
||||||
|
await batch.submit(widget.service);
|
||||||
|
if (!mounted) return;
|
||||||
|
if (batch.sources.every((source) => source.created)) {
|
||||||
|
widget.onBatchCreated?.call(batch.sources);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final errors = widget.sources.map((source) => source.createError).whereType<String>().toSet();
|
||||||
|
if (errors.isEmpty) {
|
||||||
|
await closeOverlay(context, true);
|
||||||
|
} else {
|
||||||
|
setState(() {
|
||||||
|
_submitting = false;
|
||||||
|
_errorText = errors.join('\n');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final screen = MediaQuery.sizeOf(context);
|
||||||
|
final canCreate =
|
||||||
|
!_submitting &&
|
||||||
|
!widget.sources.any((source) => source.loading) &&
|
||||||
|
widget.sources.any((source) => source.hasSelection);
|
||||||
|
return AlertDialog(
|
||||||
|
padding: const EdgeInsets.all(18),
|
||||||
|
title: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(child: Text(context.l10n.resolvedFiles)),
|
||||||
|
AppTooltip(
|
||||||
|
message: context.l10n.close,
|
||||||
|
child: GhostButton(
|
||||||
|
key: const ValueKey('resolve-close-button'),
|
||||||
|
onPressed: _submitting ? null : _cancel,
|
||||||
|
child: const Icon(Icons.close, size: 18),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
content: SizedBox(
|
||||||
|
width: screen.width < 760 ? screen.width - 68 : 720,
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
height: (screen.height * 0.48).clamp(120.0, 440.0),
|
||||||
|
child: IgnorePointer(
|
||||||
|
ignoring: _submitting,
|
||||||
|
child: ResolveFileTree(
|
||||||
|
sources: List.of(widget.sources),
|
||||||
|
onSelectionChanged: (selection) {
|
||||||
|
final selectedBySource = <String, List<int>>{};
|
||||||
|
for (final (sourceId, index) in selection) {
|
||||||
|
selectedBySource.putIfAbsent(sourceId, () => []).add(index);
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
for (final source in widget.sources) {
|
||||||
|
if (source.result == null || source.created) continue;
|
||||||
|
source.selected
|
||||||
|
..clear()
|
||||||
|
..addAll(selectedBySource[source.id] ?? const []);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_errorText != null)
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: BoxConstraints(maxHeight: screen.height * 0.15),
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Text(_errorText!, style: TextStyle(color: AppPalette.of(context).error, fontSize: 12)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
flutter.Flexible(
|
||||||
|
child: CreateTaskActionButtons(
|
||||||
|
submitting: _submitting,
|
||||||
|
onCancel: _cancel,
|
||||||
|
onSubmit: canCreate ? _submit : null,
|
||||||
|
cancelLabel: context.l10n.cancel,
|
||||||
|
submitLabel: context.l10n.createAction,
|
||||||
|
cancelButtonKey: const ValueKey('resolve-cancel-button'),
|
||||||
|
submitButtonKey: const ValueKey('resolve-create-button'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,99 +2,150 @@ import 'package:flutter/widgets.dart';
|
|||||||
import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
|
import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
|
||||||
|
|
||||||
import '../../../../api/model/resource.dart';
|
import '../../../../api/model/resource.dart';
|
||||||
|
import '../../../../core/icons/gopeed_icons.dart';
|
||||||
|
import '../../../../shared/widgets/app_tooltip.dart';
|
||||||
|
import '../../application/pending_download.dart';
|
||||||
import '../../../../l10n/l10n.dart';
|
import '../../../../l10n/l10n.dart';
|
||||||
import '../../../../shared/theme/app_design_tokens.dart';
|
import '../../../../shared/theme/app_design_tokens.dart';
|
||||||
import '../../../../shared/theme/app_palette.dart';
|
import '../../../../shared/theme/app_palette.dart';
|
||||||
import '../../../../shared/widgets/file_tree_view.dart';
|
import '../../../../shared/widgets/file_tree_view.dart';
|
||||||
import '../../../../util/util.dart';
|
import '../../../../util/util.dart';
|
||||||
|
|
||||||
class ResolveFileTree extends StatefulWidget {
|
typedef PendingFileKey = (String, int);
|
||||||
const ResolveFileTree({
|
|
||||||
super.key,
|
|
||||||
required this.files,
|
|
||||||
required this.initialSelection,
|
|
||||||
required this.onSelectionChanged,
|
|
||||||
});
|
|
||||||
|
|
||||||
final List<FileInfo> files;
|
class ResolveFileTree extends StatefulWidget {
|
||||||
final List<int> initialSelection;
|
const ResolveFileTree({super.key, required this.sources, required this.onSelectionChanged});
|
||||||
final ValueChanged<List<int>> onSelectionChanged;
|
|
||||||
|
final List<PendingDownload> sources;
|
||||||
|
final ValueChanged<Set<PendingFileKey>> onSelectionChanged;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<ResolveFileTree> createState() => _ResolveFileTreeState();
|
State<ResolveFileTree> createState() => _ResolveFileTreeState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _ResolveFileTreeState extends State<ResolveFileTree> {
|
class _ResolveFileTreeState extends State<ResolveFileTree> {
|
||||||
late List<FileTreeItem<int>> _treeItems;
|
late List<FileTreeItem<PendingFileKey>> _treeItems;
|
||||||
late List<int> _allFileIndexes;
|
late Map<PendingFileKey, FileInfo> _files;
|
||||||
late final Set<int> _selectedIndexes;
|
late Map<String, String> _labels;
|
||||||
|
late Map<String, PendingDownload> _sourcesById;
|
||||||
|
late Map<String, PendingDownload> _sourcesByRootKey;
|
||||||
|
final Set<PendingFileKey> _selected = {};
|
||||||
final Set<_FileTypeFilter> _activeTypeFilters = {};
|
final Set<_FileTypeFilter> _activeTypeFilters = {};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_selectedIndexes = widget.initialSelection.where(_isValidIndex).toSet();
|
|
||||||
_rebuildTreeItems();
|
_rebuildTreeItems();
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _notifySelection());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didUpdateWidget(covariant ResolveFileTree oldWidget) {
|
void didUpdateWidget(covariant ResolveFileTree oldWidget) {
|
||||||
super.didUpdateWidget(oldWidget);
|
super.didUpdateWidget(oldWidget);
|
||||||
if (identical(widget.files, oldWidget.files)) return;
|
final previousFiles = _files;
|
||||||
_selectedIndexes.removeWhere((index) => !_isValidIndex(index));
|
|
||||||
_activeTypeFilters.clear();
|
|
||||||
_rebuildTreeItems();
|
_rebuildTreeItems();
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _notifySelection());
|
if (previousFiles.length != _files.length || !previousFiles.keys.every(_files.containsKey)) {
|
||||||
|
_activeTypeFilters.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _rebuildTreeItems() {
|
||||||
|
_files = {};
|
||||||
|
_labels = {};
|
||||||
|
_treeItems = [];
|
||||||
|
_sourcesById = {for (final source in widget.sources) source.id: source};
|
||||||
|
_sourcesByRootKey = {for (final source in widget.sources) 'folder:${source.id}': source};
|
||||||
|
_selected.clear();
|
||||||
|
for (final source in widget.sources) {
|
||||||
|
if (source.result == null) {
|
||||||
|
_labels[source.id] = source.name;
|
||||||
|
_treeItems.add(
|
||||||
|
FileTreeItem(
|
||||||
|
key: source.id,
|
||||||
|
path: source.id,
|
||||||
|
name: source.name,
|
||||||
|
size: 0,
|
||||||
|
data: (source.id, -1),
|
||||||
|
directoryOnly: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final files = source.files.isEmpty ? [FileInfo(name: source.name)] : source.files;
|
||||||
|
// A non-empty resource name is a real directory, even for one file.
|
||||||
|
final hasRoot = source.result!.res.name.trim().isNotEmpty;
|
||||||
|
if (hasRoot) _labels[source.id] = source.name;
|
||||||
|
for (final entry in files.indexed) {
|
||||||
|
final key = (source.id, entry.$1);
|
||||||
|
final file = entry.$2;
|
||||||
|
if (!source.created) {
|
||||||
|
_files[key] = file;
|
||||||
|
if (source.selected.contains(entry.$1)) _selected.add(key);
|
||||||
|
}
|
||||||
|
_treeItems.add(
|
||||||
|
FileTreeItem<PendingFileKey>(
|
||||||
|
key: '${source.id}:${entry.$1}',
|
||||||
|
path: hasRoot ? '${source.id}/${file.path}' : file.path,
|
||||||
|
namespace: hasRoot ? '' : source.id,
|
||||||
|
name: file.name,
|
||||||
|
size: file.size,
|
||||||
|
data: key,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final selectedCount = _selectedIndexes.length;
|
final allSelected = _files.isNotEmpty && _selected.length == _files.length;
|
||||||
final allSelected = _allFileIndexes.isNotEmpty && selectedCount == _allFileIndexes.length;
|
final partial = _selected.isNotEmpty && !allSelected;
|
||||||
final partiallySelected = selectedCount > 0 && !allSelected;
|
|
||||||
final selectedSize = _selectedIndexes.fold<int>(0, (sum, index) => sum + widget.files[index].size);
|
|
||||||
|
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: FileTreeView<int>(
|
child: FileTreeView<PendingFileKey>(
|
||||||
items: _treeItems,
|
items: _treeItems,
|
||||||
initialExpandedDepth: 1,
|
directoryLabels: _labels,
|
||||||
|
initialExpandedDepth: 2,
|
||||||
keyPrefix: 'resolve-tree',
|
keyPrefix: 'resolve-tree',
|
||||||
|
iconWidgetBuilder: _sourceIcon,
|
||||||
rowHeight: _resolveTreeRowHeight,
|
rowHeight: _resolveTreeRowHeight,
|
||||||
contentTextStyle: _resolveFileNameStyle,
|
contentTextStyle: _resolveFileNameStyle,
|
||||||
headerLeading: ExcludeFocus(
|
headerLeading: ExcludeFocus(
|
||||||
child: Checkbox(
|
child: Checkbox(
|
||||||
state: allSelected
|
state: allSelected
|
||||||
? CheckboxState.checked
|
? CheckboxState.checked
|
||||||
: (partiallySelected ? CheckboxState.indeterminate : CheckboxState.unchecked),
|
: partial
|
||||||
onChanged: _allFileIndexes.isEmpty ? null : (_) => _setFileSelection(_allFileIndexes, !allSelected),
|
? CheckboxState.indeterminate
|
||||||
|
: CheckboxState.unchecked,
|
||||||
|
onChanged: _files.isEmpty ? null : (_) => _setSelection(_files.keys, !allSelected),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
leadingBuilder: (context, node) {
|
leadingBuilder: (context, node) {
|
||||||
final indexes = node.leafItems.map((item) => item.data).toList(growable: false);
|
final keys = node.leafItems.map((item) => item.data).where(_files.containsKey).toList();
|
||||||
final nodeSelectedCount = indexes.where(_selectedIndexes.contains).length;
|
final count = keys.where(_selected.contains).length;
|
||||||
final selected = indexes.isNotEmpty && nodeSelectedCount == indexes.length;
|
|
||||||
final partial = nodeSelectedCount > 0 && !selected;
|
|
||||||
return ExcludeFocus(
|
return ExcludeFocus(
|
||||||
child: Checkbox(
|
child: Checkbox(
|
||||||
state: selected
|
state: keys.isNotEmpty && count == keys.length
|
||||||
? CheckboxState.checked
|
? CheckboxState.checked
|
||||||
: (partial ? CheckboxState.indeterminate : CheckboxState.unchecked),
|
: count > 0
|
||||||
onChanged: (_) => _setFileSelection(indexes, !selected),
|
? CheckboxState.indeterminate
|
||||||
|
: CheckboxState.unchecked,
|
||||||
|
onChanged: keys.isEmpty ? null : (_) => _setSelection(keys, count != keys.length),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
onNodePressed: _toggleNodeSelection,
|
onNodePressed: (node) {
|
||||||
|
final keys = node.leafItems.map((item) => item.data).where(_files.containsKey).toList();
|
||||||
|
if (keys.isNotEmpty) _setSelection(keys, !keys.every(_selected.contains));
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
_TreeFooter(
|
_TreeFooter(
|
||||||
selectedCount: selectedCount,
|
selectedCount: _selected.length,
|
||||||
totalCount: _allFileIndexes.length,
|
totalCount: _files.length,
|
||||||
selectedSize: selectedSize,
|
selectedSize: _selected.fold(0, (sum, key) => sum + _files[key]!.size),
|
||||||
unknownSize: selectedCount > 0 && selectedSize == 0,
|
unknownSize: _selected.any((key) => _files[key]!.size <= 0),
|
||||||
activeTypeFilters: _activeTypeFilters,
|
activeTypeFilters: _activeTypeFilters,
|
||||||
onSelectVideo: () => _toggleTypeFilter(_FileTypeFilter.video),
|
onSelectVideo: () => _toggleTypeFilter(_FileTypeFilter.video),
|
||||||
onSelectAudio: () => _toggleTypeFilter(_FileTypeFilter.audio),
|
onSelectAudio: () => _toggleTypeFilter(_FileTypeFilter.audio),
|
||||||
@@ -104,65 +155,63 @@ class _ResolveFileTreeState extends State<ResolveFileTree> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _isValidIndex(int index) => index >= 0 && index < widget.files.length;
|
Widget _sourceIcon(BuildContext context, FileTreeNode<PendingFileKey> node) {
|
||||||
|
final source = node.item == null ? _sourcesByRootKey[node.key] : _sourcesById[node.item!.data.$1];
|
||||||
void _rebuildTreeItems() {
|
final palette = AppPalette.of(context);
|
||||||
_allFileIndexes = List<int>.generate(widget.files.length, (index) => index, growable: false);
|
if (source == null) {
|
||||||
_treeItems = widget.files
|
return Icon(node.isFolder ? BootstrapIcons.folder2 : GopeedIcons.file, size: 18, color: palette.textSecondary);
|
||||||
.asMap()
|
}
|
||||||
.entries
|
final pending = source;
|
||||||
.map(
|
final message = pending.loading
|
||||||
(entry) => FileTreeItem<int>(
|
? (pending.resolving ? context.l10n.resolvingResource : context.l10n.waitingToResolve)
|
||||||
key: entry.key.toString(),
|
: pending.resolveError ?? pending.request.url;
|
||||||
path: entry.value.path,
|
return AppTooltip(
|
||||||
name: entry.value.name,
|
focusable: true,
|
||||||
size: entry.value.size,
|
message: message,
|
||||||
data: entry.key,
|
child: Semantics(
|
||||||
),
|
label: message,
|
||||||
)
|
child: pending.loading
|
||||||
.toList(growable: false);
|
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator())
|
||||||
|
: Icon(
|
||||||
|
pending.resolveError != null
|
||||||
|
? Icons.error_outline
|
||||||
|
: node.isFolder && pending.isBt
|
||||||
|
? GopeedIcons.folderBt
|
||||||
|
: node.isFolder
|
||||||
|
? BootstrapIcons.folder2
|
||||||
|
: GopeedIcons.file,
|
||||||
|
size: 18,
|
||||||
|
color: pending.resolveError != null ? palette.error : palette.textSecondary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _setFileSelection(Iterable<int> indexes, bool selected) {
|
void _setSelection(Iterable<PendingFileKey> keys, bool selected) {
|
||||||
setState(() {
|
setState(() {
|
||||||
_activeTypeFilters.clear();
|
_activeTypeFilters.clear();
|
||||||
if (selected) {
|
if (selected) {
|
||||||
_selectedIndexes.addAll(indexes);
|
_selected.addAll(keys);
|
||||||
} else {
|
} else {
|
||||||
_selectedIndexes.removeAll(indexes);
|
_selected.removeAll(keys);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
_notifySelection();
|
widget.onSelectionChanged(Set.of(_selected));
|
||||||
}
|
|
||||||
|
|
||||||
void _toggleNodeSelection(FileTreeNode<int> node) {
|
|
||||||
final indexes = node.leafItems.map((item) => item.data).toList(growable: false);
|
|
||||||
final selected = indexes.isNotEmpty && indexes.every(_selectedIndexes.contains);
|
|
||||||
_setFileSelection(indexes, !selected);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void _toggleTypeFilter(_FileTypeFilter filter) {
|
void _toggleTypeFilter(_FileTypeFilter filter) {
|
||||||
setState(() {
|
setState(() {
|
||||||
if (!_activeTypeFilters.remove(filter)) {
|
if (!_activeTypeFilters.remove(filter)) _activeTypeFilters.add(filter);
|
||||||
_activeTypeFilters.add(filter);
|
final extensions = {for (final active in _activeTypeFilters) ...active.extensions};
|
||||||
}
|
_selected
|
||||||
final extensions = <String>{for (final activeFilter in _activeTypeFilters) ...activeFilter.extensions};
|
|
||||||
_selectedIndexes
|
|
||||||
..clear()
|
..clear()
|
||||||
..addAll(
|
..addAll(
|
||||||
widget.files
|
_files.entries
|
||||||
.asMap()
|
|
||||||
.entries
|
|
||||||
.where((entry) => extensions.contains(_extensionOf(entry.value.name)))
|
.where((entry) => extensions.contains(_extensionOf(entry.value.name)))
|
||||||
.map((entry) => entry.key),
|
.map((entry) => entry.key),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
_notifySelection();
|
widget.onSelectionChanged(Set.of(_selected));
|
||||||
}
|
|
||||||
|
|
||||||
void _notifySelection() {
|
|
||||||
final values = _selectedIndexes.toList()..sort();
|
|
||||||
widget.onSelectionChanged(values);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
import '../../../../../core/utils/breakpoints.dart';
|
import '../../../../../core/utils/breakpoints.dart';
|
||||||
|
import '../../../../../shared/theme/app_design_tokens.dart';
|
||||||
import '../../../domain/task_record.dart';
|
import '../../../domain/task_record.dart';
|
||||||
import '../task_context_menu.dart';
|
import '../task_context_menu.dart';
|
||||||
import 'task_card_desktop.dart';
|
import 'task_card_desktop.dart';
|
||||||
@@ -10,6 +11,8 @@ class TaskCard extends StatelessWidget {
|
|||||||
const TaskCard({
|
const TaskCard({
|
||||||
super.key,
|
super.key,
|
||||||
required this.task,
|
required this.task,
|
||||||
|
this.expanded = false,
|
||||||
|
this.nested = false,
|
||||||
required this.selected,
|
required this.selected,
|
||||||
required this.batchMode,
|
required this.batchMode,
|
||||||
required this.selectedInBatch,
|
required this.selectedInBatch,
|
||||||
@@ -25,6 +28,8 @@ class TaskCard extends StatelessWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
final TaskRecord task;
|
final TaskRecord task;
|
||||||
|
final bool expanded;
|
||||||
|
final bool nested;
|
||||||
final bool selected;
|
final bool selected;
|
||||||
final bool batchMode;
|
final bool batchMode;
|
||||||
final bool selectedInBatch;
|
final bool selectedInBatch;
|
||||||
@@ -42,40 +47,44 @@ class TaskCard extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final isMobile = MediaQuery.sizeOf(context).width < Breakpoints.mobile;
|
final isMobile = MediaQuery.sizeOf(context).width < Breakpoints.mobile;
|
||||||
|
|
||||||
if (isMobile) {
|
final card = isMobile
|
||||||
final card = TaskCardMobile(
|
? TaskCardMobile(
|
||||||
task: task,
|
task: task,
|
||||||
selected: selected,
|
expanded: expanded,
|
||||||
batchMode: batchMode,
|
selected: selected,
|
||||||
selectedInBatch: selectedInBatch,
|
batchMode: batchMode,
|
||||||
onPressed: onPressed,
|
selectedInBatch: selectedInBatch,
|
||||||
onToggleBatch: onToggleBatch,
|
onPressed: onPressed,
|
||||||
onPause: onPause,
|
onToggleBatch: onToggleBatch,
|
||||||
onResume: onResume,
|
onPause: task.canPause ? onPause : null,
|
||||||
onDelete: onDelete,
|
onResume: task.canResume ? onResume : null,
|
||||||
onOpen: onOpen,
|
onDelete: onDelete,
|
||||||
onReveal: onReveal,
|
onOpen: onOpen,
|
||||||
listeningForUpdate: listeningForUpdate,
|
onReveal: onReveal,
|
||||||
);
|
listeningForUpdate: listeningForUpdate,
|
||||||
final actions = contextActions;
|
)
|
||||||
return actions == null ? card : TaskContextMenu(task: task, actions: actions, child: card);
|
: TaskCardDesktop(
|
||||||
}
|
task: task,
|
||||||
|
expanded: expanded,
|
||||||
final card = TaskCardDesktop(
|
selected: selected,
|
||||||
task: task,
|
batchMode: batchMode,
|
||||||
selected: selected,
|
selectedInBatch: selectedInBatch,
|
||||||
batchMode: batchMode,
|
onPressed: onPressed,
|
||||||
selectedInBatch: selectedInBatch,
|
onToggleBatch: onToggleBatch,
|
||||||
onPressed: onPressed,
|
onPause: task.canPause ? onPause : null,
|
||||||
onToggleBatch: onToggleBatch,
|
onResume: task.canResume ? onResume : null,
|
||||||
onPause: onPause,
|
onDelete: onDelete,
|
||||||
onResume: onResume,
|
onOpen: onOpen,
|
||||||
onDelete: onDelete,
|
onReveal: onReveal,
|
||||||
onOpen: onOpen,
|
listeningForUpdate: listeningForUpdate,
|
||||||
onReveal: onReveal,
|
);
|
||||||
listeningForUpdate: listeningForUpdate,
|
|
||||||
);
|
|
||||||
final actions = contextActions;
|
final actions = contextActions;
|
||||||
return actions == null ? card : TaskContextMenu(task: task, actions: actions, child: card);
|
return Padding(
|
||||||
|
padding: EdgeInsetsDirectional.only(start: nested ? AppDesignTokens.space24 : 0),
|
||||||
|
child: Semantics(
|
||||||
|
expanded: task.isGroup ? expanded : null,
|
||||||
|
child: actions == null ? card : TaskContextMenu(task: task, actions: actions, child: card),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+19
-11
@@ -14,6 +14,7 @@ class TaskCardDesktop extends StatefulWidget {
|
|||||||
const TaskCardDesktop({
|
const TaskCardDesktop({
|
||||||
super.key,
|
super.key,
|
||||||
required this.task,
|
required this.task,
|
||||||
|
this.expanded = false,
|
||||||
required this.selected,
|
required this.selected,
|
||||||
required this.batchMode,
|
required this.batchMode,
|
||||||
required this.selectedInBatch,
|
required this.selectedInBatch,
|
||||||
@@ -28,6 +29,7 @@ class TaskCardDesktop extends StatefulWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
final TaskRecord task;
|
final TaskRecord task;
|
||||||
|
final bool expanded;
|
||||||
final bool selected;
|
final bool selected;
|
||||||
final bool batchMode;
|
final bool batchMode;
|
||||||
final bool selectedInBatch;
|
final bool selectedInBatch;
|
||||||
@@ -64,7 +66,7 @@ class _TaskCardDesktopState extends State<TaskCardDesktop> {
|
|||||||
_lastTapTime = isDoubleTap ? null : now;
|
_lastTapTime = isDoubleTap ? null : now;
|
||||||
_lastTapPosition = isDoubleTap ? null : details.globalPosition;
|
_lastTapPosition = isDoubleTap ? null : details.globalPosition;
|
||||||
widget.onPressed();
|
widget.onPressed();
|
||||||
if (isDoubleTap) {
|
if (isDoubleTap && !widget.task.isGroup) {
|
||||||
widget.onOpen?.call();
|
widget.onOpen?.call();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -134,7 +136,7 @@ class _TaskCardDesktopState extends State<TaskCardDesktop> {
|
|||||||
)
|
)
|
||||||
: const SizedBox.shrink(),
|
: const SizedBox.shrink(),
|
||||||
),
|
),
|
||||||
TaskCardIcon(task: task),
|
TaskCardIcon(task: task, expanded: widget.expanded),
|
||||||
const SizedBox(width: 16),
|
const SizedBox(width: 16),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
@@ -234,15 +236,21 @@ class _ProgressContent extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
|
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
|
||||||
final actions = switch (task.status) {
|
final actions = task.isGroup && task.status != TaskStatus.completed
|
||||||
TaskStatus.downloading => [(Icons.pause, onPause), (Icons.close, onDelete)],
|
? [
|
||||||
TaskStatus.paused => [(Icons.play_arrow, onResume), (Icons.close, onDelete)],
|
if (task.canPause) (Icons.pause, onPause),
|
||||||
TaskStatus.failed => [(Icons.refresh, onResume), (Icons.delete_outline, onDelete)],
|
if (task.canResume) (Icons.play_arrow, onResume),
|
||||||
TaskStatus.completed => [
|
(Icons.close, onDelete),
|
||||||
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, null),
|
]
|
||||||
(Icons.delete_outline, onDelete),
|
: switch (task.status) {
|
||||||
],
|
TaskStatus.downloading => [(Icons.pause, onPause), (Icons.close, onDelete)],
|
||||||
};
|
TaskStatus.paused => [(Icons.play_arrow, onResume), (Icons.close, onDelete)],
|
||||||
|
TaskStatus.failed => [(Icons.refresh, onResume), (Icons.delete_outline, onDelete)],
|
||||||
|
TaskStatus.completed => [
|
||||||
|
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, null),
|
||||||
|
(Icons.delete_outline, onDelete),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
return actions
|
return actions
|
||||||
.map(
|
.map(
|
||||||
|
|||||||
+19
-11
@@ -13,6 +13,7 @@ class TaskCardMobile extends StatefulWidget {
|
|||||||
const TaskCardMobile({
|
const TaskCardMobile({
|
||||||
super.key,
|
super.key,
|
||||||
required this.task,
|
required this.task,
|
||||||
|
this.expanded = false,
|
||||||
required this.selected,
|
required this.selected,
|
||||||
required this.batchMode,
|
required this.batchMode,
|
||||||
required this.selectedInBatch,
|
required this.selectedInBatch,
|
||||||
@@ -27,6 +28,7 @@ class TaskCardMobile extends StatefulWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
final TaskRecord task;
|
final TaskRecord task;
|
||||||
|
final bool expanded;
|
||||||
final bool selected;
|
final bool selected;
|
||||||
final bool batchMode;
|
final bool batchMode;
|
||||||
final bool selectedInBatch;
|
final bool selectedInBatch;
|
||||||
@@ -62,7 +64,7 @@ class _TaskCardMobileState extends State<TaskCardMobile> {
|
|||||||
onExit: (_) => setState(() => _hovered = false),
|
onExit: (_) => setState(() => _hovered = false),
|
||||||
child: GestureDetector(
|
child: GestureDetector(
|
||||||
onTap: widget.onPressed,
|
onTap: widget.onPressed,
|
||||||
onDoubleTap: !widget.batchMode && task.status == TaskStatus.completed ? widget.onOpen : null,
|
onDoubleTap: !widget.batchMode && !task.isGroup && task.status == TaskStatus.completed ? widget.onOpen : null,
|
||||||
child: Container(
|
child: Container(
|
||||||
key: const ValueKey('task-card-mobile-surface'),
|
key: const ValueKey('task-card-mobile-surface'),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@@ -117,7 +119,7 @@ class _TaskCardMobileState extends State<TaskCardMobile> {
|
|||||||
)
|
)
|
||||||
: const SizedBox.shrink(),
|
: const SizedBox.shrink(),
|
||||||
),
|
),
|
||||||
TaskCardIcon(task: task),
|
TaskCardIcon(task: task, expanded: widget.expanded),
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 12),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
@@ -168,15 +170,21 @@ class _TaskCardMobileState extends State<TaskCardMobile> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
|
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
|
||||||
final actions = switch (task.status) {
|
final actions = task.isGroup && task.status != TaskStatus.completed
|
||||||
TaskStatus.downloading => [(Icons.pause, widget.onPause), (Icons.close, widget.onDelete)],
|
? [
|
||||||
TaskStatus.paused => [(Icons.play_arrow, widget.onResume), (Icons.close, widget.onDelete)],
|
if (task.canPause) (Icons.pause, widget.onPause),
|
||||||
TaskStatus.failed => [(Icons.refresh, widget.onResume), (Icons.delete_outline, widget.onDelete)],
|
if (task.canResume) (Icons.play_arrow, widget.onResume),
|
||||||
TaskStatus.completed => [
|
(Icons.close, widget.onDelete),
|
||||||
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, widget.onReveal),
|
]
|
||||||
(Icons.delete_outline, widget.onDelete),
|
: switch (task.status) {
|
||||||
],
|
TaskStatus.downloading => [(Icons.pause, widget.onPause), (Icons.close, widget.onDelete)],
|
||||||
};
|
TaskStatus.paused => [(Icons.play_arrow, widget.onResume), (Icons.close, widget.onDelete)],
|
||||||
|
TaskStatus.failed => [(Icons.refresh, widget.onResume), (Icons.delete_outline, widget.onDelete)],
|
||||||
|
TaskStatus.completed => [
|
||||||
|
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, widget.onReveal),
|
||||||
|
(Icons.delete_outline, widget.onDelete),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
return actions
|
return actions
|
||||||
.map(
|
.map(
|
||||||
|
|||||||
@@ -46,25 +46,35 @@ class TaskUpdateListeningIndicator extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class TaskCardIcon extends StatelessWidget {
|
class TaskCardIcon extends StatelessWidget {
|
||||||
const TaskCardIcon({super.key, required this.task});
|
const TaskCardIcon({super.key, required this.task, this.expanded = false});
|
||||||
|
|
||||||
final TaskRecord task;
|
final TaskRecord task;
|
||||||
|
final bool expanded;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final palette = AppPalette.of(context);
|
final palette = AppPalette.of(context);
|
||||||
|
|
||||||
return SizedBox(
|
return Row(
|
||||||
width: 32,
|
mainAxisSize: MainAxisSize.min,
|
||||||
height: 32,
|
children: [
|
||||||
child: ClipRRect(
|
if (task.isGroup) ...[
|
||||||
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
|
Icon(expanded ? Icons.expand_more : Icons.chevron_right, size: 18, color: palette.textSecondary),
|
||||||
clipBehavior: Clip.hardEdge,
|
const SizedBox(width: AppDesignTokens.space4),
|
||||||
child: ColoredBox(
|
],
|
||||||
color: palette.taskCardIconBg,
|
SizedBox(
|
||||||
child: Center(child: Icon(task.icon, size: 20, color: palette.textSecondary)),
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
|
||||||
|
clipBehavior: Clip.hardEdge,
|
||||||
|
child: ColoredBox(
|
||||||
|
color: palette.taskCardIconBg,
|
||||||
|
child: Center(child: Icon(task.icon, size: 20, color: palette.textSecondary)),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,14 +69,14 @@ class TaskContextMenu extends StatelessWidget {
|
|||||||
shad.MenuButton(
|
shad.MenuButton(
|
||||||
key: const ValueKey('task-context-resume'),
|
key: const ValueKey('task-context-resume'),
|
||||||
leading: const Icon(Icons.play_arrow, size: 16),
|
leading: const Icon(Icons.play_arrow, size: 16),
|
||||||
enabled: task.status == TaskStatus.paused || task.status == TaskStatus.failed,
|
enabled: task.canResume,
|
||||||
onPressed: (_) => actions.onResume(),
|
onPressed: (_) => actions.onResume(),
|
||||||
child: Text(context.l10n.continueAction),
|
child: Text(context.l10n.continueAction),
|
||||||
),
|
),
|
||||||
shad.MenuButton(
|
shad.MenuButton(
|
||||||
key: const ValueKey('task-context-pause'),
|
key: const ValueKey('task-context-pause'),
|
||||||
leading: const Icon(Icons.pause, size: 16),
|
leading: const Icon(Icons.pause, size: 16),
|
||||||
enabled: task.status == TaskStatus.downloading,
|
enabled: task.canPause,
|
||||||
onPressed: (_) => actions.onPause(),
|
onPressed: (_) => actions.onPause(),
|
||||||
child: Text(context.l10n.pause),
|
child: Text(context.l10n.pause),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -5,7 +5,13 @@ import '../../../../shared/theme/app_palette.dart';
|
|||||||
import '../../../../shared/theme/app_design_tokens.dart';
|
import '../../../../shared/theme/app_design_tokens.dart';
|
||||||
import '../../../../l10n/l10n.dart';
|
import '../../../../l10n/l10n.dart';
|
||||||
|
|
||||||
Future<bool?> showTaskDeleteDialog(BuildContext context, {required int taskCount, required bool keepFiles}) async {
|
Future<bool?> showTaskDeleteDialog(
|
||||||
|
BuildContext context, {
|
||||||
|
required int taskCount,
|
||||||
|
required bool keepFiles,
|
||||||
|
int? memberCount,
|
||||||
|
int? fileCount,
|
||||||
|
}) async {
|
||||||
var currentKeepFiles = keepFiles;
|
var currentKeepFiles = keepFiles;
|
||||||
final dialog = const DialogOverlayHandler().show<bool>(
|
final dialog = const DialogOverlayHandler().show<bool>(
|
||||||
context: context,
|
context: context,
|
||||||
@@ -32,34 +38,46 @@ Future<bool?> showTaskDeleteDialog(BuildContext context, {required int taskCount
|
|||||||
title: Text(dialogContext.l10n.deleteTasksTitle(taskCount)),
|
title: Text(dialogContext.l10n.deleteTasksTitle(taskCount)),
|
||||||
content: SizedBox(
|
content: SizedBox(
|
||||||
width: contentWidth,
|
width: contentWidth,
|
||||||
child: AnimatedContainer(
|
child: Column(
|
||||||
key: const ValueKey('task-delete-keep-files-option'),
|
mainAxisSize: MainAxisSize.min,
|
||||||
duration: const Duration(milliseconds: 160),
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
padding: const EdgeInsets.symmetric(
|
children: [
|
||||||
horizontal: AppDesignTokens.space16,
|
if (memberCount != null) ...[
|
||||||
vertical: AppDesignTokens.space12,
|
Text(dialogContext.l10n.taskGroupDeleteImpact(memberCount, fileCount ?? 0)),
|
||||||
),
|
const SizedBox(height: AppDesignTokens.space16),
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: currentKeepFiles ? palette.brandSoft : palette.surfaceSoft,
|
|
||||||
border: Border.all(color: currentKeepFiles ? palette.brand.withValues(alpha: 0.45) : palette.border),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
dialogContext.l10n.deleteTaskTip,
|
|
||||||
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w500),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: AppDesignTokens.space16),
|
|
||||||
Switch(
|
|
||||||
key: const ValueKey('task-delete-keep-files-switch'),
|
|
||||||
value: currentKeepFiles,
|
|
||||||
onChanged: (value) => setDialogState(() => currentKeepFiles = value),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
AnimatedContainer(
|
||||||
|
key: const ValueKey('task-delete-keep-files-option'),
|
||||||
|
duration: const Duration(milliseconds: 160),
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: AppDesignTokens.space16,
|
||||||
|
vertical: AppDesignTokens.space12,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: currentKeepFiles ? palette.brandSoft : palette.surfaceSoft,
|
||||||
|
border: Border.all(
|
||||||
|
color: currentKeepFiles ? palette.brand.withValues(alpha: 0.45) : palette.border,
|
||||||
|
),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
dialogContext.l10n.deleteTaskTip,
|
||||||
|
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w500),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppDesignTokens.space16),
|
||||||
|
Switch(
|
||||||
|
key: const ValueKey('task-delete-keep-files-switch'),
|
||||||
|
value: currentKeepFiles,
|
||||||
|
onChanged: (value) => setDialogState(() => currentKeepFiles = value),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
|
|||||||
@@ -121,7 +121,9 @@ class _TaskDetailsViewState extends ConsumerState<TaskDetailsView> {
|
|||||||
final contentPadding = widget.mobile
|
final contentPadding = widget.mobile
|
||||||
? AppDesignTokens.taskDetailsMobilePadding
|
? AppDesignTokens.taskDetailsMobilePadding
|
||||||
: AppDesignTokens.taskDetailsDesktopPadding;
|
: AppDesignTokens.taskDetailsDesktopPadding;
|
||||||
final runtimeStatus = _tabIndex == 1 ? ref.watch(taskRuntimeStatusProvider(widget.task.id)).value : null;
|
final runtimeStatus = _tabIndex == 1 && !widget.task.isGroup
|
||||||
|
? ref.watch(taskRuntimeStatusProvider(widget.task.id)).value
|
||||||
|
: null;
|
||||||
final content = Column(
|
final content = Column(
|
||||||
children: [
|
children: [
|
||||||
Container(
|
Container(
|
||||||
@@ -148,12 +150,14 @@ class _TaskDetailsViewState extends ConsumerState<TaskDetailsView> {
|
|||||||
active: _tabIndex == 1,
|
active: _tabIndex == 1,
|
||||||
onTap: () => setState(() => _tabIndex = 1),
|
onTap: () => setState(() => _tabIndex = 1),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 24),
|
if (!widget.task.isGroup) ...[
|
||||||
_DrawerTabButton(
|
const SizedBox(width: 24),
|
||||||
label: context.l10n.taskDetailsStatsTab,
|
_DrawerTabButton(
|
||||||
active: _tabIndex == 2,
|
label: context.l10n.taskDetailsStatsTab,
|
||||||
onTap: () => setState(() => _tabIndex = 2),
|
active: _tabIndex == 2,
|
||||||
),
|
onTap: () => setState(() => _tabIndex = 2),
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -340,7 +344,7 @@ class _TaskInfoTab extends StatelessWidget {
|
|||||||
onCancel: onCancelEditUrl,
|
onCancel: onCancelEditUrl,
|
||||||
onSave: onSaveUrl,
|
onSave: onSaveUrl,
|
||||||
)
|
)
|
||||||
else
|
else if (!task.isGroup)
|
||||||
_CopyableInfoBlock(
|
_CopyableInfoBlock(
|
||||||
label: context.l10n.downloadLink,
|
label: context.l10n.downloadLink,
|
||||||
value: task.url,
|
value: task.url,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:flutter/material.dart' show Icons;
|
import 'package:flutter/material.dart' show Icons;
|
||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
||||||
|
|
||||||
@@ -7,6 +8,7 @@ import '../../../../l10n/l10n.dart';
|
|||||||
import '../../../../shared/widgets/app_tooltip.dart';
|
import '../../../../shared/widgets/app_tooltip.dart';
|
||||||
import '../../../../util/util.dart';
|
import '../../../../util/util.dart';
|
||||||
import '../../domain/task_record.dart';
|
import '../../domain/task_record.dart';
|
||||||
|
import '../../application/tasks_controller.dart';
|
||||||
import 'task_file_manager.dart';
|
import 'task_file_manager.dart';
|
||||||
|
|
||||||
Future<void> browseTaskFiles(BuildContext context, TaskRecord task, {required bool mobile}) async {
|
Future<void> browseTaskFiles(BuildContext context, TaskRecord task, {required bool mobile}) async {
|
||||||
@@ -49,7 +51,16 @@ Future<void> showTaskFileBrowserDialog(BuildContext context, TaskRecord task) as
|
|||||||
content: SizedBox(
|
content: SizedBox(
|
||||||
width: dialogWidth,
|
width: dialogWidth,
|
||||||
height: dialogHeight,
|
height: dialogHeight,
|
||||||
child: TaskFileManagerView(task: task),
|
child: Consumer(
|
||||||
|
builder: (context, ref, _) {
|
||||||
|
final state = ref.watch(tasksControllerProvider).value;
|
||||||
|
final current = state?.findTask(task.id);
|
||||||
|
if (state != null && current == null) {
|
||||||
|
return Center(child: Text(context.l10n.taskNotFound));
|
||||||
|
}
|
||||||
|
return TaskFileManagerView(task: current ?? task);
|
||||||
|
},
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -120,14 +120,19 @@ class _TaskFileManagerViewState extends State<TaskFileManagerView> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String _localPath(_TaskFileEntry entry) {
|
String _localPath(_TaskFileEntry entry) {
|
||||||
|
if (entry.localPath != null) return entry.localPath!;
|
||||||
if (!widget.task.isFolder && _index.fileCount == 1) return widget.task.storagePath;
|
if (!widget.task.isFolder && _index.fileCount == 1) return widget.task.storagePath;
|
||||||
final segments = entry.fullPath.split('/').where((part) => part.isNotEmpty);
|
final segments = entry.fullPath.split('/').where((part) => part.isNotEmpty);
|
||||||
return path.joinAll([widget.task.storagePath, ...segments]);
|
return path.joinAll([widget.task.storagePath, ...segments]);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _accessUrl(_TaskFileEntry entry) {
|
String _accessUrl(_TaskFileEntry entry) {
|
||||||
final encodedPath = entry.fullPath.split('/').where((part) => part.isNotEmpty).map(Uri.encodeComponent).join('/');
|
final encodedPath = (entry.source?.accessPath ?? entry.fullPath)
|
||||||
return api.join('/fs/tasks/${Uri.encodeComponent(widget.task.id)}/$encodedPath');
|
.split('/')
|
||||||
|
.where((part) => part.isNotEmpty)
|
||||||
|
.map(Uri.encodeComponent)
|
||||||
|
.join('/');
|
||||||
|
return api.join('/fs/tasks/${Uri.encodeComponent(entry.source?.taskId ?? widget.task.id)}/$encodedPath');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,7 +309,7 @@ class _FileActionButton extends StatelessWidget {
|
|||||||
|
|
||||||
class _TaskFileDirectoryIndex {
|
class _TaskFileDirectoryIndex {
|
||||||
_TaskFileDirectoryIndex(TaskRecord task) {
|
_TaskFileDirectoryIndex(TaskRecord task) {
|
||||||
final sourceFiles = task.files.isEmpty
|
final sourceFiles = task.files.isEmpty && !task.isGroup
|
||||||
? [TaskFileNode(path: '/', name: task.name, sizeBytes: task.totalBytes ?? 0)]
|
? [TaskFileNode(path: '/', name: task.name, sizeBytes: task.totalBytes ?? 0)]
|
||||||
: task.files;
|
: task.files;
|
||||||
fileCount = sourceFiles.length;
|
fileCount = sourceFiles.length;
|
||||||
@@ -313,8 +318,18 @@ class _TaskFileDirectoryIndex {
|
|||||||
final directory = _normalizeDirectory(file.path);
|
final directory = _normalizeDirectory(file.path);
|
||||||
final name = singleFile ? path.basename(task.storagePath) : file.name;
|
final name = singleFile ? path.basename(task.storagePath) : file.name;
|
||||||
final fullPath = directory == '/' ? '/$name' : '$directory/$name';
|
final fullPath = directory == '/' ? '/$name' : '$directory/$name';
|
||||||
_add(directory, _TaskFileEntry(directory: false, fullPath: fullPath, name: name, size: file.sizeBytes));
|
_add(
|
||||||
_addParentDirectories(directory);
|
directory,
|
||||||
|
_TaskFileEntry(
|
||||||
|
directory: false,
|
||||||
|
fullPath: fullPath,
|
||||||
|
name: name,
|
||||||
|
size: file.sizeBytes,
|
||||||
|
source: file,
|
||||||
|
localPath: file.localPath,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
_addParentDirectories(directory, file.localPath == null ? null : path.dirname(file.localPath!));
|
||||||
}
|
}
|
||||||
for (final entries in _entries.values) {
|
for (final entries in _entries.values) {
|
||||||
entries.sort((left, right) {
|
entries.sort((left, right) {
|
||||||
@@ -331,15 +346,19 @@ class _TaskFileDirectoryIndex {
|
|||||||
|
|
||||||
List<_TaskFileEntry> entries(String directory) => _entries[directory] ?? const [];
|
List<_TaskFileEntry> entries(String directory) => _entries[directory] ?? const [];
|
||||||
|
|
||||||
void _addParentDirectories(String directory) {
|
void _addParentDirectories(String directory, String? localPath) {
|
||||||
var current = directory;
|
var current = directory;
|
||||||
while (current != '/') {
|
while (current != '/') {
|
||||||
final parent = path.posix.dirname(current);
|
final parent = path.posix.dirname(current);
|
||||||
final normalizedParent = parent == '.' ? '/' : parent;
|
final normalizedParent = parent == '.' ? '/' : parent;
|
||||||
final name = path.posix.basename(current);
|
final name = path.posix.basename(current);
|
||||||
_add(normalizedParent, _TaskFileEntry(directory: true, fullPath: current, name: name, size: 0));
|
_add(
|
||||||
|
normalizedParent,
|
||||||
|
_TaskFileEntry(directory: true, fullPath: current, name: name, size: 0, localPath: localPath),
|
||||||
|
);
|
||||||
_entries.putIfAbsent(current, () => []);
|
_entries.putIfAbsent(current, () => []);
|
||||||
current = normalizedParent;
|
current = normalizedParent;
|
||||||
|
if (localPath != null) localPath = path.dirname(localPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,12 +369,21 @@ class _TaskFileDirectoryIndex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _TaskFileEntry {
|
class _TaskFileEntry {
|
||||||
const _TaskFileEntry({required this.directory, required this.fullPath, required this.name, required this.size});
|
const _TaskFileEntry({
|
||||||
|
required this.directory,
|
||||||
|
required this.fullPath,
|
||||||
|
required this.name,
|
||||||
|
required this.size,
|
||||||
|
this.source,
|
||||||
|
this.localPath,
|
||||||
|
});
|
||||||
|
|
||||||
final bool directory;
|
final bool directory;
|
||||||
final String fullPath;
|
final String fullPath;
|
||||||
final String name;
|
final String name;
|
||||||
final int size;
|
final int size;
|
||||||
|
final TaskFileNode? source;
|
||||||
|
final String? localPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
String _normalizeDirectory(String value) {
|
String _normalizeDirectory(String value) {
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ class _TaskFileTreeState extends State<TaskFileTree> {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final progressByIndex = {
|
final progressByIndex = {
|
||||||
for (final file in widget.runtimeStatus?.files ?? const <FileRuntimeStatus>[]) file.index: file,
|
for (final file in widget.runtimeStatus?.files ?? const <FileRuntimeStatus>[]) file.index: file,
|
||||||
|
if (widget.task.isGroup)
|
||||||
|
for (final (index, file) in widget.task.files.indexed)
|
||||||
|
file.resourceIndex ?? index: FileRuntimeStatus(
|
||||||
|
index: file.resourceIndex ?? index,
|
||||||
|
size: file.sizeBytes,
|
||||||
|
downloaded: file.downloadedBytes ?? 0,
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
return Column(
|
return Column(
|
||||||
@@ -179,7 +186,17 @@ class _FileDownloadProgress extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final palette = AppPalette.of(context);
|
final palette = AppPalette.of(context);
|
||||||
final taskStateIcon = switch (taskStatus) {
|
final statuses = node.leafItems.map((item) => item.data.status).whereType<TaskStatus>().toSet();
|
||||||
|
final status = statuses.isEmpty
|
||||||
|
? taskStatus
|
||||||
|
: statuses.contains(TaskStatus.downloading)
|
||||||
|
? TaskStatus.downloading
|
||||||
|
: statuses.contains(TaskStatus.failed)
|
||||||
|
? TaskStatus.failed
|
||||||
|
: statuses.contains(TaskStatus.paused)
|
||||||
|
? TaskStatus.paused
|
||||||
|
: TaskStatus.completed;
|
||||||
|
final taskStateIcon = switch (status) {
|
||||||
TaskStatus.paused => Semantics(
|
TaskStatus.paused => Semantics(
|
||||||
label: context.l10n.pause,
|
label: context.l10n.pause,
|
||||||
child: Icon(Icons.pause_circle_filled, size: 16, color: palette.textMuted),
|
child: Icon(Icons.pause_circle_filled, size: 16, color: palette.textMuted),
|
||||||
|
|||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "بيانات الملف المُتعذّب فارغة",
|
"torrentDataEmpty": "بيانات الملف المُتعذّب فارغة",
|
||||||
"torrentPathUnavailable": "غير قادر على الوصول إلى طريق الملف المُتعذّب",
|
"torrentPathUnavailable": "غير قادر على الوصول إلى طريق الملف المُتعذّب",
|
||||||
"selectAtLeastOneFile": "اختار ملف واحد على الأقل",
|
"selectAtLeastOneFile": "اختار ملف واحد على الأقل",
|
||||||
"resolvedFiles": "الملفات المبتغاة",
|
"resolvedFiles": "قائمة الملفات",
|
||||||
|
"waitingToResolve": "بانتظار التحليل",
|
||||||
|
"resolvingResource": "جارٍ تحليل المورد",
|
||||||
"resolvedFileCount": "{count}",
|
"resolvedFileCount": "{count}",
|
||||||
"resolvedCategoryDirectory": "سيتم الحفظ في {path}",
|
"resolvedCategoryDirectory": "سيتم الحفظ في {path}",
|
||||||
"resourceHasNoFiles": "ولا توجد في هذا المورد قائمة ملف قابلة للاختيار",
|
"resourceHasNoFiles": "ولا توجد في هذا المورد قائمة ملف قابلة للاختيار",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "حالة التحديث",
|
"trackerSubscriptionUpdateStatus": "حالة التحديث",
|
||||||
"trackerSubscriptionTrackerCount": "عدد المتتبعات",
|
"trackerSubscriptionTrackerCount": "عدد المتتبعات",
|
||||||
"trackerSubscriptionNotUpdated": "لم يُحدّث بعد",
|
"trackerSubscriptionNotUpdated": "لم يُحدّث بعد",
|
||||||
"actions": "الإجراءات"
|
"actions": "الإجراءات",
|
||||||
|
"taskGroupDeleteImpact": "سيؤثر على {taskCount} من مهام التنزيل و{fileCount} من الملفات."
|
||||||
}
|
}
|
||||||
@@ -386,7 +386,9 @@
|
|||||||
"torrentDataEmpty": "Torrent fayl məlumatı boşdur",
|
"torrentDataEmpty": "Torrent fayl məlumatı boşdur",
|
||||||
"torrentPathUnavailable": "Torrent fayl yoluna giriş mümkün olmadı",
|
"torrentPathUnavailable": "Torrent fayl yoluna giriş mümkün olmadı",
|
||||||
"selectAtLeastOneFile": "Ən azı bir fayl seçin",
|
"selectAtLeastOneFile": "Ən azı bir fayl seçin",
|
||||||
"resolvedFiles": "Tapılmış Fayllar",
|
"resolvedFiles": "Fayl siyahısı",
|
||||||
|
"waitingToResolve": "Təhlil gözlənilir",
|
||||||
|
"resolvingResource": "Resurs təhlil edilir",
|
||||||
"resolvedFileCount": "{count} fayl tapıldı",
|
"resolvedFileCount": "{count} fayl tapıldı",
|
||||||
"resolvedCategoryDirectory": "{path} qovluğuna saxlanılacaq",
|
"resolvedCategoryDirectory": "{path} qovluğuna saxlanılacaq",
|
||||||
"resourceHasNoFiles": "Bu resursda seçilə bilən fayl siyahısı yoxdur",
|
"resourceHasNoFiles": "Bu resursda seçilə bilən fayl siyahısı yoxdur",
|
||||||
@@ -661,5 +663,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "Yeniləmə statusu",
|
"trackerSubscriptionUpdateStatus": "Yeniləmə statusu",
|
||||||
"trackerSubscriptionTrackerCount": "Tracker sayı",
|
"trackerSubscriptionTrackerCount": "Tracker sayı",
|
||||||
"trackerSubscriptionNotUpdated": "Hələ yenilənməyib",
|
"trackerSubscriptionNotUpdated": "Hələ yenilənməyib",
|
||||||
"actions": "Əməliyyatlar"
|
"actions": "Əməliyyatlar",
|
||||||
|
"taskGroupDeleteImpact": "{taskCount} endirməyə və {fileCount} fayla təsir edir."
|
||||||
}
|
}
|
||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "El fitxer torrent de dades és buit",
|
"torrentDataEmpty": "El fitxer torrent de dades és buit",
|
||||||
"torrentPathUnavailable": "No s' ha pogut accedir al camí del fitxer torrent",
|
"torrentPathUnavailable": "No s' ha pogut accedir al camí del fitxer torrent",
|
||||||
"selectAtLeastOneFile": "Seleccioneu com a mínim un fitxer",
|
"selectAtLeastOneFile": "Seleccioneu com a mínim un fitxer",
|
||||||
"resolvedFiles": "Fitxers resolts",
|
"resolvedFiles": "Llista de fitxers",
|
||||||
|
"waitingToResolve": "Esperant l’anàlisi",
|
||||||
|
"resolvingResource": "S’està analitzant el recurs",
|
||||||
"resolvedFileCount": "{count}",
|
"resolvedFileCount": "{count}",
|
||||||
"resolvedCategoryDirectory": "Es desarà a {path}",
|
"resolvedCategoryDirectory": "Es desarà a {path}",
|
||||||
"resourceHasNoFiles": "El recurs no té cap llista de fitxers per seleccionar",
|
"resourceHasNoFiles": "El recurs no té cap llista de fitxers per seleccionar",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "Estat de l’actualització",
|
"trackerSubscriptionUpdateStatus": "Estat de l’actualització",
|
||||||
"trackerSubscriptionTrackerCount": "Nombre de trackers",
|
"trackerSubscriptionTrackerCount": "Nombre de trackers",
|
||||||
"trackerSubscriptionNotUpdated": "Sense actualitzar",
|
"trackerSubscriptionNotUpdated": "Sense actualitzar",
|
||||||
"actions": "Accions"
|
"actions": "Accions",
|
||||||
|
"taskGroupDeleteImpact": "Afecta {taskCount} baixades i {fileCount} fitxers."
|
||||||
}
|
}
|
||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "Torrent-Dateidaten sind leer",
|
"torrentDataEmpty": "Torrent-Dateidaten sind leer",
|
||||||
"torrentPathUnavailable": "Auf den Torrent-Dateipfad kann nicht zugegriffen werden",
|
"torrentPathUnavailable": "Auf den Torrent-Dateipfad kann nicht zugegriffen werden",
|
||||||
"selectAtLeastOneFile": "Wählen Sie mindestens eine Datei aus",
|
"selectAtLeastOneFile": "Wählen Sie mindestens eine Datei aus",
|
||||||
"resolvedFiles": "Aufgelöste Dateien",
|
"resolvedFiles": "Dateiliste",
|
||||||
|
"waitingToResolve": "Warten auf Auflösung",
|
||||||
|
"resolvingResource": "Ressource wird aufgelöst",
|
||||||
"resolvedFileCount": "{count}-Dateien behoben",
|
"resolvedFileCount": "{count}-Dateien behoben",
|
||||||
"resolvedCategoryDirectory": "Wird in {path} gespeichert",
|
"resolvedCategoryDirectory": "Wird in {path} gespeichert",
|
||||||
"resourceHasNoFiles": "Die Ressource verfügt über keine auswählbare Dateiliste",
|
"resourceHasNoFiles": "Die Ressource verfügt über keine auswählbare Dateiliste",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "Aktualisierungsstatus",
|
"trackerSubscriptionUpdateStatus": "Aktualisierungsstatus",
|
||||||
"trackerSubscriptionTrackerCount": "Tracker-Anzahl",
|
"trackerSubscriptionTrackerCount": "Tracker-Anzahl",
|
||||||
"trackerSubscriptionNotUpdated": "Noch nicht aktualisiert",
|
"trackerSubscriptionNotUpdated": "Noch nicht aktualisiert",
|
||||||
"actions": "Aktionen"
|
"actions": "Aktionen",
|
||||||
|
"taskGroupDeleteImpact": "Betrifft {taskCount} Downloads und {fileCount} Dateien."
|
||||||
}
|
}
|
||||||
@@ -406,7 +406,9 @@
|
|||||||
"torrentDataEmpty": "Torrent file data is empty",
|
"torrentDataEmpty": "Torrent file data is empty",
|
||||||
"torrentPathUnavailable": "Unable to access the torrent file path",
|
"torrentPathUnavailable": "Unable to access the torrent file path",
|
||||||
"selectAtLeastOneFile": "Select at least one file",
|
"selectAtLeastOneFile": "Select at least one file",
|
||||||
"resolvedFiles": "Resolved Files",
|
"resolvedFiles": "File List",
|
||||||
|
"waitingToResolve": "Waiting to resolve",
|
||||||
|
"resolvingResource": "Resolving resource",
|
||||||
"resolvedFileCount": "{count, plural, =1{1 file resolved} other{{count} files resolved}}",
|
"resolvedFileCount": "{count, plural, =1{1 file resolved} other{{count} files resolved}}",
|
||||||
"resolvedCategoryDirectory": "Will be saved to {path}",
|
"resolvedCategoryDirectory": "Will be saved to {path}",
|
||||||
"@resolvedCategoryDirectory": {
|
"@resolvedCategoryDirectory": {
|
||||||
@@ -704,5 +706,16 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "Update status",
|
"trackerSubscriptionUpdateStatus": "Update status",
|
||||||
"trackerSubscriptionTrackerCount": "Tracker count",
|
"trackerSubscriptionTrackerCount": "Tracker count",
|
||||||
"trackerSubscriptionNotUpdated": "Not updated",
|
"trackerSubscriptionNotUpdated": "Not updated",
|
||||||
"actions": "Actions"
|
"actions": "Actions",
|
||||||
|
"taskGroupDeleteImpact": "Affects {taskCount} downloads and {fileCount} files.",
|
||||||
|
"@taskGroupDeleteImpact": {
|
||||||
|
"placeholders": {
|
||||||
|
"taskCount": {
|
||||||
|
"type": "int"
|
||||||
|
},
|
||||||
|
"fileCount": {
|
||||||
|
"type": "int"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "Los datos de archivos Torrent están vacíos",
|
"torrentDataEmpty": "Los datos de archivos Torrent están vacíos",
|
||||||
"torrentPathUnavailable": "Incapaz de acceder a la ruta del archivo torrent",
|
"torrentPathUnavailable": "Incapaz de acceder a la ruta del archivo torrent",
|
||||||
"selectAtLeastOneFile": "Seleccione al menos un archivo",
|
"selectAtLeastOneFile": "Seleccione al menos un archivo",
|
||||||
"resolvedFiles": "Archivos resueltos",
|
"resolvedFiles": "Lista de archivos",
|
||||||
|
"waitingToResolve": "Esperando resolución",
|
||||||
|
"resolvingResource": "Resolviendo recurso",
|
||||||
"resolvedFileCount": "{count} resueltos",
|
"resolvedFileCount": "{count} resueltos",
|
||||||
"resolvedCategoryDirectory": "Se guardará en {path}",
|
"resolvedCategoryDirectory": "Se guardará en {path}",
|
||||||
"resourceHasNoFiles": "El recurso no tiene lista de archivos seleccionable",
|
"resourceHasNoFiles": "El recurso no tiene lista de archivos seleccionable",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "Estado de actualización",
|
"trackerSubscriptionUpdateStatus": "Estado de actualización",
|
||||||
"trackerSubscriptionTrackerCount": "Número de trackers",
|
"trackerSubscriptionTrackerCount": "Número de trackers",
|
||||||
"trackerSubscriptionNotUpdated": "Sin actualizar",
|
"trackerSubscriptionNotUpdated": "Sin actualizar",
|
||||||
"actions": "Acciones"
|
"actions": "Acciones",
|
||||||
|
"taskGroupDeleteImpact": "Afecta a {taskCount} descargas y {fileCount} archivos."
|
||||||
}
|
}
|
||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "داده های فایل تورنت خالی است",
|
"torrentDataEmpty": "داده های فایل تورنت خالی است",
|
||||||
"torrentPathUnavailable": "امکان دسترسی به مسیر فایل تورنت",
|
"torrentPathUnavailable": "امکان دسترسی به مسیر فایل تورنت",
|
||||||
"selectAtLeastOneFile": "حداقل یک فایل را انتخاب کنید",
|
"selectAtLeastOneFile": "حداقل یک فایل را انتخاب کنید",
|
||||||
"resolvedFiles": "فایل های حل شده",
|
"resolvedFiles": "فهرست فایلها",
|
||||||
|
"waitingToResolve": "در انتظار پردازش",
|
||||||
|
"resolvingResource": "در حال پردازش منبع",
|
||||||
"resolvedFileCount": "{count} فایل شناسایی شد",
|
"resolvedFileCount": "{count} فایل شناسایی شد",
|
||||||
"resolvedCategoryDirectory": "در {path} ذخیره میشود",
|
"resolvedCategoryDirectory": "در {path} ذخیره میشود",
|
||||||
"resourceHasNoFiles": "منبع هیچ لیست فایل قابل انتخاب ندارد",
|
"resourceHasNoFiles": "منبع هیچ لیست فایل قابل انتخاب ندارد",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "وضعیت بهروزرسانی",
|
"trackerSubscriptionUpdateStatus": "وضعیت بهروزرسانی",
|
||||||
"trackerSubscriptionTrackerCount": "تعداد ردیابها",
|
"trackerSubscriptionTrackerCount": "تعداد ردیابها",
|
||||||
"trackerSubscriptionNotUpdated": "هنوز بهروزرسانی نشده",
|
"trackerSubscriptionNotUpdated": "هنوز بهروزرسانی نشده",
|
||||||
"actions": "عملیات"
|
"actions": "عملیات",
|
||||||
|
"taskGroupDeleteImpact": "بر {taskCount} بارگیری و {fileCount} پرونده تأثیر میگذارد."
|
||||||
}
|
}
|
||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "Les données du fichier Torrent sont vides",
|
"torrentDataEmpty": "Les données du fichier Torrent sont vides",
|
||||||
"torrentPathUnavailable": "Impossible d'accéder au chemin de fichier torrent",
|
"torrentPathUnavailable": "Impossible d'accéder au chemin de fichier torrent",
|
||||||
"selectAtLeastOneFile": "Sélectionnez au moins un fichier",
|
"selectAtLeastOneFile": "Sélectionnez au moins un fichier",
|
||||||
"resolvedFiles": "Fichiers résolus",
|
"resolvedFiles": "Liste des fichiers",
|
||||||
|
"waitingToResolve": "En attente d’analyse",
|
||||||
|
"resolvingResource": "Analyse de la ressource",
|
||||||
"resolvedFileCount": "{count} résolus",
|
"resolvedFileCount": "{count} résolus",
|
||||||
"resolvedCategoryDirectory": "Sera enregistré dans {path}",
|
"resolvedCategoryDirectory": "Sera enregistré dans {path}",
|
||||||
"resourceHasNoFiles": "La ressource n'a pas de liste de fichiers sélectionnable",
|
"resourceHasNoFiles": "La ressource n'a pas de liste de fichiers sélectionnable",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "État de mise à jour",
|
"trackerSubscriptionUpdateStatus": "État de mise à jour",
|
||||||
"trackerSubscriptionTrackerCount": "Nombre de trackers",
|
"trackerSubscriptionTrackerCount": "Nombre de trackers",
|
||||||
"trackerSubscriptionNotUpdated": "Pas encore mis à jour",
|
"trackerSubscriptionNotUpdated": "Pas encore mis à jour",
|
||||||
"actions": "Actions"
|
"actions": "Actions",
|
||||||
|
"taskGroupDeleteImpact": "Concerne {taskCount} téléchargements et {fileCount} fichiers."
|
||||||
}
|
}
|
||||||
@@ -372,7 +372,9 @@
|
|||||||
"torrentDataEmpty": "A torrent fájl adatai üresek",
|
"torrentDataEmpty": "A torrent fájl adatai üresek",
|
||||||
"torrentPathUnavailable": "Nem érhető el a torrent fájl elérési útja",
|
"torrentPathUnavailable": "Nem érhető el a torrent fájl elérési útja",
|
||||||
"selectAtLeastOneFile": "Válasszon ki legalább egy fájlt",
|
"selectAtLeastOneFile": "Válasszon ki legalább egy fájlt",
|
||||||
"resolvedFiles": "Feloldott fájlok",
|
"resolvedFiles": "Fájllista",
|
||||||
|
"waitingToResolve": "Feldolgozásra vár",
|
||||||
|
"resolvingResource": "Erőforrás feldolgozása",
|
||||||
"resolvedFileCount": "{count} fájlok megoldva",
|
"resolvedFileCount": "{count} fájlok megoldva",
|
||||||
"resolvedCategoryDirectory": "Ide lesz mentve: {path}",
|
"resolvedCategoryDirectory": "Ide lesz mentve: {path}",
|
||||||
"resourceHasNoFiles": "Az erőforrásnak nincs kiválasztható fájllistája",
|
"resourceHasNoFiles": "Az erőforrásnak nincs kiválasztható fájllistája",
|
||||||
@@ -477,5 +479,6 @@
|
|||||||
"trackerSubscriptionUpdateStatus": "Frissítés állapota",
|
"trackerSubscriptionUpdateStatus": "Frissítés állapota",
|
||||||
"trackerSubscriptionTrackerCount": "Trackerek száma",
|
"trackerSubscriptionTrackerCount": "Trackerek száma",
|
||||||
"trackerSubscriptionNotUpdated": "Még nem frissült",
|
"trackerSubscriptionNotUpdated": "Még nem frissült",
|
||||||
"actions": "Műveletek"
|
"actions": "Műveletek",
|
||||||
|
"taskGroupDeleteImpact": "{taskCount} letöltést és {fileCount} fájlt érint."
|
||||||
}
|
}
|
||||||
Loaded 50 of 84 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user