home_controller.dart 11 KB

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