home_controller.dart 11 KB

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