Files
AeroTrack/lib/services/sync_service.dart
T

199 lines
6.2 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import '../models/canister.dart';
import '../models/dose_record.dart';
import 'storage_service.dart';
class SyncResult {
final bool success;
final String message;
final int? latencyMs;
final int newRecordsCount;
SyncResult({
required this.success,
required this.message,
this.latencyMs,
this.newRecordsCount = 0,
});
}
class SyncService {
static const String _keyServerUrl = 'aerotrack_lan_server_url';
static const String _keyDeviceName = 'aerotrack_device_name';
static const String _keyDeviceId = 'aerotrack_device_id';
static const String _keyLastSync = 'aerotrack_last_sync_time';
static const String _keyAutoSync = 'aerotrack_auto_sync';
// 默认局域网地址推荐(契合私有服务器 192.168.21.200)
static const String defaultServerUrl = 'http://192.168.21.200:8090';
final StorageService storageService;
SyncService(this.storageService);
static Future<String> getDeviceId() async {
final prefs = await SharedPreferences.getInstance();
String? id = prefs.getString(_keyDeviceId);
if (id == null) {
id = const Uuid().v4();
await prefs.setString(_keyDeviceId, id);
}
return id;
}
static Future<String> getServerUrl() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_keyServerUrl) ?? defaultServerUrl;
}
static Future<void> setServerUrl(String url) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyServerUrl, url.trim());
}
static Future<String> getDeviceName() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_keyDeviceName) ?? '家人手机';
}
static Future<void> setDeviceName(String name) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyDeviceName, name.trim());
}
static Future<bool> getAutoSyncEnabled() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(_keyAutoSync) ?? true;
}
static Future<void> setAutoSyncEnabled(bool enabled) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_keyAutoSync, enabled);
}
static Future<DateTime?> getLastSyncTime() async {
final prefs = await SharedPreferences.getInstance();
final str = prefs.getString(_keyLastSync);
return str != null ? DateTime.tryParse(str) : null;
}
/// 测试与局域网服务器连通性
static Future<int?> pingServer(String serverUrl) async {
try {
final cleanUrl = serverUrl.trim().replaceAll(RegExp(r'/+$'), '');
final uri = Uri.parse('$cleanUrl/api/v1/ping');
final stopwatch = Stopwatch()..start();
final res = await http.get(uri).timeout(const Duration(seconds: 3));
stopwatch.stop();
if (res.statusCode == 200) {
return stopwatch.elapsedMilliseconds;
}
} catch (e) {
debugPrint('Ping server error: $e');
}
return null;
}
/// 执行完整双向增量同步
Future<SyncResult> performSync({String? customUrl}) async {
final baseUrl = (customUrl ?? await getServerUrl()).replaceAll(RegExp(r'/+$'), '');
final deviceName = await getDeviceName();
final deviceId = await getDeviceId();
final pingMs = await pingServer(baseUrl);
if (pingMs == null) {
return SyncResult(
success: false,
message: '无法连接局域网服务器 ($baseUrl),请检查 Wi-Fi 或 IP 地址',
);
}
try {
final localRecords = storageService.getRecords();
final localCanisters = storageService.getCanisters();
final lastSync = await getLastSyncTime();
final body = json.encode({
'device_name': deviceName,
'device_id': deviceId,
'last_sync_time': lastSync?.toIso8601String(),
'records': localRecords.map((r) => r.toMap()).toList(),
'canisters': localCanisters.map((c) => c.toMap()).toList(),
});
final syncUri = Uri.parse('$baseUrl/api/v1/sync');
final res = await http.post(
syncUri,
headers: {'Content-Type': 'application/json; charset=utf-8'},
body: body,
).timeout(const Duration(seconds: 6));
if (res.statusCode == 200) {
final data = json.decode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
// 1. 合并远端记录到本地
final remoteRecordsRaw = data['records'] as List<dynamic>? ?? [];
final remoteRecords = remoteRecordsRaw
.map((item) => DoseRecord.fromMap(item as Map<String, dynamic>))
.toList();
final existingIds = localRecords.map((r) => r.id).toSet();
int newCount = 0;
for (var r in remoteRecords) {
if (!existingIds.contains(r.id)) {
await storageService.addRecord(r);
newCount++;
}
}
// 2. 合并远端药瓶状态到本地
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
final remoteCanisters = remoteCanistersRaw
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
.toList();
if (remoteCanisters.isNotEmpty) {
await storageService.saveCanisters(remoteCanisters);
}
// 3. 更新同步时间
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyLastSync, DateTime.now().toIso8601String());
return SyncResult(
success: true,
message: '同步成功!拉取到 $newCount 条新记录',
latencyMs: pingMs,
newRecordsCount: newCount,
);
} else {
return SyncResult(
success: false,
message: '服务器返回错误 HTTP ${res.statusCode}',
);
}
} catch (e) {
return SyncResult(
success: false,
message: '同步中断: $e',
);
}
}
/// 默默在后台尝试同步(失败不弹窗干扰用户)
Future<void> syncSilently() async {
final enabled = await getAutoSyncEnabled();
if (!enabled) return;
try {
await performSync();
} catch (_) {}
}
}