br-addon 0.2.20

This is an addon
Documentation
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/// 功能
pub mod action;
/// 插件
pub mod addon;
/// 模块
pub mod module;
/// 请求数据
pub mod request;
/// api清单
pub mod swagger;
#[allow(clippy::too_many_arguments)]
#[cfg(any(
    feature = "sqlite",
    feature = "mssql",
    feature = "mysql",
    feature = "pgsql"
))]
/// 数据表构造
pub mod tables;
/// 工具
pub mod tools;

use crate::action::Action;
use crate::addon::Addon;
use crate::module::Module;
use crate::request::Request;
use crate::tools::{Tools, ToolsConfig};
#[cfg(any(
    feature = "mysql",
    feature = "sqlite",
    feature = "mssql",
    feature = "pgsql"
))]
use br_db::types::TableOptions;
use json::{array, object, JsonValue};
use lazy_static::lazy_static;
use log::{error, info};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::LazyLock;
use std::sync::{Mutex, OnceLock};
use std::{fs, thread};

lazy_static! {
    static ref CONFIG: Mutex<HashMap<String, JsonValue>> = Mutex::new(HashMap::new());
}
/// 工具集合(写入一次,后续只读)
static PLUGIN_TOOLS: OnceLock<Tools> = OnceLock::new();
/// 全局监听线程
static GLOBAL_HANDLE: LazyLock<Mutex<HashMap<String, String>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));
/// 全局加载的插件清单
pub static GLOBAL_ADDONS: OnceLock<Vec<String>> = OnceLock::new();
/// 全局加载的模块清单
pub static GLOBAL_MODULE: OnceLock<Vec<String>> = OnceLock::new();
/// 全局加载的动作清单
pub static GLOBAL_ACTION: OnceLock<Vec<String>> = OnceLock::new();

thread_local! {
    /// 单线程全局变量
    static GLOBAL_DATA: RefCell<JsonValue> = RefCell::new(object!{});
}
/// 插件接口
pub trait Plugin {
    /// 加载插件
    fn addon(name: &str) -> Result<Box<dyn Addon>, String>;
    /// 加载模型
    fn module(name: &str) -> Result<Box<dyn Module>, String> {
        let (addon_name, module_name) = Self::split2(name)?;
        Self::addon(addon_name)?.module(module_name)
    }
    /// 加载动作
    fn action(name: &str) -> Result<Box<dyn Action>, String> {
        let (addon_name, module_name, action_name) = Self::split3(name)?;
        Self::addon(addon_name)?
            .module(module_name)?
            .action(action_name)
    }
    /// 内部api
    fn api_run(name: &str, request: Request) -> Result<JsonValue, String> {
        let (addon_name, module_name, action_name) = Self::split3(name)?;
        match Self::addon(addon_name)?
            .module(module_name)?
            .action(action_name)?
            .run(request)
        {
            Ok(e) => Ok(e.data),
            Err(e) => Err(e.message),
        }
    }
    /// 加载工具装置
    /// * path 配置文件路径
    fn load_tools(config: ToolsConfig) -> Result<(), String> {
        if PLUGIN_TOOLS.get().is_some() {
            return Ok(());
        }
        let tools = Tools::new(config)?;
        let _ = PLUGIN_TOOLS.set(tools);
        Ok(())
    }
    /// 获取工具
    fn get_tools() -> Tools {
        PLUGIN_TOOLS.get().expect("tools not initialized").clone()
    }
    /// 加载全局配置文件
    fn load_config(name: &str, config: JsonValue) {
        if let Ok(mut cfg) = CONFIG.lock() {
            cfg.insert(name.into(), config.clone());
        }
    }
    /// 根据API清单初始化数据库
    ///
    /// * path 插件目录
    #[cfg(any(
        feature = "mysql",
        feature = "sqlite",
        feature = "mssql",
        feature = "pgsql"
    ))]
    fn init_db() -> Result<(), String> {
        info!("=============数据库更新开始=============");
        let mut tables = HashMap::new();
        // 生成数据库文件
        let sql = PathBuf::from("sql");

        // 删除目录
        if let Some(sql_path) = sql.to_str() {
            match fs::remove_dir_all(sql_path) {
                Ok(_) => {}
                Err(e) => {
                    #[cfg(any(
                        feature = "mysql",
                        feature = "sqlite",
                        feature = "mssql",
                        feature = "pgsql"
                    ))]
                    error!("目录删除失败: {e}");
                }
            }
        }

        // 创建目录
        if let Some(sql_path) = sql.to_str() {
            match fs::create_dir_all(sql_path) {
                Ok(_) => {}
                Err(e) => error!("目录创建失败: {e}"),
            }
        }

        let sql_file = sql.join("sql.json");
        let mut db_install = array![];

        for api_name in GLOBAL_MODULE.wait() {
            let module = match Self::module(api_name) {
                Ok(e) => e,
                Err(e) => {
                    error!("加载模型错误: {}", e);
                    continue;
                }
            };
            if !module.table() {
                continue;
            }
            if !tables.contains_key(module._table_name()) {
                tables.insert(module._table_name(), module);
            }
        }

        for (_, module) in tables.iter_mut() {
            let mut opt = TableOptions::default();

            let unique = module
                .table_unique()
                .iter()
                .map(|x| (*x).to_string())
                .collect::<Vec<String>>();
            let unique = unique.iter().map(|x| x.as_str()).collect::<Vec<&str>>();

            let index = module
                .table_index()
                .iter()
                .map(|x| x.iter().map(|&y| y.to_string()).collect::<Vec<String>>())
                .collect::<Vec<Vec<String>>>();
            let index = index
                .iter()
                .map(|x| x.iter().map(|y| y.as_str()).collect::<Vec<&str>>())
                .collect::<Vec<Vec<&str>>>();

            opt.set_table_name(module._table_name());
            opt.set_table_title(module.title());
            opt.set_table_key(module.table_key());
            opt.set_table_fields(module.fields().clone());
            opt.set_table_unique(unique.clone());
            opt.set_table_index(index.clone());
            opt.set_table_partition(module.table_partition());
            opt.set_table_partition_columns(module.table_partition_columns());
            let mut tools = Self::get_tools();
            let sql = tools
                .db
                .table(module._table_name())
                .fetch_sql()
                .table_create(opt.clone());

            let mut exec_tools = Self::get_tools();
            let table_exists = exec_tools.db.table_is_exist(module._table_name());

            let update_sql = if table_exists {
                tools
                    .db
                    .table(module._table_name())
                    .fetch_sql()
                    .table_update(opt.clone())
            } else {
                JsonValue::Null
            };
            db_install
                .push(object! {
                   table:module._table_name(),
                   field:module.fields().clone(),
                   key:module.table_key(),
                   index:index.clone(),
                   unique:unique.clone(),
                   sql:sql,
                   update_sql:update_sql
                })
                .ok();
            if let Err(e) = fs::write(sql_file.clone(), db_install.to_string()) {
                error!("写入SQL文件失败: {e}");
            }

            if table_exists {
                let res = exec_tools.db.table_update(opt);
                match res.as_i32().unwrap_or(-1) {
                    -1 => {}
                    0 => {
                        info!("数据库更新情况: {} 失败", module._table_name());
                    }
                    1 => {
                        info!("数据库更新情况: {} 成功", module._table_name());
                    }
                    _ => {}
                }
            } else {
                let res = exec_tools.db.table_create(opt);
                info!("安装完成情况: {} {}", module._table_name(), res);
            }
        }
        info!("=============数据库更新完成=============");
        Ok(())
    }
    #[cfg(any(
        feature = "mysql",
        feature = "sqlite",
        feature = "mssql",
        feature = "pgsql"
    ))]
    fn init_data() -> Result<(), String> {
        let mut exec_tools = Self::get_tools();
        for api_name in GLOBAL_MODULE.wait() {
            let mut module = match Self::module(api_name) {
                Ok(e) => e,
                Err(e) => {
                    error!("加载模型错误: {}", e);
                    continue;
                }
            };
            if !module.table() {
                continue;
            }
            let init_data = module.init_data();
            if !init_data.is_empty() {
                let count = exec_tools.db.table(module._table_name()).count();
                if count.is_empty() {
                    let r = exec_tools.db
                        .table(module._table_name())
                        .insert_all(init_data);
                    info!("初始化【{}】数据 {} 条", module._table_name(), r.len());
                }
            }
        }
        info!("所有模块数据初始化完成");
        Ok(())
    }

    /// 全局插件监听入口
    fn handles() {
        let mut map = match GLOBAL_HANDLE.lock() {
            Ok(m) => m,
            Err(_) => return,
        };

        for api in GLOBAL_ADDONS.wait() {
            let mut addon_name = match Self::addon(api.as_str()) {
                Ok(e) => e,
                Err(e) => {
                    error!("插件: {api} 加载错误 {e}");
                    continue;
                }
            };
            if map.get(addon_name.name()).is_none() {
                map.insert(addon_name.name().to_string(), addon_name.name().to_string());
                thread::spawn(move || addon_name.handle());
            }
        }
        for api in GLOBAL_MODULE.wait() {
            let mut module_name = match Self::module(api.as_str()) {
                Ok(e) => e,
                Err(e) => {
                    error!("插件: {api} 加载错误 {e}");
                    continue;
                }
            };
            if map.get(module_name.module_name()).is_none() {
                map.insert(
                    module_name.module_name().to_string(),
                    module_name.module_name().to_string(),
                );
                thread::spawn(move || module_name.handle());
            }
        }
    }
    /// 生成Swagger
    fn swagger(
        title: &str,
        description: &str,
        version: &str,
        uaturl: &str,
        produrl: &str,
        tags: JsonValue,
        paths: JsonValue,
    ) -> JsonValue {
        let info = object! {
            openapi:"3.0.0",
            info:{
                title:title,
                description:description,
                version:version
            },
            components: {
                securitySchemes: {
                    BearerToken: {
                        "type": "http",
                        "scheme": "bearer",
                        "bearerFormat": "Token"
                    }
                }
            },
            tags:tags,
            security: [
                {
                    "BearerToken": []
                }
            ],
            servers:[
                {
                    "url":uaturl,
                    "description": "测试地址"
                },
                {
                    "url":produrl,
                    "description": "正式地址"
                }
            ],
            paths:paths
        };
        info
    }
    /// 生成 api 列表
    fn generate_api_list(
        apipath: PathBuf,
        path: PathBuf,
        index: usize,
    ) -> Result<Vec<String>, String> {
        #[cfg(debug_assertions)]
        {
            let mut plugin_list = Vec::new();
            if path.is_dir() {
                let res = fs::read_dir(path);
                match res {
                    Ok(entries) => {
                        for entry in entries {
                            let entry = match entry {
                                Ok(e) => e,
                                Err(e) => return Err(e.to_string()),
                            };
                            let path = entry.path();
                            if path.is_dir() {
                                let path_str = match path.to_str() {
                                    Some(s) => s,
                                    None => continue,
                                };
                                let res = Self::generate_api_list(
                                    apipath.clone(),
                                    path_str.parse().unwrap_or_default(),
                                    index + 1,
                                )?;
                                plugin_list.extend(res);
                            } else if path.is_file() {
                                let path_str = match path.to_str() {
                                    Some(s) => s,
                                    None => continue,
                                };
                                if path_str.ends_with("mod.rs") {
                                    continue;
                                }
                                let addon = path
                                    .parent()
                                    .and_then(|p| p.parent())
                                    .and_then(|p| p.file_name())
                                    .and_then(|n| n.to_str())
                                    .unwrap_or_default();
                                let model = path
                                    .parent()
                                    .and_then(|p| p.file_name())
                                    .and_then(|n| n.to_str())
                                    .unwrap_or_default();
                                let action = path
                                    .file_name()
                                    .and_then(|n| n.to_str())
                                    .unwrap_or_default()
                                    .trim_end_matches(".rs");
                                let api = format!("{addon}.{model}.{action}");
                                match Self::action(api.as_str()) {
                                    Ok(e) => plugin_list.push(e.api()),
                                    Err(_) => continue,
                                }
                            }
                        }
                    }
                    Err(e) => return Err(e.to_string()),
                }
            }
            if index == 0 {
                if let Some(parent) = apipath.clone().parent() {
                    let _ = fs::create_dir_all(parent);
                }
                let _ = fs::write(&apipath, JsonValue::from(plugin_list.clone()).to_string());
                info!(
                    "=============API数量: {} 条=============",
                    plugin_list.len()
                );
                Self::_load_apis(plugin_list.clone())?;
            }
            Ok(plugin_list)
        }
        #[cfg(not(debug_assertions))]
        {
            let apis = fs::read_to_string(&apipath).unwrap_or_default();
            let apis = json::parse(&apis).unwrap_or(array![]);
            let apis = apis
                .members()
                .map(|x| x.as_str().unwrap_or_default().to_string())
                .collect::<Vec<String>>();
            info!("=============API数量: {} 条=============", apis.len());
            Self::_load_apis(apis.clone())?;
            Ok(apis)
        }
    }
    /// 加载api清单
    fn _load_apis(apis: Vec<String>) -> Result<(), String> {
        let mut action_list = vec![];
        let mut module_list = vec![];
        let mut addons_list = vec![];
        for api in apis {
            let action = Self::action(api.as_str())?;
            action_list.push(action.api());
            if !module_list.contains(&action.module_name()) {
                module_list.push(action.module_name());
            }
            if !addons_list.contains(&action.addon_name()) {
                addons_list.push(action.addon_name());
            }
        }
        let _ = GLOBAL_ACTION.set(action_list);
        let _ = GLOBAL_MODULE.set(module_list);
        let _ = GLOBAL_ADDONS.set(addons_list);
        Ok(())
    }
    /// 设置全局变量
    fn set_global_data(key: &str, value: JsonValue) {
        GLOBAL_DATA.with(|data| {
            data.borrow_mut()[key] = value;
        });
    }
    /// 获取全局变量数据
    fn get_global_data() -> JsonValue {
        GLOBAL_DATA.with(|data| data.borrow().clone())
    }
    /// 获取全局变量指定字段数据
    fn get_global_data_key(key: &str) -> JsonValue {
        GLOBAL_DATA.with(|data| data.borrow()[key].clone())
    }
    #[inline]
    fn split2(name: &str) -> Result<(&str, &str), String> {
        let t = name.split('.').collect::<Vec<&str>>();
        if t.len() < 2 {
            return Err(format!("模型格式不正确: {name}"));
        }
        Ok((t[0], t[1]))
    }

    #[inline]
    fn split3(name: &str) -> Result<(&str, &str, &str), String> {
        if let Some((a, rest)) = name.split_once('.') {
            if let Some((b, c)) = rest.split_once('.') {
                if !a.is_empty() && !b.is_empty() && !c.is_empty() {
                    Ok((a, b, c))
                } else {
                    Err("动作格式不正确".to_string())
                }
            } else {
                Err("动作格式不正确".to_string())
            }
        } else {
            Err("动作格式不正确".to_string())
        }
    }
}
/// API 错误响应
#[derive(Debug, Clone)]
pub struct ApiResponse {
    pub types: ApiType,
    pub code: i32,
    pub message: String,
    pub data: JsonValue,
    pub success: bool,
    pub timestamp: i64,
}
impl ApiResponse {
    #[must_use]
    pub fn json(&self) -> JsonValue {
        match self.types {
            ApiType::Json => object! {
                code: self.code,
                message: self.message.clone(),
                data: self.data.clone(),
                success: self.success
            },
            ApiType::Redirect
            | ApiType::Download
            | ApiType::Preview
            | ApiType::Txt
            | ApiType::Html => self.data.clone(),
        }
    }
    pub fn swagger(&mut self) -> JsonValue {
        let type_str = self.types.str();
        let mut content = object! {};
        content[type_str] = object! {};
        content[type_str]["schema"]["type"] = if self.data.is_array() {
            "array"
        } else {
            "object"
        }
        .into();
        content[type_str]["schema"]["properties"] = self.data.clone();

        content[type_str]["schema"]["type"] = match content[type_str]["schema"]["type"]
            .as_str()
            .unwrap_or("object")
        {
            "int" => "integer".into(),
            _ => content[type_str]["schema"]["type"].clone(),
        };
        object! {
            "description":self.message.clone(),
            "content":content
        }
    }
    pub fn success(data: JsonValue, mut message: &str) -> Self {
        if message.is_empty() {
            message = "success";
        }
        Self {
            success: true,
            types: ApiType::Json,
            code: 0,
            message: message.to_string(),
            data,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    pub fn fail(code: i32, message: &str) -> Self {
        Self {
            types: ApiType::Json,
            code,
            message: message.to_string(),
            data: JsonValue::Null,
            success: false,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    pub fn error(data: JsonValue, message: &str) -> Self {
        Self {
            types: ApiType::Json,
            code: -1,
            message: message.to_string(),
            data,
            success: false,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    /// 重定向
    pub fn redirect(url: &str) -> Self {
        Self {
            types: ApiType::Redirect,
            code: 0,
            message: "".to_string(),
            data: url.into(),
            success: true,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    /// 下载
    pub fn download(filename: &str) -> Self {
        Self {
            types: ApiType::Download,
            code: 0,
            message: "".to_string(),
            data: filename.into(),
            success: true,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    /// 预览
    pub fn preview(filename: &str) -> Self {
        Self {
            types: ApiType::Preview,
            code: 0,
            message: "".to_string(),
            data: filename.into(),
            success: true,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    /// 文本
    pub fn txt(txt: &str) -> Self {
        Self {
            types: ApiType::Txt,
            code: 0,
            message: "".to_string(),
            data: txt.into(),
            success: true,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
    pub fn html(data: &str) -> Self {
        Self {
            types: ApiType::Html,
            code: 0,
            message: "".to_string(),
            data: data.into(),
            success: true,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
}
impl Default for ApiResponse {
    fn default() -> Self {
        Self {
            types: ApiType::Json,
            code: 0,
            message: "".to_string(),
            data: JsonValue::Null,
            success: false,
            timestamp: br_fields::datetime::Timestamp::timestamp(),
        }
    }
}
/// API 响应
#[derive(Debug, Clone)]
pub enum ApiType {
    /// JSON类型
    Json,
    /// 重定向
    /// (重定向地址: http://xxxxxx)
    Redirect,
    /// 下载
    /// (文件地址: 文件绝对地址)
    Download,
    /// 预览
    /// (文件地址: 文件绝对地址)
    Preview,
    /// TXT格式
    Txt,
    /// 返回网页
    Html,
}
impl ApiType {
    #[must_use]
    pub fn str(&self) -> &'static str {
        match self {
            Self::Json => "application/json",
            Self::Redirect | Self::Download | Self::Preview => "text/html",
            Self::Txt => "text/plain",
            Self::Html => "text/html",
        }
    }
}