core_controller.dart 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 '../../pigeons/core_api.g.dart';
  7. import '../../utils/haptic_feedback_manager.dart';
  8. import '../../utils/log/logger.dart';
  9. import '../constants/enums.dart';
  10. import '../data/models/vpn_message.dart';
  11. import '../dialog/error_dialog.dart';
  12. import '../dialog/feedback_bottom_sheet.dart';
  13. import 'api_controller.dart';
  14. class CoreController extends GetxService {
  15. final TAG = 'CoreController';
  16. final _apiController = Get.find<ApiController>();
  17. final _state = ConnectionState.disconnected.obs;
  18. ConnectionState get state => _state.value;
  19. set state(ConnectionState value) => _state.value = value;
  20. final _timer = "00:00:00".obs;
  21. String get timer => _timer.value;
  22. set timer(String value) => _timer.value = value;
  23. // VPN 事件流订阅
  24. StreamSubscription<String>? _eventSubscription;
  25. CancelToken? _cancelToken;
  26. @override
  27. void onInit() {
  28. super.onInit();
  29. _initCheckConnect();
  30. _startListeningToEvents();
  31. }
  32. @override
  33. void onClose() {
  34. super.onClose();
  35. // 取消事件流订阅
  36. _eventSubscription?.cancel();
  37. _eventSubscription = null;
  38. }
  39. void _initCheckConnect() {
  40. CoreApi().isConnected().then((value) {
  41. if (value == true) {
  42. state = ConnectionState.connected;
  43. CoreApi().reconnect();
  44. } else {
  45. state = ConnectionState.disconnected;
  46. }
  47. });
  48. }
  49. void handleConnection() {
  50. if (state == ConnectionState.disconnected) {
  51. // 开始连接 - 轻微震动
  52. state = ConnectionState.connecting;
  53. HapticFeedbackManager.connectionStart();
  54. getDispatchInfo();
  55. } else {
  56. // 断开连接
  57. CoreApi().disconnect();
  58. }
  59. }
  60. Future<void> getDispatchInfo() async {
  61. // 如果正在请求中,取消当前请求
  62. if (_cancelToken != null) {
  63. log(TAG, '取消当前请求,重新发起新请求');
  64. _cancelToken?.cancel('取消旧请求,发起新请求');
  65. }
  66. // 创建新的 CancelToken
  67. final currentToken = CancelToken();
  68. _cancelToken = currentToken;
  69. try {
  70. final locationId = 187;
  71. final locationCode = 'auto_mm';
  72. final launch = await _apiController.getDispatchInfo(
  73. locationId,
  74. locationCode,
  75. cancelToken: currentToken,
  76. );
  77. // 只有当前 token 没有被替换时才清空
  78. if (_cancelToken == currentToken) {
  79. _cancelToken = null;
  80. }
  81. if (state == ConnectionState.connecting) {
  82. final sessionId = Uuid().v4();
  83. final socksPort = launch.socksPort!;
  84. final tunnelConfig = launch.tunnelConfig!;
  85. final configJson = jsonEncode(launch.nodes);
  86. CoreApi().connect(sessionId, socksPort, tunnelConfig, configJson);
  87. }
  88. } on DioException catch (e) {
  89. // 只有当前 token 没有被替换时才清空
  90. if (_cancelToken == currentToken) {
  91. _cancelToken = null;
  92. }
  93. // 如果是取消错误,不处理
  94. if (e.type == DioExceptionType.cancel) {
  95. log(TAG, '请求已取消');
  96. return;
  97. }
  98. if (state == ConnectionState.connecting) {
  99. state = ConnectionState.disconnected;
  100. }
  101. log(TAG, 'getDispatchInfo error: $e');
  102. } catch (e) {
  103. // 只有当前 token 没有被替换时才清空
  104. if (_cancelToken == currentToken) {
  105. _cancelToken = null;
  106. }
  107. if (state == ConnectionState.connecting) {
  108. state = ConnectionState.disconnected;
  109. }
  110. log(TAG, 'getDispatchInfo error: $e');
  111. }
  112. }
  113. /// 开始监听来自 Android 的事件
  114. void _startListeningToEvents() {
  115. _eventSubscription = onEventChange().listen(
  116. _handleEventChange,
  117. onError: (error) {
  118. log(TAG, '事件流错误: $error');
  119. },
  120. );
  121. }
  122. // 处理从原生端接收到的消息
  123. void _handleEventChange(String message) {
  124. try {
  125. final Map<String, dynamic> json = jsonDecode(message);
  126. final String type = json['type'] ?? '';
  127. switch (type) {
  128. case 'vpn_status':
  129. _handleVpnStatus(VpnStatusMessage.fromJson(json));
  130. break;
  131. case 'timer_update':
  132. _handleTimerUpdate(TimerUpdateMessage.fromJson(json));
  133. break;
  134. default:
  135. log(TAG, '未知消息类型: $type');
  136. }
  137. } catch (e) {
  138. log(TAG, '解析消息失败: $e');
  139. }
  140. }
  141. void _handleVpnStatus(VpnStatusMessage message) {
  142. final vpnError = VpnError.fromValue(message.status);
  143. log(TAG, 'VPN状态变化: ${vpnError.label}, message=${message.message}');
  144. // 根据状态码处理不同的VPN状态
  145. switch (vpnError) {
  146. case VpnError.idle:
  147. // disconnected
  148. _onVpnDisconnected();
  149. break;
  150. case VpnError.connecting:
  151. // connecting
  152. _onVpnConnecting();
  153. break;
  154. case VpnError.connected:
  155. // connected
  156. _onVpnConnected();
  157. break;
  158. case VpnError.error:
  159. // error
  160. _onVpnError();
  161. break;
  162. case VpnError.serviceDisconnected:
  163. // service disconnected
  164. _onVpnServiceDisconnected();
  165. break;
  166. case VpnError.permissionDenied:
  167. // permission denied
  168. _onVpnPermissionDenied();
  169. break;
  170. }
  171. }
  172. void _handleTimerUpdate(TimerUpdateMessage message) {
  173. log(
  174. TAG,
  175. '计时更新: time=${message.currentTime}, mode=${message.mode}, running=${message.isRunning}, paused=${message.isPaused}',
  176. );
  177. timer = _formatTime(message.currentTime);
  178. // 处理计时更新
  179. if (message.isRunning) {
  180. if (message.isPaused) {
  181. _onTimerPaused(message.currentTime, message.mode);
  182. } else {
  183. _onTimerRunning(message.currentTime, message.mode);
  184. }
  185. } else {
  186. _onTimerStopped();
  187. }
  188. }
  189. // VPN状态处理方法
  190. void _onVpnDisconnected() {
  191. log(TAG, 'VPN已断开连接');
  192. // 更新UI状态
  193. state = ConnectionState.disconnected;
  194. timer = "00:00:00";
  195. HapticFeedbackManager.connectionDisconnected();
  196. FeedbackBottomSheet.show();
  197. }
  198. void _onVpnConnecting() {
  199. log(TAG, 'VPN正在连接');
  200. // 显示连接中状态
  201. state = ConnectionState.connecting;
  202. }
  203. void _onVpnConnected() {
  204. log(TAG, 'VPN已连接');
  205. // 显示已连接状态
  206. state = ConnectionState.connected;
  207. HapticFeedbackManager.connectionSuccess();
  208. }
  209. void _onVpnError() {
  210. log(TAG, 'VPN连接错误');
  211. // 显示错误信息
  212. state = ConnectionState.disconnected;
  213. timer = "00:00:00";
  214. HapticFeedbackManager.connectionDisconnected();
  215. }
  216. void _onVpnServiceDisconnected() {
  217. log(TAG, 'VPN服务异常断开连接');
  218. // 显示错误信息
  219. state = ConnectionState.disconnected;
  220. timer = "00:00:00";
  221. HapticFeedbackManager.connectionDisconnected();
  222. // 可以显示错误提示
  223. ErrorDialog.show(message: 'VPN服务异常断开连接');
  224. }
  225. void _onVpnPermissionDenied() {
  226. log(TAG, 'VPN权限拒绝');
  227. // 显示权限拒绝状态
  228. state = ConnectionState.disconnected;
  229. HapticFeedbackManager.connectionDisconnected();
  230. // 可以显示错误提示
  231. ErrorDialog.show(message: '权限拒绝');
  232. }
  233. // 计时器状态处理方法
  234. void _onTimerRunning(int currentTime, int mode) {
  235. log(
  236. TAG,
  237. '计时器运行中: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}',
  238. );
  239. }
  240. void _onTimerPaused(int currentTime, int mode) {
  241. log(
  242. TAG,
  243. '计时器已暂停: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}',
  244. );
  245. }
  246. void _onTimerStopped() {
  247. log(TAG, '计时器已停止');
  248. }
  249. // 格式化时间显示
  250. String _formatTime(int timeMs) {
  251. final totalSeconds = (timeMs / 1000).abs().round();
  252. final days = totalSeconds ~/ 86400; // 86400 = 24 * 3600
  253. final hours = (totalSeconds % 86400) ~/ 3600;
  254. final minutes = (totalSeconds % 3600) ~/ 60;
  255. final seconds = totalSeconds % 60;
  256. if (days > 0) {
  257. return '$days days ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  258. } else if (hours > 0) {
  259. return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  260. } else {
  261. return '00:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  262. }
  263. }
  264. }