api_controller.dart 34 KB

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