87 lines
2.4 KiB
Dart
87 lines
2.4 KiB
Dart
import 'package:dio/dio.dart';
|
|
import 'package:miaoji_zhang/shared/update/update_config.dart';
|
|
import 'package:miaoji_zhang/shared/update/update_models.dart';
|
|
|
|
enum UpdateFailureKind { unavailable, rateLimited, network, invalidResponse }
|
|
|
|
class UpdateCheckException implements Exception {
|
|
final UpdateFailureKind kind;
|
|
final String message;
|
|
|
|
const UpdateCheckException(this.kind, this.message);
|
|
|
|
@override
|
|
String toString() => message;
|
|
}
|
|
|
|
class UpdateApi {
|
|
UpdateApi({Dio? dio})
|
|
: _dio =
|
|
dio ??
|
|
Dio(
|
|
BaseOptions(
|
|
baseUrl: UpdateConfig.baseUrl,
|
|
connectTimeout: const Duration(seconds: 8),
|
|
receiveTimeout: const Duration(seconds: 15),
|
|
sendTimeout: const Duration(seconds: 8),
|
|
),
|
|
);
|
|
|
|
final Dio _dio;
|
|
|
|
Future<UpdateCheckResponse> check({
|
|
required String platform,
|
|
required String channel,
|
|
required int currentBuild,
|
|
}) async {
|
|
try {
|
|
final response = await _dio.get<Object?>(
|
|
'/api/client/v1/update',
|
|
queryParameters: {
|
|
'appKey': UpdateConfig.appKey,
|
|
'platform': platform,
|
|
'channel': channel,
|
|
'currentBuild': currentBuild,
|
|
},
|
|
);
|
|
final data = response.data;
|
|
if (data is! Map) {
|
|
throw const UpdateCheckException(
|
|
UpdateFailureKind.invalidResponse,
|
|
'更新服务返回格式异常',
|
|
);
|
|
}
|
|
return UpdateCheckResponse.fromJson(Map<String, dynamic>.from(data));
|
|
} on DioException catch (error) {
|
|
switch (error.response?.statusCode) {
|
|
case 404:
|
|
throw const UpdateCheckException(
|
|
UpdateFailureKind.unavailable,
|
|
'当前版本尚未配置更新渠道',
|
|
);
|
|
case 429:
|
|
throw const UpdateCheckException(
|
|
UpdateFailureKind.rateLimited,
|
|
'检查更新过于频繁,请稍后再试',
|
|
);
|
|
}
|
|
throw const UpdateCheckException(
|
|
UpdateFailureKind.network,
|
|
'暂时无法连接更新服务,请检查网络后重试',
|
|
);
|
|
} on UpdateCheckException {
|
|
rethrow;
|
|
} on FormatException catch (error) {
|
|
throw UpdateCheckException(
|
|
UpdateFailureKind.invalidResponse,
|
|
error.message.toString(),
|
|
);
|
|
} catch (_) {
|
|
throw const UpdateCheckException(
|
|
UpdateFailureKind.invalidResponse,
|
|
'更新服务返回格式异常',
|
|
);
|
|
}
|
|
}
|
|
}
|