From e4ed73d60408a3b1b818ec64b8e5cb97fc634f7e Mon Sep 17 00:00:00 2001 From: DelLevin-Home Date: Sun, 21 Jun 2026 10:28:09 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E6=9C=8D=E5=8A=A1=E5=99=A8?= =?UTF-8?q?=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/main.dart | 32 -- lib/pages/note/note_form_page.dart | 2 +- lib/pages/sync/cloud_sync_page.dart | 16 +- lib/pages/sync/server_sync_page.dart | 422 ---------------------- lib/providers/app_provider.dart | 258 ++------------ lib/utils/database_helper.dart | 18 - lib/utils/sync/server_data_service.dart | 385 -------------------- lib/utils/sync/server_sync_service.dart | 445 ------------------------ lib/utils/user_prefs.dart | 26 -- lib/widgets/fade_in_local_image.dart | 16 +- 10 files changed, 32 insertions(+), 1588 deletions(-) delete mode 100644 lib/pages/sync/server_sync_page.dart delete mode 100644 lib/utils/sync/server_data_service.dart delete mode 100644 lib/utils/sync/server_sync_service.dart diff --git a/lib/main.dart b/lib/main.dart index f740c43..b1dafa5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -11,7 +11,6 @@ import 'utils/app_router.dart'; import 'utils/user_prefs.dart'; import 'utils/changelog_service.dart'; import 'utils/sync/auto_backup_service.dart'; -import 'utils/sync/server_sync_service.dart'; import 'utils/usage_stats_service.dart'; import 'providers/app_provider.dart'; @@ -35,9 +34,6 @@ Future _bootstrap(AppProvider appProvider) async { } appProvider.initMainTabIndex(); - // sync 校验放到后台执行,不阻塞启动 - unawaited(_validateSyncOnStartup()); - unawaited(_initAutoBackup()); unawaited(_initUsageStats()); } @@ -61,34 +57,6 @@ Future _initUsageStats() async { } } -/// 启动时校验同步激活码:有效则继续,过期/失效则下载数据并关闭同步 -Future _validateSyncOnStartup() async { - try { - final prefs = UserPrefs(); - if (!prefs.syncEnabled || prefs.syncServerUrl.isEmpty || prefs.syncActivationCode.isEmpty) { - return; // 未开启同步,跳过 - } - - debugPrint('[Startup] 校验同步激活码...'); - final result = await ServerSyncService.instance.checkActivation(); - - if (result != null && result['valid'] == true) { - // 激活码有效,更新有效期信息 - await prefs.setSyncExpiresAt(result['expires_at'] ?? ''); - await prefs.setSyncIsPermanent(result['is_permanent'] == true); - debugPrint('[Startup] 激活码有效,继续同步模式'); - } else { - // 激活码无效/过期,下载服务端数据并关闭同步 - debugPrint('[Startup] 激活码失效: ${result?['error'] ?? '未知'},关闭同步并下载数据'); - await ServerSyncService.instance.downloadToLocal(); - await prefs.setSyncEnabled(false); - debugPrint('[Startup] 已切换到本地模式'); - } - } catch (e) { - debugPrint('[Startup] 激活码校验异常: $e'); - } -} - class MyApp extends StatefulWidget { final AppProvider appProvider; const MyApp({super.key, required this.appProvider}); diff --git a/lib/pages/note/note_form_page.dart b/lib/pages/note/note_form_page.dart index 4f7c379..417f9a9 100644 --- a/lib/pages/note/note_form_page.dart +++ b/lib/pages/note/note_form_page.dart @@ -524,7 +524,7 @@ class _NoteFormPageState extends State { Future _showAddTagDialog() async { final controller = TextEditingController(); - // 从 tags 表获取已有标签(sync 模式下走服务端 API) + // 从 tags 表获取已有标签 final provider = context.read(); final tagRows = await provider.getTags('note_tag'); final allTags = tagRows.map((t) => t['name'] as String).toSet(); diff --git a/lib/pages/sync/cloud_sync_page.dart b/lib/pages/sync/cloud_sync_page.dart index da05cd3..3ba2536 100644 --- a/lib/pages/sync/cloud_sync_page.dart +++ b/lib/pages/sync/cloud_sync_page.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'webdav_sync_page.dart'; -import 'server_sync_page.dart'; /// 云备份主页面 - 选择备份方式 class CloudSyncPage extends StatelessWidget { @@ -25,15 +24,6 @@ class CloudSyncPage extends StatelessWidget { onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const WebDAVSyncPage())), ), - const SizedBox(height: 12), - _buildOption( - colors: colors, - icon: Icons.sync_outlined, - title: '服务端实时同步', - subtitle: '自建服务端,多设备数据实时同步', - onTap: () => - Navigator.push(context, MaterialPageRoute(builder: (_) => const ServerSyncPage())), - ), const SizedBox(height: 28), _buildInfo(colors), ], @@ -142,11 +132,7 @@ class CloudSyncPage extends StatelessWidget { const SizedBox(height: 14), _infoItem(colors, 'WebDAV 备份:将数据备份到支持 WebDAV 的云盘'), const SizedBox(height: 8), - _infoItem(colors, '服务端实时同步:通过自建服务端实现多设备实时同步'), - const SizedBox(height: 8), - _infoItem(colors, '激活码由服务端管理员在管理后台生成'), - const SizedBox(height: 8), - _infoItem(colors, '建议定期备份 + 实时同步配合使用'), + _infoItem(colors, '建议定期备份到本地或云盘'), ]), ); } diff --git a/lib/pages/sync/server_sync_page.dart b/lib/pages/sync/server_sync_page.dart deleted file mode 100644 index 81180ea..0000000 --- a/lib/pages/sync/server_sync_page.dart +++ /dev/null @@ -1,422 +0,0 @@ -import 'dart:async'; -import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import '../../providers/app_provider.dart'; -import '../../utils/user_prefs.dart'; -import '../../utils/sync/server_sync_service.dart'; -import '../../utils/sync/server_data_service.dart'; -import '../../utils/toast_util.dart'; - -/// 服务端实时同步页面 -class ServerSyncPage extends StatefulWidget { - const ServerSyncPage({super.key}); - - @override - State createState() => _ServerSyncPageState(); -} - -class _ServerSyncPageState extends State { - final UserPrefs _prefs = UserPrefs(); - final _urlController = TextEditingController(); - final _codeController = TextEditingController(); - - bool _syncEnabled = false; - bool _isActivated = false; - bool _isChecking = false; - String _expiresText = ''; - Timer? _statusTimer; - - @override - void initState() { - super.initState(); - _loadSettings(); - } - - @override - void dispose() { - _urlController.dispose(); - _codeController.dispose(); - _statusTimer?.cancel(); - super.dispose(); - } - - void _loadSettings() { - final url = _prefs.syncServerUrl; - final code = _prefs.syncActivationCode; - _urlController.text = url; - _codeController.text = code; - _isActivated = url.isNotEmpty && code.isNotEmpty; - _syncEnabled = _isActivated && _prefs.syncEnabled; - _updateExpiresText(); - if (_isActivated) { - _startStatusPolling(); - _checkStatus(); // 立即向服务端验证 - } - } - - void _updateExpiresText() { - if (_prefs.syncIsPermanent) { - _expiresText = '永久有效'; - } else { - final exp = _prefs.syncExpiresAt; - if (exp.isNotEmpty) { - try { - final dt = DateTime.parse(exp).add(const Duration(hours: 8)); - _expiresText = '有效期至 ${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')} ' - '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}'; - } catch (_) { - _expiresText = '有效期至 $exp'; - } - } else { - _expiresText = ''; - } - } - } - - void _startStatusPolling() { - _statusTimer?.cancel(); - _statusTimer = Timer.periodic(const Duration(minutes: 1), (_) => _checkStatus()); - } - - Future _checkStatus() async { - if (!_isActivated) return; - final result = await ServerSyncService.instance.checkActivation(); - if (!mounted) return; - if (result == null || result['valid'] != true) { - await _prefs.setSyncEnabled(false); - setState(() { - _isActivated = false; - _syncEnabled = false; - _expiresText = '激活码已失效'; - }); - if (mounted) ToastUtil.show(context, '激活码已失效,同步已关闭'); - } else { - await _prefs.setSyncExpiresAt(result['expires_at'] ?? ''); - await _prefs.setSyncIsPermanent(result['is_permanent'] == true); - _updateExpiresText(); - } - } - - Future _checkActivation() async { - final url = _urlController.text.trim(); - final code = _codeController.text.trim().toUpperCase(); - if (url.isEmpty || code.isEmpty) { - ToastUtil.show(context, '请输入服务器地址和激活码'); - return; - } - setState(() => _isChecking = true); - await _prefs.setSyncServerUrl(url); - await _prefs.setSyncActivationCode(code); - - final result = await ServerSyncService.instance.checkActivation(); - if (!mounted) return; - setState(() => _isChecking = false); - - if (result != null && result['valid'] == true) { - _isActivated = true; - await _prefs.setSyncExpiresAt(result['expires_at'] ?? ''); - await _prefs.setSyncIsPermanent(result['is_permanent'] == true); - _updateExpiresText(); - _startStatusPolling(); - await _prefs.setSyncEnabled(true); - _syncEnabled = true; - await ServerSyncService.instance.syncWithServer(); - if (mounted) ToastUtil.show(context, '激活成功,实时同步已开启'); - } else { - final error = result?['error'] ?? '激活失败'; - if (mounted) ToastUtil.show(context, error.toString()); - } - } - - Future _toggleSync(bool value) async { - if (value && _isActivated) { - // 开启同步:合并本地与服务端数据 - await _prefs.setSyncEnabled(true); - if (!mounted) return; - setState(() => _syncEnabled = true); - if (mounted) ToastUtil.show(context, '正在同步数据...'); - await ServerSyncService.instance.syncWithServer(); - final provider = context.read(); - await provider.loadMovies(); - await provider.loadBooks(); - await provider.loadNotes(); - if (mounted) ToastUtil.show(context, '同步已开启,数据已合并'); - } else { - // 关闭同步:从服务器下载数据库和图片到本地 - if (mounted) ToastUtil.show(context, '正在从服务器下载数据...'); - final success = await ServerSyncService.instance.downloadToLocal(); - await _prefs.setSyncEnabled(false); - if (!mounted) return; - setState(() => _syncEnabled = false); - final provider = context.read(); - await provider.loadMovies(); - await provider.loadBooks(); - await provider.loadNotes(); - if (mounted) { - ToastUtil.show(context, success ? '数据已下载到本地' : '服务器无备份,保留本地数据'); - } - } - } - - Future _disconnect() async { - final confirm = await showDialog( - context: context, - builder: (ctx) { - final colors = Theme.of(ctx).colorScheme; - return AlertDialog( - backgroundColor: colors.surface, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - title: const Text('断开连接', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)), - content: Text('将清除服务器配置和激活信息,确定要断开吗?', - style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))), - actions: [ - TextButton( - onPressed: () => Navigator.pop(ctx, false), - child: Text('取消', style: TextStyle(color: colors.onSurface.withValues(alpha: 0.4)))), - TextButton( - onPressed: () => Navigator.pop(ctx, true), - child: const Text('确定', style: TextStyle(color: Color(0xFFE53935)))), - ], - ); - }, - ); - if (confirm != true) return; - - _statusTimer?.cancel(); - await _toggleSync(false); - await _prefs.setSyncServerUrl(''); - await _prefs.setSyncActivationCode(''); - await _prefs.setSyncExpiresAt(''); - await _prefs.setSyncIsPermanent(false); - await _prefs.setSyncEnabled(false); - - setState(() { - _isActivated = false; - _syncEnabled = false; - _expiresText = ''; - _urlController.clear(); - _codeController.clear(); - }); - if (mounted) ToastUtil.show(context, '已断开连接'); - } - - @override - Widget build(BuildContext context) { - final colors = Theme.of(context).colorScheme; - return Scaffold( - backgroundColor: colors.surfaceContainerHigh, - appBar: AppBar(title: const Text('服务端实时同步')), - body: ListView(padding: const EdgeInsets.all(20), children: [ - // 状态卡片 - Container( - padding: const EdgeInsets.all(20), - decoration: BoxDecoration( - color: colors.surface, - borderRadius: BorderRadius.circular(16), - boxShadow: [ - BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 8, offset: const Offset(0, 2)) - ], - ), - child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row(children: [ - Container( - width: 10, - height: 10, - decoration: BoxDecoration( - color: _isActivated - ? const Color(0xFF66BB6A) - : colors.onSurface.withValues(alpha: 0.15), - shape: BoxShape.circle)), - const SizedBox(width: 10), - Text(_isActivated ? '已激活' : '未激活', - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: _isActivated - ? const Color(0xFF66BB6A) - : colors.onSurface.withValues(alpha: 0.3))), - const Spacer(), - if (_isActivated) - GestureDetector( - onTap: _disconnect, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), - decoration: BoxDecoration( - color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), - child: const Text('断开', - style: TextStyle(fontSize: 12, color: Color(0xFFE57373)))), - ), - ]), - const SizedBox(height: 20), - Text('服务器地址', - style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), - const SizedBox(height: 6), - TextField( - controller: _urlController, - style: TextStyle(fontSize: 14, color: colors.onSurface), - decoration: _inputDeco(colors, '例: http://192.168.1.100:5000'), - ), - const SizedBox(height: 14), - Text('激活码', - style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), - const SizedBox(height: 6), - TextField( - controller: _codeController, - style: TextStyle(fontSize: 14, color: colors.onSurface), - textCapitalization: TextCapitalization.characters, - decoration: _inputDeco(colors, '例: MK-A1B2C3D4E5F6')), - const SizedBox(height: 16), - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: _isChecking ? null : _checkActivation, - style: ElevatedButton.styleFrom( - backgroundColor: colors.primary, - foregroundColor: colors.onPrimary, - disabledBackgroundColor: colors.onSurface.withValues(alpha: 0.15), - elevation: 0, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), - padding: const EdgeInsets.symmetric(vertical: 13)), - child: _isChecking - ? SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator(strokeWidth: 2, color: colors.onPrimary)) - : Text(_isActivated ? '重新验证' : '验证激活', - style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)), - ), - ), - if (_expiresText.isNotEmpty) ...[ - const SizedBox(height: 12), - Center( - child: Row(mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.access_time, - size: 14, - color: _prefs.syncIsPermanent - ? const Color(0xFF66BB6A) - : const Color(0xFFFF9800)), - const SizedBox(width: 6), - Text(_expiresText, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: _prefs.syncIsPermanent - ? const Color(0xFF66BB6A) - : const Color(0xFFFF9800))), - ])), - ], - ]), - ), - const SizedBox(height: 16), - // 同步开关 - Container( - padding: const EdgeInsets.all(20), - decoration: BoxDecoration( - color: colors.surface, - borderRadius: BorderRadius.circular(16), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.03), blurRadius: 8, offset: const Offset(0, 2)) - ]), - child: Row(children: [ - Container( - width: 44, - height: 44, - decoration: BoxDecoration( - color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(10)), - child: Icon(_syncEnabled ? Icons.sync : Icons.sync_disabled, - color: _syncEnabled - ? colors.primary - : colors.onSurface.withValues(alpha: 0.25), - size: 22)), - const SizedBox(width: 14), - Expanded( - child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('服务端实时同步', - style: TextStyle( - fontSize: 15, fontWeight: FontWeight.w500, color: colors.onSurface)), - const SizedBox(height: 2), - Text(_syncEnabled ? '使用服务端数据,多设备实时共享' : '关闭后下载数据到本地使用', - style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.3))), - ])), - Switch( - value: _syncEnabled, - onChanged: _isActivated ? _toggleSync : null, - activeThumbColor: colors.primary, - activeTrackColor: colors.primary.withValues(alpha: 0.3), - inactiveThumbColor: colors.surface, - inactiveTrackColor: colors.outline), - ]), - ), - const SizedBox(height: 24), - // 说明 - Container( - padding: const EdgeInsets.all(18), - decoration: BoxDecoration( - color: colors.surface, - borderRadius: BorderRadius.circular(14), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.03), blurRadius: 6, offset: const Offset(0, 2)) - ]), - child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row(children: [ - Container( - width: 36, - height: 36, - decoration: BoxDecoration( - color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(8)), - child: Icon(Icons.info_outline, - size: 18, color: colors.onSurface.withValues(alpha: 0.6))), - const SizedBox(width: 10), - Text('使用说明', - style: TextStyle( - fontSize: 14, fontWeight: FontWeight.w600, color: colors.onSurface)), - ]), - const SizedBox(height: 14), - _infoItem(colors, '1. 在服务端管理后台生成激活码'), - const SizedBox(height: 8), - _infoItem(colors, '2. 输入服务器地址和激活码完成验证'), - const SizedBox(height: 8), - _infoItem(colors, '3. 验证通过后自动开启实时同步'), - const SizedBox(height: 8), - _infoItem(colors, '4. 开启时所有数据通过服务端接口操作'), - const SizedBox(height: 8), - _infoItem(colors, '5. 关闭时从服务端下载数据到本地使用'), - ]), - ), - const SizedBox(height: 40), - ]), - ); - } - - InputDecoration _inputDeco(ColorScheme colors, String hint) { - return InputDecoration( - hintText: hint, - hintStyle: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.25)), - filled: true, - fillColor: colors.surfaceContainerHigh, - contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), - border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(10), - borderSide: BorderSide(color: colors.primary, width: 1)), - ); - } - - Widget _infoItem(ColorScheme colors, String text) { - return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container( - width: 5, - height: 5, - margin: const EdgeInsets.only(top: 6), - decoration: BoxDecoration( - color: colors.onSurface.withValues(alpha: 0.3), shape: BoxShape.circle)), - const SizedBox(width: 10), - Expanded( - child: Text(text, - style: TextStyle( - fontSize: 13, color: colors.onSurface.withValues(alpha: 0.5), height: 1.5))), - ]); - } -} diff --git a/lib/providers/app_provider.dart b/lib/providers/app_provider.dart index e5f772c..ac87af3 100644 --- a/lib/providers/app_provider.dart +++ b/lib/providers/app_provider.dart @@ -1,4 +1,3 @@ -import 'dart:io'; import 'package:flutter/material.dart'; import '../models/data_models.dart'; import '../utils/movie/movie_dao.dart'; @@ -14,7 +13,6 @@ import '../models/reader_book.dart'; import '../utils/database_helper.dart'; import '../utils/image_path_helper.dart'; import '../utils/user_prefs.dart'; -import '../utils/sync/server_data_service.dart'; /// 应用全局状态管理 class AppProvider extends ChangeNotifier { @@ -50,15 +48,6 @@ class AppProvider extends ChangeNotifier { // 配色方案索引 int _colorSchemeIndex = 0; - /// 是否使用远程服务端(同步开关 + 已激活) - bool get _useRemote { - final prefs = UserPrefs(); - return prefs.syncEnabled && - prefs.syncServerUrl.isNotEmpty && - prefs.syncActivationCode.isNotEmpty && - ServerDataService.instance.isAvailable; - } - // 观影选中的状态 (0: 已看,1: 想看,2: 在看) int _movieStatusIndex = 0; @@ -74,12 +63,7 @@ class AppProvider extends ChangeNotifier { // 初始化数据库 Future initDatabase() async { - debugPrint('[AppProvider] initDatabase, _useRemote=$_useRemote'); - if (_useRemote) { - // 同步模式:从服务端拉取数据 - await Future.wait([loadMovies(), loadBooks(), loadNotes()]); - return; - } + debugPrint('[AppProvider] initDatabase'); final results = await Future.wait([ _movieDao.getAllMovies(), _bookDao.getAllBooks(), @@ -120,39 +104,18 @@ class AppProvider extends ChangeNotifier { // 加载影视数据 Future loadMovies() async { - if (_useRemote) { - debugPrint('[AppProvider] loadMovies from server'); - _movies = await ServerDataService.instance.getMovies(); - debugPrint('[AppProvider] server movies: ${_movies.length}'); - notifyListeners(); - return; - } _movies = await _movieDao.getAllMovies(); notifyListeners(); } - + // 加载书籍数据 Future loadBooks() async { - if (_useRemote) { - debugPrint('[AppProvider] loadBooks from server'); - _books = await ServerDataService.instance.getBooks(); - debugPrint('[AppProvider] server books: ${_books.length}'); - notifyListeners(); - return; - } _books = await _bookDao.getAllBooks(); notifyListeners(); } // 加载笔记数据 Future loadNotes() async { - if (_useRemote) { - debugPrint('[AppProvider] loadNotes from server'); - _notes = await ServerDataService.instance.getNotes(); - debugPrint('[AppProvider] server notes: ${_notes.length}'); - notifyListeners(); - return; - } _notes = await _noteDao.getAllNotes(); notifyListeners(); } @@ -181,23 +144,14 @@ class AppProvider extends ChangeNotifier { static const int _pageSize = 20; Future> loadMoviesPaged({String? status, required int offset}) async { - if (_useRemote) { - return ServerDataService.instance.getMovies(status: status, limit: _pageSize, offset: offset); - } return _movieDao.getMoviesPaged(status: status, limit: _pageSize, offset: offset); } Future> loadBooksPaged({String? status, required int offset}) async { - if (_useRemote) { - return ServerDataService.instance.getBooks(status: status, limit: _pageSize, offset: offset); - } return _bookDao.getBooksPaged(status: status, limit: _pageSize, offset: offset); } Future> loadNotesPaged({required int offset}) async { - if (_useRemote) { - return ServerDataService.instance.getNotes(limit: _pageSize, offset: offset); - } return _noteDao.getNotesPaged(limit: _pageSize, offset: offset); } @@ -301,37 +255,14 @@ class AppProvider extends ChangeNotifier { // ─── 图片上传辅助 ──────────────────────────────────────────────── - Future _uploadImagesIfRemote(List paths) async { - if (!_useRemote) return; - final valid = paths.where((p) => p != null && p!.isNotEmpty).cast().toList(); - if (valid.isEmpty) return; - final exist = []; - for (final p in valid) { - if (File(p).existsSync()) exist.add(p); - } - if (exist.isNotEmpty) { - await ServerDataService.uploadLocalImages(exist); - } - } - // 添加影视记录 Future addMovie(Movie movie) async { - if (_useRemote) { - await ServerDataService.instance.saveMovie(movie); - } else { - await _movieDao.insertMovie(movie); - } - await _uploadImagesIfRemote([movie.posterPath]); + await _movieDao.insertMovie(movie); await loadMovies(); } Future updateMovie(Movie movie) async { - if (_useRemote) { - await ServerDataService.instance.saveMovie(movie); - } else { - await _movieDao.updateMovie(movie); - } - await _uploadImagesIfRemote([movie.posterPath]); + await _movieDao.updateMovie(movie); await loadMovies(); } @@ -356,69 +287,37 @@ class AppProvider extends ChangeNotifier { } Future removeMovie(String id) async { - if (_useRemote) { - await ServerDataService.instance.deleteMovie(id); - } else { - await _movieDao.deleteMovie(id); - } + await _movieDao.deleteMovie(id); await loadMovies(); } Future addBook(Book book) async { - if (_useRemote) { - await ServerDataService.instance.saveBook(book); - } else { - await _bookDao.insertBook(book); - } - await _uploadImagesIfRemote([book.coverPath]); + await _bookDao.insertBook(book); await loadBooks(); } Future updateBook(Book book) async { - if (_useRemote) { - await ServerDataService.instance.saveBook(book); - } else { - await _bookDao.updateBook(book); - } - await _uploadImagesIfRemote([book.coverPath]); + await _bookDao.updateBook(book); await loadBooks(); } Future removeBook(String id) async { - if (_useRemote) { - await ServerDataService.instance.deleteBook(id); - } else { - await _bookDao.deleteBook(id); - } + await _bookDao.deleteBook(id); await loadBooks(); } Future addNote(Note note) async { - if (_useRemote) { - await ServerDataService.instance.saveNote(note); - } else { - await _noteDao.insertNote(note); - } - await _uploadImagesIfRemote(note.images); + await _noteDao.insertNote(note); await loadNotes(); } Future updateNote(Note note) async { - if (_useRemote) { - await ServerDataService.instance.saveNote(note); - } else { - await _noteDao.updateNote(note); - } - await _uploadImagesIfRemote(note.images); + await _noteDao.updateNote(note); await loadNotes(); } Future removeNote(String id) async { - if (_useRemote) { - await ServerDataService.instance.deleteNote(id); - } else { - await _noteDao.deleteNote(id); - } + await _noteDao.deleteNote(id); await loadNotes(); } @@ -426,34 +325,26 @@ class AppProvider extends ChangeNotifier { /// 获取影视的所有影评 Future> getMovieReviews(String movieId) async { - if (_useRemote) return await ServerDataService.instance.getMovieReviews(movieId); return await _reviewDao.getReviewsByMovieId(movieId); } /// 添加影评 Future addMovieReview(MovieReview review) async { - if (_useRemote) await ServerDataService.instance.saveMovieReview(review); - else await _reviewDao.insertReview(review); + await _reviewDao.insertReview(review); } /// 更新影评 Future updateMovieReview(MovieReview review) async { - if (_useRemote) await ServerDataService.instance.saveMovieReview(review); - else await _reviewDao.updateReview(review); + await _reviewDao.updateReview(review); } /// 删除影评 Future removeMovieReview(String id) async { - if (_useRemote) await ServerDataService.instance.deleteMovieReview(id); - else await _reviewDao.deleteReview(id); + await _reviewDao.deleteReview(id); } /// 获取影视的影评数量 Future getMovieReviewCount(String movieId) async { - if (_useRemote) { - final reviews = await ServerDataService.instance.getMovieReviews(movieId); - return reviews.length; - } return await _reviewDao.getReviewCount(movieId); } @@ -461,22 +352,16 @@ class AppProvider extends ChangeNotifier { /// 获取影视的所有海报 Future> getMoviePosters(String movieId) async { - if (_useRemote) return await ServerDataService.instance.getMoviePosters(movieId); return await _posterDao.getPostersByMovieId(movieId); } /// 添加海报 Future addMoviePoster(MoviePoster poster) async { - if (_useRemote) await ServerDataService.instance.saveMoviePoster(poster); - else await _posterDao.insertPoster(poster); + await _posterDao.insertPoster(poster); } /// 删除海报 Future removeMoviePoster(String id) async { - if (_useRemote) { - await ServerDataService.instance.deleteMoviePoster(id); - return; - } final poster = await _posterDao.getPosterById(id); if (poster != null) { await ImagePathHelper.instance.deleteFile(poster.posterPath); @@ -486,10 +371,6 @@ class AppProvider extends ChangeNotifier { /// 获取影视的海报数量 Future getMoviePosterCount(String movieId) async { - if (_useRemote) { - final posters = await ServerDataService.instance.getMoviePosters(movieId); - return posters.length; - } return await _posterDao.getPosterCount(movieId); } @@ -497,34 +378,26 @@ class AppProvider extends ChangeNotifier { /// 获取书籍的所有书评 Future> getBookReviews(String bookId) async { - if (_useRemote) return await ServerDataService.instance.getBookReviews(bookId); return await _bookReviewDao.getReviewsByBookId(bookId); } /// 添加书评 Future addBookReview(BookReview review) async { - if (_useRemote) await ServerDataService.instance.saveBookReview(review); - else await _bookReviewDao.insertReview(review); + await _bookReviewDao.insertReview(review); } /// 更新书评 Future updateBookReview(BookReview review) async { - if (_useRemote) await ServerDataService.instance.saveBookReview(review); - else await _bookReviewDao.updateReview(review); + await _bookReviewDao.updateReview(review); } /// 删除书评 Future removeBookReview(String id) async { - if (_useRemote) await ServerDataService.instance.deleteBookReview(id); - else await _bookReviewDao.deleteReview(id); + await _bookReviewDao.deleteReview(id); } /// 获取书籍的书评数量 Future getBookReviewCount(String bookId) async { - if (_useRemote) { - final reviews = await ServerDataService.instance.getBookReviews(bookId); - return reviews.length; - } return await _bookReviewDao.getReviewCount(bookId); } @@ -532,34 +405,26 @@ class AppProvider extends ChangeNotifier { /// 获取书籍的所有摘抄 Future> getBookExcerpts(String bookId) async { - if (_useRemote) return await ServerDataService.instance.getBookExcerpts(bookId); return await _bookExcerptDao.getExcerptsByBookId(bookId); } /// 添加摘抄 Future addBookExcerpt(BookExcerpt excerpt) async { - if (_useRemote) await ServerDataService.instance.saveBookExcerpt(excerpt); - else await _bookExcerptDao.insertExcerpt(excerpt); + await _bookExcerptDao.insertExcerpt(excerpt); } /// 更新摘抄 Future updateBookExcerpt(BookExcerpt excerpt) async { - if (_useRemote) await ServerDataService.instance.saveBookExcerpt(excerpt); - else await _bookExcerptDao.updateExcerpt(excerpt); + await _bookExcerptDao.updateExcerpt(excerpt); } /// 删除摘抄 Future removeBookExcerpt(String id) async { - if (_useRemote) await ServerDataService.instance.deleteBookExcerpt(id); - else await _bookExcerptDao.deleteExcerpt(id); + await _bookExcerptDao.deleteExcerpt(id); } /// 获取书籍的摘抄数量 Future getBookExcerptCount(String bookId) async { - if (_useRemote) { - final excerpts = await ServerDataService.instance.getBookExcerpts(bookId); - return excerpts.length; - } return await _bookExcerptDao.getExcerptCount(bookId); } @@ -567,80 +432,53 @@ class AppProvider extends ChangeNotifier { /// 获取已删除的影视 Future> getDeletedMovies() async { - if (_useRemote) return ServerDataService.instance.getDeletedMovies(); return await _movieDao.getDeletedMovies(); } /// 恢复影视 Future restoreMovie(String id) async { - if (_useRemote) { - await ServerDataService.instance.restoreMovie(id); - } else { - await _movieDao.restoreMovie(id); - } + await _movieDao.restoreMovie(id); await loadMovies(); } /// 彻底删除影视 Future permanentDeleteMovie(String id) async { await ImagePathHelper.instance.deleteMovieImages(id); - if (_useRemote) { - await ServerDataService.instance.permanentDeleteMovie(id); - } else { - await _movieDao.permanentDeleteMovie(id); - } + await _movieDao.permanentDeleteMovie(id); } /// 获取已删除的书籍 Future> getDeletedBooks() async { - if (_useRemote) return ServerDataService.instance.getDeletedBooks(); return await _bookDao.getDeletedBooks(); } /// 恢复书籍 Future restoreBook(String id) async { - if (_useRemote) { - await ServerDataService.instance.restoreBook(id); - } else { - await _bookDao.restoreBook(id); - } + await _bookDao.restoreBook(id); await loadBooks(); } /// 彻底删除书籍 Future permanentDeleteBook(String id) async { await ImagePathHelper.instance.deleteBookImages(id); - if (_useRemote) { - await ServerDataService.instance.permanentDeleteBook(id); - } else { - await _bookDao.permanentDeleteBook(id); - } + await _bookDao.permanentDeleteBook(id); } /// 获取已删除的笔记 Future> getDeletedNotes() async { - if (_useRemote) return ServerDataService.instance.getDeletedNotes(); return await _noteDao.getDeletedNotes(); } /// 恢复笔记 Future restoreNote(String id) async { - if (_useRemote) { - await ServerDataService.instance.restoreNote(id); - } else { - await _noteDao.restoreNote(id); - } + await _noteDao.restoreNote(id); await loadNotes(); } /// 彻底删除笔记 Future permanentDeleteNote(String id) async { await ImagePathHelper.instance.deleteNoteImages(id); - if (_useRemote) { - await ServerDataService.instance.permanentDeleteNote(id); - } else { - await _noteDao.permanentDeleteNote(id); - } + await _noteDao.permanentDeleteNote(id); } /// 清空回收站 @@ -667,9 +505,6 @@ class AppProvider extends ChangeNotifier { // ========== 标签管理方法 ========== Future>> getTags(String type, {bool excludeHidden = false}) async { - if (_useRemote) { - return await ServerDataService.instance.getTags(type.isEmpty ? null : type); - } return await _tagDao.getTagsByType(type, excludeHidden: excludeHidden); } @@ -680,26 +515,14 @@ class AppProvider extends ChangeNotifier { Future addTag(String name, String type) async { final id = await _tagDao.addTag(name, type); - if (_useRemote) { - await ServerDataService.instance.saveTag(name, type); - } await _reloadByTagType(type); return id; } Future renameTag(String tagId, String newName, String type) async { - final tag = await _tagDao.getTagById(tagId); - final oldName = tag?['name'] as String?; final result = await _tagDao.renameTag(tagId, newName); if (result) { - if (_useRemote) { - if (oldName != null) { - await ServerDataService.instance.deleteTagByName(oldName, type); - } - await ServerDataService.instance.saveTag(newName, type); - await _pushAffectedByType(type); // 先推到服务端 - } - await _reloadByTagType(type); // 再从服务端拉最新 + await _reloadByTagType(type); } return result; } @@ -707,38 +530,15 @@ class AppProvider extends ChangeNotifier { Future deleteTag(String tagId, String type, {String? replacementName}) async { await _tagDao.deleteTag(tagId, replacementName: replacementName); - if (_useRemote) { - await ServerDataService.instance.deleteTag(tagId); - if (replacementName != null) { - await ServerDataService.instance.saveTag(replacementName, type); - } - await _pushAffectedByType(type); // 先推到服务端 - } - await _reloadByTagType(type); // 再从服务端拉最新 + await _reloadByTagType(type); } /// 仅删除标签本身,不级联影响已有条目 Future deleteTagOnly(String tagId, String type) async { await _tagDao.deleteTagOnly(tagId); - if (_useRemote) { - await ServerDataService.instance.deleteTag(tagId); - } await _reloadByTagType(type); } - /// 把某类型的所有条目推送到服务端(标签级联后调用) - Future _pushAffectedByType(String type) async { - final server = ServerDataService.instance; - switch (type) { - case 'movie_genre': - for (final m in _movies) { await server.saveMovie(m); } - case 'book_genre': - for (final b in _books) { await server.saveBook(b); } - case 'note_tag': - for (final n in _notes) { await server.saveNote(n); } - } - } - /// 从影视/书籍/笔记数据中解析标签,同步到 tags 表 Future syncTagsFromData() async { final db = await DatabaseHelper.instance.database; diff --git a/lib/utils/database_helper.dart b/lib/utils/database_helper.dart index 4280c1f..a0d62d0 100644 --- a/lib/utils/database_helper.dart +++ b/lib/utils/database_helper.dart @@ -1,7 +1,6 @@ import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import 'package:flutter/foundation.dart'; -import 'dart:io'; import '../models/data_models.dart'; /// 数据库帮助类 - 管理数据库的创建和版本控制 @@ -28,23 +27,6 @@ class DatabaseHelper { _database = await _initDB('mooknote.db'); } - /// 从备份字节重写数据库文件并安全重连, - /// 始终按当前代码的 targetVersion 重新初始化,避免版本不一致。 - Future reopenDatabaseFromBytes(Uint8List bytes) async { - await close(); - - final dbPath = await getDatabasesPath(); - final path = join(dbPath, 'mooknote.db'); - - final dbFile = File(path); - if (await dbFile.exists()) { - await dbFile.delete(); - } - - await dbFile.writeAsBytes(bytes, flush: true); - _database = await _initDB('mooknote.db'); - } - Future get database async { if (_database != null) return _database!; _database = await _initDB('mooknote.db'); diff --git a/lib/utils/sync/server_data_service.dart b/lib/utils/sync/server_data_service.dart deleted file mode 100644 index a59d041..0000000 --- a/lib/utils/sync/server_data_service.dart +++ /dev/null @@ -1,385 +0,0 @@ -import 'dart:convert'; -import 'dart:io'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; -import 'package:path_provider/path_provider.dart'; -import 'package:path/path.dart' as p; -import '../../models/data_models.dart'; -import '../user_prefs.dart'; - -/// 服务端数据服务 - 所有数据操作通过远程 API -class ServerDataService { - static final ServerDataService instance = ServerDataService._(); - ServerDataService._(); - - final UserPrefs _prefs = UserPrefs(); - - String get _baseUrl => _prefs.syncServerUrl; - String get _code => _prefs.syncActivationCode; - - Map get _headers => {'Content-Type': 'application/json'}; - - Map _body([Map? extra]) { - return {'code': _code, ...?extra}; - } - - bool get isAvailable => _baseUrl.isNotEmpty && _code.isNotEmpty; - - Future _post(String path, [Map? extra]) async { - try { - final url = '$_baseUrl$path'; - debugPrint('[ServerData] POST $url'); - final resp = await http.post( - Uri.parse(url), - headers: _headers, - body: jsonEncode(_body(extra)), - ).timeout(const Duration(seconds: 30)); - debugPrint('[ServerData] ${resp.statusCode} $path'); - if (resp.statusCode != 200) return null; - return jsonDecode(resp.body); - } catch (e) { - debugPrint('[ServerData] ERROR $path: $e'); - return null; - } - } - - // ─── 影视 ──────────────────────────────────────────────────── - - Future> getMovies({String? status, int? limit, int? offset}) async { - final body = {}; - if (status != null && status.isNotEmpty) body['status'] = status; - if (limit != null) body['limit'] = limit; - if (offset != null) body['offset'] = offset; - final data = await _post('/api/data/movies', body.isEmpty ? null : body); - if (data == null || data['movies'] == null) return []; - return (data['movies'] as List).map((m) => Movie.fromJson(m as Map)).toList(); - } - - Future saveMovie(Movie movie) async { - final data = await _post('/api/data/movie/save', {'movie': movie.toJson()}); - return data != null; - } - - Future deleteMovie(String id) async { - final data = await _post('/api/data/movie/delete', {'id': id}); - return data != null; - } - - // ─── 书籍 ──────────────────────────────────────────────────── - - Future> getBooks({String? status, int? limit, int? offset}) async { - final body = {}; - if (status != null && status.isNotEmpty) body['status'] = status; - if (limit != null) body['limit'] = limit; - if (offset != null) body['offset'] = offset; - final data = await _post('/api/data/books', body.isEmpty ? null : body); - if (data == null || data['books'] == null) return []; - return (data['books'] as List).map((b) => Book.fromJson(b as Map)).toList(); - } - - Future saveBook(Book book) async { - final data = await _post('/api/data/book/save', {'book': book.toJson()}); - return data != null; - } - - Future deleteBook(String id) async { - final data = await _post('/api/data/book/delete', {'id': id}); - return data != null; - } - - // ─── 笔记 ──────────────────────────────────────────────────── - - Future> getNotes({int? limit, int? offset}) async { - final body = {}; - if (limit != null) body['limit'] = limit; - if (offset != null) body['offset'] = offset; - final data = await _post('/api/data/notes', body.isEmpty ? null : body); - if (data == null || data['notes'] == null) return []; - return (data['notes'] as List).map((n) => Note.fromJson(n as Map)).toList(); - } - - Future saveNote(Note note) async { - final data = await _post('/api/data/note/save', {'note': note.toJson()}); - return data != null; - } - - Future deleteNote(String id) async { - final data = await _post('/api/data/note/delete', {'id': id}); - return data != null; - } - - // ─── 回收站 ──────────────────────────────────────────────────── - - Future> getDeletedMovies() async { - final data = await _post('/api/data/movies/deleted'); - if (data == null || data['movies'] == null) return []; - return (data['movies'] as List).map((m) => Movie.fromJson(m as Map)).toList(); - } - - Future restoreMovie(String id) async { - final data = await _post('/api/data/movie/restore', {'id': id}); - return data != null; - } - - Future permanentDeleteMovie(String id) async { - final data = await _post('/api/data/movie/permanent_delete', {'id': id}); - return data != null; - } - - Future> getDeletedBooks() async { - final data = await _post('/api/data/books/deleted'); - if (data == null || data['books'] == null) return []; - return (data['books'] as List).map((b) => Book.fromJson(b as Map)).toList(); - } - - Future restoreBook(String id) async { - final data = await _post('/api/data/book/restore', {'id': id}); - return data != null; - } - - Future permanentDeleteBook(String id) async { - final data = await _post('/api/data/book/permanent_delete', {'id': id}); - return data != null; - } - - Future> getDeletedNotes() async { - final data = await _post('/api/data/notes/deleted'); - if (data == null || data['notes'] == null) return []; - return (data['notes'] as List).map((n) => Note.fromJson(n as Map)).toList(); - } - - Future restoreNote(String id) async { - final data = await _post('/api/data/note/restore', {'id': id}); - return data != null; - } - - Future permanentDeleteNote(String id) async { - final data = await _post('/api/data/note/permanent_delete', {'id': id}); - return data != null; - } - - // ─── 影评 ──────────────────────────────────────────────────── - - Future> getMovieReviews(String movieId) async { - final data = await _post('/api/data/movie_reviews', {'movie_id': movieId}); - if (data == null || data['reviews'] == null) return []; - return (data['reviews'] as List).map((r) => MovieReview.fromJson(r as Map)).toList(); - } - - Future> getAllMovieReviews() async { - final data = await _post('/api/data/movie_reviews'); - if (data == null || data['reviews'] == null) return []; - return (data['reviews'] as List).map((r) => MovieReview.fromJson(r as Map)).toList(); - } - - Future saveMovieReview(MovieReview review) async { - final data = await _post('/api/data/movie_review/save', {'review': review.toJson()}); - return data != null; - } - - Future deleteMovieReview(String id) async { - final data = await _post('/api/data/movie_review/delete', {'id': id}); - return data != null; - } - - // ─── 海报 ──────────────────────────────────────────────────── - - Future> getMoviePosters(String movieId) async { - final data = await _post('/api/data/movie_posters', {'movie_id': movieId}); - if (data == null || data['posters'] == null) return []; - return (data['posters'] as List).map((p) => MoviePoster.fromJson(p as Map)).toList(); - } - - Future> getAllMoviePosters() async { - final data = await _post('/api/data/movie_posters'); - if (data == null || data['posters'] == null) return []; - return (data['posters'] as List).map((p) => MoviePoster.fromJson(p as Map)).toList(); - } - - Future saveMoviePoster(MoviePoster poster) async { - final data = await _post('/api/data/movie_poster/save', {'poster': poster.toJson()}); - return data != null; - } - - Future deleteMoviePoster(String id) async { - final data = await _post('/api/data/movie_poster/delete', {'id': id}); - return data != null; - } - - // ─── 书评 ──────────────────────────────────────────────────── - - Future> getBookReviews(String bookId) async { - final data = await _post('/api/data/book_reviews', {'book_id': bookId}); - if (data == null || data['reviews'] == null) return []; - return (data['reviews'] as List).map((r) => BookReview.fromJson(r as Map)).toList(); - } - - Future> getAllBookReviews() async { - final data = await _post('/api/data/book_reviews'); - if (data == null || data['reviews'] == null) return []; - return (data['reviews'] as List).map((r) => BookReview.fromJson(r as Map)).toList(); - } - - Future saveBookReview(BookReview review) async { - final data = await _post('/api/data/book_review/save', {'review': review.toJson()}); - return data != null; - } - - Future deleteBookReview(String id) async { - final data = await _post('/api/data/book_review/delete', {'id': id}); - return data != null; - } - - // ─── 书摘 ──────────────────────────────────────────────────── - - Future> getBookExcerpts(String bookId) async { - final data = await _post('/api/data/book_excerpts', {'book_id': bookId}); - if (data == null || data['excerpts'] == null) return []; - return (data['excerpts'] as List).map((e) => BookExcerpt.fromJson(e as Map)).toList(); - } - - Future> getAllBookExcerpts() async { - final data = await _post('/api/data/book_excerpts'); - if (data == null || data['excerpts'] == null) return []; - return (data['excerpts'] as List).map((e) => BookExcerpt.fromJson(e as Map)).toList(); - } - - Future saveBookExcerpt(BookExcerpt excerpt) async { - final data = await _post('/api/data/book_excerpt/save', {'excerpt': excerpt.toJson()}); - return data != null; - } - - Future deleteBookExcerpt(String id) async { - final data = await _post('/api/data/book_excerpt/delete', {'id': id}); - return data != null; - } - - // ─── 批量同步 ──────────────────────────────────────────────── - - Future> batchSync({ - List? movies, - List? books, - List? notes, - List>? tags, - List>? movieReviews, - List>? moviePosters, - List>? bookReviews, - List>? bookExcerpts, - }) async { - final data = await _post('/api/data/batch_sync', { - if (movies != null) 'movies': movies.map((m) => m.toJson()).toList(), - if (books != null) 'books': books.map((b) => b.toJson()).toList(), - if (notes != null) 'notes': notes.map((n) => n.toJson()).toList(), - if (tags != null) 'tags': tags, - if (movieReviews != null) 'movie_reviews': movieReviews, - if (moviePosters != null) 'movie_posters': moviePosters, - if (bookReviews != null) 'book_reviews': bookReviews, - if (bookExcerpts != null) 'book_excerpts': bookExcerpts, - }); - if (data == null) return {}; - return { - 'movies': (data['movies'] as int?) ?? 0, - 'books': (data['books'] as int?) ?? 0, - 'notes': (data['notes'] as int?) ?? 0, - 'tags': (data['tags'] as int?) ?? 0, - 'movie_reviews': (data['movie_reviews'] as int?) ?? 0, - 'movie_posters': (data['movie_posters'] as int?) ?? 0, - 'book_reviews': (data['book_reviews'] as int?) ?? 0, - 'book_excerpts': (data['book_excerpts'] as int?) ?? 0, - }; - } - - // ─── 标签 ──────────────────────────────────────────────────── - - Future>> getTags(String? type) async { - final data = await _post('/api/data/tags', type != null ? {'type': type} : null); - if (data == null || data['tags'] == null) return []; - return (data['tags'] as List).map((t) => Map.from(t as Map)).toList(); - } - - Future saveTag(String name, String type) async { - final data = await _post('/api/data/tag/save', {'tag': {'name': name, 'type': type}}); - return data != null; - } - - Future deleteTag(String id) async { - final data = await _post('/api/data/tag/delete', {'id': id}); - return data != null; - } - - Future deleteTagByName(String name, String type) async { - final data = await _post('/api/data/tag/delete_by_name', {'name': name, 'type': type}); - return data != null; - } - - // ─── 图片 ──────────────────────────────────────────────────── - - /// 是否激活(AppProvider 也会用这个检查) - static bool get isActive { - final p = UserPrefs(); - return p.syncEnabled && p.syncServerUrl.isNotEmpty && p.syncActivationCode.isNotEmpty; - } - - /// 将本地路径转为服务端图片 URL - static Future toImageUrl(String localPath) async { - if (!isActive) return localPath; - final appDir = (await getApplicationDocumentsDirectory()).path; - final relPath = p.relative(localPath, from: appDir).replaceAll('\\', '/'); - final prefs = UserPrefs(); - return '${prefs.syncServerUrl}/api/data/image/${prefs.syncActivationCode}/$relPath'; - } - - /// 批量上传图片到服务端(自动计算相对路径) - static Future uploadLocalImages(List filePaths) async { - debugPrint('[Sync] uploadLocalImages: isActive=$isActive count=${filePaths.length}'); - if (!isActive || filePaths.isEmpty) return; - debugPrint('[Sync] 调用 uploadImages...'); - final result = await instance.uploadImages(filePaths); - debugPrint('[Sync] uploadImages 返回: ${result.length} 个文件'); - } - - /// 上传单张图片到服务端 - static Future uploadLocalImage(String filePath) async { - if (!isActive || filePath.isEmpty) return; - final result = await instance.uploadImage(filePath); - debugPrint('[Sync] 上传图片: ${result ?? "失败"}'); - } - - String imageUrl(String relPath) { - return '$_baseUrl/api/data/image/$_code/$relPath'; - } - - Future> uploadImages(List filePaths) async { - debugPrint('[Sync] uploadImages: 准备上传 ${filePaths.length} 个文件到 $_baseUrl/api/data/image/upload'); - final request = http.MultipartRequest('POST', Uri.parse('$_baseUrl/api/data/image/upload')); - request.fields['code'] = _code; - final appDir = (await getApplicationDocumentsDirectory()).path; - for (final path in filePaths) { - final relPath = p.relative(path, from: appDir).replaceAll('\\', '/'); - final file = File(path); - final exists = await file.exists(); - final size = exists ? await file.length() : 0; - debugPrint('[Sync] 图片: $relPath (存在=$exists 大小=$size)'); - if (exists) { - final bytes = await file.readAsBytes(); - request.files.add(http.MultipartFile.fromBytes( - 'images', bytes, - filename: relPath, - )); - } - } - debugPrint('[Sync] 发送 upload 请求 (${request.files.length} 个文件)...'); - final resp = await request.send().timeout(const Duration(seconds: 60)); - debugPrint('[Sync] upload 响应: ${resp.statusCode}'); - if (resp.statusCode != 200) return []; - final body = await resp.stream.bytesToString(); - debugPrint('[Sync] upload 响应体: $body'); - final data = jsonDecode(body) as Map; - return (data['files'] as List?)?.cast() ?? []; - } - - Future uploadImage(String filePath) async { - final files = await uploadImages([filePath]); - return files.isNotEmpty ? files.first : null; - } -} diff --git a/lib/utils/sync/server_sync_service.dart b/lib/utils/sync/server_sync_service.dart deleted file mode 100644 index 621d224..0000000 --- a/lib/utils/sync/server_sync_service.dart +++ /dev/null @@ -1,445 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; -import 'package:path_provider/path_provider.dart'; -import 'package:path/path.dart' as p; -import 'package:sqflite/sqflite.dart'; -import '../user_prefs.dart'; -import '../database_helper.dart'; -import '../../models/data_models.dart'; -import '../movie/movie_dao.dart'; -import '../book/book_dao.dart'; -import '../note/note_dao.dart'; -import 'server_data_service.dart'; - -/// 服务端实时同步服务 -/// - 开启时:智能合并本地与服务端数据 -/// - 关闭时:从服务器下载数据到本地 -class ServerSyncService { - static final ServerSyncService instance = ServerSyncService._(); - ServerSyncService._(); - - final UserPrefs _prefs = UserPrefs(); - bool _isSyncing = false; - - bool get isConfigured { - return _prefs.syncServerUrl.isNotEmpty && _prefs.syncActivationCode.isNotEmpty; - } - - Future?> checkActivation() async { - final url = _prefs.syncServerUrl; - final code = _prefs.syncActivationCode; - final deviceId = _prefs.deviceId; - if (url.isEmpty || code.isEmpty || deviceId.isEmpty) return null; - try { - final resp = await http.post( - Uri.parse('$url/api/activate'), - headers: {'Content-Type': 'application/json'}, - body: '{"code":"$code","device_id":"$deviceId"}', - ).timeout(const Duration(seconds: 5)); - return resp.statusCode == 200 - ? _jsonDecode(resp.body) - : {'valid': false, 'error': '激活码无效'}; - } catch (_) { - return {'valid': false, 'error': '无法连接服务器'}; - } - } - - Map? _jsonDecode(String s) { - try { final d = jsonDecode(s); return d is Map ? d : null; } catch (_) { return null; } - } - - /// 开启同步:智能合并本地与服务端数据 - Future syncWithServer() async { - if (!isConfigured || _isSyncing) { - debugPrint('[Sync] 跳过: configured=$isConfigured syncing=$_isSyncing'); - return false; - } - _isSyncing = true; - try { - debugPrint('[Sync] ========== 开始同步 =========='); - final server = ServerDataService.instance; - - // 读取本地数据 - final localMovies = await MovieDao().getAllMovies(); - final localBooks = await BookDao().getAllBooks(); - final localNotes = await NoteDao().getAllNotes(); - final db = await DatabaseHelper.instance.database; - final localMovieReviews = await db.query('movie_reviews'); - final localMoviePosters = await db.query('movie_posters'); - final localBookReviews = await db.query('book_reviews'); - final localBookExcerpts = await db.query('book_excerpts'); - - debugPrint('[Sync] 本地: 影视${localMovies.length} 书籍${localBooks.length} 笔记${localNotes.length} ' - '影评${localMovieReviews.length} 海报${localMoviePosters.length} ' - '书评${localBookReviews.length} 书摘${localBookExcerpts.length}'); - - // 读取服务端数据 - final remoteMovies = await server.getMovies(); - final remoteBooks = await server.getBooks(); - final remoteNotes = await server.getNotes(); - - debugPrint('[Sync] 服务端: 影视${remoteMovies.length} 书籍${remoteBooks.length} 笔记${remoteNotes.length}'); - - // 需要 push 到服务端的数据 - final pushMovies = []; - final pushBooks = []; - final pushNotes = []; - final pushMovieReviews = >[]; - final pushMoviePosters = >[]; - final pushBookReviews = >[]; - final pushBookExcerpts = >[]; - - // 服务端无数据 → 全量 push - if (remoteMovies.isEmpty && remoteBooks.isEmpty && remoteNotes.isEmpty) { - pushMovies.addAll(localMovies); - pushBooks.addAll(localBooks); - pushNotes.addAll(localNotes); - pushMovieReviews.addAll(localMovieReviews); - pushMoviePosters.addAll(localMoviePosters); - pushBookReviews.addAll(localBookReviews); - pushBookExcerpts.addAll(localBookExcerpts); - } else { - // 按 updated_at 合并 - final remoteMovieMap = {for (final m in remoteMovies) m.id: m}; - for (final m in localMovies) { - final r = remoteMovieMap.remove(m.id); - if (r == null || m.updatedAt.isAfter(r.updatedAt)) { - pushMovies.add(m); - } else { - await _upsertLocalMovie(m: r); - } - } - for (final r in remoteMovieMap.values) { - await _upsertLocalMovie(m: r); - } - - final remoteBookMap = {for (final b in remoteBooks) b.id: b}; - for (final b in localBooks) { - final r = remoteBookMap.remove(b.id); - if (r == null || b.updatedAt.isAfter(r.updatedAt)) { - pushBooks.add(b); - } else { - await _upsertLocalBook(b: r); - } - } - for (final r in remoteBookMap.values) { - await _upsertLocalBook(b: r); - } - - final remoteNoteMap = {for (final n in remoteNotes) n.id: n}; - for (final n in localNotes) { - final r = remoteNoteMap.remove(n.id); - if (r == null || n.updatedAt.isAfter(r.updatedAt)) { - pushNotes.add(n); - } else { - await _upsertLocalNote(n: r); - } - } - for (final r in remoteNoteMap.values) { - await _upsertLocalNote(n: r); - } - - // 子表合并:movie_reviews / movie_posters / book_reviews / book_excerpts - await _mergeSubTable(db, server, 'movie_reviews', localMovieReviews, pushMovieReviews); - await _mergeSubTable(db, server, 'movie_posters', localMoviePosters, pushMoviePosters); - await _mergeSubTable(db, server, 'book_reviews', localBookReviews, pushBookReviews); - await _mergeSubTable(db, server, 'book_excerpts', localBookExcerpts, pushBookExcerpts); - } - - // 收集所有本地图片路径 - final allImagePaths = _collectAllLocalImages( - localMovies, localBooks, localNotes, localMoviePosters); - debugPrint('[Sync] 全部图片: ${allImagePaths.length} 张'); - - // 先下载本地缺失的图片 - final missingImages = []; - final existingImages = []; - for (final p in allImagePaths) { - if (await File(p).exists()) { - existingImages.add(p); - } else { - missingImages.add(p); - } - } - debugPrint('[Sync] 缺失${missingImages.length}张 现有${existingImages.length}张'); - - if (missingImages.isNotEmpty) { - debugPrint('[Sync] 下载缺失图片...'); - final appDir = (await getApplicationDocumentsDirectory()).path; - for (final path in missingImages) { - try { - final relPath = p.relative(path, from: appDir).replaceAll('\\', '/'); - final url = '${_prefs.syncServerUrl}/api/data/image/${_prefs.syncActivationCode}/$relPath'; - final resp = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 15)); - if (resp.statusCode == 200) { - final dest = File(path); - await dest.parent.create(recursive: true); - await dest.writeAsBytes(resp.bodyBytes); - } - } catch (_) {} - } - debugPrint('[Sync] 缺失图片下载完成'); - } - - // 上传本地已有图片 - if (existingImages.isNotEmpty) { - debugPrint('[Sync] 上传 ${existingImages.length} 张现有图片...'); - await ServerDataService.uploadLocalImages(existingImages); - } - - // 批量 push 数据到服务端 - final hasPush = pushMovies.isNotEmpty || pushBooks.isNotEmpty || pushNotes.isNotEmpty || - pushMovieReviews.isNotEmpty || pushMoviePosters.isNotEmpty || - pushBookReviews.isNotEmpty || pushBookExcerpts.isNotEmpty; - debugPrint('[Sync] hasPush=$hasPush'); - if (hasPush) { - final localTags = await db.query('tags'); - final result = await server.batchSync( - movies: pushMovies.isEmpty ? null : pushMovies, - books: pushBooks.isEmpty ? null : pushBooks, - notes: pushNotes.isEmpty ? null : pushNotes, - tags: localTags.isEmpty ? null : localTags.cast>(), - movieReviews: pushMovieReviews.isEmpty ? null : pushMovieReviews, - moviePosters: pushMoviePosters.isEmpty ? null : pushMoviePosters, - bookReviews: pushBookReviews.isEmpty ? null : pushBookReviews, - bookExcerpts: pushBookExcerpts.isEmpty ? null : pushBookExcerpts, - ); - debugPrint('[Sync] batchSync 结果: $result'); - } - - debugPrint('[Sync] 合并完成'); - return true; - } catch (e) { - debugPrint('[Sync] 合并异常: $e'); - return false; - } finally { - _isSyncing = false; - } - } - - // ─── 合并辅助方法 ──────────────────────────────────────────── - - Future _upsertLocalMovie({required Movie m}) async { - final db = await DatabaseHelper.instance.database; - await db.insert('movies', m.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); - } - - Future _upsertLocalBook({required Book b}) async { - final db = await DatabaseHelper.instance.database; - await db.insert('books', b.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); - } - - Future _upsertLocalNote({required Note n}) async { - final db = await DatabaseHelper.instance.database; - await db.insert('notes', n.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); - } - - /// 收集所有实际存在的本地图片路径 - List _collectAllLocalImages(List movies, List books, - List notes, List> posters) { - final paths = []; - for (final m in movies) { - if (m.posterPath != null && m.posterPath!.isNotEmpty) paths.add(m.posterPath!); - } - for (final b in books) { - if (b.coverPath != null && b.coverPath!.isNotEmpty) paths.add(b.coverPath!); - } - for (final n in notes) { - paths.addAll(n.images.where((i) => i.isNotEmpty)); - } - for (final p in posters) { - final pp = p['poster_path'] as String?; - if (pp != null && pp.isNotEmpty) paths.add(pp); - } - return paths; - } - - /// 合并子表(reviews/posters/excerpts):本地优先 push,服务端补充 - Future _mergeSubTable(Database db, ServerDataService server, String table, - List> local, List> pushList) async { - // 尝试获取服务端数据 - List> remote = []; - bool serverOk = false; - try { - switch (table) { - case 'movie_reviews': - remote = (await server.getAllMovieReviews()).map((r) => r.toJson()).toList(); - case 'movie_posters': - remote = (await server.getAllMoviePosters()).map((p) => p.toJson()).toList(); - case 'book_reviews': - remote = (await server.getAllBookReviews()).map((r) => r.toJson()).toList(); - case 'book_excerpts': - remote = (await server.getAllBookExcerpts()).map((e) => e.toJson()).toList(); - } - serverOk = true; - } catch (_) {} - - if (!serverOk) { - // 服务端不可用 → 全量 push 本地数据 - pushList.addAll(local); - return; - } - - final remoteMap = {for (final r in remote) r['id'] as String: r}; - for (final l in local) { - final r = remoteMap.remove(l['id'] as String); - if (r == null) { - pushList.add(l); - } else { - final lTime = l['updated_at'] as String? ?? ''; - final rTime = r['updated_at'] as String? ?? ''; - if (lTime.compareTo(rTime) > 0) pushList.add(l); - } - } - // 服务端有、本地无 → 写入本地 - for (final r in remoteMap.values) { - await db.insert(table, r, conflictAlgorithm: ConflictAlgorithm.replace); - } - } - - /// 关闭同步:上传完整备份到服务器后切回本地 - Future uploadBackupAndDisconnect() async { - if (!isConfigured || _isSyncing) return false; - _isSyncing = true; - try { - debugPrint('[Sync] ========== 关闭同步:上传备份 =========='); - final url = _prefs.syncServerUrl; - final code = _prefs.syncActivationCode; - final deviceId = _prefs.deviceId; - final appDir = (await getApplicationDocumentsDirectory()).path; - - // 上传数据库(先关闭连接再读取,避免文件被占用) - await DatabaseHelper.instance.close(); - final dbPath = await DatabaseHelper.instance.databasePath; - final request = http.MultipartRequest('POST', Uri.parse('$url/api/sync/upload')); - request.fields['code'] = code; - request.fields['device_id'] = deviceId; - if (dbPath != null && File(dbPath).existsSync()) { - final dbBytes = await File(dbPath).readAsBytes(); - request.files.add(http.MultipartFile.fromBytes( - 'database', dbBytes, - filename: 'mooknote.db', - )); - debugPrint('[Sync] 上传数据库: ${dbBytes.length} bytes'); - } - // 重新打开数据库 - await DatabaseHelper.instance.reopen(); - - // 收集并上传所有图片 - final imagePaths = _collectAllImageFiles(appDir); - debugPrint('[Sync] 上传 ${imagePaths.length} 张图片...'); - for (final path in imagePaths) { - final relPath = p.relative(path, from: appDir).replaceAll('\\', '/'); - if (await File(path).exists()) { - final bytes = await File(path).readAsBytes(); - request.files.add(http.MultipartFile.fromBytes( - 'images', bytes, - filename: relPath, - )); - } - } - - final resp = await request.send().timeout(const Duration(seconds: 300)); - final body = await resp.stream.bytesToString(); - debugPrint('[Sync] 上传备份响应: ${resp.statusCode} $body'); - - if (resp.statusCode == 200) { - debugPrint('[Sync] 备份上传成功,关闭同步'); - } - return resp.statusCode == 200; - } catch (e) { - debugPrint('[Sync] 上传备份异常: $e'); - return false; - } finally { - _isSyncing = false; - } - } - - /// 收集所有图片文件(递归扫描 images 目录) - List _collectAllImageFiles(String appDir) { - final paths = []; - final imagesDir = Directory(p.join(appDir, 'images')); - if (!imagesDir.existsSync()) return paths; - for (final entity in imagesDir.listSync(recursive: true)) { - if (entity is File) { - paths.add(entity.path); - } - } - return paths; - } - Future downloadToLocal() async { - if (!isConfigured || _isSyncing) { - debugPrint('[Sync] downloadToLocal 跳过: configured=$isConfigured syncing=$_isSyncing'); - return false; - } - _isSyncing = true; - try { - debugPrint('[Sync] ========== 关闭同步:从服务器下载 =========='); - final url = _prefs.syncServerUrl; - final code = _prefs.syncActivationCode; - final deviceId = _prefs.deviceId; - - debugPrint('[Sync] 查询备份信息...'); - final infoResp = await http.post( - Uri.parse('$url/api/sync/info'), - headers: {'Content-Type': 'application/json'}, - body: '{"code":"$code","device_id":"$deviceId"}', - ).timeout(const Duration(seconds: 15)); - debugPrint('[Sync] /api/sync/info 响应: ${infoResp.statusCode}'); - if (infoResp.statusCode != 200) return false; - - final info = _jsonDecode(infoResp.body); - debugPrint('[Sync] info: $info'); - if (info == null || info['has_backup'] != true) { - debugPrint('[Sync] 服务器无备份,跳过下载'); - return false; - } - - debugPrint('[Sync] 下载数据库...'); - final dbResp = await http.post( - Uri.parse('$url/api/sync/download/database'), - headers: {'Content-Type': 'application/json'}, - body: '{"code":"$code"}', - ).timeout(const Duration(seconds: 120)); - debugPrint('[Sync] 数据库下载响应: ${dbResp.statusCode} size=${dbResp.bodyBytes.length}'); - if (dbResp.statusCode != 200) return false; - - await DatabaseHelper.instance.reopenDatabaseFromBytes(dbResp.bodyBytes); - debugPrint('[Sync] 数据库已重写并重新打开'); - - final images = (info['images'] as List?) - ?.map((e) => e is Map ? {'name': e['name'] as String, 'rel_path': e['rel_path'] as String} : null) - .where((e) => e != null).cast>().toList() ?? []; - - debugPrint('[Sync] 下载 ${images.length} 张图片...'); - final appDir = await getApplicationDocumentsDirectory(); - int downloaded = 0; - for (final img in images) { - try { - final relPath = img['rel_path']!.replaceAll('\\', '/'); - final imgResp = await http.get( - Uri.parse('$url/api/sync/download/image/$code/$relPath'), - ).timeout(const Duration(seconds: 30)); - if (imgResp.statusCode == 200) { - final dest = File(p.join(appDir.path, relPath)); - await dest.parent.create(recursive: true); - await dest.writeAsBytes(imgResp.bodyBytes); - downloaded++; - } - } catch (_) {} - } - debugPrint('[Sync] 下载完成: 数据库 + $downloaded/${images.length} 张图片'); - - debugPrint('[Sync] 下载到本地完成'); - return true; - } catch (e) { - debugPrint('[Sync] 下载到本地异常: $e'); - return false; - } finally { - _isSyncing = false; - } - } -} diff --git a/lib/utils/user_prefs.dart b/lib/utils/user_prefs.dart index 6984046..9a6bc74 100644 --- a/lib/utils/user_prefs.dart +++ b/lib/utils/user_prefs.dart @@ -133,32 +133,6 @@ class UserPrefs { String get deviceId => prefs.getString('deviceId') ?? ''; Future setDeviceId(String value) => prefs.setString('deviceId', value); - // ========== 服务端实时同步设置 ========== - - /// 服务器地址 - String get syncServerUrl => prefs.getString('syncServerUrl') ?? ''; - Future setSyncServerUrl(String value) => prefs.setString('syncServerUrl', value); - - /// 激活码 - String get syncActivationCode => prefs.getString('syncActivationCode') ?? ''; - Future setSyncActivationCode(String value) => prefs.setString('syncActivationCode', value); - - /// 激活码有效期 - String get syncExpiresAt => prefs.getString('syncExpiresAt') ?? ''; - Future setSyncExpiresAt(String value) => prefs.setString('syncExpiresAt', value); - - /// 是否永久有效 - bool get syncIsPermanent => prefs.getBool('syncIsPermanent') ?? false; - Future setSyncIsPermanent(bool value) => prefs.setBool('syncIsPermanent', value); - - /// 实时同步开关(默认开启) - bool get syncEnabled => prefs.getBool('syncEnabled') ?? true; - Future setSyncEnabled(bool value) => prefs.setBool('syncEnabled', value); - - /// 上次同步到的 entry id - int get syncLastEntryId => prefs.getInt('syncLastEntryId') ?? 0; - Future setSyncLastEntryId(int value) => prefs.setInt('syncLastEntryId', value); - // ========== 版本更新 ========== /// 已忽略的版本号(不再提示更新) diff --git a/lib/widgets/fade_in_local_image.dart b/lib/widgets/fade_in_local_image.dart index b6f8c1b..8435304 100644 --- a/lib/widgets/fade_in_local_image.dart +++ b/lib/widgets/fade_in_local_image.dart @@ -1,9 +1,7 @@ import 'dart:io'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import '../utils/sync/server_data_service.dart'; -/// 带淡入动画的图片组件(支持本地文件 + 服务端 URL 回退) +/// 带淡入动画的图片组件(支持本地文件 + HTTP URL) class FadeInLocalImage extends StatefulWidget { final String? path; final double? width; @@ -66,18 +64,6 @@ class _FadeInLocalImageState extends State return; } - if (ServerDataService.isActive) { - try { - final url = await ServerDataService.toImageUrl(widget.path!); - debugPrint('[Image] 本地不存在,使用服务端: $url'); - _useNetwork = true; - _imageUrl = url; - setState(() => _loaded = true); - _controller.forward(); - return; - } catch (_) {} - } - setState(() => _error = true); }