core_controller.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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:get/get.dart';
  7. import 'package:package_info_plus/package_info_plus.dart';
  8. import 'package:uuid/uuid.dart';
  9. import '../../config/translations/strings_enum.dart';
  10. import '../../pigeons/core_api.g.dart';
  11. import '../../utils/boost_report_manager.dart';
  12. import '../../utils/haptic_feedback_manager.dart';
  13. import '../../utils/log/logger.dart';
  14. import '../../utils/network_helper.dart';
  15. import '../components/ix_snackbar.dart';
  16. import '../constants/enums.dart';
  17. import '../data/models/api_exception.dart';
  18. import '../data/models/failure.dart';
  19. import '../data/models/vpn_message.dart';
  20. import '../data/sp/ix_sp.dart';
  21. import '../dialog/error_dialog.dart';
  22. import '../dialog/feedback_bottom_sheet.dart';
  23. import 'api_controller.dart';
  24. class CoreController extends GetxService {
  25. final TAG = 'CoreController';
  26. final _apiController = Get.find<ApiController>();
  27. final _state = ConnectionState.disconnected.obs;
  28. ConnectionState get state => _state.value;
  29. set state(ConnectionState value) => _state.value = value;
  30. // 公开状态流供外部监听
  31. Rx<ConnectionState> get stateStream => _state;
  32. final _timer = "00:00:00".obs;
  33. String get timer => _timer.value;
  34. set timer(String value) => _timer.value = value;
  35. // VPN 事件流订阅
  36. StreamSubscription<String>? _eventSubscription;
  37. CancelToken? _cancelToken;
  38. //全局uuid
  39. final _globalUuid = Uuid().v4();
  40. String locationSelectionType = 'auto';
  41. @override
  42. void onInit() {
  43. super.onInit();
  44. _initCheckConnect();
  45. _startListeningToEvents();
  46. }
  47. @override
  48. void onClose() {
  49. super.onClose();
  50. // 取消事件流订阅
  51. _eventSubscription?.cancel();
  52. _eventSubscription = null;
  53. }
  54. void _initCheckConnect() {
  55. CoreApi().isConnected().then((value) {
  56. if (value == true) {
  57. state = ConnectionState.connected;
  58. CoreApi().reconnect();
  59. } else {
  60. state = ConnectionState.disconnected;
  61. }
  62. });
  63. }
  64. void handleConnection() {
  65. if (state == ConnectionState.disconnected) {
  66. // 开始连接 - 轻微震动
  67. state = ConnectionState.connecting;
  68. HapticFeedbackManager.connectionStart();
  69. getDispatchInfo();
  70. } else {
  71. // 断开连接
  72. CoreApi().disconnect();
  73. }
  74. }
  75. void selectLocationConnect() {
  76. if (state != ConnectionState.disconnected) {
  77. CoreApi().disconnect();
  78. // 延迟300ms
  79. Future.delayed(const Duration(milliseconds: 300), () {
  80. state = ConnectionState.connecting;
  81. getDispatchInfo();
  82. });
  83. } else {
  84. handleConnection();
  85. }
  86. }
  87. Future<void> getDispatchInfo() async {
  88. // 如果正在请求中,取消当前请求
  89. if (_cancelToken != null) {
  90. log(TAG, '取消当前请求,重新发起新请求');
  91. _cancelToken?.cancel('取消旧请求,发起新请求');
  92. }
  93. // 创建新的 CancelToken
  94. final currentToken = CancelToken();
  95. _cancelToken = currentToken;
  96. // 创建一条加速日志
  97. await createBoostLog();
  98. try {
  99. final locationId = IXSP.getSelectedLocation()?['id'];
  100. final locationCode = IXSP.getSelectedLocation()?['code'];
  101. final launch = await _apiController.getDispatchInfo(
  102. locationId,
  103. locationCode,
  104. cancelToken: currentToken,
  105. );
  106. // 只有当前 token 没有被替换时才清空
  107. if (_cancelToken == currentToken) {
  108. _cancelToken = null;
  109. }
  110. if (state == ConnectionState.connecting) {
  111. final sessionId = Uuid().v4();
  112. final socksPort = launch.nodesConfig!.socketPort!;
  113. final tunnelConfig = launch.nodesConfig!.tunnelConfig!;
  114. final configJson = jsonEncode(launch.nodesConfig!);
  115. CoreApi().connect(sessionId, socksPort, tunnelConfig, configJson);
  116. }
  117. } on DioException catch (e, s) {
  118. // 只有当前 token 没有被替换时才清空
  119. if (_cancelToken == currentToken) {
  120. _cancelToken = null;
  121. }
  122. // 如果是取消错误,不处理
  123. if (e.type == DioExceptionType.cancel) {
  124. log(TAG, '请求已取消');
  125. return;
  126. }
  127. if (state == ConnectionState.connecting) {
  128. state = ConnectionState.disconnected;
  129. }
  130. handleErrorDialog(e, s);
  131. log(TAG, 'getDispatchInfo error: $e');
  132. } catch (e, s) {
  133. // 只有当前 token 没有被替换时才清空
  134. if (_cancelToken == currentToken) {
  135. _cancelToken = null;
  136. }
  137. if (state == ConnectionState.connecting) {
  138. state = ConnectionState.disconnected;
  139. }
  140. handleErrorDialog(e, s);
  141. log(TAG, 'getDispatchInfo error: $e');
  142. }
  143. }
  144. /// 开始监听来自 Android 的事件
  145. void _startListeningToEvents() {
  146. _eventSubscription = onEventChange().listen(
  147. _handleEventChange,
  148. onError: (error) {
  149. log(TAG, '事件流错误: $error');
  150. },
  151. );
  152. }
  153. // 处理从原生端接收到的消息
  154. void _handleEventChange(String message) {
  155. try {
  156. final Map<String, dynamic> json = jsonDecode(message);
  157. final String type = json['type'] ?? '';
  158. switch (type) {
  159. case 'vpn_status':
  160. _handleVpnStatus(VpnStatusMessage.fromJson(json));
  161. break;
  162. case 'timer_update':
  163. _handleTimerUpdate(TimerUpdateMessage.fromJson(json));
  164. break;
  165. default:
  166. log(TAG, '未知消息类型: $type');
  167. }
  168. } catch (e) {
  169. log(TAG, '解析消息失败: $e');
  170. }
  171. }
  172. void _handleVpnStatus(VpnStatusMessage message) {
  173. final vpnError = VpnStatus.fromValue(message.status);
  174. log(
  175. TAG,
  176. 'VPN状态变化: ${vpnError.label}, status=${message.status}, message=${message.message}',
  177. );
  178. // 根据状态码处理不同的VPN状态
  179. switch (vpnError) {
  180. case VpnStatus.idle:
  181. // disconnected
  182. _onVpnDisconnected();
  183. break;
  184. case VpnStatus.connecting:
  185. // connecting
  186. _onVpnConnecting();
  187. break;
  188. case VpnStatus.connected:
  189. // connected
  190. _onVpnConnected();
  191. break;
  192. case VpnStatus.error:
  193. // error
  194. _onVpnError(message.message);
  195. break;
  196. case VpnStatus.serviceDisconnected:
  197. // service disconnected
  198. _onVpnServiceDisconnected();
  199. break;
  200. case VpnStatus.permissionDenied:
  201. // permission denied
  202. _onVpnPermissionDenied();
  203. break;
  204. }
  205. }
  206. void _handleTimerUpdate(TimerUpdateMessage message) {
  207. log(
  208. TAG,
  209. '计时更新: time=${message.currentTime}, mode=${message.mode}, running=${message.isRunning}, paused=${message.isPaused}',
  210. );
  211. timer = _formatTime(message.currentTime);
  212. // 处理计时更新
  213. if (message.isRunning) {
  214. if (message.isPaused) {
  215. _onTimerPaused(message.currentTime, message.mode);
  216. } else {
  217. _onTimerRunning(message.currentTime, message.mode);
  218. }
  219. } else {
  220. _onTimerStopped();
  221. }
  222. }
  223. // VPN状态处理方法
  224. void _onVpnDisconnected() {
  225. log(TAG, 'VPN已断开连接');
  226. // 更新UI状态
  227. state = ConnectionState.disconnected;
  228. timer = "00:00:00";
  229. HapticFeedbackManager.connectionDisconnected();
  230. FeedbackBottomSheet.show();
  231. }
  232. void _onVpnConnecting() {
  233. log(TAG, 'VPN正在连接');
  234. // 显示连接中状态
  235. state = ConnectionState.connecting;
  236. }
  237. void _onVpnConnected() {
  238. log(TAG, 'VPN已连接');
  239. // 显示已连接状态
  240. state = ConnectionState.connected;
  241. HapticFeedbackManager.connectionSuccess();
  242. }
  243. void _onVpnError(String message) {
  244. log(TAG, 'VPN连接错误');
  245. // 显示错误信息
  246. state = ConnectionState.disconnected;
  247. timer = "00:00:00";
  248. HapticFeedbackManager.connectionDisconnected();
  249. ErrorDialog.show(
  250. message: message == 'null' ? Strings.vpnConnectionError.tr : message,
  251. );
  252. }
  253. void _onVpnServiceDisconnected() {
  254. log(TAG, 'VPN服务异常断开连接');
  255. // 显示错误信息
  256. state = ConnectionState.disconnected;
  257. timer = "00:00:00";
  258. HapticFeedbackManager.connectionDisconnected();
  259. // 可以显示错误提示
  260. ErrorDialog.show(message: Strings.vpnServiceDisconnected.tr);
  261. }
  262. void _onVpnPermissionDenied() {
  263. log(TAG, 'VPN权限拒绝');
  264. // 显示权限拒绝状态
  265. state = ConnectionState.disconnected;
  266. HapticFeedbackManager.connectionDisconnected();
  267. // 可以显示错误提示
  268. ErrorDialog.show(message: '权限拒绝');
  269. }
  270. // 计时器状态处理方法
  271. void _onTimerRunning(int currentTime, int mode) {
  272. log(
  273. TAG,
  274. '计时器运行中: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}',
  275. );
  276. }
  277. void _onTimerPaused(int currentTime, int mode) {
  278. log(
  279. TAG,
  280. '计时器已暂停: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}',
  281. );
  282. }
  283. void _onTimerStopped() {
  284. log(TAG, '计时器已停止');
  285. }
  286. // 格式化时间显示
  287. String _formatTime(int timeMs) {
  288. final totalSeconds = (timeMs / 1000).abs().round();
  289. final days = totalSeconds ~/ 86400; // 86400 = 24 * 3600
  290. final hours = (totalSeconds % 86400) ~/ 3600;
  291. final minutes = (totalSeconds % 3600) ~/ 60;
  292. final seconds = totalSeconds % 60;
  293. if (days > 0) {
  294. return '$days days ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  295. } else if (hours > 0) {
  296. return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  297. } else {
  298. return '00:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  299. }
  300. }
  301. void handleSnackBarError(dynamic error, StackTrace stackTrace) {
  302. if (error is ApiException) {
  303. IXSnackBar.showIXErrorSnackBar(
  304. title: Strings.error.tr,
  305. message: error.message,
  306. );
  307. } else if (error is Failure) {
  308. IXSnackBar.showIXErrorSnackBar(
  309. title: Strings.error.tr,
  310. message: error.message ?? Strings.unknownError.tr,
  311. );
  312. } else if (error is DioException) {
  313. switch (error.type) {
  314. case DioExceptionType.connectionError:
  315. case DioExceptionType.connectionTimeout:
  316. case DioExceptionType.receiveTimeout:
  317. case DioExceptionType.sendTimeout:
  318. IXSnackBar.showIXErrorSnackBar(
  319. title: Strings.error.tr,
  320. message: Strings.unableToConnectNetwork.tr,
  321. );
  322. break;
  323. default:
  324. IXSnackBar.showIXErrorSnackBar(
  325. title: Strings.error.tr,
  326. message: Strings.unableToConnectServer.tr,
  327. );
  328. }
  329. } else {
  330. IXSnackBar.showIXErrorSnackBar(
  331. title: Strings.error.tr,
  332. message: error.toString(),
  333. );
  334. }
  335. }
  336. void handleErrorDialog(dynamic error, StackTrace stackTrace) {
  337. if (error is ApiException) {
  338. ErrorDialog.show(title: Strings.error.tr, message: error.message);
  339. } else if (error is Failure) {
  340. ErrorDialog.show(
  341. title: Strings.error.tr,
  342. message: error.message ?? Strings.unknownError.tr,
  343. );
  344. } else if (error is DioException) {
  345. switch (error.type) {
  346. case DioExceptionType.connectionError:
  347. case DioExceptionType.connectionTimeout:
  348. case DioExceptionType.receiveTimeout:
  349. case DioExceptionType.sendTimeout:
  350. ErrorDialog.show(
  351. title: Strings.error.tr,
  352. message: Strings.unableToConnectNetwork.tr,
  353. );
  354. break;
  355. default:
  356. ErrorDialog.show(
  357. title: Strings.error.tr,
  358. message: Strings.unableToConnectServer.tr,
  359. );
  360. }
  361. } else {
  362. ErrorDialog.show(title: Strings.error.tr, message: error.toString());
  363. }
  364. }
  365. // 创建一条加速日志
  366. Future<void> createBoostLog() async {
  367. await initLog();
  368. await setSessionInfoLog();
  369. await setTargetInfoLog();
  370. }
  371. // 初始化日志
  372. Future<void> initLog() async {
  373. await BoostReportManager().init();
  374. }
  375. // 读取历史日志
  376. Future<void> readHistoryLog() async {
  377. await BoostReportManager().readHistoryLog();
  378. }
  379. // 初始化会话日志
  380. Future<void> setSessionInfoLog() async {
  381. final deviceInfoPlugin = DeviceInfoPlugin();
  382. final appVersion = await PackageInfo.fromPlatform().then(
  383. (value) => value.version,
  384. );
  385. final networkType = await NetworkHelper.instance.getNetworkType();
  386. Map<String, String> deviceInfo = {};
  387. if (Platform.isIOS) {
  388. final iosOsInfo = await deviceInfoPlugin.iosInfo;
  389. deviceInfo = {
  390. 'deviceModel': iosOsInfo.model,
  391. 'osVersion': iosOsInfo.systemVersion,
  392. 'appVersion': appVersion,
  393. 'networkType': networkType,
  394. 'deviceBrand': iosOsInfo.utsname.machine,
  395. };
  396. } else if (Platform.isAndroid) {
  397. final androidOsInfo = await deviceInfoPlugin.androidInfo;
  398. deviceInfo = {
  399. 'deviceModel': androidOsInfo.model,
  400. 'osVersion': androidOsInfo.version.release,
  401. 'appVersion': appVersion,
  402. 'networkType': networkType,
  403. 'deviceBrand': androidOsInfo.brand,
  404. };
  405. }
  406. final boostSessionId = Uuid().v4();
  407. await BoostReportManager().initSessionInfo(
  408. appSessionId: _globalUuid,
  409. boostSessionId: boostSessionId,
  410. deviceInfo: deviceInfo,
  411. );
  412. }
  413. // 初始化目标信息
  414. Future<void> setTargetInfoLog() async {
  415. await BoostReportManager().addTargetInfo(
  416. locationSelectionType: locationSelectionType,
  417. location: IXSP.getSelectedLocation(),
  418. );
  419. }
  420. }