-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.go
78 lines (64 loc) · 1.86 KB
/
telegram.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
package slinky
import (
"fmt"
"net/url"
"strings"
)
// Telegram Account: ^https://t\.me/[A-Za-z0-9_]{5,32}$
// Telegram Account with Phone Number: ^https://t\.me/+[0-9]{1,15}$
func decodeTelegramURL(url *url.URL) (*URL, error) {
if url.Scheme == "http" {
url.Scheme = "https"
}
if url.Scheme != "https" {
return nil, fmt.Errorf("%w: invalid Telegram scheme", ErrInvalidURL)
}
if url.Host != "t.me" {
return nil, fmt.Errorf("%w: invalid Telegram host", ErrInvalidURL)
}
path := strings.TrimSuffix(url.Path, "/")
switch {
case strings.HasPrefix(path, "/+"):
if len(path) < 1 || path[0] != '/' {
return nil, fmt.Errorf("%w: invalid Telegram path", ErrInvalidURL)
}
phoneNumber := strings.TrimPrefix(path, "/")
if strings.ContainsFunc(phoneNumber, isNotTelegramPhoneNumberRune) {
return nil, fmt.Errorf("%w: invalid Telegram phone number", ErrInvalidURL)
}
return &URL{
Service: Telegram,
Type: "Account",
ID: phoneNumber,
Data: map[string]string{
"phoneNumber": phoneNumber,
},
URL: url,
}, nil
default:
if len(path) < 1 || path[0] != '/' {
return nil, fmt.Errorf("%w: invalid Telegram path", ErrInvalidURL)
}
username := strings.TrimPrefix(path, "/")
if strings.ContainsFunc(username, isNotTelegramHandleRune) {
return nil, fmt.Errorf("%w: invalid Telegram username", ErrInvalidURL)
}
return &URL{
Service: Telegram,
Type: "Account",
ID: username,
Data: map[string]string{
"username": username,
},
URL: url,
}, nil
}
}
const telegramHandleAlpha = "ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmonpqrstuvwxyz0123456789_"
func isNotTelegramHandleRune(r rune) bool {
return !strings.ContainsRune(telegramHandleAlpha, r)
}
const telegramPhoneNumberAlpha = "0123456789+"
func isNotTelegramPhoneNumberRune(r rune) bool {
return !strings.ContainsRune(telegramPhoneNumberAlpha, r)
}