generated from dellevin/template
功能优化
This commit is contained in:
@@ -9,6 +9,12 @@ class DatabaseHelper {
|
||||
|
||||
DatabaseHelper._init();
|
||||
|
||||
/// 数据库文件路径
|
||||
Future<String?> get databasePath async {
|
||||
final path = await getDatabasesPath();
|
||||
return join(path, 'mooknote.db');
|
||||
}
|
||||
|
||||
/// 重新打开数据库(用于 WebDAV 同步后)
|
||||
Future<void> reopenDatabase() async {
|
||||
// 关闭现有连接
|
||||
@@ -566,7 +572,15 @@ class DatabaseHelper {
|
||||
|
||||
// 关闭数据库
|
||||
Future close() async {
|
||||
final db = await instance.database;
|
||||
db.close();
|
||||
if (_database != null) {
|
||||
await _database!.close();
|
||||
_database = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 重新打开(关闭后重新初始化)
|
||||
Future reopen() async {
|
||||
await close();
|
||||
await database;
|
||||
}
|
||||
}
|
||||
|
||||
168
lib/utils/sync/server_data_service.dart
Normal file
168
lib/utils/sync/server_data_service.dart
Normal file
@@ -0,0 +1,168 @@
|
||||
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<String, String> get _headers => {'Content-Type': 'application/json'};
|
||||
|
||||
Map<String, dynamic> _body([Map<String, dynamic>? extra]) {
|
||||
return {'code': _code, ...?extra};
|
||||
}
|
||||
|
||||
bool get isAvailable => _baseUrl.isNotEmpty && _code.isNotEmpty;
|
||||
|
||||
Future<dynamic> _post(String path, [Map<String, dynamic>? extra]) async {
|
||||
final resp = await http.post(
|
||||
Uri.parse('$_baseUrl$path'),
|
||||
headers: _headers,
|
||||
body: jsonEncode(_body(extra)),
|
||||
).timeout(const Duration(seconds: 30));
|
||||
if (resp.statusCode != 200) return null;
|
||||
return jsonDecode(resp.body);
|
||||
}
|
||||
|
||||
// ─── 影视 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Movie>> getMovies() async {
|
||||
final data = await _post('/api/data/movies');
|
||||
if (data == null || data['movies'] == null) return [];
|
||||
return (data['movies'] as List).map((m) => Movie.fromJson(m as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
Future<bool> saveMovie(Movie movie) async {
|
||||
final data = await _post('/api/data/movie/save', {'movie': movie.toJson()});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
Future<bool> deleteMovie(String id) async {
|
||||
final data = await _post('/api/data/movie/delete', {'id': id});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
// ─── 书籍 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Book>> getBooks() async {
|
||||
final data = await _post('/api/data/books');
|
||||
if (data == null || data['books'] == null) return [];
|
||||
return (data['books'] as List).map((b) => Book.fromJson(b as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
Future<bool> saveBook(Book book) async {
|
||||
final data = await _post('/api/data/book/save', {'book': book.toJson()});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
Future<bool> deleteBook(String id) async {
|
||||
final data = await _post('/api/data/book/delete', {'id': id});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
// ─── 笔记 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Note>> getNotes() async {
|
||||
final data = await _post('/api/data/notes');
|
||||
if (data == null || data['notes'] == null) return [];
|
||||
return (data['notes'] as List).map((n) => Note.fromJson(n as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
Future<bool> saveNote(Note note) async {
|
||||
final data = await _post('/api/data/note/save', {'note': note.toJson()});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
Future<bool> deleteNote(String id) async {
|
||||
final data = await _post('/api/data/note/delete', {'id': id});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
// ─── 标签 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Map<String, dynamic>>> 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<String, dynamic>.from(t as Map)).toList();
|
||||
}
|
||||
|
||||
Future<bool> saveTag(String name, String type) async {
|
||||
final data = await _post('/api/data/tag/save', {'tag': {'name': name, 'type': type}});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
Future<bool> deleteTag(String id) async {
|
||||
final data = await _post('/api/data/tag/delete', {'id': id});
|
||||
return data != null;
|
||||
}
|
||||
|
||||
// ─── 图片 ────────────────────────────────────────────────────
|
||||
|
||||
/// 是否激活(AppProvider 也会用这个检查)
|
||||
static bool get isActive {
|
||||
final p = UserPrefs();
|
||||
return p.syncEnabled && p.syncServerUrl.isNotEmpty && p.syncActivationCode.isNotEmpty;
|
||||
}
|
||||
|
||||
/// 将本地路径转为服务端图片 URL
|
||||
static Future<String> 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<void> uploadLocalImages(List<String> filePaths) async {
|
||||
if (!isActive || filePaths.isEmpty) return;
|
||||
final result = await instance.uploadImages(filePaths);
|
||||
debugPrint('[Sync] 上传 ${result.length}/${filePaths.length} 张图片');
|
||||
}
|
||||
|
||||
/// 上传单张图片到服务端
|
||||
static Future<void> 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<List<String>> uploadImages(List<String> filePaths) async {
|
||||
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);
|
||||
request.files.add(await http.MultipartFile(
|
||||
'images', file.readAsBytes().asStream(), await file.length(),
|
||||
filename: relPath,
|
||||
));
|
||||
}
|
||||
final resp = await request.send().timeout(const Duration(seconds: 60));
|
||||
if (resp.statusCode != 200) return [];
|
||||
final body = await resp.stream.bytesToString();
|
||||
final data = jsonDecode(body) as Map<String, dynamic>;
|
||||
return (data['files'] as List?)?.cast<String>() ?? [];
|
||||
}
|
||||
|
||||
Future<String?> uploadImage(String filePath) async {
|
||||
final files = await uploadImages([filePath]);
|
||||
return files.isNotEmpty ? files.first : null;
|
||||
}
|
||||
}
|
||||
165
lib/utils/sync/server_sync_service.dart
Normal file
165
lib/utils/sync/server_sync_service.dart
Normal file
@@ -0,0 +1,165 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import '../user_prefs.dart';
|
||||
import '../database_helper.dart';
|
||||
|
||||
/// 服务端实时同步服务
|
||||
/// - 开启时:上传一次本地数据到服务器,后续 CRUD 走 API
|
||||
/// - 关闭时:从服务器下载数据到本地,切换本地数据库
|
||||
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<Map<String, dynamic>?> 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<String, dynamic>? _jsonDecode(String s) {
|
||||
try { final d = jsonDecode(s); return d is Map<String, dynamic> ? d : null; } catch (_) { return null; }
|
||||
}
|
||||
|
||||
/// 开启同步:上传本地数据到服务器
|
||||
Future<bool> uploadToServer() async {
|
||||
if (!isConfigured || _isSyncing) return false;
|
||||
_isSyncing = true;
|
||||
try {
|
||||
final url = _prefs.syncServerUrl;
|
||||
final code = _prefs.syncActivationCode;
|
||||
final deviceId = _prefs.deviceId;
|
||||
|
||||
final dbPath = await DatabaseHelper.instance.databasePath;
|
||||
if (dbPath == null || !File(dbPath).existsSync()) {
|
||||
debugPrint('[Sync] 数据库文件不存在');
|
||||
return false;
|
||||
}
|
||||
|
||||
final request = http.MultipartRequest('POST', Uri.parse('$url/api/sync/upload'));
|
||||
request.fields['code'] = code;
|
||||
request.fields['device_id'] = deviceId;
|
||||
request.files.add(await http.MultipartFile.fromPath('database', dbPath));
|
||||
|
||||
final appDir = await getApplicationDocumentsDirectory();
|
||||
final imgDir = Directory(p.join(appDir.path, 'images'));
|
||||
if (await imgDir.exists()) {
|
||||
await for (final entity in imgDir.list(recursive: true)) {
|
||||
if (entity is File) {
|
||||
final relPath = p.relative(entity.path, from: appDir.path).replaceAll('\\', '/');
|
||||
request.files.add(await http.MultipartFile('images', entity.readAsBytes().asStream(), await entity.length(), filename: relPath));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final avatarsDir = Directory(p.join(appDir.path, 'avatars'));
|
||||
if (await avatarsDir.exists()) {
|
||||
await for (final entity in avatarsDir.list()) {
|
||||
if (entity is File) {
|
||||
final relPath = p.relative(entity.path, from: appDir.path).replaceAll('\\', '/');
|
||||
request.files.add(await http.MultipartFile('images', entity.readAsBytes().asStream(), await entity.length(), filename: relPath));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final resp = await request.send().timeout(const Duration(seconds: 300));
|
||||
if (resp.statusCode == 200) {
|
||||
debugPrint('[Sync] 上传成功');
|
||||
return true;
|
||||
}
|
||||
debugPrint('[Sync] 上传失败 HTTP ${resp.statusCode}');
|
||||
} catch (e) {
|
||||
debugPrint('[Sync] 上传异常: $e');
|
||||
} finally {
|
||||
_isSyncing = false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 关闭同步:从服务器下载数据到本地
|
||||
Future<bool> downloadToLocal() async {
|
||||
if (!isConfigured || _isSyncing) return false;
|
||||
_isSyncing = true;
|
||||
try {
|
||||
final url = _prefs.syncServerUrl;
|
||||
final code = _prefs.syncActivationCode;
|
||||
final deviceId = _prefs.deviceId;
|
||||
|
||||
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));
|
||||
if (infoResp.statusCode != 200) return false;
|
||||
|
||||
final info = _jsonDecode(infoResp.body);
|
||||
if (info == null || info['has_backup'] != true) return false;
|
||||
|
||||
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));
|
||||
if (dbResp.statusCode != 200) return false;
|
||||
|
||||
final dbPath = await DatabaseHelper.instance.databasePath;
|
||||
if (dbPath != null) {
|
||||
await DatabaseHelper.instance.close();
|
||||
await File(dbPath).writeAsBytes(dbResp.bodyBytes);
|
||||
await DatabaseHelper.instance.reopen();
|
||||
}
|
||||
|
||||
final images = (info['images'] as List<dynamic>?)
|
||||
?.map((e) => e is Map ? {'name': e['name'] as String, 'rel_path': e['rel_path'] as String} : null)
|
||||
.where((e) => e != null).cast<Map<String, String>>().toList() ?? [];
|
||||
|
||||
final appDir = await getApplicationDocumentsDirectory();
|
||||
for (final img in images) {
|
||||
try {
|
||||
final relPath = img['rel_path']!;
|
||||
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);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
debugPrint('[Sync] 下载到本地完成');
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint('[Sync] 下载到本地异常: $e');
|
||||
return false;
|
||||
} finally {
|
||||
_isSyncing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io' show Platform;
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
@@ -21,7 +22,7 @@ class UsageStatsService with WidgetsBindingObserver {
|
||||
Timer? _heartbeatTimer;
|
||||
bool _started = false;
|
||||
|
||||
static const _heartbeatInterval = Duration(minutes: 5);
|
||||
static const _heartbeatInterval = Duration(minutes: 1);
|
||||
|
||||
/// 启动统计服务(App 启动时调用一次)
|
||||
Future<void> start() async {
|
||||
@@ -103,7 +104,11 @@ class UsageStatsService with WidgetsBindingObserver {
|
||||
.post(
|
||||
Uri.parse('$serverUrl/api/heartbeat'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'device_hash': deviceId}),
|
||||
body: jsonEncode({
|
||||
'device_hash': deviceId,
|
||||
'device_type': Platform.operatingSystem, // android/ios/windows/macos/linux
|
||||
'device_name': '${Platform.operatingSystem} ${Platform.operatingSystemVersion}',
|
||||
}),
|
||||
)
|
||||
.timeout(const Duration(seconds: 5));
|
||||
} catch (_) {
|
||||
|
||||
@@ -105,4 +105,30 @@ class UserPrefs {
|
||||
/// 匿名设备标识(首次启动自动生成)
|
||||
String get deviceId => prefs.getString('deviceId') ?? '';
|
||||
Future<bool> setDeviceId(String value) => prefs.setString('deviceId', value);
|
||||
|
||||
// ========== 服务端实时同步设置 ==========
|
||||
|
||||
/// 服务器地址
|
||||
String get syncServerUrl => prefs.getString('syncServerUrl') ?? '';
|
||||
Future<bool> setSyncServerUrl(String value) => prefs.setString('syncServerUrl', value);
|
||||
|
||||
/// 激活码
|
||||
String get syncActivationCode => prefs.getString('syncActivationCode') ?? '';
|
||||
Future<bool> setSyncActivationCode(String value) => prefs.setString('syncActivationCode', value);
|
||||
|
||||
/// 激活码有效期
|
||||
String get syncExpiresAt => prefs.getString('syncExpiresAt') ?? '';
|
||||
Future<bool> setSyncExpiresAt(String value) => prefs.setString('syncExpiresAt', value);
|
||||
|
||||
/// 是否永久有效
|
||||
bool get syncIsPermanent => prefs.getBool('syncIsPermanent') ?? false;
|
||||
Future<bool> setSyncIsPermanent(bool value) => prefs.setBool('syncIsPermanent', value);
|
||||
|
||||
/// 实时同步开关(默认开启)
|
||||
bool get syncEnabled => prefs.getBool('syncEnabled') ?? true;
|
||||
Future<bool> setSyncEnabled(bool value) => prefs.setBool('syncEnabled', value);
|
||||
|
||||
/// 上次同步到的 entry id
|
||||
int get syncLastEntryId => prefs.getInt('syncLastEntryId') ?? 0;
|
||||
Future<bool> setSyncLastEntryId(int value) => prefs.setInt('syncLastEntryId', value);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user