br_addon/
lib.rs

1/// 功能
2pub mod action;
3/// 插件
4pub mod addon;
5/// 模块
6pub mod module;
7/// 请求数据
8pub mod request;
9/// api清单
10pub mod swagger;
11/// 工具
12pub mod tools;
13
14use crate::action::Action;
15use crate::addon::Addon;
16use crate::module::Module;
17use crate::request::Request;
18use crate::tools::{Tools, ToolsConfig};
19#[cfg(any(feature = "mysql", feature = "sqlite", feature = "mssql"))]
20use br_db::types::TableOptions;
21use json::{array, object, JsonValue};
22use lazy_static::lazy_static;
23use log::info;
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::sync::Mutex;
27use std::{fs, io};
28use std::cell::RefCell;
29
30lazy_static! {
31    /// 工具集合
32    static ref PLUGIN_TOOLS: Mutex<HashMap<String,Tools>> =Mutex::new(HashMap::new());
33    static ref CONFIG: Mutex<HashMap<String,JsonValue>> =Mutex::new(HashMap::new());
34}
35
36thread_local! {
37    /// 单线程全局变量
38    static GLOBAL_DATA: RefCell<JsonValue> = RefCell::new(object!{});
39}
40/// 插件接口
41pub trait Plugin {
42    /// 加载插件
43    fn addon(name: &str) -> Result<Box<dyn Addon>, String>;
44    /// 加载模型
45    fn module(name: &str) -> Result<Box<dyn Module>, String> {
46        let res = name.split(".").collect::<Vec<&str>>();
47        if res.len() < 2 {
48            return Err("模型格式不正确".to_string());
49        }
50        Self::addon(res[0])?.module(res[1])
51    }
52    /// 加载动作
53    fn action(name: &str) -> Result<Box<dyn Action>, String> {
54        let res = name.split(".").collect::<Vec<&str>>();
55        if res.len() < 3 {
56            return Err("动作格式不正确".to_string());
57        }
58        Self::addon(res[0])?.module(res[1])?.action(res[2])
59    }
60    /// 内部api
61    fn api_run(name: &str, request: Request) -> Result<JsonValue, String> {
62        let res = name.split(".").collect::<Vec<&str>>();
63        if res.len() != 3 {
64            return Err("action格式不正确".to_string());
65        }
66        match Self::addon(res[0])?.module(res[1])?.action(res[2])?.run(request) {
67            Ok(e) => Ok(e.data),
68            Err(e) => Err(e.message),
69        }
70    }
71    /// 加载api
72    fn api(name: &str) -> Result<Box<dyn Action>, String> {
73        let res = name.split(".").collect::<Vec<&str>>();
74        if res.len() != 3 {
75            return Err("api 格式不正确".to_string());
76        }
77        Self::addon(res[0])?.module(res[1])?.action(res[2])
78    }
79    /// 加载工具装置
80    /// * path 配置文件路径
81    fn load_tools(config: ToolsConfig) -> Result<(), String> {
82        if PLUGIN_TOOLS.lock().unwrap().get("tools").is_none() {
83            let res = Tools::new(config)?;
84            PLUGIN_TOOLS.lock().unwrap().insert("tools".into(), res.clone());
85        }
86        Ok(())
87    }
88    /// 获取工具
89    fn get_tools() -> Tools {
90        let tools = PLUGIN_TOOLS.lock().unwrap();
91        let tools = tools.get("tools").unwrap().clone();
92        tools
93    }
94    /// 加载全局配置文件
95    fn load_config(name: &str, config: JsonValue) {
96        CONFIG.lock().unwrap().insert(name.into(), config.clone());
97    }
98    /// 根据API清单初始化数据库
99    ///
100    /// * path 插件目录
101    #[cfg(any(feature = "mysql", feature = "sqlite", feature = "mssql"))]
102    fn init_db(file_path: PathBuf) -> Result<(), String> {
103        info!("=============数据库更新开始=============");
104        let list = match fs::read_to_string(file_path.clone()) {
105            Ok(e) => json::parse(&e).unwrap_or(array![]),
106            Err(e) => return Err(format!("加载API清单失败: {}", e)),
107        };
108        let mut tables = HashMap::new();
109        for api_name in list.members() {
110            let api_info = api_name.as_str().unwrap_or("").split(".").collect::<Vec<&str>>();
111            let mut addon = match Self::addon(api_info[0]) {
112                Ok(e) => e,
113                Err(_) => {
114                    continue;
115                }
116            };
117            let module = match addon.module(api_info[1]) {
118                Ok(e) => e,
119                Err(_) => {
120                    continue;
121                }
122            };
123            if !module.table() {
124                continue;
125            }
126            if !tables.contains_key(module._table_name()) {
127                tables.insert(module._table_name(), module);
128            }
129        }
130
131
132        for (_, module) in tables.iter_mut() {
133            let mut opt = TableOptions::default();
134
135            let unique = module.table_unique().iter().map(|x| (*x).to_string()).collect::<Vec<String>>();
136            let unique = unique.iter().map(|x| x.as_str()).collect::<Vec<&str>>();
137
138            let index = module.table_index().iter().map(|x| x.iter().map(|&y| y.to_string()).collect::<Vec<String>>()).collect::<Vec<Vec<String>>>();
139            let index = index.iter().map(|x| x.iter().map(|y| y.as_str()).collect::<Vec<&str>>()).collect::<Vec<Vec<&str>>>();
140
141            opt.set_table_name(module._table_name());
142            opt.set_table_title(module.title());
143            opt.set_table_key(module.table_key());
144            opt.set_table_fields(module.fields().clone());
145            opt.set_table_unique(unique);
146            opt.set_table_index(index);
147            opt.set_table_partition(module.table_partition());
148            opt.set_table_partition_columns(module.table_partition_columns());
149
150            if Self::get_tools().db.table_is_exist(module._table_name()) {
151                let res = Self::get_tools().db.table_update(opt);
152                match res.as_i32().unwrap() {
153                    -1 => {}
154                    0 => {
155                        info!("数据库更新情况: {} 失败", module._table_name());
156                    }
157                    1 => {
158                        info!("数据库更新情况: {} 成功", module._table_name());
159                    }
160                    _ => {}
161                }
162            } else {
163                let res = Self::get_tools().db.table_create(opt);
164                info!("安装完成情况: {} {}", module._table_name(), res);
165            }
166        }
167        info!("=============数据库更新完成=============");
168        Ok(())
169    }
170    /// 生成Swagger
171    fn swagger(
172        title: &str,
173        description: &str,
174        version: &str,
175        uaturl: &str,
176        produrl: &str,
177        tags: JsonValue,
178        paths: JsonValue,
179    ) -> JsonValue {
180        let info = object! {
181            openapi:"3.0.0",
182            info:{
183                title:title,
184                description:description,
185                version:version
186            },
187            components: {
188                securitySchemes: {
189                    BearerToken: {
190                        "type": "http",
191                        "scheme": "bearer",
192                        "bearerFormat": "Token"
193                    }
194                }
195            },
196            tags:tags,
197            security: [
198                {
199                    "BearerToken": []
200                }
201            ],
202            servers:[
203                {
204                    "url":uaturl,
205                    "description": "测试地址"
206                },
207                {
208                    "url":produrl,
209                    "description": "正式地址"
210                }
211            ],
212            paths:paths
213        };
214        info
215    }
216    /// 生成 api 列表
217    fn generate_api_list(apipath: PathBuf, path: PathBuf, index: usize) -> io::Result<Vec<String>> {
218        #[cfg(debug_assertions)]
219        {
220            let mut plugin_list = vec![];
221            if path.is_dir() {
222                let res = fs::read_dir(path);
223                match res {
224                    Ok(entries) => {
225                        for entry in entries {
226                            let entry = entry.unwrap();
227                            let path = entry.path();
228                            if path.is_dir() {
229                                let res = Self::generate_api_list(
230                                    apipath.clone(),
231                                    path.to_str().unwrap().parse().unwrap(),
232                                    index + 1,
233                                )?;
234                                plugin_list.extend(res);
235                            } else if path.is_file() {
236                                if path.to_str().unwrap().ends_with("mod.rs") {
237                                    continue;
238                                }
239                                let addon = path.parent().unwrap().parent().unwrap().file_name().unwrap().to_str().unwrap();
240                                let model = path.parent().unwrap().file_name().unwrap().to_str().unwrap();
241                                let action = path.file_name().unwrap().to_str().unwrap().trim_end_matches(".rs");
242                                let api = format!("{}.{}.{}", addon, model, action);
243                                match Self::api(api.as_str()) {
244                                    Ok(e) => plugin_list.push(e.api()),
245                                    Err(_) => continue
246                                }
247                            }
248                        }
249                    }
250                    Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e.to_string()))
251                }
252            }
253            if index == 0 {
254                fs::create_dir_all(apipath.clone().parent().unwrap()).unwrap();
255                fs::write(apipath, JsonValue::from(plugin_list.clone()).to_string()).unwrap();
256                info!("=============API数量: {} 条=============", plugin_list.len());
257            }
258            Ok(plugin_list)
259        }
260        #[cfg(not(debug_assertions))]
261        {
262            let apis = fs::read_to_string(apipath).unwrap();
263            let apis = json::parse(&apis).unwrap();
264            let mut apis = apis.members().map(|x| x.as_str().unwrap().to_string()).collect::<Vec<String>>();
265            info!("=============API数量: {} 条=============", apis.len());
266            Ok(apis)
267        }
268    }
269
270    /// 设置全局变量
271    fn set_global_data(key: &str, value: JsonValue) {
272        GLOBAL_DATA.with(|data| {
273            data.borrow_mut()[key] = value;
274        });
275    }
276    /// 获取全局变量数据
277    fn get_global_data() -> JsonValue {
278        GLOBAL_DATA.with(|data| {
279            data.borrow().clone()
280        })
281    }
282    /// 获取全局变量指定字段数据
283    fn get_global_data_key(key: &str) -> JsonValue {
284        GLOBAL_DATA.with(|data| {
285            data.borrow()[key].clone()
286        })
287    }
288}
289/// API 错误响应
290#[derive(Debug, Clone)]
291pub struct ApiResponse {
292    pub types: ApiType,
293    pub code: i32,
294    pub message: String,
295    pub data: JsonValue,
296    pub success: bool,
297}
298impl ApiResponse {
299    pub fn json(self) -> JsonValue {
300        match self.types {
301            ApiType::Json => object! {
302                code: self.code,
303                message: self.message,
304                data: self.data,
305                success: self.success
306            },
307            ApiType::Redirect => self.data,
308            ApiType::Download => self.data,
309            ApiType::Preview => self.data,
310            ApiType::Txt => self.data,
311        }
312    }
313    pub fn swagger(&mut self) -> JsonValue {
314        let mut content = object! {};
315        content[self.types.str().as_str()] = object! {};
316        content[self.types.str().as_str()]["schema"]["type"] = if self.data.is_array() {
317            "array"
318        } else {
319            "object"
320        }.into();
321        content[self.types.str().as_str()]["schema"]["properties"] = self.data.clone();
322
323        content[self.types.str().as_str()]["schema"]["type"] = match content[self.types.str().as_str()]["schema"]["type"].as_str().unwrap() {
324            "int" => "integer".into(),
325            _ => content[self.types.str().as_str()]["schema"]["type"].clone(),
326        };
327        let data = object! {
328            "description":self.message.clone(),
329            "content":content
330        };
331        data
332    }
333    pub fn success(data: JsonValue, mut message: &str) -> Self {
334        if message.is_empty() {
335            message = "success";
336        }
337        Self {
338            success: true,
339            types: ApiType::Json,
340            code: 0,
341            message: message.to_string(),
342            data,
343        }
344    }
345    pub fn fail(code: i32, message: &str) -> Self {
346        Self {
347            types: ApiType::Json,
348            code,
349            message: message.to_string(),
350            data: JsonValue::Null,
351            success: false,
352        }
353    }
354    pub fn error(data: JsonValue, message: &str) -> Self {
355        Self {
356            types: ApiType::Json,
357            code: -1,
358            message: message.to_string(),
359            data,
360            success: false,
361        }
362    }
363    /// 重定向
364    pub fn redirect(url: &str) -> Self {
365        Self {
366            types: ApiType::Redirect,
367            code: 0,
368            message: "".to_string(),
369            data: url.into(),
370            success: true,
371        }
372    }
373    /// 下载
374    pub fn download(filename: &str) -> Self {
375        Self {
376            types: ApiType::Download,
377            code: 0,
378            message: "".to_string(),
379            data: filename.into(),
380            success: true,
381        }
382    }
383    /// 预览
384    pub fn preview(filename: &str) -> Self {
385        Self {
386            types: ApiType::Preview,
387            code: 0,
388            message: "".to_string(),
389            data: filename.into(),
390            success: true,
391        }
392    }
393    /// 文本
394    pub fn txt(txt: &str) -> Self {
395        Self {
396            types: ApiType::Txt,
397            code: 0,
398            message: "".to_string(),
399            data: txt.into(),
400            success: true,
401        }
402    }
403}
404impl Default for ApiResponse {
405    fn default() -> Self {
406        Self {
407            types: ApiType::Json,
408            code: 0,
409            message: "".to_string(),
410            data: JsonValue::Null,
411            success: false,
412        }
413    }
414}
415/// API 响应
416#[derive(Debug, Clone)]
417pub enum ApiType {
418    /// JSON类型
419    Json,
420    /// 重定向
421    /// (重定向地址: http://xxxxxx)
422    Redirect,
423    /// 下载
424    /// (文件地址: 文件绝对地址)
425    Download,
426    /// 预览
427    /// (文件地址: 文件绝对地址)
428    Preview,
429    /// TXT格式
430    Txt,
431}
432impl ApiType {
433    pub fn str(&mut self) -> String {
434        match self {
435            ApiType::Json => "application/json",
436            ApiType::Redirect | ApiType::Download | ApiType::Preview => "text/html",
437            ApiType::Txt => "text/plain",
438        }.to_string()
439    }
440}