api_controller.dart 40 KB

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