/
Message.go
764 lines (660 loc) · 23.9 KB
/
Message.go
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
package ext
import (
"encoding/json"
"fmt"
"html"
"strconv"
"strings"
"unicode"
"unicode/utf16"
"github.com/veerpratap1234/gotgbot/parsemode"
)
type MessageEntity struct {
Type string `json:"type"`
Offset int `json:"offset"`
Length int `json:"length"`
Url string `json:"url"`
User *User `json:"user"`
Language string `json:"language"`
}
type ParsedMessageEntity struct {
Type string `json:"type"`
Offset int `json:"offset"`
Length int `json:"length"`
Url string `json:"url"`
User *User `json:"user"`
Text string `json:"text"`
}
type Audio struct {
FileId string `json:"file_id"`
FileUniqueId string `json:"file_unique_id"`
Duration int `json:"duration"`
Performer string `json:"performer"`
Title string `json:"title"`
FileName string `json:"file_name"`
MimeType string `json:"mime_type"`
FileSize int `json:"file_size"`
Thumb *PhotoSize `json:"thumb"`
}
type Document struct {
FileId string `json:"file_id"`
FileUniqueId string `json:"file_unique_id"`
Thumb *PhotoSize `json:"thumb"`
FileName string `json:"file_name"`
MimeType string `json:"mime_type"`
FileSize int `json:"file_size"`
}
type PhotoSize struct {
FileId string `json:"file_id"`
FileUniqueId string `json:"file_unique_id"`
Width int `json:"width"`
Height int `json:"height"`
FileSize int `json:"file_size"`
}
type Video struct {
FileId string `json:"file_id"`
FileUniqueId string `json:"file_unique_id"`
Width int `json:"width"`
Height int `json:"height"`
Duration int `json:"duration"`
Thumb *PhotoSize `json:"thumb"`
FileName string `json:"file_name"`
MimeType string `json:"mime_type"`
FileSize int `json:"file_size"`
}
type Voice struct {
FileId string `json:"file_id"`
FileUniqueId string `json:"file_unique_id"`
Duration int `json:"duration"`
MimeType string `json:"mime_type"`
FileSize int `json:"file_size"`
}
type VideoNote struct {
FileId string `json:"file_id"`
FileUniqueId string `json:"file_unique_id"`
Length int `json:"length"`
Duration int `json:"duration"`
Thumb *PhotoSize `json:"thumb"`
FileSize int `json:"file_size"`
}
type Contact struct {
PhoneNumber string `json:"phone_number"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
UserId int `json:"user_id"`
}
type Location struct {
Longitude float64 `json:"longitude"`
Latitude float64 `json:"latitude"`
HorizontalAccuracy float64 `json:"horizontal_accuracy"`
LivePeriod int `json:"live_period"`
Heading int `json:"heading"`
ProximityAlertRadius int `json:"proximity_alert_radius"`
}
type Venue struct {
Location Location `json:"location"`
Title string `json:"title"`
Address string `json:"address"`
FoursquareId string `json:"foursquare_id"`
FoursquareType string `json:"foursquare_type"`
GooglePlaceId string `json:"google_place_id"`
GooglePlaceType string `json:"google_place_type"`
}
type ProximityAlertTriggered struct {
Traveler User `json:"traveler"`
Watcher User `json:"watcher"`
Distance int `json:"distance"`
}
type PreCheckoutQuery struct {
Id string `json:"id"`
From *User `json:"from"`
Currency string `json:"currency"`
TotalAmount int `json:"total_amount"`
InvoicePayload string `json:"invoice_payload"`
ShippingOptionId string `json:"shipping_option_id"`
OrderInfo OrderInfo `json:"order_info"`
}
type PollOption struct {
Text string `json:"text"`
VoterCount int `json:"voter_count"`
}
type Poll struct {
Bot Bot `json:"-"`
Id string `json:"id"`
Question string `json:"question"`
Options []PollOption `json:"options"`
TotalVoterCount int `json:"total_voter_count"`
IsClosed bool `json:"is_closed"`
IsAnonymous bool `json:"is_anonymous"`
Type string `json:"type"`
AllowsMultipleAnswers bool `json:"allows_multiple_answers"`
CorrectOptionId int `json:"correct_option_id"`
Explanation string `json:"explanation"`
ExplanationEntities []MessageEntity `json:"explanation_entities"`
OpenPeriod int `json:"open_period"`
CloseDate int `json:"close_date"`
}
type PollAnswer struct {
Bot Bot `json:"-"`
PollId string `json:"poll_id"`
User *User `json:"user"`
OptionIds []int `json:"option_ids"`
}
type Dice struct {
Bot Bot `json:"-"`
Emoji string `json:"emoji"`
Value int `json:"value"`
}
type Message struct {
Bot Bot `json:"-"`
MessageId int `json:"message_id"`
From *User `json:"from"`
SenderChat *Chat `json:"sender_chat"`
Date int `json:"date"`
Chat *Chat `json:"chat"`
ForwardFrom *User `json:"forward_from"`
ForwardFromChat *Chat `json:"forward_from_chat"`
ForwardFromMessageId int `json:"forward_from_message_id"`
ForwardSignature string `json:"forward_signature"`
ForwardSenderName string `json:"forward_sender_name"`
ForwardDate int `json:"forward_date"`
ReplyToMessage *Message `json:"reply_to_message"`
ViaBot *User `json:"via_bot"`
EditDate int `json:"edit_date"`
MediaGroupId string `json:"media_group_id"`
AuthorSignature string `json:"author_signature"`
Text string `json:"text"`
Entities []MessageEntity `json:"entities"`
CaptionEntities []MessageEntity `json:"caption_entities"`
Audio *Audio `json:"audio"`
Document *Document `json:"document"`
Animation *Animation `json:"animation"`
Game *Game `json:"game"`
Photo []PhotoSize `json:"photo"`
Sticker *Sticker `json:"sticker"`
Video *Video `json:"video"`
Voice *Voice `json:"voice"`
VideoNote *VideoNote `json:"video_note"`
Caption string `json:"caption"`
Contact *Contact `json:"contact"`
Location *Location `json:"location"`
Venue *Venue `json:"venue"`
Poll *Poll `json:"poll"`
Dice *Dice `json:"dice"`
NewChatMembers []User `json:"new_chat_members"`
LeftChatMember *User `json:"left_chat_member"`
NewChatTitle string `json:"new_chat_title"`
NewChatPhoto []PhotoSize `json:"new_chat_photo"`
DeleteChatPhoto bool `json:"delete_chat_photo"`
GroupChatCreated bool `json:"group_chat_created"`
SupergroupChatCreated bool `json:"supergroup_chat_created"`
ChannelChatCreated bool `json:"channel_chat_created"`
MigrateToChatId int `json:"migrate_to_chat_id"`
MigrateFromChatId int `json:"migrate_from_chat_id"`
PinnedMessage *Message `json:"pinned_message"`
Invoice *Invoice `json:"invoice"`
SuccessfulPayment *SuccessfulPayment `json:"successful_payment"`
ConnectedWebsite string `json:"connected_website"`
PassportData *PassportData `json:"passport_data"`
ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered"`
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup"`
// internals
utf16Text []uint16
utf16Caption []uint16
originalTextMD string
originalTextMDV2 string
originalTextHTML string
originalCaptionMD string
originalCaptionMDV2 string
originalCaptionHTML string
}
func (b Bot) ParseMessage(message json.RawMessage) (mess *Message, err error) {
mess = &Message{Bot: b}
return mess, json.Unmarshal(message, mess)
}
func (m Message) ReplyText(text string) (*Message, error) {
return m.Bot.ReplyText(m.Chat.Id, text, m.MessageId)
}
func (m Message) ReplyTextf(format string, a ...interface{}) (*Message, error) {
return m.Bot.ReplyText(m.Chat.Id, fmt.Sprintf(format, a...), m.MessageId)
}
func (m Message) ReplyHTML(text string) (*Message, error) {
return m.Bot.ReplyHTML(m.Chat.Id, text, m.MessageId)
}
func (m Message) ReplyHTMLf(format string, a ...interface{}) (*Message, error) {
return m.Bot.ReplyHTML(m.Chat.Id, fmt.Sprintf(format, a...), m.MessageId)
}
func (m Message) ReplyMarkdown(text string) (*Message, error) {
return m.Bot.ReplyMarkdown(m.Chat.Id, text, m.MessageId)
}
func (m Message) ReplyMarkdownf(format string, a ...interface{}) (*Message, error) {
return m.Bot.ReplyMarkdown(m.Chat.Id, fmt.Sprintf(format, a...), m.MessageId)
}
func (m Message) EditText(text string) (*Message, error) {
return m.Bot.EditMessageText(m.Chat.Id, m.MessageId, text)
}
func (m Message) EditTextf(format string, a ...interface{}) (*Message, error) {
return m.Bot.EditMessageText(m.Chat.Id, m.MessageId, fmt.Sprintf(format, a...))
}
func (m Message) EditHTML(text string) (*Message, error) {
return m.Bot.EditMessageHTML(m.Chat.Id, m.MessageId, text)
}
func (m Message) EditHTMLf(format string, a ...interface{}) (*Message, error) {
return m.Bot.EditMessageHTML(m.Chat.Id, m.MessageId, fmt.Sprintf(format, a...))
}
func (m Message) EditMarkdown(text string) (*Message, error) {
return m.Bot.EditMessageMarkdown(m.Chat.Id, m.MessageId, text)
}
func (m Message) EditMarkdownf(format string, a ...interface{}) (*Message, error) {
return m.Bot.EditMessageMarkdown(m.Chat.Id, m.MessageId, fmt.Sprintf(format, a...))
}
func (m Message) EditCaption(text string) (*Message, error) {
return m.Bot.EditMessageCaption(m.Chat.Id, m.MessageId, text)
}
func (m Message) EditCaptionf(format string, a ...interface{}) (*Message, error) {
return m.Bot.EditMessageCaption(m.Chat.Id, m.MessageId, fmt.Sprintf(format, a...))
}
func (m Message) EditCaptionHTML(text string) (*Message, error) {
return m.Bot.editMessageCaption(m.Chat.Id, m.MessageId, text, nil, parsemode.Html)
}
func (m Message) EditCaptionHTMLf(format string, a ...interface{}) (*Message, error) {
return m.Bot.editMessageCaption(m.Chat.Id, m.MessageId, fmt.Sprintf(format, a...), nil, parsemode.Html)
}
func (m Message) EditCaptionMarkdown(text string) (*Message, error) {
return m.Bot.editMessageCaption(m.Chat.Id, m.MessageId, text, nil, parsemode.Markdown)
}
func (m Message) EditCaptionMarkdownf(format string, a ...interface{}) (*Message, error) {
return m.Bot.editMessageCaption(m.Chat.Id, m.MessageId, fmt.Sprintf(format, a...), nil, parsemode.Markdown)
}
func (m Message) ReplyAudio(audio InputFile) (*Message, error) {
return m.Bot.ReplyAudio(m.Chat.Id, audio, m.MessageId)
}
func (m Message) ReplyDocument(document InputFile) (*Message, error) {
return m.Bot.ReplyDocument(m.Chat.Id, document, m.MessageId)
}
func (m Message) ReplyLocation(latitude float64, longitude float64) (*Message, error) {
return m.Bot.ReplyLocation(m.Chat.Id, latitude, longitude, m.MessageId)
}
func (m Message) ReplyPhoto(photo InputFile) (*Message, error) {
return m.Bot.ReplyPhoto(m.Chat.Id, photo, m.MessageId)
}
func (m Message) ReplySticker(sticker InputFile) (*Message, error) {
return m.Bot.ReplySticker(m.Chat.Id, sticker, m.MessageId)
}
func (m Message) ReplyVenue(latitude float64, longitude float64, title string, address string) (*Message, error) {
return m.Bot.ReplyVenue(m.Chat.Id, latitude, longitude, title, address, m.MessageId)
}
func (m Message) ReplyVideo(video InputFile) (*Message, error) {
return m.Bot.ReplyVideo(m.Chat.Id, video, m.MessageId)
}
func (m Message) ReplyVideoNote(videoNote InputFile) (*Message, error) {
return m.Bot.ReplyVideoNote(m.Chat.Id, videoNote, m.MessageId)
}
func (m Message) ReplyVoice(voice InputFile) (*Message, error) {
return m.Bot.ReplyVoice(m.Chat.Id, voice, m.MessageId)
}
func (m Message) Delete() (bool, error) {
return m.Bot.DeleteMessage(m.Chat.Id, m.MessageId)
}
func (m Message) Forward(chatId int) (*Message, error) {
return m.Bot.ForwardMessage(chatId, m.Chat.Id, m.MessageId)
}
func (m *Message) ParseEntities() (out []ParsedMessageEntity) {
for _, ent := range m.Entities {
out = append(out, m.ParseEntity(ent))
}
return out
}
func (m *Message) ParseCaptionEntities() (out []ParsedMessageEntity) {
for _, ent := range m.CaptionEntities {
out = append(out, m.ParseCaptionEntity(ent))
}
return out
}
func (m *Message) ParseEntityTypes(accepted map[string]struct{}) (out []ParsedMessageEntity) {
for _, ent := range m.Entities {
if _, ok := accepted[ent.Type]; ok {
out = append(out, m.ParseEntity(ent))
}
}
return out
}
func (m *Message) ParseCaptionEntityTypes(accepted map[string]struct{}) (out []ParsedMessageEntity) {
for _, ent := range m.CaptionEntities {
if _, ok := accepted[ent.Type]; ok {
out = append(out, m.ParseCaptionEntity(ent))
}
}
return out
}
func (m *Message) ParseEntity(entity MessageEntity) ParsedMessageEntity {
if m.utf16Text == nil {
m.utf16Text = utf16.Encode([]rune(m.Text))
}
text := string(utf16.Decode(m.utf16Text[entity.Offset : entity.Offset+entity.Length]))
if entity.User != nil {
entity.User.Bot = m.Bot
}
if entity.Type == "url" {
entity.Url = text
}
return ParsedMessageEntity{
Type: entity.Type,
Offset: len(string(utf16.Decode(m.utf16Text[:entity.Offset]))),
Length: len(text),
Url: entity.Url,
User: entity.User,
Text: text,
}
}
func (m *Message) ParseCaptionEntity(entity MessageEntity) ParsedMessageEntity {
if m.utf16Caption == nil {
m.utf16Caption = utf16.Encode([]rune(m.Caption))
}
text := string(utf16.Decode(m.utf16Caption[entity.Offset : entity.Offset+entity.Length]))
if entity.User != nil {
entity.User.Bot = m.Bot
}
if entity.Type == "url" {
entity.Url = text
}
return ParsedMessageEntity{
Type: entity.Type,
Offset: len(string(utf16.Decode(m.utf16Caption[:entity.Offset]))),
Length: len(text),
Url: entity.Url,
User: entity.User,
Text: text,
}
}
var mdMap = map[string]string{
"bold": "*",
"italic": "_",
"code": "`",
}
var mdV2Map = map[string]string{
"bold": "*",
"italic": "_",
"code": "`",
"pre": "```",
"underline": "__",
"strikethrough": "~",
}
var htmlMap = map[string]string{
"bold": "b",
"italic": "i",
"code": "code",
"pre": "pre",
"underline": "u",
"strikethrough": "s",
}
func (m *Message) OriginalText() string {
return m.originalMD()
}
func (m *Message) OriginalTextV2() string {
return m.originalMDV2()
}
func (m *Message) OriginalHTML() string {
return m.originalHTML()
}
func (m *Message) originalMD() string {
if m.originalTextMD != "" {
return m.originalTextMD
}
if m.utf16Text == nil {
m.utf16Text = utf16.Encode([]rune(m.Text))
}
m.originalTextMD = getOrigMsgMD(m.utf16Text, m.Entities)
return m.originalTextMD
}
func (m *Message) originalHTML() string {
if m.originalTextHTML != "" {
return m.originalTextHTML
}
if m.utf16Text == nil {
m.utf16Text = utf16.Encode([]rune(m.Text))
}
m.originalTextHTML = getOrigMsgHTML(m.utf16Text, m.Entities)
return m.originalTextHTML
}
func (m *Message) originalMDV2() string {
if m.originalTextMDV2 != "" {
return m.originalTextMDV2
}
if m.utf16Text == nil {
m.utf16Text = utf16.Encode([]rune(m.Text))
}
m.originalTextMDV2 = getOrigMsgMDV2(m.utf16Text, m.Entities)
return m.originalTextMDV2
}
func (m *Message) OriginalCaption() string {
return m.originalCaptionTextMD()
}
func (m *Message) OriginalCaptionV2() string {
return m.originalCaptionTextMDV2()
}
func (m *Message) OriginalCaptionHTML() string {
return m.originalCaptionTextHTML()
}
func (m *Message) originalCaptionTextMD() string {
if m.originalCaptionMD != "" {
return m.originalCaptionMD
}
if m.utf16Caption == nil {
m.utf16Caption = utf16.Encode([]rune(m.Caption))
}
m.originalCaptionMD = getOrigMsgMD(m.utf16Caption, m.CaptionEntities)
return m.originalCaptionMD
}
func (m *Message) originalCaptionTextHTML() string {
if m.originalCaptionHTML != "" {
return m.originalCaptionHTML
}
if m.utf16Caption == nil {
m.utf16Caption = utf16.Encode([]rune(m.Caption))
}
m.originalCaptionHTML = getOrigMsgHTML(m.utf16Caption, m.CaptionEntities)
return m.originalCaptionHTML
}
func (m *Message) originalCaptionTextMDV2() string {
if m.originalCaptionMDV2 != "" {
return m.originalCaptionMDV2
}
if m.utf16Caption == nil {
m.utf16Caption = utf16.Encode([]rune(m.Caption))
}
m.originalCaptionMDV2 = getOrigMsgMDV2(m.utf16Caption, m.CaptionEntities)
return m.originalCaptionMDV2
}
// Does not support nesting. only look at upper entities.
func getOrigMsgMD(utf16Data []uint16, ents []MessageEntity) string {
out := strings.Builder{}
prev := 0
for _, ent := range getUpperEntities(ents) {
newPrev := ent.Offset + ent.Length
prevText := string(utf16.Decode(utf16Data[prev:ent.Offset]))
text := utf16.Decode(utf16Data[ent.Offset:newPrev])
pre, cleanCntnt, post := splitEdgeWhitespace(string(text))
cleanCntntRune := []rune(cleanCntnt)
switch ent.Type {
case "bold", "italic", "code":
out.WriteString(prevText + pre + mdMap[ent.Type] + escapeContainedMDV1(cleanCntntRune, []rune(mdMap[ent.Type])) + mdMap[ent.Type] + post)
case "text_mention":
out.WriteString(prevText + pre + "[" + escapeContainedMDV1(cleanCntntRune, []rune("[]()")) + "](tg://user?id=" + strconv.Itoa(ent.User.Id) + ")" + post)
case "text_link":
out.WriteString(prevText + pre + "[" + escapeContainedMDV1(cleanCntntRune, []rune("[]()")) + "](" + ent.Url + ")" + post)
default:
continue
}
prev = newPrev
}
out.WriteString(string(utf16.Decode(utf16Data[prev:])))
return out.String()
}
func getOrigMsgHTML(utf16Data []uint16, ents []MessageEntity) string {
if len(ents) == 0 {
return html.EscapeString(string(utf16.Decode(utf16Data)))
}
bd := strings.Builder{}
prev := 0
for _, e := range getUpperEntities(ents) {
data, end := fillNestedHTML(utf16Data, e, prev, getChildEntities(e, ents))
bd.WriteString(data)
prev = end
}
bd.WriteString(html.EscapeString(string(utf16.Decode(utf16Data[prev:]))))
return bd.String()
}
func getOrigMsgMDV2(utf16Data []uint16, ents []MessageEntity) string {
if len(ents) == 0 {
return string(utf16.Decode(utf16Data))
}
bd := strings.Builder{}
prev := 0
for _, e := range getUpperEntities(ents) {
data, end := fillNestedMarkdownV2(utf16Data, e, prev, getChildEntities(e, ents))
bd.WriteString(data)
prev = end
}
bd.WriteString(string(utf16.Decode(utf16Data[prev:])))
return bd.String()
}
func fillNestedHTML(data []uint16, ent MessageEntity, start int, entities []MessageEntity) (string, int) {
entEnd := ent.Offset + ent.Length
if len(entities) == 0 || entEnd < entities[0].Offset {
// no nesting; just return straight away and move to next.
return writeFinalHTML(data, ent, start, html.EscapeString(string(utf16.Decode(data[ent.Offset:entEnd])))), entEnd
}
subPrev := ent.Offset
subEnd := ent.Offset
bd := strings.Builder{}
for _, e := range getUpperEntities(entities) {
if e.Offset < subEnd || e == ent {
continue
}
if e.Offset >= entEnd {
break
}
out, end := fillNestedHTML(data, e, subPrev, getChildEntities(e, entities))
bd.WriteString(out)
subPrev = end
}
bd.WriteString(html.EscapeString(string(utf16.Decode(data[subPrev:entEnd]))))
return writeFinalHTML(data, ent, start, bd.String()), entEnd
}
func fillNestedMarkdownV2(data []uint16, ent MessageEntity, start int, entities []MessageEntity) (string, int) {
entEnd := ent.Offset + ent.Length
if len(entities) == 0 || entEnd < entities[0].Offset {
// no nesting; just return straight away and move to next.
return writeFinalMarkdownV2(data, ent, start, string(utf16.Decode(data[ent.Offset:entEnd]))), entEnd
}
subPrev := ent.Offset
subEnd := ent.Offset
bd := strings.Builder{}
for _, e := range getUpperEntities(entities) {
if e.Offset < subEnd || e == ent {
continue
}
if e.Offset >= entEnd {
break
}
out, end := fillNestedMarkdownV2(data, e, subPrev, getChildEntities(e, entities))
bd.WriteString(out)
subPrev = end
}
bd.WriteString(string(utf16.Decode(data[subPrev:entEnd])))
return writeFinalMarkdownV2(data, ent, start, bd.String()), entEnd
}
func splitEdgeWhitespace(text string) (pre string, cntnt string, post string) {
bd := strings.Builder{}
rText := []rune(text)
for i := 0; i < len(rText) && unicode.IsSpace(rText[i]); i++ {
bd.WriteRune(rText[i])
}
pre = bd.String()
text = strings.TrimPrefix(text, pre)
bd.Reset()
for i := len(rText) - 1; i >= 0 && unicode.IsSpace(rText[i]); i-- {
bd.WriteRune(rText[i])
}
post = bd.String()
return pre, strings.TrimSuffix(text, post), post
}
func writeFinalHTML(data []uint16, ent MessageEntity, start int, cntnt string) string {
prevText := html.EscapeString(string(utf16.Decode(data[start:ent.Offset])))
switch ent.Type {
case "bold", "italic", "code", "underline", "strikethrough":
return prevText + "<" + htmlMap[ent.Type] + ">" + cntnt + "</" + htmlMap[ent.Type] + ">"
case "pre":
// <pre>text</pre>
if ent.Language == "" {
return prevText + "<pre>" + cntnt + "</pre>"
}
// <pre><code class="lang">text</code></pre>
return prevText + `<pre><code class="` + ent.Language + `">` + cntnt + "</code></pre>"
case "text_mention":
return prevText + `<a href="tg://user?id=` + strconv.Itoa(ent.User.Id) + `">` + cntnt + "</a>"
case "text_link":
return prevText + `<a href="` + ent.Url + `">` + cntnt + "</a>"
default:
return prevText + cntnt
}
}
func writeFinalMarkdownV2(data []uint16, ent MessageEntity, start int, cntnt string) string {
prevText := string(utf16.Decode(data[start:ent.Offset]))
pre, cleanCntnt, post := splitEdgeWhitespace(cntnt)
switch ent.Type {
case "bold", "italic", "code", "underline", "strikethrough", "pre":
return prevText + pre + mdV2Map[ent.Type] + cleanCntnt + mdV2Map[ent.Type] + post
case "text_mention":
return prevText + pre + "[" + cleanCntnt + "](tg://user?id=" + strconv.Itoa(ent.User.Id) + ")" + post
case "text_link":
return prevText + pre + "[" + cleanCntnt + "](" + ent.Url + ")" + post
default:
return prevText + cntnt
}
}
func getUpperEntities(ents []MessageEntity) []MessageEntity {
prev := 0
var uppers []MessageEntity
for _, e := range ents {
if e.Offset < prev {
continue
}
uppers = append(uppers, e)
prev = e.Offset + e.Length
}
return uppers
}
func getChildEntities(ent MessageEntity, ents []MessageEntity) []MessageEntity {
end := ent.Offset + ent.Length
var children []MessageEntity
for _, e := range ents {
if e.Offset < ent.Offset || e == ent {
continue
}
if e.Offset >= end {
break
}
children = append(children, e)
}
return children
}
func escapeContainedMDV1(data []rune, mdType []rune) string {
out := strings.Builder{}
for _, x := range data {
if contains(x, mdType) {
out.WriteRune('\\')
}
out.WriteRune(x)
}
return out.String()
}
func contains(r rune, rs []rune) bool {
for _, rr := range rs {
if r == rr {
return true
}
}
return false
}