forked from tucnak/telebot
/
entity_parser.go
90 lines (77 loc) · 2.14 KB
/
entity_parser.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
package telebot
import (
"fmt"
"html"
"unicode/utf16"
)
func (msg *Message) MessageHTMLText() string {
entities := msg.Entities
text := html.EscapeString(msg.Text)
inputu16 := utf16.Encode([]rune(text))
var outputu16 []uint16
var counter int
for idx := 0; idx <= len(inputu16); idx++ {
inputTags := []uint16{}
for _, entity := range entities {
start := entity.Offset
end := entity.Offset + entity.Length
pref, postf := getEntityTags(entity)
if idx == start {
inputTags = append(inputTags, pref...)
} else if idx == end {
inputTags = append(postf, inputTags...)
}
}
if len(inputTags) > 0 || idx == len(inputu16) {
nextRawPartCopy := make([]uint16, len(inputu16[counter:idx]))
copy(nextRawPartCopy, inputu16[counter:idx])
nextPart := append(nextRawPartCopy, inputTags...)
outputu16 = append(outputu16, nextPart...)
counter = idx
}
}
if len(outputu16) > 0 {
text = string(utf16.Decode(outputu16))
}
return text
}
func getEntityTags(entity MessageEntity) ([]uint16, []uint16) {
var prefix, postfix string
switch entity.Type {
case EntityBold:
prefix, postfix = "<b>", "</b>"
case EntityItalic:
prefix, postfix = "<i>", "</i>"
case EntityUnderline:
prefix, postfix = "<u>", "</u>"
case EntityStrikethrough:
prefix, postfix = "<s>", "</s>"
case EntitySpoiler:
prefix, postfix = "<tg-spoiler>", "</tg-spoiler>"
case EntityTextLink:
fallthrough
case EntityURL:
prefix, postfix = fmt.Sprintf(`<a href="%s">`, entity.URL), "</a>"
case EntityTMention:
fallthrough
case EntityMention:
if entity.User != nil {
prefix, postfix = fmt.Sprintf(`<a href="tg://user?id=%v">`, entity.User.ID), "</a>"
} else {
prefix, postfix = "", ""
}
case EntityCustomEmoji:
prefix, postfix = fmt.Sprintf(`<tg-emoji emoji-id="%v">`, entity.CustomEmoji), "</tg-emoji >"
case EntityCodeBlock:
fallthrough
case EntityCode:
if len(entity.Language) > 0 {
prefix, postfix = fmt.Sprintf(`<code class="%v">`, entity.Language), "</code>"
} else {
prefix, postfix = `<code>`, "</code>"
}
default:
prefix, postfix = "", ""
}
return utf16.Encode([]rune(prefix)), utf16.Encode([]rune(postfix))
}