-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
parse.go
68 lines (59 loc) · 1.37 KB
/
parse.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
package encoding
import (
"encoding/hex"
"html"
"regexp"
"strings"
)
// BreakString breaks words and lines.
func BreakString(msg string, wordLen int, lineLen int) string {
words := []string{}
lines := []string{}
for i := 0; i < len(msg); i += wordLen {
end := i + wordLen
if end > len(msg) {
end = len(msg)
}
word := msg[i:end]
if l := len(words); l != 0 && l%lineLen == 0 {
lines = append(lines, strings.Join(words, " "))
words = []string{}
}
words = append(words, word)
}
lines = append(lines, strings.Join(words, " "))
return strings.Join(lines, "\n")
}
func stripTags(body string) string {
re := regexp.MustCompile(`<\/?[^>]+(>|$)`)
return re.ReplaceAllString(body, "")
}
// FindSaltpack finds saltpack message in a string.
func FindSaltpack(msg string, isHTML bool) (string, string) {
if isHTML {
msg = html.UnescapeString(msg)
}
re := regexp.MustCompile(`(?s).*BEGIN (.*)MESSAGE\.(.*)END .*MESSAGE.*`)
s := re.FindStringSubmatch(msg)
brand, out := "", ""
if len(s) >= 2 {
brand = strings.TrimSpace(TrimSaltpack(s[1], true))
}
if len(s) >= 3 {
out = s[2]
out = strings.ReplaceAll(out, "\\n", "")
}
if isHTML {
out = stripTags(out)
}
out = TrimSaltpack(out, false)
return out, brand
}
// MustHex decodes hex string or panics.
func MustHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}