refactor: 优化日志输出,仅在调试模式下启用

- 为所有 print 语句添加 kDebugMode 检查
- 更新 KRLogUtil 工具类,Release 模式下禁用日志输出
- 优化 18 个文件中的 335+ 条日志语句
- 提升 Release 版本性能并增强安全性

(cherry picked from commit 301f1510ba81fe94fb08e013ca80b3ca708a2e15)
This commit is contained in:
Rust 2025-11-01 05:15:34 -07:00 committed by speakeloudest
parent b3ee1cc6dc
commit 4c5763647d
18 changed files with 665 additions and 232 deletions

View File

@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:get/get.dart'; import 'package:get/get.dart';
import '../response/kr_node_list.dart'; import '../response/kr_node_list.dart';
import 'package:flutter/foundation.dart';
/// ///
class KROutboundItem { class KROutboundItem {
@ -50,14 +51,18 @@ class KROutboundItem {
// 🔧 使API格式 // 🔧 使API格式
// port serverAddr // port serverAddr
if (nodeListItem.port > 0 && nodeListItem.serverAddr.isNotEmpty) { if (nodeListItem.port > 0 && nodeListItem.serverAddr.isNotEmpty) {
if (kDebugMode) {
print(' 节点 ${nodeListItem.name} 使用直接字段构建配置'); print(' 节点 ${nodeListItem.name} 使用直接字段构建配置');
}
_buildConfigFromFields(nodeListItem); _buildConfigFromFields(nodeListItem);
return; return;
} }
// config API格式 // config API格式
if (nodeListItem.config.isEmpty) { if (nodeListItem.config.isEmpty) {
if (kDebugMode) {
print('❌ 节点 ${nodeListItem.name} 缺少配置信息无port或config'); print('❌ 节点 ${nodeListItem.name} 缺少配置信息无port或config');
}
config = {}; config = {};
return; return;
} }
@ -66,8 +71,12 @@ class KROutboundItem {
try { try {
json = jsonDecode(nodeListItem.config) as Map<String, dynamic>; json = jsonDecode(nodeListItem.config) as Map<String, dynamic>;
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 节点 ${nodeListItem.name} 的 config 解析失败: $e,尝试使用直接字段'); print('❌ 节点 ${nodeListItem.name} 的 config 解析失败: $e,尝试使用直接字段');
}
if (kDebugMode) {
print('📄 Config 内容: ${nodeListItem.config}'); print('📄 Config 内容: ${nodeListItem.config}');
}
_buildConfigFromFields(nodeListItem); _buildConfigFromFields(nodeListItem);
return; return;
} }
@ -237,14 +246,30 @@ class KROutboundItem {
/// API格式 /// API格式
void _buildConfigFromFields(KrNodeListItem nodeListItem) { void _buildConfigFromFields(KrNodeListItem nodeListItem) {
if (kDebugMode) {
print('🔧 开始构建节点配置 - 协议: ${nodeListItem.protocol}, 名称: ${nodeListItem.name}'); print('🔧 开始构建节点配置 - 协议: ${nodeListItem.protocol}, 名称: ${nodeListItem.name}');
}
if (kDebugMode) {
print('📋 节点详细信息:'); print('📋 节点详细信息:');
}
if (kDebugMode) {
print(' - serverAddr: ${nodeListItem.serverAddr}'); print(' - serverAddr: ${nodeListItem.serverAddr}');
}
if (kDebugMode) {
print(' - port: ${nodeListItem.port}'); print(' - port: ${nodeListItem.port}');
}
if (kDebugMode) {
print(' - uuid: ${nodeListItem.uuid}'); print(' - uuid: ${nodeListItem.uuid}');
}
if (kDebugMode) {
print(' - method: ${nodeListItem.method}'); print(' - method: ${nodeListItem.method}');
}
if (kDebugMode) {
print(' - config: ${nodeListItem.config}'); print(' - config: ${nodeListItem.config}');
}
if (kDebugMode) {
print(' - protocols: ${nodeListItem.protocols}'); print(' - protocols: ${nodeListItem.protocols}');
}
// 🔧 config transport // 🔧 config transport
Map<String, dynamic>? transportConfig; Map<String, dynamic>? transportConfig;
@ -254,7 +279,9 @@ class KROutboundItem {
if (nodeListItem.protocols.isNotEmpty) { if (nodeListItem.protocols.isNotEmpty) {
try { try {
final protocolsList = jsonDecode(nodeListItem.protocols) as List; final protocolsList = jsonDecode(nodeListItem.protocols) as List;
if (kDebugMode) {
print('📄 解析到 protocols 数组,共 ${protocolsList.length} 个协议'); print('📄 解析到 protocols 数组,共 ${protocolsList.length} 个协议');
}
// //
Map<String, dynamic>? matchedProtocol; Map<String, dynamic>? matchedProtocol;
@ -263,14 +290,18 @@ class KROutboundItem {
final type = protocolMap['type']?.toString().toLowerCase() ?? ''; final type = protocolMap['type']?.toString().toLowerCase() ?? '';
final enable = protocolMap['enable'] ?? true; final enable = protocolMap['enable'] ?? true;
if (kDebugMode) {
print(' 📋 协议: type=$type, enable=$enable'); print(' 📋 协议: type=$type, enable=$enable');
}
// hysteria hysteria2 hysteria // hysteria hysteria2 hysteria
if (type == nodeListItem.protocol.toLowerCase() || if (type == nodeListItem.protocol.toLowerCase() ||
(nodeListItem.protocol == 'hysteria' && type == 'hysteria2') || (nodeListItem.protocol == 'hysteria' && type == 'hysteria2') ||
(nodeListItem.protocol == 'hysteria2' && type == 'hysteria')) { (nodeListItem.protocol == 'hysteria2' && type == 'hysteria')) {
matchedProtocol = protocolMap; matchedProtocol = protocolMap;
if (kDebugMode) {
print(' ✅ 找到匹配的协议配置: $type'); print(' ✅ 找到匹配的协议配置: $type');
}
break; break;
} }
} }
@ -279,7 +310,9 @@ class KROutboundItem {
// transport // transport
if (matchedProtocol['network'] != null || matchedProtocol['transport'] != null) { if (matchedProtocol['network'] != null || matchedProtocol['transport'] != null) {
final network = matchedProtocol['network'] ?? matchedProtocol['transport']; final network = matchedProtocol['network'] ?? matchedProtocol['transport'];
if (kDebugMode) {
print(' 📡 传输协议: $network'); print(' 📡 传输协议: $network');
}
if (network == 'ws' || network == 'websocket') { if (network == 'ws' || network == 'websocket') {
transportConfig = { transportConfig = {
@ -290,22 +323,28 @@ class KROutboundItem {
if (host != null && host.toString().isNotEmpty) { if (host != null && host.toString().isNotEmpty) {
transportConfig['headers'] = {'Host': host.toString()}; transportConfig['headers'] = {'Host': host.toString()};
} }
if (kDebugMode) {
print(' ✅ WebSocket transport: $transportConfig'); print(' ✅ WebSocket transport: $transportConfig');
}
} else if (network == 'grpc') { } else if (network == 'grpc') {
transportConfig = { transportConfig = {
'type': 'grpc', 'type': 'grpc',
'service_name': matchedProtocol['grpc_service_name'] ?? matchedProtocol['service_name'] ?? '', 'service_name': matchedProtocol['grpc_service_name'] ?? matchedProtocol['service_name'] ?? '',
}; };
if (kDebugMode) {
print(' ✅ gRPC transport: $transportConfig'); print(' ✅ gRPC transport: $transportConfig');
}
} else if (network == 'http' || network == 'h2') { } else if (network == 'http' || network == 'h2') {
transportConfig = { transportConfig = {
'type': 'http', 'type': 'http',
'host': [matchedProtocol['http_host'] ?? matchedProtocol['host'] ?? ''], 'host': [matchedProtocol['http_host'] ?? matchedProtocol['host'] ?? ''],
'path': matchedProtocol['http_path'] ?? matchedProtocol['path'] ?? '/', 'path': matchedProtocol['http_path'] ?? matchedProtocol['path'] ?? '/',
}; };
if (kDebugMode) {
print(' ✅ HTTP transport: $transportConfig'); print(' ✅ HTTP transport: $transportConfig');
} }
} }
}
// security // security
if (matchedProtocol['tls'] != null || matchedProtocol['security'] != null) { if (matchedProtocol['tls'] != null || matchedProtocol['security'] != null) {
@ -319,35 +358,47 @@ class KROutboundItem {
'allow_insecure': matchedProtocol['allow_insecure'] ?? matchedProtocol['insecure'] ?? true, 'allow_insecure': matchedProtocol['allow_insecure'] ?? matchedProtocol['insecure'] ?? true,
'fingerprint': matchedProtocol['fingerprint'] ?? 'chrome', 'fingerprint': matchedProtocol['fingerprint'] ?? 'chrome',
}; };
if (kDebugMode) {
print(' ✅ Security config: security=$security, tls_enabled=$tlsEnabled, config=$securityConfig'); print(' ✅ Security config: security=$security, tls_enabled=$tlsEnabled, config=$securityConfig');
} }
} }
}
} catch (e) { } catch (e) {
if (kDebugMode) {
print('⚠️ 解析 protocols 字段失败: $e'); print('⚠️ 解析 protocols 字段失败: $e');
} }
} }
}
// config API格式 // config API格式
if (transportConfig == null && nodeListItem.config.isNotEmpty) { if (transportConfig == null && nodeListItem.config.isNotEmpty) {
try { try {
final configJson = jsonDecode(nodeListItem.config) as Map<String, dynamic>; final configJson = jsonDecode(nodeListItem.config) as Map<String, dynamic>;
if (kDebugMode) {
print('📄 解析到 config JSON: $configJson'); print('📄 解析到 config JSON: $configJson');
}
// transport // transport
if (configJson['transport'] != null && configJson['transport'] != 'tcp') { if (configJson['transport'] != null && configJson['transport'] != 'tcp') {
transportConfig = _buildTransport(configJson); transportConfig = _buildTransport(configJson);
if (kDebugMode) {
print('✅ 从 config 找到 transport 配置: $transportConfig'); print('✅ 从 config 找到 transport 配置: $transportConfig');
} }
}
// security_config // security_config
if (configJson['security_config'] != null) { if (configJson['security_config'] != null) {
securityConfig = configJson['security_config'] as Map<String, dynamic>; securityConfig = configJson['security_config'] as Map<String, dynamic>;
if (kDebugMode) {
print('✅ 从 config 找到 security_config: $securityConfig'); print('✅ 从 config 找到 security_config: $securityConfig');
} }
}
} catch (e) { } catch (e) {
if (kDebugMode) {
print('⚠️ 解析 config 字段失败: $e'); print('⚠️ 解析 config 字段失败: $e');
} }
} }
}
switch (nodeListItem.protocol) { switch (nodeListItem.protocol) {
case "shadowsocks": case "shadowsocks":
@ -364,9 +415,15 @@ class KROutboundItem {
"method": finalMethod, "method": finalMethod,
"password": nodeListItem.uuid "password": nodeListItem.uuid
}; };
if (kDebugMode) {
print('✅ Shadowsocks 节点配置构建成功: ${nodeListItem.name}'); print('✅ Shadowsocks 节点配置构建成功: ${nodeListItem.name}');
}
if (kDebugMode) {
print('📄 使用加密方法: $finalMethod'); print('📄 使用加密方法: $finalMethod');
}
if (kDebugMode) {
print('📄 完整配置: $config'); print('📄 完整配置: $config');
}
break; break;
case "vless": case "vless":
// IP地址 // IP地址
@ -381,7 +438,9 @@ class KROutboundItem {
// 🔧 security_config TLS // 🔧 security_config TLS
final bool vlessTlsEnabled = securityConfig?['tls_enabled'] ?? false; final bool vlessTlsEnabled = securityConfig?['tls_enabled'] ?? false;
if (kDebugMode) {
print('🔐 VLESS TLS 状态: enabled=$vlessTlsEnabled'); print('🔐 VLESS TLS 状态: enabled=$vlessTlsEnabled');
}
config = { config = {
"type": "vless", "type": "vless",
@ -400,8 +459,12 @@ class KROutboundItem {
} }
} }
}; };
if (kDebugMode) {
print('✅ VLESS 节点配置构建成功: ${nodeListItem.name}'); print('✅ VLESS 节点配置构建成功: ${nodeListItem.name}');
}
if (kDebugMode) {
print('📄 完整配置: $config'); print('📄 完整配置: $config');
}
break; break;
case "vmess": case "vmess":
// IP地址 // IP地址
@ -416,7 +479,9 @@ class KROutboundItem {
// 🔧 security_config TLS // 🔧 security_config TLS
final bool tlsEnabled = securityConfig?['tls_enabled'] ?? false; final bool tlsEnabled = securityConfig?['tls_enabled'] ?? false;
if (kDebugMode) {
print('🔐 TLS 状态: enabled=$tlsEnabled'); print('🔐 TLS 状态: enabled=$tlsEnabled');
}
config = { config = {
"type": "vmess", "type": "vmess",
@ -437,8 +502,12 @@ class KROutboundItem {
} }
} }
}; };
if (kDebugMode) {
print('✅ VMess 节点配置构建成功: ${nodeListItem.name}'); print('✅ VMess 节点配置构建成功: ${nodeListItem.name}');
}
if (kDebugMode) {
print('📄 完整配置: $config'); print('📄 完整配置: $config');
}
break; break;
case "trojan": case "trojan":
// IP地址 // IP地址
@ -468,16 +537,28 @@ class KROutboundItem {
} }
} }
}; };
if (kDebugMode) {
print('✅ Trojan 节点配置构建成功: ${nodeListItem.name}'); print('✅ Trojan 节点配置构建成功: ${nodeListItem.name}');
}
if (kDebugMode) {
print('📄 完整配置: $config'); print('📄 完整配置: $config');
}
break; break;
case "hysteria": case "hysteria":
case "hysteria2": case "hysteria2":
// "hysteria" Hysteria2 // "hysteria" Hysteria2
if (kDebugMode) {
print('🔍 构建 Hysteria2 节点: ${nodeListItem.name}'); print('🔍 构建 Hysteria2 节点: ${nodeListItem.name}');
}
if (kDebugMode) {
print(' - serverAddr: ${nodeListItem.serverAddr}'); print(' - serverAddr: ${nodeListItem.serverAddr}');
}
if (kDebugMode) {
print(' - port: ${nodeListItem.port}'); print(' - port: ${nodeListItem.port}');
}
if (kDebugMode) {
print(' - uuid: ${nodeListItem.uuid}'); print(' - uuid: ${nodeListItem.uuid}');
}
// //
final bool isDomain = !RegExp(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') final bool isDomain = !RegExp(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
@ -494,11 +575,17 @@ class KROutboundItem {
if (isDomain) "server_name": nodeListItem.serverAddr, if (isDomain) "server_name": nodeListItem.serverAddr,
} }
}; };
if (kDebugMode) {
print('✅ Hysteria2 节点配置构建成功'); print('✅ Hysteria2 节点配置构建成功');
}
if (kDebugMode) {
print('📄 完整配置: ${jsonEncode(config)}'); print('📄 完整配置: ${jsonEncode(config)}');
}
break; break;
default: default:
if (kDebugMode) {
print('⚠️ 不支持的协议类型: ${nodeListItem.protocol}'); print('⚠️ 不支持的协议类型: ${nodeListItem.protocol}');
}
config = {}; config = {};
} }
} }

View File

@ -3,6 +3,7 @@ import 'kr_group_outbound_list.dart';
import '../response/kr_node_list.dart'; import '../response/kr_node_list.dart';
import 'kr_outbound_item.dart'; import 'kr_outbound_item.dart';
import 'package:flutter/foundation.dart';
/// ///
class KrOutboundsList { class KrOutboundsList {
@ -47,14 +48,24 @@ class KrOutboundsList {
final KROutboundItem item = KROutboundItem(element); final KROutboundItem item = KROutboundItem(element);
// 🔍 country // 🔍 country
if (kDebugMode) {
print('🗺️ 构建节点: name="${element.name}", tag="${item.tag}", country="${item.country}"'); print('🗺️ 构建节点: name="${element.name}", tag="${item.tag}", country="${item.country}"');
}
if (kDebugMode) {
print(' - element.country: "${element.country}"'); print(' - element.country: "${element.country}"');
}
if (kDebugMode) {
print(' - item.country: "${item.country}"'); print(' - item.country: "${item.country}"');
}
if (kDebugMode) {
print(' - country.isEmpty: ${item.country.isEmpty}'); print(' - country.isEmpty: ${item.country.isEmpty}');
}
// type // type
if (item.config.isEmpty || !item.config.containsKey('type')) { if (item.config.isEmpty || !item.config.containsKey('type')) {
if (kDebugMode) {
print('⚠️ 跳过无效节点: ${element.name},配置为空或缺少 type 字段'); print('⚠️ 跳过无效节点: ${element.name},配置为空或缺少 type 字段');
}
continue; // continue; //
} }
@ -72,8 +83,10 @@ class KrOutboundsList {
configJsonList.add(item.config); configJsonList.add(item.config);
keyList[item.tag] = item; keyList[item.tag] = item;
if (kDebugMode) {
print('✅ keyList["${item.tag}"] 已设置country="${item.country}"'); print('✅ keyList["${item.tag}"] 已设置country="${item.country}"');
} }
}
// KRGroupOutboundList groupOutboundList // KRGroupOutboundList groupOutboundList
for (var tag in tagGroups.keys) { for (var tag in tagGroups.keys) {

View File

@ -8,6 +8,7 @@ import 'package:kaer_with_panels/app/services/kr_site_config_service.dart';
import 'dart:async'; import 'dart:async';
import '../../../services/kr_device_info_service.dart'; import '../../../services/kr_device_info_service.dart';
import 'package:flutter/foundation.dart';
/// Crisp /// Crisp
class KRCrispController extends GetxController { class KRCrispController extends GetxController {
@ -47,7 +48,9 @@ class KRCrispController extends GetxController {
kr_isInitialized.value = true; kr_isInitialized.value = true;
} }
} catch (e) { } catch (e) {
if (kDebugMode) {
print('初始化 Crisp 时出错: $e'); print('初始化 Crisp 时出错: $e');
}
if (!_kr_isDisposed) { if (!_kr_isDisposed) {
kr_isInitialized.value = false; kr_isInitialized.value = false;
} }
@ -125,9 +128,13 @@ class KRCrispController extends GetxController {
'device_id': deviceId, 'device_id': deviceId,
}); });
if (kDebugMode) {
print('Crisp 初始化完成'); print('Crisp 初始化完成');
}
} catch (e) { } catch (e) {
if (kDebugMode) {
print('初始化 Crisp 时出错: $e'); print('初始化 Crisp 时出错: $e');
}
crispController = null; crispController = null;
rethrow; rethrow;
} }
@ -155,9 +162,11 @@ class KRCrispController extends GetxController {
kr_isLoading.value = false; kr_isLoading.value = false;
} }
} catch (e) { } catch (e) {
if (kDebugMode) {
print('清理 Crisp 资源时出错: $e'); print('清理 Crisp 资源时出错: $e');
} }
} }
}
/// Crisp locale /// Crisp locale
/// 西 /// 西

View File

@ -29,6 +29,7 @@ import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart'; import 'package:kaer_with_panels/app/utils/kr_common_util.dart';
import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart'; import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart'; import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:flutter/foundation.dart';
class KRHomeController extends GetxController with WidgetsBindingObserver { class KRHomeController extends GetxController with WidgetsBindingObserver {
/// ///
@ -498,7 +499,9 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
void _bindConnectionStatus() { void _bindConnectionStatus() {
// //
ever(KRSingBoxImp.instance.kr_status, (status) { ever(KRSingBoxImp.instance.kr_status, (status) {
if (kDebugMode) {
print('🔵 Controller 收到状态变化: ${status.runtimeType}'); print('🔵 Controller 收到状态变化: ${status.runtimeType}');
}
KRLogUtil.kr_i('🔄 连接状态变化: $status', tag: 'HomeController'); KRLogUtil.kr_i('🔄 连接状态变化: $status', tag: 'HomeController');
KRLogUtil.kr_i('📊 当前状态类型: ${status.runtimeType}', tag: 'HomeController'); KRLogUtil.kr_i('📊 当前状态类型: ${status.runtimeType}', tag: 'HomeController');
@ -526,7 +529,9 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
break; break;
case SingboxStarted(): case SingboxStarted():
KRLogUtil.kr_i('🟢 状态: 已启动', tag: 'HomeController'); KRLogUtil.kr_i('🟢 状态: 已启动', tag: 'HomeController');
if (kDebugMode) {
print('🔵 状态变为 Started, 当前延迟=${kr_currentNodeLatency.value}'); print('🔵 状态变为 Started, 当前延迟=${kr_currentNodeLatency.value}');
}
// //
_cancelConnectionTimeout(); _cancelConnectionTimeout();
@ -538,11 +543,15 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
// 🔧 -1(),0() // 🔧 -1(),0()
if (kr_currentNodeLatency.value == -1) { if (kr_currentNodeLatency.value == -1) {
if (kDebugMode) {
print('🔵 强制将延迟从 -1 更新为 0'); print('🔵 强制将延迟从 -1 更新为 0');
}
kr_currentNodeLatency.value = 0; kr_currentNodeLatency.value = 0;
kr_currentNodeLatency.refresh(); // kr_currentNodeLatency.refresh(); //
if (kDebugMode) {
print('🔵 延迟值已刷新'); print('🔵 延迟值已刷新');
} }
}
// 🔧 // 🔧
_kr_updateLatencyOnConnected(); _kr_updateLatencyOnConnected();
@ -551,7 +560,9 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
kr_isConnected.refresh(); kr_isConnected.refresh();
// UI // UI
update(); update();
if (kDebugMode) {
print('🔵 状态更新完成,当前延迟=${kr_currentNodeLatency.value}'); print('🔵 状态更新完成,当前延迟=${kr_currentNodeLatency.value}');
}
break; break;
case SingboxStopping(): case SingboxStopping():
KRLogUtil.kr_i('🟠 状态: 正在停止', tag: 'HomeController'); KRLogUtil.kr_i('🟠 状态: 正在停止', tag: 'HomeController');
@ -637,12 +648,16 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
final currentStatus = KRSingBoxImp.instance.kr_status.value; final currentStatus = KRSingBoxImp.instance.kr_status.value;
KRLogUtil.kr_i('🔵 toggleSwitch 被调用: value=$value, currentStatus=$currentStatus', tag: 'HomeController'); KRLogUtil.kr_i('🔵 toggleSwitch 被调用: value=$value, currentStatus=$currentStatus', tag: 'HomeController');
if (kDebugMode) {
print('🔵 toggleSwitch: value=$value, currentStatus=$currentStatus'); print('🔵 toggleSwitch: value=$value, currentStatus=$currentStatus');
}
// 🔧 : hiddify-app "switching status, debounce" // 🔧 : hiddify-app "switching status, debounce"
if (currentStatus is SingboxStarting || currentStatus is SingboxStopping) { if (currentStatus is SingboxStarting || currentStatus is SingboxStopping) {
KRLogUtil.kr_i('🔄 正在切换中,忽略本次操作 (当前状态: $currentStatus)', tag: 'HomeController'); KRLogUtil.kr_i('🔄 正在切换中,忽略本次操作 (当前状态: $currentStatus)', tag: 'HomeController');
if (kDebugMode) {
print('🔵 忽略操作:正在切换中'); print('🔵 忽略操作:正在切换中');
}
return; return;
} }
@ -650,17 +665,23 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
if (value) { if (value) {
// //
KRLogUtil.kr_i('🔄 开始连接...', tag: 'HomeController'); KRLogUtil.kr_i('🔄 开始连接...', tag: 'HomeController');
if (kDebugMode) {
print('🔵 执行 kr_start()'); print('🔵 执行 kr_start()');
}
await KRSingBoxImp.instance.kr_start(); await KRSingBoxImp.instance.kr_start();
KRLogUtil.kr_i('✅ 连接命令已发送', tag: 'HomeController'); KRLogUtil.kr_i('✅ 连接命令已发送', tag: 'HomeController');
if (kDebugMode) {
print('🔵 kr_start() 完成'); print('🔵 kr_start() 完成');
}
// 🔧 : 3 // 🔧 : 3
await _waitForStatus(SingboxStarted, maxSeconds: 3); await _waitForStatus(SingboxStarted, maxSeconds: 3);
} else { } else {
// //
KRLogUtil.kr_i('🛑 开始断开连接...', tag: 'HomeController'); KRLogUtil.kr_i('🛑 开始断开连接...', tag: 'HomeController');
if (kDebugMode) {
print('🔵 执行 kr_stop()'); print('🔵 执行 kr_stop()');
}
await KRSingBoxImp.instance.kr_stop().timeout( await KRSingBoxImp.instance.kr_stop().timeout(
const Duration(seconds: 10), const Duration(seconds: 10),
onTimeout: () { onTimeout: () {
@ -669,32 +690,44 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
}, },
); );
KRLogUtil.kr_i('✅ 断开命令已发送', tag: 'HomeController'); KRLogUtil.kr_i('✅ 断开命令已发送', tag: 'HomeController');
if (kDebugMode) {
print('🔵 kr_stop() 完成'); print('🔵 kr_stop() 完成');
}
// 🔧 : 2 // 🔧 : 2
await _waitForStatus(SingboxStopped, maxSeconds: 2); await _waitForStatus(SingboxStopped, maxSeconds: 2);
} }
} catch (e) { } catch (e) {
KRLogUtil.kr_e('❌ 切换失败: $e', tag: 'HomeController'); KRLogUtil.kr_e('❌ 切换失败: $e', tag: 'HomeController');
if (kDebugMode) {
print('🔵 切换失败: $e'); print('🔵 切换失败: $e');
}
// //
kr_forceSyncConnectionStatus(); kr_forceSyncConnectionStatus();
} }
if (kDebugMode) {
print('🔵 toggleSwitch 完成,当前 kr_isConnected=${kr_isConnected.value}'); print('🔵 toggleSwitch 完成,当前 kr_isConnected=${kr_isConnected.value}');
} }
}
/// 🔧 /// 🔧
Future<void> _waitForStatus(Type expectedType, {int maxSeconds = 3}) async { Future<void> _waitForStatus(Type expectedType, {int maxSeconds = 3}) async {
if (kDebugMode) {
print('🔵 等待状态变为: $expectedType'); print('🔵 等待状态变为: $expectedType');
}
final startTime = DateTime.now(); final startTime = DateTime.now();
while (DateTime.now().difference(startTime).inSeconds < maxSeconds) { while (DateTime.now().difference(startTime).inSeconds < maxSeconds) {
final currentStatus = KRSingBoxImp.instance.kr_status.value; final currentStatus = KRSingBoxImp.instance.kr_status.value;
if (kDebugMode) {
print('🔵 当前状态: ${currentStatus.runtimeType}'); print('🔵 当前状态: ${currentStatus.runtimeType}');
}
if (currentStatus.runtimeType == expectedType) { if (currentStatus.runtimeType == expectedType) {
if (kDebugMode) {
print('🔵 状态已达到: $expectedType'); print('🔵 状态已达到: $expectedType');
}
// kr_isConnected // kr_isConnected
kr_forceSyncConnectionStatus(); kr_forceSyncConnectionStatus();
return; return;
@ -703,7 +736,9 @@ class KRHomeController extends GetxController with WidgetsBindingObserver {
await Future.delayed(const Duration(milliseconds: 100)); await Future.delayed(const Duration(milliseconds: 100));
} }
if (kDebugMode) {
print('🔵 等待超时,强制同步状态'); print('🔵 等待超时,强制同步状态');
}
kr_forceSyncConnectionStatus(); kr_forceSyncConnectionStatus();
} }

View File

@ -10,6 +10,7 @@ import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/singbox/model/singbox_status.dart'; import 'package:kaer_with_panels/singbox/model/singbox_status.dart';
import '../controllers/kr_home_controller.dart'; import '../controllers/kr_home_controller.dart';
import '../models/kr_home_views_status.dart'; import '../models/kr_home_views_status.dart';
import 'package:flutter/foundation.dart';
class KRHomeConnectionInfoView extends GetView<KRHomeController> { class KRHomeConnectionInfoView extends GetView<KRHomeController> {
const KRHomeConnectionInfoView({super.key}); const KRHomeConnectionInfoView({super.key});
@ -82,7 +83,9 @@ class KRHomeConnectionInfoView extends GetView<KRHomeController> {
// 🔧 使 Obx // 🔧 使 Obx
Obx(() { Obx(() {
final countryCode = controller.kr_getCurrentNodeCountry(); final countryCode = controller.kr_getCurrentNodeCountry();
if (kDebugMode) {
print('🌍 ConnectionInfo 更新,国家代码: $countryCode'); print('🌍 ConnectionInfo 更新,国家代码: $countryCode');
}
return KRCountryFlag( return KRCountryFlag(
countryCode: countryCode, countryCode: countryCode,
); );
@ -104,7 +107,9 @@ class KRHomeConnectionInfoView extends GetView<KRHomeController> {
children: [ children: [
Obx(() { Obx(() {
final delay = controller.kr_currentNodeLatency.value; final delay = controller.kr_currentNodeLatency.value;
if (kDebugMode) {
print('🔵 UI延迟显示更新: delay=$delay'); print('🔵 UI延迟显示更新: delay=$delay');
}
// //
Color getLatencyColor(int delay) { Color getLatencyColor(int delay) {
@ -227,7 +232,9 @@ class KRHomeConnectionInfoView extends GetView<KRHomeController> {
final isSwitching = status is SingboxStarting || status is SingboxStopping; final isSwitching = status is SingboxStarting || status is SingboxStopping;
// 🔧 // 🔧
if (kDebugMode) {
print('🔵 Switch UI 更新: status=${status.runtimeType}, isConnected=$isConnected, isSwitching=$isSwitching'); print('🔵 Switch UI 更新: status=${status.runtimeType}, isConnected=$isConnected, isSwitching=$isSwitching');
}
return CupertinoSwitch( return CupertinoSwitch(
value: isConnected, value: isConnected,
@ -235,7 +242,9 @@ class KRHomeConnectionInfoView extends GetView<KRHomeController> {
onChanged: isSwitching onChanged: isSwitching
? null ? null
: (bool value) { : (bool value) {
if (kDebugMode) {
print('🔵 Switch onChanged 触发: 请求=$value, 当前状态=$status'); print('🔵 Switch onChanged 触发: 请求=$value, 当前状态=$status');
}
controller.kr_toggleSwitch(value); controller.kr_toggleSwitch(value);
}, },
activeColor: Colors.blue, activeColor: Colors.blue,

View File

@ -16,6 +16,7 @@ import 'package:kaer_with_panels/app/widgets/kr_network_image.dart';
import '../../../widgets/kr_simple_loading.dart'; import '../../../widgets/kr_simple_loading.dart';
import '../../../../singbox/model/singbox_proxy_type.dart'; import '../../../../singbox/model/singbox_proxy_type.dart';
import 'package:flutter/foundation.dart';
/// ///
/// ///
@ -281,7 +282,9 @@ class KRHomeNodeListView extends GetView<KRHomeController> {
// 🔧 async // 🔧 async
onTap: () async { onTap: () async {
try { try {
if (kDebugMode) {
print('🔄 用户点击节点: ${server.tag}'); print('🔄 用户点击节点: ${server.tag}');
}
// 使 // 使
final success = await controller final success = await controller
.kr_performNodeSwitch(server.tag); .kr_performNodeSwitch(server.tag);
@ -290,12 +293,18 @@ class KRHomeNodeListView extends GetView<KRHomeController> {
if (success) { if (success) {
controller.kr_currentListStatus.value = controller.kr_currentListStatus.value =
KRHomeViewsListStatus.kr_none; KRHomeViewsListStatus.kr_none;
if (kDebugMode) {
print('✅ 节点切换成功,关闭列表'); print('✅ 节点切换成功,关闭列表');
}
} else { } else {
if (kDebugMode) {
print('❌ 节点切换失败,列表保持打开'); print('❌ 节点切换失败,列表保持打开');
} }
}
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 节点切换异常: $e'); print('❌ 节点切换异常: $e');
}
KRLogUtil.kr_e('节点切换异常: $e', KRLogUtil.kr_e('节点切换异常: $e',
tag: 'NodeListView'); tag: 'NodeListView');
} }

View File

@ -5,6 +5,7 @@ import 'package:latlong2/latlong.dart';
import '../../../utils/kr_fm_tc.dart'; import '../../../utils/kr_fm_tc.dart';
import '../controllers/kr_home_controller.dart'; import '../controllers/kr_home_controller.dart';
import '../../../utils/kr_log_util.dart'; import '../../../utils/kr_log_util.dart';
import 'package:flutter/foundation.dart';
/// ///
class KRHomeMapView extends GetView<KRHomeController> { class KRHomeMapView extends GetView<KRHomeController> {
@ -187,12 +188,16 @@ return GetBuilder<KRHomeController>(
/// ///
Marker _buildStyledMarker(dynamic node) { Marker _buildStyledMarker(dynamic node) {
if (kDebugMode) {
print("原始Marker${node}"); print("原始Marker${node}");
}
int type = 0; int type = 0;
MaterialColor markerColor = Colors.grey; MaterialColor markerColor = Colors.grey;
// //
bool status = controller.kr_isConnected.value; bool status = controller.kr_isConnected.value;
if (kDebugMode) {
print("连接状态:$status"); print("连接状态:$status");
}
if(status){ if(status){
if (node.urlTestDelay.value == 0) { if (node.urlTestDelay.value == 0) {
// 0使 // 0使

View File

@ -11,6 +11,7 @@ import 'package:kaer_with_panels/app/widgets/hi_help_entrance.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart'; import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart'; import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart';
import 'package:kaer_with_panels/app/services/kr_site_config_service.dart'; import 'package:kaer_with_panels/app/services/kr_site_config_service.dart';
import 'package:flutter/foundation.dart';
class KRLoginView extends GetView<KRLoginController> { class KRLoginView extends GetView<KRLoginController> {
const KRLoginView({super.key}); const KRLoginView({super.key});

View File

@ -10,6 +10,7 @@ import '../../../utils/kr_event_bus.dart';
import '../../../utils/kr_common_util.dart'; import '../../../utils/kr_common_util.dart';
import '../../../localization/app_translations.dart'; import '../../../localization/app_translations.dart';
import '../../../utils/kr_log_util.dart'; import '../../../utils/kr_log_util.dart';
import 'package:flutter/foundation.dart';
/// Tauri /// Tauri
class KROrderStatusController extends GetxController { class KROrderStatusController extends GetxController {
@ -71,12 +72,24 @@ class KROrderStatusController extends GetxController {
@override @override
void onInit() { void onInit() {
super.onInit(); super.onInit();
if (kDebugMode) {
print('═══════════════════════════════════════'); print('═══════════════════════════════════════');
}
if (kDebugMode) {
print('📊 订单状态页面初始化'); print('📊 订单状态页面初始化');
}
if (kDebugMode) {
print(' 订单号: $kr_order'); print(' 订单号: $kr_order');
}
if (kDebugMode) {
print(' 支付方式: $kr_paymentType'); print(' 支付方式: $kr_paymentType');
}
if (kDebugMode) {
print(' Checkout类型: $kr_checkoutType'); print(' Checkout类型: $kr_checkoutType');
}
if (kDebugMode) {
print('═══════════════════════════════════════'); print('═══════════════════════════════════════');
}
// //
kr_checkPaymentStatus(); kr_checkPaymentStatus();
@ -92,7 +105,9 @@ class KROrderStatusController extends GetxController {
@override @override
void onClose() { void onClose() {
if (kDebugMode) {
print('🔚 订单状态页面关闭,清理定时器'); print('🔚 订单状态页面关闭,清理定时器');
}
kr_timer?.cancel(); kr_timer?.cancel();
kr_countdownTimer?.cancel(); kr_countdownTimer?.cancel();
super.onClose(); super.onClose();
@ -100,7 +115,9 @@ class KROrderStatusController extends GetxController {
/// Tauri 5 /// Tauri 5
void kr_startCheckingPaymentStatus() { void kr_startCheckingPaymentStatus() {
if (kDebugMode) {
print('🔄 启动支付状态轮询每5秒检查一次'); print('🔄 启动支付状态轮询每5秒检查一次');
}
// 5 // 5
kr_timer = Timer.periodic(const Duration(seconds: 5), (timer) { kr_timer = Timer.periodic(const Duration(seconds: 5), (timer) {
@ -118,7 +135,9 @@ class KROrderStatusController extends GetxController {
if (kr_orderCreatedAt == null) { if (kr_orderCreatedAt == null) {
// //
kr_formattedCountdown.value = '15:00'; kr_formattedCountdown.value = '15:00';
if (kDebugMode) {
print('⏱️ 倒计时更新: 等待订单创建时间...'); print('⏱️ 倒计时更新: 等待订单创建时间...');
}
return; return;
} }
@ -128,12 +147,24 @@ class KROrderStatusController extends GetxController {
final timeLeft = targetTime - now; final timeLeft = targetTime - now;
if (kDebugMode) {
print('⏱️ 倒计时调试信息:'); print('⏱️ 倒计时调试信息:');
}
if (kDebugMode) {
print(' 当前时间(ms): $now'); print(' 当前时间(ms): $now');
}
if (kDebugMode) {
print(' 创建时间(ms): $createdAt'); print(' 创建时间(ms): $createdAt');
}
if (kDebugMode) {
print(' 目标时间(ms): $targetTime'); print(' 目标时间(ms): $targetTime');
}
if (kDebugMode) {
print(' 剩余时间(ms): $timeLeft'); print(' 剩余时间(ms): $timeLeft');
}
if (kDebugMode) {
print(' 剩余时间(秒): ${(timeLeft / 1000).floor()}'); print(' 剩余时间(秒): ${(timeLeft / 1000).floor()}');
}
if (timeLeft > 0) { if (timeLeft > 0) {
kr_countdown.value = timeLeft; kr_countdown.value = timeLeft;
@ -141,7 +172,9 @@ class KROrderStatusController extends GetxController {
final minutes = (timeLeft / 60000).floor(); final minutes = (timeLeft / 60000).floor();
final seconds = ((timeLeft % 60000) / 1000).floor(); final seconds = ((timeLeft % 60000) / 1000).floor();
kr_formattedCountdown.value = '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'; kr_formattedCountdown.value = '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
if (kDebugMode) {
print(' 格式化倒计时: ${kr_formattedCountdown.value}'); print(' 格式化倒计时: ${kr_formattedCountdown.value}');
}
} else { } else {
// //
kr_countdown.value = 0; kr_countdown.value = 0;
@ -149,7 +182,9 @@ class KROrderStatusController extends GetxController {
kr_countdownTimer?.cancel(); kr_countdownTimer?.cancel();
kr_timer?.cancel(); kr_timer?.cancel();
if (kDebugMode) {
print('⏱️ 订单支付超时15分钟'); print('⏱️ 订单支付超时15分钟');
}
kr_statusTitle.value = AppTranslations.kr_orderStatus.closedTitle; kr_statusTitle.value = AppTranslations.kr_orderStatus.closedTitle;
kr_statusDescription.value = AppTranslations.kr_orderStatus.timeoutMessage; kr_statusDescription.value = AppTranslations.kr_orderStatus.timeoutMessage;
kr_isLoading.value = false; kr_isLoading.value = false;
@ -161,14 +196,18 @@ class KROrderStatusController extends GetxController {
final now = DateTime.now().millisecondsSinceEpoch; final now = DateTime.now().millisecondsSinceEpoch;
try { try {
if (kDebugMode) {
print('🔍 检查订单状态 [${kr_order}]'); print('🔍 检查订单状态 [${kr_order}]');
}
// 使 // 使
final result = await kr_subscribeApi.kr_queryOrderStatus(kr_order); final result = await kr_subscribeApi.kr_queryOrderStatus(kr_order);
result.fold( result.fold(
(error) { (error) {
if (kDebugMode) {
print('❌ 查询失败: ${error.msg}'); print('❌ 查询失败: ${error.msg}');
}
KRLogUtil.kr_e('检查支付状态失败: ${error.msg}', tag: 'OrderStatusController'); KRLogUtil.kr_e('检查支付状态失败: ${error.msg}', tag: 'OrderStatusController');
kr_isLoading.value = false; kr_isLoading.value = false;
kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle; kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle;
@ -186,13 +225,23 @@ class KROrderStatusController extends GetxController {
isMilliseconds ? timestamp : timestamp * 1000 isMilliseconds ? timestamp : timestamp * 1000
); );
if (kDebugMode) {
print('📅 订单创建时间: ${kr_orderCreatedAt}'); print('📅 订单创建时间: ${kr_orderCreatedAt}');
}
if (kDebugMode) {
print('📅 原始时间戳: $timestamp'); print('📅 原始时间戳: $timestamp');
}
if (kDebugMode) {
print('📅 时间戳类型: ${isMilliseconds ? "毫秒级" : "秒级"}'); print('📅 时间戳类型: ${isMilliseconds ? "毫秒级" : "秒级"}');
}
if (kDebugMode) {
print('📅 转换后时间戳(ms): ${kr_orderCreatedAt!.millisecondsSinceEpoch}'); print('📅 转换后时间戳(ms): ${kr_orderCreatedAt!.millisecondsSinceEpoch}');
} }
}
if (kDebugMode) {
print('📊 订单状态: ${kr_orderStatus.kr_status} (${_getStatusName(kr_orderStatus.kr_status)})'); print('📊 订单状态: ${kr_orderStatus.kr_status} (${_getStatusName(kr_orderStatus.kr_status)})');
}
switch (kr_orderStatus.kr_status) { switch (kr_orderStatus.kr_status) {
case kr_statusPending: case kr_statusPending:
@ -204,7 +253,9 @@ class KROrderStatusController extends GetxController {
case kr_statusPaid: case kr_statusPaid:
// //
if (kDebugMode) {
print('✅ 订单已支付,等待确认...'); print('✅ 订单已支付,等待确认...');
}
kr_statusTitle.value = AppTranslations.kr_orderStatus.paidTitle; kr_statusTitle.value = AppTranslations.kr_orderStatus.paidTitle;
kr_statusDescription.value = AppTranslations.kr_orderStatus.paidDescription; kr_statusDescription.value = AppTranslations.kr_orderStatus.paidDescription;
kr_statusIcon.value = 'payment_success'; kr_statusIcon.value = 'payment_success';
@ -212,7 +263,9 @@ class KROrderStatusController extends GetxController {
case kr_statusFinished: case kr_statusFinished:
// //
if (kDebugMode) {
print('🎉 订单完成!停止轮询'); print('🎉 订单完成!停止轮询');
}
kr_isPaymentSuccess.value = true; kr_isPaymentSuccess.value = true;
kr_isLoading.value = false; kr_isLoading.value = false;
kr_timer?.cancel(); kr_timer?.cancel();
@ -226,7 +279,9 @@ class KROrderStatusController extends GetxController {
case kr_statusClose: case kr_statusClose:
// //
if (kDebugMode) {
print('❌ 订单已关闭'); print('❌ 订单已关闭');
}
kr_isLoading.value = false; kr_isLoading.value = false;
kr_timer?.cancel(); kr_timer?.cancel();
kr_countdownTimer?.cancel(); kr_countdownTimer?.cancel();
@ -237,7 +292,9 @@ class KROrderStatusController extends GetxController {
case kr_statusFailed: case kr_statusFailed:
// //
if (kDebugMode) {
print('❌ 支付失败'); print('❌ 支付失败');
}
kr_isLoading.value = false; kr_isLoading.value = false;
kr_timer?.cancel(); kr_timer?.cancel();
kr_countdownTimer?.cancel(); kr_countdownTimer?.cancel();
@ -248,7 +305,9 @@ class KROrderStatusController extends GetxController {
default: default:
// //
if (kDebugMode) {
print('⚠️ 未知状态: ${kr_orderStatus.kr_status}'); print('⚠️ 未知状态: ${kr_orderStatus.kr_status}');
}
kr_isLoading.value = false; kr_isLoading.value = false;
kr_timer?.cancel(); kr_timer?.cancel();
kr_countdownTimer?.cancel(); kr_countdownTimer?.cancel();
@ -262,7 +321,9 @@ class KROrderStatusController extends GetxController {
}, },
); );
} catch (error) { } catch (error) {
if (kDebugMode) {
print('❌ 异常: $error'); print('❌ 异常: $error');
}
KRLogUtil.kr_e('检查支付状态失败: $error', tag: 'OrderStatusController'); KRLogUtil.kr_e('检查支付状态失败: $error', tag: 'OrderStatusController');
kr_isLoading.value = false; kr_isLoading.value = false;
kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle; kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle;

View File

@ -13,6 +13,7 @@ import '../../../model/response/kr_payment_methods.dart';
import '../../../routes/app_pages.dart'; import '../../../routes/app_pages.dart';
import '../../../services/api_service/kr_api.user.dart'; import '../../../services/api_service/kr_api.user.dart';
import '../../../utils/kr_event_bus.dart'; import '../../../utils/kr_event_bus.dart';
import 'package:flutter/foundation.dart';
/// ///
/// ///

View File

@ -1,5 +1,6 @@
import 'dart:convert'; import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart'; import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/common/app_config.dart'; import 'package:kaer_with_panels/app/common/app_config.dart';
@ -30,14 +31,17 @@ class BaseResponse<T> {
if (shouldDecrypt && cipherText.isNotEmpty && nonce.isNotEmpty) { if (shouldDecrypt && cipherText.isNotEmpty && nonce.isNotEmpty) {
try { try {
if (kDebugMode) {
print('═══════════════════════════════════════'); print('═══════════════════════════════════════');
print('🔐 检测到加密响应,开始解密...'); print('🔐 检测到加密响应,开始解密...');
print('📥 加密数据长度: ${cipherText.length} 字符'); print('📥 加密数据长度: ${cipherText.length} 字符');
print('⏰ 时间戳: $nonce'); print('⏰ 时间戳: $nonce');
}
final decrypted = KRAesUtil.decryptData(cipherText, nonce, AppConfig.kr_encryptionKey); final decrypted = KRAesUtil.decryptData(cipherText, nonce, AppConfig.kr_encryptionKey);
body = jsonDecode(decrypted); body = jsonDecode(decrypted);
if (kDebugMode) {
print('✅ 解密成功'); print('✅ 解密成功');
print(''); print('');
print('📦 解密后的完整数据:'); print('📦 解密后的完整数据:');
@ -45,12 +49,15 @@ class BaseResponse<T> {
final bodyStr = JsonEncoder.withIndent(' ').convert(body); final bodyStr = JsonEncoder.withIndent(' ').convert(body);
print(bodyStr); print(bodyStr);
print('═══════════════════════════════════════'); print('═══════════════════════════════════════');
}
KRLogUtil.kr_i('🔓 解密成功', tag: 'BaseResponse'); KRLogUtil.kr_i('🔓 解密成功', tag: 'BaseResponse');
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 解密失败: $e'); print('❌ 解密失败: $e');
print('⚠️ 将使用原始数据'); print('⚠️ 将使用原始数据');
print('═══════════════════════════════════════'); print('═══════════════════════════════════════');
}
KRLogUtil.kr_e('❌ 解密失败: $e', tag: 'BaseResponse'); KRLogUtil.kr_e('❌ 解密失败: $e', tag: 'BaseResponse');
body = dataMap; body = dataMap;
} }

View File

@ -22,6 +22,7 @@ import 'package:loggy/loggy.dart';
import '../utils/kr_aes_util.dart'; import '../utils/kr_aes_util.dart';
import '../utils/kr_log_util.dart'; import '../utils/kr_log_util.dart';
import 'package:flutter/foundation.dart';
// import 'package:video/app/utils/common_util.dart'; // import 'package:video/app/utils/common_util.dart';
// import 'package:video/app/utils/log_util.dart'; // import 'package:video/app/utils/log_util.dart';
@ -316,32 +317,48 @@ class HttpUtil {
class MyInterceptor extends Interceptor { class MyInterceptor extends Interceptor {
@override @override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) { void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
if (kDebugMode) {
print('>>> Request │ ${options.method}${options.uri}'); print('>>> Request │ ${options.method}${options.uri}');
}
if (options.data != null) { if (options.data != null) {
if (kDebugMode) {
print('Body: ${options.data}'); print('Body: ${options.data}');
} }
}
handler.next(options); handler.next(options);
} }
@override @override
void onResponse(Response response, ResponseInterceptorHandler handler) { void onResponse(Response response, ResponseInterceptorHandler handler) {
if (kDebugMode) {
print('<<< Response │ ${response.requestOptions.method}${response.statusCode} ${response.statusMessage}${response.requestOptions.uri}'); print('<<< Response │ ${response.requestOptions.method}${response.statusCode} ${response.statusMessage}${response.requestOptions.uri}');
}
if (response.data != null) { if (response.data != null) {
if (kDebugMode) {
print('Body: ${response.data}'); print('Body: ${response.data}');
} }
}
handler.next(response); handler.next(response);
} }
@override @override
void onError(DioException err, ErrorInterceptorHandler handler) { void onError(DioException err, ErrorInterceptorHandler handler) {
if (kDebugMode) {
print('<<< Error │ ${err.requestOptions.method}${err.requestOptions.uri}'); print('<<< Error │ ${err.requestOptions.method}${err.requestOptions.uri}');
}
if (kDebugMode) {
print('Error Type: ${err.type}'); print('Error Type: ${err.type}');
}
if (err.message != null) { if (err.message != null) {
if (kDebugMode) {
print('Error Message: ${err.message}'); print('Error Message: ${err.message}');
} }
}
if (err.response?.data != null) { if (err.response?.data != null) {
if (kDebugMode) {
print('Response Data: ${err.response?.data}'); print('Response Data: ${err.response?.data}');
} }
}
handler.next(err); handler.next(err);
} }
} }
@ -350,17 +367,25 @@ class MyInterceptor extends Interceptor {
class _KRSimpleHttpInterceptor extends Interceptor { class _KRSimpleHttpInterceptor extends Interceptor {
@override @override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) { void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
if (kDebugMode) {
print('>>> Request │ ${options.method}${options.uri}'); print('>>> Request │ ${options.method}${options.uri}');
}
if (options.data != null) { if (options.data != null) {
if (kDebugMode) {
print('Body: ${options.data}'); print('Body: ${options.data}');
}
// data time // data time
if (options.data is Map<String, dynamic>) { if (options.data is Map<String, dynamic>) {
final data = options.data as Map<String, dynamic>; final data = options.data as Map<String, dynamic>;
if (data.containsKey('data') && data.containsKey('time')) { if (data.containsKey('data') && data.containsKey('time')) {
try { try {
if (kDebugMode) {
print(''); print('');
}
if (kDebugMode) {
print('🔐 检测到加密请求,正在解密...'); print('🔐 检测到加密请求,正在解密...');
}
// //
final encryptedData = data['data'] as String; final encryptedData = data['data'] as String;
final nonce = data['time'] as String; final nonce = data['time'] as String;
@ -369,29 +394,41 @@ class _KRSimpleHttpInterceptor extends Interceptor {
nonce, nonce,
AppConfig.kr_encryptionKey, AppConfig.kr_encryptionKey,
); );
if (kDebugMode) {
print('🔓 解密后的原始请求数据:'); print('🔓 解密后的原始请求数据:');
}
// JSON // JSON
try { try {
final jsonData = jsonDecode(decrypted); final jsonData = jsonDecode(decrypted);
final prettyJson = JsonEncoder.withIndent(' ').convert(jsonData); final prettyJson = JsonEncoder.withIndent(' ').convert(jsonData);
if (kDebugMode) {
print(prettyJson); print(prettyJson);
}
} catch (_) { } catch (_) {
if (kDebugMode) {
print(decrypted); print(decrypted);
} }
}
} catch (e) { } catch (e) {
if (kDebugMode) {
print('⚠️ 请求解密失败: $e'); print('⚠️ 请求解密失败: $e');
} }
} }
} }
} }
}
handler.next(options); handler.next(options);
} }
@override @override
void onResponse(Response response, ResponseInterceptorHandler handler) { void onResponse(Response response, ResponseInterceptorHandler handler) {
if (kDebugMode) {
print('<<< Response │ ${response.requestOptions.method}${response.statusCode} ${response.statusMessage}${response.requestOptions.uri}'); print('<<< Response │ ${response.requestOptions.method}${response.statusCode} ${response.statusMessage}${response.requestOptions.uri}');
}
if (response.data != null) { if (response.data != null) {
if (kDebugMode) {
print('Body: ${response.data}'); print('Body: ${response.data}');
}
// data time // data time
if (response.data is Map<String, dynamic>) { if (response.data is Map<String, dynamic>) {
@ -403,8 +440,12 @@ class _KRSimpleHttpInterceptor extends Interceptor {
nestedData.containsKey('data') && nestedData.containsKey('data') &&
nestedData.containsKey('time')) { nestedData.containsKey('time')) {
try { try {
if (kDebugMode) {
print(''); print('');
}
if (kDebugMode) {
print('🔐 检测到加密响应,正在解密...'); print('🔐 检测到加密响应,正在解密...');
}
// //
final encryptedData = nestedData['data'] as String; final encryptedData = nestedData['data'] as String;
final nonce = nestedData['time'] as String; final nonce = nestedData['time'] as String;
@ -413,34 +454,50 @@ class _KRSimpleHttpInterceptor extends Interceptor {
nonce, nonce,
AppConfig.kr_encryptionKey, AppConfig.kr_encryptionKey,
); );
print('🔓 解密后的原始响应数据: ${response.requestOptions.uri}'); if (kDebugMode) {
print('🔓 解密后的原始响应数据:');
}
// JSON // JSON
try { try {
final jsonData = jsonDecode(decrypted); final jsonData = jsonDecode(decrypted);
final prettyJson = JsonEncoder.withIndent(' ').convert(jsonData); final prettyJson = JsonEncoder.withIndent(' ').convert(jsonData);
if (kDebugMode) {
print(prettyJson); print(prettyJson);
}
} catch (_) { } catch (_) {
if (kDebugMode) {
print(decrypted); print(decrypted);
} }
}
} catch (e) { } catch (e) {
if (kDebugMode) {
print('⚠️ 响应解密失败: $e'); print('⚠️ 响应解密失败: $e');
} }
} }
} }
} }
}
handler.next(response); handler.next(response);
} }
@override @override
void onError(DioException err, ErrorInterceptorHandler handler) { void onError(DioException err, ErrorInterceptorHandler handler) {
if (kDebugMode) {
print('<<< Error │ ${err.requestOptions.method}${err.requestOptions.uri}'); print('<<< Error │ ${err.requestOptions.method}${err.requestOptions.uri}');
}
if (kDebugMode) {
print('Error Type: ${err.type}'); print('Error Type: ${err.type}');
}
if (err.message != null) { if (err.message != null) {
if (kDebugMode) {
print('Error Message: ${err.message}'); print('Error Message: ${err.message}');
} }
}
if (err.response?.data != null) { if (err.response?.data != null) {
if (kDebugMode) {
print('Response Data: ${err.response?.data}'); print('Response Data: ${err.response?.data}');
} }
}
handler.next(err); handler.next(err);
} }
} }

View File

@ -1,4 +1,4 @@
import 'dart:io'; import 'dart:io' as io;
import 'dart:math'; import 'dart:math';
import 'dart:convert'; import 'dart:convert';
@ -21,6 +21,8 @@ import '../kr_device_info_service.dart';
import '../kr_site_config_service.dart'; import '../kr_site_config_service.dart';
import '../../common/app_config.dart'; import '../../common/app_config.dart';
import 'package:dio/dio.dart' as dio; import 'package:dio/dio.dart' as dio;
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:flutter/foundation.dart';
class KRAuthApi { class KRAuthApi {
/// ///
@ -465,17 +467,17 @@ class KRAuthApi {
} }
String _kr_getUserAgent() { String _kr_getUserAgent() {
if (Platform.isAndroid) { if (io.Platform.isAndroid) {
return 'android'; return 'android';
} else if (Platform.isIOS) { } else if (io.Platform.isIOS) {
return 'ios'; return 'ios';
} else if (Platform.isMacOS) { } else if (io.Platform.isMacOS) {
return 'mac'; return 'mac';
} else if (Platform.isWindows) { } else if (io.Platform.isWindows) {
return 'windows'; return 'windows';
} else if (Platform.isLinux) { } else if (io.Platform.isLinux) {
return 'linux'; return 'linux';
} else if (Platform.isFuchsia) { } else if (io.Platform.isFuchsia) {
return 'harmony'; return 'harmony';
} else { } else {
return 'unknown'; return 'unknown';

View File

@ -27,26 +27,32 @@ class KRDeviceInfoService {
/// ///
Future<void> initialize() async { Future<void> initialize() async {
try { try {
if (kDebugMode) {
print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
print('📱 开始初始化设备信息服务'); print('📱 开始初始化设备信息服务');
print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
}
KRLogUtil.kr_i('📱 开始初始化设备信息', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 开始初始化设备信息', tag: 'KRDeviceInfoService');
_deviceId = await _getDeviceId(); _deviceId = await _getDeviceId();
_deviceDetails = await _getDeviceDetails(); _deviceDetails = await _getDeviceDetails();
if (kDebugMode) {
print('✅ 设备信息初始化成功'); print('✅ 设备信息初始化成功');
print('📱 设备ID: $_deviceId'); print('📱 设备ID: $_deviceId');
print('📱 设备平台: ${getPlatformName()}'); print('📱 设备平台: ${getPlatformName()}');
print('📱 设备型号: ${getDeviceModel()}'); print('📱 设备型号: ${getDeviceModel()}');
print('📱 系统版本: ${getOSVersion()}'); print('📱 系统版本: ${getOSVersion()}');
print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
}
KRLogUtil.kr_i('✅ 设备信息初始化成功', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('✅ 设备信息初始化成功', tag: 'KRDeviceInfoService');
KRLogUtil.kr_i('📱 设备ID - $_deviceId', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 设备ID - $_deviceId', tag: 'KRDeviceInfoService');
KRLogUtil.kr_i('📱 设备详情 - $_deviceDetails', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 设备详情 - $_deviceDetails', tag: 'KRDeviceInfoService');
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 设备信息初始化失败: $e'); print('❌ 设备信息初始化失败: $e');
}
KRLogUtil.kr_e('❌ 设备信息初始化失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ 设备信息初始化失败 - $e', tag: 'KRDeviceInfoService');
} }
} }
@ -79,7 +85,9 @@ class KRDeviceInfoService {
return identifier; return identifier;
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 获取设备ID失败: $e'); print('❌ 获取设备ID失败: $e');
}
KRLogUtil.kr_e('❌ 获取设备ID失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ 获取设备ID失败 - $e', tag: 'KRDeviceInfoService');
// ,ID // ,ID
return await _getOrCreateStoredDeviceId(); return await _getOrCreateStoredDeviceId();
@ -119,12 +127,16 @@ class KRDeviceInfoService {
final bytes = utf8.encode(combined); final bytes = utf8.encode(combined);
final hash = sha256.convert(bytes); final hash = sha256.convert(bytes);
if (kDebugMode) {
print('📱 Android多因子ID生成 - 因子数: ${factors.where((f) => f != null && f.isNotEmpty).length}'); print('📱 Android多因子ID生成 - 因子数: ${factors.where((f) => f != null && f.isNotEmpty).length}');
}
KRLogUtil.kr_i('📱 Android多因子ID - $hash', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 Android多因子ID - $hash', tag: 'KRDeviceInfoService');
return hash.toString(); return hash.toString();
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ Android设备ID获取失败: $e'); print('❌ Android设备ID获取失败: $e');
}
KRLogUtil.kr_e('❌ Android设备ID获取失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ Android设备ID获取失败 - $e', tag: 'KRDeviceInfoService');
return ''; return '';
} }
@ -157,12 +169,16 @@ class KRDeviceInfoService {
final bytes = utf8.encode(combined); final bytes = utf8.encode(combined);
final hash = sha256.convert(bytes); final hash = sha256.convert(bytes);
if (kDebugMode) {
print('📱 iOS多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}'); print('📱 iOS多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}');
}
KRLogUtil.kr_i('📱 iOS多因子ID - $hash', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 iOS多因子ID - $hash', tag: 'KRDeviceInfoService');
return hash.toString(); return hash.toString();
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ iOS设备ID获取失败: $e'); print('❌ iOS设备ID获取失败: $e');
}
KRLogUtil.kr_e('❌ iOS设备ID获取失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ iOS设备ID获取失败 - $e', tag: 'KRDeviceInfoService');
return ''; return '';
} }
@ -193,12 +209,16 @@ class KRDeviceInfoService {
final bytes = utf8.encode(combined); final bytes = utf8.encode(combined);
final hash = sha256.convert(bytes); final hash = sha256.convert(bytes);
if (kDebugMode) {
print('📱 macOS多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}'); print('📱 macOS多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}');
}
KRLogUtil.kr_i('📱 macOS多因子ID - $hash', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 macOS多因子ID - $hash', tag: 'KRDeviceInfoService');
return hash.toString(); return hash.toString();
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ macOS设备ID获取失败: $e'); print('❌ macOS设备ID获取失败: $e');
}
KRLogUtil.kr_e('❌ macOS设备ID获取失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ macOS设备ID获取失败 - $e', tag: 'KRDeviceInfoService');
return ''; return '';
} }
@ -229,12 +249,16 @@ class KRDeviceInfoService {
final bytes = utf8.encode(combined); final bytes = utf8.encode(combined);
final hash = sha256.convert(bytes); final hash = sha256.convert(bytes);
if (kDebugMode) {
print('📱 Windows多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}'); print('📱 Windows多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}');
}
KRLogUtil.kr_i('📱 Windows多因子ID - $hash', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 Windows多因子ID - $hash', tag: 'KRDeviceInfoService');
return hash.toString(); return hash.toString();
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ Windows设备ID获取失败: $e'); print('❌ Windows设备ID获取失败: $e');
}
KRLogUtil.kr_e('❌ Windows设备ID获取失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ Windows设备ID获取失败 - $e', tag: 'KRDeviceInfoService');
return ''; return '';
} }
@ -265,12 +289,16 @@ class KRDeviceInfoService {
final bytes = utf8.encode(combined); final bytes = utf8.encode(combined);
final hash = sha256.convert(bytes); final hash = sha256.convert(bytes);
if (kDebugMode) {
print('📱 Linux多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}'); print('📱 Linux多因子ID生成 - 因子数: ${factors.where((f) => f.isNotEmpty).length}');
}
KRLogUtil.kr_i('📱 Linux多因子ID - $hash', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 Linux多因子ID - $hash', tag: 'KRDeviceInfoService');
return hash.toString(); return hash.toString();
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ Linux设备ID获取失败: $e'); print('❌ Linux设备ID获取失败: $e');
}
KRLogUtil.kr_e('❌ Linux设备ID获取失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ Linux设备ID获取失败 - $e', tag: 'KRDeviceInfoService');
return ''; return '';
} }
@ -288,16 +316,22 @@ class KRDeviceInfoService {
// UUID // UUID
storedId = _generateUniqueId(); storedId = _generateUniqueId();
await storage.kr_saveData(key: key, value: storedId); await storage.kr_saveData(key: key, value: storedId);
if (kDebugMode) {
print('📱 生成新的设备ID: $storedId'); print('📱 生成新的设备ID: $storedId');
}
KRLogUtil.kr_i('📱 生成新的设备ID - $storedId', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 生成新的设备ID - $storedId', tag: 'KRDeviceInfoService');
} else { } else {
if (kDebugMode) {
print('📱 使用存储的设备ID: $storedId'); print('📱 使用存储的设备ID: $storedId');
}
KRLogUtil.kr_i('📱 使用存储的设备ID - $storedId', tag: 'KRDeviceInfoService'); KRLogUtil.kr_i('📱 使用存储的设备ID - $storedId', tag: 'KRDeviceInfoService');
} }
return storedId; return storedId;
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 获取存储的设备ID失败: $e'); print('❌ 获取存储的设备ID失败: $e');
}
KRLogUtil.kr_e('❌ 获取存储的设备ID失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ 获取存储的设备ID失败 - $e', tag: 'KRDeviceInfoService');
return _generateUniqueId(); return _generateUniqueId();
} }
@ -383,7 +417,9 @@ class KRDeviceInfoService {
'platform': 'unknown', 'platform': 'unknown',
}; };
} catch (e) { } catch (e) {
if (kDebugMode) {
print('❌ 获取设备详情失败: $e'); print('❌ 获取设备详情失败: $e');
}
KRLogUtil.kr_e('❌ 获取设备详情失败 - $e', tag: 'KRDeviceInfoService'); KRLogUtil.kr_e('❌ 获取设备详情失败 - $e', tag: 'KRDeviceInfoService');
return { return {
'platform': 'unknown', 'platform': 'unknown',

View File

@ -47,33 +47,53 @@ class KRSiteConfigService extends ChangeNotifier {
/// ///
Future<bool> initialize() async { Future<bool> initialize() async {
try { try {
if (kDebugMode) {
print('🔧 KRSiteConfigService.initialize() 开始执行'); print('🔧 KRSiteConfigService.initialize() 开始执行');
}
KRLogUtil.kr_i('🔧 开始初始化网站配置', tag: 'KRSiteConfigService'); KRLogUtil.kr_i('🔧 开始初始化网站配置', tag: 'KRSiteConfigService');
// Debug 使 // Debug 使
final baseUrl = AppConfig().baseUrl; final baseUrl = AppConfig().baseUrl;
if (kDebugMode) {
print('📍 baseUrl = $baseUrl'); print('📍 baseUrl = $baseUrl');
}
final url = '$baseUrl/v1/common/site/config'; final url = '$baseUrl/v1/common/site/config';
if (kDebugMode) {
print('📍 完整URL = $url'); print('📍 完整URL = $url');
}
KRLogUtil.kr_i('📤 请求网站配置 - $url', tag: 'KRSiteConfigService'); KRLogUtil.kr_i('📤 请求网站配置 - $url', tag: 'KRSiteConfigService');
if (kDebugMode) {
print('📤 准备发送 GET 请求到: $url'); print('📤 准备发送 GET 请求到: $url');
}
if (kDebugMode) {
print('⏱️ 超时配置: connectTimeout=10s, sendTimeout=10s, receiveTimeout=10s'); print('⏱️ 超时配置: connectTimeout=10s, sendTimeout=10s, receiveTimeout=10s');
}
if (kDebugMode) {
print('⏳ 开始发送请求...'); print('⏳ 开始发送请求...');
}
final startTime = DateTime.now(); final startTime = DateTime.now();
final response = await _dio.get(url); final response = await _dio.get(url);
final endTime = DateTime.now(); final endTime = DateTime.now();
final duration = endTime.difference(startTime).inMilliseconds; final duration = endTime.difference(startTime).inMilliseconds;
if (kDebugMode) {
print('⏱️ 请求耗时: ${duration}ms'); print('⏱️ 请求耗时: ${duration}ms');
}
if (kDebugMode) {
print('✅ 请求完成,状态码: ${response.statusCode}'); print('✅ 请求完成,状态码: ${response.statusCode}');
}
KRLogUtil.kr_i('📥 响应状态码 - ${response.statusCode}', tag: 'KRSiteConfigService'); KRLogUtil.kr_i('📥 响应状态码 - ${response.statusCode}', tag: 'KRSiteConfigService');
if (response.statusCode == 200) { if (response.statusCode == 200) {
final responseData = response.data; final responseData = response.data;
if (kDebugMode) {
print('📥 响应数据类型: ${responseData.runtimeType}'); print('📥 响应数据类型: ${responseData.runtimeType}');
}
if (kDebugMode) {
print('📥 响应数据: $responseData'); print('📥 响应数据: $responseData');
}
KRLogUtil.kr_i('📥 响应数据 - $responseData', tag: 'KRSiteConfigService'); KRLogUtil.kr_i('📥 响应数据 - $responseData', tag: 'KRSiteConfigService');
if (responseData['code'] == 200) { if (responseData['code'] == 200) {
@ -96,24 +116,46 @@ class KRSiteConfigService extends ChangeNotifier {
return false; return false;
} }
} on DioException catch (e, stackTrace) { } on DioException catch (e, stackTrace) {
if (kDebugMode) {
print('❌ Dio请求异常: ${e.type}'); print('❌ Dio请求异常: ${e.type}');
}
if (kDebugMode) {
print('❌ 错误信息: ${e.message}'); print('❌ 错误信息: ${e.message}');
}
if (kDebugMode) {
print('❌ 请求URL: ${e.requestOptions.uri}'); print('❌ 请求URL: ${e.requestOptions.uri}');
}
if (kDebugMode) {
print('❌ 连接超时: ${e.requestOptions.connectTimeout}'); print('❌ 连接超时: ${e.requestOptions.connectTimeout}');
}
if (kDebugMode) {
print('❌ 发送超时: ${e.requestOptions.sendTimeout}'); print('❌ 发送超时: ${e.requestOptions.sendTimeout}');
}
if (kDebugMode) {
print('❌ 接收超时: ${e.requestOptions.receiveTimeout}'); print('❌ 接收超时: ${e.requestOptions.receiveTimeout}');
}
if (e.response != null) { if (e.response != null) {
if (kDebugMode) {
print('❌ 响应状态码: ${e.response?.statusCode}'); print('❌ 响应状态码: ${e.response?.statusCode}');
}
if (kDebugMode) {
print('❌ 响应数据: ${e.response?.data}'); print('❌ 响应数据: ${e.response?.data}');
} }
}
if (kDebugMode) {
print('📚 堆栈跟踪: $stackTrace'); print('📚 堆栈跟踪: $stackTrace');
}
KRLogUtil.kr_e('❌ Dio异常 - ${e.type}: ${e.message}', tag: 'KRSiteConfigService'); KRLogUtil.kr_e('❌ Dio异常 - ${e.type}: ${e.message}', tag: 'KRSiteConfigService');
KRLogUtil.kr_e('📚 堆栈: $stackTrace', tag: 'KRSiteConfigService'); KRLogUtil.kr_e('📚 堆栈: $stackTrace', tag: 'KRSiteConfigService');
return false; return false;
} catch (e, stackTrace) { } catch (e, stackTrace) {
if (kDebugMode) {
print('❌ 未知异常: $e'); print('❌ 未知异常: $e');
}
if (kDebugMode) {
print('📚 堆栈跟踪: $stackTrace'); print('📚 堆栈跟踪: $stackTrace');
}
KRLogUtil.kr_e('❌ 初始化失败 - $e', tag: 'KRSiteConfigService'); KRLogUtil.kr_e('❌ 初始化失败 - $e', tag: 'KRSiteConfigService');
KRLogUtil.kr_e('📚 堆栈: $stackTrace', tag: 'KRSiteConfigService'); KRLogUtil.kr_e('📚 堆栈: $stackTrace', tag: 'KRSiteConfigService');
return false; return false;

View File

@ -22,6 +22,7 @@ import '../../utils/kr_country_util.dart';
import '../../utils/kr_log_util.dart'; import '../../utils/kr_log_util.dart';
import '../../utils/kr_secure_storage.dart'; import '../../utils/kr_secure_storage.dart';
import '../../common/app_run_data.dart'; import '../../common/app_run_data.dart';
import 'package:flutter/foundation.dart';
enum KRConnectionType { enum KRConnectionType {
global, global,
@ -549,36 +550,46 @@ class KRSingBoxImp {
/// ///
/// hiddify-app: libcore UI /// hiddify-app: libcore UI
void _kr_subscribeToStatus() { void _kr_subscribeToStatus() {
if (kDebugMode) {
print('🔵 _kr_subscribeToStatus 被调用,重新订阅状态流'); print('🔵 _kr_subscribeToStatus 被调用,重新订阅状态流');
}
KRLogUtil.kr_i('🔵 _kr_subscribeToStatus 被调用', tag: 'SingBox'); KRLogUtil.kr_i('🔵 _kr_subscribeToStatus 被调用', tag: 'SingBox');
// //
for (var sub in _kr_subscriptions) { for (var sub in _kr_subscriptions) {
if (sub.hashCode.toString().contains('Status')) { if (sub.hashCode.toString().contains('Status')) {
sub.cancel(); sub.cancel();
if (kDebugMode) {
print('🔵 已取消旧的状态订阅'); print('🔵 已取消旧的状态订阅');
} }
} }
}
_kr_subscriptions _kr_subscriptions
.removeWhere((sub) => sub.hashCode.toString().contains('Status')); .removeWhere((sub) => sub.hashCode.toString().contains('Status'));
_kr_subscriptions.add( _kr_subscriptions.add(
kr_singBox.watchStatus().listen( kr_singBox.watchStatus().listen(
(status) { (status) {
if (kDebugMode) {
print('🔵 收到 Native 状态更新: ${status.runtimeType}'); print('🔵 收到 Native 状态更新: ${status.runtimeType}');
}
KRLogUtil.kr_i('📡 收到状态更新: $status', tag: 'SingBox'); KRLogUtil.kr_i('📡 收到状态更新: $status', tag: 'SingBox');
kr_status.value = status; kr_status.value = status;
}, },
onError: (error) { onError: (error) {
if (kDebugMode) {
print('🔵 状态流错误: $error'); print('🔵 状态流错误: $error');
}
KRLogUtil.kr_e('📡 状态流错误: $error', tag: 'SingBox'); KRLogUtil.kr_e('📡 状态流错误: $error', tag: 'SingBox');
}, },
cancelOnError: false, cancelOnError: false,
), ),
); );
if (kDebugMode) {
print('🔵 状态流订阅完成'); print('🔵 状态流订阅完成');
} }
}
/// ///
void _kr_subscribeToStats() { void _kr_subscribeToStats() {
@ -1141,7 +1152,9 @@ class KRSingBoxImp {
final selectedNode = await KRSecureStorage().kr_readData(key: _keySelectedNode); final selectedNode = await KRSecureStorage().kr_readData(key: _keySelectedNode);
if (selectedNode != null && selectedNode.isNotEmpty) { if (selectedNode != null && selectedNode.isNotEmpty) {
KRLogUtil.kr_i('🎯 恢复用户选择的节点: $selectedNode', tag: 'SingBox'); KRLogUtil.kr_i('🎯 恢复用户选择的节点: $selectedNode', tag: 'SingBox');
if (kDebugMode) {
print('🔵 启动后恢复节点选择: $selectedNode'); print('🔵 启动后恢复节点选择: $selectedNode');
}
// 500ms确保sing-box完全启动 // 500ms确保sing-box完全启动
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
@ -1150,19 +1163,27 @@ class KRSingBoxImp {
try { try {
await kr_selectOutbound(selectedNode); await kr_selectOutbound(selectedNode);
KRLogUtil.kr_i('✅ 节点已切换到用户选择: $selectedNode', tag: 'SingBox'); KRLogUtil.kr_i('✅ 节点已切换到用户选择: $selectedNode', tag: 'SingBox');
if (kDebugMode) {
print('🔵 节点切换成功: $selectedNode'); print('🔵 节点切换成功: $selectedNode');
}
} catch (e) { } catch (e) {
KRLogUtil.kr_e('❌ 节点切换失败: $e', tag: 'SingBox'); KRLogUtil.kr_e('❌ 节点切换失败: $e', tag: 'SingBox');
if (kDebugMode) {
print('🔵 节点切换失败: $e'); print('🔵 节点切换失败: $e');
} }
}
} else { } else {
KRLogUtil.kr_i(' 没有保存的节点选择,使用默认配置', tag: 'SingBox'); KRLogUtil.kr_i(' 没有保存的节点选择,使用默认配置', tag: 'SingBox');
if (kDebugMode) {
print('🔵 没有保存的节点选择,使用默认'); print('🔵 没有保存的节点选择,使用默认');
} }
}
} catch (e) { } catch (e) {
KRLogUtil.kr_e('❌ 恢复节点选择失败: $e', tag: 'SingBox'); KRLogUtil.kr_e('❌ 恢复节点选择失败: $e', tag: 'SingBox');
if (kDebugMode) {
print('🔵 恢复节点选择失败: $e'); print('🔵 恢复节点选择失败: $e');
} }
}
}); });
} catch (e, stackTrace) { } catch (e, stackTrace) {
KRLogUtil.kr_e('💥 SingBox 启动异常: $e', tag: 'SingBox'); KRLogUtil.kr_e('💥 SingBox 启动异常: $e', tag: 'SingBox');

View File

@ -1,6 +1,8 @@
import 'package:flutter/foundation.dart';
import 'package:loggy/loggy.dart'; import 'package:loggy/loggy.dart';
/// ///
/// 🔒 Release模式下所有日志都不会输出
class KRLogUtil { class KRLogUtil {
static final KRLogUtil _instance = KRLogUtil._internal(); static final KRLogUtil _instance = KRLogUtil._internal();
factory KRLogUtil() => _instance; factory KRLogUtil() => _instance;
@ -8,38 +10,59 @@ class KRLogUtil {
/// ///
static void kr_init() { static void kr_init() {
// Debug
if (kDebugMode) {
Loggy.initLoggy( Loggy.initLoggy(
logPrinter: PrettyPrinter(), logPrinter: PrettyPrinter(),
); );
} }
}
/// ///
/// 🔒 Debug
static void kr_d(String message, {String? tag}) { static void kr_d(String message, {String? tag}) {
if (kDebugMode) {
Loggy('${tag ?? 'KRLogUtil'}').debug(message); Loggy('${tag ?? 'KRLogUtil'}').debug(message);
} }
}
/// ///
/// 🔒 Debug
static void kr_i(String message, {String? tag}) { static void kr_i(String message, {String? tag}) {
if (kDebugMode) {
Loggy('${tag ?? 'KRLogUtil'}').info(message); Loggy('${tag ?? 'KRLogUtil'}').info(message);
} }
}
/// ///
/// 🔒 Debug
static void kr_w(String message, {String? tag}) { static void kr_w(String message, {String? tag}) {
if (kDebugMode) {
Loggy('${tag ?? 'KRLogUtil'}').warning(message); Loggy('${tag ?? 'KRLogUtil'}').warning(message);
} }
}
/// ///
/// 🔒 Debug
static void kr_e(String message, {String? tag, Object? error, StackTrace? stackTrace}) { static void kr_e(String message, {String? tag, Object? error, StackTrace? stackTrace}) {
if (kDebugMode) {
Loggy('${tag ?? 'KRLogUtil'}').error(message, error, stackTrace); Loggy('${tag ?? 'KRLogUtil'}').error(message, error, stackTrace);
} }
}
/// ///
/// 🔒 Debug
static void kr_network(String message, {String? tag}) { static void kr_network(String message, {String? tag}) {
if (kDebugMode) {
Loggy('${tag ?? 'Network'}').info(message); Loggy('${tag ?? 'Network'}').info(message);
} }
}
/// ///
/// 🔒 Debug
static void kr_performance(String message, {String? tag}) { static void kr_performance(String message, {String? tag}) {
if (kDebugMode) {
Loggy('${tag ?? 'Performance'}').info(message); Loggy('${tag ?? 'Performance'}').info(message);
} }
} }
}

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:country_flags/country_flags.dart'; import 'package:country_flags/country_flags.dart';
import 'package:flutter/foundation.dart';
class KRCountryFlag extends StatelessWidget { class KRCountryFlag extends StatelessWidget {
final String countryCode; final String countryCode;
@ -38,17 +39,29 @@ class KRCountryFlag extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// 🔍 // 🔍
if (kDebugMode) {
print('🏳️ KRCountryFlag.build 被调用'); print('🏳️ KRCountryFlag.build 被调用');
}
if (kDebugMode) {
print(' - 原始 countryCode: "$countryCode"'); print(' - 原始 countryCode: "$countryCode"');
}
if (kDebugMode) {
print(' - countryCode.isEmpty: ${countryCode.isEmpty}'); print(' - countryCode.isEmpty: ${countryCode.isEmpty}');
}
if (kDebugMode) {
print(' - countryCode.length: ${countryCode.length}'); print(' - countryCode.length: ${countryCode.length}');
}
final processedCode = _getCountryCode(countryCode); final processedCode = _getCountryCode(countryCode);
if (kDebugMode) {
print(' - 处理后 code: "$processedCode"'); print(' - 处理后 code: "$processedCode"');
}
// //
if (countryCode.isEmpty) { if (countryCode.isEmpty) {
if (kDebugMode) {
print(' ❌ 国家代码为空,显示占位符'); print(' ❌ 国家代码为空,显示占位符');
}
return Container( return Container(
width: width ?? 50.w, width: width ?? 50.w,
height: height ?? 50.w, height: height ?? 50.w,
@ -65,7 +78,9 @@ class KRCountryFlag extends StatelessWidget {
final double actualWidth = width ?? 50.w; final double actualWidth = width ?? 50.w;
final double actualHeight = maintainSize ? actualWidth : (height ?? 50.w); final double actualHeight = maintainSize ? actualWidth : (height ?? 50.w);
if (kDebugMode) {
print(' ✅ 尝试加载国旗: $processedCode'); print(' ✅ 尝试加载国旗: $processedCode');
}
Widget flagWidget = CountryFlag.fromCountryCode( Widget flagWidget = CountryFlag.fromCountryCode(
processedCode, processedCode,