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
use crate::error::Error;
use serde::Serialize;
use serde_json::{json, Value};

pub trait WecomMessage {
    fn msg_type(&self) -> MessageType;
    fn key(&self) -> String;
    fn value(&self) -> impl Serialize
    where
        Self: Serialize,
    {
        self
    }
}

#[derive(Debug, Serialize)]
pub enum MessageType {
    Text,
    Image,
    Audio,
    Video,
    File,
    TextCard,
    News,
    Markdown,
}

#[derive(Debug)]
pub struct MessageBuilder {
    users: Option<String>,
    groups: Option<String>,
    tags: Option<String>,
    agent_id: Option<usize>,
    safe: i64,
    enable_id_trans: i64,
    enable_duplicate_check: i64,
    duplicate_check_interval: usize,
}

impl Default for MessageBuilder {
    fn default() -> Self {
        Self {
            users: None,
            groups: None,
            tags: None,
            agent_id: None,
            safe: 0,
            enable_id_trans: 0,
            enable_duplicate_check: 0,
            duplicate_check_interval: 1800,
        }
    }
}

impl MessageBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn to_users(mut self, users: Vec<&str>) -> Self {
        self.users = Some(
            users
                .iter()
                .fold("".to_string(), |acc, &u| format!("{acc}|{u}"))
                .trim_start_matches('|')
                .to_string(),
        );
        self
    }

    pub fn to_groups(mut self, groups: Vec<&str>) -> Self {
        self.groups = Some(
            groups
                .iter()
                .fold("".to_string(), |acc, &u| format!("{acc}|{u}"))
                .trim_start_matches('|')
                .to_string(),
        );
        self
    }

    pub fn to_tags(mut self, tags: Vec<&str>) -> Self {
        self.tags = Some(
            tags.iter()
                .fold("".to_string(), |acc, &u| format!("{acc}|{u}"))
                .trim_start_matches('|')
                .to_string(),
        );
        self
    }

    pub fn from_agent(mut self, agent_id: usize) -> Self {
        self.agent_id = Some(agent_id);
        self
    }

    pub fn with_safe(mut self, safe: i64) -> Self {
        self.safe = safe;
        self
    }
    pub fn with_enable_id_trans(mut self, enable_id_trans: i64) -> Self {
        self.enable_id_trans = enable_id_trans;
        self
    }
    pub fn with_enable_duplicate_check(mut self, enable_duplicate_check: i64) -> Self {
        self.enable_duplicate_check = enable_duplicate_check;
        self
    }
    pub fn with_duplicate_check_interval(mut self, duplicate_check_interval: usize) -> Self {
        self.duplicate_check_interval = duplicate_check_interval;
        self
    }

    pub fn build<T>(&self, content: T) -> Result<Value, Box<dyn std::error::Error>>
    where
        T: Serialize + WecomMessage,
    {
        if [&self.users, &self.groups, &self.tags]
            .iter()
            .all(|&x| x.is_none())
        {
            return Err(Box::new(Error::new(-999, "收件人不可为空".to_string())));
        }

        if self.agent_id.is_none() {
            return Err(Box::new(Error::new(-999, "AgentID不可为空".to_string())));
        }

        let empty_string = "".to_string();
        let mut j = json!({
            "touser": self.users.clone().unwrap_or(empty_string.clone()),
            "toparty": self.groups.clone().unwrap_or(empty_string.clone()),
            "totag": self.tags.clone().unwrap_or(empty_string.clone()),
            "msgtype": match content.msg_type() {
                MessageType::Audio => "voice".to_string(),
                MessageType::File => "file".to_string(),
                MessageType::Image => "image".to_string(),
                MessageType::Markdown => "markdown".to_string(),
                MessageType::News => "news".to_string(),
                MessageType::Text => "text".to_string(),
                MessageType::TextCard => "textcard".to_string(),
                MessageType::Video => "video".to_string(),
            },
            "agentid": self.agent_id.expect("AgentID should not be None"),
            "safe": self.safe,
            "enable_id_trans": self.enable_id_trans,
            "enable_duplicate_check": self.enable_duplicate_check,
            "duplicate_check_interval": self.duplicate_check_interval,});
        j.as_object_mut()
            .unwrap()
            .insert(content.key(), serde_json::to_value(content.value())?);
        Ok(j)
    }
}

// 文本消息
// 示例
// {
//    "touser" : "UserID1|UserID2|UserID3",
//    "toparty" : "PartyID1|PartyID2",
//    "totag" : "TagID1 | TagID2",
//    "msgtype" : "text",
//    "agentid" : 1,
//    "text" : {
//        "content" : "Hello from <a href=\"https://yinguobing.com\">Wondering AI</a>!"
//    },
//    "safe":0,
//    "enable_id_trans": 0,
//    "enable_duplicate_check": 0,
//    "duplicate_check_interval": 1800
// }
#[derive(Debug, Serialize, PartialEq)]
pub struct Text {
    content: String,
}

impl Text {
    pub fn new(content: String) -> Self {
        Self { content }
    }
}

impl WecomMessage for Text {
    fn msg_type(&self) -> MessageType {
        MessageType::Text
    }

    fn key(&self) -> String {
        "text".to_string()
    }
}

// 图片消息
// 示例
// {
//    "touser" : "UserID1|UserID2|UserID3",
//    "toparty" : "PartyID1|PartyID2",
//    "totag" : "TagID1 | TagID2",
//    "msgtype" : "image",
//    "agentid" : 1,
//    "image" : {
//         "media_id" : "MEDIA_ID"
//    },
//    "safe":0,
//    "enable_duplicate_check": 0,
//    "duplicate_check_interval": 1800
// }
pub struct ImageMsg {}

// 语音消息
// 示例
// {
//     "touser" : "UserID1|UserID2|UserID3",
//     "toparty" : "PartyID1|PartyID2",
//     "totag" : "TagID1 | TagID2",
//     "msgtype" : "voice",
//     "agentid" : 1,
//     "voice" : {
//          "media_id" : "MEDIA_ID"
//     },
//     "enable_duplicate_check": 0,
//     "duplicate_check_interval": 1800
// }
pub struct AudioMsg {}

// 视频消息
// 示例
// {
//     "touser" : "UserID1|UserID2|UserID3",
//     "toparty" : "PartyID1|PartyID2",
//     "totag" : "TagID1 | TagID2",
//     "msgtype" : "video",
//     "agentid" : 1,
//     "video" : {
//          "media_id" : "MEDIA_ID",
//          "title" : "Title",
//          "description" : "Description"
//     },
//     "safe":0,
//     "enable_duplicate_check": 0,
//     "duplicate_check_interval": 1800
// }
pub struct VideoMsg {}

// 文件消息
// 示例
// {
//     "touser" : "UserID1|UserID2|UserID3",
//     "toparty" : "PartyID1|PartyID2",
//     "totag" : "TagID1 | TagID2",
//     "msgtype" : "file",
//     "agentid" : 1,
//     "file" : {
//          "media_id" : "1Yv-zXfHjSjU-7LH-GwtYqDGS-zz6w22KmWAT5COgP7o"
//     },
//     "safe":0,
//     "enable_duplicate_check": 0,
//     "duplicate_check_interval": 1800
// }
pub struct FileMsg {}

// 文本卡片消息
// 示例
// {
//     "touser" : "UserID1|UserID2|UserID3",
//     "toparty" : "PartyID1 | PartyID2",
//     "totag" : "TagID1 | TagID2",
//     "msgtype" : "textcard",
//     "agentid" : 1,
//     "textcard" : {
//              "title" : "领奖通知",
//              "description" : "<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台,领奖码:xxxx</div><div class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>",
//              "url" : "URL",
//                          "btntxt":"更多"
//     },
//     "enable_id_trans": 0,
//     "enable_duplicate_check": 0,
//     "duplicate_check_interval": 1800
// }
pub struct TextCardMsg {}

// MarkDown消息
// 示例
// {
//     "touser" : "UserID1|UserID2|UserID3",
//     "toparty" : "PartyID1|PartyID2",
//     "totag" : "TagID1 | TagID2",
//     "msgtype": "markdown",
//     "agentid" : 1,
//     "markdown": {
//          "content": "您的会议室已经预定,稍后会同步到`邮箱`  \n>**事项详情**  \n>事 项:<font color=\"info\">开会</font>  \n>组织者:@miglioguan  \n>参与者:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang  \n>  \n>会议室:<font color=\"info\">广州TIT 1楼 301</font>  \n>日 期:<font color=\"warning\">2018年5月18日</font>  \n>时 间:<font color=\"comment\">上午9:00-11:00</font>  \n>  \n>请准时参加会议。  \n>  \n>如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)"
//     },
//     "enable_duplicate_check": 0,
//     "duplicate_check_interval": 1800
// }
pub struct MarkDownMsg {}

#[cfg(test)]
mod test {
    use std::vec;

    use super::*;
    #[test]
    fn test_builder() {
        let content = Text::new("hello text!".to_string());
        let msg = MessageBuilder::default()
            .to_users(vec!["robin", "tom", "Alex", "Susanna"])
            .to_groups(vec!["a", "b", "c"])
            .to_tags(vec!["x", "y", "z"])
            .from_agent(1)
            .with_safe(1)
            .with_enable_id_trans(1)
            .with_enable_duplicate_check(1)
            .with_duplicate_check_interval(800)
            .build(content)
            .expect("Massage should be built");
        let raw = json!({
            "touser" : "robin|tom|Alex|Susanna",
            "toparty" : "a|b|c",
            "totag" : "x|y|z",
            "msgtype": "text",
            "agentid" : 1,
            "safe": 1,
            "enable_id_trans": 1,
            "enable_duplicate_check": 1,
            "duplicate_check_interval": 800,
            "text": {
                 "content": "hello text!"
            },
        });
        assert_eq!(msg, serde_json::to_value(raw).unwrap());
    }
}