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:
@@ -9,7 +9,7 @@ const String baseUrl = String.fromEnvironment(
|
||||
'API_BASE_URL',
|
||||
defaultValue: kReleaseMode
|
||||
? 'https://erpapi.datalumina.cn/xiaomai'
|
||||
: 'http://10.4.165.54:5000',
|
||||
: 'http://192.168.1.34:5000',
|
||||
);
|
||||
|
||||
class ApiException implements Exception {
|
||||
@@ -44,6 +44,7 @@ class ApiClient {
|
||||
final Dio _dio;
|
||||
final LocalDatabase _db;
|
||||
final AuthExpiredNotifier? _authExpiredNotifier;
|
||||
Future<_TokenRefreshResult>? _refreshInFlight;
|
||||
|
||||
ApiClient({
|
||||
required LocalDatabase db,
|
||||
@@ -79,6 +80,63 @@ class ApiClient {
|
||||
await _db.delete('refresh_token');
|
||||
}
|
||||
|
||||
Future<void> clearTokensIfRefreshMatches(String failedRefreshToken) async {
|
||||
if (await refreshToken != failedRefreshToken) return;
|
||||
await clearTokens();
|
||||
}
|
||||
|
||||
Future<_TokenRefreshResult> _refreshTokens() {
|
||||
final active = _refreshInFlight;
|
||||
if (active != null) return active;
|
||||
final future = _performTokenRefresh();
|
||||
_refreshInFlight = future;
|
||||
return future.whenComplete(() {
|
||||
if (identical(_refreshInFlight, future)) _refreshInFlight = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<_TokenRefreshResult> _performTokenRefresh() async {
|
||||
final refresh = await refreshToken;
|
||||
if (refresh == null) return const _TokenRefreshResult.invalid();
|
||||
try {
|
||||
final response = await Dio(
|
||||
BaseOptions(
|
||||
baseUrl: baseUrl,
|
||||
connectTimeout: const Duration(seconds: 15),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
),
|
||||
).post('/api/auth/refresh', data: {'refreshToken': refresh});
|
||||
final body = response.data;
|
||||
final data = body is Map ? body['data'] : null;
|
||||
final rawCode = body is Map ? body['code'] : null;
|
||||
final code = rawCode is int ? rawCode : int.tryParse('$rawCode');
|
||||
if (code != null && code != 0) {
|
||||
return _TokenRefreshResult.invalid(refreshToken: refresh);
|
||||
}
|
||||
if (data is Map &&
|
||||
data['accessToken'] is String &&
|
||||
data['refreshToken'] is String) {
|
||||
final accessToken = data['accessToken'] as String;
|
||||
final newRefreshToken = data['refreshToken'] as String;
|
||||
// 刷新期间用户可能已经退出或切换账号,旧响应不得覆盖新会话。
|
||||
if (await refreshToken != refresh) {
|
||||
return const _TokenRefreshResult.transientFailure();
|
||||
}
|
||||
await saveTokens(accessToken, newRefreshToken);
|
||||
return _TokenRefreshResult.success(accessToken);
|
||||
}
|
||||
return const _TokenRefreshResult.transientFailure();
|
||||
} on DioException catch (error) {
|
||||
if (error.response?.statusCode == 400 ||
|
||||
error.response?.statusCode == 401) {
|
||||
return _TokenRefreshResult.invalid(refreshToken: refresh);
|
||||
}
|
||||
return const _TokenRefreshResult.transientFailure();
|
||||
} catch (_) {
|
||||
return const _TokenRefreshResult.transientFailure();
|
||||
}
|
||||
}
|
||||
|
||||
void notifyAuthExpired() {
|
||||
_authExpiredNotifier?.notify();
|
||||
}
|
||||
@@ -202,31 +260,51 @@ class _AuthInterceptor extends Interceptor {
|
||||
|
||||
@override
|
||||
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||
if (err.response?.statusCode == 401) {
|
||||
final refresh = await _client.refreshToken;
|
||||
if (refresh != null) {
|
||||
try {
|
||||
final response = await Dio(
|
||||
BaseOptions(baseUrl: baseUrl),
|
||||
).post('/api/auth/refresh', data: {'refreshToken': refresh});
|
||||
final data = response.data['data'];
|
||||
if (data != null) {
|
||||
await _client.saveTokens(data['accessToken'], data['refreshToken']);
|
||||
final opts = err.requestOptions;
|
||||
final token = data['accessToken'];
|
||||
opts.headers['Authorization'] = 'Bearer $token';
|
||||
final retryResponse = await Dio(
|
||||
BaseOptions(baseUrl: baseUrl),
|
||||
).fetch(opts);
|
||||
return handler.resolve(retryResponse);
|
||||
}
|
||||
} catch (e) {
|
||||
log('[ApiClient] token刷新失败: $e');
|
||||
}
|
||||
if (err.response?.statusCode != 401 ||
|
||||
err.requestOptions.extra['authRetried'] == true) {
|
||||
return handler.next(err);
|
||||
}
|
||||
|
||||
final result = await _client._refreshTokens();
|
||||
if (result.accessToken != null) {
|
||||
try {
|
||||
final opts = err.requestOptions;
|
||||
opts.extra['authRetried'] = true;
|
||||
opts.headers['Authorization'] = 'Bearer ${result.accessToken}';
|
||||
final retryResponse = await _client.dio.fetch(opts);
|
||||
return handler.resolve(retryResponse);
|
||||
} catch (error) {
|
||||
log('[ApiClient] 请求重试失败: $error');
|
||||
}
|
||||
} else if (result.isInvalid) {
|
||||
final failedRefresh = result.failedRefreshToken;
|
||||
if (failedRefresh != null) {
|
||||
await _client.clearTokensIfRefreshMatches(failedRefresh);
|
||||
} else {
|
||||
await _client.clearTokens();
|
||||
}
|
||||
await _client.clearTokens();
|
||||
_client.notifyAuthExpired();
|
||||
}
|
||||
handler.next(err);
|
||||
}
|
||||
}
|
||||
|
||||
class _TokenRefreshResult {
|
||||
final String? accessToken;
|
||||
final bool isInvalid;
|
||||
final String? failedRefreshToken;
|
||||
|
||||
const _TokenRefreshResult._({
|
||||
this.accessToken,
|
||||
this.isInvalid = false,
|
||||
this.failedRefreshToken,
|
||||
});
|
||||
|
||||
const _TokenRefreshResult.success(String accessToken)
|
||||
: this._(accessToken: accessToken);
|
||||
|
||||
const _TokenRefreshResult.invalid({String? refreshToken})
|
||||
: this._(isInvalid: true, failedRefreshToken: refreshToken);
|
||||
|
||||
const _TokenRefreshResult.transientFailure() : this._();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../providers/auth_provider.dart';
|
||||
import '../../widgets/admin_drawer.dart';
|
||||
import '../../widgets/backoffice_ui.dart';
|
||||
import 'admin_doctors_page.dart';
|
||||
@@ -12,7 +13,11 @@ final adminPageProvider = NotifierProvider<AdminPageNotifier, String>(
|
||||
|
||||
class AdminPageNotifier extends Notifier<String> {
|
||||
@override
|
||||
String build() => 'doctors';
|
||||
String build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return 'doctors';
|
||||
}
|
||||
|
||||
void set(String page) => state = page;
|
||||
}
|
||||
|
||||
|
||||
@@ -274,11 +274,12 @@ class _DeviceScanPageState extends ConsumerState<DeviceScanPage>
|
||||
if (await notifier.isDuplicateReading(device, reading)) return false;
|
||||
|
||||
final api = ref.read(apiClientProvider);
|
||||
await api.post('/api/health-records', data: reading.toHealthRecord());
|
||||
final records = <Map<String, dynamic>>[reading.toHealthRecord()];
|
||||
final heartRateRecord = reading.toHeartRateRecord();
|
||||
if (heartRateRecord != null) {
|
||||
await api.post('/api/health-records', data: heartRateRecord);
|
||||
records.add(heartRateRecord);
|
||||
}
|
||||
await api.post('/api/health-records/batch', data: records);
|
||||
await notifier.recordSuccessfulSync(device: device, reading: reading);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -81,7 +81,10 @@ class DietFoodValidationException implements Exception {
|
||||
|
||||
class DietNotifier extends Notifier<DietState> {
|
||||
@override
|
||||
DietState build() => DietState();
|
||||
DietState build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return DietState();
|
||||
}
|
||||
|
||||
void setImage(String path) {
|
||||
state = state.copyWith(imagePath: path);
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../../widgets/backoffice_ui.dart';
|
||||
final _consListProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/consultations');
|
||||
return (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
|
||||
@@ -7,6 +7,7 @@ import '../../widgets/backoffice_ui.dart';
|
||||
import '../doctor/doctor_home_page.dart' show doctorPageProvider;
|
||||
|
||||
final _dashboardProvider = FutureProvider<Map<String, dynamic>?>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/dashboard');
|
||||
return res.data['data'] as Map<String, dynamic>?;
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../../widgets/app_toast.dart';
|
||||
import '../../widgets/backoffice_ui.dart';
|
||||
|
||||
final _ptsSimple = FutureProvider<List<Map<String, dynamic>>>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/patients-simple');
|
||||
return (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
@@ -50,7 +51,9 @@ class _DoctorFollowUpEditPageState
|
||||
_titleCtrl.text = d['title'] ?? '';
|
||||
_notesCtrl.text = d['notes'] ?? '';
|
||||
_pid = d['userId']?.toString();
|
||||
final at = DateTime.tryParse(d['scheduledAt']?.toString() ?? '');
|
||||
final at = DateTime.tryParse(
|
||||
d['scheduledAt']?.toString() ?? '',
|
||||
)?.toLocal();
|
||||
if (at != null) {
|
||||
_date = at;
|
||||
_time = TimeOfDay.fromDateTime(at);
|
||||
@@ -261,7 +264,7 @@ class _DoctorFollowUpEditPageState
|
||||
final data = {
|
||||
'userId': _pid,
|
||||
'title': _titleCtrl.text.trim(),
|
||||
'scheduledAt': at.toIso8601String(),
|
||||
'scheduledAt': at.toUtc().toIso8601String(),
|
||||
'notes': _notesCtrl.text.trim().isEmpty ? null : _notesCtrl.text.trim(),
|
||||
};
|
||||
if (isEdit) {
|
||||
@@ -294,6 +297,7 @@ final _fupDetailForEdit = FutureProvider.family<Map<String, dynamic>?, String>((
|
||||
ref,
|
||||
id,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/follow-ups');
|
||||
final items = (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
|
||||
@@ -8,6 +8,7 @@ import '../../utils/backoffice_formatters.dart';
|
||||
import '../../widgets/backoffice_ui.dart';
|
||||
|
||||
final _fupRefresh = FutureProvider<String?>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/follow-ups');
|
||||
final items = (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
@@ -21,7 +22,11 @@ final _fupList = NotifierProvider<FupListN, List<Map<String, dynamic>>>(
|
||||
|
||||
class FupListN extends Notifier<List<Map<String, dynamic>>> {
|
||||
@override
|
||||
List<Map<String, dynamic>> build() => [];
|
||||
List<Map<String, dynamic>> build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return [];
|
||||
}
|
||||
|
||||
void replace(List<Map<String, dynamic>> v) => state = v;
|
||||
void markDone(String id) => state = state
|
||||
.map((f) => f['id'] == id ? {...f, 'status': 'Completed'} : f)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../providers/auth_provider.dart';
|
||||
import '../../widgets/doctor_drawer.dart';
|
||||
import '../../widgets/backoffice_ui.dart';
|
||||
import 'doctor_dashboard_page.dart';
|
||||
@@ -97,6 +98,10 @@ final doctorPageProvider = NotifierProvider<DoctorPageNotifier, String>(
|
||||
|
||||
class DoctorPageNotifier extends Notifier<String> {
|
||||
@override
|
||||
String build() => 'dashboard';
|
||||
String build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
return 'dashboard';
|
||||
}
|
||||
|
||||
void set(String page) => state = page;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import '../../widgets/backoffice_ui.dart';
|
||||
|
||||
final _patientDetailProvider =
|
||||
FutureProvider.family<Map<String, dynamic>?, String>((ref, id) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/patients/$id');
|
||||
return res.data['data'] as Map<String, dynamic>?;
|
||||
|
||||
@@ -7,6 +7,7 @@ import '../../widgets/app_toast.dart';
|
||||
import '../../widgets/backoffice_ui.dart';
|
||||
|
||||
final _docProfileProvider = FutureProvider<Map<String, dynamic>?>((ref) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/profile');
|
||||
return res.data['data'] as Map<String, dynamic>?;
|
||||
|
||||
@@ -10,6 +10,7 @@ import '../../widgets/backoffice_ui.dart';
|
||||
|
||||
final _reportDetailProvider =
|
||||
FutureProvider.family<Map<String, dynamic>?, String>((ref, id) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/reports/$id');
|
||||
return res.data['data'] as Map<String, dynamic>?;
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../../widgets/backoffice_ui.dart';
|
||||
final _reportsProvider = FutureProvider<List<Map<String, dynamic>>>((
|
||||
ref,
|
||||
) async {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
final api = ref.read(apiClientProvider);
|
||||
final res = await api.get('/api/doctor/reports');
|
||||
return (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
|
||||
|
||||
@@ -85,6 +85,7 @@ class _HomePageState extends ConsumerState<HomePage>
|
||||
}
|
||||
|
||||
void _sendMessage() {
|
||||
if (ref.read(chatProvider).isStreaming) return;
|
||||
final text = _textCtrl.text.trim();
|
||||
final imagePath = _pickedImagePath;
|
||||
if (text.isEmpty && imagePath == null) return;
|
||||
@@ -425,6 +426,9 @@ class _HomePageState extends ConsumerState<HomePage>
|
||||
}
|
||||
|
||||
Widget _buildInputBar() {
|
||||
final isStreaming = ref.watch(
|
||||
chatProvider.select((state) => state.isStreaming),
|
||||
);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 0, 12, 10),
|
||||
child: Container(
|
||||
@@ -490,7 +494,9 @@ class _HomePageState extends ConsumerState<HomePage>
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
customBorder: const CircleBorder(),
|
||||
onTap: _sendMessage,
|
||||
onTap: isStreaming
|
||||
? () => ref.read(chatProvider.notifier).stopGenerating()
|
||||
: _sendMessage,
|
||||
child: Ink(
|
||||
width: 38,
|
||||
height: 38,
|
||||
@@ -498,8 +504,8 @@ class _HomePageState extends ConsumerState<HomePage>
|
||||
gradient: AppColors.primaryGradient,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(
|
||||
LucideIcons.send,
|
||||
child: Icon(
|
||||
isStreaming ? Icons.stop_rounded : LucideIcons.send,
|
||||
size: 18,
|
||||
color: Colors.white,
|
||||
),
|
||||
|
||||
@@ -6,12 +6,12 @@ import '../../../core/app_colors.dart';
|
||||
import '../../../core/app_design_tokens.dart';
|
||||
import '../../../core/app_module_visuals.dart';
|
||||
import '../../../core/app_theme.dart';
|
||||
import '../../../core/api_client.dart' show baseUrl;
|
||||
import '../../../core/navigation_provider.dart';
|
||||
import '../../../providers/chat_provider.dart';
|
||||
import '../../../providers/data_providers.dart';
|
||||
import '../../../widgets/ai_content.dart';
|
||||
import '../../../widgets/app_toast.dart';
|
||||
import '../../../widgets/authenticated_network_image.dart';
|
||||
|
||||
ChatMessage messageAtDisplayIndex(List<ChatMessage> messages, int index) =>
|
||||
messages[index];
|
||||
@@ -1045,8 +1045,8 @@ class ChatMessagesView extends ConsumerWidget {
|
||||
child: localPath != null
|
||||
? Image.file(File(localPath), fit: BoxFit.cover)
|
||||
: imageUrl != null
|
||||
? Image.network(
|
||||
_mediaUrl(imageUrl),
|
||||
? AuthenticatedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, e, s) => Container(
|
||||
width: 80,
|
||||
@@ -1122,7 +1122,11 @@ class ChatMessagesView extends ConsumerWidget {
|
||||
|
||||
static void _showFullImage(BuildContext context, String? path) {
|
||||
if (path == null) return;
|
||||
final resolvedPath = _mediaUrl(path);
|
||||
final isNetwork =
|
||||
path.startsWith('http://') ||
|
||||
path.startsWith('https://') ||
|
||||
path.startsWith('/uploads/') ||
|
||||
path.startsWith('/api/');
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => Dialog(
|
||||
@@ -1134,9 +1138,12 @@ class ChatMessagesView extends ConsumerWidget {
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: InteractiveViewer(
|
||||
child: resolvedPath.startsWith('http')
|
||||
? Image.network(resolvedPath, fit: BoxFit.contain)
|
||||
: Image.file(File(resolvedPath), fit: BoxFit.contain),
|
||||
child: isNetwork
|
||||
? AuthenticatedNetworkImage(
|
||||
imageUrl: path,
|
||||
fit: BoxFit.contain,
|
||||
)
|
||||
: Image.file(File(path), fit: BoxFit.contain),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
@@ -1160,12 +1167,6 @@ class ChatMessagesView extends ConsumerWidget {
|
||||
);
|
||||
}
|
||||
|
||||
static String _mediaUrl(String path) {
|
||||
if (path.startsWith('http://') || path.startsWith('https://')) return path;
|
||||
if (path.startsWith('/uploads/')) return '$baseUrl$path';
|
||||
return path;
|
||||
}
|
||||
|
||||
/// 处理 AI 回复里的 markdown 链接点击:
|
||||
/// - app://diet → 触发拍照/相册选择,跳到饮食拍照流程
|
||||
/// - app://report → 跳到报告列表(用户可在那里上传新报告)
|
||||
|
||||
@@ -27,6 +27,7 @@ class DietRecordListPage extends ConsumerStatefulWidget {
|
||||
class _DietRecordListPageState extends ConsumerState<DietRecordListPage> {
|
||||
List<Map<String, dynamic>> _data = [];
|
||||
bool _loading = true;
|
||||
String? _loadError;
|
||||
int _trendDays = 7;
|
||||
DateTime _selectedDate = DateTime.now();
|
||||
|
||||
@@ -37,12 +38,22 @@ class _DietRecordListPageState extends ConsumerState<DietRecordListPage> {
|
||||
}
|
||||
|
||||
Future<void> _refresh() async {
|
||||
final records = await ref.read(dietServiceProvider).getRecords();
|
||||
if (mounted) {
|
||||
try {
|
||||
final records = await ref.read(dietServiceProvider).getRecords();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_data = records;
|
||||
_loading = false;
|
||||
_loadError = null;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
if (_data.isEmpty) {
|
||||
setState(() => _loadError = '网络异常或服务暂时不可用,请稍后重试');
|
||||
} else {
|
||||
AppToast.show(context, '刷新失败,已保留当前记录', type: AppToastType.error);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +115,19 @@ class _DietRecordListPageState extends ConsumerState<DietRecordListPage> {
|
||||
onPressed: () => popRoute(ref),
|
||||
),
|
||||
),
|
||||
body: const Center(child: CircularProgressIndicator()),
|
||||
body: _loadError == null
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: AppErrorState(
|
||||
title: '饮食记录加载失败',
|
||||
subtitle: _loadError,
|
||||
onRetry: () {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_loadError = null;
|
||||
});
|
||||
_refresh();
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -390,33 +413,67 @@ class _DietRecordListPageState extends ConsumerState<DietRecordListPage> {
|
||||
|
||||
void _showEditDialog(String id, num cal) {
|
||||
final ctrl = TextEditingController(text: '$cal');
|
||||
showDialog(
|
||||
var saving = false;
|
||||
showDialog<void>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('修改热量'),
|
||||
content: TextField(
|
||||
controller: ctrl,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(labelText: '热量(千卡)'),
|
||||
barrierDismissible: !saving,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (context, setDialogState) => AlertDialog(
|
||||
title: const Text('修改热量'),
|
||||
content: TextField(
|
||||
controller: ctrl,
|
||||
enabled: !saving,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(labelText: '热量(千卡)'),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: saving ? null : () => Navigator.pop(ctx),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: saving
|
||||
? null
|
||||
: () async {
|
||||
final calories = int.tryParse(ctrl.text.trim());
|
||||
if (calories == null || calories < 0) {
|
||||
AppToast.show(
|
||||
context,
|
||||
'请输入正确的热量',
|
||||
type: AppToastType.warning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setDialogState(() => saving = true);
|
||||
try {
|
||||
await ref.read(dietServiceProvider).updateRecord(id, {
|
||||
'totalCalories': calories,
|
||||
});
|
||||
if (!ctx.mounted) return;
|
||||
Navigator.pop(ctx);
|
||||
await _refresh();
|
||||
} catch (_) {
|
||||
if (!ctx.mounted) return;
|
||||
setDialogState(() => saving = false);
|
||||
AppToast.show(
|
||||
context,
|
||||
'保存失败,请检查网络后重试',
|
||||
type: AppToastType.error,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: saving
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('保存'),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
Navigator.pop(ctx);
|
||||
await ref.read(dietServiceProvider).updateRecord(id, {
|
||||
'totalCalories': int.tryParse(ctrl.text) ?? 0,
|
||||
});
|
||||
_refresh();
|
||||
},
|
||||
child: const Text('保存'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
).whenComplete(ctrl.dispose);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2546,7 +2603,7 @@ class _FollowUpItem extends StatelessWidget {
|
||||
|
||||
String _formatDateTime(String? iso) {
|
||||
if (iso == null) return '';
|
||||
final dt = DateTime.tryParse(iso);
|
||||
final dt = DateTime.tryParse(iso)?.toLocal();
|
||||
if (dt == null) return iso;
|
||||
return '${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')}';
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import '../../widgets/enterprise_widgets.dart';
|
||||
import '../../widgets/app_error_state.dart';
|
||||
import '../../widgets/app_empty_state.dart';
|
||||
import '../../widgets/app_toast.dart';
|
||||
import '../../widgets/authenticated_network_image.dart';
|
||||
|
||||
const _reportPageColor = AppColors.report;
|
||||
const _reportPageSoft = Color(0xFFF0F0FF);
|
||||
@@ -202,6 +203,7 @@ class ReportNotifier extends Notifier<ReportState> {
|
||||
|
||||
@override
|
||||
ReportState build() {
|
||||
ref.watch(userSessionIdentityProvider);
|
||||
ref.onDispose(() => _pollTimer?.cancel());
|
||||
Future.microtask(() => loadReports());
|
||||
return ReportState();
|
||||
@@ -237,7 +239,7 @@ class ReportNotifier extends Notifier<ReportState> {
|
||||
title: title,
|
||||
type: m['fileType']?.toString() ?? 'Image',
|
||||
uploadedAt:
|
||||
DateTime.tryParse(m['createdAt']?.toString() ?? '') ??
|
||||
DateTime.tryParse(m['createdAt']?.toString() ?? '')?.toLocal() ??
|
||||
DateTime.now(),
|
||||
fileUrl: m['fileUrl']?.toString(),
|
||||
hasAnalysis: m['aiSummary'] != null,
|
||||
@@ -249,7 +251,9 @@ class ReportNotifier extends Notifier<ReportState> {
|
||||
doctorComment: m['doctorComment']?.toString(),
|
||||
doctorRecommendation: m['doctorRecommendation']?.toString(),
|
||||
doctorName: m['doctorName']?.toString(),
|
||||
reviewedAt: DateTime.tryParse(m['reviewedAt']?.toString() ?? ''),
|
||||
reviewedAt: DateTime.tryParse(
|
||||
m['reviewedAt']?.toString() ?? '',
|
||||
)?.toLocal(),
|
||||
);
|
||||
}).toList();
|
||||
state = state.copyWith(
|
||||
@@ -1053,8 +1057,8 @@ class _ReportOriginalPageState extends ConsumerState<ReportOriginalPage> {
|
||||
child: InteractiveViewer(
|
||||
minScale: 0.7,
|
||||
maxScale: 4,
|
||||
child: Image.network(
|
||||
imageUrl,
|
||||
child: AuthenticatedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
key: ValueKey('$imageUrl-$_reloadToken'),
|
||||
fit: BoxFit.contain,
|
||||
loadingBuilder: (context, child, progress) {
|
||||
|
||||
@@ -21,7 +21,8 @@ final notificationPrefsProvider =
|
||||
class NotificationPrefsNotifier extends Notifier<NotificationPrefsViewState> {
|
||||
@override
|
||||
NotificationPrefsViewState build() {
|
||||
Future.microtask(load);
|
||||
final session = ref.watch(userSessionIdentityProvider);
|
||||
if (session != null) Future.microtask(load);
|
||||
return const NotificationPrefsViewState(loading: true);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../../core/app_design_tokens.dart';
|
||||
import '../../core/app_theme.dart';
|
||||
import '../../core/navigation_provider.dart';
|
||||
import '../../providers/auth_provider.dart';
|
||||
import '../../providers/omron_device_provider.dart';
|
||||
|
||||
class SettingsPage extends ConsumerWidget {
|
||||
const SettingsPage({super.key});
|
||||
@@ -172,6 +173,7 @@ class SettingsPage extends ConsumerWidget {
|
||||
);
|
||||
if (ok == true) {
|
||||
await ref.read(apiClientProvider).delete('/api/user/account');
|
||||
await ref.read(omronDeviceProvider.notifier).clearCurrentAccountData();
|
||||
await ref.read(authProvider.notifier).logout();
|
||||
goRoute(ref, 'login');
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -34,7 +34,7 @@ class InAppNotification {
|
||||
actionTargetId: json['actionTargetId']?.toString(),
|
||||
isRead: json['isRead'] == true,
|
||||
createdAt:
|
||||
DateTime.tryParse(json['createdAt']?.toString() ?? '') ??
|
||||
DateTime.tryParse(json['createdAt']?.toString() ?? '')?.toLocal() ??
|
||||
DateTime.now(),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ class SseHandler {
|
||||
String? pdfUrl,
|
||||
required String token,
|
||||
}) {
|
||||
final params = <String, String>{'message': message, 'token': token};
|
||||
final params = <String, String>{'message': message};
|
||||
if (conversationId != null) {
|
||||
params['conversationId'] = conversationId;
|
||||
}
|
||||
@@ -29,14 +29,26 @@ class SseHandler {
|
||||
.join('&');
|
||||
final url = '$baseUrl/api/ai/$agentType/chat?$query';
|
||||
|
||||
final controller = StreamController<Map<String, dynamic>>();
|
||||
_connect(controller, url);
|
||||
final cancelToken = CancelToken();
|
||||
late final StreamController<Map<String, dynamic>> controller;
|
||||
controller = StreamController<Map<String, dynamic>>(
|
||||
onListen: () {
|
||||
_connect(controller, url, token, cancelToken);
|
||||
},
|
||||
onCancel: () {
|
||||
if (!cancelToken.isCancelled) {
|
||||
cancelToken.cancel('用户停止生成');
|
||||
}
|
||||
},
|
||||
);
|
||||
return controller.stream;
|
||||
}
|
||||
|
||||
static Future<void> _connect(
|
||||
StreamController<Map<String, dynamic>> controller,
|
||||
String url,
|
||||
String token,
|
||||
CancelToken cancelToken,
|
||||
) async {
|
||||
try {
|
||||
final dio = Dio(
|
||||
@@ -48,7 +60,11 @@ class SseHandler {
|
||||
|
||||
final response = await dio.get(
|
||||
url,
|
||||
options: Options(responseType: ResponseType.stream),
|
||||
cancelToken: cancelToken,
|
||||
options: Options(
|
||||
responseType: ResponseType.stream,
|
||||
headers: {'Authorization': 'Bearer $token'},
|
||||
),
|
||||
);
|
||||
|
||||
final stream = response.data.stream as Stream<List<int>>;
|
||||
@@ -81,10 +97,19 @@ class SseHandler {
|
||||
}
|
||||
}
|
||||
controller.close();
|
||||
} on DioException catch (e) {
|
||||
if (CancelToken.isCancel(e)) {
|
||||
if (!controller.isClosed) await controller.close();
|
||||
return;
|
||||
}
|
||||
if (!controller.isClosed) {
|
||||
controller.add({'action': 'error', 'message': e.toString()});
|
||||
await controller.close();
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.isClosed) {
|
||||
controller.add({'action': 'error', 'message': e.toString()});
|
||||
controller.close();
|
||||
await controller.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
131
health_app/lib/widgets/authenticated_network_image.dart
Normal file
131
health_app/lib/widgets/authenticated_network_image.dart
Normal file
@@ -0,0 +1,131 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/api_client.dart' show baseUrl;
|
||||
import '../providers/auth_provider.dart';
|
||||
|
||||
String protectedMediaUrl(String value) {
|
||||
final trimmed = value.trim();
|
||||
if (trimmed.isEmpty) return trimmed;
|
||||
|
||||
final absolute = Uri.tryParse(trimmed);
|
||||
final path = absolute?.path ?? trimmed.split('?').first;
|
||||
final legacyIndex = path.toLowerCase().indexOf('/uploads/users/');
|
||||
if (legacyIndex >= 0) {
|
||||
final fileName = Uri.decodeComponent(path.split('/').last);
|
||||
return '$baseUrl/api/files/content/${Uri.encodeComponent(fileName)}';
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
||||
return trimmed;
|
||||
}
|
||||
if (trimmed.startsWith('/')) return '$baseUrl$trimmed';
|
||||
return '$baseUrl/$trimmed';
|
||||
}
|
||||
|
||||
bool mediaRequiresAuthentication(String url) {
|
||||
final normalizedBase = baseUrl.endsWith('/') ? baseUrl : '$baseUrl/';
|
||||
return url == baseUrl || url.startsWith(normalizedBase);
|
||||
}
|
||||
|
||||
class AuthenticatedNetworkImage extends ConsumerStatefulWidget {
|
||||
final String imageUrl;
|
||||
final BoxFit? fit;
|
||||
final double? width;
|
||||
final double? height;
|
||||
final ImageLoadingBuilder? loadingBuilder;
|
||||
final ImageErrorWidgetBuilder? errorBuilder;
|
||||
|
||||
const AuthenticatedNetworkImage({
|
||||
super.key,
|
||||
required this.imageUrl,
|
||||
this.fit,
|
||||
this.width,
|
||||
this.height,
|
||||
this.loadingBuilder,
|
||||
this.errorBuilder,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<AuthenticatedNetworkImage> createState() =>
|
||||
_AuthenticatedNetworkImageState();
|
||||
}
|
||||
|
||||
class _AuthenticatedNetworkImageState
|
||||
extends ConsumerState<AuthenticatedNetworkImage> {
|
||||
late String _resolvedUrl;
|
||||
Future<Uint8List>? _bytes;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_configure();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant AuthenticatedNetworkImage oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.imageUrl != widget.imageUrl) _configure();
|
||||
}
|
||||
|
||||
void _configure() {
|
||||
_resolvedUrl = protectedMediaUrl(widget.imageUrl);
|
||||
_bytes = mediaRequiresAuthentication(_resolvedUrl)
|
||||
? _loadProtectedBytes(_resolvedUrl)
|
||||
: null;
|
||||
}
|
||||
|
||||
Future<Uint8List> _loadProtectedBytes(String url) async {
|
||||
final response = await ref
|
||||
.read(apiClientProvider)
|
||||
.dio
|
||||
.get<List<int>>(
|
||||
url,
|
||||
options: Options(responseType: ResponseType.bytes),
|
||||
);
|
||||
return Uint8List.fromList(response.data ?? const []);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bytes = _bytes;
|
||||
if (bytes == null) {
|
||||
return Image.network(
|
||||
_resolvedUrl,
|
||||
fit: widget.fit,
|
||||
width: widget.width,
|
||||
height: widget.height,
|
||||
loadingBuilder: widget.loadingBuilder,
|
||||
errorBuilder: widget.errorBuilder,
|
||||
);
|
||||
}
|
||||
|
||||
return FutureBuilder<Uint8List>(
|
||||
future: bytes,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasError) {
|
||||
return widget.errorBuilder?.call(
|
||||
context,
|
||||
snapshot.error!,
|
||||
snapshot.stackTrace,
|
||||
) ??
|
||||
const Icon(Icons.broken_image_outlined);
|
||||
}
|
||||
final data = snapshot.data;
|
||||
if (data == null) {
|
||||
return const Center(child: CircularProgressIndicator(strokeWidth: 2));
|
||||
}
|
||||
return Image.memory(
|
||||
data,
|
||||
fit: widget.fit,
|
||||
width: widget.width,
|
||||
height: widget.height,
|
||||
errorBuilder: widget.errorBuilder,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user