-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
parser.go
268 lines (243 loc) · 5.27 KB
/
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
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
package html
import (
"io"
"strings"
"github.com/go-faster/errors"
"golang.org/x/net/html"
"github.com/gotd/td/telegram/message/entity"
"github.com/gotd/td/tg"
)
type htmlParser struct {
tokenizer *html.Tokenizer
builder *entity.Builder
stack stack
attr map[string]string
opts Options
}
func (p *htmlParser) fillAttrs() {
// Clear old attrs.
for k := range p.attr {
delete(p.attr, k)
}
// Fill with new attributes.
for {
key, value, ok := p.tokenizer.TagAttr()
p.attr[string(key)] = string(value)
if !ok {
break
}
}
}
const (
pre = "pre"
code = "code"
em = "em"
ins = "ins"
strike = "strike"
del = "del"
strong = "strong"
span = "span"
tgSpoiler = "tg-spoiler"
)
func (p *htmlParser) tag(tn []byte) string {
// Here we intern some well-known tags.
switch string(tn) {
case "b":
return "b"
case strong:
return strong
case "i":
return "i"
case em:
return em
case "u":
return "u"
case ins:
return ins
case "s":
return "s"
case strike:
return strike
case del:
return del
case "a":
return "a"
case pre:
return pre
case code:
return code
case span:
return span
case tgSpoiler:
return tgSpoiler
default:
return string(tn)
}
}
func (p *htmlParser) startTag() error {
var e stackElem
tn, hasAttr := p.tokenizer.TagName()
e.tag = p.tag(tn)
if hasAttr {
p.fillAttrs()
}
e.token = p.builder.Token()
// See https://core.telegram.org/bots/api#html-style.
switch e.tag {
case "b", strong:
e.format = entity.Bold()
case "i", em:
e.format = entity.Italic()
case "u", ins:
e.format = entity.Underline()
case "s", strike, del:
e.format = entity.Strike()
case "a":
e.attr = p.attr["href"]
if e.attr == "" {
break
}
f, err := getURLFormatter(e.attr, p.opts.UserResolver)
if err != nil {
f = nil
}
e.format = f
case code:
const langPrefix = "language-"
e.format = entity.Code()
e.attr = strings.TrimPrefix(p.attr["class"], langPrefix)
if len(p.stack) < 1 {
break
}
// BotAPI docs says:
// > Use nested <pre> and <code> tags, to define programming language for <pre> entity.
last := &p.stack[len(p.stack)-1]
if last.tag != pre {
break
}
if lang := e.attr; lang != "" {
// Set language parameter.
last.format = entity.Pre(lang)
}
case pre:
e.format = entity.Pre("")
if len(p.stack) < 1 {
break
}
last := &p.stack[len(p.stack)-1]
if last.tag != code {
break
}
if lang := last.attr; lang != "" {
// Set language parameter.
e.format = entity.Pre(lang)
}
case span:
if p.attr["class"] == "tg-spoiler" {
e.format = entity.Spoiler()
}
case tgSpoiler:
e.format = entity.Spoiler()
}
p.stack.push(e)
return nil
}
func (p *htmlParser) endTag(checkName bool) error {
tn, _ := p.tokenizer.TagName()
s, ok := p.stack.pop()
switch {
case !ok:
return errors.Errorf("unexpected end tag %q", tn)
case checkName && s.tag != string(tn):
return errors.Errorf("expected tag %q, got %q", s.tag, tn)
}
// Compute UTF-16 length of entity.
length := s.token.UTF16Length(p.builder)
switch s.tag {
case "a":
// TDLib tries to parse link from <a> body, so we should too.
if s.attr == "" {
msg := s.token.Text(p.builder)
if f, err := getURLFormatter(msg, p.opts.UserResolver); err == nil {
s.format = f
}
}
case "code":
l, ok := p.builder.LastEntity()
if !ok {
break
}
last, ok := l.(*tg.MessageEntityPre)
if !ok {
break
}
// Do not add Code entity, if last entity is Pre with same offset.
if last.GetOffset() == s.token.UTF16Offset() && last.GetLength() == length {
return nil
}
}
// Do not add empty entities.
if length == 0 || s.format == nil {
return nil
}
s.token.Apply(p.builder, s.format)
return nil
}
func (p *htmlParser) parse() error {
for {
tt := p.tokenizer.Next()
switch tt {
case html.ErrorToken:
if err := p.tokenizer.Err(); !errors.Is(err, io.EOF) {
return err
}
return nil
case html.TextToken:
var text []byte
if p.opts.DisableTelegramEscape {
text = p.tokenizer.Text()
} else {
text = telegramUnescape(p.tokenizer.Raw())
}
_, _ = p.builder.Write(text)
case html.StartTagToken:
if err := p.startTag(); err != nil {
return err
}
case html.EndTagToken:
if err := p.endTag(true); err != nil {
return err
}
case html.CommentToken:
// html.Tokenizer returns comment token for empty closing tags.
raw := p.tokenizer.Raw()
if len(raw) >= 3 && string(raw[:2]) == "</" && raw[len(raw)-1] == '>' {
if err := p.endTag(false); err != nil {
return err
}
}
}
}
}
// HTML parses given input from reader and adds parsed entities to given builder.
// Notice that this parser ignores unsupported tags.
//
// Parameter userResolver is used to resolve user by ID during formatting. May be nil.
// If userResolver is nil, formatter will create tg.InputUser using only ID.
// Notice that it's okay for bots, but not for users.
//
// See https://core.telegram.org/bots/api#html-style.
func HTML(r io.Reader, b *entity.Builder, opts Options) error {
opts.setDefaults()
p := htmlParser{
tokenizer: html.NewTokenizer(r),
builder: b,
attr: map[string]string{},
opts: opts,
}
if err := p.parse(); err != nil {
return errors.Wrap(err, "parse")
}
b.ShrinkPreCode()
return nil
}