home_controller.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import 'package:get/get.dart';
  2. import 'package:nomo/app/controllers/api_controller.dart';
  3. import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
  4. import '../../../../utils/system_helper.dart';
  5. import '../../../controllers/base_core_api.dart';
  6. import '../../../../utils/awesome_notifications_helper.dart';
  7. import '../../../../utils/log/logger.dart';
  8. import '../../../base/base_controller.dart';
  9. import '../../../constants/enums.dart';
  10. import '../../../controllers/core_controller.dart';
  11. import '../../../data/models/banner/banner_list.dart';
  12. import '../../../data/models/launch/groups.dart';
  13. import '../../../data/sp/ix_sp.dart';
  14. import '../../../dialog/error_dialog.dart';
  15. import '../../../routes/app_pages.dart';
  16. /// 主页控制器
  17. class HomeController extends BaseController {
  18. final coreController = Get.find<CoreController>();
  19. final apiController = Get.find<ApiController>();
  20. final TAG = 'HomeController';
  21. final _refreshController = RefreshController(initialRefresh: false);
  22. RefreshController get refreshController => _refreshController;
  23. final _currentBannerIndex = 0.obs;
  24. int get currentBannerIndex => _currentBannerIndex.value;
  25. set currentBannerIndex(int value) => _currentBannerIndex.value = value;
  26. // 最近位置是否展开
  27. final _isRecentLocationsExpanded = false.obs;
  28. bool get isRecentLocationsExpanded => _isRecentLocationsExpanded.value;
  29. set isRecentLocationsExpanded(bool value) =>
  30. _isRecentLocationsExpanded.value = value;
  31. /// 收起最近位置列表
  32. void collapseRecentLocations() {
  33. if (_isRecentLocationsExpanded.value) {
  34. _isRecentLocationsExpanded.value = false;
  35. }
  36. }
  37. // 统计信息
  38. final _uplinkBytes = 0.obs;
  39. final _downlinkBytes = 0.obs;
  40. int get uplinkBytes => _uplinkBytes.value;
  41. int get downlinkBytes => _downlinkBytes.value;
  42. // 延迟信息
  43. final _currentDelay = 0.obs;
  44. int get currentDelay => _currentDelay.value;
  45. // 当前选择的位置
  46. final _selectedLocation = Rxn<Locations>();
  47. Locations? get selectedLocation => _selectedLocation.value;
  48. set selectedLocation(Locations? value) => _selectedLocation.value = value;
  49. // 最近使用的位置列表
  50. final _recentLocations = <Locations>[].obs;
  51. List<Locations> get recentLocations =>
  52. _recentLocations.where((loc) => loc.id != selectedLocation?.id).toList();
  53. // Banner 列表
  54. final _bannerList = <Banner>[].obs;
  55. List<Banner> get bannerList => _bannerList;
  56. set bannerList(List<Banner> value) => _bannerList.assignAll(value);
  57. // Banner 列表
  58. final _nineBannerList = <Banner>[].obs;
  59. List<Banner> get nineBannerList => _nineBannerList;
  60. set nineBannerList(List<Banner> value) => _nineBannerList.assignAll(value);
  61. @override
  62. void onInit() {
  63. super.onInit();
  64. _initializeLocations();
  65. getBanner(position: 'nine');
  66. getBanner(position: 'banner');
  67. AwesomeNotificationsHelper.init();
  68. AwesomeNotificationsHelper.showPushNoticeDialog();
  69. checkUpdate();
  70. }
  71. Future<void> checkUpdate() async {
  72. final isVpnRunning = await BaseCoreApi().isConnected() ?? false;
  73. if (!isVpnRunning) {
  74. await apiController.checkUpdate();
  75. }
  76. }
  77. /// 初始化位置数据
  78. void _initializeLocations() {
  79. // 从 SharedPreferences 加载保存的节点数据
  80. _loadSavedLocations();
  81. }
  82. /// 从 SharedPreferences 加载保存的节点数据
  83. void _loadSavedLocations() {
  84. try {
  85. // 加载当前选中的节点
  86. final selectedLocationData = IXSP.getSelectedLocation();
  87. if (selectedLocationData != null) {
  88. final savedLocation = Locations.fromJson(selectedLocationData);
  89. // 检查保存的节点是否存在于当前 groups 中
  90. if (_isLocationExistsInGroups(savedLocation)) {
  91. selectedLocation = savedLocation;
  92. } else {
  93. // 如果节点不存在于 groups 中,选中第一个可用节点
  94. // 如果当前节点是连接中的状态,则断开连接
  95. if (coreController.state != ConnectionState.disconnected) {
  96. BaseCoreApi().disconnect();
  97. }
  98. log(
  99. TAG,
  100. 'Saved location not found in groups, selecting first available',
  101. );
  102. _selectFirstAvailableLocation();
  103. }
  104. } else {
  105. // 如果没有保存的节点,选中第一个可用节点
  106. _selectFirstAvailableLocation();
  107. }
  108. // 加载最近选择的节点列表
  109. final recentLocationsData = IXSP.getRecentLocations();
  110. if (recentLocationsData.isNotEmpty) {
  111. _recentLocations.assignAll(
  112. recentLocationsData.map((e) => Locations.fromJson(e)).toList(),
  113. );
  114. }
  115. } catch (e) {
  116. log(TAG, 'Error loading saved locations: $e');
  117. }
  118. }
  119. /// 检查节点是否存在于当前 groups 中
  120. bool _isLocationExistsInGroups(Locations location) {
  121. final launch = IXSP.getLaunch();
  122. final groups = launch?.groups;
  123. if (groups == null) return false;
  124. // 检查 normal 列表
  125. if (groups.normal?.list != null) {
  126. for (var locationList in groups.normal!.list!) {
  127. if (locationList.locations != null) {
  128. for (var loc in locationList.locations!) {
  129. if (loc.id == location.id) {
  130. return true;
  131. }
  132. }
  133. }
  134. }
  135. }
  136. // 检查 streaming 列表
  137. if (groups.streaming?.list != null) {
  138. for (var locationList in groups.streaming!.list!) {
  139. if (locationList.locations != null) {
  140. for (var loc in locationList.locations!) {
  141. if (loc.id == location.id) {
  142. return true;
  143. }
  144. }
  145. }
  146. }
  147. }
  148. return false;
  149. }
  150. /// 选中第一个可用节点
  151. void _selectFirstAvailableLocation() {
  152. try {
  153. final launch = IXSP.getLaunch();
  154. final normalList = launch?.groups?.normal?.list;
  155. if (normalList != null && normalList.isNotEmpty) {
  156. // 遍历找到第一个有可用节点的国家
  157. for (var locationList in normalList) {
  158. if (locationList.locations != null &&
  159. locationList.locations!.isNotEmpty) {
  160. // 选中第一个节点
  161. final firstLocation = locationList.locations!.first;
  162. selectLocation(firstLocation);
  163. break;
  164. }
  165. }
  166. }
  167. } catch (e) {
  168. log(TAG, 'Error selecting first available location: $e');
  169. }
  170. }
  171. /// 选择位置
  172. void selectLocation(
  173. Locations location, {
  174. String locationSelectionType = 'auto',
  175. }) {
  176. selectedLocation = location;
  177. coreController.locationSelectionType = locationSelectionType;
  178. // 更新最近使用列表
  179. _updateRecentLocations(location);
  180. // 保存到 SharedPreferences
  181. _saveLocationsToStorage();
  182. }
  183. // 从节点列表中选择节点后需要延迟300ms
  184. void handleConnect({bool delay = false}) {
  185. if (delay) {
  186. // 延迟300ms
  187. Future.delayed(const Duration(milliseconds: 300), () {
  188. coreController.selectLocationConnect();
  189. });
  190. } else {
  191. coreController.selectLocationConnect();
  192. }
  193. }
  194. /// 更新最近使用的位置列表
  195. void _updateRecentLocations(Locations location) {
  196. // 移除已存在的位置
  197. _recentLocations.removeWhere((loc) => loc.id == location.id);
  198. // 添加到列表开头
  199. _recentLocations.insert(0, location);
  200. // 保持最多4个最近使用的位置(过滤掉当前选中后能显示3个)
  201. if (_recentLocations.length > 4) {
  202. _recentLocations.removeRange(4, _recentLocations.length);
  203. }
  204. }
  205. /// 保存位置数据到 SharedPreferences
  206. void _saveLocationsToStorage() {
  207. try {
  208. // 保存当前选中的节点
  209. if (selectedLocation != null) {
  210. IXSP.saveSelectedLocation(selectedLocation!.toJson());
  211. }
  212. // 保存最近选择的节点列表
  213. final recentLocationsJson = _recentLocations
  214. .map((e) => e.toJson())
  215. .toList();
  216. IXSP.saveRecentLocations(recentLocationsJson);
  217. } catch (e) {
  218. log(TAG, 'Error saving locations to storage: $e');
  219. }
  220. }
  221. void onRefresh() async {
  222. try {
  223. await apiController.refreshLaunch();
  224. getBanner(position: 'nine', isCache: false);
  225. getBanner(position: 'banner', isCache: false);
  226. refreshController.refreshCompleted();
  227. } catch (e) {
  228. refreshController.refreshFailed();
  229. }
  230. }
  231. /// 当 Launch 数据更新时刷新节点
  232. void refreshOnLaunchChanged() {
  233. log(TAG, 'Launch data changed, refreshing locations');
  234. _loadSavedLocations();
  235. }
  236. // 设置默认auto连接
  237. void setDefaultAutoConnect() {
  238. coreController.locationSelectionType = 'auto';
  239. coreController.handleConnection();
  240. }
  241. /// 获取 banner 列表
  242. /// [position] banner 位置类型,如 "banner"、"media"、"nine" 等
  243. Future<void> getBanner({
  244. String position = 'banner',
  245. bool isCache = true,
  246. }) async {
  247. try {
  248. // 先读取缓存数据
  249. final cacheBanners = IXSP.getBanner(position);
  250. if (cacheBanners != null &&
  251. cacheBanners.list != null &&
  252. cacheBanners.list!.isNotEmpty &&
  253. isCache) {
  254. if (position == 'banner') {
  255. bannerList = cacheBanners.list!;
  256. } else if (position == 'nine') {
  257. nineBannerList = cacheBanners.list!;
  258. }
  259. log(TAG, 'Loaded banner from cache for position: $position');
  260. }
  261. // 请求最新数据
  262. final banners = await apiController.getBanner(position: position);
  263. if (banners.list != null && banners.list!.isNotEmpty) {
  264. if (position == 'banner') {
  265. bannerList = banners.list!;
  266. } else if (position == 'nine') {
  267. nineBannerList = banners.list!;
  268. }
  269. // 保存到缓存
  270. await IXSP.saveBanner(position, banners);
  271. log(TAG, 'Banner updated and cached for position: $position');
  272. }
  273. } catch (e) {
  274. log(TAG, 'Error loading banners for position $position: $e');
  275. }
  276. }
  277. //点击banner
  278. void onBannerTap(Banner? banner) {
  279. if (banner?.action == null) return;
  280. final action = BannerAction.values.firstWhere(
  281. (e) => e.toString().split('.').last == banner?.action,
  282. orElse: () => BannerAction.notice, // 默认值
  283. );
  284. switch (action) {
  285. case BannerAction.urlOut:
  286. if (banner?.data != null) {
  287. SystemHelper.openWebPage(banner!.data!);
  288. }
  289. break;
  290. case BannerAction.urlIn:
  291. if (banner?.data != null) {
  292. Get.toNamed(
  293. Routes.WEB,
  294. arguments: {
  295. 'title': banner?.title ?? '',
  296. 'url': banner?.data ?? '',
  297. },
  298. );
  299. }
  300. break;
  301. case BannerAction.deepLink:
  302. if (banner?.data != null) {
  303. // Handle deep link
  304. SystemHelper.handleDeepLink(banner!.data!);
  305. }
  306. break;
  307. case BannerAction.openPkg:
  308. if (banner?.data != null) {
  309. // Open specific package
  310. SystemHelper.openPackage(banner!.data!);
  311. }
  312. break;
  313. case BannerAction.notice:
  314. if (banner?.data != null) {
  315. // Show notice dialog
  316. ErrorDialog.show(
  317. title: banner?.title ?? '',
  318. message: banner?.content,
  319. );
  320. }
  321. break;
  322. case BannerAction.page:
  323. if (banner?.data != null) {
  324. final uri = Uri.parse(banner!.data!);
  325. Get.toNamed(
  326. uri.path,
  327. arguments: {...uri.queryParameters, 'banner': banner},
  328. );
  329. }
  330. break;
  331. }
  332. }
  333. }