aboutsummaryrefslogtreecommitdiff
path: root/html.go
blob: 463e1f3b9e18b8e41e2a33c47506b3bc369bb3df (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package human

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/url"
	"strings"
)

var ErrUnsupportedContentType = errors.New("unsupported content type")

// GetHumanFromHTML returns the [Human] contained in the [http.Response].
//
// If Content-Type is unsupported, it returns [ErrUnsupportedContentType].
// Currently, only `text/html` is supported.
//
// [http.Client] is used to retrieve the `human.json` linked in the [http.Response.Body].
func GetHumanFromHTML(ctx context.Context, client *http.Client, resp *http.Response) (*Human, error) {
	if !strings.Contains(resp.Header.Get("Content-Type"), "text/html") {
		return nil, ErrUnsupportedContentType
	}
	b, err := io.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return nil, err
	}
	url, err := GetURLFromHTML(b, resp.Request.URL)
	if err != nil {
		return nil, err
	}
	if url == nil {
		return nil, nil
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url.String(), nil)
	if err != nil {
		return nil, err
	}
	resp, err = client.Do(req)
	if err != nil {
		return nil, err
	}
	b, err = io.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return nil, err
	}
	var h Human
	return &h, json.Unmarshal(b, &h)
}

// GetURLFromHTML returns the [url.URL] extracted from the raw HTML.
// Base is the URL containing the HTML.
//
// Returns nil if nothing is found.
func GetURLFromHTML(b []byte, base *url.URL) (*url.URL, error) {
	content := string(b)
	runed := []rune(content)
	i := strings.Index(content, `<link `)
	for i >= 0 && i+6 < len(runed) {
		content = string(runed[i+6:])
		runed = []rune(content)
		args := parseArgs(content)
		if args["rel"] == "human-json" {
			href, ok := args["href"]
			if ok {
				u, err := url.Parse(href)
				if err != nil {
					return nil, err
				}
				if u.Host != "" {
					return u, nil
				}
				path := u.Path
				*u = *base
				if strings.HasPrefix(path, "/") {
					u.Path = path
				} else {
					u = u.JoinPath(path)
				}
				return u, nil
			}
		}
		i = strings.Index(content, `<link `)
	}
	return nil, nil
}

func parseArgs(base string) map[string]string {
	content := []rune(base)
	i := 0
	res := map[string]string{}

	var sep bool
	var key strings.Builder
	var value strings.Builder
	var quote bool
	next := true
	finish := func() {
		quote = false
		sep = false
		if key.Len() > 0 {
			res[key.String()] = value.String()
		}
		key.Reset()
		value.Reset()
	}
	for i < len(content) && next {
		curr := content[i]
		if !sep {
			switch curr {
			case '=':
				sep = true
			case '/':
				if i+1 >= len(content) || string(content[i:i+2]) != "/>" {
					key.WriteRune(curr)
					i++
					continue
				}
				fallthrough
			case '>':
				next = false
				fallthrough
			case ' ':
				finish()
			default:
				key.WriteRune(curr)
			}
		} else {
			switch curr {
			case '"':
				if value.Len() == 0 {
					quote = true
					i++
					continue
				} else if quote {
					finish()
					i++
					continue
				}
			case '/':
				if i+1 >= len(content) || string(content[i:i+2]) != "/>" {
					value.WriteRune(curr)
					i++
					continue
				}
				fallthrough
			case '>':
				if !quote {
					next = false
				}
				fallthrough
			case ' ':
				if !quote {
					finish()
					i++
					continue
				}
				fallthrough
			default:
			}
			value.WriteRune(curr)
		}
		i++
	}
	if key.Len() > 0 {
		res[key.String()] = value.String()
	}
	return res
}