api_controller.dart 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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. final result = await ApiRouter().getDispatchInfo(
  476. request,
  477. cancelToken: cancelToken,
  478. );
  479. if (!result.success) {
  480. throw Failure(
  481. code: result.errorCode ?? '',
  482. message: result.errorMessage ?? '',
  483. );
  484. }
  485. // 重置禁用状态
  486. IXSP.setLastIsRegionDisabled(false);
  487. IXSP.setLastIsUserDisabled(false);
  488. final launchData = Launch.fromJson(result.data);
  489. // 更新URL列表
  490. await ApiDomains.instance.updateFromLaunch(launchData);
  491. // 保存app配置
  492. await IXSP.saveAppConfig(launchData.appConfig!);
  493. return launchData;
  494. } on ApiException catch (_) {
  495. rethrow;
  496. } on Failure catch (_) {
  497. rethrow;
  498. } on DioException catch (e) {
  499. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  500. e.response?.statusCode == Errors.eUserDisabled ||
  501. e.response?.statusCode == Errors.eTokenExpired) {
  502. rethrow;
  503. } else {
  504. if (await NetworkHelper.instance.isNetworkAvailable()) {
  505. final url = await ApiDomains.instance.getNextRouterUrl();
  506. log(TAG, 'getDispatchInfo request failed for URL $url: $e');
  507. if (url.isEmpty) {
  508. rethrow;
  509. }
  510. ApiRouter().setbaseUrl(url);
  511. } else {
  512. rethrow;
  513. }
  514. }
  515. } catch (e) {
  516. final url = await ApiDomains.instance.getNextRouterUrl();
  517. log(TAG, 'getDispatchInfo request failed for URL $url: $e');
  518. if (url.isEmpty) {
  519. rethrow;
  520. }
  521. ApiRouter().setbaseUrl(url);
  522. }
  523. }
  524. }
  525. Future<Launch> register(Map<String, dynamic> params) async {
  526. while (true) {
  527. try {
  528. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  529. final request = fp.toJson();
  530. request.addAll(params);
  531. final result = await ApiCore().register(request);
  532. if (!result.success) {
  533. throw Failure(
  534. code: result.errorCode ?? '',
  535. message: result.errorMessage ?? '',
  536. );
  537. }
  538. final launchData = Launch.fromJson(result.data);
  539. // 注册成功后上报firebase注册事件
  540. sendAnalytics(FirebaseEvent.register);
  541. // 保存 Launch 数据
  542. await IXSP.saveLaunch(launchData);
  543. // 初始化Launch
  544. await initData(launchData);
  545. return launchData;
  546. } on ApiException catch (_) {
  547. rethrow;
  548. } on Failure catch (_) {
  549. rethrow;
  550. } on DioException catch (e) {
  551. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  552. e.response?.statusCode == Errors.eUserDisabled ||
  553. e.response?.statusCode == Errors.eTokenExpired) {
  554. rethrow;
  555. } else {
  556. if (await NetworkHelper.instance.isNetworkAvailable()) {
  557. final url = await ApiDomains.instance.getNextApiUrl();
  558. log(TAG, 'Register request failed for URL $url: $e');
  559. if (url.isEmpty) {
  560. rethrow;
  561. }
  562. ApiCore().setbaseUrl(url);
  563. } else {
  564. rethrow;
  565. }
  566. }
  567. } catch (e) {
  568. final url = await ApiDomains.instance.getNextApiUrl();
  569. log(TAG, 'Register request failed for URL $url: $e');
  570. if (url.isEmpty) {
  571. rethrow;
  572. }
  573. ApiCore().setbaseUrl(url);
  574. }
  575. }
  576. }
  577. Future<Launch> login(Map<String, dynamic> params) async {
  578. while (true) {
  579. try {
  580. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  581. final request = fp.toJson();
  582. request.addAll(params);
  583. final result = await ApiCore().login(request);
  584. if (!result.success) {
  585. throw Failure(
  586. code: result.errorCode ?? '',
  587. message: result.errorMessage ?? '',
  588. );
  589. }
  590. final launchData = Launch.fromJson(result.data);
  591. // 注册成功后上报firebase注册事件
  592. sendAnalytics(FirebaseEvent.login);
  593. // 保存 Launch 数据
  594. await IXSP.saveLaunch(launchData);
  595. // 初始化Launch
  596. await initData(launchData);
  597. return launchData;
  598. } on ApiException catch (_) {
  599. rethrow;
  600. } on Failure catch (_) {
  601. rethrow;
  602. } on DioException catch (e) {
  603. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  604. e.response?.statusCode == Errors.eUserDisabled ||
  605. e.response?.statusCode == Errors.eTokenExpired) {
  606. rethrow;
  607. } else {
  608. if (await NetworkHelper.instance.isNetworkAvailable()) {
  609. final url = await ApiDomains.instance.getNextApiUrl();
  610. log(TAG, 'Login request failed for URL $url: $e');
  611. if (url.isEmpty) {
  612. rethrow;
  613. }
  614. ApiCore().setbaseUrl(url);
  615. } else {
  616. rethrow;
  617. }
  618. }
  619. } catch (e) {
  620. final url = await ApiDomains.instance.getNextApiUrl();
  621. log(TAG, 'Login request failed for URL $url: $e');
  622. if (url.isEmpty) {
  623. rethrow;
  624. }
  625. ApiCore().setbaseUrl(url);
  626. }
  627. }
  628. }
  629. Future<Launch> logout() async {
  630. try {
  631. final request = fp.toJson();
  632. final result = await ApiCore().logout(request);
  633. if (!result.success) {
  634. throw Failure(
  635. code: result.errorCode ?? '',
  636. message: result.errorMessage ?? '',
  637. );
  638. }
  639. final launchData = Launch.fromJson(result.data);
  640. // 登出成功后上报firebase登出事件
  641. sendAnalytics(FirebaseEvent.logout);
  642. // 保存 Launch 数据
  643. await IXSP.saveLaunch(launchData);
  644. await initData(launchData);
  645. return launchData;
  646. } catch (e) {
  647. rethrow;
  648. }
  649. }
  650. Future<Launch> deleteAccount() async {
  651. try {
  652. final request = fp.toJson();
  653. final result = await ApiCore().deleteAccount(request);
  654. if (!result.success) {
  655. throw Failure(
  656. code: result.errorCode ?? '',
  657. message: result.errorMessage ?? '',
  658. );
  659. }
  660. final launchData = Launch.fromJson(result.data);
  661. // 登出成功后上报firebase登出事件
  662. sendAnalytics(FirebaseEvent.deleteAccount);
  663. // 保存 Launch 数据
  664. await IXSP.saveLaunch(launchData);
  665. await initData(launchData);
  666. return launchData;
  667. } catch (e) {
  668. rethrow;
  669. }
  670. }
  671. Future<String> changePassword(Map<String, dynamic> params) async {
  672. try {
  673. final request = fp.toJson();
  674. request.addAll(params);
  675. final result = await ApiCore().changePassword(request);
  676. if (!result.success) {
  677. throw Failure(
  678. code: result.errorCode ?? '',
  679. message: result.errorMessage ?? '',
  680. );
  681. }
  682. return result.errorMessage ?? '';
  683. } catch (e) {
  684. rethrow;
  685. }
  686. }
  687. Future<Groups> getLocations() async {
  688. while (true) {
  689. try {
  690. ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
  691. final request = fp.toJson();
  692. final result = await ApiCore().getLocations(request);
  693. if (!result.success) {
  694. throw Failure(
  695. code: result.errorCode ?? '',
  696. message: result.errorMessage ?? '',
  697. );
  698. }
  699. final groups = Groups.fromJson(result.data);
  700. await IXSP.saveGroups(groups);
  701. return groups;
  702. } on ApiException catch (_) {
  703. rethrow;
  704. } on Failure catch (_) {
  705. rethrow;
  706. } on DioException catch (e) {
  707. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  708. e.response?.statusCode == Errors.eUserDisabled ||
  709. e.response?.statusCode == Errors.eTokenExpired) {
  710. rethrow;
  711. } else {
  712. if (await NetworkHelper.instance.isNetworkAvailable()) {
  713. final url = await ApiDomains.instance.getNextApiUrl();
  714. log(TAG, 'getLocations request failed for URL $url: $e');
  715. if (url.isEmpty) {
  716. rethrow;
  717. }
  718. ApiCore().setbaseUrl(url);
  719. } else {
  720. rethrow;
  721. }
  722. }
  723. } catch (e) {
  724. final url = await ApiDomains.instance.getNextApiUrl();
  725. log(TAG, 'getLocations request failed for URL $url: $e');
  726. if (url.isEmpty) {
  727. rethrow;
  728. }
  729. ApiCore().setbaseUrl(url);
  730. }
  731. }
  732. }
  733. Future<List<ChannelPlan>> getChannelPlanList() async {
  734. try {
  735. final request = fp.toJson();
  736. final result = await ApiCore().getChannelPlanList(request);
  737. if (!result.success) {
  738. throw Failure(
  739. code: result.errorCode ?? '',
  740. message: result.errorMessage ?? '',
  741. );
  742. }
  743. final channelPlanList = ChannelPlanList.fromJson(result.data);
  744. return channelPlanList.list ?? [];
  745. } catch (e) {
  746. rethrow;
  747. }
  748. }
  749. Future<Launch> subscribe(Map<String, dynamic> params) async {
  750. try {
  751. final request = fp.toJson();
  752. request.addAll(params);
  753. final result = await ApiCore().subscribe(request);
  754. if (!result.success) {
  755. throw Failure(
  756. code: result.errorCode ?? '',
  757. message: result.errorMessage ?? '',
  758. );
  759. }
  760. final launchData = Launch.fromJson(result.data);
  761. // 登出成功后上报firebase登出事件
  762. sendAnalytics(FirebaseEvent.subscribe);
  763. // 保存 Launch 数据
  764. await IXSP.saveLaunch(launchData);
  765. // 初始化Launch
  766. await initData(launchData);
  767. return launchData;
  768. } catch (e) {
  769. rethrow;
  770. }
  771. }
  772. Future<Launch> restore() async {
  773. try {
  774. final request = fp.toJson();
  775. final result = await ApiCore().restore(request);
  776. if (!result.success) {
  777. throw Failure(
  778. code: result.errorCode ?? '',
  779. message: result.errorMessage ?? '',
  780. );
  781. }
  782. final launchData = Launch.fromJson(result.data);
  783. // 登出成功后上报firebase登出事件
  784. sendAnalytics(FirebaseEvent.restore);
  785. // 保存 Launch 数据
  786. await IXSP.saveLaunch(launchData);
  787. // 初始化Launch
  788. await initData(launchData);
  789. return launchData;
  790. } catch (e) {
  791. rethrow;
  792. }
  793. }
  794. Future<void> connected(Map<String, dynamic> params) async {
  795. try {
  796. final request = fp.toJson();
  797. request.addAll(params);
  798. final result = await ApiRouter().connected(request);
  799. if (!result.success) {
  800. throw Failure(
  801. code: result.errorCode ?? '',
  802. message: result.errorMessage ?? '',
  803. );
  804. }
  805. } catch (e) {
  806. rethrow;
  807. }
  808. }
  809. Future<String> uploadLogs(List<dynamic> items, {bool isCache = false}) async {
  810. await updateFingerprintData();
  811. Map<String, dynamic> request = fp.toJson();
  812. request['items'] = items;
  813. while (true) {
  814. try {
  815. ApiLog().setbaseUrl(ApiDomains.instance.getLogUrl());
  816. final result = await ApiLog().uploadLogs(request);
  817. if (!result.success) {
  818. throw Failure(
  819. code: result.errorCode ?? '',
  820. message: result.errorMessage ?? '',
  821. );
  822. }
  823. return result.errorMessage ?? '';
  824. } on ApiException catch (_) {
  825. rethrow;
  826. } on Failure catch (_) {
  827. rethrow;
  828. } on DioException catch (e) {
  829. if (e.response?.statusCode == Errors.eRegionNotAvailable ||
  830. e.response?.statusCode == Errors.eUserDisabled ||
  831. e.response?.statusCode == Errors.eTokenExpired) {
  832. if (isCache) {
  833. await _cacheLogRequest(items);
  834. }
  835. rethrow;
  836. } else {
  837. if (await NetworkHelper.instance.isNetworkAvailable()) {
  838. final url = await ApiDomains.instance.getNextLogUrl();
  839. if (url.isEmpty) {
  840. if (isCache) {
  841. await _cacheLogRequest(items);
  842. }
  843. rethrow;
  844. }
  845. log(
  846. TAG,
  847. 'uploadLogs request failed for URL ${ApiLog().baseUrl}: $e',
  848. );
  849. ApiLog().setbaseUrl(url);
  850. } else {
  851. if (isCache) {
  852. await _cacheLogRequest(items);
  853. }
  854. rethrow;
  855. }
  856. }
  857. } catch (e) {
  858. final url = await ApiDomains.instance.getNextLogUrl();
  859. if (url.isEmpty) {
  860. if (isCache) {
  861. await _cacheLogRequest(items);
  862. }
  863. rethrow;
  864. }
  865. log(TAG, 'uploadLogs request failed for URL ${ApiLog().baseUrl}: $e');
  866. ApiLog().setbaseUrl(url);
  867. }
  868. }
  869. }
  870. // 缓存日志请求数据
  871. Future<void> _cacheLogRequest(dynamic items) async {
  872. try {
  873. final dir = await getApplicationDocumentsDirectory();
  874. final cacheDir = Directory('${dir.path}/log_cache');
  875. if (!await cacheDir.exists()) {
  876. await cacheDir.create(recursive: true);
  877. }
  878. // 生成唯一的文件名
  879. final timestamp = DateTime.now().millisecondsSinceEpoch;
  880. final fileName = 'log_$timestamp.json';
  881. final file = File('${cacheDir.path}/$fileName');
  882. // 将请求数据写入文件
  883. await file.writeAsString(jsonEncode(items));
  884. // 清理缓存目录
  885. await _cleanupCacheDirectory(cacheDir);
  886. } catch (e) {
  887. log(TAG, 'Failed to cache log request: $e');
  888. }
  889. }
  890. // 清理缓存目录
  891. Future<void> _cleanupCacheDirectory(Directory cacheDir) async {
  892. try {
  893. const maxFiles = 10; // 最多保留10个文件
  894. const maxCacheSize = 5 * 1024 * 1024; // 5MB
  895. final files = await cacheDir.list().toList();
  896. // 按修改时间排序
  897. files.sort(
  898. (a, b) => a.statSync().modified.compareTo(b.statSync().modified),
  899. );
  900. // 计算当前缓存大小
  901. int totalSize = 0;
  902. for (var file in files) {
  903. totalSize += file.statSync().size;
  904. }
  905. // 如果超过文件数量或大小限制,删除最旧的文件
  906. while ((files.length > maxFiles || totalSize > maxCacheSize) &&
  907. files.isNotEmpty) {
  908. final oldestFile = files.removeAt(0);
  909. totalSize -= oldestFile.statSync().size;
  910. await oldestFile.delete();
  911. }
  912. } catch (e) {
  913. log(TAG, 'Failed to cleanup cache directory: $e');
  914. }
  915. }
  916. Future<void> uploadApiStatisticsLog(
  917. List<Map<String, dynamic>> logs, {
  918. LogModule module = LogModule.NM_ApiLaunchLog,
  919. }) async {
  920. if (isNeedUploadLogs(module)) {
  921. await uploadLogs(logs);
  922. }
  923. }
  924. // 判断是否需要上传日志
  925. bool isNeedUploadLogs(LogModule module) {
  926. final launch = IXSP.getLaunch();
  927. if (launch == null) {
  928. return false;
  929. }
  930. if (launch.appConfig?.disabledLogModules?.contains(module.name) ?? false) {
  931. return false;
  932. }
  933. return true;
  934. }
  935. /// 获取订阅周期类型文本
  936. /// subscribeType: 1Day 2Week 3Month 4Year
  937. String _getSubscribeTypeText() {
  938. final user = IXSP.getUser();
  939. final planInfo = user?.planInfo;
  940. // 仅当 isSubscribe=true 时有效
  941. if (planInfo?.isSubscribe != true) {
  942. return planInfo?.subTitle ?? '';
  943. }
  944. switch (planInfo?.subscribeType) {
  945. case 1:
  946. return 'Day';
  947. case 2:
  948. return 'Week';
  949. case 3:
  950. return 'Month';
  951. case 4:
  952. return 'Year';
  953. default:
  954. return '';
  955. }
  956. }
  957. /// 获取过期时间文本
  958. String _getExpireTimeText() {
  959. final user = IXSP.getUser();
  960. final expireTime = user?.expireTime;
  961. if (expireTime == null || expireTime == 0) {
  962. return '';
  963. }
  964. // 时间戳转日期(秒级时间戳)
  965. final date = DateTime.fromMillisecondsSinceEpoch(expireTime * 1000);
  966. final formatted =
  967. "${date.year.toString().padLeft(4, '0')}-"
  968. "${date.month.toString().padLeft(2, '0')}-"
  969. "${date.day.toString().padLeft(2, '0')}";
  970. return formatted;
  971. }
  972. /// 获取有效期显示文本
  973. String _getValidTermText() {
  974. final subscribeType = _getSubscribeTypeText();
  975. final expireTime = _getExpireTimeText();
  976. if (subscribeType.isNotEmpty && expireTime.isNotEmpty) {
  977. return '$subscribeType / $expireTime';
  978. } else if (expireTime.isNotEmpty) {
  979. return expireTime;
  980. }
  981. return '';
  982. }
  983. /// 启动剩余时间倒计时
  984. /// [seconds] 剩余时间(秒),例如:3600 表示 1 小时
  985. void startRemainTimeCountdown(int seconds) {
  986. // 取消之前的定时器
  987. _remainTimeTimer?.cancel();
  988. // 设置初始剩余时间
  989. _remainTimeSeconds.value = seconds;
  990. // 启动每秒倒计时
  991. _remainTimeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
  992. if (_remainTimeSeconds.value > 0) {
  993. _remainTimeSeconds.value--;
  994. } else {
  995. // 倒计时结束
  996. timer.cancel();
  997. _remainTimeTimer = null;
  998. _onRemainTimeExpired();
  999. }
  1000. });
  1001. }
  1002. /// 停止剩余时间倒计时
  1003. void stopRemainTimeCountdown() {
  1004. _remainTimeTimer?.cancel();
  1005. _remainTimeTimer = null;
  1006. }
  1007. /// 更新剩余时间(从服务器获取新的时间后调用)
  1008. void updateRemainTime(int seconds) {
  1009. stopRemainTimeCountdown();
  1010. if (seconds > 0) {
  1011. startRemainTimeCountdown(seconds);
  1012. } else {
  1013. _remainTimeSeconds.value = 0;
  1014. }
  1015. }
  1016. /// 剩余时间到期处理
  1017. void _onRemainTimeExpired() {
  1018. log(TAG, 'VIP剩余时间已到期');
  1019. // 可以在这里添加到期后的处理逻辑,例如:
  1020. // - 显示续费提示
  1021. // - 断开VPN连接
  1022. // - 刷新用户信息
  1023. }
  1024. /// 格式化剩余时间显示
  1025. String _formatRemainTime(int totalSeconds) {
  1026. if (totalSeconds <= 0) {
  1027. return '00:00:00';
  1028. }
  1029. final hours = totalSeconds ~/ 3600;
  1030. final minutes = (totalSeconds % 3600) ~/ 60;
  1031. final seconds = totalSeconds % 60;
  1032. return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  1033. }
  1034. }