二次开发源码提交

This commit is contained in:
2026-05-15 08:52:48 +08:00
parent 4131f7321a
commit eb35a1d067
191 changed files with 34566 additions and 0 deletions
@@ -0,0 +1,886 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:lucide_icons/lucide_icons.dart';
import 'package:open_file/open_file.dart';
import 'package:provider/provider.dart';
import '../../../core/constants/storage_keys.dart';
import '../../../core/utils/app_logger.dart';
import '../../../data/models/cache_settings_model.dart';
import '../../../services/cache_manager_service.dart';
import '../../../services/download_service.dart';
import '../../../services/storage_service.dart';
import '../../providers/download_manager_provider.dart';
import '../../providers/theme_provider.dart';
import '../../providers/user_setting_provider.dart';
import '../../widgets/glassmorphism_container.dart';
import '../../widgets/toast_helper.dart';
import '../../widgets/desktop_constrained.dart';
import 'log_viewer_page.dart';
/// 应用设置页(缓存、主题、语言)
class AppSettingsPage extends StatefulWidget {
const AppSettingsPage({super.key});
@override
State<AppSettingsPage> createState() => _AppSettingsPageState();
}
class _AppSettingsPageState extends State<AppSettingsPage> {
CacheSettingsModel _cacheSettings = CacheSettingsModel();
bool _isLoading = true;
int? _currentCacheSize;
bool _isCleaning = false;
bool _wifiOnlyEnabled = false;
int _downloadRetries = 3;
int _taskRetentionDays = 7;
bool _gravatarMirrorEnabled = true;
String _gravatarMirrorUrl = 'https://weavatar.com';
String _logFilePath = '';
int? _logFileSize;
String _cacheDirPath = '';
@override
void initState() {
super.initState();
_loadCacheSettings();
_loadWifiOnlySetting();
_loadGravatarMirrorSetting();
_loadLogInfo();
}
Future<void> _loadCacheSettings() async {
try {
final service = CacheManagerService.instance;
await service.initialize();
final settings = service.settings;
if (mounted) {
setState(() {
_cacheSettings = settings;
_isLoading = false;
});
}
Future.delayed(const Duration(milliseconds: 100), () async {
final cacheSize = await service.getCacheSize();
final cacheDir = await service.getCacheDir();
if (mounted) {
setState(() {
_currentCacheSize = cacheSize;
_cacheDirPath = cacheDir.path;
});
}
});
} catch (e) {
if (mounted) setState(() => _isLoading = false);
}
}
Future<void> _saveCacheSettings() async {
final service = CacheManagerService.instance;
await service.saveSettings(_cacheSettings);
if (mounted) ToastHelper.success('设置已保存');
}
Future<void> _loadLogInfo() async {
final path = await AppLogger.logFilePath;
final size = await AppLogger.logFileSize;
if (mounted) {
setState(() {
_logFilePath = path;
_logFileSize = size;
});
}
}
Future<void> _loadWifiOnlySetting() async {
final enabled = await StorageService.instance
.getBool(StorageKeys.downloadWifiOnly) ??
false;
final retries = await StorageService.instance
.getInt(StorageKeys.downloadRetries) ??
3;
final retentionDays = await StorageService.instance
.getInt(StorageKeys.taskRetentionDays) ??
7;
if (mounted) {
setState(() {
_wifiOnlyEnabled = enabled;
_downloadRetries = retries;
_taskRetentionDays = retentionDays;
});
}
}
Future<void> _loadGravatarMirrorSetting() async {
final enabled = await StorageService.instance
.getBool(StorageKeys.gravatarMirrorEnabled) ??
true;
final url = await StorageService.instance
.getString(StorageKeys.gravatarMirrorUrl) ??
'https://weavatar.com';
if (mounted) {
setState(() {
_gravatarMirrorEnabled = enabled;
_gravatarMirrorUrl = url;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('应用设置')),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: DesktopConstrained(
child: ListView(
children: [
_buildSection(
title: '外观',
children: [
ListTile(
leading: const Icon(Icons.dark_mode_outlined),
title: const Text('深色模式'),
subtitle: Text(_themeModeLabel(context)),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showThemeModeDialog(context),
),
ListTile(
leading: const Icon(Icons.palette_outlined),
title: const Text('主题色'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
CircleAvatar(
backgroundColor: context.watch<ThemeProvider>().seedColor,
radius: 10,
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right),
],
),
onTap: () => _showThemeColorPicker(context),
),
ListTile(
leading: const Icon(Icons.language),
title: const Text('语言'),
subtitle: const Text('跟随系统'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLanguageDialog(context),
),
],
),
_buildSection(
title: 'Gravatar 镜像',
children: [
SwitchListTile(
title: const Text('启用 Gravatar 镜像'),
subtitle: const Text('国内网络建议启用,加速 Gravatar 头像加载'),
value: _gravatarMirrorEnabled,
onChanged: (value) async {
setState(() => _gravatarMirrorEnabled = value);
await StorageService.instance
.setBool(StorageKeys.gravatarMirrorEnabled, value);
},
),
if (_gravatarMirrorEnabled)
ListTile(
leading: const Icon(Icons.dns_outlined),
title: const Text('镜像地址'),
subtitle: Text(_gravatarMirrorUrl),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showGravatarMirrorUrlDialog(context),
),
],
),
_buildSection(
title: '下载设置',
children: [
SwitchListTile(
title: const Text('仅WiFi下载'),
subtitle: const Text('非WiFi环境下暂停下载,等待WiFi后自动恢复'),
value: _wifiOnlyEnabled,
onChanged: (value) async {
setState(() => _wifiOnlyEnabled = value);
await StorageService.instance
.setBool(StorageKeys.downloadWifiOnly, value);
if (mounted) {
if (!context.mounted) return;
context
.read<DownloadManagerProvider>()
.setWifiOnlyEnabled(value);
}
},
),
ListTile(
title: const Text('重试次数'),
subtitle: Text(_downloadRetries == 0 ? '不重试' : '失败后自动重试 $_downloadRetries'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showRetriesDialog(context),
),
ListTile(
title: const Text('任务记录保留'),
subtitle: Text(_taskRetentionDays == -1 ? '永久保留' : '保留 $_taskRetentionDays'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showRetentionDaysDialog(context),
),
],
),
_buildSection(
title: '缓存设置',
children: [
ListTile(
title: const Text('最大缓存大小'),
subtitle: Text(_cacheSettings.maxCacheSizeReadable),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showMaxCacheSizeDialog(context),
),
ListTile(
title: const Text('缓存过期时间'),
subtitle: Text(_cacheSettings.cacheExpireDurationReadable),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showCacheExpireDurationDialog(context),
),
SwitchListTile(
title: const Text('自动清理最旧文件'),
subtitle: const Text('当超过最大缓存大小时自动清理'),
value: _cacheSettings.autoCleanOldFiles,
onChanged: (value) {
setState(() {
_cacheSettings = _cacheSettings.copyWith(autoCleanOldFiles: value);
});
_saveCacheSettings();
},
),
],
),
_buildSection(
title: '缓存信息',
children: [
if (_cacheDirPath.isNotEmpty)
ListTile(
title: const Text('缓存目录'),
subtitle: Text(
_cacheDirPath,
style: const TextStyle(fontSize: 11),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
trailing: (Platform.isWindows || Platform.isLinux)
? const Icon(Icons.open_in_new, size: 18)
: null,
onTap: (Platform.isWindows || Platform.isLinux)
? _openCacheDir
: null,
),
ListTile(
title: const Text('当前缓存大小'),
subtitle: Text(_formatBytes(_currentCacheSize)),
),
ListTile(
title: const Text('清空缓存'),
leading: const Icon(Icons.delete_outline, color: Colors.red),
trailing: _isCleaning
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.chevron_right),
onTap: _isCleaning ? null : _clearCache,
),
],
),
_buildSection(
title: '日志管理',
children: [
ListTile(
title: const Text('日志文件路径'),
subtitle: Text(
_logFilePath,
style: const TextStyle(fontSize: 11),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
ListTile(
title: const Text('日志文件大小'),
subtitle: Text(_formatBytes(_logFileSize)),
),
if (!Platform.isAndroid)
ListTile(
title: const Text('打开日志目录'),
leading: const Icon(Icons.folder_open),
trailing: const Icon(Icons.chevron_right),
onTap: _openLogFolder,
),
ListTile(
title: const Text('导出日志'),
leading: const Icon(Icons.file_download_outlined),
subtitle: const Text('导出到 Download 目录'),
trailing: const Icon(Icons.chevron_right),
onTap: _exportLog,
),
ListTile(
title: const Text('预览日志'),
leading: const Icon(Icons.visibility_outlined),
trailing: const Icon(Icons.chevron_right),
onTap: _previewLog,
),
ListTile(
title: const Text('清空日志'),
leading: const Icon(Icons.delete_outline, color: Colors.red),
trailing: const Icon(Icons.chevron_right),
onTap: _clearLog,
),
],
),
],
),
),
);
}
Widget _buildSection({required String title, required List<Widget> children}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
title,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
Card(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: Column(children: children),
),
],
),
);
}
Future<void> _showThemeColorPicker(BuildContext context) async {
final colors = [
('默认蓝', Colors.blue),
('靛蓝', Colors.indigo),
('紫色', Colors.purple),
('粉红', Colors.pink),
('红色', Colors.red),
('橙色', Colors.orange),
('琥珀', Colors.amber),
('绿色', Colors.green),
('青色', Colors.teal),
('青蓝', Colors.cyan),
];
final currentColor = context.read<ThemeProvider>().seedColor;
final selected = await showDialog<Color>(
context: context,
builder: (ctx) => SimpleDialog(
title: const Text('选择主题色'),
children: colors.map((c) {
final isSelected = currentColor.toARGB32() == c.$2.toARGB32();
return SimpleDialogOption(
onPressed: () => Navigator.of(ctx).pop(c.$2),
child: Row(
children: [
CircleAvatar(backgroundColor: c.$2, radius: 14),
const SizedBox(width: 12),
Expanded(child: Text(c.$1)),
if (isSelected)
Icon(Icons.check, color: Theme.of(ctx).colorScheme.primary),
],
),
);
}).toList(),
),
);
if (selected == null || !mounted) return;
if (!context.mounted) return;
// 立即更新本地主题
await context.read<ThemeProvider>().setSeedColor(selected);
if (!context.mounted) return;
// 同步到服务端
final hex = '#${selected.toARGB32().toRadixString(16).padLeft(8, '0').substring(2)}';
final success = await context.read<UserSettingProvider>().updatePreferredTheme(hex);
if (!mounted) return;
if (success) {
ToastHelper.success('主题色已更新');
} else {
ToastHelper.failure('同步主题色到服务端失败');
}
}
String _themeModeLabel(BuildContext context) {
final mode = context.watch<ThemeProvider>().themeMode;
return switch (mode) {
AppThemeMode.light => '浅色',
AppThemeMode.dark => '深色',
AppThemeMode.system => '跟随系统',
};
}
Future<void> _showThemeModeDialog(BuildContext context) async {
final currentMode = context.read<ThemeProvider>().themeMode;
final options = [
(AppThemeMode.system, '跟随系统', Icons.brightness_auto),
(AppThemeMode.light, '浅色', Icons.light_mode),
(AppThemeMode.dark, '深色', Icons.dark_mode),
];
final selected = await showDialog<AppThemeMode>(
context: context,
builder: (ctx) => SimpleDialog(
title: const Text('深色模式'),
children: options.map((opt) {
final isSelected = currentMode == opt.$1;
return SimpleDialogOption(
onPressed: () => Navigator.of(ctx).pop(opt.$1),
child: Row(
children: [
Icon(opt.$3),
const SizedBox(width: 12),
Expanded(child: Text(opt.$2)),
if (isSelected)
Icon(Icons.check, color: Theme.of(ctx).colorScheme.primary),
],
),
);
}).toList(),
),
);
if (selected == null || !mounted) return;
if (!context.mounted) return;
await context.read<ThemeProvider>().setThemeMode(selected);
}
Future<void> _showLanguageDialog(BuildContext context) async {
final languages = [
('zh-CN', '简体中文'),
('zh-TW', '繁體中文'),
('en-US', 'English'),
('ja-JP', '日本語'),
];
final selected = await showDialog<String>(
context: context,
builder: (ctx) => SimpleDialog(
title: const Text('选择语言'),
children: languages.map((l) {
return SimpleDialogOption(
onPressed: () => Navigator.of(ctx).pop(l.$1),
child: Text(l.$2),
);
}).toList(),
),
);
if (selected == null || !mounted) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().updateLanguage(selected);
if (!mounted) return;
if (success) {
ToastHelper.success('语言偏好已保存');
} else {
ToastHelper.failure('更新语言失败');
}
}
Future<void> _showMaxCacheSizeDialog(BuildContext context) async {
final availableSizes = CacheSettingsModel.availableSizes;
final currentValue = _cacheSettings.maxCacheSize ~/ (1024 * 1024);
final selected = await _showGlassOptionDialog<int>(
context,
title: '最大缓存大小',
icon: LucideIcons.hardDrive,
options: availableSizes.map((size) => (size, '$size MB', currentValue == size)).toList(),
);
if (selected != null && mounted) {
setState(() => _cacheSettings = CacheSettingsModel.fromMB(selected));
_saveCacheSettings();
}
}
Future<void> _showCacheExpireDurationDialog(BuildContext context) async {
final availableDurations = CacheSettingsModel.availableDurations;
final currentValue = _cacheSettings.cacheExpireDuration ~/ (24 * 60 * 60 * 1000);
final selected = await _showGlassOptionDialog<int>(
context,
title: '缓存过期时间',
icon: LucideIcons.timer,
options: availableDurations.map((days) => (days, '$days', currentValue == days)).toList(),
);
if (selected != null && mounted) {
setState(() => _cacheSettings = CacheSettingsModel.fromDays(selected));
_saveCacheSettings();
}
}
Future<void> _showRetriesDialog(BuildContext context) async {
final retriesOptions = [0, 1, 2, 3, 5, 10];
final selected = await _showGlassOptionDialog<int>(
context,
title: '重试次数',
icon: LucideIcons.refreshCw,
subtitle: '下载失败后自动重试的次数',
options: retriesOptions.map((retries) =>
(retries, retries == 0 ? '不重试' : '$retries', _downloadRetries == retries)).toList(),
);
if (selected != null && mounted) {
setState(() => _downloadRetries = selected);
await StorageService.instance
.setInt(StorageKeys.downloadRetries, selected);
}
}
Future<void> _showRetentionDaysDialog(BuildContext context) async {
final options = [
(7, '7 天'),
(15, '15 天'),
(30, '30 天'),
(-1, '永久保留'),
];
final selected = await _showGlassOptionDialog<int>(
context,
title: '任务记录保留时间',
icon: LucideIcons.clock,
subtitle: '超过保留时间的已完成任务将被自动清理',
options: options.map((opt) => (opt.$1, opt.$2, _taskRetentionDays == opt.$1)).toList(),
);
if (selected != null && mounted) {
setState(() => _taskRetentionDays = selected);
await StorageService.instance
.setInt(StorageKeys.taskRetentionDays, selected);
}
}
/// 通用毛玻璃选项选择对话框
Future<T?> _showGlassOptionDialog<T>(
BuildContext context, {
required String title,
required IconData icon,
String? subtitle,
required List<(T, String, bool)> options,
}) {
return showGeneralDialog<T>(
context: context,
barrierDismissible: true,
barrierLabel: title,
barrierColor: Colors.black38,
transitionDuration: const Duration(milliseconds: 250),
transitionBuilder: (context, animation, secondaryAnimation, child) {
final scaleAnim = CurvedAnimation(
parent: animation,
curve: Curves.easeOutCubic,
).drive(Tween(begin: 0.92, end: 1.0));
final fadeAnim = CurvedAnimation(
parent: animation,
curve: Curves.easeOut,
).drive(Tween(begin: 0.0, end: 1.0));
return ScaleTransition(
scale: scaleAnim,
child: FadeTransition(opacity: fadeAnim, child: child),
);
},
pageBuilder: (context, animation, secondaryAnimation) {
final screenWidth = MediaQuery.of(context).size.width;
final dialogWidth = screenWidth >= 600 ? 380.0 : screenWidth - 48.0;
final colorScheme = Theme.of(context).colorScheme;
final theme = Theme.of(context);
return Center(
child: SizedBox(
width: dialogWidth,
child: GlassmorphismContainer(
borderRadius: 16,
sigmaX: 20,
sigmaY: 20,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Material(
color: Colors.transparent,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Header
Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 8, 12),
child: Row(
children: [
Icon(icon, size: 20, color: colorScheme.primary),
const SizedBox(width: 10),
Expanded(
child: Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
),
IconButton(
icon: const Icon(LucideIcons.x, size: 20),
onPressed: () => Navigator.of(context).pop(),
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
),
],
),
),
if (subtitle != null)
Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 8),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
subtitle,
style: TextStyle(fontSize: 13, color: theme.hintColor),
),
),
),
const Divider(height: 1),
// Options
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.5,
),
child: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 4),
itemCount: options.length,
itemBuilder: (context, index) {
final (value, label, isSelected) = options[index];
return ListTile(
leading: Icon(
isSelected
? LucideIcons.checkCircle2
: LucideIcons.circle,
size: 20,
color: isSelected
? colorScheme.primary
: theme.hintColor,
),
title: Text(label),
selected: isSelected,
onTap: () => Navigator.of(context).pop(value),
);
},
),
),
],
),
),
),
),
),
);
},
);
}
Future<void> _showGravatarMirrorUrlDialog(BuildContext context) async {
final controller = TextEditingController(text: _gravatarMirrorUrl);
final presets = [
'https://weavatar.com',
'https://gravatar.loli.net',
'https://cdn.v2ex.com/gravatar',
];
final selected = await showDialog<String>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Gravatar 镜像地址'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: controller,
decoration: const InputDecoration(
labelText: '镜像地址',
hintText: '例如: https://weavatar.com',
isDense: true,
),
),
const SizedBox(height: 16),
const Text('常用镜像:', style: TextStyle(fontSize: 12, color: Colors.grey)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: presets.map((url) => ActionChip(
label: Text(url, style: const TextStyle(fontSize: 11)),
onPressed: () => controller.text = url,
)).toList(),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(controller.text.trim()),
child: const Text('确定'),
),
],
),
);
if (selected != null && selected.isNotEmpty && mounted) {
var url = selected;
if (url.endsWith('/')) url = url.substring(0, url.length - 1);
setState(() => _gravatarMirrorUrl = url);
await StorageService.instance
.setString(StorageKeys.gravatarMirrorUrl, url);
}
}
Future<void> _clearCache() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('清空缓存'),
content: const Text('确定要清空所有缓存吗?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.error),
child: const Text('清空'),
),
],
),
);
if (confirmed == true && mounted) {
setState(() => _isCleaning = true);
try {
final service = CacheManagerService.instance;
await service.clearCache();
final newCacheSize = await service.getCacheSize();
if (mounted) {
setState(() {
_currentCacheSize = newCacheSize;
_isCleaning = false;
});
ToastHelper.success('缓存已清空');
}
} catch (e) {
if (mounted) {
setState(() => _isCleaning = false);
ToastHelper.failure('清空缓存失败: $e');
}
}
}
}
String _formatBytes(int? bytes) {
if (bytes == null) return '未知';
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
}
Future<void> _openLogFolder() async {
try {
final path = _logFilePath;
if (path.isEmpty) {
ToastHelper.error('日志文件路径未获取');
return;
}
final dir = File(path).parent.path;
final result = await OpenFile.open(dir);
if (result.type != ResultType.done) {
if (mounted) ToastHelper.error('无法打开目录:${result.message}');
}
} catch (e) {
if (mounted) ToastHelper.error('打开目录失败:$e');
}
}
Future<void> _openCacheDir() async {
try {
if (_cacheDirPath.isEmpty) {
ToastHelper.error('缓存目录路径未获取');
return;
}
final result = await OpenFile.open(_cacheDirPath);
if (result.type != ResultType.done) {
if (mounted) ToastHelper.error('无法打开目录:${result.message}');
}
} catch (e) {
if (mounted) ToastHelper.error('打开目录失败:$e');
}
}
Future<void> _exportLog() async {
try {
final dir = await DownloadService().getDownloadDirectory();
final destPath = await AppLogger.exportLog(dir.path);
if (destPath != null && mounted) {
ToastHelper.success('日志已导出到:$destPath');
} else if (mounted) {
ToastHelper.error('导出失败:日志文件不存在');
}
} catch (e) {
if (mounted) ToastHelper.error('导出日志失败:$e');
}
}
Future<void> _previewLog() async {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const LogViewerPage()),
);
}
Future<void> _clearLog() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('清空日志'),
content: const Text('确定要清空日志文件内容吗?此操作不可恢复。'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.error),
child: const Text('清空'),
),
],
),
);
if (confirmed == true && mounted) {
await AppLogger.clearLog();
await _loadLogInfo();
if (mounted) ToastHelper.success('日志已清空');
}
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/material.dart';
import '../../../data/models/user_setting_model.dart';
import '../../../services/user_setting_service.dart';
import '../../widgets/toast_helper.dart';
import '../../widgets/desktop_constrained.dart';
/// 积分变动历史页
class CreditHistoryPage extends StatefulWidget {
final int currentCredit;
const CreditHistoryPage({super.key, required this.currentCredit});
@override
State<CreditHistoryPage> createState() => _CreditHistoryPageState();
}
class _CreditHistoryPageState extends State<CreditHistoryPage> {
final List<CreditChange> _changes = [];
String? _nextToken;
bool _isLoading = true;
bool _isLoadingMore = false;
bool get _hasMore => _nextToken != null && _nextToken!.isNotEmpty;
@override
void initState() {
super.initState();
_loadChanges();
}
Future<void> _loadChanges() async {
try {
final result = await UserSettingService.instance.getCreditChanges(
nextPageToken: _nextToken,
);
if (mounted) {
setState(() {
_changes.addAll(result.changes);
_nextToken = result.nextToken;
_isLoading = false;
_isLoadingMore = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
_isLoadingMore = false;
});
ToastHelper.failure('加载积分记录失败: $e');
}
}
}
Future<void> _loadMore() async {
if (_isLoadingMore || !_hasMore) return;
setState(() => _isLoadingMore = true);
await _loadChanges();
}
Future<void> _refresh() async {
setState(() {
_changes.clear();
_nextToken = null;
_isLoading = true;
});
await _loadChanges();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Scaffold(
appBar: AppBar(title: const Text('积分记录')),
body: DesktopConstrained(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: _refresh,
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
Text(
'${widget.currentCredit}',
style: theme.textTheme.displaySmall?.copyWith(
fontWeight: FontWeight.bold,
color: colorScheme.primary,
),
),
const SizedBox(height: 4),
Text('当前积分', style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
)),
],
),
),
),
if (_changes.isEmpty)
const SliverFillRemaining(
child: Center(child: Text('暂无积分记录', style: TextStyle(color: Colors.grey))),
)
else ...[
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
if (index == _changes.length) {
return _hasMore
? Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: _isLoadingMore
? const CircularProgressIndicator()
: TextButton(
onPressed: _loadMore,
child: const Text('加载更多'),
),
),
)
: const SizedBox.shrink();
}
final change = _changes[index];
final isPositive = change.diff > 0;
return ListTile(
leading: Icon(
isPositive ? Icons.add_circle_outline : Icons.remove_circle_outline,
color: isPositive ? Colors.green : Colors.red,
),
title: Text(change.reasonLabel),
subtitle: Text(_formatDateTime(change.changedAt)),
trailing: Text(
'${isPositive ? "+" : ""}${change.diff}',
style: TextStyle(
color: isPositive ? Colors.green : Colors.red,
fontWeight: FontWeight.bold,
),
),
);
},
childCount: _changes.length + 1,
),
),
],
],
),
),
),
);
}
String _formatDateTime(DateTime dt) {
return '${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}'
' ${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
}
}
@@ -0,0 +1,306 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../data/models/user_setting_model.dart';
import '../../providers/user_setting_provider.dart';
import '../../widgets/toast_helper.dart';
import '../../widgets/desktop_constrained.dart';
/// 文件偏好设置页
class FilePreferencesPage extends StatefulWidget {
const FilePreferencesPage({super.key});
@override
State<FilePreferencesPage> createState() => _FilePreferencesPageState();
}
class _FilePreferencesPageState extends State<FilePreferencesPage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<UserSettingProvider>().loadSettings();
});
}
@override
Widget build(BuildContext context) {
final provider = context.watch<UserSettingProvider>();
final settings = provider.settings;
return Scaffold(
appBar: AppBar(title: const Text('文件偏好')),
body: DesktopConstrained(
child: ListView(
children: [
_buildSection(
title: '版本保留',
children: [
SwitchListTile(
secondary: const Icon(Icons.history),
title: const Text('启用版本保留'),
subtitle: const Text('保留文件的历史版本'),
value: settings?.versionRetentionEnabled ?? false,
onChanged: (value) async {
final success = await context.read<UserSettingProvider>().updateVersionRetention(enabled: value);
if (!mounted) return;
if (!success) ToastHelper.failure('更新失败');
},
),
ListTile(
leading: const Icon(Icons.filter_list),
title: const Text('保留的文件类型'),
subtitle: Text(
settings?.versionRetentionExt == null
? '所有文件类型'
: (settings!.versionRetentionExt!.isEmpty
? '所有文件类型'
: settings.versionRetentionExt!.join(', ')),
),
trailing: const Icon(Icons.chevron_right),
enabled: settings?.versionRetentionEnabled ?? false,
onTap: () => _showExtEditor(context, settings),
),
ListTile(
leading: const Icon(Icons.numbers),
title: const Text('最大保留版本数'),
subtitle: Text(
(settings?.versionRetentionMax ?? 0) == 0
? '无限制'
: '${settings!.versionRetentionMax} 个版本',
),
trailing: const Icon(Icons.chevron_right),
enabled: settings?.versionRetentionEnabled ?? false,
onTap: () => _showMaxVersionsDialog(context, settings),
),
],
),
_buildSection(
title: '视图与同步',
children: [
SwitchListTile(
secondary: const Icon(Icons.sync_disabled),
title: const Text('禁用视图同步'),
subtitle: const Text('关闭后视图设置不会跨设备同步'),
value: settings?.disableViewSync ?? false,
onChanged: (value) async {
final success = await context.read<UserSettingProvider>().updateViewSync(value);
if (!mounted) return;
if (!success) ToastHelper.failure('更新失败');
},
),
],
),
_buildSection(
title: '分享',
children: [
ListTile(
leading: const Icon(Icons.share_outlined),
title: const Text('个人主页分享链接可见性'),
subtitle: Text(_shareVisibilityLabel(settings?.shareLinksInProfile ?? '')),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showShareVisibilityDialog(context, settings),
),
],
),
],
),
),
);
}
Widget _buildSection({required String title, required List<Widget> children}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
title,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
Card(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: Column(children: children),
),
],
),
);
}
String _shareVisibilityLabel(String value) {
switch (value) {
case 'all_share':
return '所有分享链接';
case 'hide_share':
return '隐藏分享链接';
default:
return '仅公开分享';
}
}
Future<void> _showShareVisibilityDialog(BuildContext context, UserSettingModel? settings) async {
final currentValue = settings?.shareLinksInProfile ?? '';
final options = [
('', '仅公开分享', '仅在个人主页显示公开分享'),
('all_share', '所有分享链接', '在个人主页显示所有分享'),
('hide_share', '隐藏分享链接', '不在个人主页显示任何分享'),
];
final selected = await showDialog<String>(
context: context,
builder: (ctx) => SimpleDialog(
title: const Text('分享链接可见性'),
children: options
.map((opt) => SimpleDialogOption(
onPressed: () => Navigator.of(ctx).pop(opt.$1),
child: Row(
children: [
Icon(
currentValue == opt.$1 ? Icons.radio_button_checked : Icons.radio_button_unchecked,
color: Theme.of(ctx).colorScheme.primary,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(opt.$2, style: const TextStyle(fontWeight: FontWeight.w500)),
Text(opt.$3, style: Theme.of(ctx).textTheme.bodySmall),
],
),
),
],
),
))
.toList(),
),
);
if (selected == null || !mounted) return;
if (selected == currentValue) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().updateShareLinksInProfile(selected);
if (!mounted) return;
if (success) {
ToastHelper.success('已更新');
} else {
ToastHelper.failure('更新失败');
}
}
Future<void> _showMaxVersionsDialog(BuildContext context, UserSettingModel? settings) async {
final controller = TextEditingController(
text: (settings?.versionRetentionMax ?? 0) == 0 ? '' : '${settings!.versionRetentionMax}',
);
final isUnlimited = (settings?.versionRetentionMax ?? 0) == 0;
final result = await showDialog<Map<String, dynamic>>(
context: context,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setDialogState) => AlertDialog(
title: const Text('最大保留版本数'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
SwitchListTile(
title: const Text('无限制'),
value: isUnlimited,
onChanged: (v) => setDialogState(() {}),
),
if (!isUnlimited)
TextField(
controller: controller,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '版本数',
hintText: '输入最大保留版本数',
),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(null), child: const Text('取消')),
FilledButton(
onPressed: () {
final unlimited = isUnlimited;
final max = unlimited ? 0 : (int.tryParse(controller.text) ?? 0);
Navigator.of(ctx).pop({'unlimited': unlimited, 'max': max});
},
child: const Text('确定'),
),
],
),
),
);
if (result == null || !mounted) return;
final max = result['max'] as int;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().updateVersionRetention(max: max);
if (!mounted) return;
if (success) {
ToastHelper.success('已更新');
} else {
ToastHelper.failure('更新失败');
}
}
Future<void> _showExtEditor(BuildContext context, UserSettingModel? settings) async {
final exts = settings?.versionRetentionExt ?? [];
final controller = TextEditingController(text: exts.join(', '));
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('保留的文件类型'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('输入文件扩展名,用逗号分隔。留空表示所有类型。'),
const SizedBox(height: 8),
TextField(
controller: controller,
decoration: const InputDecoration(
labelText: '扩展名',
hintText: '.doc, .pdf, .xlsx',
),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('确定'),
),
],
),
);
if (confirmed != true || !mounted) return;
final text = controller.text.trim();
List<String>? newExts;
if (text.isEmpty) {
newExts = null; // null 表示所有类型
} else {
newExts = text.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
}
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().updateVersionRetention(ext: newExts);
if (!mounted) return;
if (success) {
ToastHelper.success('已更新');
} else {
ToastHelper.failure('更新失败');
}
}
}
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import '../../../core/utils/app_logger.dart';
import '../../widgets/toast_helper.dart';
/// 日志预览页面
class LogViewerPage extends StatefulWidget {
const LogViewerPage({super.key});
@override
State<LogViewerPage> createState() => _LogViewerPageState();
}
class _LogViewerPageState extends State<LogViewerPage> {
String _logContent = '';
bool _isLoading = true;
final bool _isAutoScroll = true;
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_loadLog();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
Future<void> _loadLog() async {
setState(() => _isLoading = true);
try {
final content = await AppLogger.readLog(maxLines: 1000);
if (mounted) {
setState(() {
_logContent = content;
_isLoading = false;
});
if (_isAutoScroll) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.jumpTo(
_scrollController.position.maxScrollExtent);
}
});
}
}
} catch (e) {
if (mounted) {
setState(() => _isLoading = false);
ToastHelper.error('读取日志失败:$e');
}
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Scaffold(
appBar: AppBar(
title: const Text('日志预览'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadLog,
tooltip: '刷新',
),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _logContent.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.description_outlined,
size: 48, color: theme.hintColor.withValues(alpha: 0.4)),
const SizedBox(height: 16),
Text('暂无日志', style: TextStyle(color: theme.hintColor)),
],
),
)
: Container(
color: isDark ? const Color(0xFF1E1E1E) : const Color(0xFFF5F5F5),
child: Scrollbar(
controller: _scrollController,
child: SingleChildScrollView(
controller: _scrollController,
padding: const EdgeInsets.all(12),
child: SelectableText(
_logContent,
style: TextStyle(
fontFamily: 'SourceCodePro',
fontSize: 13,
height: 1.5,
color: isDark ? Colors.grey[300] : Colors.grey[900],
),
),
),
),
),
);
}
}
@@ -0,0 +1,288 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import '../../../data/models/user_model.dart';
import '../../../services/user_setting_service.dart';
import '../../providers/auth_provider.dart';
import '../../providers/user_setting_provider.dart';
import '../../widgets/toast_helper.dart';
import '../../widgets/desktop_constrained.dart';
import '../../widgets/user_avatar.dart';
/// 个人资料编辑页
class ProfileEditPage extends StatefulWidget {
const ProfileEditPage({super.key});
@override
State<ProfileEditPage> createState() => _ProfileEditPageState();
}
class _ProfileEditPageState extends State<ProfileEditPage> {
bool _isUploadingAvatar = false;
@override
Widget build(BuildContext context) {
final auth = context.watch<AuthProvider>();
final user = auth.user;
return Scaffold(
appBar: AppBar(title: const Text('个人资料')),
body: DesktopConstrained(
child: ListView(
children: [
const SizedBox(height: 24),
_buildAvatarSection(context, user),
const SizedBox(height: 16),
_buildInfoTile(
context,
icon: Icons.badge_outlined,
title: '昵称',
value: user?.nickname ?? '',
onTap: () => _showEditNickDialog(context, user),
),
_buildInfoTile(
context,
icon: Icons.email_outlined,
title: '邮箱',
value: user?.email ?? '',
onTap: null, // 邮箱不可修改
),
_buildInfoTile(
context,
icon: Icons.group_outlined,
title: '用户组',
value: user?.group?.name ?? '',
onTap: null,
),
_buildInfoTile(
context,
icon: Icons.calendar_today_outlined,
title: '注册时间',
value: _formatDate(user?.createdAt),
onTap: null,
),
],
),
),
);
}
Widget _buildAvatarSection(BuildContext context, UserModel? user) {
final colorScheme = Theme.of(context).colorScheme;
return Center(
child: Stack(
children: [
_buildAvatar(context, user, 80),
Positioned(
right: 0,
bottom: 0,
child: Container(
decoration: BoxDecoration(
color: colorScheme.primary,
shape: BoxShape.circle,
border: Border.all(color: colorScheme.surface, width: 2),
),
child: _isUploadingAvatar
? Padding(
padding: const EdgeInsets.all(6),
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.onPrimary,
),
),
)
: IconButton(
icon: Icon(Icons.camera_alt, size: 16, color: colorScheme.onPrimary),
onPressed: _showAvatarOptions,
padding: const EdgeInsets.all(4),
constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
),
),
),
],
),
);
}
Widget _buildAvatar(BuildContext context, UserModel? user, double size) {
return UserAvatar(
userId: user?.id ?? '',
email: user?.email,
displayName: user?.nickname ?? '用户',
radius: size / 2,
);
}
Widget _buildInfoTile(
BuildContext context, {
required IconData icon,
required String title,
required String value,
VoidCallback? onTap,
}) {
return ListTile(
leading: Icon(icon),
title: Text(title),
subtitle: Text(value, style: Theme.of(context).textTheme.bodyMedium),
trailing: onTap != null ? const Icon(Icons.chevron_right) : null,
onTap: onTap,
);
}
Future<void> _showAvatarOptions() async {
final result = await showModalBottomSheet<String>(
context: context,
builder: (ctx) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.photo_library),
title: const Text('从相册选择'),
onTap: () => Navigator.of(ctx).pop('gallery'),
),
ListTile(
leading: const Icon(Icons.camera_alt),
title: const Text('拍照'),
onTap: () => Navigator.of(ctx).pop('camera'),
),
ListTile(
leading: const Icon(Icons.person_outline),
title: const Text('使用 Gravatar'),
subtitle: const Text('根据邮箱自动生成头像'),
onTap: () => Navigator.of(ctx).pop('gravatar'),
),
],
),
),
);
if (result == null || !mounted) return;
if (result == 'gravatar') {
await _resetToGravatar();
} else {
final source = result == 'camera' ? ImageSource.camera : ImageSource.gallery;
await _pickAndUploadAvatar(source);
}
}
Future<void> _pickAndUploadAvatar(ImageSource source) async {
try {
final picker = ImagePicker();
final image = await picker.pickImage(source: source, maxWidth: 512, maxHeight: 512);
if (image == null || !mounted) return;
setState(() => _isUploadingAvatar = true);
final bytes = await image.readAsBytes();
final service = UserSettingService.instance;
await service.updateAvatar(bytes);
if (!mounted) return;
// 刷新用户信息
await context.read<AuthProvider>().refreshUser();
// 清除头像缓存,使其他页面的 UserAvatar 刷新
if (!mounted) return;
final userId = context.read<AuthProvider>().user?.id ?? '';
await UserAvatar.evictCache(userId);
if (mounted) {
setState(() => _isUploadingAvatar = false);
ToastHelper.success('头像已更新');
}
} catch (e) {
if (mounted) {
setState(() => _isUploadingAvatar = false);
ToastHelper.failure('上传头像失败: $e');
}
}
}
Future<void> _resetToGravatar() async {
try {
setState(() => _isUploadingAvatar = true);
final service = UserSettingService.instance;
await service.updateAvatar(null);
if (!mounted) return;
await context.read<AuthProvider>().refreshUser();
if (!mounted) return;
// 清除头像缓存,使其他页面的 UserAvatar 刷新
final userId = context.read<AuthProvider>().user?.id ?? '';
await UserAvatar.evictCache(userId);
if (mounted) {
setState(() => _isUploadingAvatar = false);
ToastHelper.success('已切换为 Gravatar');
}
} catch (e) {
if (mounted) {
setState(() => _isUploadingAvatar = false);
ToastHelper.failure('操作失败: $e');
}
}
}
Future<void> _showEditNickDialog(BuildContext context, UserModel? user) async {
final controller = TextEditingController(text: user?.nickname ?? '');
final formKey = GlobalKey<FormState>();
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('修改昵称'),
content: Form(
key: formKey,
child: TextFormField(
controller: controller,
autofocus: true,
decoration: const InputDecoration(
labelText: '昵称',
hintText: '请输入新昵称',
),
validator: (v) {
if (v == null || v.trim().isEmpty) return '昵称不能为空';
if (v.trim().length > 255) return '昵称不能超过255个字符';
return null;
},
),
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.of(ctx).pop(true);
}
},
child: const Text('确定'),
),
],
),
);
if (confirmed != true || !mounted) return;
final newNick = controller.text.trim();
if (newNick == user?.nickname) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().updateNick(newNick);
if (!mounted) return;
if (!context.mounted) return;
if (success) {
// 同步刷新 AuthProvider 中的用户信息
await context.read<AuthProvider>().refreshUser();
ToastHelper.success('昵称已修改');
} else {
ToastHelper.failure('修改昵称失败');
}
}
String _formatDate(DateTime? date) {
if (date == null) return '';
return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}
}
@@ -0,0 +1,358 @@
import 'package:cloudreve4_flutter/core/constants/quick_access_defaults.dart';
import 'package:cloudreve4_flutter/services/storage_service.dart';
import 'package:cloudreve4_flutter/presentation/widgets/toast_helper.dart';
import 'package:flutter/material.dart';
import 'package:lucide_icons/lucide_icons.dart';
class QuickAccessSettingsPage extends StatefulWidget {
const QuickAccessSettingsPage({super.key});
@override
State<QuickAccessSettingsPage> createState() => _QuickAccessSettingsPageState();
}
class _QuickAccessSettingsPageState extends State<QuickAccessSettingsPage> {
List<QuickAccessConfig> _items = [];
bool _isLoaded = false;
@override
void initState() {
super.initState();
_loadConfig();
}
Future<void> _loadConfig() async {
var saved = await StorageService.instance.getString(QuickAccessConfig.storageKey);
if (saved != null && saved.isNotEmpty) {
try {
if (mounted) setState(() { _items = QuickAccessConfig.parseSaved(saved); _isLoaded = true; });
return;
} catch (_) {}
}
// 迁移 v1
final v1 = await StorageService.instance.getString('quick_access_shortcuts');
if (v1 != null && v1.isNotEmpty) {
final migrated = QuickAccessConfig.migrateV1(v1);
if (mounted) {
setState(() { _items = migrated; _isLoaded = true; });
await _save();
}
return;
}
if (mounted) setState(() { _items = List.from(QuickAccessConfig.defaults); _isLoaded = true; });
}
Future<void> _save() async {
await StorageService.instance.setString(
QuickAccessConfig.storageKey,
QuickAccessConfig.serialize(_items),
);
}
Future<void> _editItem(int index) async {
final item = _items[index];
final labelController = TextEditingController(text: item.label);
final pathController = TextEditingController(text: item.path);
final result = await showDialog<_EditResult>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('编辑快捷入口'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: labelController,
decoration: const InputDecoration(labelText: '名称', hintText: '例如: 图片'),
),
const SizedBox(height: 12),
TextField(
controller: pathController,
decoration: const InputDecoration(labelText: '目录路径', hintText: '例如: /Images'),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(_EditResult(labelController.text, pathController.text)),
child: const Text('确定'),
),
],
),
);
if (result != null) {
setState(() {
_items[index] = item.copyWith(
label: result.label.isNotEmpty ? result.label : item.label,
path: result.path.isNotEmpty ? result.path : item.path,
);
});
_save();
ToastHelper.success('快捷入口已更新');
}
}
Future<void> _addItem() async {
final labelController = TextEditingController();
final pathController = TextEditingController();
IconData selectedIcon = LucideIcons.folder;
Color selectedColor = QuickAccessConfig.colorPool[0];
final result = await showDialog<_AddResult>(
context: context,
builder: (ctx) {
return StatefulBuilder(
builder: (ctx, setDialogState) {
return AlertDialog(
title: const Text('新增快捷入口'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: labelController,
decoration: const InputDecoration(labelText: '名称', hintText: '例如: 图片'),
),
const SizedBox(height: 12),
TextField(
controller: pathController,
decoration: const InputDecoration(labelText: '目录路径', hintText: '例如: /Images'),
),
const SizedBox(height: 16),
Text('图标', style: Theme.of(ctx).textTheme.bodySmall?.copyWith(color: Theme.of(ctx).hintColor)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: QuickAccessConfig.iconPool.map((icon) {
final isSelected = icon.codePoint == selectedIcon.codePoint;
return GestureDetector(
onTap: () => setDialogState(() => selectedIcon = icon),
child: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: isSelected ? Theme.of(ctx).colorScheme.primary.withValues(alpha: 0.15) : null,
borderRadius: BorderRadius.circular(10),
border: isSelected
? Border.all(color: Theme.of(ctx).colorScheme.primary, width: 2)
: Border.all(color: Theme.of(ctx).dividerColor),
),
child: Icon(icon, size: 20, color: isSelected ? Theme.of(ctx).colorScheme.primary : Theme.of(ctx).hintColor),
),
);
}).toList(),
),
const SizedBox(height: 16),
Text('颜色', style: Theme.of(ctx).textTheme.bodySmall?.copyWith(color: Theme.of(ctx).hintColor)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: QuickAccessConfig.colorPool.map((color) {
final isSelected = color.toARGB32() == selectedColor.toARGB32();
return GestureDetector(
onTap: () => setDialogState(() => selectedColor = color),
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: color.withValues(alpha: 0.6),
borderRadius: BorderRadius.circular(10),
border: isSelected
? Border.all(color: color.darken(0.2), width: 3)
: null,
),
child: isSelected
? Icon(LucideIcons.check, size: 18, color: color.darken(0.3))
: null,
),
);
}).toList(),
),
],
),
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(_AddResult(
labelController.text,
pathController.text,
selectedIcon,
selectedColor,
)),
child: const Text('添加'),
),
],
);
},
);
},
);
if (result != null && result.label.isNotEmpty && result.path.isNotEmpty) {
setState(() {
_items.add(QuickAccessConfig(
id: 'custom_${DateTime.now().millisecondsSinceEpoch}',
label: result.label,
icon: result.icon,
path: result.path,
color: result.color,
));
});
_save();
ToastHelper.success('快捷入口已添加');
}
}
void _moveItem(int from, int to) {
if (from < 0 || from >= _items.length || to < 0 || to >= _items.length || from == to) return;
setState(() {
final item = _items.removeAt(from);
_items.insert(to, item);
});
_save();
}
void _deleteItem(int index) {
if (_items[index].isDefault) return;
setState(() {
_items.removeAt(index);
});
_save();
ToastHelper.success('快捷入口已删除');
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('快捷入口')),
body: ListView(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'自定义概览页中显示的快捷目录入口。默认入口不可删除,但可编辑路径和调整顺序。',
style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
),
),
if (_isLoaded)
...List.generate(_items.length, (index) {
final item = _items[index];
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: item.color.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(10),
),
child: Icon(item.icon, size: 20, color: item.color.darken(0.3)),
),
title: Row(
children: [
Text(item.label),
if (item.isDefault) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(4),
),
child: Text('默认', style: TextStyle(fontSize: 10, color: theme.colorScheme.primary, fontWeight: FontWeight.w600)),
),
],
],
),
subtitle: Text(item.path, style: TextStyle(color: theme.hintColor, fontSize: 12)),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
// 上移
IconButton(
icon: Icon(LucideIcons.chevronUp, size: 18),
onPressed: index > 0 ? () => _moveItem(index, index - 1) : null,
tooltip: '上移',
visualDensity: VisualDensity.compact,
),
// 下移
IconButton(
icon: Icon(LucideIcons.chevronDown, size: 18),
onPressed: index < _items.length - 1 ? () => _moveItem(index, index + 1) : null,
tooltip: '下移',
visualDensity: VisualDensity.compact,
),
// 编辑
IconButton(
icon: Icon(LucideIcons.pencil, size: 16),
onPressed: () => _editItem(index),
tooltip: '编辑',
visualDensity: VisualDensity.compact,
),
// 删除(默认不可删)
if (!item.isDefault)
IconButton(
icon: Icon(LucideIcons.trash2, size: 16, color: theme.colorScheme.error),
onPressed: () => _deleteItem(index),
tooltip: '删除',
visualDensity: VisualDensity.compact,
),
],
),
),
);
}),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(
child: FilledButton.icon(
icon: const Icon(LucideIcons.plus, size: 18),
label: const Text('新增快捷入口'),
onPressed: _addItem,
),
),
const SizedBox(width: 12),
OutlinedButton.icon(
icon: const Icon(LucideIcons.rotateCcw, size: 16),
label: const Text('恢复默认'),
onPressed: () {
setState(() { _items = List.from(QuickAccessConfig.defaults); });
_save();
ToastHelper.success('已恢复默认设置');
},
),
],
),
),
const SizedBox(height: 32),
],
),
);
}
}
class _EditResult {
final String label;
final String path;
_EditResult(this.label, this.path);
}
class _AddResult {
final String label;
final String path;
final IconData icon;
final Color color;
_AddResult(this.label, this.path, this.icon, this.color);
}
@@ -0,0 +1,601 @@
import 'dart:convert';
import 'package:cloudreve4_flutter/core/utils/app_logger.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../../data/models/user_setting_model.dart';
import '../../../services/user_setting_service.dart';
import '../../providers/auth_provider.dart';
import '../../providers/user_setting_provider.dart';
import '../../widgets/toast_helper.dart';
import '../../widgets/desktop_constrained.dart';
/// 安全设置页
class SecuritySettingsPage extends StatefulWidget {
const SecuritySettingsPage({super.key});
@override
State<SecuritySettingsPage> createState() => _SecuritySettingsPageState();
}
class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<UserSettingProvider>().loadSettings();
});
}
@override
Widget build(BuildContext context) {
final provider = context.watch<UserSettingProvider>();
final settings = provider.settings;
return Scaffold(
appBar: AppBar(title: const Text('安全设置')),
body: DesktopConstrained(
child: ListView(
children: [
_buildSection(
title: '密码',
children: [
ListTile(
leading: const Icon(Icons.lock_outline),
title: const Text('修改密码'),
subtitle: Text(settings?.passwordless == true ? '当前使用无密码登录' : '修改账户密码'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showChangePasswordDialog(context),
),
],
),
_buildSection(
title: '两步验证',
children: [
SwitchListTile(
secondary: Icon(
settings?.twoFaEnabled == true ? Icons.shield : Icons.shield_outlined,
),
title: const Text('两步验证 (2FA)'),
subtitle: Text(
settings?.twoFaEnabled == true ? '已启用 — 登录时需要验证码' : '未启用',
),
value: settings?.twoFaEnabled ?? false,
onChanged: (value) {
if (value) {
_showEnable2FADialog(context);
} else {
_showDisable2FADialog(context);
}
},
),
],
),
_buildSection(
title: 'Passkey',
children: [
ListTile(
leading: const Icon(Icons.vpn_key_outlined),
title: Text('Passkey (${settings?.passkeys.length ?? 0})'),
subtitle: settings?.passkeys.isEmpty ?? true
? const Text('未注册任何 Passkey')
: Text('已注册 ${settings!.passkeys.length} 个 Passkey'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showPasskeyList(context, settings),
),
],
),
_buildSection(
title: '已关联账号',
children: _buildOpenIdTiles(context, settings),
),
_buildSection(
title: '已授权应用',
children: _buildOAuthGrantTiles(context, settings),
),
if (settings?.loginActivity.isNotEmpty ?? false)
_buildSection(
title: '登录活动',
children: _buildLoginActivityTiles(settings!),
),
],
),
),
);
}
Widget _buildSection({required String title, required List<Widget> children}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
title,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
Card(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: Column(children: children),
),
],
),
);
}
// ---- 修改密码 ----
Future<void> _showChangePasswordDialog(BuildContext context) async {
final currentCtrl = TextEditingController();
final newCtrl = TextEditingController();
final confirmCtrl = TextEditingController();
final formKey = GlobalKey<FormState>();
bool obscureCurrent = true;
bool obscureNew = true;
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setDialogState) => AlertDialog(
title: const Text('修改密码'),
content: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: currentCtrl,
obscureText: obscureCurrent,
decoration: InputDecoration(
labelText: '当前密码',
suffixIcon: IconButton(
icon: Icon(obscureCurrent ? Icons.visibility_off : Icons.visibility),
onPressed: () => setDialogState(() => obscureCurrent = !obscureCurrent),
),
),
validator: (v) => (v == null || v.isEmpty) ? '请输入当前密码' : null,
),
const SizedBox(height: 12),
TextFormField(
controller: newCtrl,
obscureText: obscureNew,
decoration: InputDecoration(
labelText: '新密码',
suffixIcon: IconButton(
icon: Icon(obscureNew ? Icons.visibility_off : Icons.visibility),
onPressed: () => setDialogState(() => obscureNew = !obscureNew),
),
),
validator: (v) {
if (v == null || v.isEmpty) return '请输入新密码';
if (v.length < 6) return '密码至少6个字符';
if (v.length > 128) return '密码不能超过128个字符';
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: confirmCtrl,
obscureText: true,
decoration: const InputDecoration(labelText: '确认新密码'),
validator: (v) {
if (v != newCtrl.text) return '两次输入的密码不一致';
return null;
},
),
],
),
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.of(ctx).pop(true);
}
},
child: const Text('确定'),
),
],
),
),
);
if (confirmed != true || !mounted) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().changePassword(
currentPassword: currentCtrl.text,
newPassword: newCtrl.text,
);
if (!mounted) return;
if (success) {
ToastHelper.success('密码已修改');
} else {
ToastHelper.failure('修改密码失败,请检查当前密码是否正确');
}
}
// ---- 启用2FA ----
Future<void> _showEnable2FADialog(BuildContext context) async {
final codeCtrl = TextEditingController();
String secret = '';
try {
// 先获取 TOTP secret
final secretJsonString = await context.read<UserSettingProvider>().prepare2FA();
final Map<String, dynamic> secretMap = jsonDecode(secretJsonString!);
secret = secretMap['data'];
} catch (e) {
secret = e.toString();
}
AppLogger.d("2FA API Response --> $secret");
if (secret.isEmpty || !mounted) {
ToastHelper.failure('获取2FA密钥失败');
return;
}
if (!context.mounted) return;
final auth = context.read<AuthProvider>();
final userEmail = auth.user?.email ?? 'user';
final otpAuthUri = 'otpauth://totp/Cloudreve:$userEmail?secret=$secret&issuer=Cloudreve';
await showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('启用两步验证'),
content: SizedBox(
width: MediaQuery.of(ctx).size.width >= 1000 ? MediaQuery.of(ctx).size.width * 0.4 : MediaQuery.of(ctx).size.width * 0.8,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text('1. 使用验证器应用扫描二维码:'),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
),
child: QrImageView(
data: otpAuthUri,
version: QrVersions.auto,
size: 180,
backgroundColor: Colors.white,
),
),
const SizedBox(height: 12),
const Text('或手动输入密钥:'),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Theme.of(ctx).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: SelectableText(
textAlign: TextAlign.center,
secret,
style: const TextStyle(fontFamily: 'SourceCodePro', fontSize: 13),
),
),
const SizedBox(height: 16),
const Text('2. 输入验证器显示的6位验证码:'),
const SizedBox(height: 8),
TextField(
controller: codeCtrl,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
maxLength: 6,
autofocus: true,
decoration: const InputDecoration(
labelText: '验证码',
counterText: '',
),
),
],
),
),
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(), child: const Text('取消')),
FilledButton(
onPressed: () async {
final code = codeCtrl.text.trim();
if (code.length != 6) {
ToastHelper.warning('请输入6位验证码');
return;
}
Navigator.of(ctx).pop();
final success = await context.read<UserSettingProvider>().enable2FA(code);
if (!mounted) return;
if (success) {
ToastHelper.success('两步验证已启用');
} else {
ToastHelper.failure('启用失败,请检查验证码是否正确');
}
},
child: const Text('启用'),
),
],
),
);
}
// ---- 禁用2FA ----
Future<void> _showDisable2FADialog(BuildContext context) async {
final codeCtrl = TextEditingController();
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('禁用两步验证'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('请输入当前验证器显示的6位验证码以确认禁用:'),
const SizedBox(height: 12),
TextField(
controller: codeCtrl,
keyboardType: TextInputType.number,
maxLength: 6,
autofocus: true,
decoration: const InputDecoration(labelText: '验证码', counterText: ''),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
child: const Text('禁用'),
),
],
),
);
if (confirmed != true || !mounted) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().disable2FA(codeCtrl.text.trim());
if (!mounted) return;
if (success) {
ToastHelper.success('两步验证已禁用');
} else {
ToastHelper.failure('禁用失败,请检查验证码是否正确');
}
}
// ---- Passkey 列表 ----
void _showPasskeyList(BuildContext context, UserSettingModel? settings) {
final passkeys = settings?.passkeys ?? [];
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (ctx) => DraggableScrollableSheet(
initialChildSize: 0.4,
minChildSize: 0.2,
maxChildSize: 0.7,
expand: false,
builder: (ctx, controller) => ListView(
controller: controller,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text('Passkey 管理', style: Theme.of(ctx).textTheme.titleMedium),
),
if (passkeys.isEmpty)
const Padding(
padding: EdgeInsets.all(32),
child: Center(child: Text('暂无已注册的 Passkey', style: TextStyle(color: Colors.grey))),
)
else
...passkeys.map((pk) => ListTile(
leading: const Icon(Icons.vpn_key),
title: Text(pk.name),
subtitle: Text('创建于 ${_formatDate(pk.createdAt)}'
'${pk.usedAt != null ? ' · 最后使用 ${_formatDate(pk.usedAt!)}' : ''}'),
trailing: IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
onPressed: () => _deletePasskey(ctx, pk),
),
)),
// 注册新Passkey暂不实现,Flutter端WebAuthn支持有限
// 后续批次实现
],
),
),
);
}
Future<void> _deletePasskey(BuildContext context, PasskeyModel passkey) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('删除 Passkey'),
content: Text('确定要删除 "${passkey.name}" 吗?'),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
child: const Text('删除'),
),
],
),
);
if (confirmed != true || !mounted) return;
try {
await UserSettingService.instance.deletePasskey(passkey.id);
if (!context.mounted) return;
await context.read<UserSettingProvider>().loadSettings();
if (mounted) ToastHelper.success('Passkey 已删除');
} catch (e) {
if (mounted) ToastHelper.failure('删除失败: $e');
}
}
// ---- 已关联账号 ----
List<Widget> _buildOpenIdTiles(BuildContext context, UserSettingModel? settings) {
final openIds = settings?.openId ?? [];
if (openIds.isEmpty) {
return [
ListTile(
leading: const Icon(Icons.link_off),
title: const Text('暂无关联账号'),
subtitle: const Text('未关联任何第三方账号'),
),
];
}
return openIds
.map((oid) => ListTile(
leading: Icon(_openIdIcon(oid.provider)),
title: Text(oid.providerName),
subtitle: Text('关联于 ${_formatDate(oid.linkedAt)}'),
trailing: IconButton(
icon: const Icon(Icons.link_off, color: Colors.red),
onPressed: () => _unlinkOpenId(context, oid),
),
))
.toList();
}
Future<void> _unlinkOpenId(BuildContext context, OpenIdProvider oid) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('解绑账号'),
content: Text('确定要解绑 ${oid.providerName} 吗?'),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
child: const Text('解绑'),
),
],
),
);
if (confirmed != true || !mounted) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().unlinkOpenId(oid.provider);
if (!mounted) return;
if (success) {
ToastHelper.success('已解绑 ${oid.providerName}');
} else {
ToastHelper.failure('解绑失败');
}
}
IconData _openIdIcon(int provider) {
switch (provider) {
case 1:
return Icons.chat_bubble; // QQ
default:
return Icons.login;
}
}
// ---- OAuth 授权 ----
List<Widget> _buildOAuthGrantTiles(BuildContext context, UserSettingModel? settings) {
final grants = settings?.oauthGrants ?? [];
if (grants.isEmpty) {
return [
ListTile(
leading: const Icon(Icons.apps_outage),
title: const Text('暂无授权应用'),
subtitle: const Text('未授权任何第三方应用'),
),
];
}
return grants
.map((grant) => ListTile(
leading: grant.clientLogo != null
? CircleAvatar(backgroundImage: NetworkImage(grant.clientLogo!))
: const CircleAvatar(child: Icon(Icons.apps)),
title: Text(grant.clientName),
subtitle: Text(grant.lastUsedAt != null
? '最后使用 ${_formatDate(grant.lastUsedAt!)}'
: '权限: ${grant.scopes.join(", ")}'),
trailing: IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.red),
onPressed: () => _revokeOAuth(context, grant),
),
))
.toList();
}
Future<void> _revokeOAuth(BuildContext context, OAuthGrant grant) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('撤销授权'),
content: Text('确定要撤销 "${grant.clientName}" 的授权吗?'),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
child: const Text('撤销'),
),
],
),
);
if (confirmed != true || !mounted) return;
if (!context.mounted) return;
final success = await context.read<UserSettingProvider>().revokeOAuthGrant(grant.clientId);
if (!mounted) return;
if (success) {
ToastHelper.success('已撤销 ${grant.clientName} 的授权');
} else {
ToastHelper.failure('撤销授权失败');
}
}
// ---- 登录活动 ----
List<Widget> _buildLoginActivityTiles(UserSettingModel settings) {
final activities = settings.loginActivity;
if (activities.isEmpty) {
return [
const ListTile(
leading: Icon(Icons.history),
title: Text('暂无登录记录'),
),
];
}
return activities.map((activity) {
final icon = activity.success
? Icons.check_circle_outline
: Icons.cancel_outlined;
final iconColor = activity.success ? Colors.green : Colors.red;
return ListTile(
leading: Icon(icon, color: iconColor),
title: Text(activity.loginMethodName),
subtitle: Text(
'${_formatDate(activity.createdAt)}'
'\n${activity.os} · ${activity.browser}'
'${activity.ip.isNotEmpty ? " · ${activity.ip}" : ""}',
),
isThreeLine: true,
);
}).toList();
}
String _formatDate(DateTime date) {
return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}
}
@@ -0,0 +1,534 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../../../data/models/user_model.dart';
import '../../../data/models/user_setting_model.dart';
import '../../../services/user_setting_service.dart';
import '../../providers/auth_provider.dart';
import '../../providers/user_setting_provider.dart';
import '../../widgets/user_avatar.dart';
import '../../widgets/toast_helper.dart';
import '../../widgets/desktop_constrained.dart';
import 'profile_edit_page.dart';
import 'security_settings_page.dart';
import 'file_preferences_page.dart';
import 'app_settings_page.dart';
import 'credit_history_page.dart';
import 'quick_access_settings_page.dart';
/// 设置主页
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
String _appVersion = '';
@override
void initState() {
super.initState();
_loadAppVersion();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<UserSettingProvider>().loadAll();
});
}
Future<void> _loadAppVersion() async {
try {
final info = await PackageInfo.fromPlatform();
if (mounted) setState(() => _appVersion = info.version);
} catch (_) {}
}
Future<void> _refresh() async {
await context.read<UserSettingProvider>().loadAll();
}
@override
Widget build(BuildContext context) {
final auth = context.watch<AuthProvider>();
final user = auth.user;
final settingProvider = context.watch<UserSettingProvider>();
final settings = settingProvider.settings;
final capacity = settingProvider.capacity;
final isLoading = settingProvider.isLoading;
return Scaffold(
appBar: AppBar(
title: const Text('设置'),
actions: [
if (isLoading)
const Center(
child: Padding(
padding: EdgeInsets.only(right: 16),
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
)
else
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _refresh,
tooltip: '刷新',
),
],
),
body: DesktopConstrained(
child: ListView(
children: [
_buildProfileCard(context, user, settings, capacity),
const SizedBox(height: 8),
_buildSection(
title: '账户与安全',
children: [
_SettingsTile(
icon: Icons.person_outline,
title: '个人资料',
subtitle: '修改昵称、头像',
onTap: () => _navigateTo(context, const ProfileEditPage()),
),
_SettingsTile(
icon: Icons.security_outlined,
title: '安全设置',
subtitle: _securitySubtitle(settings),
onTap: () => _navigateTo(context, const SecuritySettingsPage()),
),
],
),
_buildSection(
title: '偏好',
children: [
_SettingsTile(
icon: Icons.apps_outlined,
title: '快捷入口',
subtitle: '自定义概览页快捷目录',
onTap: () => _navigateTo(context, const QuickAccessSettingsPage()),
),
_SettingsTile(
icon: Icons.folder_outlined,
title: '文件偏好',
subtitle: '版本保留、视图同步、分享可见性',
onTap: () => _navigateTo(context, const FilePreferencesPage()),
),
_SettingsTile(
icon: Icons.tune,
title: '应用设置',
subtitle: '缓存、主题、语言',
onTap: () => _navigateTo(context, const AppSettingsPage()),
),
],
),
// 财务区域(有数据时才显示)
if (settings != null) ..._buildProSections(context, settings),
_buildSection(
title: '关于',
children: [
ListTile(
leading: const Icon(Icons.info_outline),
title: const Text('应用名称'),
subtitle: const Text('公云存储'),
),
ListTile(
leading: const Icon(Icons.tag),
title: const Text('版本号'),
subtitle: Text(_appVersion.isEmpty ? '加载中...' : _appVersion),
),
ListTile(
leading: const Icon(Icons.copyright),
title: const Text('License'),
subtitle: const Text('AGPL-3.0'),
),
ListTile(
leading: const Icon(Icons.code),
title: const Text('二次开发'),
subtitle: const Text('gongyun_app'),
trailing: const Icon(Icons.open_in_new, size: 16),
onTap: () {
launchUrl(
Uri.parse('https://git.saont.net/gongyun/app'),
mode: LaunchMode.externalApplication,
);
},
),
ListTile(
leading: const Icon(Icons.code),
title: const Text('基于'),
subtitle: const Text('cloudreve4_flutter'),
trailing: const Icon(Icons.open_in_new, size: 16),
onTap: () {
launchUrl(
Uri.parse('https://github.com/LimoYuan/cloudreve4_flutter'),
mode: LaunchMode.externalApplication,
);
},
),
],
),
const SizedBox(height: 24),
_buildLogoutButton(context, auth),
const SizedBox(height: 32),
],
),
),
);
}
/// 财务区域(存储包、积分、会员)
List<Widget> _buildProSections(BuildContext context, UserSettingModel settings) {
final sections = <Widget>[];
final hasStoragePacks = settings.storagePacks.isNotEmpty;
final hasCredit = settings.credit > 0;
final hasMembership = settings.groupExpires != null;
if (hasStoragePacks || hasCredit || hasMembership) {
final children = <Widget>[];
if (hasMembership) {
children.add(ListTile(
leading: const Icon(Icons.workspace_premium_outlined),
title: const Text('会员'),
subtitle: Text('到期: ${_formatDate(settings.groupExpires!)}'),
trailing: TextButton(
onPressed: () => _cancelMembership(context),
child: const Text('取消会员', style: TextStyle(color: Colors.red)),
),
));
}
if (hasStoragePacks) {
children.add(ListTile(
leading: const Icon(Icons.inventory_2_outlined),
title: Text('存储包 (${settings.storagePacks.length})'),
subtitle: Text(_storagePackSummary(settings.storagePacks)),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showStoragePacks(context, settings.storagePacks),
));
}
if (hasCredit) {
children.add(ListTile(
leading: const Icon(Icons.account_balance_wallet_outlined),
title: const Text('积分'),
subtitle: Text('${settings.credit} 积分'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _navigateTo(context, CreditHistoryPage(currentCredit: settings.credit)),
));
}
sections.add(_buildSection(title: '财务', children: children));
}
return sections;
}
Widget _buildProfileCard(BuildContext context, UserModel? user, UserSettingModel? settings, UserCapacityModel? capacity) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: InkWell(
onTap: () => _navigateTo(context, const ProfileEditPage()),
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Row(
children: [
_buildAvatar(context, user, 56),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
user?.nickname ?? '未登录',
style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 2),
Text(
user?.email ?? '',
style: theme.textTheme.bodySmall?.copyWith(color: colorScheme.onSurfaceVariant),
),
if (user?.group != null) ...[
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Text(
user!.group!.name,
style: theme.textTheme.labelSmall?.copyWith(
color: colorScheme.onPrimaryContainer,
),
),
),
],
],
),
),
const Icon(Icons.chevron_right),
],
),
if (capacity != null) ...[
const SizedBox(height: 16),
_buildStorageBar(context, capacity),
],
],
),
),
),
);
}
Widget _buildAvatar(BuildContext context, UserModel? user, double size) {
return UserAvatar(
userId: user?.id ?? '',
email: user?.email,
displayName: user?.nickname ?? '用户',
radius: size / 2,
);
}
Widget _buildStorageBar(BuildContext context, UserCapacityModel capacity) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final usedText = _formatBytes(capacity.used);
final totalText = _formatBytes(capacity.total);
final percent = capacity.usagePercentage;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('存储空间', style: theme.textTheme.bodySmall),
Text('$usedText / $totalText', style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
)),
],
),
const SizedBox(height: 6),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: (percent / 100).clamp(0.0, 1.0),
minHeight: 6,
backgroundColor: colorScheme.surfaceContainerHighest,
),
),
],
);
}
Widget _buildSection({required String title, required List<Widget> children}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
title,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
Card(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: Column(children: children),
),
],
),
);
}
Widget _buildLogoutButton(BuildContext context, AuthProvider auth) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: OutlinedButton.icon(
onPressed: () => _confirmLogout(context, auth),
icon: Icon(Icons.logout, color: Theme.of(context).colorScheme.error),
label: Text('退出登录', style: TextStyle(color: Theme.of(context).colorScheme.error)),
style: OutlinedButton.styleFrom(
minimumSize: const Size(double.infinity, 48),
side: BorderSide(color: Theme.of(context).colorScheme.error.withValues(alpha: 0.3)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
);
}
String _securitySubtitle(UserSettingModel? settings) {
if (settings == null) return '';
final items = <String>[];
if (settings.twoFaEnabled) items.add('2FA已启用');
if (settings.passwordless) items.add('无密码登录');
return items.isEmpty ? '密码、2FA' : items.join('');
}
// ---- 存储包 ----
String _storagePackSummary(List<StoragePack> packs) {
final total = packs.fold<int>(0, (sum, p) => sum + p.size);
return '${_formatBytes(total)} · ${packs.length} 个存储包';
}
void _showStoragePacks(BuildContext context, List<StoragePack> packs) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (ctx) => DraggableScrollableSheet(
initialChildSize: 0.5,
minChildSize: 0.3,
maxChildSize: 0.8,
expand: false,
builder: (ctx, controller) => ListView(
controller: controller,
padding: const EdgeInsets.symmetric(horizontal: 16),
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text('存储包', style: Theme.of(ctx).textTheme.titleMedium),
),
...packs.map((pack) => Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(pack.name, style: Theme.of(ctx).textTheme.titleSmall),
Text(_formatBytes(pack.size), style: Theme.of(ctx).textTheme.labelLarge),
],
),
const SizedBox(height: 4),
Text(
'激活: ${_formatDate(pack.activeSince)}'
'${pack.expireAt != null ? " · 到期: ${_formatDate(pack.expireAt!)}" : " · 永久"}',
style: Theme.of(ctx).textTheme.bodySmall,
),
if (pack.isExpired) ...[
const SizedBox(height: 4),
Text('已过期', style: TextStyle(color: Theme.of(ctx).colorScheme.error, fontSize: 12)),
],
],
),
),
)),
const SizedBox(height: 16),
],
),
),
);
}
// ---- 取消会员 ----
Future<void> _cancelMembership(BuildContext context) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('取消会员'),
content: const Text('确定要取消当前会员吗?取消后将失去会员权益。'),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
child: const Text('确认取消'),
),
],
),
);
if (confirmed != true || !mounted) return;
try {
await UserSettingService.instance.updateUserSetting(groupExpires: true);
if (!context.mounted) return;
await context.read<UserSettingProvider>().loadSettings();
if (mounted) ToastHelper.success('会员已取消');
} catch (e) {
if (mounted) ToastHelper.failure('取消会员失败: $e');
}
}
Future<void> _navigateTo(BuildContext context, Widget page) async {
await Navigator.of(context).push(MaterialPageRoute(builder: (_) => page));
if (!context.mounted) return;
if (mounted) {
context.read<UserSettingProvider>().loadAll();
}
}
Future<void> _confirmLogout(BuildContext context, AuthProvider auth) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('退出登录'),
content: const Text('确定要退出当前账号吗?'),
actions: [
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.error),
child: const Text('退出'),
),
],
),
);
if (confirmed == true && mounted) {
await auth.logout();
if (!context.mounted) return;
Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false);
}
}
String _formatBytes(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
}
String _formatDate(DateTime date) {
return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}
}
class _SettingsTile extends StatelessWidget {
final IconData icon;
final String title;
final String subtitle;
final VoidCallback onTap;
const _SettingsTile({
required this.icon,
required this.title,
required this.subtitle,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return ListTile(
leading: Icon(icon),
title: Text(title),
subtitle: Text(subtitle, style: Theme.of(context).textTheme.bodySmall),
trailing: const Icon(Icons.chevron_right),
onTap: onTap,
);
}
}