feat: add download directory placeholders, category support (#1188)

This commit is contained in:
Copilot authored and GitHub committed 2025-11-27 18:39:08 +08:00
1 parent 9d9f1caaaa
commit 49b4d99b5e
31 files changed
+1204 -118

No files matched your search

@@ -8,6 +8,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:get/get.dart';
import 'package:launch_at_startup/launch_at_startup.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:share_handler/share_handler.dart';
import 'package:tray_manager/tray_manager.dart';
@@ -504,6 +505,7 @@ class AppController extends GetxController with WindowListener, TrayListener {
// default select all tracker subscribe urls
extra.bt.trackerSubscribeUrls.addAll(allTrackerSubscribeUrls);
}
final proxy = config.proxy;
if (proxy.scheme.isEmpty) {
proxy.scheme = 'http';
@@ -521,6 +523,45 @@ class AppController extends GetxController with WindowListener, TrayListener {
config.downloadDir = './';
}
}
// Initialize default download categories if empty
if (extra.downloadCategories.isEmpty) {
await _initDefaultDownloadCategories();
}
}
Future<void> _initDefaultDownloadCategories() async {
final extra = downloaderConfig.value.extra;
final downloadDir = downloaderConfig.value.downloadDir;
// Add default built-in categories with i18n keys
// No need to set initial name value, it will be retrieved via nameKey
extra.downloadCategories.addAll([
DownloadCategory(
name: '',
path: path.join(downloadDir, 'Music'),
isBuiltIn: true,
nameKey: 'categoryMusic',
),
DownloadCategory(
name: '',
path: path.join(downloadDir, 'Video'),
isBuiltIn: true,
nameKey: 'categoryVideo',
),
DownloadCategory(
name: '',
path: path.join(downloadDir, 'Document'),
isBuiltIn: true,
nameKey: 'categoryDocument',
),
DownloadCategory(
name: '',
path: path.join(downloadDir, 'Program'),
isBuiltIn: true,
nameKey: 'categoryProgram',
),
]);
}
Future<void> _initLaunchAtStartup() async {
@@ -12,6 +12,7 @@ import 'package:rounded_loading_button_plus/rounded_loading_button.dart';
import '../../../../api/api.dart';
import '../../../../api/model/create_task.dart';
import '../../../../api/model/create_task_batch.dart';
import '../../../../api/model/downloader_config.dart';
import '../../../../api/model/options.dart';
import '../../../../api/model/request.dart';
import '../../../../api/model/resolve_result.dart';
@@ -72,7 +73,9 @@ class CreateView extends GetView<CreateController> {
.toString();
}
if (_pathController.text.isEmpty) {
_pathController.text = appController.downloaderConfig.value.downloadDir;
// Render placeholders when initializing the path
final downloadDir = appController.downloaderConfig.value.downloadDir;
_pathController.text = renderPathPlaceholders(downloadDir);
}
final CreateTask? routerParams = Get.rootDelegate.arguments();
@@ -328,6 +331,8 @@ class CreateView extends GetView<CreateController> {
DirectorySelector(
controller: _pathController,
),
// Category selector
_buildCategorySelector(appController),
Obx(
() => Visibility(
visible: controller.showAdvanced.value,
@@ -912,4 +917,66 @@ class CreateView extends GetView<CreateController> {
],
));
}
Widget _buildCategorySelector(AppController appController) {
final categories =
appController.downloaderConfig.value.extra.downloadCategories
.where((c) => !c.isDeleted) // Filter out deleted categories
.toList();
if (categories.isEmpty) {
return const SizedBox.shrink();
}
// Helper to get display name
String getCategoryDisplayName(DownloadCategory category) {
if (category.nameKey != null && category.nameKey!.isNotEmpty) {
return category.nameKey!.tr;
}
return category.name;
}
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
children: [
Text(
'selectCategory'.tr,
style: TextStyle(
color: Get.theme.hintColor,
fontSize: 12,
),
),
const SizedBox(width: 8),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: categories.map((category) {
return Padding(
padding: const EdgeInsets.only(right: 8),
child: OutlinedButton(
onPressed: () {
_pathController.text = renderPathPlaceholders(category.path);
},
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 4,
),
minimumSize: Size.zero,
),
child: Text(
getCategoryDisplayName(category),
style: const TextStyle(fontSize: 12),
),
),
);
}).toList(),
),
),
),
],
),
);
}
}
@@ -35,6 +35,14 @@ final _divider = const Divider().paddingOnly(left: 10, right: 10);
class SettingView extends GetView<SettingController> {
const SettingView({Key? key}) : super(key: key);
// Helper function to get display name for a category
static String _getCategoryDisplayName(DownloadCategory category) {
if (category.nameKey != null && category.nameKey!.isNotEmpty) {
return category.nameKey!.tr;
}
return category.name;
}
@override
Widget build(BuildContext context) {
final appController = Get.find<AppController>();
@@ -71,20 +79,25 @@ class SettingView extends GetView<SettingController> {
'downloadDir', () => downloaderCfg.value.downloadDir, (Key key) {
final downloadDirController =
TextEditingController(text: downloaderCfg.value.downloadDir);
downloadDirController.addListener(() async {
// Update config only when editing is done (on focus lost or submit)
void onEditComplete() {
if (downloadDirController.text != downloaderCfg.value.downloadDir) {
downloaderCfg.value.downloadDir = downloadDirController.text;
if (Util.isDesktop()) {
controller.clearTap();
}
await debounceSave();
debounceSave();
}
});
}
return DirectorySelector(
controller: downloadDirController,
showLabel: false,
showAndoirdToggle: true,
allowEdit: true,
showPlaceholderButton: true,
onEditComplete: onEditComplete,
);
});
final buildMaxRunning = _buildConfigItem(
@@ -135,6 +148,133 @@ class SettingView extends GetView<SettingController> {
);
});
// Download categories configuration
buildDownloadCategories() {
final categories = downloaderCfg.value.extra.downloadCategories
.where((c) => !c.isDeleted) // Filter out deleted categories
.toList();
return ListTile(
title: Text('downloadCategories'.tr),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (categories.isEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'add'.tr,
style: TextStyle(color: Theme.of(context).hintColor),
),
),
...categories.map((category) {
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_getCategoryDisplayName(category),
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
category.path,
style: TextStyle(
fontSize: 12,
color: Theme.of(context).hintColor,
),
overflow: TextOverflow.ellipsis,
),
],
),
),
IconButton(
icon: Icon(
Icons.edit,
size: 20,
color: Theme.of(context).hintColor,
),
onPressed: () {
_showCategoryDialog(
context,
debounceSave,
downloaderCfg,
category: category,
);
},
),
IconButton(
icon: Icon(
Icons.delete,
size: 20,
color: Theme.of(context).hintColor,
),
onPressed: () async {
// Show confirmation dialog
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text('tip'.tr),
content: Text('confirmDelete'.tr),
actions: [
TextButton(
onPressed: () =>
Navigator.of(context).pop(false),
child: Text('cancel'.tr),
),
TextButton(
onPressed: () =>
Navigator.of(context).pop(true),
child: Text('confirm'.tr),
),
],
),
);
if (confirmed == true) {
if (category.isBuiltIn) {
// Mark built-in category as deleted instead of removing it
downloaderCfg.update((val) {
category.isDeleted = true;
});
} else {
// Remove custom categories completely
downloaderCfg.update((val) {
val!.extra.downloadCategories = val
.extra.downloadCategories
.where((c) => c != category)
.toList();
});
}
debounceSave();
}
},
),
],
),
);
}),
Padding(
padding: const EdgeInsets.only(top: 8),
child: OutlinedButton.icon(
icon: const Icon(Icons.add, size: 18),
label: Text('add'.tr),
onPressed: () {
_showCategoryDialog(
context,
debounceSave,
downloaderCfg,
);
},
),
),
],
),
);
}
buildBrowserExtension() {
return ListTile(
title: Text('browserExtension'.tr),
@@ -896,22 +1036,37 @@ class SettingView extends GetView<SettingController> {
// advanced config webhook items
final buildWebhook = _buildConfigItem(
'webhook',
() => 'items'.trParams(
{'count': downloaderCfg.value.extra.webhookUrls.length.toString()}),
() => downloaderCfg.value.webhook.enable ? 'on'.tr : 'off'.tr,
(Key key) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'webhookEnable'.tr,
style: Theme.of(Get.context!).textTheme.bodyMedium,
),
const Spacer(),
Switch(
value: downloaderCfg.value.webhook.enable,
onChanged: (value) {
downloaderCfg.update((val) {
val!.webhook.enable = value;
});
debounceSave();
},
),
],
),
_padding,
Text(
'webhookDesc'.tr,
style: Theme.of(Get.context!).textTheme.bodySmall,
),
_padding,
// List of existing webhook URLs
...downloaderCfg.value.extra.webhookUrls
.asMap()
.entries
.map((entry) {
...downloaderCfg.value.webhook.urls.asMap().entries.map((entry) {
final index = entry.key;
final url = entry.value;
return Padding(
@@ -936,8 +1091,12 @@ class SettingView extends GetView<SettingController> {
icon: const Icon(Icons.delete, size: 20),
tooltip: 'delete'.tr,
onPressed: () async {
downloaderCfg.value.extra.webhookUrls.removeAt(index);
downloaderCfg.refresh();
// Create new list to avoid unmodifiable list error
final urls = List<String>.from(downloaderCfg.value.webhook.urls);
urls.removeAt(index);
downloaderCfg.update((val) {
val!.webhook.urls = urls;
});
await debounceSave();
},
),
@@ -1018,6 +1177,7 @@ class SettingView extends GetView<SettingController> {
child: Column(
children: _addDivider([
buildDownloadDir(),
buildDownloadCategories(),
buildMaxRunning(),
buildDefaultDirectDownload(),
buildBrowserExtension(),
@@ -1205,12 +1365,16 @@ class SettingView extends GetView<SettingController> {
saveController.start();
try {
// Create new list to avoid unmodifiable list error
final urls = List<String>.from(downloaderCfg.value.webhook.urls);
if (isEdit) {
downloaderCfg.value.extra.webhookUrls[index] = url;
urls[index] = url;
} else {
downloaderCfg.value.extra.webhookUrls.add(url);
urls.add(url);
}
downloaderCfg.refresh();
downloaderCfg.update((val) {
val!.webhook.urls = urls;
});
await appController.saveConfig();
if (dialogContext.mounted) {
Navigator.of(dialogContext).pop();
@@ -1302,6 +1466,88 @@ class SettingView extends GetView<SettingController> {
return 'themeSystem'.tr;
}
}
void _showCategoryDialog(
BuildContext context,
Future<bool> Function() debounceSave,
Rx<DownloaderConfig> downloaderCfg, {
DownloadCategory? category,
}) {
final isEdit = category != null;
final nameController = TextEditingController(
text: isEdit ? _getCategoryDisplayName(category) : '',
);
final pathController = TextEditingController(text: category?.path ?? '');
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(isEdit ? 'edit'.tr : 'add'.tr),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: nameController,
decoration: InputDecoration(
labelText: 'categoryName'.tr,
),
),
const SizedBox(height: 16),
DirectorySelector(
controller: pathController,
showLabel: true,
allowEdit: true,
showPlaceholderButton: true,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('cancel'.tr),
),
TextButton(
onPressed: () {
if (nameController.text.isEmpty || pathController.text.isEmpty) {
return;
}
if (isEdit) {
// Trigger UI update by wrapping changes in update()
downloaderCfg.update((val) {
// If name changed, clear nameKey so it won't be re-translated
final nameChanged =
nameController.text != _getCategoryDisplayName(category);
category.name = nameController.text;
category.path = pathController.text;
if (nameChanged) {
category.nameKey = null;
}
// If editing a deleted built-in category, unmark it as deleted
if (category.isBuiltIn && category.isDeleted) {
category.isDeleted = false;
}
});
} else {
downloaderCfg.update((val) {
val!.extra.downloadCategories = [
...val.extra.downloadCategories,
DownloadCategory(
name: nameController.text,
path: pathController.text,
),
];
});
}
debounceSave();
Navigator.of(context).pop();
},
child: Text('confirm'.tr),
),
],
),
);
}
}
enum ProxyModeEnum {
+181 -17
View File
@@ -14,17 +14,86 @@ import '../../util/util.dart';
final deviceInfo = DeviceInfoPlugin();
// Placeholder information for download directory
class PathPlaceholder {
final String placeholder;
final String description;
final String example;
const PathPlaceholder({
required this.placeholder,
required this.description,
required this.example,
});
}
// Available placeholders for download directory
List<PathPlaceholder> getPathPlaceholders() {
final now = DateTime.now();
final year = now.year.toString();
final month = now.month.toString().padLeft(2, '0');
final day = now.day.toString().padLeft(2, '0');
return [
PathPlaceholder(
placeholder: '%year%',
description: 'placeholderYear'.tr,
example: year,
),
PathPlaceholder(
placeholder: '%month%',
description: 'placeholderMonth'.tr,
example: month,
),
PathPlaceholder(
placeholder: '%day%',
description: 'placeholderDay'.tr,
example: day,
),
PathPlaceholder(
placeholder: '%date%',
description: 'placeholderDate'.tr,
example: '$year-$month-$day',
),
];
}
// Render placeholders in a path with actual values
String renderPathPlaceholders(String path) {
if (path.isEmpty) return path;
final now = DateTime.now();
final year = now.year.toString();
final month = now.month.toString().padLeft(2, '0');
final day = now.day.toString().padLeft(2, '0');
final date = '$year-$month-$day';
return path
.replaceAll('%year%', year)
.replaceAll('%month%', month)
.replaceAll('%day%', day)
.replaceAll('%date%', date);
}
class DirectorySelector extends StatefulWidget {
final TextEditingController controller;
final bool showLabel;
final bool showAndoirdToggle;
final bool allowEdit;
final bool showPlaceholderButton;
final VoidCallback? onEditComplete;
final bool showRenderedPlaceholders;
const DirectorySelector(
{Key? key,
required this.controller,
this.showLabel = true,
this.showAndoirdToggle = false})
: super(key: key);
const DirectorySelector({
Key? key,
required this.controller,
this.showLabel = true,
this.showAndoirdToggle = false,
this.allowEdit = false,
this.showPlaceholderButton = false,
this.onEditComplete,
this.showRenderedPlaceholders = false,
}) : super(key: key);
@override
State<DirectorySelector> createState() => _DirectorySelectorState();
@@ -108,22 +177,117 @@ class _DirectorySelectorState extends State<DirectorySelector> {
return null;
}
Widget? buildPlaceholderButton() {
if (!widget.showPlaceholderButton) return null;
return PopupMenuButton<String>(
icon: const Icon(Icons.data_object),
tooltip: 'insertPlaceholder'.tr,
onSelected: (String placeholder) {
final currentText = widget.controller.text;
final selection = widget.controller.selection;
final cursorPosition = selection.baseOffset >= 0
? selection.baseOffset
: currentText.length;
final newText = currentText.substring(0, cursorPosition) +
placeholder +
currentText.substring(cursorPosition);
widget.controller.text = newText;
widget.controller.selection = TextSelection.fromPosition(
TextPosition(offset: cursorPosition + placeholder.length),
);
},
itemBuilder: (BuildContext context) {
final placeholders = getPathPlaceholders();
return placeholders.map((p) {
return PopupMenuItem<String>(
value: p.placeholder,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${p.placeholder} - ${p.description}',
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
'example'.trParams({'value': p.example}),
style: TextStyle(
fontSize: 12,
color: Theme.of(context).hintColor,
),
),
],
),
);
}).toList();
},
);
}
return Row(
children: [
Expanded(
child: TextFormField(
readOnly: Util.isWeb() ? false : true,
controller: widget.controller,
decoration: widget.showLabel
? InputDecoration(
labelText: 'downloadDir'.tr,
)
: null,
validator: (v) {
return v!.trim().isNotEmpty ? null : 'downloadDirValid'.tr;
child: ValueListenableBuilder<TextEditingValue>(
valueListenable: widget.controller,
builder: (context, value, child) {
Widget? suffix;
if (widget.showRenderedPlaceholders && value.text.contains('%')) {
final renderedPath = renderPathPlaceholders(value.text);
// Show rendered path as a chip/badge in the input field
suffix = Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
margin: const EdgeInsets.only(right: 8),
decoration: BoxDecoration(
color: Colors.blue[50],
borderRadius: BorderRadius.circular(4),
border: Border.all(color: Colors.blue[200]!),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.arrow_forward, size: 14, color: Colors.blue[700]),
const SizedBox(width: 4),
Flexible(
child: Text(
renderedPath,
style: TextStyle(
color: Colors.blue[700],
fontSize: 12,
fontWeight: FontWeight.w500,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
return TextFormField(
readOnly: widget.allowEdit ? false : (Util.isWeb() ? false : true),
controller: widget.controller,
decoration: widget.showLabel
? InputDecoration(
labelText: 'downloadDir'.tr,
suffix: suffix,
)
: InputDecoration(
suffix: suffix,
),
validator: (v) {
return v!.trim().isNotEmpty ? null : 'downloadDirValid'.tr;
},
onEditingComplete: widget.onEditComplete,
onTapOutside: (event) {
// Call onEditComplete when user taps outside the field
widget.onEditComplete?.call();
},
);
},
)),
buildSelectWidget()
buildSelectWidget(),
buildPlaceholderButton(),
].where((e) => e != null).map((e) => e!).toList(),
);
}