1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use std::fs;
use std::sync::mpsc::{Sender, Receiver};

use json::{JsonValue, object};

#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use br_db::Db;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use br_db::config::Config as DbConfig;
#[cfg(any(feature = "cache"))]
use br_cache::Cache;
#[cfg(any(feature = "kafka"))]
use br_kafka::Kafka;

use lazy_static::lazy_static;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use std::path::PathBuf;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use std::process::exit;

#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use log::{error};
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
use log::info;
use crate::config::Config;

pub mod addon;
pub mod model;
pub mod action;
pub mod config;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
pub mod table;

/// 集合工具
#[derive(Clone)]
pub struct Tools {
    #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
    pub db: Db,
    #[cfg(any(feature = "cache"))]
    pub cache: Cache,
    #[cfg(any(feature = "kafka"))]
    pub kafka: Kafka,

    pub config: Config,
}

impl Tools {
    pub fn new(path: &str) -> Result<Self, String> {
        let config = match Config::new(path) {
            Ok(e) => e,
            Err(e) => {
                return Err(e);
            }
        };

        let mut that = Self {
            #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
            db: Db::None,
            #[cfg(any(feature = "cache"))]
            cache: Cache::None,
            #[cfg(any(feature = "kafka"))]
            kafka: Kafka::connect(object! {}),
            config,
        };

        #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
        that.set_db(format!("{}", that.config.config_dir.join("db.json").to_str().unwrap()).as_str());
        #[cfg(any(feature = "cache"))]
        that.set_cache(format!("{}", that.config.config_dir.join("cache.json").to_str().unwrap()).as_str());
        #[cfg(any(feature = "kafka"))]
        that.set_kafka(format!("{}", that.config.config_dir.join("kafka.json").to_str().unwrap()).as_str());
        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), that.clone());
        Ok(that)
    }
    #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite", feature = "mysqls"))]
    pub fn set_db(&mut self, config_filename: &str) -> &mut Self {
        let conf = fs::read_to_string(config_filename.clone());
        match conf {
            Ok(str) => {
                match json::parse(str.as_str().clone()) {
                    Ok(config) => {
                        self.db = Db::new(config);
                        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
                    }
                    Err(e) => {
                        error!("数据库配置文件错误: {}",e.to_string());
                    }
                }
            }
            Err(_) => {
                let data = DbConfig::default().json();
                let path_buf = PathBuf::from(config_filename.clone());
                fs::create_dir_all(config_filename.trim_end_matches(path_buf.file_name().unwrap().to_str().unwrap())).unwrap();
                fs::write(config_filename, data.to_string()).expect("创建数据库配置文件失败");
                info!("创建配置文件成功请重启");
                exit(0)
            }
        }
        self
    }
    #[cfg(any(feature = "cache"))]
    pub fn set_cache(&mut self, config_path: &str) -> &mut Self {
        self.cache = Cache::load(config_path.clone());
        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
        self
    }
    #[cfg(any(feature = "kafka"))]
    pub fn set_kafka(&mut self, config_path: &str) -> &mut Self {
        let conf = fs::read_to_string(config_path.clone()).unwrap();
        match json::parse(conf.as_str().clone()) {
            Ok(config) => {
                self.kafka = Kafka::connect(config);
                PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
            }
            Err(e) => {
                error!("kafka配置文件错误: {}", e.to_string());
            }
        }
        self
    }
}

lazy_static! {
    /// 工具集合
    pub static ref PLUGIN_TOOLS: Mutex<HashMap<String,Tools>> =Mutex::new(HashMap::new());
    pub static ref PLUGIN_WS_TX: Mutex<HashMap<String,Sender<JsonValue>>> =Mutex::new(HashMap::new());
    pub static ref PLUGIN_WS_RX: Mutex<HashMap<String,Arc<Mutex<Receiver<JsonValue>>>>> =Mutex::new(HashMap::new());
}


/// 按钮颜色
pub enum BtnColor {
    Red,
    Blue,
    Yellow,
    Green,
}

impl BtnColor {
    fn from(self) -> &'static str {
        match self {
            BtnColor::Red => "red",
            BtnColor::Blue => "blue",
            BtnColor::Yellow => "yellow",
            BtnColor::Green => "green",
        }
    }
}

/// 按钮模式
pub enum BtnMode {
    Form,
    FormDownload,
    Url,
    Api,
    Download,
    Path,
}

impl BtnMode {
    fn from(self) -> &'static str {
        match self {
            BtnMode::Form => "form",
            BtnMode::FormDownload => "form_download",
            BtnMode::Api => "api",
            BtnMode::Download => "download",
            BtnMode::Url => "url",
            BtnMode::Path => "path",
        }
    }
}

/// 返回响应
#[derive(Clone, Debug)]
pub struct Response(&'static str, JsonValue);

impl Response {
    /// 获取消息
    pub fn get_msg(self) -> &'static str {
        self.0
    }
    /// 获取数据
    pub fn get_data(self) -> JsonValue {
        self.1
    }
    /// 获取业务数据
    pub fn get_data_data(self) -> JsonValue {
        self.get_data()["data"].clone()
    }
    /// 获取业务反馈编号
    pub fn get_data_code(self) -> i32 {
        self.get_data()["code"].as_i32().unwrap()
    }
    /// 获取业务提示消息
    pub fn get_data_msg(self) -> String {
        self.get_data()["msg"].to_string()
    }
    pub fn into(self) -> (&'static str, JsonValue) {
        return (self.0, self.1);
    }
    /// 成功
    pub fn success(data: JsonValue, msg: &str) -> Self {
        let data = object! {code: 0,data:data,msg: msg.to_string()};
        Self("json", data)
    }
    /// 失败
    pub fn fail(msg: &str) -> Self {
        let data = object! {
            code: -1,
            msg: msg.to_string()
        };
        Self("json", data)
    }
    /// 失败
    pub fn error(code: usize, msg: String) -> Self {
        let data = object! {
            code: code,
            msg: msg
        };
        Self("json", data)
    }

    /// 通知消息
    pub fn notify(msg: &str, btn_name: &str, path: &str) -> Self {
        let data = object! {
            code: 0,
            msg: msg.to_string(),
            btn_name:btn_name,
            path:path
        };
        Self("json", data)
    }

    /// 登陆
    pub fn login(msg: &str) -> Self {
        let data = object! {code: 1000,msg: msg.to_string(),};
        Self("json", data)
    }
    /// 下载
    pub fn download(filename: &str) -> Self {
        Self("download", filename.into())
    }
    /// 重定向
    pub fn redirect(url: &str) -> Self {
        Self("url", url.into())
    }
}