refactor!: working WD-4 user discovery

This commit is contained in:
DevMiner 2024-08-20 22:43:26 +02:00
parent cf0053312d
commit 61891d891a
91 changed files with 12768 additions and 5562 deletions

View file

@ -1,13 +1,19 @@
package webfinger
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/lysand-org/versia-go/pkg/protoretry"
"net/http"
"net/url"
"strings"
)
var (
ErrInvalidSyntax = errors.New("must follow the format \"acct:<ID|Username>@<DOMAIN>\"")
ErrUserNotFound = errors.New("user could not be found")
)
func ParseResource(res string) (*UserID, error) {
@ -48,7 +54,7 @@ type Response struct {
type Link struct {
Relation string `json:"rel"`
Type any `json:"type"`
Type string `json:"type"`
Link string `json:"href"`
}
@ -70,3 +76,47 @@ func (u User) WebFingerResource() Response {
},
}
}
func Discover(c *protoretry.Client, ctx context.Context, baseURI, username string) (*User, error) {
u := &User{UserID: UserID{ID: username, Domain: baseURI}}
body, resp, err := c.GET(ctx, &url.URL{
Scheme: "https",
Host: u.UserID.Domain,
Path: "/.well-known/webfinger",
RawQuery: url.Values{"resource": []string{"acct:" + u.String()}}.Encode(),
})
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusNotFound {
return nil, ErrUserNotFound
} else if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var respBody Response
if err := json.Unmarshal(body, &respBody); err != nil {
return nil, err
}
if respBody.Error != nil {
return nil, fmt.Errorf("webfinger error: %s", *respBody.Error)
}
for _, link := range respBody.Links {
if link.Relation == "self" {
if u.URI, err = url.Parse(link.Link); err != nil {
return nil, err
}
} else if link.Relation == "avatar" {
u.AvatarMIMEType = link.Type
if u.Avatar, err = url.Parse(link.Link); err != nil {
return nil, err
}
}
}
return u, nil
}