2022-09-01 17:57:59 +00:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/xml"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
|
2022-11-27 00:23:47 +00:00
|
|
|
ihttp "git.ptzo.gdn/feditools/go-lib/http"
|
2022-09-01 17:57:59 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// HostMetaWebFingerTemplateRel matches a webfinger link relationship.
|
|
|
|
const HostMetaWebFingerTemplateRel = "lrdd"
|
|
|
|
|
|
|
|
type HostMeta struct {
|
|
|
|
XMLNS string `xml:"xmlns,attr"`
|
|
|
|
Links []Link `xml:"Link"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HostMeta) WebFingerURI() WebFingerURI {
|
|
|
|
for _, link := range h.Links {
|
|
|
|
if link.Rel == HostMetaWebFingerTemplateRel {
|
|
|
|
return WebFingerURI(link.Template)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
func FetchHostMeta(ctx context.Context, t *http.Client, domain string, config ...bool) (*HostMeta, error) {
|
|
|
|
hostMetaURI := &url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: domain,
|
|
|
|
Path: "/.well-known/host-meta",
|
|
|
|
}
|
|
|
|
if len(config) > 0 && !config[0] {
|
|
|
|
hostMetaURI.Scheme = "http"
|
|
|
|
}
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, hostMetaURI.String(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, NewErrorf("req: %s", err.Error())
|
|
|
|
}
|
|
|
|
req.Header.Add("Accept", ihttp.MimeAppXML.String())
|
|
|
|
|
|
|
|
// do request
|
|
|
|
resp, err := t.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, NewErrorf("get: %s", err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
hostMeta := new(HostMeta)
|
|
|
|
if err := xml.NewDecoder(resp.Body).Decode(&hostMeta); err != nil {
|
|
|
|
return nil, NewErrorf("decode: %s", err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
return hostMeta, nil
|
|
|
|
}
|