90f318e246
Deploy Client / build-windows (push) Failing after 21s
Deploy Client / build-client-web (push) Successful in 42s
Deploy Client / build-macos (push) Successful in 2m8s
Deploy Client / build-android (push) Successful in 1m25s
Deploy Client / build-ios (push) Successful in 2m47s
Deploy Client / release-deploy-client (push) Has been skipped
设备/状态管理屏(查看本店在线设备/会话,管理员可强制下线)、登录携带设备信息、 会话心跳(/auth/ping)、被踢下线/会话失效提示、顶栏精简 + 用户名移至左侧栏底部。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
166 lines
5.9 KiB
Dart
166 lines
5.9 KiB
Dart
import 'package:dio/dio.dart';
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||
import '../auth/auth_state.dart';
|
||
import '../config/app_config.dart';
|
||
import '../errors/error_reporter.dart';
|
||
import '../../providers/connectivity_provider.dart';
|
||
import 'retry_interceptor.dart';
|
||
|
||
/// Public Dio instance for unauthenticated calls (login / refresh)
|
||
final _publicDio = _buildPublicDio();
|
||
|
||
Dio _buildPublicDio() {
|
||
final dio = Dio(BaseOptions(
|
||
baseUrl: AppConfig.apiBaseUrl,
|
||
connectTimeout: const Duration(seconds: 8),
|
||
receiveTimeout: const Duration(seconds: 15),
|
||
));
|
||
dio.interceptors.add(RetryInterceptor(dio));
|
||
return dio;
|
||
}
|
||
|
||
final apiClientProvider = Provider<ApiClient>((ref) {
|
||
// 只监听登录/登出,不监听 token 内容变化。
|
||
// token refresh 只改 accessToken,isLoggedIn 不变,provider 不重建,
|
||
// 避免旧 Dio 被 close 后还在执行 fetch 导致 "adapter was closed"。
|
||
ref.watch(authStateProvider.select((s) => s.isLoggedIn));
|
||
final user = ref.read(authStateProvider).user;
|
||
|
||
final client = ApiClient(
|
||
token: user?.accessToken,
|
||
refreshToken: user?.refreshToken,
|
||
onTokenRefreshed: (newToken) {
|
||
ref.read(authStateProvider.notifier).updateAccessToken(newToken);
|
||
},
|
||
onAuthFailed: (reason) {
|
||
if (ref.read(authStateProvider).isLoggedIn) {
|
||
if (reason != null) {
|
||
ref.read(sessionEndedMessageProvider.notifier).state = reason;
|
||
}
|
||
ref.read(authStateProvider.notifier).logout();
|
||
}
|
||
},
|
||
onConnectionError: () {
|
||
ref.read(connectivityProvider.notifier).forceCheck();
|
||
},
|
||
);
|
||
ref.onDispose(client.dispose);
|
||
return client;
|
||
});
|
||
|
||
class ApiClient {
|
||
late final Dio _dio;
|
||
bool _disposed = false;
|
||
|
||
ApiClient({
|
||
String? token,
|
||
String? refreshToken,
|
||
void Function(String newToken)? onTokenRefreshed,
|
||
void Function(String? reason)? onAuthFailed,
|
||
void Function()? onConnectionError,
|
||
}) {
|
||
_dio = Dio(BaseOptions(
|
||
baseUrl: AppConfig.apiBaseUrl,
|
||
connectTimeout: const Duration(seconds: 8),
|
||
receiveTimeout: const Duration(seconds: 15),
|
||
headers: {
|
||
if (token != null) 'Authorization': 'Bearer $token',
|
||
},
|
||
));
|
||
|
||
// 网络层错误自动重试(须在错误处理拦截器之前,先重试再走 401/上报逻辑)
|
||
_dio.interceptors.add(RetryInterceptor(_dio));
|
||
|
||
// 网络错误 + 401 拦截器
|
||
_dio.interceptors.add(
|
||
InterceptorsWrapper(
|
||
onError: (DioException e, ErrorInterceptorHandler handler) async {
|
||
if (_disposed) return handler.next(e);
|
||
|
||
// 网络层错误(连接拒绝、超时等)→ 立即触发连通性检测
|
||
final isNetworkError = e.type == DioExceptionType.connectionError ||
|
||
e.type == DioExceptionType.connectionTimeout ||
|
||
e.type == DioExceptionType.receiveTimeout ||
|
||
e.type == DioExceptionType.sendTimeout;
|
||
if (isNetworkError) {
|
||
onConnectionError?.call();
|
||
return handler.next(e);
|
||
}
|
||
|
||
// 服务端 5xx 错误上报(4xx 是业务/权限错误,不上报)
|
||
final statusCode = e.response?.statusCode ?? 0;
|
||
if (statusCode >= 500) {
|
||
reportError(
|
||
'[${e.requestOptions.method}] ${e.requestOptions.path} → $statusCode',
|
||
e.stackTrace,
|
||
errorType: ErrorType.apiError,
|
||
);
|
||
}
|
||
|
||
if (e.response?.statusCode == 401 && (refreshToken ?? '').isNotEmpty) {
|
||
debugPrint('[ApiClient] got 401 on ${e.requestOptions.path}, trying refresh...');
|
||
try {
|
||
final resp = await _publicDio.post('/auth/refresh', data: {
|
||
'refresh_token': refreshToken,
|
||
});
|
||
final newToken = resp.data['data']['access_token'] as String;
|
||
_dio.options.headers['Authorization'] = 'Bearer $newToken';
|
||
if (!_disposed) onTokenRefreshed?.call(newToken);
|
||
final opts = e.requestOptions;
|
||
opts.headers['Authorization'] = 'Bearer $newToken';
|
||
final retryResp = await _dio.fetch(opts);
|
||
return handler.resolve(retryResp);
|
||
} catch (refreshErr) {
|
||
debugPrint('[ApiClient] refresh failed: $refreshErr');
|
||
// 区分「被踢/会话失效」与普通登录过期,便于登录页给出明确提示
|
||
String? reason;
|
||
if (refreshErr is DioException &&
|
||
refreshErr.response?.data is Map &&
|
||
refreshErr.response?.data['code'] == 'SESSION_REVOKED') {
|
||
reason = '您的账号已在其他设备登录,或登录已失效,请重新登录';
|
||
}
|
||
if (!_disposed) onAuthFailed?.call(reason);
|
||
}
|
||
} else if (e.response?.statusCode == 401) {
|
||
debugPrint('[ApiClient] got 401 on ${e.requestOptions.path}, no refresh token');
|
||
}
|
||
return handler.next(e);
|
||
},
|
||
),
|
||
);
|
||
}
|
||
|
||
/// 取消所有进行中的请求,标记实例为已废弃
|
||
void dispose() {
|
||
_disposed = true;
|
||
_dio.close(force: true);
|
||
}
|
||
|
||
Future<Response> get(String path, {Map<String, dynamic>? params}) =>
|
||
_dio.get(path, queryParameters: params);
|
||
|
||
Future<List<int>> getBytes(String path) async {
|
||
final resp = await _dio.get<List<int>>(path,
|
||
options: Options(responseType: ResponseType.bytes));
|
||
return resp.data ?? [];
|
||
}
|
||
|
||
Future<Response> post(String path, {dynamic data}) =>
|
||
_dio.post(path, data: data);
|
||
|
||
Future<Response> put(String path, {dynamic data}) =>
|
||
_dio.put(path, data: data);
|
||
|
||
Future<Response> patch(String path, {dynamic data}) =>
|
||
_dio.patch(path, data: data);
|
||
|
||
Future<Response> delete(String path) => _dio.delete(path);
|
||
}
|
||
|
||
/// Unauthenticated client for login/refresh
|
||
class PublicApiClient {
|
||
static Future<Response> post(String path, {dynamic data}) =>
|
||
_publicDio.post(path, data: data);
|
||
}
|