1use std::error::Error;
2use once_cell::sync::OnceCell;
3use std::io::BufRead;
4use serde_derive::{Deserialize, Serialize};
5use serde_json::Value;
6
7#[derive(Serialize, Deserialize, Debug)]
8struct ChatApiConfig {
9 api_key: Option<String>,
10}
11
12#[derive(Serialize, Deserialize, Debug)]
13struct AiConfig {
14 chatglm_api_key: Vec<ChatApiConfig>,
15}
16
17pub async fn chatglm_api_read_config(file_path: &str, glm: &str) -> Result<String, Box<dyn Error>> {
18 let file_content = tokio::fs::read_to_string(file_path).await?;
19 let config: AiConfig = toml::from_str(&file_content)?;
20
21 let response = match glm {
22 "chatglm_api_key" => config.chatglm_api_key,
23 _ => return Err("Invalid ChatGLM API".into()),
24 };
25
26 let json_string = serde_json::to_string(&response)?;
27
28 Ok(json_string)
29}
30
31pub struct APIKeys {
32 user_id: String,
33 user_secret: String,
34}
35
36impl APIKeys {
37 fn new(user_id: &str, user_secret: &str) -> APIKeys {
38 APIKeys {
39 user_id: user_id.to_string(),
40 user_secret: user_secret.to_string(),
41 }
42 }
43
44 pub fn get_instance(api: &str) -> &APIKeys {
45 static INSTANCE: OnceCell<APIKeys> = OnceCell::new();
46
47 INSTANCE.get_or_init(|| {
48 let parts: Vec<&str> = api.trim().split('.').collect();
49 if parts.len() == 2 {
50 APIKeys::new(parts[0], parts[1])
51 } else {
52 panic!("Your API Key is Invalid");
53 }
54 })
55 }
56
57 pub fn get_user_id(&self) -> &str {
58 &self.user_id
59 }
60
61 pub fn get_user_secret(&self) -> &str {
62 &self.user_secret
63 }
64
65 pub async fn load_api_key(user_config: &str) -> Result<String, Box<dyn Error>> {
66 let json_string = match chatglm_api_read_config(user_config, "chatglm_api_key").await {
67 Ok(final_json_string) => final_json_string,
68 Err(err) => return Err(format!("Error reading config file: {}", err).into()),
69 };
70
71 let api_key: Value = serde_json::from_str(&json_string)
72 .map_err(|err| format!("Failed to parse JSON: {}", err))?;
73
74 let glm_key = api_key[0]["api_key"]
75 .as_str()
76 .ok_or_else(|| "Failed to get api_key")?
77 .to_string();
78
79 Ok(glm_key)
80 }
81}