core_controller.dart 11 KB

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