home_controller.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. AwesomeNotificationsHelper.init();
  66. getBanner(position: 'nine');
  67. getBanner(position: 'banner');
  68. }
  69. /// 初始化位置数据
  70. void _initializeLocations() {
  71. // 从 SharedPreferences 加载保存的节点数据
  72. _loadSavedLocations();
  73. }
  74. /// 从 SharedPreferences 加载保存的节点数据
  75. void _loadSavedLocations() {
  76. try {
  77. // 加载当前选中的节点
  78. final selectedLocationData = IXSP.getSelectedLocation();
  79. if (selectedLocationData != null) {
  80. final savedLocation = Locations.fromJson(selectedLocationData);
  81. // 检查保存的节点是否存在于当前 groups 中
  82. if (_isLocationExistsInGroups(savedLocation)) {
  83. selectedLocation = savedLocation;
  84. } else {
  85. // 如果节点不存在于 groups 中,选中第一个可用节点
  86. // 如果当前节点是连接中的状态,则断开连接
  87. if (coreController.state != ConnectionState.disconnected) {
  88. BaseCoreApi().disconnect();
  89. }
  90. log(
  91. TAG,
  92. 'Saved location not found in groups, selecting first available',
  93. );
  94. _selectFirstAvailableLocation();
  95. }
  96. } else {
  97. // 如果没有保存的节点,选中第一个可用节点
  98. _selectFirstAvailableLocation();
  99. }
  100. // 加载最近选择的节点列表
  101. final recentLocationsData = IXSP.getRecentLocations();
  102. if (recentLocationsData.isNotEmpty) {
  103. _recentLocations.assignAll(
  104. recentLocationsData.map((e) => Locations.fromJson(e)).toList(),
  105. );
  106. }
  107. } catch (e) {
  108. log(TAG, 'Error loading saved locations: $e');
  109. }
  110. }
  111. /// 检查节点是否存在于当前 groups 中
  112. bool _isLocationExistsInGroups(Locations location) {
  113. final launch = IXSP.getLaunch();
  114. final groups = launch?.groups;
  115. if (groups == null) return false;
  116. // 检查 normal 列表
  117. if (groups.normal?.list != null) {
  118. for (var locationList in groups.normal!.list!) {
  119. if (locationList.locations != null) {
  120. for (var loc in locationList.locations!) {
  121. if (loc.id == location.id) {
  122. return true;
  123. }
  124. }
  125. }
  126. }
  127. }
  128. // 检查 streaming 列表
  129. if (groups.streaming?.list != null) {
  130. for (var locationList in groups.streaming!.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. return false;
  141. }
  142. /// 选中第一个可用节点
  143. void _selectFirstAvailableLocation() {
  144. try {
  145. final launch = IXSP.getLaunch();
  146. final normalList = launch?.groups?.normal?.list;
  147. if (normalList != null && normalList.isNotEmpty) {
  148. // 遍历找到第一个有可用节点的国家
  149. for (var locationList in normalList) {
  150. if (locationList.locations != null &&
  151. locationList.locations!.isNotEmpty) {
  152. // 选中第一个节点
  153. final firstLocation = locationList.locations!.first;
  154. selectLocation(firstLocation);
  155. break;
  156. }
  157. }
  158. }
  159. } catch (e) {
  160. log(TAG, 'Error selecting first available location: $e');
  161. }
  162. }
  163. /// 选择位置
  164. void selectLocation(
  165. Locations location, {
  166. String locationSelectionType = 'auto',
  167. }) {
  168. selectedLocation = location;
  169. coreController.locationSelectionType = locationSelectionType;
  170. // 更新最近使用列表
  171. _updateRecentLocations(location);
  172. // 保存到 SharedPreferences
  173. _saveLocationsToStorage();
  174. }
  175. void handleConnect({bool delay = false}) {
  176. if (delay) {
  177. // 延迟300ms
  178. Future.delayed(const Duration(milliseconds: 300), () {
  179. coreController.selectLocationConnect();
  180. });
  181. } else {
  182. coreController.selectLocationConnect();
  183. }
  184. }
  185. /// 更新最近使用的位置列表
  186. void _updateRecentLocations(Locations location) {
  187. // 移除已存在的位置
  188. _recentLocations.removeWhere((loc) => loc.id == location.id);
  189. // 添加到列表开头
  190. _recentLocations.insert(0, location);
  191. // 保持最多4个最近使用的位置(过滤掉当前选中后能显示3个)
  192. if (_recentLocations.length > 4) {
  193. _recentLocations.removeRange(4, _recentLocations.length);
  194. }
  195. }
  196. /// 保存位置数据到 SharedPreferences
  197. void _saveLocationsToStorage() {
  198. try {
  199. // 保存当前选中的节点
  200. if (selectedLocation != null) {
  201. IXSP.saveSelectedLocation(selectedLocation!.toJson());
  202. }
  203. // 保存最近选择的节点列表
  204. final recentLocationsJson = _recentLocations
  205. .map((e) => e.toJson())
  206. .toList();
  207. IXSP.saveRecentLocations(recentLocationsJson);
  208. } catch (e) {
  209. log(TAG, 'Error saving locations to storage: $e');
  210. }
  211. }
  212. void onRefresh() async {
  213. try {
  214. await apiController.launch();
  215. getBanner(position: 'nine', isCache: false);
  216. getBanner(position: 'banner', isCache: false);
  217. refreshController.refreshCompleted();
  218. } catch (e) {
  219. refreshController.refreshFailed();
  220. }
  221. }
  222. /// 当 Launch 数据更新时刷新节点
  223. void refreshOnLaunchChanged() {
  224. log(TAG, 'Launch data changed, refreshing locations');
  225. _loadSavedLocations();
  226. }
  227. // 设置默认auto连接
  228. void setDefaultAutoConnect() {
  229. coreController.locationSelectionType = 'auto';
  230. coreController.handleConnection();
  231. }
  232. /// 获取 banner 列表
  233. /// [position] banner 位置类型,如 "banner"、"media"、"nine" 等
  234. Future<void> getBanner({
  235. String position = 'banner',
  236. bool isCache = true,
  237. }) async {
  238. try {
  239. // 先读取缓存数据
  240. final cacheBanners = IXSP.getBanner(position);
  241. if (cacheBanners != null &&
  242. cacheBanners.list != null &&
  243. cacheBanners.list!.isNotEmpty &&
  244. isCache) {
  245. if (position == 'banner') {
  246. bannerList = cacheBanners.list!;
  247. } else if (position == 'nine') {
  248. nineBannerList = cacheBanners.list!;
  249. }
  250. log(TAG, 'Loaded banner from cache for position: $position');
  251. }
  252. // 请求最新数据
  253. final banners = await apiController.getBanner(position: position);
  254. if (banners.list != null && banners.list!.isNotEmpty) {
  255. if (position == 'banner') {
  256. bannerList = banners.list!;
  257. } else if (position == 'nine') {
  258. nineBannerList = banners.list!;
  259. }
  260. // 保存到缓存
  261. await IXSP.saveBanner(position, banners);
  262. log(TAG, 'Banner updated and cached for position: $position');
  263. }
  264. } catch (e) {
  265. log(TAG, 'Error loading banners for position $position: $e');
  266. }
  267. }
  268. //点击banner
  269. void onBannerTap(Banner? banner) {
  270. if (banner?.action == null) return;
  271. final action = BannerAction.values.firstWhere(
  272. (e) => e.toString().split('.').last == banner?.action,
  273. orElse: () => BannerAction.notice, // 默认值
  274. );
  275. switch (action) {
  276. case BannerAction.urlOut:
  277. if (banner?.data != null) {
  278. SystemHelper.openWebPage(banner!.data!);
  279. }
  280. break;
  281. case BannerAction.urlIn:
  282. if (banner?.data != null) {
  283. Get.toNamed(
  284. Routes.WEB,
  285. arguments: {
  286. 'title': banner?.title ?? '',
  287. 'url': banner?.data ?? '',
  288. },
  289. );
  290. }
  291. break;
  292. case BannerAction.deepLink:
  293. if (banner?.data != null) {
  294. // Handle deep link
  295. SystemHelper.handleDeepLink(banner!.data!);
  296. }
  297. break;
  298. case BannerAction.openPkg:
  299. if (banner?.data != null) {
  300. // Open specific package
  301. SystemHelper.openPackage(banner!.data!);
  302. }
  303. break;
  304. case BannerAction.notice:
  305. if (banner?.data != null) {
  306. // Show notice dialog
  307. ErrorDialog.show(
  308. title: banner?.title ?? '',
  309. message: banner?.content,
  310. );
  311. }
  312. break;
  313. case BannerAction.page:
  314. if (banner?.data != null) {
  315. final uri = Uri.parse(banner!.data!);
  316. Get.toNamed(uri.path, arguments: uri.queryParameters);
  317. }
  318. break;
  319. }
  320. }
  321. }