home_controller.dart 11 KB

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