This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
body.go
361 lines (327 loc) · 7.43 KB
/
body.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
package templates
import (
"bytes"
"fmt"
"html"
"regexp"
"strconv"
"github.com/bakape/meguca/common"
"github.com/bakape/meguca/config"
)
// Embeddable URL types
const (
youTube = iota
soundCloud
vimeo
)
var (
commandRegexp = regexp.MustCompile(`^#(flip|\d*d\d+|8ball|pyu|pcount)$`)
diceRegexp = regexp.MustCompile(`^(\d*)d(\d+)$`)
linkRegexp = regexp.MustCompile(`^>>(>*)(\d+)$`)
referenceRegexp = regexp.MustCompile(`^>>>(>*)\/(\w+)\/$`)
urlRegexp = regexp.MustCompile(
`^(?:magnet:\?|https?:\/\/)[-a-zA-Z0-9@:%_\+\.~#\?&\/=]+$`,
)
providers = map[int]string{
youTube: "Youtube",
soundCloud: "SoundCloud",
vimeo: "Vimeo",
}
embedPatterns = [...]struct {
typ int
patt *regexp.Regexp
}{
{
youTube,
regexp.MustCompile(`https?:\/\/(?:[^\.]+\.)?youtube\.com\/watch\/?\?(?:.+&)?v=([^&]+)`),
},
{
youTube,
regexp.MustCompile(`https?:\/\/(?:[^\.]+\.)?(?:youtu\.be|youtube\.com\/embed)\/([a-zA-Z0-9_-]+)`),
},
{
soundCloud,
regexp.MustCompile(`https?:\/\/soundcloud.com\/.*`),
},
{
vimeo,
regexp.MustCompile(`https?:\/\/(?:www\.)?vimeo\.com\/.+`),
},
}
)
type bodyContext struct {
state struct { // Body parser state
spoiler, quote bool
iDice int
}
common.Post
OP uint64
htmlWriter
}
// Render the text body of a post
func renderBody(p common.Post, op uint64) string {
c := bodyContext{
Post: p,
OP: op,
}
lines := bytes.Split([]byte(c.Body), []byte{'\n'})
if c.Editing {
for i := 0; i < len(lines)-1; i++ {
c.parseTerminatedLine(lines[i])
}
c.parseOpenLine(lines[len(lines)-1])
} else {
for _, line := range lines {
c.parseTerminatedLine(line)
}
}
return c.String()
}
// Parse a line that is no longer being edited
func (c *bodyContext) parseTerminatedLine(line []byte) {
// For hiding redundant newlines using CSS
if len(line) == 0 {
c.WriteString("<br>")
return
}
c.initLine(line[0])
if line[0] == '#' {
if m := commandRegexp.FindSubmatch(line); m != nil {
c.parseCommands(string(m[1]))
c.terminateTags(true)
return
}
}
c.parseSpoilers(line, (*c).parseFragment)
c.terminateTags(true)
}
// Open a new line container and check for quotes
func (c *bodyContext) initLine(first byte) {
c.state.spoiler = false
c.state.quote = false
c.WriteString("<span>")
if first == '>' {
c.WriteString("<em>")
c.state.quote = true
}
}
// Injects spoiler tags and calls fn on the remaining parts
func (c *bodyContext) parseSpoilers(frag []byte, fn func([]byte)) {
for {
i := bytes.Index(frag, []byte{'*', '*'})
if i != -1 {
fn(frag[:i])
if c.state.spoiler {
c.WriteString("</del>")
} else {
c.WriteString("<del>")
}
c.state.spoiler = !c.state.spoiler
frag = frag[i+2:]
} else {
fn(frag)
break
}
}
}
// Parse a line fragment
func (c *bodyContext) parseFragment(frag []byte) {
for i, word := range bytes.Split(frag, []byte{' '}) {
if i != 0 {
c.WriteByte(' ')
}
if len(word) == 0 {
continue
}
if word[0] == '>' {
if m := linkRegexp.FindSubmatch(word); m != nil {
// Post links
c.parsePostLink(m)
continue
} else if m := referenceRegexp.FindSubmatch(word); m != nil {
// Internal and custom reference URLs
c.parseReference(m)
continue
}
} else {
// Generic HTTP(S) URLs and magnet links
match := false
// Checking the first byte is much cheaper than a function call. Do
// that first, as most cases won't match.
switch word[0] {
case 'h':
match = bytes.HasPrefix(word, []byte("http"))
case 'm':
match = bytes.HasPrefix(word, []byte("magnet:?"))
}
if match {
c.parseURL(word)
continue
}
}
c.escape(word)
}
}
// Parse a potential link to a post
func (c *bodyContext) parsePostLink(m [][]byte) {
if c.Links == nil {
c.Write(m[0])
return
}
id, _ := strconv.ParseUint(string(m[2]), 10, 64)
verified, ok := c.Links[id]
if !ok {
c.Write(m[0])
return
}
if len(m[1]) != 0 { // Write extra quotes
c.Write(m[1])
}
html := renderPostLink(
id,
verified.OP,
verified.Board,
verified.OP != c.OP,
)
c.WriteString(string(html))
}
// Parse internal or customly set reference URL
func (c *bodyContext) parseReference(m [][]byte) {
var (
m2 = string(m[2])
href string
)
if config.IsBoard(m2) {
href = fmt.Sprintf("/%s/", m2)
} else if href = config.Get().Links[m2]; href != "" {
} else {
c.Write(m[0])
return
}
if len(m[1]) != 0 {
c.Write(m[1])
}
c.newTabLink(href, fmt.Sprintf(">>>/%s/", string(m[2])))
}
// Format and anchor link that opens in a new tab
func (c *bodyContext) newTabLink(href, text string) {
fmt.Fprintf(
c,
`<a href="%s" target="_blank">%s</a>`,
html.EscapeString(href),
html.EscapeString(text),
)
}
// Parse generic URLs and magnet links
func (c *bodyContext) parseURL(bit []byte) {
s := string(bit)
switch {
case !urlRegexp.Match(bit):
c.escape(bit)
case c.parseEmbeds(bit):
case bit[0] == 'm': // Don't open a new tab for magnet links
s = html.EscapeString(s)
fmt.Fprintf(c, `<a href="%s">%s</a>`, s, s)
default:
c.newTabLink(s, s)
}
}
// Parse select embeddable URLs. Returns, if any found.
func (c *bodyContext) parseEmbeds(b []byte) bool {
for _, t := range embedPatterns {
if !t.patt.Match(b) {
continue
}
fmt.Fprintf(
c,
`<em><a class="embed" target="_blank" data-type="%d" href="%s">[%s] ???</a></em>`,
t.typ,
html.EscapeString(string(b)),
providers[t.typ],
)
return true
}
return false
}
// Write an HTML-escaped string to buffer
func (c *bodyContext) escape(bit []byte) {
c.WriteString(html.EscapeString(string(bit)))
}
// Parse a hash command
func (c *bodyContext) parseCommands(bit string) {
// Guard against invalid dice rolls
invalid := c.Commands == nil ||
c.state.iDice > len(c.Commands)-1 ||
c.Commands[c.state.iDice].Val == nil
if invalid {
c.writeInvalidCommand(bit)
return
}
// TODO: Sycnwatch
inner := new(bytes.Buffer)
switch bit {
case "flip", "8ball", "pyu", "pcount":
fmt.Fprint(inner, c.Commands[c.state.iDice].Val)
c.state.iDice++
default:
// Validate dice
m := diceRegexp.FindStringSubmatch(bit)
if m[1] != "" {
if rolls, err := strconv.Atoi(m[1]); err != nil || rolls > 10 {
c.writeInvalidCommand(bit)
return
}
}
if sides, err := strconv.Atoi(m[2]); err != nil || sides > 100 {
c.writeInvalidCommand(bit)
return
}
// Cast []interface to []uint16
uncast := c.Commands[c.state.iDice].Val.([]interface{})
rolls := make([]uint16, len(uncast))
for i := range rolls {
rolls[i] = uint16(uncast[i].(float64))
}
c.state.iDice++
var sum uint
for i, roll := range rolls {
if i != 0 {
inner.WriteString(" + ")
}
sum += uint(roll)
inner.WriteString(strconv.FormatUint(uint64(roll), 10))
}
if len(rolls) > 1 {
fmt.Fprintf(inner, " = %d", sum)
}
}
fmt.Fprintf(c, "<strong>#%s (%s)</strong>", bit, inner.String())
}
// If command validation failed, simply write the string
func (c *bodyContext) writeInvalidCommand(bit string) {
c.WriteByte('#')
c.WriteString(bit)
}
// Close any open HTML tags
func (c *bodyContext) terminateTags(newLine bool) {
if c.state.spoiler {
c.WriteString("</del>")
}
if c.state.quote {
c.WriteString("</em>")
}
if newLine {
c.WriteString("<br>")
}
c.WriteString("</span>")
}
// Parse a line that is still being edited
func (c *bodyContext) parseOpenLine(line []byte) {
if len(line) == 0 {
c.WriteString("<span></span>")
return
}
c.initLine(line[0])
c.parseSpoilers(line, (*c).escape)
c.terminateTags(false)
}