-
Notifications
You must be signed in to change notification settings - Fork 7
/
twitter.go
61 lines (52 loc) · 1.43 KB
/
twitter.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
package url
import (
"errors"
"fmt"
"html"
"net/url"
"regexp"
"strings"
)
var (
twitterRE = regexp.MustCompile(`^https?://twitter\.com/.*?/status/\d+(/photo/\d+)?(#|$)`)
tweetRE = regexp.MustCompile(`(?s)<meta property="og:description" content="([^"]*)"`)
tweetImageRE = regexp.MustCompile(`<meta property="og:image" content="([^"]*)"`)
)
// Twitter frontend is not scrapable easily and they require using their API.
// Instead, use the alternative Twitter front-end https://github.com/zedeus/nitter
const nitterDomain = "nitter.net"
func handleTwitter(target string) (string, error) {
if !twitterRE.MatchString(target) {
return "", errSkip
}
u, err := url.Parse(target)
if err != nil {
return "", err
}
u.Host = nitterDomain
body, err := get(u.String())
if err != nil {
return "", err
}
text := tweetRE.FindStringSubmatch(body)
if text == nil {
return "", errors.New("url: twitter: cannot parse tweet")
}
s := text[1]
image := tweetImageRE.FindStringSubmatch(body)
if image != nil {
uri, err := url.QueryUnescape(image[1])
if err != nil {
return "", err
}
s = fmt.Sprintf("%v %v", s, uri)
}
s = stripTags(s)
// unescape would replace by \u00a0 but we prefer normal space \u0020
s = strings.ReplaceAll(s, " ", " ")
s = strings.ReplaceAll(s, "\n", " ")
s = html.UnescapeString(s)
s = trim(s)
s = strings.ReplaceAll(s, "http://"+nitterDomain, "https://"+nitterDomain)
return s, nil
}