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            
134            let mut opt = TableOptions::default();
135
136            let unique = module.table_unique().iter().map(|x| x.to_string()).collect::<Vec<String>>();
137            let unique = unique.iter().map(|x| x.as_str()).collect::<Vec<&str>>();
138
139            let index = module.table_index().iter().map(|x| x.iter().map(|&y| y.to_string()).collect::<Vec<String>>()).collect::<Vec<Vec<String>>>();
140            let index = index.iter().map(|x| x.iter().map(|y| y.as_str()).collect::<Vec<&str>>()).collect::<Vec<Vec<&str>>>();
141
142            opt.set_table_name(module._table_name());
143            opt.set_table_title(module.title());
144            opt.set_table_key(module.table_key());
145            opt.set_table_fields(module.fields().clone());
146            opt.set_table_unique(unique);
147            opt.set_table_index(index);
148            opt.set_table_partition(module.table_partition());
149            opt.set_table_partition_columns(module.table_partition_columns());
150            
151            if Self::get_tools().db.table_is_exist(module._table_name()) {
152                let res = Self::get_tools().db.table_update(opt);
153                match res.as_i32().unwrap() {
154                    -1 => {}
155                    0 => {
156                        info!("数据库更新情况: {} 失败", module._table_name());
157                    }
158                    1 => {
159                        info!("数据库更新情况: {} 成功", module._table_name());
160                    }
161                    _ => {}
162                }
163            } else {
164                let res = Self::get_tools().db.table_create(opt);
165                info!("安装完成情况: {} {}", module._table_name(), res);
166            }
167        }
168        info!("=============数据库更新完成=============");
169        Ok(())
170    }
171    /// 生成Swagger
172    fn swagger(
173        title: &str,
174        description: &str,
175        version: &str,
176        uaturl: &str,
177        produrl: &str,
178        tags: JsonValue,
179        paths: JsonValue,
180    ) -> JsonValue {
181        let info = object! {
182            openapi:"3.0.0",
183            info:{
184                title:title,
185                description:description,
186                version:version
187            },
188            components: {
189                securitySchemes: {
190                    BearerToken: {
191                        "type": "http",
192                        "scheme": "bearer",
193                        "bearerFormat": "Token"
194                    }
195                }
196            },
197            tags:tags,
198            security: [
199                {
200                    "BearerToken": []
201                }
202            ],
203            servers:[
204                {
205                    "url":uaturl,
206                    "description": "测试地址"
207                },
208                {
209                    "url":produrl,
210                    "description": "正式地址"
211                }
212            ],
213            paths:paths
214        };
215        info
216    }
217    /// 生成 api 列表
218    fn generate_api_list(apipath: PathBuf, path: PathBuf, index: usize) -> io::Result<Vec<String>> {
219        #[cfg(debug_assertions)]
220        {
221            let mut plugin_list = vec![];
222            if path.is_dir() {
223                let res = fs::read_dir(path);
224                match res {
225                    Ok(entries) => {
226                        for entry in entries {
227                            let entry = entry.unwrap();
228                            let path = entry.path();
229                            if path.is_dir() {
230                                let res = Self::generate_api_list(
231                                    apipath.clone(),
232                                    path.to_str().unwrap().parse().unwrap(),
233                                    index + 1,
234                                )?;
235                                plugin_list.extend(res);
236                            } else if path.is_file() {
237                                if path.to_str().unwrap().ends_with("mod.rs") {
238                                    continue;
239                                }
240                                let addon = path.parent().unwrap().parent().unwrap().file_name().unwrap().to_str().unwrap();
241                                let model = path.parent().unwrap().file_name().unwrap().to_str().unwrap();
242                                let action = path.file_name().unwrap().to_str().unwrap().trim_end_matches(".rs");
243                                let api = format!("{}.{}.{}", addon, model, action);
244                                match Self::api(api.as_str()) {
245                                    Ok(e) => plugin_list.push(e.api()),
246                                    Err(_) => {
247                                        println!("<API>: {api}");
248                                    }
249                                }
250                            }
251                        }
252                    }
253                    Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e.to_string()))
254                }
255            }
256            if index == 0 {
257                fs::create_dir_all(apipath.clone().parent().unwrap()).unwrap();
258                fs::write(apipath, JsonValue::from(plugin_list.clone()).to_string()).unwrap();
259                info!("=============API数量: {} 条=============", plugin_list.len());
260            }
261            Ok(plugin_list)
262        }
263        #[cfg(not(debug_assertions))]
264        {
265            let apis = fs::read_to_string(apipath).unwrap();
266            let apis = json::parse(&apis).unwrap();
267            let mut apis = apis.members().map(|x| x.as_str().unwrap().to_string()).collect::<Vec<String>>();
268            info!("=============API数量: {} 条=============", apis.len());
269            Ok(apis)
270        }
271    }
272
273    /// 设置全局变量
274    fn set_global_data(key: &str, value: JsonValue) {
275        GLOBAL_DATA.with(|data| {
276            data.borrow_mut()[key] = value;
277        });
278    }
279    /// 获取全局变量数据
280    fn get_global_data() -> JsonValue {
281        GLOBAL_DATA.with(|data| {
282            data.borrow().clone()
283        })
284    }
285    /// 获取全局变量指定字段数据
286    fn get_global_data_key(key: &str) -> JsonValue {
287        GLOBAL_DATA.with(|data| {
288            data.borrow()[key].clone()
289        })
290    }
291}
292/// API 错误响应
293#[derive(Debug, Clone)]
294pub struct ApiResponse {
295    pub types: ApiType,
296    pub code: i32,
297    pub message: String,
298    pub data: JsonValue,
299    pub success: bool,
300}
301impl ApiResponse {
302    pub fn json(self) -> JsonValue {
303        match self.types {
304            ApiType::Json => object! {
305                code: self.code,
306                message: self.message,
307                data: self.data,
308                success: self.success
309            },
310            ApiType::Redirect => self.data,
311            ApiType::Download => self.data,
312            ApiType::Preview => self.data,
313            ApiType::Txt => self.data,
314        }
315    }
316    pub fn swagger(&mut self) -> JsonValue {
317        let mut content = object! {};
318        content[self.types.str().as_str()] = object! {};
319        content[self.types.str().as_str()]["schema"]["type"] = if self.data.is_array() {
320            "array"
321        } else {
322            "object"
323        }.into();
324        content[self.types.str().as_str()]["schema"]["properties"] = self.data.clone();
325
326        content[self.types.str().as_str()]["schema"]["type"] = match content[self.types.str().as_str()]["schema"]["type"].as_str().unwrap() {
327            "int" => "integer".into(),
328            _ => content[self.types.str().as_str()]["schema"]["type"].clone(),
329        };
330        let data = object! {
331            "description":self.message.clone(),
332            "content":content
333        };
334        data
335    }
336    pub fn success(data: JsonValue, mut message: &str) -> Self {
337        if message.is_empty() {
338            message = "success";
339        }
340        Self {
341            success: true,
342            types: ApiType::Json,
343            code: 0,
344            message: message.to_string(),
345            data,
346        }
347    }
348    pub fn fail(code: i32, message: &str) -> Self {
349        Self {
350            types: ApiType::Json,
351            code,
352            message: message.to_string(),
353            data: JsonValue::Null,
354            success: false,
355        }
356    }
357    pub fn error(data: JsonValue, message: &str) -> Self {
358        Self {
359            types: ApiType::Json,
360            code: -1,
361            message: message.to_string(),
362            data,
363            success: false,
364        }
365    }
366    /// 重定向
367    pub fn redirect(url: &str) -> Self {
368        Self {
369            types: ApiType::Redirect,
370            code: 0,
371            message: "".to_string(),
372            data: url.into(),
373            success: true,
374        }
375    }
376    /// 下载
377    pub fn download(filename: &str) -> Self {
378        Self {
379            types: ApiType::Download,
380            code: 0,
381            message: "".to_string(),
382            data: filename.into(),
383            success: true,
384        }
385    }
386    /// 预览
387    pub fn preview(filename: &str) -> Self {
388        Self {
389            types: ApiType::Preview,
390            code: 0,
391            message: "".to_string(),
392            data: filename.into(),
393            success: true,
394        }
395    }
396    /// 文本
397    pub fn txt(txt: &str) -> Self {
398        Self {
399            types: ApiType::Txt,
400            code: 0,
401            message: "".to_string(),
402            data: txt.into(),
403            success: true,
404        }
405    }
406}
407impl Default for ApiResponse {
408    fn default() -> Self {
409        Self {
410            types: ApiType::Json,
411            code: 0,
412            message: "".to_string(),
413            data: JsonValue::Null,
414            success: false,
415        }
416    }
417}
418/// API 响应
419#[derive(Debug, Clone)]
420pub enum ApiType {
421    /// JSON类型
422    Json,
423    /// 重定向
424    /// (重定向地址: http://xxxxxx)
425    Redirect,
426    /// 下载
427    /// (文件地址: 文件绝对地址)
428    Download,
429    /// 预览
430    /// (文件地址: 文件绝对地址)
431    Preview,
432    /// TXT格式
433    Txt,
434}
435impl ApiType {
436    pub fn str(&mut self) -> String {
437        match self {
438            ApiType::Json => "application/json",
439            ApiType::Redirect | ApiType::Download | ApiType::Preview => "text/html",
440            ApiType::Txt => "text/plain",
441        }.to_string()
442    }
443}