-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathMsgBuilder.cs
682 lines (627 loc) · 22.4 KB
/
MsgBuilder.cs
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
using Newtonsoft.Json;
using Pbx;
using System;
using System.Collections.Generic;
using System.Text;
using static Tinode.ChatBot.ChatBot;
namespace Tinode.ChatBot
{
/// <summary>
/// Nullable property for json serialization message base class.
/// </summary>
public class MessageBase
{
/// <summary>
/// override to json string
/// </summary>
/// <returns>json string </returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
}
}
/// <summary>
/// formatt control message
/// </summary>
public class FmtMessage:MessageBase
{
[JsonProperty("at")]
public int? At { get; set; }
[JsonProperty("len")]
public int? Len { get; set; }
[JsonProperty("tp")]
public string Tp { get; set; }
[JsonProperty("key")]
public int? Key { get; set; }
}
/// <summary>
/// entity message
/// </summary>
public class EntMessage:MessageBase
{
[JsonProperty("tp")]
public string Tp { get; set; }
[JsonProperty("data")]
public EntData Data { get; set; }
}
/// <summary>
/// entity data details
/// </summary>
public class EntData:MessageBase
{
[JsonProperty("mime")]
public string Mime { get; set; }
[JsonProperty("val")]
public dynamic Val { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("ref")]
public string Ref { get; set; }
[JsonProperty("width")]
public int? Width { get; set; }
[JsonProperty("height")]
public int? Height { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("size")]
public int? Size { get; set; }
[JsonProperty("act")]
public string Act { get; set; }
}
/// <summary>
/// Chat messaage
/// </summary>
public class ChatMessage:MessageBase
{
/// <summary>
/// message text part
/// </summary>
[JsonProperty("txt")]
public string Text { get; set; }
/// <summary>
/// message format information
/// </summary>
[JsonProperty("fmt")]
public List<FmtMessage> Fmt { get; set; }
/// <summary>
/// message entity information
/// </summary>
[JsonProperty("ent")]
public List<EntMessage> Ent { get; set; }
/// <summary>
/// if this is a plain text message
/// </summary>
[JsonIgnore]
public bool IsPlainText { get; set; }
/// <summary>
/// message from type, user or group, if not set it is unknown
/// </summary>
[JsonIgnore]
public string MessageType { get; set; }
public ChatMessage()
{
Text = "";
MessageType = "unknown";
}
/// <summary>
/// Get original text message, inlude original '\n'
/// </summary>
/// <returns>original message</returns>
public string GetFormattedText()
{
if (Text==null)
{
return null;
}
var textArray = Text.ToCharArray();
if (Fmt!=null)
{
foreach (var fmt in Fmt)
{
if (!string.IsNullOrEmpty(fmt.Tp))
{
if (fmt.Tp=="BR")
{
textArray[fmt.At.Value] = '\n';
}
}
}
}
return new String(textArray);
}
/// <summary>
/// get entity from chat message by entity type
/// </summary>
/// <param name="tp">entity type</param>
/// <returns>entity datas</returns>
public List<EntData> GetEntDatas(string tp)
{
var ret = new List<EntData>();
if (Ent != null)
{
foreach (var ent in Ent)
{
if (ent.Tp == tp)
{
ret.Add(ent.Data);
}
}
}
return ret;
}
/// <summary>
/// get mentioned users
/// </summary>
/// <returns>mentioned user datas</returns>
public List<EntData> GetMentions()
{
return GetEntDatas("MN");
}
/// <summary>
/// get images
/// </summary>
/// <returns>image data</returns>
public List<EntData> GetImages()
{
return GetEntDatas("IM");
}
/// <summary>
/// get hashtags
/// </summary>
/// <returns>hashtag data</returns>
public List<EntData> GetHashTags()
{
return GetEntDatas("HT");
}
/// <summary>
/// get links
/// </summary>
/// <returns>link data</returns>
public List<EntData> GetLinks()
{
return GetEntDatas("LN");
}
/// <summary>
/// get generic attachment
/// </summary>
/// <returns>generic attachment data</returns>
public List<EntData> GetGenericAttachment()
{
return GetEntDatas("EX");
}
}
/// <summary>
/// Chat message builder
/// </summary>
public class MsgBuilder
{
/// <summary>
/// Build message data
/// </summary>
public ChatMessage Message { get; private set; }
public MsgBuilder()
{
ReSet();
}
/// <summary>
/// Reset all build message to init
/// </summary>
public void ReSet()
{
Message = new ChatMessage();
Message.Ent = new List<EntMessage>();
Message.Fmt = new List<FmtMessage>();
}
/// <summary>
/// Append text message to build message
/// </summary>
/// <param name="text">text message</param>
/// <param name="isBold">if text should bold style</param>
/// <param name="isItalic">if text should italic style</param>
/// <param name="isDeleted">if text should deleted style</param>
/// <param name="isCode">if text is code like data</param>
/// <param name="isLink">if text is link</param>
/// <param name="isMention">if text is mention user, should contains '@', for example: @tinode</param>
/// <param name="isHashTag">if text is hashtags, should contains '#',for example: #tinode</param>
/// <param name="isForm">if text is form</param>
/// <param name="isButton">if text is button</param>
/// <param name="buttonDataName">button name</param>
/// <param name="buttonDataAct">button act</param>
/// <param name="buttonDataVal">button val</param>
public void AppendText(string text,bool isBold=false,bool isItalic=false,bool isDeleted=false
,bool isCode=false,bool isLink=false,bool isMention=false,bool isHashTag=false,bool isForm=false,bool isButton=false,string buttonDataName=null, string buttonDataAct="pub",string buttonDataVal=null)
{
int baseLen = Message.Text.Length;
Message.Text += text;
if (text.Contains("\n"))
{
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
FmtMessage fmt = new FmtMessage() { At = baseLen + i, Tp = "BR", Len = 1 };
Message.Fmt.Add(fmt);
}
}
}
var leftLen =baseLen+(text.Length- text.TrimStart().Length);
var subLen = text.Length - text.TrimEnd().Length;
var validLen = Message.Text.Length - leftLen - subLen;
if (isBold)
{
FmtMessage fmt = new FmtMessage() { Tp = "ST",At= leftLen, Len= validLen };
Message.Fmt.Add(fmt);
}
if (isItalic)
{
FmtMessage fmt = new FmtMessage() { Tp = "EM" ,At = leftLen, Len = validLen };
Message.Fmt.Add(fmt);
}
if (isDeleted)
{
FmtMessage fmt = new FmtMessage() { Tp = "DL" , At = leftLen, Len = validLen };
Message.Fmt.Add(fmt);
}
if (isCode)
{
FmtMessage fmt = new FmtMessage() { Tp = "CO" , At = leftLen, Len = validLen };
Message.Fmt.Add(fmt);
}
if (isLink)
{
FmtMessage fmt = new FmtMessage() { At = leftLen, Len = validLen ,Key=Message.Ent.Count};
Message.Fmt.Add(fmt);
var url = text.Trim().ToLower();
if (!url.StartsWith("http://")&&!url.StartsWith("https://"))
{
url = $"http://{text.Trim()}";
}
EntMessage ent = new EntMessage() { Tp="LN",Data=new EntData() { Url=url} };
Message.Ent.Add(ent);
}
if (isMention)
{
FmtMessage fmt = new FmtMessage() { At = leftLen, Len = validLen, Key = Message.Ent.Count };
Message.Fmt.Add(fmt);
var mentionName = text.Trim().Substring(1);
EntMessage ent = new EntMessage() { Tp = "MN", Data = new EntData() { Val = mentionName} };
Message.Ent.Add(ent);
}
if (isHashTag)
{
FmtMessage fmt = new FmtMessage() { At = leftLen, Len = validLen, Key = Message.Ent.Count };
Message.Fmt.Add(fmt);
var hashTag = text.Trim();
EntMessage ent = new EntMessage() { Tp = "HT", Data = new EntData() { Val = hashTag } };
Message.Ent.Add(ent);
}
if (isForm)
{
FmtMessage fmt = new FmtMessage() { At = leftLen, Len = validLen, Tp="FM" };
Message.Fmt.Add(fmt);
}
if (isButton)
{
var btnName = buttonDataName;
if (btnName == null)
{
buttonDataName = text.Trim().ToLower();
}
FmtMessage fmt = new FmtMessage() { At = leftLen, Len = validLen, Key = Message.Ent.Count };
Message.Fmt.Add(fmt);
var btnText = text.Trim();
EntMessage ent = new EntMessage() { Tp = "BN", Data = new EntData() {Name=buttonDataName, Act=buttonDataAct, Val = buttonDataVal } };
Message.Ent.Add(ent);
}
}
/// <summary>
/// Append text message and line break to build message
/// </summary>
/// <param name="text">text message</param>
/// <param name="isBold">if text should bold style</param>
/// <param name="isItalic">if text should italic style</param>
/// <param name="isDeleted">if text should deleted style</param>
/// <param name="isCode">if text is code like data</param>
/// <param name="isLink">if text is link</param>
/// <param name="isMention">if text is mention user, should contains '@', for example: @tinode</param>
/// <param name="isHashTag">if text is hashtags, should contains '#',for example: #tinode</param>
/// <param name="isForm">if text is form</param>
/// <param name="isButton">if text is button</param>
/// <param name="buttonDataName">button name</param>
/// <param name="buttonDataAct">button act</param>
/// <param name="buttonDataVal">button val</param>
public void AppendTextLine(string text, bool isBold = false, bool isItalic = false, bool isDeleted = false
, bool isCode = false, bool isLink = false, bool isMention = false, bool isHashTag = false, bool isForm = false, bool isButton = false, string buttonDataName = null, string buttonDataAct = "pub", string buttonDataVal = null)
{
AppendText($"{text}\n", isBold, isItalic, isDeleted, isCode, isLink, isMention, isHashTag,isForm,isButton,buttonDataName,buttonDataAct,buttonDataVal);
}
/// <summary>
/// Append image to build message
/// </summary>
/// <param name="imageName">image name</param>
/// <param name="mime">image mime type</param>
/// <param name="width">display width</param>
/// <param name="height">display height</param>
/// <param name="imageBase64">image base64 value</param>
public void AppendImage(string imageName, string mime, int width, int height, string imageBase64)
{
Message.Fmt.Add(new FmtMessage()
{
At = Message.Text.Length,
Len = 1,
Key = Message.Ent.Count,
});
Message.Ent.Add(new EntMessage()
{
Tp = "IM",
Data = new EntData()
{
Mime = mime,
Width = width,
Height = height,
Name = imageName,
Val = imageBase64,
}
});
}
/// <summary>
/// Append file to build message
/// </summary>
/// <param name="fileName">file name</param>
/// <param name="mime">file mime type</param>
/// <param name="contentBase64">file base64 value</param>
public void AppendFile(string fileName, string mime, string contentBase64)
{
Message.Fmt.Add(new FmtMessage()
{
At=Message.Text.Length,
Len = 0,
Key=Message.Ent.Count,
});
Message.Ent.Add(new EntMessage()
{
Tp = "EX",
Data = new EntData()
{
Mime = mime,
Name = fileName,
Val = contentBase64,
}
});
}
/// <summary>
/// append a attachment file to chat message
/// </summary>
/// <param name="attachmentInfo">attachment file information, you can get it with ChatBot.Upload(...)</param>
public void AppendAttachment(UploadedAttachmentInfo attachmentInfo)
{
Message.Fmt.Add(new FmtMessage()
{
At=Message.Text.Length,
Key=Message.Ent.Count,
Len = 1,
});
Message.Ent.Add(new EntMessage()
{
Tp="EX",
Data=new EntData()
{
Mime=attachmentInfo.Mime,
Name=attachmentInfo.FileName,
Ref=attachmentInfo.RelativeUrl,
Size=int.Parse(attachmentInfo.Size.ToString()),
},
});
}
/// <summary>
/// parse a raw ServerData to friendly ChatMessage
/// </summary>
/// <param name="message">raw messsage</param>
/// <returns>parsed chat message</returns>
public static ChatMessage Parse(ServerData message)
{
ChatMessage chatMsg;
if (message.Head.ContainsKey("mime"))
{
chatMsg = JsonConvert.DeserializeObject<ChatMessage>(message.Content.ToStringUtf8()
, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
chatMsg.IsPlainText = false;
}
else
{
chatMsg = new ChatMessage() { Text = JsonConvert.DeserializeObject<string>(message.Content.ToStringUtf8()) };
chatMsg.IsPlainText = true;
}
if (message.Topic.StartsWith("usr"))
{
chatMsg.MessageType = "user";
}
else if (message.Topic.StartsWith("grp"))
{
chatMsg.MessageType = "group";
}
return chatMsg;
}
/// <summary>
/// try to parse a raw ServerData to friendly ChatMessage
/// </summary>
/// <param name="message">raw message</param>
/// <param name="chatMsg">parsed chat message</param>
/// <returns>success:true, else:false</returns>
public static bool TryParse(ServerData message,out ChatMessage chatMsg)
{
try
{
chatMsg = MsgBuilder.Parse(message);
return true;
}
catch (Exception e)
{
chatMsg = null;
return false;
}
}
/// <summary>
/// build text chat message with formatted
/// </summary>
/// <param name="text">text message</param>
/// <returns>text chat message</returns>
public static ChatMessage BuildTextMessage(string text=" ")
{
var msg = new ChatMessage();
msg.Text = text;
msg.Ent = new List<EntMessage>();
msg.Fmt = new List<FmtMessage>();
if (text.Contains("\n"))
{
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
FmtMessage fmt = new FmtMessage() { At = i, Tp = "BR",Len=1 };
msg.Fmt.Add(fmt);
}
}
}
return msg;
}
/// <summary>
/// build a image chat message
/// </summary>
/// <param name="imageName">image file name</param>
/// <param name="mime">mime type.such as image/png</param>
/// <param name="width">image display width</param>
/// <param name="height">image display height</param>
/// <param name="imageBase64">iamge with base64 encode</param>
/// <param name="text">text message with the image</param>
/// <returns>image chat message</returns>
public static ChatMessage BuildImageMessage(string imageName,string mime,int width,int height,string imageBase64,string text=" ")
{
var msg = new ChatMessage();
msg.Text = text;
msg.Ent = new List<EntMessage>();
msg.Fmt = new List<FmtMessage>();
msg.Ent.Add(new EntMessage()
{
Tp = "IM",
Data = new EntData()
{
Mime = mime,
Width = width,
Height = height,
Name = imageName,
Val = imageBase64,
}
});
msg.Fmt.Add(new FmtMessage()
{
At=text.Length,
Len = 1,
Key=0,
});
if (text.Contains("\n"))
{
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
FmtMessage fmt = new FmtMessage() { At = i, Tp = "BR",Len=1 };
msg.Fmt.Add(fmt);
}
}
}
return msg;
}
/// <summary>
/// build a file chat message
/// </summary>
/// <param name="fileName">file name</param>
/// <param name="mime">mime type, such as text/plain</param>
/// <param name="contentBase64">file with base64 encode</param>
/// <param name="text">text messaage with the file</param>
/// <returns>file chat message</returns>
public static ChatMessage BuildFileMessage(string fileName, string mime, string contentBase64, string text = " ")
{
var msg = new ChatMessage();
msg.Text = text;
msg.Ent = new List<EntMessage>();
msg.Fmt = new List<FmtMessage>();
msg.Ent.Add(new EntMessage()
{
Tp = "EX",
Data = new EntData()
{
Mime = mime,
Name = fileName,
Val = contentBase64,
}
});
msg.Fmt.Add(new FmtMessage()
{
At=text.Length,
Len = 0,
Key=0,
});
if (text.Contains("\n"))
{
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
FmtMessage fmt = new FmtMessage() { At = i, Tp = "BR",Len=1 };
msg.Fmt.Add(fmt);
}
}
}
return msg;
}
/// <summary>
/// build a attachment message
/// </summary>
/// <param name="attachmentInfo">attachment file information, you can get it with ChatBot.Upload(...)</param>
/// <param name="text">text message with the attachment</param>
/// <returns>attachment chat message</returns>
public static ChatMessage BuildAttachmentMessage(UploadedAttachmentInfo attachmentInfo, string text=" ")
{
var msg = new ChatMessage();
msg.Text = text;
msg.Ent = new List<EntMessage>();
msg.Fmt = new List<FmtMessage>();
msg.Ent.Add(new EntMessage()
{
Tp = "EX",
Data = new EntData()
{
Mime = attachmentInfo.Mime,
Name = attachmentInfo.FileName,
Ref = attachmentInfo.RelativeUrl,
Size= int.Parse(attachmentInfo.Size.ToString()),
}
});
msg.Fmt.Add(new FmtMessage()
{
At = text.Length,
Len = 1,
Key = 0,
});
if (text.Contains("\n"))
{
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
FmtMessage fmt = new FmtMessage() { At = i, Tp = "BR", Len = 1 };
msg.Fmt.Add(fmt);
}
}
}
return msg;
}
}
}