api_controller.dart 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:device_info_plus/device_info_plus.dart';
  5. import 'package:dio/dio.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:get/get.dart';
  8. import 'package:nomo/app/api/router/api_router.dart';
  9. import 'package:nomo/app/data/sp/ix_sp.dart';
  10. import 'package:package_info_plus/package_info_plus.dart';
  11. import 'package:path_provider/path_provider.dart';
  12. import 'package:play_install_referrer/play_install_referrer.dart';
  13. import '../../config/translations/localization_service.dart';
  14. import '../../config/translations/strings_enum.dart';
  15. import '../../pigeons/core_api.g.dart';
  16. import '../../utils/api_statistics.dart';
  17. import '../../utils/device_manager.dart';
  18. import '../../utils/geo_downloader.dart';
  19. import '../../utils/log/logger.dart';
  20. import '../../utils/network_helper.dart';
  21. import '../../utils/ntp_time_service.dart';
  22. import '../api/core/api_core.dart';
  23. import '../api/log/api_log.dart';
  24. import '../components/country_restricted_overlay.dart';
  25. import '../components/ix_snackbar.dart';
  26. import '../constants/api_domains.dart';
  27. import '../constants/configs.dart';
  28. import '../constants/enums.dart';
  29. import '../constants/errors.dart';
  30. import '../constants/platforms.dart';
  31. import '../data/models/api_exception.dart';
  32. import '../data/models/channelplan/channel_plan_list.dart';
  33. import '../data/models/failure.dart';
  34. import '../data/models/fingerprint.dart';
  35. import '../data/models/launch/groups.dart';
  36. import '../data/models/launch/launch.dart';
  37. import '../dialog/all_dialog.dart';
  38. class ApiController extends GetxService with WidgetsBindingObserver {
  39. final TAG = 'ApiController';
  40. // 记录是否已经显示禁用弹窗
  41. bool isShowDisabled = false;
  42. //是否是游客
  43. final _isGuest = false.obs;
  44. bool get isGuest => _isGuest.value;
  45. set isGuest(bool value) => _isGuest.value = value;
  46. //是否是会员
  47. final _isPremium = false.obs;
  48. bool get isPremium => _isPremium.value;
  49. set isPremium(bool value) => _isPremium.value = value;
  50. //用户等级
  51. final _userLevel = 1.obs;
  52. int get userLevel => _userLevel.value;
  53. set userLevel(int value) => _userLevel.value = value;
  54. // 过期时间文本
  55. final _expireTimeText = ''.obs;
  56. String get expireTimeText => _expireTimeText.value;
  57. set expireTimeText(String value) => _expireTimeText.value = value;
  58. // 有效期文本
  59. final _validTermText = ''.obs;
  60. String get validTermText => _validTermText.value;
  61. set validTermText(String value) => _validTermText.value = value;
  62. //全部节点列表
  63. final _nodesList = <LocationList>[].obs;
  64. List<LocationList> get nodesList => _nodesList.value;
  65. set nodesList(List<LocationList> value) => _nodesList.value = value;
  66. //初始化fingerprint
  67. Fingerprint fp = Fingerprint.empty();
  68. // 全局剩余时间倒计时(秒)
  69. final _remainTimeSeconds = 0.obs;
  70. int get remainTimeSeconds => _remainTimeSeconds.value;
  71. set remainTimeSeconds(int value) => _remainTimeSeconds.value = value;
  72. // 格式化后的剩余时间字符串
  73. String get remainTimeFormatted => _formatRemainTime(_remainTimeSeconds.value);
  74. // 倒计时定时器
  75. Timer? _remainTimeTimer;
  76. // 是否在后台
  77. bool isBackground = false;
  78. @override
  79. void onInit() {
  80. super.onInit();
  81. WidgetsBinding.instance.addObserver(this);
  82. }
  83. @override
  84. void onClose() {
  85. WidgetsBinding.instance.removeObserver(this);
  86. super.onClose();
  87. }
  88. @override
  89. void didChangeAppLifecycleState(AppLifecycleState state) {
  90. log("App state: $state");
  91. if (state == AppLifecycleState.paused) {
  92. isBackground = true;
  93. ApiStatistics.instance.onAppPaused();
  94. } else if (state == AppLifecycleState.resumed) {
  95. if (isBackground) {
  96. isBackground = false;
  97. asyncHandleLaunch(isRefreshLaunch: true);
  98. ApiStatistics.instance.onAppResumed();
  99. }
  100. }
  101. }
  102. Future<Fingerprint> initFingerprint() async {
  103. // 读取app发布渠道
  104. if (Platform.isIOS) {
  105. fp.channel = 'apple';
  106. } else if (Platform.isAndroid) {
  107. try {
  108. final channel = await CoreApi().getChannel();
  109. fp.channel = channel ?? 'unknown';
  110. } catch (e) {
  111. log(TAG, 'read app channel error: $e');
  112. fp.channel = '';
  113. }
  114. try {
  115. final advertisingId = await CoreApi().getAdvertisingId();
  116. fp.googleId = advertisingId ?? '';
  117. } catch (e) {
  118. log(TAG, 'read app googleId error: $e');
  119. fp.googleId = '';
  120. }
  121. try {
  122. ReferrerDetails referrerDetails =
  123. await PlayInstallReferrer.installReferrer;
  124. fp.refer = referrerDetails.installReferrer ?? '';
  125. } catch (e) {
  126. log(TAG, 'get install referrer error: $e');
  127. fp.refer = '';
  128. }
  129. }
  130. // 读取应用信息
  131. final info = await PackageInfo.fromPlatform();
  132. fp.appVersionCode = int.tryParse(info.buildNumber) ?? 0;
  133. fp.appVersionName = info.version;
  134. // 读取设备信息
  135. final deviceInfo = DeviceInfoPlugin();
  136. if (Platform.isIOS) {
  137. fp.platform = Platforms.iOS;
  138. final iosOsInfo = await deviceInfo.iosInfo;
  139. fp.deviceModel = iosOsInfo.model;
  140. fp.deviceOs = iosOsInfo.systemVersion;
  141. fp.deviceBrand = iosOsInfo.utsname.machine;
  142. } else if (Platform.isAndroid) {
  143. fp.platform = Platforms.android;
  144. final androidOsInfo = await deviceInfo.androidInfo;
  145. fp.deviceModel = androidOsInfo.model;
  146. fp.deviceOs = androidOsInfo.version.release;
  147. fp.deviceBrand = androidOsInfo.brand;
  148. fp.androidId = androidOsInfo.id;
  149. }
  150. //获取设备尺寸
  151. fp.deviceHeight = Get.height.toInt();
  152. fp.deviceWidth = Get.width.toInt();
  153. // 读取设备ID
  154. fp.deviceId = DeviceManager.getCacheDeviceId();
  155. fp.isNewInstall = IXSP.getIsNewInstall();
  156. await updateFingerprintData();
  157. return fp;
  158. }
  159. // 更新部分数据
  160. Future<void> updateFingerprintData() async {
  161. fp.lang = IXSP.getCurrentLocal().languageCode;
  162. fp.phoneCountryIso = LocalizationService.getSystemCountry();
  163. fp.isVpn = await CoreApi().isConnected() ?? false;
  164. if (!fp.isVpn) {
  165. fp.isConnectedVpn = false;
  166. }
  167. try {
  168. final simInfo = await CoreApi().getSimInfo();
  169. // 解析sim
  170. final sim = jsonDecode(simInfo ?? '{}');
  171. fp.simReady = sim['simReady'];
  172. fp.carrierName = sim['carrierName'];
  173. fp.mcc = sim['mcc'];
  174. fp.mnc = sim['mnc'];
  175. fp.countryIso = sim['countryIso'];
  176. fp.networkCarrierName = sim['networkCarrierName'];
  177. fp.networkMcc = sim['networkMcc'];
  178. fp.networkMnc = sim['networkMnc'];
  179. fp.networkCountryIso = sim['networkCountryIso'];
  180. } catch (e) {
  181. log(TAG, 'read app sim error: $e');
  182. }
  183. }
  184. Future<void> initData(Launch? launch) async {
  185. // 初始化是否第一次安装
  186. IXSP.setIsNewInstall(false);
  187. fp.userUuid = '';
  188. fp.isNewInstall = false;
  189. await initLaunch(launch);
  190. }
  191. Future<void> initLaunch(Launch? launch) async {
  192. try {
  193. if (launch != null) {
  194. // 初始化用户状态
  195. isGuest = launch.userConfig?.memberLevel == MemberLevel.guest.level;
  196. userLevel = launch.userConfig?.userLevel ?? 1;
  197. isPremium = userLevel == 3 || userLevel == 9999;
  198. expireTimeText = _getExpireTimeText();
  199. validTermText = _getValidTermText();
  200. updateRemainTime(launch.userConfig?.remainTime ?? 0);
  201. NtpTimeService().initLaunchInitialTime();
  202. // 设置路由和节点
  203. nodesList = launch.groups?.normal?.list ?? [];
  204. // 设置资源url
  205. if (launch.appConfig?.assetUrls != null &&
  206. launch.appConfig!.assetUrls!.isNotEmpty) {
  207. Configs.assetUrl = launch.appConfig!.assetUrls![0];
  208. }
  209. // 设置官网url
  210. if (launch.appConfig?.websiteUrl != null &&
  211. launch.appConfig!.websiteUrl!.isNotEmpty) {
  212. Configs.websiteUrl = launch.appConfig!.websiteUrl!;
  213. }
  214. }
  215. } catch (e) {
  216. log(TAG, 'initLaunch error: $e');
  217. }
  218. }
  219. // 发送分析事件, 后续可以发送到firebase
  220. Future<void> sendAnalytics(FirebaseEvent event) async {
  221. try {} catch (e) {
  222. log('sendAnalytics error: $e');
  223. }
  224. }
  225. Future<Launch> launch({bool isCache = false}) async {
  226. sendAnalytics(isCache ? FirebaseEvent.launchCache : FirebaseEvent.launch);
  227. while (true) {
  228. try {
  229. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  230. final request = fp.toJson();
  231. final result = await ApiCore().launch(request);
  232. if (!result.success) {
  233. throw Failure(
  234. code: result.errorCode ?? '',
  235. message: result.errorMessage ?? '',
  236. );
  237. }
  238. sendAnalytics(
  239. isCache
  240. ? FirebaseEvent.launchCacheSuccess
  241. : FirebaseEvent.launchSuccess,
  242. );
  243. // 重置禁用状态
  244. IXSP.setLastIsRegionDisabled(false);
  245. IXSP.setLastIsUserDisabled(false);
  246. final launchData = Launch.fromJson(result.data);
  247. // 设置扩展数据
  248. fp.exData = launchData.exData;
  249. // 更新URL列表
  250. await ApiDomains.instance.updateFromLaunch(launchData);
  251. // 保存Launch数据
  252. await IXSP.saveLaunch(launchData);
  253. // 初始化Launch
  254. await initData(launchData);
  255. return launchData;
  256. } on ApiException catch (e) {
  257. final url = await ApiDomains.instance.getNextApiUrl();
  258. log(TAG, 'Launch request failed for URL $url: $e');
  259. if (url.isEmpty) {
  260. rethrow;
  261. }
  262. ApiCore().setbaseUrl(url);
  263. } on Failure catch (_) {
  264. rethrow;
  265. } on DioException catch (e) {
  266. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  267. e.response?.statusCode == Errors.eUserDisabled ||
  268. e.response?.statusCode == Errors.eTokenExpired) {
  269. rethrow;
  270. } else {
  271. if (await NetworkHelper.instance.isNetworkAvailable()) {
  272. final url = await ApiDomains.instance.getNextApiUrl();
  273. log(TAG, 'Launch request failed for URL $url: $e');
  274. if (url.isEmpty) {
  275. rethrow;
  276. }
  277. ApiCore().setbaseUrl(url);
  278. } else {
  279. rethrow;
  280. }
  281. }
  282. } catch (e) {
  283. final url = await ApiDomains.instance.getNextApiUrl();
  284. log(TAG, 'Launch request failed for URL $url: $e');
  285. if (url.isEmpty) {
  286. rethrow;
  287. }
  288. ApiCore().setbaseUrl(url);
  289. }
  290. }
  291. }
  292. Future<Launch> refreshLaunch() async {
  293. while (true) {
  294. try {
  295. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  296. final request = fp.toJson();
  297. final result = await ApiCore().refreshLaunch(request);
  298. if (!result.success) {
  299. throw Failure(
  300. code: result.errorCode ?? '',
  301. message: result.errorMessage ?? '',
  302. );
  303. }
  304. // 重置禁用状态
  305. IXSP.setLastIsRegionDisabled(false);
  306. IXSP.setLastIsUserDisabled(false);
  307. final launchData = Launch.fromJson(result.data);
  308. // 设置扩展数据
  309. fp.exData = launchData.exData;
  310. // 更新URL列表
  311. await ApiDomains.instance.updateFromLaunch(launchData);
  312. // 保存Launch数据
  313. await IXSP.saveLaunch(launchData);
  314. // 初始化Launch
  315. await initData(launchData);
  316. return launchData;
  317. } on ApiException catch (e) {
  318. final url = await ApiDomains.instance.getNextApiUrl();
  319. log(TAG, 'refresh launch request failed for URL $url: $e');
  320. if (url.isEmpty) {
  321. rethrow;
  322. }
  323. ApiCore().setbaseUrl(url);
  324. } on Failure catch (_) {
  325. rethrow;
  326. } on DioException catch (e) {
  327. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  328. e.response?.statusCode == Errors.eUserDisabled ||
  329. e.response?.statusCode == Errors.eTokenExpired) {
  330. rethrow;
  331. } else {
  332. if (await NetworkHelper.instance.isNetworkAvailable()) {
  333. final url = await ApiDomains.instance.getNextApiUrl();
  334. log(TAG, 'refresh launch request failed for URL $url: $e');
  335. if (url.isEmpty) {
  336. rethrow;
  337. }
  338. ApiCore().setbaseUrl(url);
  339. } else {
  340. rethrow;
  341. }
  342. }
  343. } catch (e) {
  344. final url = await ApiDomains.instance.getNextApiUrl();
  345. log(TAG, 'refresh launch request failed for URL $url: $e');
  346. if (url.isEmpty) {
  347. rethrow;
  348. }
  349. ApiCore().setbaseUrl(url);
  350. }
  351. }
  352. }
  353. Future<void> asyncHandleLaunch({bool isRefreshLaunch = false}) async {
  354. try {
  355. final data = isRefreshLaunch
  356. ? await refreshLaunch()
  357. : await launch(isCache: true);
  358. final isVpnRunning = await CoreApi().isConnected() ?? false;
  359. if (!isVpnRunning) {
  360. await checkUpdate();
  361. // 下载smartgeo文件
  362. GeoDownloader().downloadSmartGeo(smartGeo: data.appConfig!.smartGeo!);
  363. }
  364. } catch (e, s) {
  365. if (IXSP.getLastIsUserDisabled()) {
  366. if (!isShowDisabled) {
  367. Get.offAll(
  368. () => CountryRestrictedOverlay(
  369. type: RestrictedType.user,
  370. onPressed: () async {
  371. // 清除LaunchData
  372. await IXSP.clearLaunchData();
  373. // 清除禁用状态
  374. IXSP.setLastIsUserDisabled(false);
  375. // 发送事件
  376. },
  377. ),
  378. transition: Transition.fadeIn,
  379. );
  380. }
  381. return;
  382. } else if (IXSP.getLastIsRegionDisabled()) {
  383. if (!isShowDisabled) {
  384. Get.offAll(
  385. () => const CountryRestrictedOverlay(type: RestrictedType.region),
  386. transition: Transition.fadeIn,
  387. );
  388. }
  389. return;
  390. } else if (IXSP.getLastIsDeviceDisabled()) {
  391. if (!isShowDisabled) {
  392. Get.offAll(
  393. () => const CountryRestrictedOverlay(type: RestrictedType.device),
  394. transition: Transition.fadeIn,
  395. );
  396. }
  397. return;
  398. }
  399. final isVpnRunning = await CoreApi().isConnected() ?? false;
  400. if (!isVpnRunning) {
  401. await checkUpdate();
  402. }
  403. handleSnackBarError(e, s);
  404. }
  405. }
  406. void handleSnackBarError(dynamic error, StackTrace stackTrace) {
  407. if (error is ApiException) {
  408. IXSnackBar.showIXErrorSnackBar(
  409. title: Strings.error.tr,
  410. message: error.message,
  411. );
  412. } else if (error is Failure) {
  413. IXSnackBar.showIXErrorSnackBar(
  414. title: Strings.error.tr,
  415. message: error.message ?? Strings.unknownError.tr,
  416. );
  417. } else if (error is DioException) {
  418. switch (error.type) {
  419. case DioExceptionType.connectionError:
  420. case DioExceptionType.connectionTimeout:
  421. case DioExceptionType.receiveTimeout:
  422. case DioExceptionType.sendTimeout:
  423. IXSnackBar.showIXErrorSnackBar(
  424. title: Strings.error.tr,
  425. message: Strings.unableToConnectNetwork.tr,
  426. );
  427. break;
  428. default:
  429. IXSnackBar.showIXErrorSnackBar(
  430. title: Strings.error.tr,
  431. message: Strings.unableToConnectServer.tr,
  432. );
  433. }
  434. } else {
  435. IXSnackBar.showIXErrorSnackBar(
  436. title: Strings.error.tr,
  437. message: error.toString(),
  438. );
  439. }
  440. }
  441. // 更新检查 - 智能时间控制版本
  442. Future<bool> checkUpdate({bool isClickCheck = false}) async {
  443. try {
  444. final upgrade = IXSP.getUpgrade();
  445. var hasUpdate = false;
  446. var hasForceUpdate = false;
  447. if (upgrade != null) {
  448. if (upgrade.upgradeType == 1) {
  449. hasUpdate = true;
  450. }
  451. if (upgrade.forced == true) {
  452. hasForceUpdate = true;
  453. }
  454. }
  455. if (hasUpdate) {
  456. AllDialog.showUpdate(hasForceUpdate: hasForceUpdate);
  457. }
  458. return hasUpdate;
  459. } catch (e) {
  460. log(TAG, 'checkUpdate error: $e');
  461. }
  462. return false;
  463. }
  464. Future<Launch> getDispatchInfo(
  465. int locationId,
  466. String locationCode, {
  467. CancelToken? cancelToken,
  468. }) async {
  469. while (true) {
  470. try {
  471. ApiRouter().setbaseUrl(ApiDomains.instance.getRouterUrl());
  472. final request = fp.toJson();
  473. request['locationId'] = locationId;
  474. request['locationCode'] = locationCode;
  475. // 获取选中的路由模式
  476. final routingMode = IXSP.getString("routing_mode_selected") ?? "smart";
  477. request['routingMode'] = routingMode;
  478. final result = await ApiRouter().getDispatchInfo(
  479. request,
  480. cancelToken: cancelToken,
  481. );
  482. if (!result.success) {
  483. throw Failure(
  484. code: result.errorCode ?? '',
  485. message: result.errorMessage ?? '',
  486. );
  487. }
  488. // 重置禁用状态
  489. IXSP.setLastIsRegionDisabled(false);
  490. IXSP.setLastIsUserDisabled(false);
  491. final launchData = Launch.fromJson(result.data);
  492. // 更新URL列表
  493. await ApiDomains.instance.updateFromLaunch(launchData);
  494. // 保存app配置
  495. await IXSP.saveAppConfig(launchData.appConfig!);
  496. return launchData;
  497. } on ApiException catch (_) {
  498. rethrow;
  499. } on Failure catch (_) {
  500. rethrow;
  501. } on DioException catch (e) {
  502. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  503. e.response?.statusCode == Errors.eUserDisabled ||
  504. e.response?.statusCode == Errors.eTokenExpired) {
  505. rethrow;
  506. } else {
  507. if (await NetworkHelper.instance.isNetworkAvailable()) {
  508. final url = await ApiDomains.instance.getNextRouterUrl();
  509. log(TAG, 'getDispatchInfo request failed for URL $url: $e');
  510. if (url.isEmpty) {
  511. rethrow;
  512. }
  513. ApiRouter().setbaseUrl(url);
  514. } else {
  515. rethrow;
  516. }
  517. }
  518. } catch (e) {
  519. final url = await ApiDomains.instance.getNextRouterUrl();
  520. log(TAG, 'getDispatchInfo request failed for URL $url: $e');
  521. if (url.isEmpty) {
  522. rethrow;
  523. }
  524. ApiRouter().setbaseUrl(url);
  525. }
  526. }
  527. }
  528. Future<Launch> register(Map<String, dynamic> params) async {
  529. while (true) {
  530. try {
  531. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  532. final request = fp.toJson();
  533. request.addAll(params);
  534. final result = await ApiCore().register(request);
  535. if (!result.success) {
  536. throw Failure(
  537. code: result.errorCode ?? '',
  538. message: result.errorMessage ?? '',
  539. );
  540. }
  541. final launchData = Launch.fromJson(result.data);
  542. // 注册成功后上报firebase注册事件
  543. sendAnalytics(FirebaseEvent.register);
  544. // 保存 Launch 数据
  545. await IXSP.saveLaunch(launchData);
  546. // 初始化Launch
  547. await initData(launchData);
  548. return launchData;
  549. } on ApiException catch (_) {
  550. rethrow;
  551. } on Failure catch (_) {
  552. rethrow;
  553. } on DioException catch (e) {
  554. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  555. e.response?.statusCode == Errors.eUserDisabled ||
  556. e.response?.statusCode == Errors.eTokenExpired) {
  557. rethrow;
  558. } else {
  559. if (await NetworkHelper.instance.isNetworkAvailable()) {
  560. final url = await ApiDomains.instance.getNextApiUrl();
  561. log(TAG, 'Register request failed for URL $url: $e');
  562. if (url.isEmpty) {
  563. rethrow;
  564. }
  565. ApiCore().setbaseUrl(url);
  566. } else {
  567. rethrow;
  568. }
  569. }
  570. } catch (e) {
  571. final url = await ApiDomains.instance.getNextApiUrl();
  572. log(TAG, 'Register request failed for URL $url: $e');
  573. if (url.isEmpty) {
  574. rethrow;
  575. }
  576. ApiCore().setbaseUrl(url);
  577. }
  578. }
  579. }
  580. Future<Launch> login(Map<String, dynamic> params) async {
  581. while (true) {
  582. try {
  583. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  584. final request = fp.toJson();
  585. request.addAll(params);
  586. final result = await ApiCore().login(request);
  587. if (!result.success) {
  588. throw Failure(
  589. code: result.errorCode ?? '',
  590. message: result.errorMessage ?? '',
  591. );
  592. }
  593. final launchData = Launch.fromJson(result.data);
  594. // 注册成功后上报firebase注册事件
  595. sendAnalytics(FirebaseEvent.login);
  596. // 保存 Launch 数据
  597. await IXSP.saveLaunch(launchData);
  598. // 初始化Launch
  599. await initData(launchData);
  600. return launchData;
  601. } on ApiException catch (_) {
  602. rethrow;
  603. } on Failure catch (_) {
  604. rethrow;
  605. } on DioException catch (e) {
  606. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  607. e.response?.statusCode == Errors.eUserDisabled ||
  608. e.response?.statusCode == Errors.eTokenExpired) {
  609. rethrow;
  610. } else {
  611. if (await NetworkHelper.instance.isNetworkAvailable()) {
  612. final url = await ApiDomains.instance.getNextApiUrl();
  613. log(TAG, 'Login request failed for URL $url: $e');
  614. if (url.isEmpty) {
  615. rethrow;
  616. }
  617. ApiCore().setbaseUrl(url);
  618. } else {
  619. rethrow;
  620. }
  621. }
  622. } catch (e) {
  623. final url = await ApiDomains.instance.getNextApiUrl();
  624. log(TAG, 'Login request failed for URL $url: $e');
  625. if (url.isEmpty) {
  626. rethrow;
  627. }
  628. ApiCore().setbaseUrl(url);
  629. }
  630. }
  631. }
  632. Future<Launch> logout() async {
  633. try {
  634. final request = fp.toJson();
  635. final result = await ApiCore().logout(request);
  636. if (!result.success) {
  637. throw Failure(
  638. code: result.errorCode ?? '',
  639. message: result.errorMessage ?? '',
  640. );
  641. }
  642. final launchData = Launch.fromJson(result.data);
  643. // 登出成功后上报firebase登出事件
  644. sendAnalytics(FirebaseEvent.logout);
  645. // 保存 Launch 数据
  646. await IXSP.saveLaunch(launchData);
  647. await initData(launchData);
  648. return launchData;
  649. } catch (e) {
  650. rethrow;
  651. }
  652. }
  653. Future<Launch> deleteAccount() async {
  654. try {
  655. final request = fp.toJson();
  656. final result = await ApiCore().deleteAccount(request);
  657. if (!result.success) {
  658. throw Failure(
  659. code: result.errorCode ?? '',
  660. message: result.errorMessage ?? '',
  661. );
  662. }
  663. final launchData = Launch.fromJson(result.data);
  664. // 登出成功后上报firebase登出事件
  665. sendAnalytics(FirebaseEvent.deleteAccount);
  666. // 保存 Launch 数据
  667. await IXSP.saveLaunch(launchData);
  668. await initData(launchData);
  669. return launchData;
  670. } catch (e) {
  671. rethrow;
  672. }
  673. }
  674. Future<String> changePassword(Map<String, dynamic> params) async {
  675. try {
  676. final request = fp.toJson();
  677. request.addAll(params);
  678. final result = await ApiCore().changePassword(request);
  679. if (!result.success) {
  680. throw Failure(
  681. code: result.errorCode ?? '',
  682. message: result.errorMessage ?? '',
  683. );
  684. }
  685. return result.errorMessage ?? '';
  686. } catch (e) {
  687. rethrow;
  688. }
  689. }
  690. Future<Groups> getLocations() async {
  691. while (true) {
  692. try {
  693. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  694. final request = fp.toJson();
  695. final result = await ApiCore().getLocations(request);
  696. if (!result.success) {
  697. throw Failure(
  698. code: result.errorCode ?? '',
  699. message: result.errorMessage ?? '',
  700. );
  701. }
  702. final groups = Groups.fromJson(result.data);
  703. await IXSP.saveGroups(groups);
  704. return groups;
  705. } on ApiException catch (_) {
  706. rethrow;
  707. } on Failure catch (_) {
  708. rethrow;
  709. } on DioException catch (e) {
  710. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  711. e.response?.statusCode == Errors.eUserDisabled ||
  712. e.response?.statusCode == Errors.eTokenExpired) {
  713. rethrow;
  714. } else {
  715. if (await NetworkHelper.instance.isNetworkAvailable()) {
  716. final url = await ApiDomains.instance.getNextApiUrl();
  717. log(TAG, 'getLocations request failed for URL $url: $e');
  718. if (url.isEmpty) {
  719. rethrow;
  720. }
  721. ApiCore().setbaseUrl(url);
  722. } else {
  723. rethrow;
  724. }
  725. }
  726. } catch (e) {
  727. final url = await ApiDomains.instance.getNextApiUrl();
  728. log(TAG, 'getLocations request failed for URL $url: $e');
  729. if (url.isEmpty) {
  730. rethrow;
  731. }
  732. ApiCore().setbaseUrl(url);
  733. }
  734. }
  735. }
  736. Future<List<ChannelPlan>> getChannelPlanList() async {
  737. try {
  738. final request = fp.toJson();
  739. final result = await ApiCore().getChannelPlanList(request);
  740. if (!result.success) {
  741. throw Failure(
  742. code: result.errorCode ?? '',
  743. message: result.errorMessage ?? '',
  744. );
  745. }
  746. final channelPlanList = ChannelPlanList.fromJson(result.data);
  747. return channelPlanList.list ?? [];
  748. } catch (e) {
  749. rethrow;
  750. }
  751. }
  752. Future<Launch> subscribe(Map<String, dynamic> params) async {
  753. try {
  754. final request = fp.toJson();
  755. request.addAll(params);
  756. final result = await ApiCore().subscribe(request);
  757. if (!result.success) {
  758. throw Failure(
  759. code: result.errorCode ?? '',
  760. message: result.errorMessage ?? '',
  761. );
  762. }
  763. final launchData = Launch.fromJson(result.data);
  764. // 登出成功后上报firebase登出事件
  765. sendAnalytics(FirebaseEvent.subscribe);
  766. // 保存 Launch 数据
  767. await IXSP.saveLaunch(launchData);
  768. // 初始化Launch
  769. await initData(launchData);
  770. return launchData;
  771. } catch (e) {
  772. rethrow;
  773. }
  774. }
  775. Future<Launch> restore() async {
  776. try {
  777. final request = fp.toJson();
  778. final result = await ApiCore().restore(request);
  779. if (!result.success) {
  780. throw Failure(
  781. code: result.errorCode ?? '',
  782. message: result.errorMessage ?? '',
  783. );
  784. }
  785. final launchData = Launch.fromJson(result.data);
  786. // 登出成功后上报firebase登出事件
  787. sendAnalytics(FirebaseEvent.restore);
  788. // 保存 Launch 数据
  789. await IXSP.saveLaunch(launchData);
  790. // 初始化Launch
  791. await initData(launchData);
  792. return launchData;
  793. } catch (e) {
  794. rethrow;
  795. }
  796. }
  797. Future<void> connected(Map<String, dynamic> params) async {
  798. try {
  799. final request = fp.toJson();
  800. request.addAll(params);
  801. final result = await ApiRouter().connected(request);
  802. if (!result.success) {
  803. throw Failure(
  804. code: result.errorCode ?? '',
  805. message: result.errorMessage ?? '',
  806. );
  807. }
  808. } catch (e) {
  809. rethrow;
  810. }
  811. }
  812. Future<String> uploadLogs(List<dynamic> items, {bool isCache = false}) async {
  813. await updateFingerprintData();
  814. Map<String, dynamic> request = fp.toJson();
  815. request['items'] = items;
  816. while (true) {
  817. try {
  818. ApiLog().setbaseUrl(ApiDomains.instance.getLogUrl());
  819. final result = await ApiLog().uploadLogs(request);
  820. if (!result.success) {
  821. throw Failure(
  822. code: result.errorCode ?? '',
  823. message: result.errorMessage ?? '',
  824. );
  825. }
  826. return result.errorMessage ?? '';
  827. } on ApiException catch (_) {
  828. rethrow;
  829. } on Failure catch (_) {
  830. rethrow;
  831. } on DioException catch (e) {
  832. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  833. e.response?.statusCode == Errors.eUserDisabled ||
  834. e.response?.statusCode == Errors.eTokenExpired) {
  835. if (isCache) {
  836. await _cacheLogRequest(items);
  837. }
  838. rethrow;
  839. } else {
  840. if (await NetworkHelper.instance.isNetworkAvailable()) {
  841. final url = await ApiDomains.instance.getNextLogUrl();
  842. if (url.isEmpty) {
  843. if (isCache) {
  844. await _cacheLogRequest(items);
  845. }
  846. rethrow;
  847. }
  848. log(
  849. TAG,
  850. 'uploadLogs request failed for URL ${ApiLog().baseUrl}: $e',
  851. );
  852. ApiLog().setbaseUrl(url);
  853. } else {
  854. if (isCache) {
  855. await _cacheLogRequest(items);
  856. }
  857. rethrow;
  858. }
  859. }
  860. } catch (e) {
  861. final url = await ApiDomains.instance.getNextLogUrl();
  862. if (url.isEmpty) {
  863. if (isCache) {
  864. await _cacheLogRequest(items);
  865. }
  866. rethrow;
  867. }
  868. log(TAG, 'uploadLogs request failed for URL ${ApiLog().baseUrl}: $e');
  869. ApiLog().setbaseUrl(url);
  870. }
  871. }
  872. }
  873. // 缓存日志请求数据
  874. Future<void> _cacheLogRequest(dynamic items) async {
  875. try {
  876. final dir = await getApplicationDocumentsDirectory();
  877. final cacheDir = Directory('${dir.path}/log_cache');
  878. if (!await cacheDir.exists()) {
  879. await cacheDir.create(recursive: true);
  880. }
  881. // 生成唯一的文件名
  882. final timestamp = DateTime.now().millisecondsSinceEpoch;
  883. final fileName = 'log_$timestamp.json';
  884. final file = File('${cacheDir.path}/$fileName');
  885. // 将请求数据写入文件
  886. await file.writeAsString(jsonEncode(items));
  887. // 清理缓存目录
  888. await _cleanupCacheDirectory(cacheDir);
  889. } catch (e) {
  890. log(TAG, 'Failed to cache log request: $e');
  891. }
  892. }
  893. // 清理缓存目录
  894. Future<void> _cleanupCacheDirectory(Directory cacheDir) async {
  895. try {
  896. const maxFiles = 10; // 最多保留10个文件
  897. const maxCacheSize = 5 * 1024 * 1024; // 5MB
  898. final files = await cacheDir.list().toList();
  899. // 按修改时间排序
  900. files.sort(
  901. (a, b) => a.statSync().modified.compareTo(b.statSync().modified),
  902. );
  903. // 计算当前缓存大小
  904. int totalSize = 0;
  905. for (var file in files) {
  906. totalSize += file.statSync().size;
  907. }
  908. // 如果超过文件数量或大小限制,删除最旧的文件
  909. while ((files.length > maxFiles || totalSize > maxCacheSize) &&
  910. files.isNotEmpty) {
  911. final oldestFile = files.removeAt(0);
  912. totalSize -= oldestFile.statSync().size;
  913. await oldestFile.delete();
  914. }
  915. } catch (e) {
  916. log(TAG, 'Failed to cleanup cache directory: $e');
  917. }
  918. }
  919. Future<void> uploadApiStatisticsLog(
  920. List<Map<String, dynamic>> logs, {
  921. LogModule module = LogModule.NM_ApiLaunchLog,
  922. }) async {
  923. if (isNeedUploadLogs(module)) {
  924. await uploadLogs(logs);
  925. }
  926. }
  927. // 判断是否需要上传日志
  928. bool isNeedUploadLogs(LogModule module) {
  929. final launch = IXSP.getLaunch();
  930. if (launch == null) {
  931. return false;
  932. }
  933. if (launch.appConfig?.disabledLogModules?.contains(module.name) ?? false) {
  934. return false;
  935. }
  936. return true;
  937. }
  938. /// 获取订阅周期类型文本
  939. /// subscribeType: 1Day 2Week 3Month 4Year
  940. String _getSubscribeTypeText() {
  941. final user = IXSP.getUser();
  942. final planInfo = user?.planInfo;
  943. // 仅当 isSubscribe=true 时有效
  944. if (planInfo?.isSubscribe != true) {
  945. return planInfo?.subTitle ?? '';
  946. }
  947. switch (planInfo?.subscribeType) {
  948. case 1:
  949. return 'Day';
  950. case 2:
  951. return 'Week';
  952. case 3:
  953. return 'Month';
  954. case 4:
  955. return 'Year';
  956. default:
  957. return '';
  958. }
  959. }
  960. /// 获取过期时间文本
  961. String _getExpireTimeText() {
  962. final user = IXSP.getUser();
  963. final expireTime = user?.expireTime;
  964. if (expireTime == null || expireTime == 0) {
  965. return '';
  966. }
  967. // 时间戳转日期(秒级时间戳)
  968. final date = DateTime.fromMillisecondsSinceEpoch(expireTime * 1000);
  969. final formatted =
  970. "${date.year.toString().padLeft(4, '0')}-"
  971. "${date.month.toString().padLeft(2, '0')}-"
  972. "${date.day.toString().padLeft(2, '0')}";
  973. return formatted;
  974. }
  975. /// 获取有效期显示文本
  976. String _getValidTermText() {
  977. final subscribeType = _getSubscribeTypeText();
  978. final expireTime = _getExpireTimeText();
  979. if (subscribeType.isNotEmpty && expireTime.isNotEmpty) {
  980. return '$subscribeType / $expireTime';
  981. } else if (expireTime.isNotEmpty) {
  982. return expireTime;
  983. }
  984. return '';
  985. }
  986. /// 启动剩余时间倒计时
  987. /// [seconds] 剩余时间(秒),例如:3600 表示 1 小时
  988. void startRemainTimeCountdown(int seconds) {
  989. // 取消之前的定时器
  990. _remainTimeTimer?.cancel();
  991. // 设置初始剩余时间
  992. _remainTimeSeconds.value = seconds;
  993. // 启动每秒倒计时
  994. _remainTimeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
  995. if (_remainTimeSeconds.value > 0) {
  996. _remainTimeSeconds.value--;
  997. } else {
  998. // 倒计时结束
  999. timer.cancel();
  1000. _remainTimeTimer = null;
  1001. _onRemainTimeExpired();
  1002. }
  1003. });
  1004. }
  1005. /// 停止剩余时间倒计时
  1006. void stopRemainTimeCountdown() {
  1007. _remainTimeTimer?.cancel();
  1008. _remainTimeTimer = null;
  1009. }
  1010. /// 更新剩余时间(从服务器获取新的时间后调用)
  1011. void updateRemainTime(int seconds) {
  1012. stopRemainTimeCountdown();
  1013. if (seconds > 0) {
  1014. startRemainTimeCountdown(seconds);
  1015. } else {
  1016. _remainTimeSeconds.value = 0;
  1017. }
  1018. }
  1019. /// 剩余时间到期处理
  1020. void _onRemainTimeExpired() {
  1021. log(TAG, 'VIP剩余时间已到期');
  1022. // 可以在这里添加到期后的处理逻辑,例如:
  1023. // - 显示续费提示
  1024. // - 断开VPN连接
  1025. // - 刷新用户信息
  1026. }
  1027. /// 格式化剩余时间显示
  1028. String _formatRemainTime(int totalSeconds) {
  1029. if (totalSeconds <= 0) {
  1030. return '00:00:00';
  1031. }
  1032. final hours = totalSeconds ~/ 3600;
  1033. final minutes = (totalSeconds % 3600) ~/ 60;
  1034. final seconds = totalSeconds % 60;
  1035. return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  1036. }
  1037. }