-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
text_utl.go
89 lines (75 loc) · 1.76 KB
/
text_utl.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
package html
import (
"net"
"net/url"
"strconv"
"strings"
"unicode/utf8"
"github.com/go-faster/errors"
"github.com/gotd/td/internal/ascii"
"github.com/gotd/td/telegram/message/entity"
)
func isIPv6(str string) bool {
ip := net.ParseIP(str)
return strings.Contains(str, ":") && ip != nil
}
func validateHostname(u *url.URL) error {
// TODO(tdakkota): make sure that it is correct
ipv6 := isIPv6(u.Host)
if !strings.ContainsRune(u.Host, '.') && ipv6 {
return errors.New("wrong HTTP URL")
}
if ipv6 {
return nil
}
allowedSymbol := func(c rune) bool {
return ascii.IsLatinLetter(c) ||
ascii.IsDigit(c) ||
(c >= '&' && c <= '.') ||
c == '_' ||
c == '!' ||
c == '$' ||
c == '~' ||
c == ';' ||
c == '=' ||
c > utf8.RuneSelf
}
for _, c := range u.Host {
if !allowedSymbol(c) {
return errors.Errorf("disallowed character %c in URL host", c)
}
}
return nil
}
func getURLFormatter(rawURL string, resolver entity.UserResolver) (entity.Formatter, error) {
const defaultProtocol = "http"
if rawURL == "" {
return nil, errors.New("empty URL")
}
// FIXME(tdakkota): move normalization to deeplink package when it's done?
u, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
if u.Scheme == "tg" && u.Host == "user" {
id, err := strconv.ParseInt(u.Query().Get("id"), 10, 64)
if err != nil {
return nil, errors.Wrapf(err, "invalid user ID %q", id)
}
user, err := resolver(id)
if err != nil {
return nil, errors.Wrapf(err, "can't resolve user %q", id)
}
return entity.MentionName(user), nil
}
if u.Scheme == "" {
u.Scheme = defaultProtocol
u.Host = u.Path
u.Path = "/"
rawURL = u.String()
}
if err := validateHostname(u); err != nil {
return nil, err
}
return entity.TextURL(rawURL), nil
}