home_controller.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:dart_json_mapper/dart_json_mapper.dart';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:get/get.dart';
  6. import 'package:naiyouwl/app/common/constants.dart';
  7. import 'package:naiyouwl/app/component/dialogs.dart';
  8. import 'package:naiyouwl/app/controller/GlobalController.dart';
  9. import 'package:naiyouwl/app/controller/controllers.dart';
  10. import 'package:naiyouwl/app/controller/service.dart';
  11. import 'package:naiyouwl/app/modules/login/views/login_view.dart';
  12. import 'package:naiyouwl/app/utils/system_proxy.dart';
  13. import 'package:naiyouwl/app/utils/utils.dart';
  14. import 'package:tray_manager/tray_manager.dart';
  15. import 'package:url_launcher/url_launcher.dart';
  16. import 'package:window_manager/window_manager.dart';
  17. import '../../../common/LogHelper.dart';
  18. import '../../../common/SharedPreferencesUtil.dart';
  19. import '../../../component/connection_status.dart';
  20. import '../../../data/model/LocalUser.dart';
  21. import '../../../data/model/NodeMode.dart';
  22. import '../../../data/model/SysConfig.dart';
  23. import '../../../data/model/UserMode.dart';
  24. import '../../../network/api_service.dart';
  25. import '../../../routes/app_pages.dart';
  26. enum ImageType {
  27. CUSTOMER,
  28. PROMOTION,
  29. TUTORIAL,
  30. RENEWAL,
  31. }
  32. class HomeController extends GetxController {
  33. //TODO: Implement HomeController
  34. var isLoading = false.obs;
  35. var sysConfig = SysConfig().obs;
  36. var localUsers = LocalUser().obs;
  37. var userMode = User().obs;
  38. var errorMsg = ''.obs;
  39. var UsersysConfig = SysConfig().obs;
  40. var connectStatus = Rx<ConnectionStatus>(ConnectionStatus.disconnected);
  41. var nodeModes = <NodeMode>[];
  42. bool get isRunning => connectStatus.value == ConnectionStatus.stopped && controllers.global.allowStatusUpdate;
  43. late final GlobalController globalController = controllers.global;
  44. StreamSubscription<RunningState>? _statusSubscription;
  45. final Map<ImageType, String> imageMap = {
  46. ImageType.CUSTOMER: "assets/images/main/customer.png",
  47. ImageType.PROMOTION: "assets/images/main/promotion.png",
  48. ImageType.TUTORIAL: "assets/images/main/tutorial.png",
  49. ImageType.RENEWAL: "assets/images/main/renewal.png",
  50. };
  51. void onImageTap(ImageType type) async {
  52. if(type == ImageType.CUSTOMER){
  53. await launchUrl(Uri.parse(UsersysConfig.value.userLoginUrlKe ?? ""));
  54. } else if (type == ImageType.PROMOTION){
  55. await launchUrl(Uri.parse(UsersysConfig.value.affUrl ?? ""));
  56. } else if (type == ImageType.TUTORIAL){
  57. await launchUrl(Uri.parse(UsersysConfig.value.userTicket ?? ""));
  58. } else if (type == ImageType.RENEWAL){
  59. await launchUrl(Uri.parse(UsersysConfig.value.userBuy ?? ""));
  60. }
  61. LogHelper().d("${imageMap[type]} tapped as ${type.toString().split('.').last}");
  62. }
  63. void updateStatus(ConnectionStatus newStatus) {
  64. connectStatus.value = newStatus;
  65. }
  66. void _handleStateChange([dynamic _]) async {
  67. // final coreStatus = controllers.service.coreStatus.value;
  68. // final isVisible = controllers.window.isVisible.value;
  69. // final serviceStatus = controllers.service.serviceStatus.value;
  70. // if(serviceStatus != RunningState.running){
  71. // updateStatus(ConnectionStatus.disconnected);
  72. // return;
  73. // }
  74. // if (coreStatus == RunningState.running && isVisible && controllers.global.allowStatusUpdate) {
  75. // updateStatus(ConnectionStatus.connecting);
  76. // await Future.delayed(const Duration(seconds: 3));
  77. // updateStatus(ConnectionStatus.stopped);
  78. // } else {
  79. // LogHelper().d("stop coreStatus serivce");
  80. // // var routeModes = controllers.global.routeModesSelect.value;
  81. // // if(routeModes != "tun"){
  82. // // controllers.config.clashCoreTunEnable.value = false;
  83. // // }
  84. // // await controllers.global.systemProxySwitch(false);
  85. // updateStatus(ConnectionStatus.disconnected);
  86. // }
  87. }
  88. Future<void> handleButtonClick() async {
  89. if(userMode.value.enable != 1){
  90. errorMsg.value = "用户是禁用的,无法连接";
  91. return;
  92. }
  93. if(connectStatus.value == ConnectionStatus.connecting ){
  94. return;
  95. }
  96. // 如果当前状态是已连接或正在连接,则停止服务
  97. if (connectStatus.value == ConnectionStatus.stopped) {
  98. controllers.global.allowStatusUpdate = false;
  99. await controllers.config.setBreakConnections(true);
  100. // // 停止服务
  101. await controllers.service.stopClash();
  102. await controllers.global.systemProxySwitch(false);
  103. updateStatus(ConnectionStatus.disconnected);
  104. return;
  105. } else {
  106. await controllers.config.setBreakConnections(true);
  107. controllers.global.allowStatusUpdate = true;
  108. var routeModes = controllers.global.routeModesSelect.value;
  109. if(routeModes == "tun"){
  110. controllers.config.clashCoreTunEnable.value = true;
  111. controllers.global.startTunMode();
  112. await controllers.service.startTunService();
  113. final coreStatus = controllers.service.coreStatus.value;
  114. if (coreStatus == RunningState.running){
  115. await controllers.service.reloadClashCore();
  116. }
  117. else{
  118. await controllers.service.startClashCore();
  119. }
  120. } else {
  121. controllers.config.clashCoreTunEnable.value = false;
  122. controllers.global.startSysMode();
  123. final coreStatus = controllers.service.coreStatus.value;
  124. if (coreStatus == RunningState.running){
  125. await controllers.service.reloadClashCore();
  126. }
  127. else{
  128. await controllers.service.startClashCore();
  129. }
  130. await controllers.global.systemProxySwitch(true);
  131. }
  132. updateStatus(ConnectionStatus.connecting);
  133. await Future.delayed(const Duration(seconds: 3));
  134. await controllers.global.updateNode();
  135. await controllers.global.updateDate();
  136. await controllers.tray.updateTray();
  137. updateStatus(ConnectionStatus.stopped);
  138. }
  139. }
  140. void SetSysProxy() async{
  141. }
  142. dynamic showError(BuildContext context) async {
  143. await showNormalDialog(context,
  144. title: '提示',
  145. content: errorMsg.value,
  146. enterText: '确认', cancelText: '',
  147. );
  148. }
  149. Future<void> stopVpn() async {
  150. controllers.global.allowStatusUpdate = false;
  151. await controllers.config.setBreakConnections(true);
  152. // // 停止服务
  153. await controllers.service.stopClashCore();
  154. await controllers.global.systemProxySwitch(false);
  155. updateStatus(ConnectionStatus.disconnected);
  156. }
  157. Future<void> fetchAuthUser() async {
  158. try {
  159. final ret = await ApiService().fetchAuthUser(KAuthUser);
  160. controllers.global.selectedNode.value = ret;
  161. controllers.global.selectNode(ret);
  162. await handleButtonClick();
  163. } catch (e) {
  164. errorMsg.value = e.toString();
  165. } finally {
  166. }
  167. }
  168. Future<void> fetchSysConfig() async {
  169. try {
  170. String? data = await SharedPreferencesUtil().getString("sysconfig");
  171. if(data != null){
  172. sysConfig.value =JsonMapper.deserialize<SysConfig>(data)!;
  173. }
  174. } catch (e) {
  175. errorMsg.value = e.toString();
  176. } finally {
  177. }
  178. }
  179. Future<void> fetchUserinfo() async {
  180. try {
  181. isLoading.value = true;
  182. userMode.value = await ApiService().userinfo("/api/client/v4/userinfo");
  183. await globalController.fetchNodes();
  184. await fetchlUserUrl(localUsers.value.email ?? "",localUsers.value.password ?? "");
  185. //await controllers.global.makeProxy();
  186. //await controllers.global.initService();
  187. // //生成配置
  188. // await controllers.global.makeProxy();
  189. // // 开始重启服务
  190. // await controllers.service.reloadClashCore();
  191. } catch (e) {
  192. errorMsg.value = e.toString();
  193. } finally {
  194. isLoading.value = false;
  195. }
  196. }
  197. Future<void> fetchNode() async {
  198. try {
  199. isLoading.value = true;
  200. await globalController.fetchNodes();
  201. } catch (e) {
  202. errorMsg.value = e.toString();
  203. } finally {
  204. isLoading.value = false;
  205. }
  206. }
  207. Future<void> outlogin() async {
  208. if(connectStatus.value == ConnectionStatus.connecting || connectStatus.value == ConnectionStatus.stopped){
  209. errorMsg.value = "先断开,在退出登录";
  210. return ;
  211. }
  212. await SharedPreferencesUtil().delete("token");
  213. try {
  214. isLoading.value = true;
  215. await ApiService().fetchLogout(KLogout);
  216. } catch (e) {
  217. errorMsg.value = e.toString();
  218. } finally {
  219. isLoading.value = false;
  220. }
  221. Get.offNamed(Routes.LOGIN);
  222. }
  223. //await SharedPreferencesUtil().setObject("localUser", userModes.toJson());
  224. Future<void> fetchlUserUrl(String username,String password) async {
  225. try {
  226. isLoading.value = true;
  227. UsersysConfig.value = await ApiService().fetchUserSysConfig(kSysConfig,{"email":username,"password":password});
  228. } catch (e) {
  229. errorMsg.value = e.toString();
  230. } finally {
  231. isLoading.value = false;
  232. }
  233. }
  234. Future<void> fetchLocalUser() async {
  235. try {
  236. String? userdata = await SharedPreferencesUtil().getString("localUser");
  237. if(userdata != null){
  238. localUsers.value = JsonMapper.deserialize<LocalUser>(userdata)!;
  239. }
  240. await fetchSysConfig();
  241. } catch (e) {
  242. errorMsg.value = e.toString();
  243. } finally {
  244. }
  245. }
  246. final count = 0.obs;
  247. @override
  248. void onInit() {
  249. super.onInit();
  250. _statusSubscription = controllers.service.coreStatus.stream.listen(_handleStateChange);
  251. fetchSysConfig();
  252. fetchLocalUser();
  253. fetchUserinfo();
  254. //controllers.global.initService();
  255. }
  256. @override
  257. void onReady() {
  258. super.onReady();
  259. }
  260. @override
  261. void onClose() {
  262. _statusSubscription?.cancel();
  263. super.onClose();
  264. }
  265. bool GetEnable() => userMode.value.enable == 1;
  266. String GetUserName() => localUsers.value.email.toString();
  267. String GetExpiredAt() => "到期时间:${userMode.value.expiredAt}";
  268. String GetTraffic() => "用户流量:${userMode.value.unusedTraffic}";
  269. String GetNode() => controllers.global.selectedNode.value?.name ?? "未选择节点";
  270. String getHttp() => "http 127.0.0.1:${controllers.core.config.value.mixedPort}";
  271. String getSocket() => "socks 127.0.0.1:${controllers.core.config.value.mixedPort}";
  272. void RouteNode() => Get.toNamed(Routes.NODE);
  273. }