feat: 文件存储安全加固 + 认证增强 + 媒体URL保护 + provider 重构
## 后端安全加固 - 新增 UserUploadPathResolver: 用户上传文件路径安全解析, 防目录穿越 - LocalReportFileStorage: 文件存储路径安全加固 - local_account_file_cleanup: 账号删除时文件清理逻辑增强 - AuthService: 认证逻辑增强 - file_endpoints / report_endpoints: 文件访问接口安全加固 - ai_chat_endpoints / doctor_endpoints: 接口安全调整 - Program.cs: 服务注册调整 ## 前端认证与媒体 - 新增 authenticated_network_image.dart: 带认证的图片加载组件 - auth_provider: 认证状态管理大幅增强(+173) - api_client: 网络客户端增强(+124) - chat_provider: 聊天 provider 重构(+76) - omron_device_provider: 蓝牙设备 provider 增强(+53) - sse_handler: SSE 处理增强(+35) - consultation_provider / data_providers / conversation_history_provider: 调整 ## 页面调整 - remaining_pages: 健康档案/饮食记录等页面增强(+115) - home_page / chat_messages_view: 主页微调 - doctor 端多页微调(consultations/dashboard/followups/patient_detail/profile/report_detail/reports) - report_pages / settings_pages / notification_prefs_page: 微调 - device_scan_page / diet_capture_page / admin_home_page: 微调 ## 测试 - 新增 file_path_security_tests: 文件路径安全测试 - 新增 protected_media_url_test: 媒体URL保护测试 - 新增 user_session_identity_test: 用户会话身份测试 - account_deletion_tests / application_service_tests / auth_tests: 更新
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
@@ -53,11 +54,15 @@ final apiClientProvider = Provider<ApiClient>((ref) {
|
||||
});
|
||||
|
||||
class AuthNotifier extends Notifier<AuthState> {
|
||||
static const _cachedUserKey = 'session_user';
|
||||
|
||||
@override
|
||||
AuthState build() {
|
||||
final removeListener = ref.read(authExpiredNotifierProvider).addListener(
|
||||
() {
|
||||
ref.read(localDbProvider).delete(_cachedUserKey);
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
_publishSessionIdentity(null);
|
||||
},
|
||||
);
|
||||
ref.onDispose(removeListener);
|
||||
@@ -72,30 +77,51 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
if (refresh == null) {
|
||||
// 无 token:判定完成、未登录
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
_publishSessionIdentity(null);
|
||||
return;
|
||||
}
|
||||
|
||||
state = const AuthState(isLoading: true);
|
||||
try {
|
||||
final response = await Dio(
|
||||
BaseOptions(baseUrl: baseUrl),
|
||||
BaseOptions(
|
||||
baseUrl: baseUrl,
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 8),
|
||||
),
|
||||
).post('/api/auth/refresh', data: {'refreshToken': refresh});
|
||||
final data = response.data['data'];
|
||||
if (data != null) {
|
||||
final body = response.data;
|
||||
final data = body is Map ? body['data'] : null;
|
||||
final code = body is Map ? body['code'] : null;
|
||||
if (data is Map) {
|
||||
await db.write('access_token', data['accessToken']);
|
||||
await db.write('refresh_token', data['refreshToken']);
|
||||
final u = data['user'] as Map<String, dynamic>?;
|
||||
state = AuthState(
|
||||
isLoggedIn: true,
|
||||
isLoading: false,
|
||||
user: UserInfo(id: '', phone: '', role: u?['role'] ?? 'User'),
|
||||
);
|
||||
final cachedUser = await _readCachedUser();
|
||||
final user = _userFromMap(u, fallback: cachedUser);
|
||||
state = AuthState(isLoggedIn: true, isLoading: false, user: user);
|
||||
_publishSessionIdentity(user);
|
||||
await _cacheUser(user);
|
||||
_loadProfile();
|
||||
} else {
|
||||
} else if (code != null && code != 0) {
|
||||
await _clearSessionStorage();
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
_publishSessionIdentity(null);
|
||||
} else {
|
||||
await _restoreOfflineSession();
|
||||
}
|
||||
} catch (_) {
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
} on DioException catch (error) {
|
||||
if (error.response?.statusCode == 400 ||
|
||||
error.response?.statusCode == 401) {
|
||||
await _clearSessionStorage();
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
_publishSessionIdentity(null);
|
||||
} else {
|
||||
await _restoreOfflineSession();
|
||||
}
|
||||
} catch (error) {
|
||||
log('[Auth] startup refresh: $error');
|
||||
await _restoreOfflineSession();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +146,8 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
birthDate: user['birthDate']?.toString(),
|
||||
),
|
||||
);
|
||||
await _cacheUser(state.user!);
|
||||
_publishSessionIdentity(state.user);
|
||||
}
|
||||
} catch (e) {
|
||||
log('[Auth] loadProfile: $e');
|
||||
@@ -177,6 +205,8 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
role: user['role'] ?? 'User',
|
||||
),
|
||||
);
|
||||
await _cacheUser(state.user!);
|
||||
_publishSessionIdentity(state.user);
|
||||
return null;
|
||||
} catch (e) {
|
||||
return '注册失败: $e';
|
||||
@@ -207,6 +237,8 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
avatarUrl: user['avatarUrl'],
|
||||
),
|
||||
);
|
||||
await _cacheUser(state.user!);
|
||||
_publishSessionIdentity(state.user);
|
||||
return null;
|
||||
} catch (e) {
|
||||
return '登录失败: $e';
|
||||
@@ -245,6 +277,8 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
avatarUrl: user['avatarUrl'],
|
||||
),
|
||||
);
|
||||
await _cacheUser(state.user!);
|
||||
_publishSessionIdentity(state.user);
|
||||
return null;
|
||||
} catch (_) {
|
||||
return 'Apple 登录失败,请稍后重试';
|
||||
@@ -264,7 +298,108 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
}
|
||||
}
|
||||
await api.clearTokens();
|
||||
await db.delete(_cachedUserKey);
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
_publishSessionIdentity(null);
|
||||
}
|
||||
|
||||
Future<void> _restoreOfflineSession() async {
|
||||
final cached = await _readCachedUser() ?? await _userFromStoredToken();
|
||||
if (cached == null) {
|
||||
state = const AuthState(isLoggedIn: false, isLoading: false);
|
||||
_publishSessionIdentity(null);
|
||||
return;
|
||||
}
|
||||
state = AuthState(user: cached, isLoggedIn: true, isLoading: false);
|
||||
_publishSessionIdentity(cached);
|
||||
}
|
||||
|
||||
UserInfo _userFromMap(Map<String, dynamic>? value, {UserInfo? fallback}) {
|
||||
return UserInfo(
|
||||
id: value?['id']?.toString() ?? fallback?.id ?? '',
|
||||
phone: value?['phone']?.toString() ?? fallback?.phone ?? '',
|
||||
role: value?['role']?.toString() ?? fallback?.role ?? 'User',
|
||||
name: value?['name']?.toString() ?? fallback?.name,
|
||||
avatarUrl: value?['avatarUrl']?.toString() ?? fallback?.avatarUrl,
|
||||
gender: value?['gender']?.toString() ?? fallback?.gender,
|
||||
birthDate: value?['birthDate']?.toString() ?? fallback?.birthDate,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _cacheUser(UserInfo user) {
|
||||
return ref
|
||||
.read(localDbProvider)
|
||||
.write(
|
||||
_cachedUserKey,
|
||||
jsonEncode({
|
||||
'id': user.id,
|
||||
'phone': user.phone,
|
||||
'role': user.role,
|
||||
'name': user.name,
|
||||
'avatarUrl': user.avatarUrl,
|
||||
'gender': user.gender,
|
||||
'birthDate': user.birthDate,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Future<UserInfo?> _readCachedUser() async {
|
||||
final raw = await ref.read(localDbProvider).read(_cachedUserKey);
|
||||
if (raw == null || raw.isEmpty) return null;
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! Map) return null;
|
||||
return _userFromMap(Map<String, dynamic>.from(decoded));
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<UserInfo?> _userFromStoredToken() async {
|
||||
final token = await ref.read(localDbProvider).read('access_token');
|
||||
if (token == null) return null;
|
||||
try {
|
||||
final parts = token.split('.');
|
||||
if (parts.length != 3) return null;
|
||||
final payload = jsonDecode(
|
||||
utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))),
|
||||
);
|
||||
if (payload is! Map) return null;
|
||||
final map = Map<String, dynamic>.from(payload);
|
||||
String? claim(String shortName, String longName) =>
|
||||
map[shortName]?.toString() ?? map[longName]?.toString();
|
||||
return UserInfo(
|
||||
id:
|
||||
claim(
|
||||
'sub',
|
||||
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier',
|
||||
) ??
|
||||
'',
|
||||
phone:
|
||||
claim(
|
||||
'phone',
|
||||
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone',
|
||||
) ??
|
||||
'',
|
||||
role:
|
||||
claim(
|
||||
'role',
|
||||
'http://schemas.microsoft.com/ws/2008/06/identity/claims/role',
|
||||
) ??
|
||||
'User',
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _clearSessionStorage() async {
|
||||
await ref.read(apiClientProvider).clearTokens();
|
||||
await ref.read(localDbProvider).delete(_cachedUserKey);
|
||||
}
|
||||
|
||||
void _publishSessionIdentity(UserInfo? user) {
|
||||
ref.read(userSessionIdentityProvider.notifier).setUser(user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,3 +407,21 @@ class AuthNotifier extends Notifier<AuthState> {
|
||||
final userRoleProvider = Provider<String>((ref) {
|
||||
return ref.watch(authProvider).user?.role ?? 'User';
|
||||
});
|
||||
|
||||
final userSessionIdentityProvider =
|
||||
NotifierProvider<UserSessionIdentityNotifier, String?>(
|
||||
UserSessionIdentityNotifier.new,
|
||||
);
|
||||
|
||||
class UserSessionIdentityNotifier extends Notifier<String?> {
|
||||
@override
|
||||
String? build() => null;
|
||||
|
||||
void setUser(UserInfo? user) {
|
||||
if (user == null || user.id.isEmpty) {
|
||||
state = null;
|
||||
return;
|
||||
}
|
||||
state = user.id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,10 +86,12 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
ActiveAgent? _lastTriggeredAgent;
|
||||
Timer? _agentTapLockTimer;
|
||||
bool _loadingConversation = false;
|
||||
int _generation = 0;
|
||||
|
||||
/// 重置整个会话:取消正在进行的 SSE,清空消息和会话 ID。
|
||||
/// 历史记录页一键清空 / 删除当前会话时调用。
|
||||
Future<void> resetSession() async {
|
||||
_generation++;
|
||||
await _cancelActiveStream();
|
||||
_cancelPendingAgentWelcome();
|
||||
_lastTriggeredAgent = null;
|
||||
@@ -140,7 +142,9 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
|
||||
@override
|
||||
ChatState build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
ref.onDispose(() {
|
||||
_generation++;
|
||||
_subscription?.cancel();
|
||||
_agentTapLockTimer?.cancel();
|
||||
_subscription = null;
|
||||
@@ -172,10 +176,13 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
}
|
||||
|
||||
Future<String?> loadConversation(String convId) async {
|
||||
if (state.isStreaming) return '小脉正在回复,请稍后再切换对话';
|
||||
if (_loadingConversation) return '正在加载其他对话,请稍候';
|
||||
_loadingConversation = true;
|
||||
await _cancelActiveStream();
|
||||
if (state.isStreaming) {
|
||||
await stopGenerating();
|
||||
} else {
|
||||
await _cancelActiveStream();
|
||||
}
|
||||
_cancelPendingAgentWelcome();
|
||||
try {
|
||||
final api = ref.read(apiClientProvider);
|
||||
@@ -194,7 +201,9 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
role: role,
|
||||
content: map['content']?.toString() ?? '',
|
||||
createdAt:
|
||||
DateTime.tryParse(map['createdAt']?.toString() ?? '') ??
|
||||
DateTime.tryParse(
|
||||
map['createdAt']?.toString() ?? '',
|
||||
)?.toLocal() ??
|
||||
DateTime.now(),
|
||||
type: _messageTypeFromMetadata(metadata),
|
||||
metadata: metadata,
|
||||
@@ -258,7 +267,8 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
Future<void> sendImage(String imagePath, String text) async {
|
||||
if (state.isStreaming) return;
|
||||
final file = File(imagePath);
|
||||
if (!await file.exists()) return;
|
||||
if (!await file.exists() || state.isStreaming) return;
|
||||
final generation = ++_generation;
|
||||
_lastTriggeredAgent = null;
|
||||
_cancelPendingAgentWelcome();
|
||||
_resumeConversationFromHistory();
|
||||
@@ -286,6 +296,8 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
uploadError = e;
|
||||
}
|
||||
|
||||
if (generation != _generation || !state.isStreaming) return;
|
||||
|
||||
// 更新消息元数据(保留本地路径 + 添加远程URL)
|
||||
final updatedMsgs = state.messages.toList();
|
||||
final idx = updatedMsgs.indexWhere((m) => m.id == userMsg.id);
|
||||
@@ -318,14 +330,15 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
|
||||
// 把图片 URL 透传给后端,后端会调 VLM 识图并把描述拼到 LLM 上下文
|
||||
final userText = text.isNotEmpty ? text : '请帮我看看这张图片';
|
||||
await _sendToAI(userText, imageUrl: uploadedUrl);
|
||||
await _sendToAI(generation, userText, imageUrl: uploadedUrl);
|
||||
}
|
||||
|
||||
/// 发送 PDF 附件 + 文字(PDF 解析在后端做)。
|
||||
Future<void> sendPdf(String pdfPath, String fileName, String text) async {
|
||||
if (state.isStreaming) return;
|
||||
final file = File(pdfPath);
|
||||
if (!await file.exists()) return;
|
||||
if (!await file.exists() || state.isStreaming) return;
|
||||
final generation = ++_generation;
|
||||
_lastTriggeredAgent = null;
|
||||
_cancelPendingAgentWelcome();
|
||||
_resumeConversationFromHistory();
|
||||
@@ -350,6 +363,8 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
// ignore,下方统一处理
|
||||
}
|
||||
|
||||
if (generation != _generation || !state.isStreaming) return;
|
||||
|
||||
// 更新消息附带的远程 URL
|
||||
if (uploadedUrl != null) {
|
||||
final updatedMsgs = state.messages.toList();
|
||||
@@ -376,11 +391,12 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
return;
|
||||
}
|
||||
|
||||
await _sendToAI(userMsg.content, pdfUrl: uploadedUrl);
|
||||
await _sendToAI(generation, userMsg.content, pdfUrl: uploadedUrl);
|
||||
}
|
||||
|
||||
Future<void> sendMessage(String text) async {
|
||||
if (text.trim().isEmpty || state.isStreaming) return;
|
||||
final generation = ++_generation;
|
||||
_lastTriggeredAgent = null;
|
||||
_cancelPendingAgentWelcome();
|
||||
_resumeConversationFromHistory();
|
||||
@@ -396,14 +412,16 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
isStreaming: true,
|
||||
);
|
||||
|
||||
await _sendToAI(text);
|
||||
await _sendToAI(generation, text);
|
||||
}
|
||||
|
||||
Future<void> _sendToAI(
|
||||
int generation,
|
||||
String text, {
|
||||
String? imageUrl,
|
||||
String? pdfUrl,
|
||||
}) async {
|
||||
if (generation != _generation || !state.isStreaming) return;
|
||||
final aiMsg = ChatMessage(
|
||||
id: '${DateTime.now().millisecondsSinceEpoch}_ai',
|
||||
role: 'assistant',
|
||||
@@ -423,6 +441,7 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
_addError(aiMsg, '未登录,请重新登录');
|
||||
return;
|
||||
}
|
||||
if (generation != _generation || !state.isStreaming) return;
|
||||
|
||||
// 始终用 unified 智能体,AI 自动判断意图分配工具
|
||||
final stream = SseHandler.connect(
|
||||
@@ -435,12 +454,18 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
);
|
||||
|
||||
await _cancelActiveStream();
|
||||
if (generation != _generation || !state.isStreaming) return;
|
||||
|
||||
final done = Completer<void>();
|
||||
_streamDone = done;
|
||||
_subscription = stream.listen(
|
||||
(event) => _processEvent(event, aiMsg),
|
||||
(event) {
|
||||
if (generation == _generation) _processEvent(event, aiMsg);
|
||||
},
|
||||
onError: (_) {
|
||||
_addError(aiMsg, '网络异常,请稍后重试');
|
||||
if (generation == _generation) {
|
||||
_addError(aiMsg, '网络异常,请稍后重试');
|
||||
}
|
||||
if (!done.isCompleted) done.complete();
|
||||
},
|
||||
onDone: () {
|
||||
@@ -454,11 +479,13 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
_subscription = null;
|
||||
}
|
||||
|
||||
if (state.isStreaming) {
|
||||
if (generation == _generation && state.isStreaming) {
|
||||
_done(aiMsg);
|
||||
}
|
||||
} catch (e) {
|
||||
_addError(aiMsg, '网络异常,请稍后重试');
|
||||
if (generation == _generation) {
|
||||
_addError(aiMsg, '网络异常,请稍后重试');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,6 +503,31 @@ class ChatNotifier extends Notifier<ChatState> {
|
||||
_streamDone = null;
|
||||
}
|
||||
|
||||
Future<void> stopGenerating() async {
|
||||
if (!state.isStreaming) return;
|
||||
_generation++;
|
||||
await _cancelActiveStream();
|
||||
final messages = state.messages.toList();
|
||||
if (messages.isNotEmpty &&
|
||||
!messages.last.isUser &&
|
||||
messages.last.type == MessageType.text) {
|
||||
final last = messages.last;
|
||||
if (last.content.trim().isEmpty) {
|
||||
messages.removeLast();
|
||||
} else {
|
||||
last.content = '${last.content.trimRight()}\n\n(已停止生成)';
|
||||
last.metadata = {...?last.metadata, 'generationStopped': true};
|
||||
messages[messages.length - 1] = last;
|
||||
}
|
||||
}
|
||||
state = state.copyWith(
|
||||
messages: messages,
|
||||
isStreaming: false,
|
||||
thinkingText: null,
|
||||
);
|
||||
ref.invalidate(conversationHistoryProvider);
|
||||
}
|
||||
|
||||
void _addError(ChatMessage aiMsg, String errorText) {
|
||||
aiMsg.content = errorText;
|
||||
aiMsg.type = MessageType.text;
|
||||
|
||||
@@ -89,7 +89,14 @@ class ConsultationChatNotifier extends Notifier<ConsultationChatState> {
|
||||
String get _hubUrl => '$baseUrl/hubs/consultation';
|
||||
|
||||
@override
|
||||
ConsultationChatState build() => const ConsultationChatState();
|
||||
ConsultationChatState build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
ref.onDispose(() async {
|
||||
await _hub?.stop();
|
||||
_hub = null;
|
||||
});
|
||||
return const ConsultationChatState();
|
||||
}
|
||||
|
||||
Future<void> init(String doctorId) async {
|
||||
state = state.copyWith(doctorId: doctorId, isLoading: true);
|
||||
@@ -169,7 +176,7 @@ class ConsultationChatNotifier extends Notifier<ConsultationChatState> {
|
||||
senderName: data['senderName']?.toString(),
|
||||
content: data['content']?.toString() ?? '',
|
||||
createdAt: data['createdAt'] != null
|
||||
? DateTime.tryParse(data['createdAt'].toString()) ??
|
||||
? DateTime.tryParse(data['createdAt'].toString())?.toLocal() ??
|
||||
DateTime.now()
|
||||
: DateTime.now(),
|
||||
);
|
||||
@@ -228,7 +235,9 @@ class ConsultationChatNotifier extends Notifier<ConsultationChatState> {
|
||||
senderName: map['senderName']?.toString(),
|
||||
content: map['content']?.toString() ?? '',
|
||||
createdAt:
|
||||
DateTime.tryParse(map['createdAt']?.toString() ?? '') ??
|
||||
DateTime.tryParse(
|
||||
map['createdAt']?.toString() ?? '',
|
||||
)?.toLocal() ??
|
||||
DateTime.now(),
|
||||
);
|
||||
}).toList();
|
||||
@@ -354,7 +363,9 @@ class ConsultationChatNotifier extends Notifier<ConsultationChatState> {
|
||||
senderName: map['senderName']?.toString(),
|
||||
content: map['content']?.toString() ?? '',
|
||||
createdAt:
|
||||
DateTime.tryParse(map['createdAt']?.toString() ?? '') ??
|
||||
DateTime.tryParse(
|
||||
map['createdAt']?.toString() ?? '',
|
||||
)?.toLocal() ??
|
||||
DateTime.now(),
|
||||
);
|
||||
})
|
||||
|
||||
@@ -25,7 +25,7 @@ class ConversationListItem {
|
||||
summary: json['summary']?.toString(),
|
||||
messageCount: (json['messageCount'] as num?)?.toInt() ?? 0,
|
||||
updatedAt:
|
||||
DateTime.tryParse(json['updatedAt']?.toString() ?? '') ??
|
||||
DateTime.tryParse(json['updatedAt']?.toString() ?? '')?.toLocal() ??
|
||||
DateTime.now(),
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,8 @@ class ConversationHistoryNotifier
|
||||
extends AsyncNotifier<List<ConversationListItem>> {
|
||||
@override
|
||||
Future<List<ConversationListItem>> build() {
|
||||
final session = ref.watch(userSessionIdentityProvider);
|
||||
if (session == null) return Future.value(const []);
|
||||
return _fetch();
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ final inAppNotificationServiceProvider = Provider<InAppNotificationService>((
|
||||
});
|
||||
|
||||
final notificationUnreadCountProvider = FutureProvider<int>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final history = await ref
|
||||
.watch(inAppNotificationServiceProvider)
|
||||
.getHistory();
|
||||
@@ -52,6 +53,7 @@ final notificationUnreadCountProvider = FutureProvider<int>((ref) async {
|
||||
|
||||
/// 最新健康数据 Provider
|
||||
final latestHealthProvider = FutureProvider<Map<String, dynamic>>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final service = ref.watch(healthServiceProvider);
|
||||
return service.getLatest();
|
||||
});
|
||||
@@ -60,6 +62,7 @@ final latestHealthProvider = FutureProvider<Map<String, dynamic>>((ref) async {
|
||||
final medicationListProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final service = ref.watch(medicationServiceProvider);
|
||||
return service.getList();
|
||||
});
|
||||
@@ -67,24 +70,28 @@ final medicationListProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
final exercisePlansProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return ref.watch(exerciseServiceProvider).getPlans();
|
||||
});
|
||||
|
||||
final followUpListProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return ref.watch(followUpServiceProvider).getList();
|
||||
});
|
||||
|
||||
final dietRecordsProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return ref.watch(dietServiceProvider).getRecords();
|
||||
});
|
||||
|
||||
final medicationReminderProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final service = ref.watch(medicationServiceProvider);
|
||||
return service.getReminders();
|
||||
});
|
||||
@@ -92,6 +99,7 @@ final medicationReminderProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
/// 医生列表 Provider
|
||||
final doctorListProvider =
|
||||
FutureProvider.autoDispose<List<Map<String, dynamic>>>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final service = ref.watch(consultationServiceProvider);
|
||||
return service.getDoctors().timeout(const Duration(seconds: 8));
|
||||
});
|
||||
@@ -100,6 +108,7 @@ final doctorListProvider =
|
||||
final currentExercisePlanProvider = FutureProvider<Map<String, dynamic>?>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final service = ref.watch(exerciseServiceProvider);
|
||||
return service.getCurrentPlan().timeout(const Duration(seconds: 8));
|
||||
});
|
||||
|
||||
@@ -50,11 +50,13 @@ class DeviceBindState {
|
||||
|
||||
class DeviceBindNotifier extends Notifier<DeviceBindState> {
|
||||
StreamSubscription<bool>? _connSub;
|
||||
late String? _sessionIdentity;
|
||||
|
||||
@override
|
||||
DeviceBindState build() {
|
||||
_sessionIdentity = ref.watch(userSessionIdentityProvider);
|
||||
ref.onDispose(() => _connSub?.cancel());
|
||||
_loadBinding();
|
||||
if (_sessionIdentity != null) _loadBinding(_sessionIdentity!);
|
||||
_listenConnection();
|
||||
return const DeviceBindState();
|
||||
}
|
||||
@@ -70,17 +72,36 @@ class DeviceBindNotifier extends Notifier<DeviceBindState> {
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _loadBinding() async {
|
||||
String _accountKey(String baseKey, [String? session]) =>
|
||||
'$baseKey:${session ?? _sessionIdentity}';
|
||||
|
||||
Future<void> _loadBinding(String session) async {
|
||||
final db = ref.read(localDbProvider);
|
||||
await _migrateLegacyBloodPressureDevice();
|
||||
final raw = await db.read(_boundDevicesKey);
|
||||
await _migrateLegacyBloodPressureDevice(session);
|
||||
final raw = await db.read(_accountKey(_boundDevicesKey, session));
|
||||
final devices = _decodeDevices(raw);
|
||||
if (_sessionIdentity != session) return;
|
||||
state = state.copyWith(devices: devices);
|
||||
}
|
||||
|
||||
Future<void> _migrateLegacyBloodPressureDevice() async {
|
||||
Future<void> _migrateLegacyBloodPressureDevice(String session) async {
|
||||
final db = ref.read(localDbProvider);
|
||||
final existing = await db.read(_boundDevicesKey);
|
||||
final accountKey = _accountKey(_boundDevicesKey, session);
|
||||
final existing = await db.read(accountKey);
|
||||
final oldSharedDevices = await db.read(_boundDevicesKey);
|
||||
if (existing == null && oldSharedDevices != null) {
|
||||
await db.write(accountKey, oldSharedDevices);
|
||||
await db.delete(_boundDevicesKey);
|
||||
final oldFingerprints = await db.read(_readingFingerprintsKey);
|
||||
if (oldFingerprints != null) {
|
||||
await db.write(
|
||||
_accountKey(_readingFingerprintsKey, session),
|
||||
oldFingerprints,
|
||||
);
|
||||
await db.delete(_readingFingerprintsKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
final legacyMac = await db.read(_legacyBpMacKey);
|
||||
if (existing != null || legacyMac == null || legacyMac.isEmpty) return;
|
||||
|
||||
@@ -91,7 +112,7 @@ class DeviceBindNotifier extends Notifier<DeviceBindState> {
|
||||
type: BleDeviceType.bloodPressure,
|
||||
serviceUuid: BleDeviceType.bloodPressure.serviceUuid,
|
||||
);
|
||||
await db.write(_boundDevicesKey, jsonEncode([migrated.toJson()]));
|
||||
await db.write(accountKey, jsonEncode([migrated.toJson()]));
|
||||
await db.delete(_legacyBpMacKey);
|
||||
await db.delete(_legacyBpNameKey);
|
||||
await db.delete(_legacyBpLastSyncKey);
|
||||
@@ -117,7 +138,7 @@ class DeviceBindNotifier extends Notifier<DeviceBindState> {
|
||||
Future<void> _saveDevices(List<BoundBleDevice> devices) async {
|
||||
final db = ref.read(localDbProvider);
|
||||
await db.write(
|
||||
_boundDevicesKey,
|
||||
_accountKey(_boundDevicesKey),
|
||||
jsonEncode(devices.map((device) => device.toJson()).toList()),
|
||||
);
|
||||
state = state.copyWith(devices: devices);
|
||||
@@ -188,7 +209,7 @@ class DeviceBindNotifier extends Notifier<DeviceBindState> {
|
||||
|
||||
Future<Map<String, String>> _loadFingerprints() async {
|
||||
final db = ref.read(localDbProvider);
|
||||
final raw = await db.read(_readingFingerprintsKey);
|
||||
final raw = await db.read(_accountKey(_readingFingerprintsKey));
|
||||
if (raw == null || raw.isEmpty) return {};
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
@@ -203,7 +224,19 @@ class DeviceBindNotifier extends Notifier<DeviceBindState> {
|
||||
|
||||
Future<void> _saveFingerprints(Map<String, String> fingerprints) async {
|
||||
final db = ref.read(localDbProvider);
|
||||
await db.write(_readingFingerprintsKey, jsonEncode(fingerprints));
|
||||
await db.write(
|
||||
_accountKey(_readingFingerprintsKey),
|
||||
jsonEncode(fingerprints),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> clearCurrentAccountData() async {
|
||||
final session = _sessionIdentity;
|
||||
if (session == null) return;
|
||||
final db = ref.read(localDbProvider);
|
||||
await db.delete(_accountKey(_boundDevicesKey, session));
|
||||
await db.delete(_accountKey(_readingFingerprintsKey, session));
|
||||
state = const DeviceBindState();
|
||||
}
|
||||
|
||||
Map<String, String> _pruneFingerprints(
|
||||
|
||||
Reference in New Issue
Block a user