aboutsummaryrefslogtreecommitdiff
path: root/html.go
blob: 52460eeb53fdfe47ddb5825080f33d4ba84c6cdc (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
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
	for i < len(content) && content[i] != '>' && (i+1 == len(content) || string(content[i:i+2]) != "/>") {
		curr := content[i]
		if !sep {
			switch curr {
			case '=':
				sep = true
			case ' ':
				sep = false
				if key.Len() > 0 {
					res[key.String()] = ""
				}
				key.Reset()
			default:
				key.WriteRune(curr)
			}
		} else {
			if value.Len() == 0 && curr == '"' {
				quote = true
			} else if (curr == '"' && quote) || curr == ' ' && !quote {
				quote = false
				sep = false
				res[key.String()] = value.String()
				key.Reset()
				value.Reset()
			} else {
				value.WriteRune(curr)
			}
		}
		i++
	}
	if key.Len() > 0 {
		res[key.String()] = value.String()
	}
	return res
}