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
use json::{JsonValue};
use crate::applet::Applet;
use crate::wecom::WeCom;
use lazy_static::lazy_static;
use std::sync::Mutex;
use std::collections::HashMap;

pub mod wecom;
pub mod applet;


lazy_static! {
    pub static ref ACCESS_TOKEN: Mutex<HashMap<String,JsonValue>> =Mutex::new(HashMap::new());
}

#[derive(Clone)]
pub enum Wechat {
    WeCom(WeCom),
    Applet(Applet),
    None,
}

impl Wechat {
    pub fn new(mode: &str, data: JsonValue) -> Self {
        let is_none = ACCESS_TOKEN.lock().unwrap().get(&*data["appid"].to_string()).is_none();
        let access_token = if is_none {
            "".to_string()
        } else {
            ACCESS_TOKEN.lock().unwrap().get(&*data["appid"].to_string()).unwrap().clone()["access_token"].to_string()
        };
        let expires_in = if is_none {
            0
        } else {
            ACCESS_TOKEN.lock().unwrap().get(&*data["appid"].to_string()).unwrap().clone()["expires_in"].as_i64().unwrap()
        };
        match mode {
            "wecom" => {
                Wechat::WeCom(WeCom {
                    corp_id: data["appid"].to_string(),
                    agent_id: data["agent_id"].to_string(),
                    secret: data["secret"].to_string(),
                    access_token,
                    expires_in,
                })
            }
            "applet" => Wechat::Applet(Applet {
                appid: data["appid"].to_string(),
                secret: data["secret"].to_string(),
                access_token,
                expires_in,
            }),
            _ => Wechat::None
        }
    }
    pub fn check(self) -> bool {
        match self {
            Wechat::WeCom(e) => e.check(),
            Wechat::Applet(e) => e.check(),
            Wechat::None => false
        }
    }
}