~handlerug/handlebot

ref: 7a899986d3a7d250418ed425c03a9e5391820979 handlebot/urlpreview/urlpreview.go -rw-r--r-- 1.1 KiB
7a899986Umar Getagazov Set user agent a month ago
                                                                                
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
package urlpreview

import (
	"context"
	"net"
	"net/http"
	"net/url"

	"git.sr.ht/~adnano/go-gemini"
)

var geminiDefaultClient = &gemini.Client{}

type Previewer struct {
	HTTPClient   *http.Client
	GeminiClient *gemini.Client
}

func (p *Previewer) Preview(ctx context.Context, u *url.URL) (string, error) {
	hostname := u.Hostname()
	if hostname == "localhost" {
		return "", nil
	}
	if ip := net.ParseIP(hostname); ip != nil && ip.IsLoopback() {
		return "", nil
	}

	var (
		res      string
		err      error
		handlers []func(context.Context, *url.URL) (string, error)
	)

	switch u.Scheme {
	case "http", "https":
		handlers = append(handlers, p.youtube, p.wolframalpha, p.jisho,
			p.generic)
	case "gemini":
		handlers = append(handlers, p.gemini)
	}
	for _, h := range handlers {
		res, err = h(ctx, u)
		if res != "" || err != nil {
			break
		}
	}
	return res, err
}

func (p *Previewer) httpClient() *http.Client {
	if p.HTTPClient != nil {
		return p.HTTPClient
	}
	return http.DefaultClient
}

func (p *Previewer) geminiClient() *gemini.Client {
	if p.GeminiClient != nil {
		return p.GeminiClient
	}
	return geminiDefaultClient
}