feat(tasks): group extension folder downloads (#1594)

This commit is contained in:
WuFeng authored and GitHub committed 2026-11-02 15:39:08 +08:00
1 parent fc0a1e0ef9
commit 1e36599d52
84 files changed
+6690 -881

No files matched your search

@@ -19,8 +19,6 @@ import '../../../../api/model/create_task_batch.dart';
import '../../../../api/model/downloader_config.dart';
import '../../../../api/model/options.dart' as api_options;
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/utils/breakpoints.dart';
import '../../../../core/utils/text_wrap.dart';
@@ -39,10 +37,11 @@ import '../../../../shared/widgets/app_toast.dart';
import '../../../../l10n/l10n.dart';
import '../../../../util/util.dart';
import '../../application/pending_create_task.dart';
import '../../application/pending_download.dart';
import '../../application/task_list_navigation.dart';
import '../widgets/history_search_field.dart';
import '../widgets/create_task_action_buttons.dart';
import '../widgets/resolve_file_tree.dart';
import '../widgets/resolve_download_dialog.dart';
class CreateTaskWindowPage extends ConsumerStatefulWidget {
const CreateTaskWindowPage({super.key, this.windowController, this.initialTask});
@@ -92,6 +91,8 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
bool _directDownload = false;
int _protocolTab = 0;
bool _creating = false;
final Map<String, int> _completedSubmissionCounts = {};
int _createSession = 0;
bool _draggingTorrent = false;
bool _asDefaultPath = false;
String _configuredDownloadDirectory = '';
@@ -248,6 +249,8 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
if (task == null || !mounted) return;
final req = task.req;
final opts = task.opts ?? api_options.Options();
_createSession++;
_completedSubmissionCounts.clear();
setState(() {
_initialSize = 0;
_checksumAlgorithm = 'md5';
@@ -871,7 +874,20 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
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) {
// Navigation is best-effort after a successful submission. A navigation
// failure must not leave a completed form available for resubmission.
@@ -883,6 +899,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
} else {
ref.read(taskListNavigationProvider.notifier).showDownloading();
}
if (!mounted || session != _createSession) return;
await _closeWindow();
}
@@ -989,53 +1006,74 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
_showToast(context.l10n.downloadLinkValid);
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;
}
final session = _createSession;
setState(() {
_creating = true;
_draggingTorrent = false;
});
try {
await _saveCreateHistory(urls);
final isDirect = _directDownload || urls.length > 1;
if (isDirect) {
await Future.wait(
urls.map((url) {
return ref
.read(gopeedServiceProvider)
.createTask(
CreateTask(
req: _buildRequest(url, protocolUrl: _protocolUrlFor(url)),
opts: _buildOptions(
url: _protocolUrlFor(url),
name: urls.length > 1 ? '' : _renameController.text.trim(),
),
),
);
}),
unawaited(
_saveCreateHistory(urls).catchError((Object error) {
if (mounted && session == _createSession) _showToast(error.toString());
}),
);
if (pendingUrls.isEmpty) {
await _finishCreation(session);
return;
}
final sources = [
for (final entry in pendingUrls.indexed)
PendingDownload(
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;
}
final request = _buildRequest(urls.first, protocolUrl: _protocolUrlFor(urls.first));
final result = await ref.read(gopeedServiceProvider).resolve(ResolveTask(req: request));
if (!mounted) return;
final created = await _showResolveDialog(request, result);
if (!created) {
if (mounted) {
setState(() => _creating = false);
}
return;
}
await _finishCreation();
final created = await showResolveDownloadsDialog(
context,
sources: sources,
service: service,
onBatchCreated: (sources) {
if (!mounted || session != _createSession) return;
for (final source in sources) {
_completedSubmissionCounts.update(source.request.url, (count) => count + 1, ifAbsent: () => 1);
}
},
);
if (!mounted || session != _createSession || !created) return;
await _finishCreation(session);
} catch (error) {
if (mounted) {
_showToast(error.toString());
setState(() => _creating = false);
}
if (mounted && session == _createSession) _showToast(error.toString());
} finally {
if (mounted) setState(() => _creating = false);
}
}
@@ -1298,190 +1336,6 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
_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 {
List<String> histories;
try {
@@ -21,13 +21,8 @@ class TaskDetailsPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final tasksAsync = ref.watch(tasksControllerProvider);
TaskRecord? task = initialTask;
for (final item in tasksAsync.value?.tasks ?? const <TaskRecord>[]) {
if (item.id == taskId) {
task = item;
break;
}
}
final state = tasksAsync.value;
final task = state == null ? initialTask : state.findTask(taskId);
final palette = AppPalette.of(context);
return AppDetailPage(
@@ -43,12 +38,12 @@ class TaskDetailsPage extends ConsumerWidget {
key: ValueKey(task.id),
task: task,
mobile: true,
onOpenStorage: () => FileExplorer.reveal(task!.storagePath),
onOpenStorage: () => FileExplorer.reveal(task.storagePath),
onUpdateUrl: (url) async {
try {
await ref
.read(tasksControllerProvider.notifier)
.updateUrl(task!.id, url, headers: task.requestHeaders);
.updateUrl(task.id, url, headers: task.requestHeaders);
} catch (error) {
if (context.mounted) {
showAppToast(context, error.toString(), type: AppToastType.error);
@@ -20,13 +20,8 @@ class TaskFilesPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final tasksAsync = ref.watch(tasksControllerProvider);
TaskRecord? task = initialTask;
for (final item in tasksAsync.value?.tasks ?? const <TaskRecord>[]) {
if (item.id == taskId) {
task = item;
break;
}
}
final state = tasksAsync.value;
final task = state == null ? initialTask : state.findTask(taskId);
final palette = AppPalette.of(context);
return shad.Scaffold(