config_inject.dart 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import 'dart:io';
  2. import 'package:crypto/crypto.dart' as crypto;
  3. import 'package:dio/adapter.dart';
  4. import 'package:dio/dio.dart';
  5. import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:get_it/get_it.dart';
  8. import 'package:package_info/package_info.dart';
  9. import 'package:shared_preferences/shared_preferences.dart';
  10. import 'package:sport/application.dart';
  11. import 'package:sport/config.dart';
  12. import 'package:sport/provider/bluetooth.dart';
  13. import 'package:sport/provider/game_info_model.dart';
  14. import 'package:sport/provider/game_model.dart';
  15. import 'package:sport/provider/login_info_model.dart';
  16. import 'package:sport/provider/message_model.dart';
  17. import 'package:sport/router/navigator_util.dart';
  18. import 'package:sport/services/api/login_api.dart';
  19. import 'package:sport/services/api/rest_client.dart';
  20. import 'package:sport/utils/toast.dart';
  21. class ConfigInject {
  22. int? os;
  23. String? version;
  24. Future<RequestOptions> _merge(RequestOptions options) async {
  25. if (version == null) {
  26. PackageInfo info = await PackageInfo.fromPlatform();
  27. version = "${info.version}+${info.buildNumber}";
  28. }
  29. if (os == null) {
  30. os = Platform.isAndroid
  31. ? 1
  32. : Platform.isIOS
  33. ? 2
  34. : 3;
  35. }
  36. SharedPreferences prefs = await SharedPreferences.getInstance();
  37. String token = prefs.getString("token") ?? "";
  38. Map<String, dynamic> headers = {Headers.acceptHeader: "gzip"};
  39. if (options.path.startsWith("/user/")) {
  40. headers.addAll(await Application.getDeviceInfoMap());
  41. }
  42. headers["token"] = "$token";
  43. var t = "${DateTime.now().millisecondsSinceEpoch}";
  44. headers["t"] = t;
  45. headers["sign"] = "${signMd5("ouj.com$t$token")}";
  46. return options.copyWith(headers: headers, queryParameters: options.queryParameters..addAll({"ver": "$version", "os": "$os", "sv": shoeVersion}));
  47. }
  48. String signMd5(String data) {
  49. return crypto.md5.convert(data.codeUnits).toString();
  50. }
  51. void inject(Config config) {
  52. isDebugShoe = config.debug;
  53. GetIt getIt = GetIt.instance;
  54. getIt.registerSingleton<Dio>(
  55. Dio(BaseOptions(
  56. baseUrl: config.baseUrl,
  57. connectTimeout: 10000,
  58. sendTimeout: 30000,
  59. receiveTimeout: 30000,
  60. // requestEncoder: (String request, RequestOptions options){
  61. // return GZipCodec().encoder()
  62. // }
  63. ))
  64. ..interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
  65. _merge(options).then((d) {
  66. handler.next(d);
  67. }).catchError((error, stackTrace) {
  68. handler.next(options);
  69. // handler.reject(error, true);
  70. });
  71. }, onResponse: (Response response, ResponseInterceptorHandler handler) {
  72. if (response.requestOptions.path.contains("checkUpdate") == true) {
  73. handler.next(response);
  74. return;
  75. }
  76. if (response.data is Map<String, dynamic>) {
  77. Map<String, dynamic> resp = response.data;
  78. if (resp['code'] == -5 || resp['code'] == -14) {
  79. SharedPreferences.getInstance().then((value) {
  80. if (Application.context != null && value.getString("token")?.isNotEmpty == true) {
  81. ToastUtil.showBottom("${resp['msg']}");
  82. NavigatorUtil.goLogin(Application.context!);
  83. }
  84. value.clear();
  85. });
  86. handler.resolve(response);
  87. return;
  88. } else if (resp['code'] != 0) {
  89. String? msg = resp['msg'];
  90. if (msg != null) ToastUtil.show("${resp['msg']}");
  91. }
  92. }
  93. handler.next(response);
  94. }, onError: (DioError e, ErrorInterceptorHandler handler) {
  95. print("network error $e");
  96. if (e.error is SocketException) {
  97. if (appLifecycleState == AppLifecycleState.resumed) ToastUtil.show("当前网络不可用");
  98. }
  99. handler.next(e);
  100. }))
  101. ..interceptors.add(DioCacheInterceptor(options: CacheOptions(store: MemCacheStore())))
  102. ..interceptors.add(LogInterceptor(request: config.debug, responseBody: config.debug, responseHeader: config.debug, requestBody: config.debug, requestHeader: config.debug))
  103. ..httpClientAdapter = (DefaultHttpClientAdapter()
  104. ..onHttpClientCreate = (client) {
  105. // client.findProxy = (uri) {
  106. // return 'PROXY 172.16.14.128:8080';
  107. // };
  108. client.badCertificateCallback = (X509Certificate cert, String host, int port) {
  109. return true;
  110. };
  111. return client;
  112. }),
  113. signalsReady: true);
  114. getIt.registerSingleton<RestClient>(RestClient(getIt<Dio>(), baseUrl: config.baseUrl), signalsReady: true);
  115. getIt.registerSingleton<LoginApi>(LoginApi(getIt<Dio>()), signalsReady: true);
  116. getIt.registerSingleton<Bluetooth>(Bluetooth());
  117. getIt.registerSingleton<GameModel>(GameModel());
  118. getIt.registerSingleton<MessageModel>(MessageModel());
  119. getIt.registerSingleton<LoginInfoModel>(LoginInfoModel());
  120. getIt.registerFactory(() => GameInfoModel());
  121. }
  122. }