api_domains.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:dio/dio.dart';
  4. import 'package:dio/io.dart';
  5. import 'package:shared_preferences/shared_preferences.dart';
  6. import '../../utils/crypto.dart';
  7. import '../../utils/developer/ix_developer_tools.dart';
  8. import '../../utils/log/logger.dart';
  9. import '../api/core/api_core.dart';
  10. import '../api/file/api_file.dart';
  11. import '../api/log/api_log.dart';
  12. import 'configs.dart';
  13. import '../data/models/launch/launch.dart';
  14. import 'keys.dart';
  15. class ApiDomains {
  16. static final ApiDomains _instance = ApiDomains._internal();
  17. static ApiDomains get instance => _instance;
  18. factory ApiDomains() => _instance;
  19. ApiDomains._internal();
  20. // 常量定义
  21. static const String _STORAGE_API_URLS = 'api_urls';
  22. static const String _STORAGE_LOG_URLS = 'log_urls';
  23. static const String _STORAGE_FILE_URLS = 'file_urls';
  24. static const String _STORAGE_BACKUP_URLS = 'backup_api_urls';
  25. static const String _STORAGE_API_URLS_INDEX = 'api_urls_index';
  26. static const String _STORAGE_LOG_URLS_INDEX = 'log_urls_index';
  27. static const String _STORAGE_FILE_URLS_INDEX = 'file_urls_index';
  28. static const String _STORAGE_IS_HARDCODED = 'is_hardcoded';
  29. static const int RETRY_COUNT_PER_LAUNCH = 2;
  30. final Dio dio = Dio(
  31. BaseOptions(
  32. connectTimeout: const Duration(seconds: 30),
  33. receiveTimeout: const Duration(seconds: 30),
  34. sendTimeout: const Duration(seconds: 30),
  35. ),
  36. );
  37. // 标记是否已经添加了监控拦截器
  38. bool _monitorInterceptorAdded = false;
  39. setProxy(String proxy) {
  40. dio.httpClientAdapter = IOHttpClientAdapter(
  41. createHttpClient: () {
  42. final client = HttpClient();
  43. client.findProxy = (uri) => proxy;
  44. client.badCertificateCallback =
  45. (X509Certificate cert, String host, int port) => true;
  46. return client;
  47. },
  48. );
  49. }
  50. // 默认API URL列表
  51. final List<String> _defaultApiUrls = [
  52. "https://d2aphju2iq7g2g.cloudfront.net",
  53. "https://api.turboaccel.website",
  54. "https://d1rvevafipy7o6.cloudfront.net",
  55. "https://api.speedboost.website",
  56. "https://dqmkongldmyxf.cloudfront.net",
  57. "https://api.fastforward.website",
  58. "https://d2cvqygi5xlqp3.cloudfront.net",
  59. "https://api.odyxighs.com",
  60. "https://service.fkey.club",
  61. ];
  62. // 默认LOG API URL列表
  63. final List<String> _defaultLogUrls = ['https://stat.fkey.win'];
  64. // 默认FILE API URL列表
  65. final List<String> _defaultFileUrls = [];
  66. // 默认备用URL列表(txt文件地址)
  67. final List<String> _defaultBackupApiUrls = [
  68. 'https://drive.google.com/uc?export=download&id=1YMEZiAHPhlAg_xZqD7dSDt0WjlcogwVz',
  69. 'https://fkey.win/.well-known/backup/backup_fk.data',
  70. ];
  71. // 当前使用的URL列表
  72. List<String> _apiUrls = [];
  73. // 当前使用的LogURL列表
  74. List<String> _logUrls = [];
  75. // 当前使用的FILE URL列表
  76. List<String> _fileUrls = [];
  77. // 当前使用的备用URL列表
  78. List<String> _backupApiUrls = [];
  79. // 当前尝试的索引
  80. int _currentIndex = 0;
  81. // 当前使用的LogURL索引
  82. int _currentLogIndex = 0;
  83. // 当前使用的FILE URL索引
  84. int _currentFileIndex = 0;
  85. // 当前正在使用的备用列表索引
  86. int _currentBackupListIndex = 0;
  87. // 添加标志位,标识是否使用的是硬编码URL
  88. bool _isUsingHardcodedUrls = true;
  89. // 添加标志位,记录硬编码请求次数
  90. int _hardcodedRequestCount = 0;
  91. // 初始化方法
  92. Future<void> init() async {
  93. initUrls();
  94. // 尝试加载保存的URLs
  95. await _loadSavedUrls();
  96. }
  97. void initUrls() {
  98. if (Configs.debug) {
  99. _apiUrls = [
  100. // 'https://api.znomo.com', // 测试环境
  101. "https://nomo-api.clickto.dev", // 开发环境
  102. ];
  103. _logUrls = [];
  104. _fileUrls = [];
  105. _backupApiUrls = [];
  106. } else {
  107. _apiUrls = List.from(_defaultApiUrls);
  108. _logUrls = List.from(_defaultLogUrls);
  109. _fileUrls = List.from(_defaultFileUrls);
  110. _backupApiUrls = List.from(_defaultBackupApiUrls);
  111. }
  112. }
  113. // 修改加载保存的URL方法,返回是否成功加载
  114. Future<void> _loadSavedUrls() async {
  115. try {
  116. final prefs = await SharedPreferences.getInstance();
  117. _currentIndex = prefs.getInt(_STORAGE_API_URLS_INDEX) ?? 0;
  118. _currentLogIndex = prefs.getInt(_STORAGE_LOG_URLS_INDEX) ?? 0;
  119. _currentFileIndex = prefs.getInt(_STORAGE_FILE_URLS_INDEX) ?? 0;
  120. _isUsingHardcodedUrls = prefs.getBool(_STORAGE_IS_HARDCODED) ?? true;
  121. final savedApiUrls = prefs.getStringList(_STORAGE_API_URLS);
  122. final savedBackupUrls = prefs.getStringList(_STORAGE_BACKUP_URLS);
  123. final savedLogUrls = prefs.getStringList(_STORAGE_LOG_URLS);
  124. final savedFileUrls = prefs.getStringList(_STORAGE_FILE_URLS);
  125. if (savedApiUrls != null && savedApiUrls.isNotEmpty) {
  126. _apiUrls = savedApiUrls;
  127. }
  128. if (savedBackupUrls != null && savedBackupUrls.isNotEmpty) {
  129. _backupApiUrls = savedBackupUrls;
  130. }
  131. if (savedLogUrls != null && savedLogUrls.isNotEmpty) {
  132. _logUrls = savedLogUrls;
  133. }
  134. if (savedFileUrls != null && savedFileUrls.isNotEmpty) {
  135. _fileUrls = savedFileUrls;
  136. }
  137. log(
  138. 'ApiDomains',
  139. 'Loaded saved URLs: ${_apiUrls.length} APIs, ${_backupApiUrls.length} backups, ${_logUrls.length} logs, ${_fileUrls.length} files',
  140. );
  141. } catch (e) {
  142. log('ApiDomains', 'Error loading saved URLs: $e');
  143. }
  144. }
  145. Future<void> setApiUrls(List<String> urls) async {
  146. try {
  147. final prefs = await SharedPreferences.getInstance();
  148. await prefs.setStringList(_STORAGE_API_URLS, urls);
  149. _currentIndex = 0;
  150. await prefs.setInt(_STORAGE_API_URLS_INDEX, _currentIndex);
  151. ApiCore().setbaseUrl(urls[_currentIndex]);
  152. } catch (e) {
  153. log('ApiDomains', 'Error saving URLs: $e');
  154. }
  155. }
  156. // 添加logUrl
  157. Future<void> addLogUrls(List<String> urls) async {
  158. try {
  159. var logList = List<String>.from(_logUrls);
  160. logList.insertAll(0, urls);
  161. _logUrls = logList.toSet().toList();
  162. await _saveLogUrls();
  163. } catch (e) {
  164. log('ApiDomains', 'Error add Log URL: $e');
  165. }
  166. }
  167. // 添加fileUrl
  168. Future<void> addFileUrls(List<String> urls) async {
  169. try {
  170. var fileList = List<String>.from(_fileUrls);
  171. fileList.insertAll(0, urls);
  172. _fileUrls = fileList.toSet().toList();
  173. await _saveFileUrls();
  174. } catch (e) {
  175. log('ApiDomains', 'Error add File URL: $e');
  176. }
  177. }
  178. // 保存当前URL列表到持久化存储
  179. Future<void> _saveApiUrls() async {
  180. try {
  181. final prefs = await SharedPreferences.getInstance();
  182. await prefs.setStringList(_STORAGE_API_URLS, _apiUrls);
  183. await prefs.setStringList(_STORAGE_BACKUP_URLS, _backupApiUrls);
  184. } catch (e) {
  185. log('ApiDomains', 'Error saving URLs: $e');
  186. }
  187. }
  188. // 保存当前LogURL列表到持久化存储
  189. Future<void> _saveLogUrls() async {
  190. try {
  191. final prefs = await SharedPreferences.getInstance();
  192. await prefs.setStringList(_STORAGE_LOG_URLS, _logUrls);
  193. } catch (e) {
  194. log('ApiDomains', 'Error saving Log URLs: $e');
  195. }
  196. }
  197. // 保存当前FILE URL列表到持久化存储
  198. Future<void> _saveFileUrls() async {
  199. try {
  200. final prefs = await SharedPreferences.getInstance();
  201. await prefs.setStringList(_STORAGE_FILE_URLS, _fileUrls);
  202. } catch (e) {
  203. log('ApiDomains', 'Error saving File URLs: $e');
  204. }
  205. }
  206. // 保存硬编码状态
  207. Future<void> _saveIsHardcodedUrls() async {
  208. try {
  209. final prefs = await SharedPreferences.getInstance();
  210. await prefs.setBool(_STORAGE_IS_HARDCODED, _isUsingHardcodedUrls);
  211. } catch (e) {
  212. log('ApiDomains', 'Error saving is hardcoded URLs: $e');
  213. }
  214. }
  215. // 保存硬编码索引
  216. Future<void> _saveApiUrlsIndex() async {
  217. try {
  218. final prefs = await SharedPreferences.getInstance();
  219. await prefs.setInt(_STORAGE_API_URLS_INDEX, _currentIndex);
  220. } catch (e) {
  221. log('ApiDomains', 'Error saving hardcoded index: $e');
  222. }
  223. }
  224. // 保存LogURL硬编码索引
  225. Future<void> _saveLogUrlsIndex() async {
  226. try {
  227. final prefs = await SharedPreferences.getInstance();
  228. await prefs.setInt(_STORAGE_LOG_URLS_INDEX, _currentLogIndex);
  229. } catch (e) {
  230. log('ApiDomains', 'Error saving Log URLs index: $e');
  231. }
  232. }
  233. // 保存FILE URL硬编码索引
  234. Future<void> _saveFileUrlsIndex() async {
  235. try {
  236. final prefs = await SharedPreferences.getInstance();
  237. await prefs.setInt(_STORAGE_FILE_URLS_INDEX, _currentFileIndex);
  238. } catch (e) {
  239. log('ApiDomains', 'Error saving File URLs index: $e');
  240. }
  241. }
  242. // 从Launch数据更新URL列表
  243. Future<void> updateFromLaunch(Launch launch) async {
  244. try {
  245. if (launch.appConfig?.apiUrls != null &&
  246. launch.appConfig!.apiUrls!.isNotEmpty) {
  247. _apiUrls = List<String>.from(launch.appConfig!.apiUrls!);
  248. // 如果ApiCore的baseUrl不在launch的apiUrls中,或者使用硬编码的url,则设置ApiCore的baseUrl为launch的apiUrls的第一个
  249. if (!_apiUrls.contains(ApiCore().baseUrl) || _isUsingHardcodedUrls) {
  250. ApiCore().setbaseUrl(_apiUrls[0]);
  251. }
  252. final baseUrl = ApiCore().baseUrl;
  253. _apiUrls.insert(0, baseUrl);
  254. _apiUrls = _apiUrls.toSet().toList();
  255. _currentIndex = 0;
  256. log('ApiDomains', 'Add ApiCore baseUrl to index 0: $baseUrl');
  257. }
  258. if (launch.appConfig?.backupApiUrls != null &&
  259. launch.appConfig!.backupApiUrls!.isNotEmpty) {
  260. _backupApiUrls = launch.appConfig!.backupApiUrls!;
  261. _currentBackupListIndex = 0;
  262. }
  263. if (launch.appConfig?.appStatUrls != null &&
  264. launch.appConfig!.appStatUrls!.isNotEmpty) {
  265. _logUrls = launch.appConfig!.appStatUrls!;
  266. // 设置ApiLog的baseUrl为launch的appStatUrls的第一个
  267. final baseUrl = _logUrls[0];
  268. ApiLog().setbaseUrl(baseUrl);
  269. _currentLogIndex = 0;
  270. log('ApiDomains', 'Add ApiLog baseUrl to index 0: $baseUrl');
  271. }
  272. if (launch.appConfig?.logFileUploadUrls != null &&
  273. launch.appConfig!.logFileUploadUrls!.isNotEmpty) {
  274. _fileUrls = launch.appConfig!.logFileUploadUrls!;
  275. // 设置ApiFile的baseUrl为launch的logFileUploadUrls的第一个
  276. final baseUrl = _fileUrls[0];
  277. ApiFile().setbaseUrl(baseUrl);
  278. _currentFileIndex = 0;
  279. log('ApiDomains', 'Add ApiFile baseUrl to index 0: $baseUrl');
  280. }
  281. _isUsingHardcodedUrls = false;
  282. await _saveIsHardcodedUrls();
  283. await _saveApiUrls();
  284. await _saveApiUrlsIndex();
  285. await _saveLogUrls();
  286. await _saveLogUrlsIndex();
  287. await _saveFileUrls();
  288. await _saveFileUrlsIndex();
  289. log('ApiDomains', 'Updated URLs from launch data');
  290. } catch (e) {
  291. log('ApiDomains', 'Error updating URLs from launch data: $e');
  292. }
  293. }
  294. // 获取当前ApiURL
  295. String getApiUrl() {
  296. if (_currentIndex >= _apiUrls.length) {
  297. _currentIndex = 0;
  298. }
  299. return _apiUrls[_currentIndex];
  300. }
  301. // 获取当前LogURL
  302. String getLogUrl() {
  303. if (_currentLogIndex >= _logUrls.length) {
  304. _currentLogIndex = 0;
  305. }
  306. return _logUrls[_currentLogIndex];
  307. }
  308. // 获取当前FILE URL
  309. String getFileUrl() {
  310. if (_currentFileIndex >= _fileUrls.length) {
  311. _currentFileIndex = 0;
  312. }
  313. return _fileUrls[_currentFileIndex];
  314. }
  315. Future<bool> isHardcodedUrls() async {
  316. return _isUsingHardcodedUrls;
  317. }
  318. // 获取下一次要尝试的URL
  319. Future<String> getNextApiUrl() async {
  320. // 使用硬编码URLs的情况
  321. if (_isUsingHardcodedUrls) {
  322. // 如果硬编码请求次数大于等于最大重试次数,返回空字符串
  323. if (_hardcodedRequestCount >= RETRY_COUNT_PER_LAUNCH) {
  324. _hardcodedRequestCount = 0;
  325. return '';
  326. }
  327. // 获取下一个索引
  328. int nextIndex = _currentIndex + 1;
  329. if (nextIndex >= _apiUrls.length) {
  330. if (_hardcodedRequestCount < RETRY_COUNT_PER_LAUNCH) {
  331. final isSuccess = await _switchToBackupList();
  332. if (isSuccess) {
  333. return getApiUrl();
  334. } else {
  335. _hardcodedRequestCount = 0;
  336. return '';
  337. }
  338. }
  339. return '';
  340. }
  341. final url = _apiUrls[nextIndex];
  342. _currentIndex++;
  343. _hardcodedRequestCount++;
  344. await _saveApiUrlsIndex();
  345. return url;
  346. }
  347. // 使用Launch数据的情况
  348. else {
  349. // 如果当前列表已用完
  350. int nextIndex = _currentIndex + 1;
  351. if (nextIndex >= _apiUrls.length) {
  352. // 尝试切换到备用列表
  353. final isSuccess = await _switchToBackupList();
  354. if (isSuccess) {
  355. return getApiUrl();
  356. } else {
  357. return '';
  358. }
  359. }
  360. // 返回当前URL
  361. final url = _apiUrls[nextIndex];
  362. _currentIndex++;
  363. await _saveApiUrlsIndex();
  364. return url;
  365. }
  366. }
  367. // 获取下一次要尝试的LogURL
  368. Future<String> getNextLogUrl() async {
  369. // 获取下一个索引
  370. int nextIndex = _currentLogIndex + 1;
  371. if (nextIndex >= _logUrls.length) {
  372. _currentLogIndex = 0;
  373. await _saveLogUrlsIndex();
  374. return '';
  375. }
  376. // 返回所有剩余的URL
  377. final url = _logUrls[nextIndex];
  378. _currentLogIndex++;
  379. await _saveLogUrlsIndex();
  380. return url;
  381. }
  382. // 获取下一次要尝试的FILE URL
  383. Future<String> getNextFileUrl() async {
  384. // 获取下一个索引
  385. int nextIndex = _currentFileIndex + 1;
  386. if (nextIndex >= _fileUrls.length) {
  387. _currentFileIndex = 0;
  388. await _saveFileUrlsIndex();
  389. return '';
  390. }
  391. // 返回所有剩余的URL
  392. final url = _fileUrls[nextIndex];
  393. _currentFileIndex++;
  394. await _saveFileUrlsIndex();
  395. return url;
  396. }
  397. // 切换到备用列表
  398. Future<bool> _switchToBackupList() async {
  399. while (_currentBackupListIndex < _backupApiUrls.length) {
  400. try {
  401. if (_currentBackupListIndex >= _backupApiUrls.length) {
  402. log('ApiDomains', 'Error: Backup URL index out of bounds');
  403. break;
  404. }
  405. final backupUrl = _backupApiUrls[_currentBackupListIndex];
  406. log('ApiDomains', 'Trying backup URL: $backupUrl');
  407. // 添加talker日志(避免重复添加)
  408. if (!_monitorInterceptorAdded) {
  409. dio.interceptors.add(SimpleNoSignApiMonitorInterceptor());
  410. _monitorInterceptorAdded = true;
  411. }
  412. final response = await dio.get(backupUrl);
  413. if (response.statusCode == 200) {
  414. log('Before decryption: ${response.data}');
  415. final decryptedBytes = Crypto.decryptBytes(
  416. response.data.toString().trim(),
  417. Keys.aesKey,
  418. Keys.aesIv,
  419. );
  420. final jsonText = utf8.decode(decryptedBytes);
  421. log('Decryption results: $jsonText');
  422. final Map<String, dynamic> map = jsonDecode(jsonText);
  423. if (map['apiUrls'] != null) {
  424. final list = List<String>.from(map['apiUrls']);
  425. _apiUrls = list;
  426. _currentIndex = 0;
  427. // 当前备用文件成功,标志可以尝试下一个
  428. _currentBackupListIndex++;
  429. await _saveApiUrls();
  430. await _saveApiUrlsIndex();
  431. log('ApiDomains', 'Switched to backup list: ${list.length} URLs');
  432. return true;
  433. }
  434. }
  435. // 当前备用文件失败,尝试下一个
  436. _currentBackupListIndex++;
  437. } catch (e) {
  438. log('ApiDomains', 'Error switching to backup list: $e');
  439. _currentBackupListIndex++;
  440. }
  441. }
  442. // 如果所有备用URL都失败了,重置为硬编码模式
  443. _isUsingHardcodedUrls = true;
  444. _currentIndex = 0;
  445. _currentBackupListIndex = 0;
  446. initUrls();
  447. await _saveIsHardcodedUrls();
  448. await _saveApiUrls();
  449. await _saveApiUrlsIndex();
  450. return false;
  451. }
  452. // 获取所有logUrl
  453. List<String> getAllLogUrls() {
  454. return _logUrls;
  455. }
  456. }