use std::env; use std::fs; use std::path::PathBuf; use crate::error::{Error, Result}; /// 当前这台手机的默认值。`.env` 留空时使用。 const DEFAULT_DEVICE: DeviceProfile = DeviceProfile { app_id: "A00154", device_id: "V02_CF64B4B1544AC5D3DB79656332385175", device_num: "V02_CF64B4B1544AC5D3DB79656332385175;V02_CF64B4B1544AC5D3DB79656332385175;AID_034b7912-c21d-3bb3-9bfe-ea789d753967", device_brand: "Redmi", device_mode: "25053RT47C", device_name: "Redmi-25053RT47C", android_id: "AID_034b7912-c21d-3bb3-9bfe-ea789d753967", client_ip: "0.0.0.0", version_name: "12.8.1", version_code: 120805, }; /// 登录报文里的设备身份。换手机或升级 APP 时改配置即可。 #[derive(Debug, Clone)] pub struct DeviceProfile { pub app_id: &'static str, pub device_id: &'static str, pub device_num: &'static str, pub device_brand: &'static str, pub device_mode: &'static str, pub device_name: &'static str, pub android_id: &'static str, pub client_ip: &'static str, pub version_name: &'static str, pub version_code: i64, } /// 界面和命令行共用的运行配置。 #[derive(Debug, Clone)] pub struct AppConfig { pub account: String, pub password: String, pub token: String, pub project_id: String, pub org_id: String, pub tenant_id: String, pub device: OwnedDevice, env_path: Option, } /// 从环境读出的设备身份,拥有自己的字符串。 #[derive(Debug, Clone)] pub struct OwnedDevice { pub app_id: String, pub device_id: String, pub device_num: String, pub device_brand: String, pub device_mode: String, pub device_name: String, pub android_id: String, pub client_ip: String, pub version_name: String, pub version_code: i64, } impl AppConfig { /// 从当前目录向上查找 `.env`,环境变量优先于文件。 pub fn load() -> Result { let env_path = find_env(); let mut file_env = Vec::new(); if let Some(path) = &env_path { file_env = parse_env(&fs::read_to_string(path)?)?; } let get = |key: &str| -> String { env::var(key) .ok() .map(|v| v.trim().to_string()) .filter(|v| !v.is_empty()) .or_else(|| { file_env .iter() .find(|(k, _)| k == key) .map(|(_, v)| v.clone()) }) .unwrap_or_default() }; let pick = |key: &str, default: &str| { let value = get(key); if value.is_empty() { default.to_string() } else { value } }; let account = get("ICENTER_ACCOUNT"); let project_id = get("ICENTER_PROJECT_ID"); let missing = [("ICENTER_ACCOUNT", account.as_str()), ("ICENTER_PROJECT_ID", project_id.as_str())] .into_iter() .filter(|(_, v)| v.is_empty()) .map(|(k, _)| k) .collect::>(); if !missing.is_empty() { return Err(Error::MissingConfig(missing.join(", "))); } let version_code = pick("ICENTER_VERSION_CODE", &DEFAULT_DEVICE.version_code.to_string()) .parse::() .unwrap_or(DEFAULT_DEVICE.version_code); Ok(Self { account, password: get("ICENTER_PASSWORD"), token: get("ICENTER_TOKEN"), project_id, org_id: { let v = get("ICENTER_ORG_ID"); if v.is_empty() { "10001".to_string() } else { v } }, tenant_id: { let v = get("ICENTER_TENANT_ID"); if v.is_empty() { "10001".to_string() } else { v } }, device: OwnedDevice { app_id: pick("ICENTER_APP_ID", DEFAULT_DEVICE.app_id), device_id: pick("ICENTER_DEVICE_ID", DEFAULT_DEVICE.device_id), device_num: pick("ICENTER_DEVICE_NUM", DEFAULT_DEVICE.device_num), device_brand: pick("ICENTER_DEVICE_BRAND", DEFAULT_DEVICE.device_brand), device_mode: pick("ICENTER_DEVICE_MODE", DEFAULT_DEVICE.device_mode), device_name: pick("ICENTER_DEVICE_NAME", DEFAULT_DEVICE.device_name), android_id: pick("ICENTER_ANDROID_ID", DEFAULT_DEVICE.android_id), client_ip: pick("ICENTER_CLIENT_IP", DEFAULT_DEVICE.client_ip), version_name: pick("ICENTER_VERSION_NAME", DEFAULT_DEVICE.version_name), version_code, }, env_path, }) } /// 把新 token 写回找到的 `.env`,方便下次直接使用。 pub fn store_token(&mut self, token: &str) -> Result<()> { self.token = token.to_string(); let Some(path) = &self.env_path else { return Ok(()); }; let text = fs::read_to_string(path).unwrap_or_default(); let mut lines: Vec = text.lines().map(str::to_string).collect(); let mut found = false; for line in &mut lines { if line.trim_start().starts_with("ICENTER_TOKEN=") { *line = format!("ICENTER_TOKEN={token}"); found = true; } } if !found { lines.push(format!("ICENTER_TOKEN={token}")); } fs::write(path, lines.join("\n") + "\n")?; Ok(()) } } fn find_env() -> Option { let mut dir = env::current_dir().ok()?; loop { let candidate = dir.join(".env"); if candidate.is_file() { return Some(candidate); } if !dir.pop() { return None; } } } fn parse_env(text: &str) -> Result> { let mut out = Vec::new(); for raw in text.lines() { let line = raw.trim(); if line.is_empty() || line.starts_with('#') || !line.contains('=') { continue; } let (key, value) = line.split_once('=').unwrap(); let value = value.trim().trim_matches('"').trim_matches('\'').to_string(); out.push((key.trim().to_string(), value)); } Ok(out) }