1pub mod action;
3pub mod addon;
5pub mod module;
7pub mod request;
9pub mod swagger;
11pub 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", feature = "pgsql"))]
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 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 static GLOBAL_DATA: RefCell<JsonValue> = RefCell::new(object!{});
39}
40pub trait Plugin {
42 fn addon(name: &str) -> Result<Box<dyn Addon>, String>;
44 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 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 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 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 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 fn get_tools() -> Tools {
90 let tools = PLUGIN_TOOLS.lock().unwrap();
91 let tools = tools.get("tools").unwrap().clone();
92 tools
93 }
94 fn load_config(name: &str, config: JsonValue) {
96 CONFIG.lock().unwrap().insert(name.into(), config.clone());
97 }
98 #[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
110
111 for api_name in list.members() {
112 let api_info = api_name.as_str().unwrap_or("").split(".").collect::<Vec<&str>>();
113 let mut addon = match Self::addon(api_info[0]) {
114 Ok(e) => e,
115 Err(_) => {
116 continue;
117 }
118 };
119 let module = match addon.module(api_info[1]) {
120 Ok(e) => e,
121 Err(_) => {
122 continue;
123 }
124 };
125 if !module.table() {
126 continue;
127 }
128 if !tables.contains_key(module._table_name()) {
129 tables.insert(module._table_name(), module);
130 }
131 }
132
133 for (_, module) in tables.iter_mut() {
134
135 let mut opt = TableOptions::default();
136
137 let unique = module.table_unique().iter().map(|x| (*x).to_string()).collect::<Vec<String>>();
138 let unique = unique.iter().map(|x| x.as_str()).collect::<Vec<&str>>();
139
140 let index = module.table_index().iter().map(|x| x.iter().map(|&y| y.to_string()).collect::<Vec<String>>()).collect::<Vec<Vec<String>>>();
141 let index = index.iter().map(|x| x.iter().map(|y| y.as_str()).collect::<Vec<&str>>()).collect::<Vec<Vec<&str>>>();
142
143 opt.set_table_name(module._table_name());
144 opt.set_table_title(module.title());
145 opt.set_table_key(module.table_key());
146 opt.set_table_fields(module.fields().clone());
147 opt.set_table_unique(unique);
148 opt.set_table_index(index);
149 opt.set_table_partition(module.table_partition());
150 opt.set_table_partition_columns(module.table_partition_columns());
151
152 if Self::get_tools().db.table_is_exist(module._table_name()) {
153 let res = Self::get_tools().db.table_update(opt);
154 match res.as_i32().unwrap() {
155 -1 => {}
156 0 => {
157 info!("数据库更新情况: {} 失败", module._table_name());
158 }
159 1 => {
160 info!("数据库更新情况: {} 成功", module._table_name());
161 }
162 _ => {}
163 }
164 } else {
165 let res = Self::get_tools().db.table_create(opt);
166 info!("安装完成情况: {} {}", module._table_name(), res);
167 }
168 }
169 info!("=============数据库更新完成=============");
170 Ok(())
171 }
172 fn swagger(
174 title: &str,
175 description: &str,
176 version: &str,
177 uaturl: &str,
178 produrl: &str,
179 tags: JsonValue,
180 paths: JsonValue,
181 ) -> JsonValue {
182 let info = object! {
183 openapi:"3.0.0",
184 info:{
185 title:title,
186 description:description,
187 version:version
188 },
189 components: {
190 securitySchemes: {
191 BearerToken: {
192 "type": "http",
193 "scheme": "bearer",
194 "bearerFormat": "Token"
195 }
196 }
197 },
198 tags:tags,
199 security: [
200 {
201 "BearerToken": []
202 }
203 ],
204 servers:[
205 {
206 "url":uaturl,
207 "description": "测试地址"
208 },
209 {
210 "url":produrl,
211 "description": "正式地址"
212 }
213 ],
214 paths:paths
215 };
216 info
217 }
218 fn generate_api_list(apipath: PathBuf, path: PathBuf, index: usize) -> io::Result<Vec<String>> {
220 #[cfg(debug_assertions)]
221 {
222 let mut plugin_list = Vec::new();
223 if path.is_dir() {
224 let res = fs::read_dir(path);
225 match res {
226 Ok(entries) => {
227 for entry in entries {
228 let entry = entry.unwrap();
229 let path = entry.path();
230 if path.is_dir() {
231 let res = Self::generate_api_list(
232 apipath.clone(),
233 path.to_str().unwrap().parse().unwrap(),
234 index + 1,
235 )?;
236 plugin_list.extend(res);
237 } else if path.is_file() {
238 if path.to_str().unwrap().ends_with("mod.rs") {
239 continue;
240 }
241 let addon = path.parent().unwrap().parent().unwrap().file_name().unwrap().to_str().unwrap();
242 let model = path.parent().unwrap().file_name().unwrap().to_str().unwrap();
243 let action = path.file_name().unwrap().to_str().unwrap().trim_end_matches(".rs");
244 let api = format!("{}.{}.{}", addon, model, action);
245 match Self::api(api.as_str()) {
246 Ok(e) => plugin_list.push(e.api()),
247 Err(_) => continue
248 }
249 }
250 }
251 }
252 Err(e) => return Err(io::Error::other(e.to_string()))
253 }
254 }
255 if index == 0 {
256 fs::create_dir_all(apipath.clone().parent().unwrap()).unwrap();
257 fs::write(apipath, JsonValue::from(plugin_list.clone()).to_string()).unwrap();
258 info!("=============API数量: {} 条=============", plugin_list.len());
259 }
260 Ok(plugin_list)
261 }
262 #[cfg(not(debug_assertions))]
263 {
264 let apis = fs::read_to_string(apipath).unwrap();
265 let apis = json::parse(&apis).unwrap();
266 let apis = apis.members().map(|x| x.as_str().unwrap().to_string()).collect::<Vec<String>>();
267 info!("=============API数量: {} 条=============", apis.len());
268 Ok(apis)
269 }
270 }
271
272 fn set_global_data(key: &str, value: JsonValue) {
274 GLOBAL_DATA.with(|data| {
275 data.borrow_mut()[key] = value;
276 });
277 }
278 fn get_global_data() -> JsonValue {
280 GLOBAL_DATA.with(|data| {
281 data.borrow().clone()
282 })
283 }
284 fn get_global_data_key(key: &str) -> JsonValue {
286 GLOBAL_DATA.with(|data| {
287 data.borrow()[key].clone()
288 })
289 }
290}
291#[derive(Debug, Clone)]
293pub struct ApiResponse {
294 pub types: ApiType,
295 pub code: i32,
296 pub message: String,
297 pub data: JsonValue,
298 pub success: bool,
299}
300impl ApiResponse {
301 pub fn json(self) -> JsonValue {
302 match self.types {
303 ApiType::Json => object! {
304 code: self.code,
305 message: self.message,
306 data: self.data,
307 success: self.success
308 },
309 ApiType::Redirect => self.data,
310 ApiType::Download => self.data,
311 ApiType::Preview => self.data,
312 ApiType::Txt => self.data,
313 }
314 }
315 pub fn swagger(&mut self) -> JsonValue {
316 let mut content = object! {};
317 content[self.types.str().as_str()] = object! {};
318 content[self.types.str().as_str()]["schema"]["type"] = if self.data.is_array() {
319 "array"
320 } else {
321 "object"
322 }.into();
323 content[self.types.str().as_str()]["schema"]["properties"] = self.data.clone();
324
325 content[self.types.str().as_str()]["schema"]["type"] = match content[self.types.str().as_str()]["schema"]["type"].as_str().unwrap() {
326 "int" => "integer".into(),
327 _ => content[self.types.str().as_str()]["schema"]["type"].clone(),
328 };
329 let data = object! {
330 "description":self.message.clone(),
331 "content":content
332 };
333 data
334 }
335 pub fn success(data: JsonValue, mut message: &str) -> Self {
336 if message.is_empty() {
337 message = "success";
338 }
339 Self {
340 success: true,
341 types: ApiType::Json,
342 code: 0,
343 message: message.to_string(),
344 data,
345 }
346 }
347 pub fn fail(code: i32, message: &str) -> Self {
348 Self {
349 types: ApiType::Json,
350 code,
351 message: message.to_string(),
352 data: JsonValue::Null,
353 success: false,
354 }
355 }
356 pub fn error(data: JsonValue, message: &str) -> Self {
357 Self {
358 types: ApiType::Json,
359 code: -1,
360 message: message.to_string(),
361 data,
362 success: false,
363 }
364 }
365 pub fn redirect(url: &str) -> Self {
367 Self {
368 types: ApiType::Redirect,
369 code: 0,
370 message: "".to_string(),
371 data: url.into(),
372 success: true,
373 }
374 }
375 pub fn download(filename: &str) -> Self {
377 Self {
378 types: ApiType::Download,
379 code: 0,
380 message: "".to_string(),
381 data: filename.into(),
382 success: true,
383 }
384 }
385 pub fn preview(filename: &str) -> Self {
387 Self {
388 types: ApiType::Preview,
389 code: 0,
390 message: "".to_string(),
391 data: filename.into(),
392 success: true,
393 }
394 }
395 pub fn txt(txt: &str) -> Self {
397 Self {
398 types: ApiType::Txt,
399 code: 0,
400 message: "".to_string(),
401 data: txt.into(),
402 success: true,
403 }
404 }
405}
406impl Default for ApiResponse {
407 fn default() -> Self {
408 Self {
409 types: ApiType::Json,
410 code: 0,
411 message: "".to_string(),
412 data: JsonValue::Null,
413 success: false,
414 }
415 }
416}
417#[derive(Debug, Clone)]
419pub enum ApiType {
420 Json,
422 Redirect,
425 Download,
428 Preview,
431 Txt,
433}
434impl ApiType {
435 pub fn str(&mut self) -> String {
436 match self {
437 ApiType::Json => "application/json",
438 ApiType::Redirect | ApiType::Download | ApiType::Preview => "text/html",
439 ApiType::Txt => "text/plain",
440 }.to_string()
441 }
442}