core_controller.dart 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 '../widgets/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. // 事件流订阅
  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. state = ConnectionState.disconnecting;
  58. CoreApi().disconnect();
  59. }
  60. }
  61. Future<void> getDispatchInfo() async {
  62. // 如果正在请求中,取消当前请求
  63. if (_cancelToken != null) {
  64. log(TAG, '取消当前请求,重新发起新请求');
  65. _cancelToken?.cancel('取消旧请求,发起新请求');
  66. }
  67. // 创建新的 CancelToken
  68. final currentToken = CancelToken();
  69. _cancelToken = currentToken;
  70. try {
  71. final launch = await _apiController.getDispatchInfo(
  72. cancelToken: currentToken,
  73. );
  74. // 只有当前 token 没有被替换时才清空
  75. if (_cancelToken == currentToken) {
  76. _cancelToken = null;
  77. }
  78. if (state == ConnectionState.connecting) {
  79. final sessionId = Uuid().v4();
  80. final socksPort = launch.socksPort!;
  81. final tunnelConfig = launch.tunnelConfig!;
  82. final configJson = jsonEncode(launch.nodes);
  83. CoreApi().connect(sessionId, socksPort, tunnelConfig, configJson);
  84. }
  85. } on DioException catch (e) {
  86. // 只有当前 token 没有被替换时才清空
  87. if (_cancelToken == currentToken) {
  88. _cancelToken = null;
  89. }
  90. // 如果是取消错误,不处理
  91. if (e.type == DioExceptionType.cancel) {
  92. log(TAG, '请求已取消');
  93. return;
  94. }
  95. if (state == ConnectionState.connecting) {
  96. state = ConnectionState.disconnected;
  97. }
  98. log(TAG, 'getDispatchInfo error: $e');
  99. } catch (e) {
  100. // 只有当前 token 没有被替换时才清空
  101. if (_cancelToken == currentToken) {
  102. _cancelToken = null;
  103. }
  104. if (state == ConnectionState.connecting) {
  105. state = ConnectionState.disconnected;
  106. }
  107. log(TAG, 'getDispatchInfo error: $e');
  108. }
  109. }
  110. /// 开始监听来自 Android 的事件
  111. void _startListeningToEvents() {
  112. _eventSubscription = onEventChange().listen(
  113. _handleEventChange,
  114. onError: (error) {
  115. log(TAG, '事件流错误: $error');
  116. },
  117. );
  118. }
  119. // 处理从原生端接收到的消息
  120. void _handleEventChange(String message) {
  121. try {
  122. final Map<String, dynamic> json = jsonDecode(message);
  123. final String type = json['type'] ?? '';
  124. switch (type) {
  125. case 'vpn_status':
  126. _handleVpnStatus(VpnStatusMessage.fromJson(json));
  127. break;
  128. case 'timer_update':
  129. _handleTimerUpdate(TimerUpdateMessage.fromJson(json));
  130. break;
  131. default:
  132. log(TAG, '未知消息类型: $type');
  133. }
  134. } catch (e) {
  135. log(TAG, '解析消息失败: $e');
  136. }
  137. }
  138. void _handleVpnStatus(VpnStatusMessage message) {
  139. log(TAG, 'VPN状态变化: status=${message.status}, message=${message.message}');
  140. // 根据状态码处理不同的VPN状态
  141. switch (message.status) {
  142. case 0:
  143. // disconnected
  144. _onVpnDisconnected();
  145. break;
  146. case 1:
  147. // connecting
  148. _onVpnConnecting();
  149. break;
  150. case 2:
  151. // connected
  152. _onVpnConnected();
  153. break;
  154. case 3:
  155. // error
  156. _onVpnError(message.message);
  157. break;
  158. case 4:
  159. // disconnecting
  160. _onVpnDisconnecting();
  161. break;
  162. case 403:
  163. // permission denied
  164. _onVpnPermissionDenied();
  165. break;
  166. default:
  167. log(TAG, '未知VPN状态: ${message.status}');
  168. }
  169. }
  170. void _handleTimerUpdate(TimerUpdateMessage message) {
  171. log(
  172. TAG,
  173. '计时更新: time=${message.currentTime}, mode=${message.mode}, running=${message.isRunning}, paused=${message.isPaused}',
  174. );
  175. timer = _formatTime(message.currentTime);
  176. // 处理计时更新
  177. if (message.isRunning) {
  178. if (message.isPaused) {
  179. _onTimerPaused(message.currentTime, message.mode);
  180. } else {
  181. _onTimerRunning(message.currentTime, message.mode);
  182. }
  183. } else {
  184. _onTimerStopped();
  185. }
  186. }
  187. // VPN状态处理方法
  188. void _onVpnDisconnected() {
  189. log(TAG, 'VPN已断开连接');
  190. // 更新UI状态
  191. state = ConnectionState.disconnected;
  192. timer = "00:00:00";
  193. HapticFeedbackManager.connectionDisconnected();
  194. FeedbackBottomSheet.show();
  195. }
  196. void _onVpnConnecting() {
  197. log(TAG, 'VPN正在连接');
  198. // 显示连接中状态
  199. state = ConnectionState.connecting;
  200. }
  201. void _onVpnConnected() {
  202. log(TAG, 'VPN已连接');
  203. // 显示已连接状态
  204. state = ConnectionState.connected;
  205. HapticFeedbackManager.connectionSuccess();
  206. }
  207. void _onVpnError(String errorMessage) {
  208. log(TAG, 'VPN连接错误: $errorMessage');
  209. // 显示错误信息
  210. state = ConnectionState.disconnected;
  211. timer = "00:00:00";
  212. HapticFeedbackManager.connectionDisconnected();
  213. // 可以显示错误提示
  214. ErrorDialog.show(message: errorMessage);
  215. }
  216. void _onVpnDisconnecting() {
  217. log(TAG, 'VPN正在断开连接');
  218. // 显示断开连接状态
  219. state = ConnectionState.disconnecting;
  220. }
  221. void _onVpnPermissionDenied() {
  222. log(TAG, 'VPN权限拒绝');
  223. // 显示权限拒绝状态
  224. state = ConnectionState.disconnected;
  225. HapticFeedbackManager.connectionDisconnected();
  226. // 可以显示错误提示
  227. ErrorDialog.show(message: '权限拒绝');
  228. }
  229. // 计时器状态处理方法
  230. void _onTimerRunning(int currentTime, int mode) {
  231. log(
  232. TAG,
  233. '计时器运行中: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}',
  234. );
  235. }
  236. void _onTimerPaused(int currentTime, int mode) {
  237. log(
  238. TAG,
  239. '计时器已暂停: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}',
  240. );
  241. }
  242. void _onTimerStopped() {
  243. log(TAG, '计时器已停止');
  244. }
  245. // 格式化时间显示
  246. String _formatTime(int timeMs) {
  247. final totalSeconds = (timeMs / 1000).abs().round();
  248. final days = totalSeconds ~/ 86400; // 86400 = 24 * 3600
  249. final hours = (totalSeconds % 86400) ~/ 3600;
  250. final minutes = (totalSeconds % 3600) ~/ 60;
  251. final seconds = totalSeconds % 60;
  252. if (days > 0) {
  253. return '$days days ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  254. } else if (hours > 0) {
  255. return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  256. } else {
  257. return '00:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  258. }
  259. }
  260. }