This commit is contained in:
DelLevin-Home
2026-03-07 23:20:24 +08:00
parent dc513fb6f6
commit d28c5e562e
24 changed files with 1983 additions and 636 deletions

View File

@@ -4,6 +4,7 @@ import 'pages/home_page.dart';
import 'utils/app_theme.dart'; import 'utils/app_theme.dart';
import 'utils/app_router.dart'; import 'utils/app_router.dart';
import 'utils/user_prefs.dart'; import 'utils/user_prefs.dart';
import 'utils/webdav_service.dart';
import 'providers/app_provider.dart'; import 'providers/app_provider.dart';
void main() async { void main() async {
@@ -17,9 +18,24 @@ void main() async {
final appProvider = AppProvider(); final appProvider = AppProvider();
await appProvider.initDatabase(); await appProvider.initDatabase();
// 检查并恢复自动备份
await _initAutoBackup();
runApp(MyApp(appProvider: appProvider)); runApp(MyApp(appProvider: appProvider));
} }
/// 初始化自动备份
Future<void> _initAutoBackup() async {
try {
final isEnabled = await WebDAVService.instance.isAutoSyncEnabled();
if (isEnabled) {
await WebDAVService.instance.startAutoSync();
}
} catch (e) {
print('初始化自动备份失败: $e');
}
}
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
final AppProvider appProvider; final AppProvider appProvider;

View File

@@ -273,8 +273,9 @@ class Book {
class Note { class Note {
final String id; final String id;
final String content; final String content;
final String contentType; // markdown / rich_text final String contentType; // markdown / plain_text
final List<String> tags; final List<String> tags;
final List<String> images; // 图片路径列表
final DateTime createdAt; final DateTime createdAt;
final DateTime updatedAt; final DateTime updatedAt;
final bool isDeleted; final bool isDeleted;
@@ -284,6 +285,7 @@ class Note {
required this.content, required this.content,
this.contentType = 'markdown', this.contentType = 'markdown',
this.tags = const [], this.tags = const [],
this.images = const [],
required this.createdAt, required this.createdAt,
required this.updatedAt, required this.updatedAt,
this.isDeleted = false, this.isDeleted = false,
@@ -295,6 +297,7 @@ class Note {
content: json['content'] ?? '', content: json['content'] ?? '',
contentType: json['content_type'] ?? 'markdown', contentType: json['content_type'] ?? 'markdown',
tags: Movie.parseStringList(json['tags']), tags: Movie.parseStringList(json['tags']),
images: Movie.parseStringList(json['images']),
createdAt: json['created_at'] != null createdAt: json['created_at'] != null
? DateTime.parse(json['created_at']) ? DateTime.parse(json['created_at'])
: DateTime.now(), : DateTime.now(),
@@ -311,6 +314,7 @@ class Note {
'content': content, 'content': content,
'content_type': contentType, 'content_type': contentType,
'tags': jsonEncode(tags), 'tags': jsonEncode(tags),
'images': jsonEncode(images),
'created_at': createdAt.toIso8601String(), 'created_at': createdAt.toIso8601String(),
'updated_at': updatedAt.toIso8601String(), 'updated_at': updatedAt.toIso8601String(),
'is_deleted': isDeleted ? 1 : 0, 'is_deleted': isDeleted ? 1 : 0,
@@ -323,6 +327,7 @@ class Note {
String? content, String? content,
String? contentType, String? contentType,
List<String>? tags, List<String>? tags,
List<String>? images,
DateTime? createdAt, DateTime? createdAt,
DateTime? updatedAt, DateTime? updatedAt,
bool? isDeleted, bool? isDeleted,
@@ -332,6 +337,7 @@ class Note {
content: content ?? this.content, content: content ?? this.content,
contentType: contentType ?? this.contentType, contentType: contentType ?? this.contentType,
tags: tags ?? this.tags, tags: tags ?? this.tags,
images: images ?? this.images,
createdAt: createdAt ?? this.createdAt, createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt, updatedAt: updatedAt ?? this.updatedAt,
isDeleted: isDeleted ?? this.isDeleted, isDeleted: isDeleted ?? this.isDeleted,

View File

@@ -5,7 +5,7 @@ import '../providers/app_provider.dart';
import '../utils/backup_service.dart'; import '../utils/backup_service.dart';
import '../utils/toast_util.dart'; import '../utils/toast_util.dart';
/// 数据备份页面 /// 本地备份页面
class BackupPage extends StatefulWidget { class BackupPage extends StatefulWidget {
const BackupPage({super.key}); const BackupPage({super.key});
@@ -22,7 +22,7 @@ class _BackupPageState extends State<BackupPage> {
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
appBar: AppBar( appBar: AppBar(
title: const Text('数据备份'), title: const Text('本地备份'),
), ),
body: ListView( body: ListView(
padding: const EdgeInsets.all(24), padding: const EdgeInsets.all(24),

View File

@@ -2,11 +2,12 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as p;
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../utils/toast_util.dart'; import '../utils/toast_util.dart';
import '../utils/image_path_helper.dart';
/// 添加/编辑书籍页面 - 紧凑双行布局设计 /// 添加/编辑书籍页面 - 紧凑双行布局设计
class BookFormPage extends StatefulWidget { class BookFormPage extends StatefulWidget {
@@ -649,18 +650,22 @@ class _BookFormPageState extends State<BookFormPage> {
); );
if (pickedFile != null) { if (pickedFile != null) {
final appDir = await getApplicationDocumentsDirectory(); // 生成文件名
final fileName = 'book_cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg';
final savedPath = path.join(appDir.path, 'book_covers', fileName);
final coverDir = Directory(path.join(appDir.path, 'book_covers')); // 如果是编辑模式使用现有书籍ID如果是新建模式使用临时ID保存时会替换
if (!await coverDir.exists()) { final bookId = widget.book?.id ?? DateTime.now().millisecondsSinceEpoch.toString();
await coverDir.create(recursive: true);
}
await File(pickedFile.path).copy(savedPath); // 保存到新的路径结构: images/books/{bookId}/{fileName}
final targetPath = await ImagePathHelper.instance.getBookCoverPath(
bookId,
fileName
);
await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath));
setState(() => _coverPath = savedPath); await File(pickedFile.path).copy(targetPath);
setState(() => _coverPath = targetPath);
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
@@ -682,10 +687,19 @@ class _BookFormPageState extends State<BookFormPage> {
final now = DateTime.now(); final now = DateTime.now();
if (widget.book == null) { if (widget.book == null) {
// 生成新的书籍ID
final newBookId = now.millisecondsSinceEpoch.toString();
// 如果有封面需要移动到正确的ID目录
String? finalCoverPath;
if (_coverPath != null && _coverPath!.isNotEmpty) {
finalCoverPath = await _moveCoverToNewId(_coverPath!, newBookId);
}
final newBook = Book( final newBook = Book(
id: now.millisecondsSinceEpoch.toString(), id: newBookId,
title: _titleController.text.trim(), title: _titleController.text.trim(),
coverPath: _coverPath, coverPath: finalCoverPath,
authors: _authors, authors: _authors,
alternateTitles: _alternateTitles, alternateTitles: _alternateTitles,
publisher: _publisherController.text.trim(), publisher: _publisherController.text.trim(),
@@ -721,4 +735,45 @@ class _BookFormPageState extends State<BookFormPage> {
Navigator.pop(context); Navigator.pop(context);
} }
/// 将封面从临时ID目录移动到新的书籍ID目录
Future<String?> _moveCoverToNewId(String currentPath, String newBookId) async {
// 检查是否已经在正确的目录中(兼容 Windows 路径分隔符)
final normalizedPath = currentPath.replaceAll('\\', '/');
if (normalizedPath.contains('/books/$newBookId/')) {
return currentPath;
}
// 提取文件名
final fileName = p.basename(currentPath);
// 获取新路径
final newPath = await ImagePathHelper.instance.getBookCoverPath(
newBookId,
fileName
);
// 确保目标目录存在
await ImagePathHelper.instance.ensureDirExists(p.dirname(newPath));
// 移动文件
final currentFile = File(currentPath);
if (await currentFile.exists()) {
await currentFile.rename(newPath);
// 删除空的临时目录
final tempDir = Directory(p.dirname(currentPath));
if (await tempDir.exists()) {
try {
await tempDir.delete(recursive: true);
} catch (e) {
// 忽略删除目录失败的情况
}
}
return newPath;
}
return null;
}
} }

View File

@@ -106,7 +106,9 @@ class _BookReviewsPageState extends State<BookReviewsPage> {
} }
Widget _buildReviewItem(BookReview review) { Widget _buildReviewItem(BookReview review) {
return Container( return InkWell(
onLongPress: () => _showDeleteDialog(review),
child: Container(
margin: const EdgeInsets.only(bottom: 16), margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -209,6 +211,7 @@ class _BookReviewsPageState extends State<BookReviewsPage> {
), ),
], ],
), ),
),
); );
} }

View File

@@ -1,7 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'webdav_sync_page.dart'; import 'webdav_sync_page.dart';
/// 云同步主页面 - 选择同步方式 /// 云备份主页面 - 选择备份方式
class CloudSyncPage extends StatelessWidget { class CloudSyncPage extends StatelessWidget {
const CloudSyncPage({super.key}); const CloudSyncPage({super.key});
@@ -10,17 +10,17 @@ class CloudSyncPage extends StatelessWidget {
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
appBar: AppBar( appBar: AppBar(
title: const Text('同步'), title: const Text('备份'),
), ),
body: ListView( body: ListView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
children: [ children: [
// WebDAV 同步选项 // WebDAV 备份选项
_buildSyncOption( _buildSyncOption(
context, context,
icon: Icons.storage_outlined, icon: Icons.storage_outlined,
title: 'WebDAV 同步', title: 'WebDAV 备份',
subtitle: '通过 WebDAV 协议同步到个人云盘如坚果云、Nextcloud 等)', subtitle: '通过 WebDAV 协议备份到个人云盘如坚果云、Nextcloud 等)',
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,
@@ -56,7 +56,7 @@ class CloudSyncPage extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'关于云同步', '关于云备份',
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@@ -65,10 +65,10 @@ class CloudSyncPage extends StatelessWidget {
), ),
SizedBox(height: 8), SizedBox(height: 8),
Text( Text(
'• 云同步可以将您的数据备份到远程服务器\n' '• 云备份可以将您的数据备份到远程服务器\n'
'• 支持多台设备之间的数据同步\n' '• 支持多台设备之间的数据恢复\n'
'• 建议定期进行云同步以确保数据安全\n' '• 建议定期进行云备份以确保数据安全\n'
'• 首次同步可能需要较长时间,请保持网络连接', '• 首次备份可能需要较长时间,请保持网络连接',
style: TextStyle( style: TextStyle(
fontSize: 13, fontSize: 13,
color: Color(0xFF666666), color: Color(0xFF666666),

View File

@@ -7,12 +7,12 @@ import 'note_tab_page.dart';
import 'search_page.dart'; import 'search_page.dart';
import 'webdav_sync_page.dart'; import 'webdav_sync_page.dart';
import '../utils/webdav_service.dart'; import '../utils/webdav_service.dart';
import '../utils/toast_util.dart';
/// 云同步模式 /// 云备份模式
enum SyncMode { enum SyncMode {
bidirectional, // 双向同步 uploadOnly, // 上传
uploadOnly, // 仅上传 downloadOnly, // 下载
downloadOnly, // 仅下载
} }
/// 主内容页 - 观影/阅读/笔记标签页 /// 主内容页 - 观影/阅读/笔记标签页
@@ -44,11 +44,11 @@ class MainContentPage extends StatelessWidget {
return AppBar( return AppBar(
title: Text(_getAppBarTitle(provider)), title: Text(_getAppBarTitle(provider)),
actions: [ actions: [
// 云同步按钮 // 云备份按钮
IconButton( IconButton(
icon: const Icon(Icons.cloud_sync_outlined), icon: const Icon(Icons.cloud_sync_outlined),
onPressed: () => _showCloudSyncDialog(context, provider), onPressed: () => _showCloudSyncDialog(context, provider),
tooltip: '同步', tooltip: '备份',
), ),
// 搜索按钮 // 搜索按钮
IconButton( IconButton(
@@ -248,7 +248,7 @@ class MainContentPage extends StatelessWidget {
), ),
), ),
child: const Text( child: const Text(
'同步', '备份',
style: TextStyle( style: TextStyle(
fontSize: 17, fontSize: 17,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@@ -260,27 +260,19 @@ class MainContentPage extends StatelessWidget {
// 同步选项 // 同步选项
Column( Column(
children: [ children: [
_buildSyncOption(
context,
icon: Icons.sync,
iconColor: const Color(0xFF1A1A1A),
title: '双向同步',
subtitle: '本地和云端数据合并,冲突时以最新为准',
onTap: () {
Navigator.pop(context);
_navigateToSync(context, SyncMode.bidirectional);
},
),
const Divider(height: 0.5, indent: 56, color: Color(0xFFE5E5E5)),
_buildSyncOption( _buildSyncOption(
context, context,
icon: Icons.cloud_upload, icon: Icons.cloud_upload,
iconColor: const Color(0xFF1A1A1A), iconColor: const Color(0xFF1A1A1A),
title: '上传', title: '上传',
subtitle: '将本地数据上传到云端,覆盖云端数据', subtitle: '将本地数据备份到云端',
onTap: () { onTap: () async {
Navigator.pop(context); Navigator.pop(context);
// 等待对话框关闭
await Future.delayed(const Duration(milliseconds: 100));
if (context.mounted) {
_navigateToSync(context, SyncMode.uploadOnly); _navigateToSync(context, SyncMode.uploadOnly);
}
}, },
), ),
const Divider(height: 0.5, indent: 56, color: Color(0xFFE5E5E5)), const Divider(height: 0.5, indent: 56, color: Color(0xFFE5E5E5)),
@@ -288,11 +280,15 @@ class MainContentPage extends StatelessWidget {
context, context,
icon: Icons.cloud_download, icon: Icons.cloud_download,
iconColor: const Color(0xFF1A1A1A), iconColor: const Color(0xFF1A1A1A),
title: '下载', title: '下载',
subtitle: '从云端下载数据到本地,覆盖本地数据', subtitle: '从云端恢复数据到本地',
onTap: () { onTap: () async {
Navigator.pop(context); Navigator.pop(context);
// 等待对话框关闭
await Future.delayed(const Duration(milliseconds: 100));
if (context.mounted) {
_navigateToSync(context, SyncMode.downloadOnly); _navigateToSync(context, SyncMode.downloadOnly);
}
}, },
), ),
], ],
@@ -395,30 +391,35 @@ class MainContentPage extends StatelessWidget {
); );
} }
/// 导航到同步页面 /// 执行云备份操作
void _navigateToSync(BuildContext context, SyncMode mode) { Future<void> _navigateToSync(BuildContext context, SyncMode mode) async {
// TODO: 打开 WebDAV 同步页面并传递同步模式 // 执行同步
// Navigator.push( final direction = mode == SyncMode.uploadOnly
// context, ? SyncDirection.upload
// MaterialPageRoute( : SyncDirection.download;
// builder: (context) => WebDAVSyncPage(syncMode: mode),
// ),
// );
// 暂时显示提示 final result = await WebDAVService.instance.syncData(direction: direction);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar( if (!context.mounted) return;
content: Text('即将开始${_getSyncModeText(mode)}...'),
duration: const Duration(seconds: 2), if (result.success) {
), // 如果需要重新加载数据(下载模式)
); if (result.needReload) {
final provider = context.read<AppProvider>();
await provider.loadMovies();
await provider.loadBooks();
await provider.loadNotes();
}
ToastUtil.show(context, '${_getSyncModeText(mode)}成功');
} else {
ToastUtil.show(context, '${_getSyncModeText(mode)}失败: ${result.message}');
}
} }
/// 获取同步模式文本 /// 获取同步模式文本
String _getSyncModeText(SyncMode mode) { String _getSyncModeText(SyncMode mode) {
switch (mode) { switch (mode) {
case SyncMode.bidirectional:
return '双向同步';
case SyncMode.uploadOnly: case SyncMode.uploadOnly:
return '上传'; return '上传';
case SyncMode.downloadOnly: case SyncMode.downloadOnly:

View File

@@ -2,11 +2,12 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as p;
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../utils/toast_util.dart'; import '../utils/toast_util.dart';
import '../utils/image_path_helper.dart';
/// 添加/编辑影视页面 - 紧凑双行布局设计 /// 添加/编辑影视页面 - 紧凑双行布局设计
class MovieFormPage extends StatefulWidget { class MovieFormPage extends StatefulWidget {
@@ -691,18 +692,22 @@ class _MovieFormPageState extends State<MovieFormPage> {
); );
if (pickedFile != null) { if (pickedFile != null) {
final appDir = await getApplicationDocumentsDirectory(); // 生成文件名
final fileName = 'movie_poster_${DateTime.now().millisecondsSinceEpoch}.jpg'; final fileName = 'poster_${DateTime.now().millisecondsSinceEpoch}.jpg';
final savedPath = path.join(appDir.path, 'movie_posters', fileName);
final posterDir = Directory(path.join(appDir.path, 'movie_posters')); // 如果是编辑模式使用现有影视ID如果是新建模式使用临时ID保存时会替换
if (!await posterDir.exists()) { final movieId = widget.movie?.id ?? DateTime.now().millisecondsSinceEpoch.toString();
await posterDir.create(recursive: true);
}
await File(pickedFile.path).copy(savedPath); // 保存到新的路径结构: images/movies/{movieId}/{fileName}
final targetPath = await ImagePathHelper.instance.getMoviePosterPath(
movieId,
fileName
);
await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath));
setState(() => _posterPath = savedPath); await File(pickedFile.path).copy(targetPath);
setState(() => _posterPath = targetPath);
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
@@ -748,10 +753,19 @@ class _MovieFormPageState extends State<MovieFormPage> {
final now = DateTime.now(); final now = DateTime.now();
if (widget.movie == null) { if (widget.movie == null) {
// 生成新的影视ID
final newMovieId = now.millisecondsSinceEpoch.toString();
// 如果有海报需要移动到正确的ID目录
String? finalPosterPath;
if (_posterPath != null && _posterPath!.isNotEmpty) {
finalPosterPath = await _movePosterToNewId(_posterPath!, newMovieId);
}
final newMovie = Movie( final newMovie = Movie(
id: now.millisecondsSinceEpoch.toString(), id: newMovieId,
title: _titleController.text.trim(), title: _titleController.text.trim(),
posterPath: _posterPath, posterPath: finalPosterPath,
releaseDate: _releaseDate, releaseDate: _releaseDate,
directors: _directors, directors: _directors,
writers: _writers, writers: _writers,
@@ -791,4 +805,45 @@ class _MovieFormPageState extends State<MovieFormPage> {
Navigator.pop(context); Navigator.pop(context);
} }
/// 将海报从临时ID目录移动到新的影视ID目录
Future<String?> _movePosterToNewId(String currentPath, String newMovieId) async {
// 检查是否已经在正确的目录中(兼容 Windows 路径分隔符)
final normalizedPath = currentPath.replaceAll('\\', '/');
if (normalizedPath.contains('/movies/$newMovieId/')) {
return currentPath;
}
// 提取文件名
final fileName = p.basename(currentPath);
// 获取新路径
final newPath = await ImagePathHelper.instance.getMoviePosterPath(
newMovieId,
fileName
);
// 确保目标目录存在
await ImagePathHelper.instance.ensureDirExists(p.dirname(newPath));
// 移动文件
final currentFile = File(currentPath);
if (await currentFile.exists()) {
await currentFile.rename(newPath);
// 删除空的临时目录
final tempDir = Directory(p.dirname(currentPath));
if (await tempDir.exists()) {
try {
await tempDir.delete(recursive: true);
} catch (e) {
// 忽略删除目录失败的情况
}
}
return newPath;
}
return null;
}
} }

View File

@@ -3,12 +3,13 @@ import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as p;
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../utils/toast_util.dart'; import '../utils/toast_util.dart';
import '../utils/image_path_helper.dart';
import 'poster_gallery_page.dart'; import 'poster_gallery_page.dart';
/// 影视海报墙页面 /// 影视海报墙页面
@@ -197,21 +198,22 @@ class _MoviePostersPageState extends State<MoviePostersPage> {
); );
if (pickedFile != null) { if (pickedFile != null) {
final appDir = await getApplicationDocumentsDirectory(); // 生成文件名
final fileName = 'movie_poster_${DateTime.now().millisecondsSinceEpoch}.jpg'; final fileName = 'posterimg_${DateTime.now().millisecondsSinceEpoch}.jpg';
final savedPath = path.join(appDir.path, 'movie_posters', fileName);
final posterDir = Directory(path.join(appDir.path, 'movie_posters')); // 保存到 posterimgs 子目录: images/movies/{movieId}/posterimgs/{fileName}
if (!await posterDir.exists()) { final targetPath = await ImagePathHelper.instance.getMoviePosterImgPath(
await posterDir.create(recursive: true); widget.movie.id,
} fileName
);
await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath));
await File(pickedFile.path).copy(savedPath); await File(pickedFile.path).copy(targetPath);
final newPoster = MoviePoster( final newPoster = MoviePoster(
id: DateTime.now().millisecondsSinceEpoch.toString(), id: DateTime.now().millisecondsSinceEpoch.toString(),
movieId: widget.movie.id, movieId: widget.movie.id,
posterPath: savedPath, posterPath: targetPath,
createdAt: DateTime.now(), createdAt: DateTime.now(),
); );

View File

@@ -101,7 +101,9 @@ class _MovieReviewsPageState extends State<MovieReviewsPage> {
} }
Widget _buildReviewItem(MovieReview review) { Widget _buildReviewItem(MovieReview review) {
return Container( return InkWell(
onLongPress: () => _showDeleteDialog(review),
child: Container(
margin: const EdgeInsets.only(bottom: 16), margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -204,6 +206,7 @@ class _MovieReviewsPageState extends State<MovieReviewsPage> {
), ),
], ],
), ),
),
); );
} }

View File

@@ -1,3 +1,4 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -18,33 +19,50 @@ class NoteDetailPage extends StatefulWidget {
class _NoteDetailPageState extends State<NoteDetailPage> { class _NoteDetailPageState extends State<NoteDetailPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// 从 Provider 获取最新的笔记数据
final note = context.watch<AppProvider>().notes.firstWhere(
(n) => n.id == widget.note.id,
orElse: () => widget.note,
);
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
appBar: AppBar( appBar: AppBar(
title: Text(_formatDateTime(widget.note.createdAt)), title: Text(_getTitle(note.content)),
actions: [ actions: [
// 格式指示器 // 格式指示器 - 纯文本标记
if (widget.note.contentType == 'markdown') if (note.contentType == 'markdown')
Container( Container(
margin: const EdgeInsets.only(right: 8), margin: const EdgeInsets.only(right: 8),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration( decoration: BoxDecoration(
color: const Color(0xFFF5F5F5), color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)), borderRadius: BorderRadius.circular(2),
), ),
child: const Row( child: const Text(
mainAxisSize: MainAxisSize.min, 'MD',
children: [
Icon(Icons.code, size: 14, color: Color(0xFF666666)),
SizedBox(width: 4),
Text(
'Markdown',
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 10,
fontWeight: FontWeight.w500,
color: Color(0xFF666666), color: Color(0xFF666666),
), ),
), ),
], )
else
Container(
margin: const EdgeInsets.only(right: 8),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(2),
),
child: const Text(
'TXT',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w500,
color: Color(0xFF666666),
),
), ),
), ),
IconButton( IconButton(
@@ -57,9 +75,9 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
body: Column( body: Column(
children: [ children: [
// 标签区域 // 标签区域
if (widget.note.tags.isNotEmpty) if (note.tags.isNotEmpty)
Container( Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: const BoxDecoration( decoration: const BoxDecoration(
border: Border( border: Border(
bottom: BorderSide(color: Color(0xFFE5E5E5), width: 0.5), bottom: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
@@ -70,7 +88,7 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
Wrap( Wrap(
spacing: 8, spacing: 8,
runSpacing: 8, runSpacing: 8,
children: widget.note.tags.map((tag) { children: note.tags.map((tag) {
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -93,9 +111,39 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
// 内容区域 // 内容区域
Expanded( Expanded(
child: widget.note.contentType == 'markdown' child: note.contentType == 'markdown'
? _buildMarkdownContent() ? _buildMarkdownContent(note)
: _buildPlainTextContent(), : _buildPlainTextContent(note),
),
// 图片区域(仅在纯文本模式下显示)
if (note.contentType == 'plain_text' && note.images.isNotEmpty)
Container(
height: 120,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
),
),
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: note.images.length,
itemBuilder: (context, index) {
return Container(
width: 100,
height: 100,
margin: const EdgeInsets.only(right: 12),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Image.file(
File(note.images[index]),
fit: BoxFit.cover,
),
);
},
),
), ),
// 底部操作栏 // 底部操作栏
@@ -107,17 +155,35 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
), ),
child: SafeArea( child: SafeArea(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row( child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.min,
children: [
// 创建时间和更新时间
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'更新于 ${_formatDateTime(widget.note.updatedAt)}', '创建时间:${_formatDateTime(note.createdAt)}',
style: const TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 11,
color: Color(0xFF999999), color: Color(0xFF999999),
), ),
), ),
const SizedBox(height: 4),
Text(
'更新时间:${_formatDateTime(note.updatedAt)}',
style: const TextStyle(
fontSize: 11,
color: Color(0xFF999999),
),
),
],
),
),
Row( Row(
children: [ children: [
IconButton( IconButton(
@@ -139,6 +205,8 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
), ),
], ],
), ),
],
),
), ),
), ),
), ),
@@ -148,9 +216,9 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
} }
/// 构建 Markdown 内容 /// 构建 Markdown 内容
Widget _buildMarkdownContent() { Widget _buildMarkdownContent(Note note) {
return Markdown( return Markdown(
data: widget.note.content, data: note.content,
styleSheet: MarkdownStyleSheet( styleSheet: MarkdownStyleSheet(
h1: const TextStyle( h1: const TextStyle(
fontSize: 24, fontSize: 24,
@@ -204,22 +272,26 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
decoration: TextDecoration.underline, decoration: TextDecoration.underline,
), ),
), ),
padding: const EdgeInsets.all(24), padding: const EdgeInsets.all(16),
); );
} }
/// 构建纯文本内容 /// 构建纯文本内容
Widget _buildPlainTextContent() { Widget _buildPlainTextContent(Note note) {
return SingleChildScrollView( return SingleChildScrollView(
padding: const EdgeInsets.all(24), padding: const EdgeInsets.all(16),
child: SizedBox(
width: double.infinity,
child: Text( child: Text(
widget.note.content, note.content,
textAlign: TextAlign.left,
style: const TextStyle( style: const TextStyle(
fontSize: 16, fontSize: 16,
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
height: 1.8, height: 1.8,
), ),
), ),
),
); );
} }
@@ -228,6 +300,17 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}'; return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
} }
/// 获取标题内容前5个字
String _getTitle(String content) {
if (content.isEmpty) return '无标题';
// 移除换行符和多余空格
final trimmed = content.replaceAll('\n', ' ').trim();
if (trimmed.isEmpty) return '无标题';
// 取前5个字
if (trimmed.length <= 5) return trimmed;
return '${trimmed.substring(0, 5)}...';
}
/// 跳转到编辑页面 /// 跳转到编辑页面
void _navigateToEdit(BuildContext context) { void _navigateToEdit(BuildContext context) {
Navigator.pushNamed(context, '/note-form', arguments: widget.note).then((_) { Navigator.pushNamed(context, '/note-form', arguments: widget.note).then((_) {

View File

@@ -1,8 +1,12 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p;
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../utils/toast_util.dart'; import '../utils/toast_util.dart';
import '../utils/image_path_helper.dart';
/// 添加/编辑笔记页面 - 极简书写界面 /// 添加/编辑笔记页面 - 极简书写界面
class NoteFormPage extends StatefulWidget { class NoteFormPage extends StatefulWidget {
@@ -18,8 +22,11 @@ class _NoteFormPageState extends State<NoteFormPage> {
late TextEditingController _contentController; late TextEditingController _contentController;
late DateTime _createdAt; late DateTime _createdAt;
List<String> _tags = []; List<String> _tags = [];
String _contentType = 'markdown'; // markdown / rich_text List<String> _images = []; // 图片路径列表
String _contentType = 'markdown'; // markdown / plain_text
bool _isEditing = false; bool _isEditing = false;
final ImagePicker _picker = ImagePicker();
String? _tempNoteId; // 新建模式时使用的临时笔记ID
@override @override
void initState() { void initState() {
@@ -28,6 +35,7 @@ class _NoteFormPageState extends State<NoteFormPage> {
_contentController = TextEditingController(text: note?.content ?? ''); _contentController = TextEditingController(text: note?.content ?? '');
_createdAt = note?.createdAt ?? DateTime.now(); _createdAt = note?.createdAt ?? DateTime.now();
_tags = note != null ? List.from(note.tags) : []; _tags = note != null ? List.from(note.tags) : [];
_images = note != null ? List.from(note.images) : [];
_contentType = note?.contentType ?? 'markdown'; _contentType = note?.contentType ?? 'markdown';
_isEditing = note != null; _isEditing = note != null;
} }
@@ -93,7 +101,32 @@ class _NoteFormPageState extends State<NoteFormPage> {
), ),
), ),
// 书写区域 // 书写区域纯文本模式下占据35%高度Markdown模式下占据全部
if (_contentType == 'plain_text')
SizedBox(
height: MediaQuery.of(context).size.height * 0.35,
child: TextField(
controller: _contentController,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
style: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
height: 1.6,
),
decoration: const InputDecoration(
hintText: '开始书写...',
hintStyle: TextStyle(
fontSize: 16,
color: Color(0xFFCCCCCC),
),
border: InputBorder.none,
contentPadding: EdgeInsets.all(16),
),
),
)
else
Expanded( Expanded(
child: TextField( child: TextField(
controller: _contentController, controller: _contentController,
@@ -105,17 +138,122 @@ class _NoteFormPageState extends State<NoteFormPage> {
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
height: 1.6, height: 1.6,
), ),
decoration: InputDecoration( decoration: const InputDecoration(
hintText: _contentType == 'markdown' ? '使用 Markdown 格式书写...' : '开始书写...', hintText: '使用 Markdown 格式书写...',
hintStyle: const TextStyle( hintStyle: TextStyle(
fontSize: 16, fontSize: 16,
color: Color(0xFFCCCCCC), color: Color(0xFFCCCCCC),
), ),
border: InputBorder.none, border: InputBorder.none,
contentPadding: const EdgeInsets.all(16), contentPadding: EdgeInsets.all(16),
), ),
), ),
), ),
// 纯文本模式下的图片区域
if (_contentType == 'plain_text') ...[
// 图片网格区域
Expanded(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 标题栏
Row(
children: [
const Text(
'图片',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Color(0xFF1A1A1A),
),
),
const SizedBox(width: 8),
Text(
'${_images.length}',
style: const TextStyle(
fontSize: 14,
color: Color(0xFF999999),
),
),
const Spacer(),
// 添加图片按钮
InkWell(
onTap: _pickImage,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
borderRadius: BorderRadius.circular(2),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.add,
size: 16,
color: Colors.white,
),
SizedBox(width: 4),
Text(
'添加',
style: TextStyle(
fontSize: 12,
color: Colors.white,
),
),
],
),
),
),
],
),
const SizedBox(height: 12),
// 图片网格4列正方形铺满
Expanded(
child: _images.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.image_outlined,
size: 48,
color: const Color(0xFFCCCCCC),
),
const SizedBox(height: 8),
const Text(
'点击添加按钮添加图片',
style: TextStyle(
fontSize: 13,
color: Color(0xFF999999),
),
),
],
),
)
: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: 1.0,
),
itemCount: _images.length,
itemBuilder: (context, index) {
return _buildImageItem(index);
},
),
),
],
),
),
),
],
], ],
), ),
); );
@@ -140,7 +278,7 @@ class _NoteFormPageState extends State<NoteFormPage> {
), ),
const SizedBox(width: 4), const SizedBox(width: 4),
Text( Text(
_contentType == 'markdown' ? 'Markdown' : '文本', _contentType == 'markdown' ? 'Markdown' : '文本',
style: const TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
color: Color(0xFF666666), color: Color(0xFF666666),
@@ -184,12 +322,12 @@ class _NoteFormPageState extends State<NoteFormPage> {
ListTile( ListTile(
leading: const Icon(Icons.text_fields, size: 20), leading: const Icon(Icons.text_fields, size: 20),
title: const Text('纯文本'), title: const Text('纯文本'),
subtitle: const Text('普通文本格式'), subtitle: const Text('普通文本格式,支持图片'),
trailing: _contentType == 'rich_text' trailing: _contentType == 'plain_text'
? const Icon(Icons.check, color: Color(0xFF1A1A1A)) ? const Icon(Icons.check, color: Color(0xFF1A1A1A))
: null, : null,
onTap: () { onTap: () {
setState(() => _contentType = 'rich_text'); setState(() => _contentType = 'plain_text');
Navigator.pop(context); Navigator.pop(context);
}, },
), ),
@@ -344,16 +482,29 @@ class _NoteFormPageState extends State<NoteFormPage> {
content: content, content: content,
contentType: _contentType, contentType: _contentType,
tags: _tags, tags: _tags,
images: _images,
updatedAt: now, updatedAt: now,
); );
await context.read<AppProvider>().updateNote(updatedNote); await context.read<AppProvider>().updateNote(updatedNote);
} else { } else {
// 添加新笔记 // 添加新笔记 - 先创建笔记获取ID
final noteId = now.millisecondsSinceEpoch.toString();
// 如果有图片需要移动到正确的ID目录
List<String> finalImages = [];
if (_images.isNotEmpty) {
// 使用保存的临时ID如果没有则使用当前noteId理论上不会走到这里
final oldNoteId = _tempNoteId ?? noteId;
final newNoteId = noteId;
finalImages = await _moveImagesToNewId(oldNoteId, newNoteId);
}
final newNote = Note( final newNote = Note(
id: now.millisecondsSinceEpoch.toString(), id: noteId,
content: content, content: content,
contentType: _contentType, contentType: _contentType,
tags: _tags, tags: _tags,
images: finalImages.isNotEmpty ? finalImages : _images,
createdAt: _createdAt, createdAt: _createdAt,
updatedAt: now, updatedAt: now,
); );
@@ -366,4 +517,123 @@ class _NoteFormPageState extends State<NoteFormPage> {
Navigator.pop(context); Navigator.pop(context);
} }
/// 将图片从临时ID目录移动到新ID目录
Future<List<String>> _moveImagesToNewId(String oldNoteId, String newNoteId) async {
final List<String> newPaths = [];
final newDir = await ImagePathHelper.instance.getNoteImagesDir(newNoteId);
for (final imagePath in _images) {
// 使用路径分隔符检查,兼容 Windows 和 Unix
final normalizedPath = imagePath.replaceAll('\\', '/');
if (normalizedPath.contains('/notes/$oldNoteId/')) {
// 需要移动的文件
final fileName = p.basename(imagePath);
final newPath = p.join(newDir, fileName);
await ImagePathHelper.instance.ensureDirExists(newDir);
// 检查源文件是否存在
final sourceFile = File(imagePath);
if (await sourceFile.exists()) {
await sourceFile.rename(newPath);
newPaths.add(newPath);
}
} else {
// 已经在正确位置的文件
newPaths.add(imagePath);
}
}
// 删除旧目录
try {
await ImagePathHelper.instance.deleteNoteImages(oldNoteId);
} catch (e) {
// 忽略删除失败
}
return newPaths;
}
/// 选择图片
Future<void> _pickImage() async {
try {
final XFile? image = await _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 1920,
maxHeight: 1920,
imageQuality: 85,
);
if (image != null) {
// 生成唯一的文件名
final fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg';
// 如果是编辑模式使用现有笔记ID如果是新建模式使用临时ID保存时会替换
String noteId;
if (_isEditing) {
noteId = widget.note!.id;
} else {
// 新建模式使用已存在的临时ID或生成新的
noteId = _tempNoteId ?? DateTime.now().millisecondsSinceEpoch.toString();
_tempNoteId = noteId;
}
// 复制图片到应用目录: images/notes/{noteId}/{fileName}
final targetDir = await ImagePathHelper.instance.getNoteImagesDir(noteId);
await ImagePathHelper.instance.ensureDirExists(targetDir);
final targetPath = p.join(targetDir, fileName);
await File(image.path).copy(targetPath);
setState(() => _images.add(targetPath));
}
} catch (e) {
ToastUtil.show(context, '选择图片失败: $e');
}
}
/// 构建图片项
Widget _buildImageItem(int index) {
return InkWell(
onLongPress: () => _showDeleteImageDialog(index),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Image.file(
File(_images[index]),
fit: BoxFit.cover,
),
),
);
}
/// 显示删除图片确认对话框
void _showDeleteImageDialog(int index) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: const Text('确定要删除这张图片吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () {
setState(() => _images.removeAt(index));
Navigator.pop(context);
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
} }

View File

@@ -32,6 +32,8 @@ class NoteTabPage extends StatelessWidget {
return RefreshIndicator( return RefreshIndicator(
onRefresh: () async => await provider.loadNotes(), onRefresh: () async => await provider.loadNotes(),
color: const Color(0xFF1A1A1A),
backgroundColor: Colors.white,
child: ListView.builder( child: ListView.builder(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
itemCount: notes.length, itemCount: notes.length,
@@ -50,25 +52,45 @@ class NoteTabPage extends StatelessWidget {
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(
Icons.note_outlined, Icons.note_outlined,
size: 80, size: 40,
color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.3), color: Color(0xFFCCCCCC),
), ),
const SizedBox(height: 16), ),
Text( const SizedBox(height: 24),
const Text(
'暂无笔记', '暂无笔记',
style: Theme.of(context).textTheme.titleMedium?.copyWith( style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant, fontSize: 16,
color: Color(0xFF999999),
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 24),
ElevatedButton.icon( InkWell(
icon: const Icon(Icons.add), onTap: () {
label: const Text('添加笔记'),
onPressed: () {
Navigator.pushNamed(context, '/note-form'); Navigator.pushNamed(context, '/note-form');
}, },
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
),
child: const Text(
'添加笔记',
style: TextStyle(
fontSize: 14,
color: Colors.white,
),
),
),
), ),
], ],
), ),

View File

@@ -396,7 +396,7 @@ class _ProfilePageState extends State<ProfilePage> {
_buildMenuItem( _buildMenuItem(
icon: Icons.backup_outlined, icon: Icons.backup_outlined,
title: '数据备份', title: '本地备份',
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,
@@ -408,7 +408,7 @@ class _ProfilePageState extends State<ProfilePage> {
_buildMenuItem( _buildMenuItem(
icon: Icons.cloud_sync_outlined, icon: Icons.cloud_sync_outlined,
title: '同步', title: '备份',
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,

View File

@@ -4,7 +4,7 @@ import '../utils/toast_util.dart';
import '../utils/webdav_service.dart'; import '../utils/webdav_service.dart';
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
/// WebDAV 同步页面 /// WebDAV 备份页面
class WebDAVSyncPage extends StatefulWidget { class WebDAVSyncPage extends StatefulWidget {
const WebDAVSyncPage({super.key}); const WebDAVSyncPage({super.key});
@@ -21,13 +21,14 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
bool _isLoading = false; bool _isLoading = false;
bool _isConfigured = false; bool _isConfigured = false;
bool _obscurePassword = true; bool _obscurePassword = true;
SyncDirection _syncDirection = SyncDirection.bidirectional; bool _isAutoSyncEnabled = false;
SyncResult? _lastSyncResult; SyncDirection _syncDirection = SyncDirection.upload;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_loadConfig(); _loadConfig();
_loadAutoSyncStatus();
} }
@override @override
@@ -39,6 +40,33 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
super.dispose(); super.dispose();
} }
/// 加载自动同步状态
Future<void> _loadAutoSyncStatus() async {
final enabled = await WebDAVService.instance.isAutoSyncEnabled();
setState(() => _isAutoSyncEnabled = enabled);
}
/// 切换自动同步
Future<void> _toggleAutoSync(bool value) async {
setState(() => _isLoading = true);
try {
if (value) {
await WebDAVService.instance.startAutoSync();
ToastUtil.show(context, '自动备份已开启每2分钟执行一次');
} else {
await WebDAVService.instance.stopAutoSync();
ToastUtil.show(context, '自动备份已关闭');
}
setState(() => _isAutoSyncEnabled = value);
} catch (e) {
ToastUtil.show(context, '操作失败: $e');
} finally {
setState(() => _isLoading = false);
}
}
/// 加载已保存的配置 /// 加载已保存的配置
Future<void> _loadConfig() async { Future<void> _loadConfig() async {
final config = await WebDAVService.instance.getConfig(); final config = await WebDAVService.instance.getConfig();
@@ -98,13 +126,7 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
setState(() => _isConfigured = true); setState(() => _isConfigured = true);
ToastUtil.show(context, result['message'] ?? '连接成功,配置已保存'); ToastUtil.show(context, result['message'] ?? '连接成功,配置已保存');
// 延迟一下再返回,确保 Toast 显示出来 // 连接成功后停留在当前页面,不返回上级
await Future.delayed(const Duration(milliseconds: 500));
// 如果是首次配置成功,返回 true 给调用方
if (mounted) {
Navigator.maybePop(context, true);
}
} else { } else {
ToastUtil.show(context, result['message'] ?? '连接失败,请检查配置'); ToastUtil.show(context, result['message'] ?? '连接失败,请检查配置');
} }
@@ -128,8 +150,6 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
if (!mounted) return; if (!mounted) return;
setState(() => _lastSyncResult = result);
if (result.success) { if (result.success) {
final details = '上传: ${result.uploadedFiles} 文件, ${result.uploadedImages} 图片\n' final details = '上传: ${result.uploadedFiles} 文件, ${result.uploadedImages} 图片\n'
'下载: ${result.downloadedFiles} 文件, ${result.downloadedImages} 图片'; '下载: ${result.downloadedFiles} 文件, ${result.downloadedImages} 图片';
@@ -228,7 +248,7 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
appBar: AppBar( appBar: AppBar(
title: const Text('WebDAV 同步'), title: const Text('WebDAV 备份'),
leading: IconButton( leading: IconButton(
icon: const Icon(Icons.arrow_back), icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.maybePop(context), onPressed: () => Navigator.maybePop(context),
@@ -337,6 +357,56 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
if (_isConfigured) ...[ if (_isConfigured) ...[
const SizedBox(height: 24), const SizedBox(height: 24),
// 自动备份开关
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Row(
children: [
const Icon(
Icons.schedule,
size: 20,
color: Color(0xFF666666),
),
const SizedBox(width: 12),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'自动备份',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Color(0xFF1A1A1A),
),
),
SizedBox(height: 2),
Text(
'每2分钟自动备份一次保留最近10个备份',
style: TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
],
),
),
Switch(
value: _isAutoSyncEnabled,
onChanged: _isLoading ? null : _toggleAutoSync,
activeColor: const Color(0xFF1A1A1A),
inactiveThumbColor: const Color(0xFF999999),
),
],
),
),
const SizedBox(height: 24),
// 同步方向选择 // 同步方向选择
const Text( const Text(
'同步方向', '同步方向',
@@ -351,15 +421,7 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
children: [ children: [
Expanded( Expanded(
child: _buildDirectionButton( child: _buildDirectionButton(
'双向同步', '上传',
SyncDirection.bidirectional,
Icons.sync,
),
),
const SizedBox(width: 8),
Expanded(
child: _buildDirectionButton(
'仅上传',
SyncDirection.upload, SyncDirection.upload,
Icons.upload, Icons.upload,
), ),
@@ -367,7 +429,7 @@ class _WebDAVSyncPageState extends State<WebDAVSyncPage> {
const SizedBox(width: 8), const SizedBox(width: 8),
Expanded( Expanded(
child: _buildDirectionButton( child: _buildDirectionButton(
'下载', '下载',
SyncDirection.download, SyncDirection.download,
Icons.download, Icons.download,
), ),

View File

@@ -7,6 +7,7 @@ import '../utils/movie_review_dao.dart';
import '../utils/movie_poster_dao.dart'; import '../utils/movie_poster_dao.dart';
import '../utils/book_review_dao.dart'; import '../utils/book_review_dao.dart';
import '../utils/book_excerpt_dao.dart'; import '../utils/book_excerpt_dao.dart';
import '../utils/image_path_helper.dart';
/// 应用全局状态管理 /// 应用全局状态管理
class AppProvider extends ChangeNotifier { class AppProvider extends ChangeNotifier {
@@ -127,7 +128,8 @@ class AppProvider extends ChangeNotifier {
await loadMovies(); await loadMovies();
} }
// 删除影视记录 // 删除影视记录(软删除,移入回收站)
// 注意:软删除时不删除图片文件,恢复时文件仍然存在
Future<void> removeMovie(String id) async { Future<void> removeMovie(String id) async {
await _movieDao.deleteMovie(id); await _movieDao.deleteMovie(id);
await loadMovies(); await loadMovies();
@@ -145,7 +147,8 @@ class AppProvider extends ChangeNotifier {
await loadBooks(); await loadBooks();
} }
// 删除书籍记录 // 删除书籍记录(软删除,移入回收站)
// 注意:软删除时不删除图片文件,恢复时文件仍然存在
Future<void> removeBook(String id) async { Future<void> removeBook(String id) async {
await _bookDao.deleteBook(id); await _bookDao.deleteBook(id);
await loadBooks(); await loadBooks();
@@ -163,7 +166,8 @@ class AppProvider extends ChangeNotifier {
await loadNotes(); await loadNotes();
} }
// 删除笔记 // 删除笔记(软删除,移入回收站)
// 注意:软删除时不删除图片文件,恢复时文件仍然存在
Future<void> removeNote(String id) async { Future<void> removeNote(String id) async {
await _noteDao.deleteNote(id); await _noteDao.deleteNote(id);
await loadNotes(); await loadNotes();
@@ -210,6 +214,13 @@ class AppProvider extends ChangeNotifier {
/// 删除海报 /// 删除海报
Future<void> removeMoviePoster(String id) async { Future<void> removeMoviePoster(String id) async {
// 先获取海报信息,以便删除文件
final poster = await _posterDao.getPosterById(id);
if (poster != null) {
// 删除海报文件
await ImagePathHelper.instance.deleteFile(poster.posterPath);
}
await _posterDao.deletePoster(id); await _posterDao.deletePoster(id);
} }
@@ -287,6 +298,9 @@ class AppProvider extends ChangeNotifier {
/// 彻底删除影视 /// 彻底删除影视
Future<void> permanentDeleteMovie(String id) async { Future<void> permanentDeleteMovie(String id) async {
// 删除影视对应的图片目录(包括海报和海报墙)
await ImagePathHelper.instance.deleteMovieImages(id);
await _movieDao.permanentDeleteMovie(id); await _movieDao.permanentDeleteMovie(id);
} }
@@ -303,6 +317,9 @@ class AppProvider extends ChangeNotifier {
/// 彻底删除书籍 /// 彻底删除书籍
Future<void> permanentDeleteBook(String id) async { Future<void> permanentDeleteBook(String id) async {
// 删除书籍对应的图片目录
await ImagePathHelper.instance.deleteBookImages(id);
await _bookDao.permanentDeleteBook(id); await _bookDao.permanentDeleteBook(id);
} }
@@ -319,6 +336,9 @@ class AppProvider extends ChangeNotifier {
/// 彻底删除笔记 /// 彻底删除笔记
Future<void> permanentDeleteNote(String id) async { Future<void> permanentDeleteNote(String id) async {
// 删除笔记对应的图片目录
await ImagePathHelper.instance.deleteNoteImages(id);
await _noteDao.permanentDeleteNote(id); await _noteDao.permanentDeleteNote(id);
} }
@@ -329,12 +349,18 @@ class AppProvider extends ChangeNotifier {
final deletedNotes = await _noteDao.getDeletedNotes(); final deletedNotes = await _noteDao.getDeletedNotes();
for (final movie in deletedMovies) { for (final movie in deletedMovies) {
// 删除影视对应的图片目录(包括海报和海报墙)
await ImagePathHelper.instance.deleteMovieImages(movie.id);
await _movieDao.permanentDeleteMovie(movie.id); await _movieDao.permanentDeleteMovie(movie.id);
} }
for (final book in deletedBooks) { for (final book in deletedBooks) {
// 删除书籍对应的图片目录
await ImagePathHelper.instance.deleteBookImages(book.id);
await _bookDao.permanentDeleteBook(book.id); await _bookDao.permanentDeleteBook(book.id);
} }
for (final note in deletedNotes) { for (final note in deletedNotes) {
// 删除笔记对应的图片目录
await ImagePathHelper.instance.deleteNoteImages(note.id);
await _noteDao.permanentDeleteNote(note.id); await _noteDao.permanentDeleteNote(note.id);
} }

View File

@@ -7,7 +7,6 @@ import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:cross_file/cross_file.dart';
import 'database_helper.dart'; import 'database_helper.dart';
/// 数据备份服务 - 支持导出和导入数据(包含图片) /// 数据备份服务 - 支持导出和导入数据(包含图片)
@@ -55,6 +54,23 @@ class BackupService {
} }
} }
// 收集笔记图片
for (final note in notes) {
final imagesJson = note['images'] as String?;
if (imagesJson != null && imagesJson.isNotEmpty) {
try {
final images = jsonDecode(imagesJson) as List<dynamic>;
for (final imagePath in images) {
if (imagePath is String && imagePath.isNotEmpty) {
imagePaths.add(imagePath);
}
}
} catch (e) {
// 解析失败,跳过
}
}
}
// 构建备份数据 // 构建备份数据
final backupData = { final backupData = {
'version': 2, 'version': 2,
@@ -78,15 +94,24 @@ class BackupService {
final jsonBytes = Uint8List.fromList(utf8.encode(jsonString)); final jsonBytes = Uint8List.fromList(utf8.encode(jsonString));
archive.addFile(ArchiveFile('data.json', jsonBytes.length, jsonBytes)); archive.addFile(ArchiveFile('data.json', jsonBytes.length, jsonBytes));
// 添加图片文件 // 添加图片文件,保持目录结构
int imageCount = 0; int imageCount = 0;
final appDir = await getApplicationDocumentsDirectory();
final imagesRoot = path.join(appDir.path, 'images');
for (final imagePath in imagePaths) { for (final imagePath in imagePaths) {
final file = File(imagePath); final file = File(imagePath);
if (await file.exists()) { if (await file.exists()) {
final bytes = await file.readAsBytes(); final bytes = await file.readAsBytes();
final fileName = path.basename(imagePath); // 计算相对路径(如 movies/1/poster.jpg
// 使用相对路径存储图片 String relativePath;
archive.addFile(ArchiveFile('images/$fileName', bytes.length, bytes)); if (imagePath.startsWith(imagesRoot)) {
relativePath = imagePath.substring(imagesRoot.length + 1); // +1 去掉开头的 /
} else {
relativePath = path.basename(imagePath);
}
// 使用相对路径存储图片,保持目录结构
archive.addFile(ArchiveFile('images/$relativePath', bytes.length, bytes));
imageCount++; imageCount++;
} }
} }
@@ -198,7 +223,7 @@ class BackupService {
final jsonString = utf8.decode(dataFile.content as List<int>); final jsonString = utf8.decode(dataFile.content as List<int>);
backupData = jsonDecode(jsonString) as Map<String, dynamic>; backupData = jsonDecode(jsonString) as Map<String, dynamic>;
// 解压图片到应用目录 // 解压图片到应用目录,保持目录结构
final appDir = await getApplicationDocumentsDirectory(); final appDir = await getApplicationDocumentsDirectory();
final imagesDir = Directory(path.join(appDir.path, 'images')); final imagesDir = Directory(path.join(appDir.path, 'images'));
if (!await imagesDir.exists()) { if (!await imagesDir.exists()) {
@@ -207,9 +232,20 @@ class BackupService {
for (final archiveFile in archive) { for (final archiveFile in archive) {
if (archiveFile.name.startsWith('images/')) { if (archiveFile.name.startsWith('images/')) {
final fileName = path.basename(archiveFile.name); // 获取相对路径(如 movies/1/poster.jpg
final outputFile = File(path.join(imagesDir.path, fileName)); final relativePath = archiveFile.name.substring(7); // 去掉 'images/' 前缀
final outputFile = File(path.join(imagesDir.path, relativePath));
// 确保父目录存在
final parentDir = outputFile.parent;
if (!await parentDir.exists()) {
await parentDir.create(recursive: true);
}
await outputFile.writeAsBytes(archiveFile.content as List<int>); await outputFile.writeAsBytes(archiveFile.content as List<int>);
// 记录文件名到新路径的映射(用于更新数据库中的路径)
final fileName = path.basename(archiveFile.name);
imagePathMap[fileName] = outputFile.path; imagePathMap[fileName] = outputFile.path;
imageCount++; imageCount++;
} }
@@ -258,11 +294,13 @@ class BackupService {
} }
} }
// 导入笔记数据 // 导入笔记数据(更新图片路径)
if (data.containsKey('notes')) { if (data.containsKey('notes')) {
final notes = data['notes'] as List<dynamic>; final notes = data['notes'] as List<dynamic>;
for (final note in notes) { for (final note in notes) {
await txn.insert('notes', _convertToDbMap(note)); final noteMap = _convertToDbMap(note);
final updatedMap = _updateNoteImagesPath(noteMap, imagePathMap);
await txn.insert('notes', updatedMap);
} }
} }
@@ -327,6 +365,7 @@ class BackupService {
} }
/// 更新图片路径为新的路径 /// 更新图片路径为新的路径
/// 支持新的存储结构images/movies/{id}/、images/books/{id}/、images/notes/{id}/
Map<String, dynamic> _updateImagePath( Map<String, dynamic> _updateImagePath(
Map<String, dynamic> item, Map<String, dynamic> item,
String pathField, String pathField,
@@ -340,6 +379,61 @@ class BackupService {
// 如果图片在映射中,更新路径 // 如果图片在映射中,更新路径
if (imagePathMap.containsKey(fileName)) { if (imagePathMap.containsKey(fileName)) {
newItem[pathField] = imagePathMap[fileName]; newItem[pathField] = imagePathMap[fileName];
} else {
// 尝试从旧版备份中恢复(旧版只保存了文件名)
// 检查是否有匹配的文件名(不区分目录结构)
for (final entry in imagePathMap.entries) {
if (path.basename(entry.key) == fileName) {
newItem[pathField] = entry.value;
break;
}
}
}
}
return newItem;
}
/// 更新笔记图片路径为新的路径
/// 支持新的存储结构images/notes/{id}/
Map<String, dynamic> _updateNoteImagesPath(
Map<String, dynamic> item,
Map<String, String> imagePathMap,
) {
final newItem = Map<String, dynamic>.from(item);
final imagesJson = item['images'] as String?;
if (imagesJson != null && imagesJson.isNotEmpty) {
try {
final images = jsonDecode(imagesJson) as List<dynamic>;
final updatedImages = <String>[];
for (final imagePath in images) {
if (imagePath is String && imagePath.isNotEmpty) {
final fileName = path.basename(imagePath);
// 如果图片在映射中,更新路径
if (imagePathMap.containsKey(fileName)) {
updatedImages.add(imagePathMap[fileName]!);
} else {
// 尝试从旧版备份中恢复(旧版只保存了文件名)
bool found = false;
for (final entry in imagePathMap.entries) {
if (path.basename(entry.key) == fileName) {
updatedImages.add(entry.value);
found = true;
break;
}
}
if (!found) {
updatedImages.add(imagePath);
}
}
}
}
newItem['images'] = jsonEncode(updatedImages);
} catch (e) {
// 解析失败,保持原样
} }
} }

View File

@@ -62,8 +62,8 @@ class BookDao {
); );
} }
// 软删除书籍记录 // 软删除书籍记录(移入回收站)
Future<int> softDeleteBook(String id) async { Future<int> deleteBook(String id) async {
final db = await _dbHelper.database; final db = await _dbHelper.database;
return await db.update( return await db.update(
'books', 'books',
@@ -76,16 +76,6 @@ class BookDao {
); );
} }
// 彻底删除书籍记录
Future<int> deleteBook(String id) async {
final db = await _dbHelper.database;
return await db.delete(
'books',
where: 'id = ?',
whereArgs: [id],
);
}
// 搜索书籍(标题、别名) // 搜索书籍(标题、别名)
Future<List<Book>> searchBooks(String query) async { Future<List<Book>> searchBooks(String query) async {
final db = await _dbHelper.database; final db = await _dbHelper.database;

View File

@@ -8,6 +8,17 @@ class DatabaseHelper {
DatabaseHelper._init(); DatabaseHelper._init();
/// 重新打开数据库(用于 WebDAV 同步后)
Future<void> reopenDatabase() async {
// 关闭现有连接
if (_database != null) {
await _database!.close();
_database = null;
}
// 重新初始化
_database = await _initDB('mooknote.db');
}
Future<Database> get database async { Future<Database> get database async {
if (_database != null) return _database!; if (_database != null) return _database!;
_database = await _initDB('mooknote.db'); _database = await _initDB('mooknote.db');
@@ -20,7 +31,7 @@ class DatabaseHelper {
return await openDatabase( return await openDatabase(
path, path,
version: 8, version: 9,
onCreate: _createDB, onCreate: _createDB,
onUpgrade: _onUpgrade, onUpgrade: _onUpgrade,
); );
@@ -59,6 +70,21 @@ class DatabaseHelper {
await _createBookReviewsTable(db); await _createBookReviewsTable(db);
await _createBookExcerptsTable(db); await _createBookExcerptsTable(db);
} }
if (oldVersion < 9) {
// 为笔记表添加图片字段
await _upgradeNotesTableV9(db);
}
}
/// 升级notes表到V9添加图片字段
Future<void> _upgradeNotesTableV9(Database db) async {
// 检查是否存在 images 列
final columns = await db.rawQuery('PRAGMA table_info(notes)');
final hasImages = columns.any((col) => col['name'] == 'images');
if (!hasImages) {
await db.execute('ALTER TABLE notes ADD COLUMN images TEXT');
}
} }
/// 升级notes表到V6添加软删除字段 /// 升级notes表到V6添加软删除字段
@@ -344,6 +370,7 @@ class DatabaseHelper {
content TEXT NOT NULL, content TEXT NOT NULL,
content_type TEXT DEFAULT 'markdown', content_type TEXT DEFAULT 'markdown',
tags TEXT, tags TEXT,
images TEXT,
created_at TEXT NOT NULL, created_at TEXT NOT NULL,
updated_at TEXT NOT NULL, updated_at TEXT NOT NULL,
is_deleted INTEGER DEFAULT 0 is_deleted INTEGER DEFAULT 0

View File

@@ -0,0 +1,163 @@
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
/// 图片路径管理助手 - 按分类和ID组织图片存储
///
/// 存储结构:
/// images/movies/{movieId}/xxxx.jpg - 影视海报
/// images/movies/{movieId}/posterimgs/xxxx.jpg - 影视海报墙图片
/// images/books/{bookId}/xxxx.jpg - 书籍封面
/// images/notes/{noteId}/xxxx.jpg - 笔记图片
class ImagePathHelper {
static final ImagePathHelper instance = ImagePathHelper._init();
ImagePathHelper._init();
String? _appDirPath;
/// 获取应用文档目录
Future<String> get _appDir async {
if (_appDirPath != null) return _appDirPath!;
final appDir = await getApplicationDocumentsDirectory();
_appDirPath = appDir.path;
return _appDirPath!;
}
/// 获取图片根目录
Future<String> get imagesRoot async {
final appDir = await _appDir;
return p.join(appDir, 'images');
}
// ==================== 影视相关路径 ====================
/// 获取影视图片目录
/// 路径: images/movies/{movieId}/
Future<String> getMovieImagesDir(String movieId) async {
final root = await imagesRoot;
return p.join(root, 'movies', movieId);
}
/// 获取影视海报路径
/// 路径: images/movies/{movieId}/{fileName}
Future<String> getMoviePosterPath(String movieId, String fileName) async {
final dir = await getMovieImagesDir(movieId);
return p.join(dir, fileName);
}
/// 获取影视海报墙目录
/// 路径: images/movies/{movieId}/posterimgs/
Future<String> getMoviePosterImgsDir(String movieId) async {
final dir = await getMovieImagesDir(movieId);
return p.join(dir, 'posterimgs');
}
/// 获取影视海报墙图片路径
/// 路径: images/movies/{movieId}/posterimgs/{fileName}
Future<String> getMoviePosterImgPath(String movieId, String fileName) async {
final dir = await getMoviePosterImgsDir(movieId);
return p.join(dir, fileName);
}
// ==================== 书籍相关路径 ====================
/// 获取书籍图片目录
/// 路径: images/books/{bookId}/
Future<String> getBookImagesDir(String bookId) async {
final root = await imagesRoot;
return p.join(root, 'books', bookId);
}
/// 获取书籍封面路径
/// 路径: images/books/{bookId}/{fileName}
Future<String> getBookCoverPath(String bookId, String fileName) async {
final dir = await getBookImagesDir(bookId);
return p.join(dir, fileName);
}
// ==================== 笔记相关路径 ====================
/// 获取笔记图片目录
/// 路径: images/notes/{noteId}/
Future<String> getNoteImagesDir(String noteId) async {
final root = await imagesRoot;
return p.join(root, 'notes', noteId);
}
/// 获取笔记图片路径
/// 路径: images/notes/{noteId}/{fileName}
Future<String> getNoteImagePath(String noteId, String fileName) async {
final dir = await getNoteImagesDir(noteId);
return p.join(dir, fileName);
}
// ==================== 目录操作 ====================
/// 确保目录存在
Future<void> ensureDirExists(String dirPath) async {
final dir = Directory(dirPath);
if (!await dir.exists()) {
await dir.create(recursive: true);
}
}
/// 删除影视图片目录(包括海报和海报墙)
/// 删除路径: images/movies/{movieId}/
Future<void> deleteMovieImages(String movieId) async {
final dirPath = await getMovieImagesDir(movieId);
await _deleteDirectory(dirPath);
}
/// 删除书籍图片目录
/// 删除路径: images/books/{bookId}/
Future<void> deleteBookImages(String bookId) async {
final dirPath = await getBookImagesDir(bookId);
await _deleteDirectory(dirPath);
}
/// 删除笔记图片目录
/// 删除路径: images/notes/{noteId}/
Future<void> deleteNoteImages(String noteId) async {
final dirPath = await getNoteImagesDir(noteId);
await _deleteDirectory(dirPath);
}
/// 删除目录及其内容
Future<void> _deleteDirectory(String dirPath) async {
final dir = Directory(dirPath);
if (await dir.exists()) {
await dir.delete(recursive: true);
}
}
/// 移动文件到新位置
Future<String> moveFile(String sourcePath, String targetDir, String fileName) async {
await ensureDirExists(targetDir);
final targetPath = p.join(targetDir, fileName);
final sourceFile = File(sourcePath);
if (await sourceFile.exists()) {
await sourceFile.rename(targetPath);
}
return targetPath;
}
/// 复制文件到新位置
Future<String> copyFile(String sourcePath, String targetDir, String fileName) async {
await ensureDirExists(targetDir);
final targetPath = p.join(targetDir, fileName);
final sourceFile = File(sourcePath);
if (await sourceFile.exists()) {
await sourceFile.copy(targetPath);
}
return targetPath;
}
/// 删除单个文件
Future<void> deleteFile(String filePath) async {
final file = File(filePath);
if (await file.exists()) {
await file.delete();
}
}
}

View File

@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
@@ -5,6 +6,9 @@ import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart'; import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';
import 'database_helper.dart';
/// WebDAV 同步结果 /// WebDAV 同步结果
class SyncResult { class SyncResult {
@@ -15,7 +19,7 @@ class SyncResult {
final int downloadedFiles; final int downloadedFiles;
final int uploadedImages; final int uploadedImages;
final int downloadedImages; final int downloadedImages;
final bool needReload; // 是否需要重新加载数据 final bool needReload;
SyncResult({ SyncResult({
required this.success, required this.success,
@@ -43,7 +47,7 @@ class _ImageSyncResult {
_ImageSyncResult({required this.uploaded, required this.downloaded}); _ImageSyncResult({required this.uploaded, required this.downloaded});
} }
/// WebDAV 服务类 /// WebDAV 服务类 - 支持自动定时备份
class WebDAVService { class WebDAVService {
static final WebDAVService _instance = WebDAVService._internal(); static final WebDAVService _instance = WebDAVService._internal();
static WebDAVService get instance => _instance; static WebDAVService get instance => _instance;
@@ -52,8 +56,15 @@ class WebDAVService {
static const String _configKey = 'webdav_config'; static const String _configKey = 'webdav_config';
static const String _lastSyncKey = 'webdav_last_sync'; static const String _lastSyncKey = 'webdav_last_sync';
static const String _autoSyncKey = 'webdav_auto_sync';
static const String _backupListKey = 'webdav_backup_list';
static const int _maxBackupCount = 10; // 保留最近10条备份
static const Duration _autoSyncInterval = Duration(minutes: 2); // 每2分钟自动备份
Map<String, String>? _cachedConfig; Map<String, String>? _cachedConfig;
Timer? _autoSyncTimer;
bool _isAutoSyncEnabled = false;
/// 获取配置 /// 获取配置
Future<Map<String, String>?> getConfig() async { Future<Map<String, String>?> getConfig() async {
@@ -99,7 +110,10 @@ class WebDAVService {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.remove(_configKey); await prefs.remove(_configKey);
await prefs.remove(_lastSyncKey); await prefs.remove(_lastSyncKey);
await prefs.remove(_autoSyncKey);
await prefs.remove(_backupListKey);
_cachedConfig = null; _cachedConfig = null;
stopAutoSync();
} }
/// 测试连接 /// 测试连接
@@ -110,13 +124,11 @@ class WebDAVService {
required String path, required String path,
}) async { }) async {
try { try {
// 构建 WebDAV URL
final baseUrl = url.endsWith('/') ? url.substring(0, url.length - 1) : url; final baseUrl = url.endsWith('/') ? url.substring(0, url.length - 1) : url;
var davUrl = '$baseUrl$path'; var davUrl = '$baseUrl$path';
print('WebDAV: Testing connection to $davUrl'); print('WebDAV: Testing connection to $davUrl');
// 先尝试 PROPFIND 请求(更通用的测试方式)
final client = http.Client(); final client = http.Client();
try { try {
var propfindRequest = http.Request('PROPFIND', Uri.parse(davUrl)); var propfindRequest = http.Request('PROPFIND', Uri.parse(davUrl));
@@ -132,15 +144,12 @@ class WebDAVService {
var propfindResponse = await client.send(propfindRequest); var propfindResponse = await client.send(propfindRequest);
print('WebDAV: PROPFIND status ${propfindResponse.statusCode}'); print('WebDAV: PROPFIND status ${propfindResponse.statusCode}');
// 处理重定向 (301, 302, 307, 308)
if (propfindResponse.statusCode == 301 || if (propfindResponse.statusCode == 301 ||
propfindResponse.statusCode == 302 || propfindResponse.statusCode == 302 ||
propfindResponse.statusCode == 307 || propfindResponse.statusCode == 307 ||
propfindResponse.statusCode == 308) { propfindResponse.statusCode == 308) {
final location = propfindResponse.headers['location']; final location = propfindResponse.headers['location'];
if (location != null) { if (location != null) {
print('WebDAV: Redirecting to $location');
// 使用重定向后的 URL 重新请求
davUrl = location; davUrl = location;
propfindRequest = http.Request('PROPFIND', Uri.parse(davUrl)); propfindRequest = http.Request('PROPFIND', Uri.parse(davUrl));
propfindRequest.headers['Authorization'] = _basicAuth(username, password); propfindRequest.headers['Authorization'] = _basicAuth(username, password);
@@ -152,7 +161,6 @@ class WebDAVService {
</D:prop> </D:prop>
</D:propfind>'''; </D:propfind>''';
propfindResponse = await client.send(propfindRequest); propfindResponse = await client.send(propfindRequest);
print('WebDAV: PROPFIND after redirect status ${propfindResponse.statusCode}');
} }
} }
@@ -161,13 +169,7 @@ class WebDAVService {
} else if (propfindResponse.statusCode == 401) { } else if (propfindResponse.statusCode == 401) {
return {'success': false, 'message': '认证失败,请检查用户名和密码'}; return {'success': false, 'message': '认证失败,请检查用户名和密码'};
} else if (propfindResponse.statusCode == 404) { } else if (propfindResponse.statusCode == 404) {
// 目录不存在,尝试创建
print('WebDAV: Directory not found, trying to create...'); print('WebDAV: Directory not found, trying to create...');
} else if (propfindResponse.statusCode == 301 ||
propfindResponse.statusCode == 302 ||
propfindResponse.statusCode == 307 ||
propfindResponse.statusCode == 308) {
return {'success': false, 'message': '服务器重定向,请尝试使用 ${propfindResponse.headers["location"] ?? "其他地址"}'};
} else { } else {
return {'success': false, 'message': '服务器返回错误: ${propfindResponse.statusCode}'}; return {'success': false, 'message': '服务器返回错误: ${propfindResponse.statusCode}'};
} }
@@ -175,7 +177,6 @@ class WebDAVService {
print('WebDAV: PROPFIND error: $e'); print('WebDAV: PROPFIND error: $e');
} }
// 尝试创建目录
try { try {
final mkcolRequest = http.Request('MKCOL', Uri.parse(davUrl)); final mkcolRequest = http.Request('MKCOL', Uri.parse(davUrl));
mkcolRequest.headers['Authorization'] = _basicAuth(username, password); mkcolRequest.headers['Authorization'] = _basicAuth(username, password);
@@ -206,7 +207,7 @@ class WebDAVService {
} }
} }
/// 同步数据(双向同步) /// 同步数据(保留原有方法用于手动同步)
Future<SyncResult> syncData({SyncDirection direction = SyncDirection.bidirectional}) async { Future<SyncResult> syncData({SyncDirection direction = SyncDirection.bidirectional}) async {
final config = await getConfig(); final config = await getConfig();
if (config == null) { if (config == null) {
@@ -219,17 +220,13 @@ class WebDAVService {
final password = config['password']!; final password = config['password']!;
final path = config['path']!; final path = config['path']!;
// 获取本地数据库文件路径
final dbPath = await getDatabasesPath(); final dbPath = await getDatabasesPath();
final dbFile = File(p.join(dbPath, 'mooknote.db')); final dbFile = File(p.join(dbPath, 'mooknote.db'));
print('WebDAV: Looking for database at ${dbFile.path}');
if (!await dbFile.exists()) { if (!await dbFile.exists()) {
return SyncResult(success: false, message: '本地数据库不存在'); return SyncResult(success: false, message: '本地数据库不存在');
} }
// 构建 WebDAV URL
final baseUrl = url.endsWith('/') ? url.substring(0, url.length - 1) : url; final baseUrl = url.endsWith('/') ? url.substring(0, url.length - 1) : url;
var davUrl = '$baseUrl$path/mooknote.db'; var davUrl = '$baseUrl$path/mooknote.db';
final davImagesUrl = '$baseUrl$path/images'; final davImagesUrl = '$baseUrl$path/images';
@@ -241,37 +238,32 @@ class WebDAVService {
int downloadedImages = 0; int downloadedImages = 0;
try { try {
// 1. 检查远程数据库是否存在
final remoteDbInfo = await _getRemoteFileInfo(client, davUrl, username, password); final remoteDbInfo = await _getRemoteFileInfo(client, davUrl, username, password);
if (direction == SyncDirection.upload) { if (direction == SyncDirection.upload) {
// 仅上传模式
print('WebDAV: Upload only mode'); print('WebDAV: Upload only mode');
final result = await _uploadFile(client, davUrl, username, password, dbFile); final result = await _uploadFile(client, davUrl, username, password, dbFile);
if (result) { if (result) {
uploadedFiles++; uploadedFiles++;
// 同步图片
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.upload); final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.upload);
uploadedImages = imageResult.uploaded; uploadedImages = imageResult.uploaded;
downloadedImages = imageResult.downloaded;
} }
} else if (direction == SyncDirection.download) { } else if (direction == SyncDirection.download) {
// 仅下载模式
print('WebDAV: Download only mode'); print('WebDAV: Download only mode');
if (remoteDbInfo != null) { if (remoteDbInfo != null) {
final result = await _downloadFile(client, davUrl, username, password, dbFile); final result = await _downloadFile(client, davUrl, username, password, dbFile);
if (result) { if (result) {
downloadedFiles++; downloadedFiles++;
// 同步图片 // 重新打开数据库以应用新数据
await DatabaseHelper.instance.reopenDatabase();
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.download); final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.download);
uploadedImages = imageResult.uploaded;
downloadedImages = imageResult.downloaded; downloadedImages = imageResult.downloaded;
} }
} else { } else {
return SyncResult(success: false, message: '远程数据库不存在'); return SyncResult(success: false, message: '远程数据库不存在');
} }
} else { } else if (direction == SyncDirection.bidirectional) {
// 双向同步模式 // 双向同步:比较时间戳决定上传还是下载
print('WebDAV: Bidirectional sync mode'); print('WebDAV: Bidirectional sync mode');
if (remoteDbInfo == null) { if (remoteDbInfo == null) {
@@ -280,7 +272,6 @@ class WebDAVService {
final result = await _uploadFile(client, davUrl, username, password, dbFile); final result = await _uploadFile(client, davUrl, username, password, dbFile);
if (result) { if (result) {
uploadedFiles++; uploadedFiles++;
// 上传所有图片
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.upload); final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.upload);
uploadedImages = imageResult.uploaded; uploadedImages = imageResult.uploaded;
} }
@@ -300,10 +291,8 @@ class WebDAVService {
final result = await _uploadFile(client, davUrl, username, password, dbFile); final result = await _uploadFile(client, davUrl, username, password, dbFile);
if (result) { if (result) {
uploadedFiles++; uploadedFiles++;
// 同步图片 final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.upload);
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.bidirectional);
uploadedImages = imageResult.uploaded; uploadedImages = imageResult.uploaded;
downloadedImages = imageResult.downloaded;
} }
} else if (timeDiff < -10) { } else if (timeDiff < -10) {
// 远程较新,下载 // 远程较新,下载
@@ -311,13 +300,13 @@ class WebDAVService {
final result = await _downloadFile(client, davUrl, username, password, dbFile); final result = await _downloadFile(client, davUrl, username, password, dbFile);
if (result) { if (result) {
downloadedFiles++; downloadedFiles++;
// 同步图片 // 重新打开数据库以应用新数据
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.bidirectional); await DatabaseHelper.instance.reopenDatabase();
uploadedImages = imageResult.uploaded; final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.download);
downloadedImages = imageResult.downloaded; downloadedImages = imageResult.downloaded;
} }
} else { } else {
// 时间相近,视为相同 // 时间相近,仅同步图片
print('WebDAV: Local and remote are similar, syncing images only...'); print('WebDAV: Local and remote are similar, syncing images only...');
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.bidirectional); final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.bidirectional);
uploadedImages = imageResult.uploaded; uploadedImages = imageResult.uploaded;
@@ -326,11 +315,9 @@ class WebDAVService {
} }
} }
// 保存同步时间
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setString(_lastSyncKey, DateTime.now().toIso8601String()); await prefs.setString(_lastSyncKey, DateTime.now().toIso8601String());
// 如果下载了数据库文件,需要重新加载
final needReload = downloadedFiles > 0; final needReload = downloadedFiles > 0;
return SyncResult( return SyncResult(
@@ -366,7 +353,6 @@ class WebDAVService {
var response = await client.send(request); var response = await client.send(request);
// 处理重定向
if (response.statusCode == 301 || response.statusCode == 302 || if (response.statusCode == 301 || response.statusCode == 302 ||
response.statusCode == 307 || response.statusCode == 308) { response.statusCode == 307 || response.statusCode == 308) {
final location = response.headers['location']; final location = response.headers['location'];
@@ -380,9 +366,7 @@ class WebDAVService {
} }
if (response.statusCode == 207) { if (response.statusCode == 207) {
// 解析 PROPFIND 响应获取修改时间
final body = await response.stream.bytesToString(); final body = await response.stream.bytesToString();
// 简单解析,提取 getlastmodified
final modifiedMatch = RegExp(r'<d:getlastmodified>([^<]+)</d:getlastmodified>', caseSensitive: false) final modifiedMatch = RegExp(r'<d:getlastmodified>([^<]+)</d:getlastmodified>', caseSensitive: false)
.firstMatch(body); .firstMatch(body);
if (modifiedMatch != null) { if (modifiedMatch != null) {
@@ -399,6 +383,493 @@ class WebDAVService {
} }
} }
/// 启动自动同步
Future<void> startAutoSync() async {
if (_autoSyncTimer != null) {
_autoSyncTimer!.cancel();
}
final prefs = await SharedPreferences.getInstance();
_isAutoSyncEnabled = true;
await prefs.setBool(_autoSyncKey, true);
// 立即执行一次备份
await performTimedBackup();
// 设置定时器每5分钟执行一次
_autoSyncTimer = Timer.periodic(_autoSyncInterval, (timer) async {
if (_isAutoSyncEnabled) {
await performTimedBackup();
}
});
print('WebDAV: 自动备份已启动每2分钟执行一次');
}
/// 停止自动同步
Future<void> stopAutoSync() async {
_autoSyncTimer?.cancel();
_autoSyncTimer = null;
_isAutoSyncEnabled = false;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_autoSyncKey, false);
print('WebDAV: 自动备份已停止');
}
/// 检查自动同步状态
Future<bool> isAutoSyncEnabled() async {
if (_autoSyncTimer != null) {
return _isAutoSyncEnabled;
}
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(_autoSyncKey) ?? false;
}
/// 执行定时备份按时间命名保留最近10条
Future<SyncResult> performTimedBackup() async {
final config = await getConfig();
if (config == null) {
return SyncResult(success: false, message: '未配置 WebDAV');
}
try {
final url = config['url']!;
final username = config['username']!;
final password = config['password']!;
final basePath = config['path']!;
// 获取本地数据库文件路径
final dbPath = await getDatabasesPath();
final dbFile = File(p.join(dbPath, 'mooknote.db'));
if (!await dbFile.exists()) {
return SyncResult(success: false, message: '本地数据库不存在');
}
// 构建 WebDAV URL使用时间戳命名
final baseUrl = url.endsWith('/') ? url.substring(0, url.length - 1) : url;
final timestamp = _formatTimestamp(DateTime.now());
final backupFileName = 'mooknote_$timestamp.zip';
final davUrl = '$baseUrl$basePath/$backupFileName';
final davImagesUrl = '$baseUrl$basePath/images';
print('WebDAV: 开始定时备份到 $davUrl');
final client = http.Client();
int uploadedImages = 0;
try {
// 1. 创建完整的备份 ZIP包含数据库和图片
final zipBytes = await _createFullBackupZip(dbFile);
if (zipBytes == null) {
return SyncResult(success: false, message: '创建备份文件失败');
}
// 2. 上传备份文件
final success = await _uploadBytes(client, davUrl, username, password, zipBytes);
if (!success) {
return SyncResult(success: false, message: '上传备份文件失败');
}
// 3. 同步图片到 images 目录
final imageResult = await _syncImages(client, davImagesUrl, username, password, SyncDirection.upload);
uploadedImages = imageResult.uploaded;
// 4. 更新备份列表并清理旧备份
await _updateBackupListAndCleanup(client, baseUrl, basePath, username, password, backupFileName);
// 5. 保存同步时间
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_lastSyncKey, DateTime.now().toIso8601String());
print('WebDAV: 定时备份完成 - $backupFileName');
return SyncResult(
success: true,
message: '备份完成: $backupFileName',
lastSyncTime: DateTime.now(),
uploadedFiles: 1,
uploadedImages: uploadedImages,
needReload: false,
);
} finally {
client.close();
}
} catch (e) {
print('WebDAV: 定时备份错误: $e');
return SyncResult(success: false, message: '备份失败: $e');
}
}
/// 创建完整的备份 ZIP包含数据库和所有图片
/// 支持新的图片存储结构images/movies/{id}/、images/books/{id}/、images/notes/{id}/
Future<List<int>?> _createFullBackupZip(File dbFile) async {
try {
final archive = Archive();
// 添加数据库文件
final dbBytes = await dbFile.readAsBytes();
archive.addFile(ArchiveFile('mooknote.db', dbBytes.length, dbBytes));
// 添加所有图片(递归遍历子目录)
final appDir = await getApplicationDocumentsDirectory();
final imagesDir = Directory('${appDir.path}/images');
if (await imagesDir.exists()) {
await _addImagesToArchive(archive, imagesDir, 'images');
}
// 添加备份信息
final backupInfo = {
'version': 2,
'backupTime': DateTime.now().toIso8601String(),
'appName': 'MookNote',
'type': 'timed_backup',
'structure': 'hierarchical', // 标记为分层结构
};
final infoJson = jsonEncode(backupInfo);
final infoBytes = utf8.encode(infoJson);
archive.addFile(ArchiveFile('backup_info.json', infoBytes.length, infoBytes));
// 压缩
final zipEncoder = ZipEncoder();
return zipEncoder.encode(archive);
} catch (e) {
print('WebDAV: 创建备份 ZIP 失败: $e');
return null;
}
}
/// 递归添加图片到归档
Future<void> _addImagesToArchive(Archive archive, Directory dir, String relativePath) async {
await for (final entity in dir.list()) {
if (entity is File) {
final fileName = p.basename(entity.path);
final bytes = await entity.readAsBytes();
final archivePath = '$relativePath/$fileName';
archive.addFile(ArchiveFile(archivePath, bytes.length, bytes));
print('WebDAV: 添加文件到备份 - $archivePath');
} else if (entity is Directory) {
final dirName = p.basename(entity.path);
await _addImagesToArchive(archive, entity, '$relativePath/$dirName');
}
}
}
/// 更新备份列表并清理旧备份
Future<void> _updateBackupListAndCleanup(
http.Client client,
String baseUrl,
String basePath,
String username,
String password,
String newBackupName,
) async {
try {
final prefs = await SharedPreferences.getInstance();
// 获取现有备份列表
List<String> backupList = [];
final listJson = prefs.getString(_backupListKey);
if (listJson != null) {
backupList = List<String>.from(jsonDecode(listJson));
}
// 添加新备份
backupList.add(newBackupName);
// 如果超过10条删除最旧的备份
while (backupList.length > _maxBackupCount) {
final oldBackup = backupList.removeAt(0);
final deleteUrl = '$baseUrl$basePath/$oldBackup';
await _deleteFile(client, deleteUrl, username, password);
print('WebDAV: 删除旧备份 $oldBackup');
}
// 保存更新后的列表
await prefs.setString(_backupListKey, jsonEncode(backupList));
print('WebDAV: 备份列表已更新,当前 ${backupList.length} 个备份');
} catch (e) {
print('WebDAV: 更新备份列表失败: $e');
}
}
/// 删除远程文件
Future<void> _deleteFile(
http.Client client,
String url,
String username,
String password,
) async {
try {
var request = http.Request('DELETE', Uri.parse(url));
request.headers['Authorization'] = _basicAuth(username, password);
var response = await client.send(request);
// 处理重定向
if (response.statusCode == 301 || response.statusCode == 302 ||
response.statusCode == 307 || response.statusCode == 308) {
final location = response.headers['location'];
if (location != null) {
request = http.Request('DELETE', Uri.parse(location));
request.headers['Authorization'] = _basicAuth(username, password);
response = await client.send(request);
}
}
} catch (e) {
print('WebDAV: 删除文件失败: $e');
}
}
/// 上传字节数据
Future<bool> _uploadBytes(
http.Client client,
String url,
String username,
String password,
List<int> bytes,
) async {
try {
var request = http.Request('PUT', Uri.parse(url));
request.headers['Authorization'] = _basicAuth(username, password);
request.headers['Content-Type'] = 'application/zip';
request.bodyBytes = bytes;
var response = await client.send(request);
// 处理重定向
if (response.statusCode == 301 || response.statusCode == 302 ||
response.statusCode == 307 || response.statusCode == 308) {
final location = response.headers['location'];
if (location != null) {
request = http.Request('PUT', Uri.parse(location));
request.headers['Authorization'] = _basicAuth(username, password);
request.headers['Content-Type'] = 'application/zip';
request.bodyBytes = bytes;
response = await client.send(request);
}
}
return response.statusCode == 201 || response.statusCode == 204;
} catch (e) {
print('WebDAV: 上传失败: $e');
return false;
}
}
/// 格式化时间戳用于文件名
String _formatTimestamp(DateTime dateTime) {
return '${dateTime.year}${_pad(dateTime.month)}${_pad(dateTime.day)}_${_pad(dateTime.hour)}${_pad(dateTime.minute)}${_pad(dateTime.second)}';
}
String _pad(int number) {
return number.toString().padLeft(2, '0');
}
/// 同步图片(支持新的目录结构)
/// 同步 images/movies/{id}/、images/books/{id}/、images/notes/{id}/ 下的所有图片
Future<_ImageSyncResult> _syncImages(
http.Client client,
String imagesUrl,
String username,
String password,
SyncDirection direction,
) async {
int uploaded = 0;
int downloaded = 0;
try {
// 获取本地图片目录
final appDir = await getApplicationDocumentsDirectory();
final localImagesDir = Directory('${appDir.path}/images');
if (!await localImagesDir.exists()) {
await localImagesDir.create(recursive: true);
}
// 递归获取本地所有图片文件(包含子目录)
final localImages = <String, File>{}; // 相对路径 -> 文件
await _collectLocalImages(localImagesDir, localImages, '');
print('WebDAV: Local images: ${localImages.length}');
// 递归获取远程所有图片文件
final remoteImages = await _listRemoteImagesRecursive(client, imagesUrl, username, password, '');
print('WebDAV: Remote images: ${remoteImages.length}');
if (direction == SyncDirection.upload) {
// 仅上传:上传所有本地图片
for (final entry in localImages.entries) {
final relativePath = entry.key;
final remoteUrl = '$imagesUrl/$relativePath';
// 确保远程父目录存在
final parentPath = p.dirname(relativePath);
if (parentPath != '.' && parentPath.isNotEmpty) {
final parentUrl = '$imagesUrl/$parentPath';
await _ensureRemoteDir(client, parentUrl, username, password);
}
final success = await _uploadFile(client, remoteUrl, username, password, entry.value);
if (success) uploaded++;
}
} else if (direction == SyncDirection.download) {
// 仅下载:下载所有远程图片
for (final relativePath in remoteImages) {
final remoteUrl = '$imagesUrl/$relativePath';
final localFile = File('${localImagesDir.path}/$relativePath');
// 确保父目录存在
await localFile.parent.create(recursive: true);
final success = await _downloadFile(client, remoteUrl, username, password, localFile);
if (success) downloaded++;
}
}
} catch (e) {
print('WebDAV: Sync images error: $e');
}
return _ImageSyncResult(uploaded: uploaded, downloaded: downloaded);
}
/// 递归收集本地图片文件
Future<void> _collectLocalImages(Directory dir, Map<String, File> result, String relativePath) async {
await for (final entity in dir.list()) {
if (entity is File) {
final fileName = p.basename(entity.path);
final path = relativePath.isEmpty ? fileName : '$relativePath/$fileName';
result[path] = entity;
} else if (entity is Directory) {
final dirName = p.basename(entity.path);
final newRelativePath = relativePath.isEmpty ? dirName : '$relativePath/$dirName';
await _collectLocalImages(entity, result, newRelativePath);
}
}
}
/// 获取远程图片列表(递归获取所有子目录中的图片)
Future<List<String>> _listRemoteImagesRecursive(
http.Client client,
String imagesUrl,
String username,
String password,
String relativePath,
) async {
final images = <String>[];
final currentUrl = relativePath.isEmpty ? imagesUrl : '$imagesUrl/$relativePath';
try {
// 创建图片目录(如果不存在)
final mkcolRequest = http.Request('MKCOL', Uri.parse(currentUrl));
mkcolRequest.headers['Authorization'] = _basicAuth(username, password);
await client.send(mkcolRequest);
// 列出目录内容
var request = http.Request('PROPFIND', Uri.parse(currentUrl));
request.headers['Authorization'] = _basicAuth(username, password);
request.headers['Depth'] = '1';
var response = await client.send(request);
// 处理重定向
if (response.statusCode == 301 || response.statusCode == 302 ||
response.statusCode == 307 || response.statusCode == 308) {
final location = response.headers['location'];
if (location != null) {
final newUrl = location;
request = http.Request('PROPFIND', Uri.parse(newUrl));
request.headers['Authorization'] = _basicAuth(username, password);
request.headers['Depth'] = '1';
response = await client.send(request);
}
}
if (response.statusCode == 207) {
final body = await response.stream.bytesToString();
// 解析响应,提取文件和目录
final hrefMatches = RegExp(r'<d:href>([^<]+)</d:href>', caseSensitive: false)
.allMatches(body);
for (final match in hrefMatches) {
final href = match.group(1)!;
final name = p.basename(href);
// 跳过当前目录自身
if (name.isEmpty) continue;
if (relativePath.isEmpty && name == 'images') continue;
// 检查是文件还是目录
final isDirectory = body.substring(
match.start,
match.end + 200 < body.length ? match.end + 200 : body.length,
).contains('<d:collection');
if (isDirectory) {
// 递归获取子目录中的图片
final newRelativePath = relativePath.isEmpty ? name : '$relativePath/$name';
final subImages = await _listRemoteImagesRecursive(
client, imagesUrl, username, password, newRelativePath,
);
images.addAll(subImages);
} else {
// 是文件,添加到列表
final filePath = relativePath.isEmpty ? name : '$relativePath/$name';
images.add(filePath);
}
}
}
} catch (e) {
print('WebDAV: List remote images error: $e');
}
return images;
}
/// 确保远程目录存在
Future<void> _ensureRemoteDir(
http.Client client,
String dirUrl,
String username,
String password,
) async {
try {
var request = http.Request('MKCOL', Uri.parse(dirUrl));
request.headers['Authorization'] = _basicAuth(username, password);
var response = await client.send(request);
// 处理重定向
if (response.statusCode == 301 || response.statusCode == 302 ||
response.statusCode == 307 || response.statusCode == 308) {
final location = response.headers['location'];
if (location != null) {
request = http.Request('MKCOL', Uri.parse(location));
request.headers['Authorization'] = _basicAuth(username, password);
response = await client.send(request);
}
}
// 201 = 创建成功, 405 = 目录已存在, 409 = 父目录不存在需要先创建
if (response.statusCode == 409) {
// 需要创建父目录
final parentPath = p.dirname(dirUrl);
if (parentPath != dirUrl) {
await _ensureRemoteDir(client, parentPath, username, password);
// 再次尝试创建当前目录
request = http.Request('MKCOL', Uri.parse(dirUrl));
request.headers['Authorization'] = _basicAuth(username, password);
await client.send(request);
}
}
} catch (e) {
print('WebDAV: 创建目录失败: $e');
}
}
/// 上传文件 /// 上传文件
Future<bool> _uploadFile( Future<bool> _uploadFile(
http.Client client, http.Client client,
@@ -474,155 +945,6 @@ class WebDAVService {
} }
} }
/// 同步图片
Future<_ImageSyncResult> _syncImages(
http.Client client,
String imagesUrl,
String username,
String password,
SyncDirection direction,
) async {
int uploaded = 0;
int downloaded = 0;
try {
// 获取本地图片目录
final appDir = await getApplicationDocumentsDirectory();
final localImagesDir = Directory('${appDir.path}/images');
if (!await localImagesDir.exists()) {
await localImagesDir.create(recursive: true);
}
// 获取本地图片列表
final localImages = <String, File>{};
if (await localImagesDir.exists()) {
await for (final entity in localImagesDir.list()) {
if (entity is File) {
final name = p.basename(entity.path);
localImages[name] = entity;
}
}
}
print('WebDAV: Local images: ${localImages.length}');
// 获取远程图片列表
final remoteImages = await _listRemoteImages(client, imagesUrl, username, password);
print('WebDAV: Remote images: ${remoteImages.length}');
if (direction == SyncDirection.upload) {
// 仅上传:上传所有本地图片
for (final entry in localImages.entries) {
final remoteUrl = '$imagesUrl/${entry.key}';
final success = await _uploadFile(client, remoteUrl, username, password, entry.value);
if (success) uploaded++;
}
} else if (direction == SyncDirection.download) {
// 仅下载:下载所有远程图片
for (final name in remoteImages) {
final remoteUrl = '$imagesUrl/$name';
final localFile = File('${localImagesDir.path}/$name');
final success = await _downloadFile(client, remoteUrl, username, password, localFile);
if (success) downloaded++;
}
} else {
// 双向同步:比较时间戳
// 上传本地有但远程没有的
for (final entry in localImages.entries) {
if (!remoteImages.contains(entry.key)) {
final remoteUrl = '$imagesUrl/${entry.key}';
final success = await _uploadFile(client, remoteUrl, username, password, entry.value);
if (success) uploaded++;
}
}
// 下载远程有但本地没有的
for (final name in remoteImages) {
if (!localImages.containsKey(name)) {
final remoteUrl = '$imagesUrl/$name';
final localFile = File('${localImagesDir.path}/$name');
final success = await _downloadFile(client, remoteUrl, username, password, localFile);
if (success) downloaded++;
}
}
}
} catch (e) {
print('WebDAV: Sync images error: $e');
}
return _ImageSyncResult(uploaded: uploaded, downloaded: downloaded);
}
/// 获取远程图片列表
Future<List<String>> _listRemoteImages(
http.Client client,
String imagesUrl,
String username,
String password,
) async {
final images = <String>[];
try {
// 创建图片目录(如果不存在)
final mkcolRequest = http.Request('MKCOL', Uri.parse(imagesUrl));
mkcolRequest.headers['Authorization'] = _basicAuth(username, password);
await client.send(mkcolRequest);
// 列出目录内容
var request = http.Request('PROPFIND', Uri.parse(imagesUrl));
request.headers['Authorization'] = _basicAuth(username, password);
request.headers['Depth'] = '1';
var response = await client.send(request);
// 处理重定向
if (response.statusCode == 301 || response.statusCode == 302 ||
response.statusCode == 307 || response.statusCode == 308) {
final location = response.headers['location'];
if (location != null) {
imagesUrl = location;
request = http.Request('PROPFIND', Uri.parse(imagesUrl));
request.headers['Authorization'] = _basicAuth(username, password);
request.headers['Depth'] = '1';
response = await client.send(request);
}
}
if (response.statusCode == 207) {
final body = await response.stream.bytesToString();
// 解析响应,提取文件名
final hrefMatches = RegExp(r'<d:href>([^<]+)</d:href>', caseSensitive: false)
.allMatches(body);
for (final match in hrefMatches) {
final href = match.group(1)!;
final name = p.basename(href);
if (name.isNotEmpty && name != 'images') {
images.add(name);
}
}
}
} catch (e) {
print('WebDAV: List remote images error: $e');
}
return images;
}
/// 获取上次同步时间
Future<DateTime?> getLastSyncTime() async {
final prefs = await SharedPreferences.getInstance();
final timeStr = prefs.getString(_lastSyncKey);
if (timeStr != null) {
try {
return DateTime.parse(timeStr);
} catch (e) {
return null;
}
}
return null;
}
/// Basic Auth 编码 /// Basic Auth 编码
String _basicAuth(String username, String password) { String _basicAuth(String username, String password) {
final credentials = base64Encode(utf8.encode('$username:$password')); final credentials = base64Encode(utf8.encode('$username:$password'));

View File

@@ -1,6 +1,9 @@
import 'dart:io'; import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../providers/app_provider.dart';
import '../utils/toast_util.dart';
/// 书籍列表项组件 - 网格布局设计 /// 书籍列表项组件 - 网格布局设计
class BookListItem extends StatelessWidget { class BookListItem extends StatelessWidget {
@@ -14,6 +17,7 @@ class BookListItem extends StatelessWidget {
onTap: () { onTap: () {
Navigator.pushNamed(context, '/book-detail', arguments: book); Navigator.pushNamed(context, '/book-detail', arguments: book);
}, },
onLongPress: () => _showDeleteDialog(context),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@@ -94,4 +98,32 @@ class BookListItem extends StatelessWidget {
), ),
); );
} }
/// 显示删除确认对话框
void _showDeleteDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: Text('确定要删除《${book.title}》吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeBook(book.id);
Navigator.pop(context);
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
} }

View File

@@ -1,6 +1,9 @@
import 'dart:io'; import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../providers/app_provider.dart';
import '../utils/toast_util.dart';
/// 观影列表项组件 - 网格布局设计 /// 观影列表项组件 - 网格布局设计
class MovieListItem extends StatelessWidget { class MovieListItem extends StatelessWidget {
@@ -14,6 +17,7 @@ class MovieListItem extends StatelessWidget {
onTap: () { onTap: () {
Navigator.pushNamed(context, '/movie-detail', arguments: movie); Navigator.pushNamed(context, '/movie-detail', arguments: movie);
}, },
onLongPress: () => _showDeleteDialog(context),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@@ -95,4 +99,31 @@ class MovieListItem extends StatelessWidget {
); );
} }
/// 显示删除确认对话框
void _showDeleteDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: Text('确定要删除《${movie.title}》吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeMovie(movie.id);
Navigator.pop(context);
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
} }

View File

@@ -1,7 +1,9 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import '../utils/toast_util.dart';
/// 笔记列表项组件 - 极简主义设计 /// 笔记列表项组件 - 极简主义设计
class NoteListItem extends StatelessWidget { class NoteListItem extends StatelessWidget {
@@ -15,21 +17,22 @@ class NoteListItem extends StatelessWidget {
onTap: () { onTap: () {
Navigator.pushNamed(context, '/note-detail', arguments: note); Navigator.pushNamed(context, '/note-detail', arguments: note);
}, },
onLongPress: () => _showDeleteDialog(context),
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), margin: const EdgeInsets.only(bottom: 8),
decoration: const BoxDecoration( padding: const EdgeInsets.all(12),
border: Border( decoration: BoxDecoration(
bottom: BorderSide(color: Color(0xFFE5E5E5), width: 0.5), color: Colors.white,
), border: Border.all(color: const Color(0xFFE5E5E5)),
), ),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// 内容摘要 // 内容摘要(去除首尾空格)
Text( Text(
note.summary, note.summary.trim(),
style: const TextStyle( style: const TextStyle(
fontSize: 15, fontSize: 14,
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
height: 1.5, height: 1.5,
), ),
@@ -37,28 +40,54 @@ class NoteListItem extends StatelessWidget {
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
const SizedBox(height: 12), // 图片预览区域显示前2张图片
if (note.images.isNotEmpty) ...[
const SizedBox(height: 10),
SizedBox(
height: 60,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: note.images.length > 2 ? 2 : note.images.length,
itemBuilder: (context, index) {
return Container(
width: 60,
height: 60,
margin: const EdgeInsets.only(right: 8),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Image.file(
File(note.images[index]),
fit: BoxFit.cover,
),
);
},
),
),
],
// 底部信息:标签 + 时间 + 操作 const SizedBox(height: 10),
// 底部信息:标签 + 时间
Row( Row(
children: [ children: [
// 标签 // 标签
if (note.tags.isNotEmpty) ...[ if (note.tags.isNotEmpty) ...[
Expanded( Expanded(
child: Wrap( child: Wrap(
spacing: 8, spacing: 4,
runSpacing: 4, runSpacing: 4,
children: note.tags.take(3).map((tag) { children: note.tags.take(2).map((tag) {
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration( decoration: BoxDecoration(
color: const Color(0xFFF5F5F5), color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)), borderRadius: BorderRadius.circular(2),
), ),
child: Text( child: Text(
tag, tag,
style: const TextStyle( style: const TextStyle(
fontSize: 11, fontSize: 10,
color: Color(0xFF666666), color: Color(0xFF666666),
), ),
), ),
@@ -69,11 +98,36 @@ class NoteListItem extends StatelessWidget {
] else ] else
const Spacer(), const Spacer(),
// 时间 // 时间和图片数量
Row(
children: [
// 图片数量(如果有图片)
if (note.images.isNotEmpty) ...[
const Icon(
Icons.image_outlined,
size: 11,
color: Color(0xFF999999),
),
const SizedBox(width: 2),
Text(
'${note.images.length}',
style: const TextStyle(
fontSize: 11,
color: Color(0xFF999999),
),
),
const SizedBox(width: 6),
],
const Icon(
Icons.access_time,
size: 11,
color: Color(0xFF999999),
),
const SizedBox(width: 2),
Text( Text(
_formatDate(note.updatedAt), _formatDate(note.updatedAt),
style: const TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 11,
color: Color(0xFF999999), color: Color(0xFF999999),
), ),
), ),
@@ -81,6 +135,8 @@ class NoteListItem extends StatelessWidget {
), ),
], ],
), ),
],
),
), ),
); );
} }
@@ -104,4 +160,32 @@ class NoteListItem extends StatelessWidget {
return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}'; return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
} }
} }
/// 显示删除确认对话框
void _showDeleteDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: const Text('确定要删除这条笔记吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeNote(note.id);
Navigator.pop(context);
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
} }