| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150 |
- import 'dart:async';
- import 'dart:convert';
- import 'dart:io';
- import 'package:device_info_plus/device_info_plus.dart';
- import 'package:dio/dio.dart';
- import 'package:flutter/material.dart';
- import 'package:get/get.dart';
- import 'package:nomo/app/api/router/api_router.dart';
- import 'package:nomo/app/data/sp/ix_sp.dart';
- import 'package:package_info_plus/package_info_plus.dart';
- import 'package:path_provider/path_provider.dart';
- import 'package:play_install_referrer/play_install_referrer.dart';
- import '../../config/translations/localization_service.dart';
- import '../../config/translations/strings_enum.dart';
- import '../../pigeons/core_api.g.dart';
- import '../../utils/api_statistics.dart';
- import '../../utils/device_manager.dart';
- import '../../utils/geo_downloader.dart';
- import '../../utils/log/logger.dart';
- import '../../utils/network_helper.dart';
- import '../../utils/ntp_time_service.dart';
- import '../api/core/api_core.dart';
- import '../api/log/api_log.dart';
- import '../components/country_restricted_overlay.dart';
- import '../components/ix_snackbar.dart';
- import '../constants/api_domains.dart';
- import '../constants/configs.dart';
- import '../constants/enums.dart';
- import '../constants/errors.dart';
- import '../constants/platforms.dart';
- import '../data/models/api_exception.dart';
- import '../data/models/channelplan/channel_plan_list.dart';
- import '../data/models/failure.dart';
- import '../data/models/fingerprint.dart';
- import '../data/models/launch/groups.dart';
- import '../data/models/launch/launch.dart';
- import '../dialog/all_dialog.dart';
- class ApiController extends GetxService with WidgetsBindingObserver {
- final TAG = 'ApiController';
- // 记录是否已经显示禁用弹窗
- bool isShowDisabled = false;
- //是否是游客
- final _isGuest = false.obs;
- bool get isGuest => _isGuest.value;
- set isGuest(bool value) => _isGuest.value = value;
- //是否是会员
- final _isPremium = false.obs;
- bool get isPremium => _isPremium.value;
- set isPremium(bool value) => _isPremium.value = value;
- //用户等级
- final _userLevel = 1.obs;
- int get userLevel => _userLevel.value;
- set userLevel(int value) => _userLevel.value = value;
- // 过期时间文本
- final _expireTimeText = ''.obs;
- String get expireTimeText => _expireTimeText.value;
- set expireTimeText(String value) => _expireTimeText.value = value;
- // 有效期文本
- final _validTermText = ''.obs;
- String get validTermText => _validTermText.value;
- set validTermText(String value) => _validTermText.value = value;
- //全部节点列表
- final _nodesList = <LocationList>[].obs;
- List<LocationList> get nodesList => _nodesList.value;
- set nodesList(List<LocationList> value) => _nodesList.value = value;
- //初始化fingerprint
- Fingerprint fp = Fingerprint.empty();
- // 全局剩余时间倒计时(秒)
- final _remainTimeSeconds = 0.obs;
- int get remainTimeSeconds => _remainTimeSeconds.value;
- set remainTimeSeconds(int value) => _remainTimeSeconds.value = value;
- // 格式化后的剩余时间字符串
- String get remainTimeFormatted => _formatRemainTime(_remainTimeSeconds.value);
- // 倒计时定时器
- Timer? _remainTimeTimer;
- // 是否在后台
- bool isBackground = false;
- @override
- void onInit() {
- super.onInit();
- WidgetsBinding.instance.addObserver(this);
- }
- @override
- void onClose() {
- WidgetsBinding.instance.removeObserver(this);
- super.onClose();
- }
- @override
- void didChangeAppLifecycleState(AppLifecycleState state) {
- log("App state: $state");
- if (state == AppLifecycleState.paused) {
- isBackground = true;
- ApiStatistics.instance.onAppPaused();
- } else if (state == AppLifecycleState.resumed) {
- if (isBackground) {
- isBackground = false;
- asyncHandleLaunch(isRefreshLaunch: true);
- ApiStatistics.instance.onAppResumed();
- }
- }
- }
- Future<Fingerprint> initFingerprint() async {
- // 读取app发布渠道
- if (Platform.isIOS) {
- fp.channel = 'apple';
- } else if (Platform.isAndroid) {
- try {
- final channel = await CoreApi().getChannel();
- fp.channel = channel ?? 'unknown';
- } catch (e) {
- log(TAG, 'read app channel error: $e');
- fp.channel = '';
- }
- try {
- final advertisingId = await CoreApi().getAdvertisingId();
- fp.googleId = advertisingId ?? '';
- } catch (e) {
- log(TAG, 'read app googleId error: $e');
- fp.googleId = '';
- }
- try {
- ReferrerDetails referrerDetails =
- await PlayInstallReferrer.installReferrer;
- fp.refer = referrerDetails.installReferrer ?? '';
- } catch (e) {
- log(TAG, 'get install referrer error: $e');
- fp.refer = '';
- }
- }
- // 读取应用信息
- final info = await PackageInfo.fromPlatform();
- fp.appVersionCode = int.tryParse(info.buildNumber) ?? 0;
- fp.appVersionName = info.version;
- // 读取设备信息
- final deviceInfo = DeviceInfoPlugin();
- if (Platform.isIOS) {
- fp.platform = Platforms.iOS;
- final iosOsInfo = await deviceInfo.iosInfo;
- fp.deviceModel = iosOsInfo.model;
- fp.deviceOs = iosOsInfo.systemVersion;
- fp.deviceBrand = iosOsInfo.utsname.machine;
- } else if (Platform.isAndroid) {
- fp.platform = Platforms.android;
- final androidOsInfo = await deviceInfo.androidInfo;
- fp.deviceModel = androidOsInfo.model;
- fp.deviceOs = androidOsInfo.version.release;
- fp.deviceBrand = androidOsInfo.brand;
- fp.androidId = androidOsInfo.id;
- }
- //获取设备尺寸
- fp.deviceHeight = Get.height.toInt();
- fp.deviceWidth = Get.width.toInt();
- // 读取设备ID
- fp.deviceId = DeviceManager.getCacheDeviceId();
- fp.isNewInstall = IXSP.getIsNewInstall();
- await updateFingerprintData();
- return fp;
- }
- // 更新部分数据
- Future<void> updateFingerprintData() async {
- fp.lang = IXSP.getCurrentLocal().languageCode;
- fp.phoneCountryIso = LocalizationService.getSystemCountry();
- fp.isVpn = await CoreApi().isConnected() ?? false;
- if (!fp.isVpn) {
- fp.isConnectedVpn = false;
- }
- try {
- final simInfo = await CoreApi().getSimInfo();
- // 解析sim
- final sim = jsonDecode(simInfo ?? '{}');
- fp.simReady = sim['simReady'];
- fp.carrierName = sim['carrierName'];
- fp.mcc = sim['mcc'];
- fp.mnc = sim['mnc'];
- fp.countryIso = sim['countryIso'];
- fp.networkCarrierName = sim['networkCarrierName'];
- fp.networkMcc = sim['networkMcc'];
- fp.networkMnc = sim['networkMnc'];
- fp.networkCountryIso = sim['networkCountryIso'];
- } catch (e) {
- log(TAG, 'read app sim error: $e');
- }
- }
- Future<void> initData(Launch? launch) async {
- // 初始化是否第一次安装
- IXSP.setIsNewInstall(false);
- fp.userUuid = '';
- fp.isNewInstall = false;
- await initLaunch(launch);
- }
- Future<void> initLaunch(Launch? launch) async {
- try {
- if (launch != null) {
- // 初始化用户状态
- isGuest = launch.userConfig?.memberLevel == MemberLevel.guest.level;
- userLevel = launch.userConfig?.userLevel ?? 1;
- isPremium = userLevel == 3 || userLevel == 9999;
- expireTimeText = _getExpireTimeText();
- validTermText = _getValidTermText();
- updateRemainTime(launch.userConfig?.remainTime ?? 0);
- NtpTimeService().initLaunchInitialTime();
- // 设置路由和节点
- nodesList = launch.groups?.normal?.list ?? [];
- // 设置资源url
- if (launch.appConfig?.assetUrls != null &&
- launch.appConfig!.assetUrls!.isNotEmpty) {
- Configs.assetUrl = launch.appConfig!.assetUrls![0];
- }
- // 设置官网url
- if (launch.appConfig?.websiteUrl != null &&
- launch.appConfig!.websiteUrl!.isNotEmpty) {
- Configs.websiteUrl = launch.appConfig!.websiteUrl!;
- }
- }
- } catch (e) {
- log(TAG, 'initLaunch error: $e');
- }
- }
- // 发送分析事件, 后续可以发送到firebase
- Future<void> sendAnalytics(FirebaseEvent event) async {
- try {} catch (e) {
- log('sendAnalytics error: $e');
- }
- }
- Future<Launch> launch({bool isCache = false}) async {
- sendAnalytics(isCache ? FirebaseEvent.launchCache : FirebaseEvent.launch);
- while (true) {
- try {
- ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
- final request = fp.toJson();
- final result = await ApiCore().launch(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- sendAnalytics(
- isCache
- ? FirebaseEvent.launchCacheSuccess
- : FirebaseEvent.launchSuccess,
- );
- // 重置禁用状态
- IXSP.setLastIsRegionDisabled(false);
- IXSP.setLastIsUserDisabled(false);
- final launchData = Launch.fromJson(result.data);
- // 设置扩展数据
- fp.exData = launchData.exData;
- // 更新URL列表
- await ApiDomains.instance.updateFromLaunch(launchData);
- // 保存Launch数据
- await IXSP.saveLaunch(launchData);
- // 初始化Launch
- await initData(launchData);
- return launchData;
- } on ApiException catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Launch request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Launch request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } else {
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Launch request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- }
- }
- }
- Future<Launch> refreshLaunch() async {
- while (true) {
- try {
- ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
- final request = fp.toJson();
- final result = await ApiCore().refreshLaunch(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- // 重置禁用状态
- IXSP.setLastIsRegionDisabled(false);
- IXSP.setLastIsUserDisabled(false);
- final launchData = Launch.fromJson(result.data);
- // 设置扩展数据
- fp.exData = launchData.exData;
- // 更新URL列表
- await ApiDomains.instance.updateFromLaunch(launchData);
- // 保存Launch数据
- await IXSP.saveLaunch(launchData);
- // 初始化Launch
- await initData(launchData);
- return launchData;
- } on ApiException catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'refresh launch request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'refresh launch request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } else {
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'refresh launch request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- }
- }
- }
- Future<void> asyncHandleLaunch({bool isRefreshLaunch = false}) async {
- try {
- final data = isRefreshLaunch
- ? await refreshLaunch()
- : await launch(isCache: true);
- final isVpnRunning = await CoreApi().isConnected() ?? false;
- if (!isVpnRunning) {
- await checkUpdate();
- // 下载smartgeo文件
- GeoDownloader().downloadSmartGeo(smartGeo: data.appConfig!.smartGeo!);
- }
- } catch (e, s) {
- if (IXSP.getLastIsUserDisabled()) {
- if (!isShowDisabled) {
- Get.offAll(
- () => CountryRestrictedOverlay(
- type: RestrictedType.user,
- onPressed: () async {
- // 清除LaunchData
- await IXSP.clearLaunchData();
- // 清除禁用状态
- IXSP.setLastIsUserDisabled(false);
- // 发送事件
- },
- ),
- transition: Transition.fadeIn,
- );
- }
- return;
- } else if (IXSP.getLastIsRegionDisabled()) {
- if (!isShowDisabled) {
- Get.offAll(
- () => const CountryRestrictedOverlay(type: RestrictedType.region),
- transition: Transition.fadeIn,
- );
- }
- return;
- } else if (IXSP.getLastIsDeviceDisabled()) {
- if (!isShowDisabled) {
- Get.offAll(
- () => const CountryRestrictedOverlay(type: RestrictedType.device),
- transition: Transition.fadeIn,
- );
- }
- return;
- }
- final isVpnRunning = await CoreApi().isConnected() ?? false;
- if (!isVpnRunning) {
- await checkUpdate();
- }
- handleSnackBarError(e, s);
- }
- }
- void handleSnackBarError(dynamic error, StackTrace stackTrace) {
- if (error is ApiException) {
- IXSnackBar.showIXErrorSnackBar(
- title: Strings.error.tr,
- message: error.message,
- );
- } else if (error is Failure) {
- IXSnackBar.showIXErrorSnackBar(
- title: Strings.error.tr,
- message: error.message ?? Strings.unknownError.tr,
- );
- } else if (error is DioException) {
- switch (error.type) {
- case DioExceptionType.connectionError:
- case DioExceptionType.connectionTimeout:
- case DioExceptionType.receiveTimeout:
- case DioExceptionType.sendTimeout:
- IXSnackBar.showIXErrorSnackBar(
- title: Strings.error.tr,
- message: Strings.unableToConnectNetwork.tr,
- );
- break;
- default:
- IXSnackBar.showIXErrorSnackBar(
- title: Strings.error.tr,
- message: Strings.unableToConnectServer.tr,
- );
- }
- } else {
- IXSnackBar.showIXErrorSnackBar(
- title: Strings.error.tr,
- message: error.toString(),
- );
- }
- }
- // 更新检查 - 智能时间控制版本
- Future<bool> checkUpdate({bool isClickCheck = false}) async {
- try {
- final upgrade = IXSP.getUpgrade();
- var hasUpdate = false;
- var hasForceUpdate = false;
- if (upgrade != null) {
- if (upgrade.upgradeType == 1) {
- hasUpdate = true;
- }
- if (upgrade.forced == true) {
- hasForceUpdate = true;
- }
- }
- if (hasUpdate) {
- AllDialog.showUpdate(hasForceUpdate: hasForceUpdate);
- }
- return hasUpdate;
- } catch (e) {
- log(TAG, 'checkUpdate error: $e');
- }
- return false;
- }
- Future<Launch> getDispatchInfo(
- int locationId,
- String locationCode, {
- CancelToken? cancelToken,
- }) async {
- while (true) {
- try {
- ApiRouter().setbaseUrl(ApiDomains.instance.getRouterUrl());
- final request = fp.toJson();
- request['locationId'] = locationId;
- request['locationCode'] = locationCode;
- // 获取选中的路由模式
- final routingMode = IXSP.getString("routing_mode_selected") ?? "smart";
- request['routingMode'] = routingMode;
- final result = await ApiRouter().getDispatchInfo(
- request,
- cancelToken: cancelToken,
- );
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- // 重置禁用状态
- IXSP.setLastIsRegionDisabled(false);
- IXSP.setLastIsUserDisabled(false);
- final launchData = Launch.fromJson(result.data);
- // 更新URL列表
- await ApiDomains.instance.updateFromLaunch(launchData);
- // 保存app配置
- await IXSP.saveAppConfig(launchData.appConfig!);
- return launchData;
- } on ApiException catch (_) {
- rethrow;
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextRouterUrl();
- log(TAG, 'getDispatchInfo request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiRouter().setbaseUrl(url);
- } else {
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextRouterUrl();
- log(TAG, 'getDispatchInfo request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiRouter().setbaseUrl(url);
- }
- }
- }
- Future<Launch> register(Map<String, dynamic> params) async {
- while (true) {
- try {
- ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
- final request = fp.toJson();
- request.addAll(params);
- final result = await ApiCore().register(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final launchData = Launch.fromJson(result.data);
- // 注册成功后上报firebase注册事件
- sendAnalytics(FirebaseEvent.register);
- // 保存 Launch 数据
- await IXSP.saveLaunch(launchData);
- // 初始化Launch
- await initData(launchData);
- return launchData;
- } on ApiException catch (_) {
- rethrow;
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Register request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } else {
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Register request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- }
- }
- }
- Future<Launch> login(Map<String, dynamic> params) async {
- while (true) {
- try {
- ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
- final request = fp.toJson();
- request.addAll(params);
- final result = await ApiCore().login(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final launchData = Launch.fromJson(result.data);
- // 注册成功后上报firebase注册事件
- sendAnalytics(FirebaseEvent.login);
- // 保存 Launch 数据
- await IXSP.saveLaunch(launchData);
- // 初始化Launch
- await initData(launchData);
- return launchData;
- } on ApiException catch (_) {
- rethrow;
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Login request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } else {
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'Login request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- }
- }
- }
- Future<Launch> logout() async {
- try {
- final request = fp.toJson();
- final result = await ApiCore().logout(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final launchData = Launch.fromJson(result.data);
- // 登出成功后上报firebase登出事件
- sendAnalytics(FirebaseEvent.logout);
- // 保存 Launch 数据
- await IXSP.saveLaunch(launchData);
- await initData(launchData);
- return launchData;
- } catch (e) {
- rethrow;
- }
- }
- Future<Launch> deleteAccount() async {
- try {
- final request = fp.toJson();
- final result = await ApiCore().deleteAccount(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final launchData = Launch.fromJson(result.data);
- // 登出成功后上报firebase登出事件
- sendAnalytics(FirebaseEvent.deleteAccount);
- // 保存 Launch 数据
- await IXSP.saveLaunch(launchData);
- await initData(launchData);
- return launchData;
- } catch (e) {
- rethrow;
- }
- }
- Future<String> changePassword(Map<String, dynamic> params) async {
- try {
- final request = fp.toJson();
- request.addAll(params);
- final result = await ApiCore().changePassword(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- return result.errorMessage ?? '';
- } catch (e) {
- rethrow;
- }
- }
- Future<Groups> getLocations() async {
- while (true) {
- try {
- ApiCore().setbaseUrl(ApiDomains.instance.getApiUrl());
- final request = fp.toJson();
- final result = await ApiCore().getLocations(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final groups = Groups.fromJson(result.data);
- await IXSP.saveGroups(groups);
- return groups;
- } on ApiException catch (_) {
- rethrow;
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'getLocations request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- } else {
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextApiUrl();
- log(TAG, 'getLocations request failed for URL $url: $e');
- if (url.isEmpty) {
- rethrow;
- }
- ApiCore().setbaseUrl(url);
- }
- }
- }
- Future<List<ChannelPlan>> getChannelPlanList() async {
- try {
- final request = fp.toJson();
- final result = await ApiCore().getChannelPlanList(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final channelPlanList = ChannelPlanList.fromJson(result.data);
- return channelPlanList.list ?? [];
- } catch (e) {
- rethrow;
- }
- }
- Future<Launch> subscribe(Map<String, dynamic> params) async {
- try {
- final request = fp.toJson();
- request.addAll(params);
- final result = await ApiCore().subscribe(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final launchData = Launch.fromJson(result.data);
- // 登出成功后上报firebase登出事件
- sendAnalytics(FirebaseEvent.subscribe);
- // 保存 Launch 数据
- await IXSP.saveLaunch(launchData);
- // 初始化Launch
- await initData(launchData);
- return launchData;
- } catch (e) {
- rethrow;
- }
- }
- Future<Launch> restore() async {
- try {
- final request = fp.toJson();
- final result = await ApiCore().restore(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- final launchData = Launch.fromJson(result.data);
- // 登出成功后上报firebase登出事件
- sendAnalytics(FirebaseEvent.restore);
- // 保存 Launch 数据
- await IXSP.saveLaunch(launchData);
- // 初始化Launch
- await initData(launchData);
- return launchData;
- } catch (e) {
- rethrow;
- }
- }
- Future<void> connected(Map<String, dynamic> params) async {
- try {
- final request = fp.toJson();
- request.addAll(params);
- final result = await ApiRouter().connected(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- } catch (e) {
- rethrow;
- }
- }
- Future<String> uploadLogs(List<dynamic> items, {bool isCache = false}) async {
- await updateFingerprintData();
- Map<String, dynamic> request = fp.toJson();
- request['items'] = items;
- while (true) {
- try {
- ApiLog().setbaseUrl(ApiDomains.instance.getLogUrl());
- final result = await ApiLog().uploadLogs(request);
- if (!result.success) {
- throw Failure(
- code: result.errorCode ?? '',
- message: result.errorMessage ?? '',
- );
- }
- return result.errorMessage ?? '';
- } on ApiException catch (_) {
- rethrow;
- } on Failure catch (_) {
- rethrow;
- } on DioException catch (e) {
- if (e.response?.statusCode == Errors.eRegionNotAvailable ||
- e.response?.statusCode == Errors.eUserDisabled ||
- e.response?.statusCode == Errors.eTokenExpired) {
- if (isCache) {
- await _cacheLogRequest(items);
- }
- rethrow;
- } else {
- if (await NetworkHelper.instance.isNetworkAvailable()) {
- final url = await ApiDomains.instance.getNextLogUrl();
- if (url.isEmpty) {
- if (isCache) {
- await _cacheLogRequest(items);
- }
- rethrow;
- }
- log(
- TAG,
- 'uploadLogs request failed for URL ${ApiLog().baseUrl}: $e',
- );
- ApiLog().setbaseUrl(url);
- } else {
- if (isCache) {
- await _cacheLogRequest(items);
- }
- rethrow;
- }
- }
- } catch (e) {
- final url = await ApiDomains.instance.getNextLogUrl();
- if (url.isEmpty) {
- if (isCache) {
- await _cacheLogRequest(items);
- }
- rethrow;
- }
- log(TAG, 'uploadLogs request failed for URL ${ApiLog().baseUrl}: $e');
- ApiLog().setbaseUrl(url);
- }
- }
- }
- // 缓存日志请求数据
- Future<void> _cacheLogRequest(dynamic items) async {
- try {
- final dir = await getApplicationDocumentsDirectory();
- final cacheDir = Directory('${dir.path}/log_cache');
- if (!await cacheDir.exists()) {
- await cacheDir.create(recursive: true);
- }
- // 生成唯一的文件名
- final timestamp = DateTime.now().millisecondsSinceEpoch;
- final fileName = 'log_$timestamp.json';
- final file = File('${cacheDir.path}/$fileName');
- // 将请求数据写入文件
- await file.writeAsString(jsonEncode(items));
- // 清理缓存目录
- await _cleanupCacheDirectory(cacheDir);
- } catch (e) {
- log(TAG, 'Failed to cache log request: $e');
- }
- }
- // 清理缓存目录
- Future<void> _cleanupCacheDirectory(Directory cacheDir) async {
- try {
- const maxFiles = 10; // 最多保留10个文件
- const maxCacheSize = 5 * 1024 * 1024; // 5MB
- final files = await cacheDir.list().toList();
- // 按修改时间排序
- files.sort(
- (a, b) => a.statSync().modified.compareTo(b.statSync().modified),
- );
- // 计算当前缓存大小
- int totalSize = 0;
- for (var file in files) {
- totalSize += file.statSync().size;
- }
- // 如果超过文件数量或大小限制,删除最旧的文件
- while ((files.length > maxFiles || totalSize > maxCacheSize) &&
- files.isNotEmpty) {
- final oldestFile = files.removeAt(0);
- totalSize -= oldestFile.statSync().size;
- await oldestFile.delete();
- }
- } catch (e) {
- log(TAG, 'Failed to cleanup cache directory: $e');
- }
- }
- Future<void> uploadApiStatisticsLog(
- List<Map<String, dynamic>> logs, {
- LogModule module = LogModule.NM_ApiLaunchLog,
- }) async {
- if (isNeedUploadLogs(module)) {
- await uploadLogs(logs);
- }
- }
- // 判断是否需要上传日志
- bool isNeedUploadLogs(LogModule module) {
- final launch = IXSP.getLaunch();
- if (launch == null) {
- return false;
- }
- if (launch.appConfig?.disabledLogModules?.contains(module.name) ?? false) {
- return false;
- }
- return true;
- }
- /// 获取订阅周期类型文本
- /// subscribeType: 1Day 2Week 3Month 4Year
- String _getSubscribeTypeText() {
- final user = IXSP.getUser();
- final planInfo = user?.planInfo;
- // 仅当 isSubscribe=true 时有效
- if (planInfo?.isSubscribe != true) {
- return planInfo?.subTitle ?? '';
- }
- switch (planInfo?.subscribeType) {
- case 1:
- return 'Day';
- case 2:
- return 'Week';
- case 3:
- return 'Month';
- case 4:
- return 'Year';
- default:
- return '';
- }
- }
- /// 获取过期时间文本
- String _getExpireTimeText() {
- final user = IXSP.getUser();
- final expireTime = user?.expireTime;
- if (expireTime == null || expireTime == 0) {
- return '';
- }
- // 时间戳转日期(秒级时间戳)
- final date = DateTime.fromMillisecondsSinceEpoch(expireTime * 1000);
- final formatted =
- "${date.year.toString().padLeft(4, '0')}-"
- "${date.month.toString().padLeft(2, '0')}-"
- "${date.day.toString().padLeft(2, '0')}";
- return formatted;
- }
- /// 获取有效期显示文本
- String _getValidTermText() {
- final subscribeType = _getSubscribeTypeText();
- final expireTime = _getExpireTimeText();
- if (subscribeType.isNotEmpty && expireTime.isNotEmpty) {
- return '$subscribeType / $expireTime';
- } else if (expireTime.isNotEmpty) {
- return expireTime;
- }
- return '';
- }
- /// 启动剩余时间倒计时
- /// [seconds] 剩余时间(秒),例如:3600 表示 1 小时
- void startRemainTimeCountdown(int seconds) {
- // 取消之前的定时器
- _remainTimeTimer?.cancel();
- // 设置初始剩余时间
- _remainTimeSeconds.value = seconds;
- // 启动每秒倒计时
- _remainTimeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
- if (_remainTimeSeconds.value > 0) {
- _remainTimeSeconds.value--;
- } else {
- // 倒计时结束
- timer.cancel();
- _remainTimeTimer = null;
- _onRemainTimeExpired();
- }
- });
- }
- /// 停止剩余时间倒计时
- void stopRemainTimeCountdown() {
- _remainTimeTimer?.cancel();
- _remainTimeTimer = null;
- }
- /// 更新剩余时间(从服务器获取新的时间后调用)
- void updateRemainTime(int seconds) {
- stopRemainTimeCountdown();
- if (seconds > 0) {
- startRemainTimeCountdown(seconds);
- } else {
- _remainTimeSeconds.value = 0;
- }
- }
- /// 剩余时间到期处理
- void _onRemainTimeExpired() {
- log(TAG, 'VIP剩余时间已到期');
- // 可以在这里添加到期后的处理逻辑,例如:
- // - 显示续费提示
- // - 断开VPN连接
- // - 刷新用户信息
- }
- /// 格式化剩余时间显示
- String _formatRemainTime(int totalSeconds) {
- if (totalSeconds <= 0) {
- return '00:00:00';
- }
- final hours = totalSeconds ~/ 3600;
- final minutes = (totalSeconds % 3600) ~/ 60;
- final seconds = totalSeconds % 60;
- return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
- }
- }
|