api_controller.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:device_info_plus/device_info_plus.dart';
  4. import 'package:dio/dio.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:get/get.dart';
  7. import 'package:nomo/app/api/router/api_router.dart';
  8. import 'package:nomo/app/data/sp/ix_sp.dart';
  9. import 'package:package_info_plus/package_info_plus.dart';
  10. import 'package:play_install_referrer/play_install_referrer.dart';
  11. import '../../config/translations/localization_service.dart';
  12. import '../../config/translations/strings_enum.dart';
  13. import '../../pigeons/core_api.g.dart';
  14. import '../../utils/device_manager.dart';
  15. import '../../utils/geo_downloader.dart';
  16. import '../../utils/log/logger.dart';
  17. import '../../utils/network_helper.dart';
  18. import '../../utils/system_helper.dart';
  19. import '../api/core/api_core.dart';
  20. import '../components/country_restricted_overlay.dart';
  21. import '../components/ix_snackbar.dart';
  22. import '../constants/api_domains.dart';
  23. import '../constants/configs.dart';
  24. import '../constants/enums.dart';
  25. import '../constants/errors.dart';
  26. import '../constants/platforms.dart';
  27. import '../data/models/api_exception.dart';
  28. import '../data/models/failure.dart';
  29. import '../data/models/fingerprint.dart';
  30. import '../data/models/launch/groups.dart';
  31. import '../data/models/launch/launch.dart';
  32. import '../dialog/update_dailog.dart';
  33. class ApiController extends GetxService {
  34. final TAG = 'ApiController';
  35. // 记录是否已经显示禁用弹窗
  36. bool isShowDisabled = false;
  37. //是否是游客
  38. final _isGuest = false.obs;
  39. bool get isGuest => _isGuest.value;
  40. set isGuest(bool value) => _isGuest.value = value;
  41. //全部节点列表
  42. final _nodesList = <LocationList>[].obs;
  43. List<LocationList> get nodesList => _nodesList.value;
  44. set nodesList(List<LocationList> value) => _nodesList.value = value;
  45. //初始化fingerprint
  46. Fingerprint fp = Fingerprint.empty();
  47. Future<Fingerprint> initFingerprint() async {
  48. // 读取app发布渠道
  49. if (Platform.isIOS) {
  50. fp.channel = 'apple';
  51. } else if (Platform.isAndroid) {
  52. try {
  53. final channel = await CoreApi().getChannel();
  54. fp.channel = channel ?? 'unknown';
  55. } catch (e) {
  56. log(TAG, 'read app channel error: $e');
  57. fp.channel = 'unknown';
  58. }
  59. }
  60. try {
  61. final advertisingId = await CoreApi().getAdvertisingId();
  62. fp.googleId = advertisingId ?? '';
  63. } catch (e) {
  64. log(TAG, 'read app googleId error: $e');
  65. fp.googleId = '';
  66. }
  67. // 读取应用信息
  68. final info = await PackageInfo.fromPlatform();
  69. fp.appVersionCode = int.tryParse(info.buildNumber) ?? 0;
  70. fp.appVersionName = info.version;
  71. // 读取设备信息
  72. final deviceInfo = DeviceInfoPlugin();
  73. if (Platform.isIOS) {
  74. fp.platform = Platforms.iOS;
  75. final iosOsInfo = await deviceInfo.iosInfo;
  76. fp.deviceModel = iosOsInfo.model;
  77. fp.deviceOs = iosOsInfo.systemVersion;
  78. fp.deviceBrand = iosOsInfo.utsname.machine;
  79. } else if (Platform.isAndroid) {
  80. fp.platform = Platforms.android;
  81. final androidOsInfo = await deviceInfo.androidInfo;
  82. fp.deviceModel = androidOsInfo.model;
  83. fp.deviceOs = androidOsInfo.version.release;
  84. fp.deviceBrand = androidOsInfo.brand;
  85. fp.androidId = androidOsInfo.id;
  86. }
  87. //获取设备尺寸
  88. fp.deviceHeight = Get.height.toInt();
  89. fp.deviceWidth = Get.width.toInt();
  90. // 读取设备ID
  91. fp.deviceId = DeviceManager.getCacheDeviceId();
  92. try {
  93. ReferrerDetails referrerDetails =
  94. await PlayInstallReferrer.installReferrer;
  95. fp.refer = referrerDetails.installReferrer ?? '';
  96. } catch (e) {
  97. log(TAG, 'get install referrer error: $e');
  98. }
  99. fp.isNewInstall = IXSP.getIsNewInstall();
  100. await updateFingerprintData();
  101. return fp;
  102. }
  103. // 更新部分数据
  104. Future<void> updateFingerprintData() async {
  105. fp.lang = IXSP.getCurrentLocal().languageCode;
  106. fp.phoneCountryIso = LocalizationService.getSystemCountry();
  107. fp.isVpn = await CoreApi().isConnected() ?? false;
  108. if (!fp.isVpn) {
  109. fp.isConnectedVpn = false;
  110. }
  111. try {
  112. final simInfo = await CoreApi().getSimInfo();
  113. // 解析sim
  114. final sim = jsonDecode(simInfo ?? '{}');
  115. fp.simReady = sim['simReady'];
  116. fp.carrierName = sim['carrierName'];
  117. fp.mcc = sim['mcc'];
  118. fp.mnc = sim['mnc'];
  119. fp.countryIso = sim['countryIso'];
  120. fp.networkCarrierName = sim['networkCarrierName'];
  121. fp.networkMcc = sim['networkMcc'];
  122. fp.networkMnc = sim['networkMnc'];
  123. fp.networkCountryIso = sim['networkCountryIso'];
  124. } catch (e) {
  125. log(TAG, 'read app sim error: $e');
  126. }
  127. }
  128. Future<void> initData(Launch? launch) async {
  129. // 初始化是否第一次安装
  130. IXSP.setIsNewInstall(false);
  131. fp.userUuid = '';
  132. fp.isNewInstall = false;
  133. await initLaunch(launch);
  134. }
  135. Future<void> initLaunch(Launch? launch) async {
  136. try {
  137. if (launch != null) {
  138. // 初始化用户状态
  139. isGuest = launch.userConfig?.memberLevel == MemberLevel.guest.level;
  140. // 设置路由和节点
  141. nodesList = launch.groups?.normal?.list ?? [];
  142. // 设置资源url
  143. if (launch.appConfig?.assetUrls != null &&
  144. launch.appConfig!.assetUrls!.isNotEmpty) {
  145. Configs.assetUrl = launch.appConfig!.assetUrls![0];
  146. }
  147. // 设置官网url
  148. if (launch.appConfig?.websiteUrl != null &&
  149. launch.appConfig!.websiteUrl!.isNotEmpty) {
  150. Configs.websiteUrl = launch.appConfig!.websiteUrl!;
  151. }
  152. }
  153. } catch (e) {
  154. log(TAG, 'initLaunch error: $e');
  155. }
  156. }
  157. // 发送分析事件, 后续可以发送到firebase
  158. Future<void> sendAnalytics(FirebaseEvent event) async {
  159. try {} catch (e) {
  160. log('sendAnalytics error: $e');
  161. }
  162. }
  163. Future<Launch> launch({bool isCache = false}) async {
  164. sendAnalytics(isCache ? FirebaseEvent.launchCache : FirebaseEvent.launch);
  165. while (true) {
  166. try {
  167. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  168. final request = fp.toJson();
  169. if (IXSP.getDisconnectDomains().isNotEmpty) {
  170. final disconnectDomainList = IXSP
  171. .getDisconnectDomains()
  172. .map((e) => e.toJson())
  173. .toList();
  174. request['disconnectDomainList'] = disconnectDomainList;
  175. }
  176. final result = await ApiCore().launch(request);
  177. if (!result.success) {
  178. throw Failure(
  179. code: result.errorCode ?? '',
  180. message: result.errorMessage ?? '',
  181. );
  182. }
  183. sendAnalytics(
  184. isCache
  185. ? FirebaseEvent.launchCacheSuccess
  186. : FirebaseEvent.launchSuccess,
  187. );
  188. if (IXSP.getDisconnectDomains().isNotEmpty) {
  189. IXSP.clearDisconnectDomains();
  190. }
  191. // 重置禁用状态
  192. IXSP.setLastIsRegionDisabled(false);
  193. IXSP.setLastIsUserDisabled(false);
  194. final launchData = Launch.fromJson(result.data);
  195. // 设置扩展数据
  196. fp.exData = launchData.exData;
  197. // 更新URL列表
  198. await ApiDomains.instance.updateFromLaunch(launchData);
  199. // 保存Launch数据
  200. await IXSP.saveLaunch(launchData);
  201. // 初始化Launch
  202. await initData(launchData);
  203. return launchData;
  204. } on ApiException catch (e) {
  205. final url = await ApiDomains.instance.getNextApiUrl();
  206. log(TAG, 'Launch request failed for URL $url: $e');
  207. if (url.isEmpty) {
  208. rethrow;
  209. }
  210. ApiCore().setbaseUrl(url);
  211. } on Failure catch (_) {
  212. rethrow;
  213. } on DioException catch (e) {
  214. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  215. e.response?.statusCode == Errors.eUserDisabled ||
  216. e.response?.statusCode == Errors.eTokenExpired) {
  217. rethrow;
  218. } else {
  219. if (await NetworkHelper.instance.isNetworkAvailable()) {
  220. final url = await ApiDomains.instance.getNextApiUrl();
  221. log(TAG, 'Launch request failed for URL $url: $e');
  222. if (url.isEmpty) {
  223. rethrow;
  224. }
  225. ApiCore().setbaseUrl(url);
  226. } else {
  227. rethrow;
  228. }
  229. }
  230. } catch (e) {
  231. final url = await ApiDomains.instance.getNextApiUrl();
  232. log(TAG, 'Launch request failed for URL $url: $e');
  233. if (url.isEmpty) {
  234. rethrow;
  235. }
  236. ApiCore().setbaseUrl(url);
  237. }
  238. }
  239. }
  240. Future<void> asyncHandleLaunch() async {
  241. try {
  242. final data = await launch(isCache: true);
  243. final isVpnRunning = await CoreApi().isConnected() ?? false;
  244. if (!isVpnRunning) {
  245. await checkUpdate();
  246. // 下载smartgeo文件
  247. GeoDownloader().downloadSmartGeo(smartGeo: data.appConfig!.smartGeo!);
  248. }
  249. } catch (e, s) {
  250. if (IXSP.getLastIsUserDisabled()) {
  251. if (!isShowDisabled) {
  252. Get.offAll(
  253. () => CountryRestrictedOverlay(
  254. type: RestrictedType.user,
  255. onPressed: () async {
  256. // 清除LaunchData
  257. await IXSP.clearLaunchData();
  258. // 清除禁用状态
  259. IXSP.setLastIsUserDisabled(false);
  260. // 发送事件
  261. },
  262. ),
  263. transition: Transition.fadeIn,
  264. );
  265. }
  266. return;
  267. } else if (IXSP.getLastIsRegionDisabled()) {
  268. if (!isShowDisabled) {
  269. Get.offAll(
  270. () => const CountryRestrictedOverlay(type: RestrictedType.region),
  271. transition: Transition.fadeIn,
  272. );
  273. }
  274. return;
  275. } else if (IXSP.getLastIsDeviceDisabled()) {
  276. if (!isShowDisabled) {
  277. Get.offAll(
  278. () => const CountryRestrictedOverlay(type: RestrictedType.device),
  279. transition: Transition.fadeIn,
  280. );
  281. }
  282. return;
  283. }
  284. final isVpnRunning = await CoreApi().isConnected() ?? false;
  285. if (!isVpnRunning) {
  286. await checkUpdate();
  287. }
  288. handleSnackBarError(e, s);
  289. }
  290. }
  291. void handleSnackBarError(dynamic error, StackTrace stackTrace) {
  292. if (error is ApiException) {
  293. IXSnackBar.showIXErrorSnackBar(
  294. title: Strings.error.tr,
  295. message: error.message,
  296. );
  297. } else if (error is Failure) {
  298. IXSnackBar.showIXErrorSnackBar(
  299. title: Strings.error.tr,
  300. message: error.message ?? Strings.unknownError.tr,
  301. );
  302. } else if (error is DioException) {
  303. switch (error.type) {
  304. case DioExceptionType.connectionError:
  305. case DioExceptionType.connectionTimeout:
  306. case DioExceptionType.receiveTimeout:
  307. case DioExceptionType.sendTimeout:
  308. IXSnackBar.showIXErrorSnackBar(
  309. title: Strings.error.tr,
  310. message: Strings.unableToConnectNetwork.tr,
  311. );
  312. break;
  313. default:
  314. IXSnackBar.showIXErrorSnackBar(
  315. title: Strings.error.tr,
  316. message: Strings.unableToConnectServer.tr,
  317. );
  318. }
  319. } else {
  320. IXSnackBar.showIXErrorSnackBar(
  321. title: Strings.error.tr,
  322. message: Strings.unknownError.tr,
  323. );
  324. }
  325. }
  326. // 更新检查 - 智能时间控制版本
  327. Future<bool> checkUpdate({bool isClickCheck = false}) async {
  328. try {
  329. final upgrade = IXSP.getUpgrade();
  330. var hasUpdate = false;
  331. var hasForceUpdate = false;
  332. if (upgrade != null) {
  333. if (upgrade.upgradeType == 1) {
  334. hasUpdate = true;
  335. }
  336. if (upgrade.forced == true) {
  337. hasForceUpdate = true;
  338. }
  339. }
  340. if (hasUpdate) {
  341. Get.dialog(
  342. WillPopScope(
  343. onWillPop: () async => false,
  344. child: UpdateDialog(
  345. upgrade: upgrade,
  346. onUpdate: () =>
  347. SystemHelper.openGooglePlayUrl(upgrade?.appStoreUrl ?? ''),
  348. onLater: hasForceUpdate
  349. ? null
  350. : () {
  351. Navigator.of(Get.context!).pop();
  352. },
  353. ),
  354. ),
  355. barrierDismissible: false,
  356. ).then((_) {
  357. log('UpdateDialog closed');
  358. });
  359. }
  360. return hasUpdate;
  361. } catch (e) {
  362. log(TAG, 'checkUpdate error: $e');
  363. }
  364. return false;
  365. }
  366. Future<Launch> getDispatchInfo(
  367. int locationId,
  368. String locationCode, {
  369. CancelToken? cancelToken,
  370. }) async {
  371. while (true) {
  372. try {
  373. ApiRouter().setbaseUrl(ApiDomains.instance.getRouterUrl());
  374. final request = fp.toJson();
  375. if (IXSP.getDisconnectDomains().isNotEmpty) {
  376. final disconnectDomainList = IXSP
  377. .getDisconnectDomains()
  378. .map((e) => e.toJson())
  379. .toList();
  380. request['disconnectDomainList'] = disconnectDomainList;
  381. }
  382. request['locationId'] = locationId;
  383. request['locationCode'] = locationCode;
  384. final result = await ApiRouter().getDispatchInfo(
  385. request,
  386. cancelToken: cancelToken,
  387. );
  388. if (!result.success) {
  389. throw Failure(
  390. code: result.errorCode ?? '',
  391. message: result.errorMessage ?? '',
  392. );
  393. }
  394. if (IXSP.getDisconnectDomains().isNotEmpty) {
  395. IXSP.clearDisconnectDomains();
  396. }
  397. // 重置禁用状态
  398. IXSP.setLastIsRegionDisabled(false);
  399. IXSP.setLastIsUserDisabled(false);
  400. final launchData = Launch.fromJson(result.data);
  401. // 更新URL列表
  402. await ApiDomains.instance.updateFromLaunch(launchData);
  403. // 保存app配置
  404. await IXSP.saveAppConfig(launchData.appConfig!);
  405. // 保存vpn配置
  406. // await IXSP.saveVpnConfig(launchData.vpnConfig!);
  407. return launchData;
  408. } on ApiException catch (_) {
  409. rethrow;
  410. } on Failure catch (_) {
  411. rethrow;
  412. } on DioException catch (e) {
  413. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  414. e.response?.statusCode == Errors.eUserDisabled ||
  415. e.response?.statusCode == Errors.eTokenExpired) {
  416. rethrow;
  417. } else {
  418. if (await NetworkHelper.instance.isNetworkAvailable()) {
  419. final url = await ApiDomains.instance.getNextRouterUrl();
  420. log(TAG, 'Launch request failed for URL $url: $e');
  421. if (url.isEmpty) {
  422. rethrow;
  423. }
  424. ApiRouter().setbaseUrl(url);
  425. } else {
  426. rethrow;
  427. }
  428. }
  429. } catch (e) {
  430. final url = await ApiDomains.instance.getNextRouterUrl();
  431. log(TAG, 'Launch request failed for URL $url: $e');
  432. if (url.isEmpty) {
  433. rethrow;
  434. }
  435. ApiRouter().setbaseUrl(url);
  436. }
  437. }
  438. }
  439. }