Code Refactor
All checks were successful
/ build (push) Successful in 2m43s

This commit is contained in:
Astra 2026-03-11 13:58:38 +00:00
parent 85fc508aa3
commit c9cc325ef7
3 changed files with 77 additions and 51 deletions

View file

@ -10,6 +10,17 @@ import (
"github.com/dghubble/sling" "github.com/dghubble/sling"
) )
const (
// URI parsing indices for at:// URIs split by "/"
uriRepoIndex = 2
uriCollectionIndex = 3
uriRkeyIndex = 4
// Custom collections
PostCollection = "blue.zio.bsky2tg.post"
AliasCollection = "blue.zio.bsky2tg.alias"
)
type BlueskyConfig struct { type BlueskyConfig struct {
PDSURL string `json:"pds-url"` PDSURL string `json:"pds-url"`
Repo string `json:"repo"` Repo string `json:"repo"`
@ -76,6 +87,7 @@ type Bluesky struct {
HttpClient *http.Client HttpClient *http.Client
Logger *log.Logger Logger *log.Logger
sling *sling.Sling sling *sling.Sling
publicSling *sling.Sling
} }
func (bluesky *Bluesky) CreateSession(cfg *BlueskyConfig) error { func (bluesky *Bluesky) CreateSession(cfg *BlueskyConfig) error {
@ -88,14 +100,14 @@ func (bluesky *Bluesky) CreateSession(cfg *BlueskyConfig) error {
} }
resp := new(BSkySessionResponse) resp := new(BSkySessionResponse)
bluesky.sling.New().Post("/xrpc/com.atproto.server.createSession").BodyJSON(body).ReceiveSuccess(resp) bluesky.sling.New().Client(bluesky.HttpClient).
Post("/xrpc/com.atproto.server.createSession").BodyJSON(body).ReceiveSuccess(resp)
if resp.AccessJWT != "" { if resp.AccessJWT != "" {
cfg.AccessJWT = resp.AccessJWT cfg.AccessJWT = resp.AccessJWT
cfg.RefreshJWT = resp.RefreshJWT cfg.RefreshJWT = resp.RefreshJWT
return nil return nil
} }
bluesky.sling.New().Set("Authorization", fmt.Sprintf("Bearer %s", bluesky.Cfg.AccessJWT))
return errors.New("unable to authenticate, check handle/password") return errors.New("unable to authenticate, check handle/password")
} }
@ -161,7 +173,7 @@ func (bluesky *Bluesky) CommitTelegramResponse(data *TelegramRecord, rkey string
Record TelegramRecord `json:"record"` Record TelegramRecord `json:"record"`
}{ }{
Repo: bluesky.Cfg.DID, Repo: bluesky.Cfg.DID,
Collection: "blue.zio.bsky2tg.post", Collection: PostCollection,
RKey: rkey, RKey: rkey,
Record: TelegramRecord{ Record: TelegramRecord{
ChannelID: data.ChannelID, ChannelID: data.ChannelID,
@ -193,7 +205,7 @@ func (bluesky *Bluesky) GetTelegramData(rkey string) (*TelegramRecord, string) {
RKey string `url:"rkey"` RKey string `url:"rkey"`
}{ }{
Repo: bluesky.Cfg.DID, Repo: bluesky.Cfg.DID,
Collection: "blue.zio.bsky2tg.post", Collection: PostCollection,
RKey: rkey, RKey: rkey,
} }
@ -215,9 +227,9 @@ func (bluesky *Bluesky) GetPost(uri string) *Post {
Repo string `url:"repo"` Repo string `url:"repo"`
Collection string `url:"collection"` Collection string `url:"collection"`
}{ }{
RKey: args[4], RKey: args[uriRkeyIndex],
Repo: args[2], Repo: args[uriRepoIndex],
Collection: args[3], Collection: args[uriCollectionIndex],
} }
bluesky.sling.New().Get("/xrpc/com.atproto.repo.getRecord").QueryStruct(params).ReceiveSuccess(&post) bluesky.sling.New().Get("/xrpc/com.atproto.repo.getRecord").QueryStruct(params).ReceiveSuccess(&post)
@ -249,7 +261,7 @@ func (bluesky *Bluesky) FetchAliases() []Records {
Collection string `url:"collection"` Collection string `url:"collection"`
}{ }{
Repo: bluesky.Cfg.DID, Repo: bluesky.Cfg.DID,
Collection: "blue.zio.bsky2tg.alias", Collection: AliasCollection,
} }
bluesky.sling.New().Get("/xrpc/com.atproto.repo.listRecords").QueryStruct(&params).Receive(resp, resp) bluesky.sling.New().Get("/xrpc/com.atproto.repo.listRecords").QueryStruct(&params).Receive(resp, resp)

View file

@ -13,9 +13,14 @@ import (
"github.com/dghubble/sling" "github.com/dghubble/sling"
) )
const (
didWebPrefixLen = len("did:web:")
atPrefixLen = len("at://")
httpClientTimeout = 3 * time.Second
)
type BSky struct { type BSky struct {
Bluesky *Bluesky Bluesky *Bluesky
DID string
} }
func NewBSky() *BSky { func NewBSky() *BSky {
@ -23,13 +28,13 @@ func NewBSky() *BSky {
Bluesky: &Bluesky{ Bluesky: &Bluesky{
Cfg: &BlueskyConfig{}, Cfg: &BlueskyConfig{},
HttpClient: &http.Client{}, HttpClient: &http.Client{},
sling: sling.New().Client(&http.Client{Timeout: time.Second * 3}), sling: sling.New().Client(&http.Client{Timeout: httpClientTimeout}),
publicSling: sling.New().Base("https://public.api.bsky.app/").Client(&http.Client{Timeout: httpClientTimeout}),
}, },
} }
} }
func (b *BSky) ResolveHandle(handle string) (string, error) { func (b *BSky) ResolveHandle(handle string) (string, error) {
httpClient := &http.Client{Timeout: 3 * time.Second}
resp := new(BSkySessionResponse) resp := new(BSkySessionResponse)
errResp := &struct { errResp := &struct {
Message string `json:"message"` Message string `json:"message"`
@ -40,8 +45,7 @@ func (b *BSky) ResolveHandle(handle string) (string, error) {
}{ }{
Handle: handle, Handle: handle,
} }
sling.New().Base("https://public.api.bsky.app/").Client(httpClient). b.Bluesky.publicSling.New().Get("/xrpc/com.atproto.identity.resolveHandle").QueryStruct(params).
Get("/xrpc/com.atproto.identity.resolveHandle").QueryStruct(params).
Receive(resp, errResp) Receive(resp, errResp)
if errResp.Error != "" { if errResp.Error != "" {
@ -51,54 +55,62 @@ func (b *BSky) ResolveHandle(handle string) (string, error) {
return resp.DID, nil return resp.DID, nil
} }
func parseDIDURL(did string) (*url.URL, error) {
if strings.HasPrefix(did, "did:web:") {
return url.Parse("https://" + did[didWebPrefixLen:] + "/.well-known/did.json")
} else if strings.HasPrefix(did, "did:plc:") {
return url.Parse("https://plc.directory/" + did)
}
return nil, errors.New("DID is not supported")
}
func (b *BSky) getPDS() error { func (b *BSky) getPDS() error {
did, _ := b.ResolveHandle(b.Bluesky.Cfg.Handle) did, _ := b.ResolveHandle(b.Bluesky.Cfg.Handle)
var didURL url.URL didURL, err := parseDIDURL(did)
if strings.HasPrefix(did, "did:web:") { if err != nil {
didURL.Host = "https://" + did[8:] return err
didURL.Path = "/.well-known/did.json"
} else if strings.HasPrefix(did, "did:plc:") {
didURL.Host = "https://plc.directory"
didURL.Path = "/" + did
} else {
return errors.New("DID is not supported")
} }
didResp := new(DIDResponse) didResp := new(DIDResponse)
sling.New().Base(didURL.Host).Get(didURL.Path).ReceiveSuccess(didResp) baseURL := fmt.Sprintf("%s://%s", didURL.Scheme, didURL.Host)
sling.New().Base(baseURL).Get(didURL.Path).ReceiveSuccess(didResp)
if didResp.ID == "" { if didResp.ID == "" {
return errors.New("unable to resolve DID") return errors.New("unable to resolve DID")
} }
b.Bluesky.Cfg.DID = didResp.ID b.Bluesky.Cfg.DID = didResp.ID
b.Bluesky.Cfg.PDSURL = didResp.Service[0].ServiceEndpoint if len(didResp.Service) == 0 {
b.Bluesky.sling.Base(didResp.Service[0].ServiceEndpoint) return errors.New("DID response has no services")
}
pdsURL := didResp.Service[0].ServiceEndpoint
if pdsURL == "" {
return errors.New("service endpoint is empty")
}
b.Bluesky.Cfg.PDSURL = pdsURL
b.Bluesky.sling.Base(pdsURL)
return nil return nil
} }
func (b *BSky) GetHandleFromDID(did string) (handle string, err error) { func (b *BSky) GetHandleFromDID(did string) (handle string, err error) {
var didURL url.URL didURL, err := parseDIDURL(did)
if strings.HasPrefix(did, "did:web:") { if err != nil {
didURL.Host = "https://" + did[8:] return "", err
didURL.Path = "/.well-known/did.json"
} else if strings.HasPrefix(did, "did:plc:") {
didURL.Host = "https://plc.directory"
didURL.Path = "/" + did
} else {
return "", errors.New("DID is not supported")
} }
didResp := new(DIDResponse) didResp := new(DIDResponse)
sling.New().Base(didURL.Host).Get(didURL.Path).ReceiveSuccess(didResp) baseURL := fmt.Sprintf("%s://%s", didURL.Scheme, didURL.Host)
sling.New().Base(baseURL).Get(didURL.Path).ReceiveSuccess(didResp)
if didResp.ID == "" { if didResp.ID == "" {
return "", errors.New("unable to resolve DID") return "", errors.New("unable to resolve DID")
} }
return didResp.AlsoKnownAs[0][5:], nil return didResp.AlsoKnownAs[0][atPrefixLen:], nil
} }
func (b *BSky) GetPDS(handle string) string { func (b *BSky) GetPDS() string {
return b.Bluesky.Cfg.PDSURL return b.Bluesky.Cfg.PDSURL
} }
@ -118,7 +130,6 @@ func (b *BSky) Auth(authData []string) error {
b.Bluesky.Cfg.Cursor = auth.Cursor b.Bluesky.Cfg.Cursor = auth.Cursor
b.Bluesky.Cfg.AccessJWT = auth.AccessJWT b.Bluesky.Cfg.AccessJWT = auth.AccessJWT
b.Bluesky.Cfg.RefreshJWT = auth.RefreshJWT b.Bluesky.Cfg.RefreshJWT = auth.RefreshJWT
// b.RefreshSession()
b.Bluesky.CheckSessionValid() b.Bluesky.CheckSessionValid()
} }

17
main.go
View file

@ -97,7 +97,7 @@ func main() {
log.Printf("Found post %s in channel %d, deleting", s[2], tgpost.ChannelID) log.Printf("Found post %s in channel %d, deleting", s[2], tgpost.ChannelID)
m := tgbotapi.NewDeleteMessages(tgpost.ChannelID, tgpost.MessageID) m := tgbotapi.NewDeleteMessages(tgpost.ChannelID, tgpost.MessageID)
h.tg.Send(m) h.tg.Send(m)
h.bsky.Bluesky.DeleteRecord([]string{s[2], s[1], "blue.zio.bsky2tg.post"}) h.bsky.Bluesky.DeleteRecord([]string{s[2], s[1], bsky.PostCollection})
} else { } else {
log.Printf("Unable to find post %s on PDS", s[2]) log.Printf("Unable to find post %s on PDS", s[2])
} }
@ -179,7 +179,7 @@ func (h *handler) HandleEvent(ctx context.Context, event *models.Event) error {
if e == "" { if e == "" {
m := tgbotapi.NewDeleteMessages(r.ChannelID, r.MessageID) m := tgbotapi.NewDeleteMessages(r.ChannelID, r.MessageID)
h.tg.Send(m) h.tg.Send(m)
h.bsky.Bluesky.DeleteRecord([]string{event.Commit.RKey, event.Did, "blue.zio.bsky2tg.post"}) h.bsky.Bluesky.DeleteRecord([]string{event.Commit.RKey, event.Did, bsky.PostCollection})
} }
} }
@ -206,6 +206,9 @@ func (h *handler) ProcessPost(event *models.Event) error {
isEditedPost = true isEditedPost = true
} }
aliases := h.bsky.Bluesky.FetchAliases()
facets := ps.ProcessFacets(aliases)
var captionText string var captionText string
if ps.IsQuotePost() { if ps.IsQuotePost() {
ownHandle, handleErr := h.bsky.GetHandleFromDID(h.bsky.Bluesky.Cfg.DID) ownHandle, handleErr := h.bsky.GetHandleFromDID(h.bsky.Bluesky.Cfg.DID)
@ -216,7 +219,7 @@ func (h *handler) ProcessPost(event *models.Event) error {
handle, _ := h.bsky.GetHandleFromDID(strings.Split(ps.Embed.Record.Record.URI, "/")[2]) handle, _ := h.bsky.GetHandleFromDID(strings.Split(ps.Embed.Record.Record.URI, "/")[2])
captionText = fmt.Sprintf( captionText = fmt.Sprintf(
quotePostFormat, quotePostFormat,
ps.ProcessFacets(h.bsky.Bluesky.FetchAliases()), facets,
strings.Split(ps.Embed.Record.Record.URI, "/")[2], strings.Split(ps.Embed.Record.Record.URI, "/")[2],
strings.Split(ps.Embed.Record.Record.URI, "/")[4], strings.Split(ps.Embed.Record.Record.URI, "/")[4],
handle, handle,
@ -227,7 +230,7 @@ func (h *handler) ProcessPost(event *models.Event) error {
handle, _ := h.bsky.GetHandleFromDID(strings.Split(ps.Embed.Record.URI, "/")[2]) handle, _ := h.bsky.GetHandleFromDID(strings.Split(ps.Embed.Record.URI, "/")[2])
captionText = fmt.Sprintf( captionText = fmt.Sprintf(
quotePostFormat, quotePostFormat,
ps.ProcessFacets(h.bsky.Bluesky.FetchAliases()), facets,
strings.Split(ps.Embed.Record.URI, "/")[2], strings.Split(ps.Embed.Record.URI, "/")[2],
strings.Split(ps.Embed.Record.URI, "/")[4], strings.Split(ps.Embed.Record.URI, "/")[4],
handle, handle,
@ -242,8 +245,8 @@ func (h *handler) ProcessPost(event *models.Event) error {
if handleErr != nil { if handleErr != nil {
ownHandle = h.bsky.Bluesky.Cfg.Handle ownHandle = h.bsky.Bluesky.Cfg.Handle
} }
if ps.ProcessFacets(h.bsky.Bluesky.FetchAliases()) != "" { if facets != "" {
captionText = fmt.Sprintf(postFormat, ps.ProcessFacets(h.bsky.Bluesky.FetchAliases()), h.bsky.Bluesky.Cfg.DID, event.Commit.RKey, ownHandle) captionText = fmt.Sprintf(postFormat, facets, h.bsky.Bluesky.Cfg.DID, event.Commit.RKey, ownHandle)
} else { } else {
captionText = fmt.Sprintf("<a href=\"https://bsky.app/profile/%s/post/%s\">🦋 @%s</a>", h.bsky.Bluesky.Cfg.DID, event.Commit.RKey, ownHandle) captionText = fmt.Sprintf("<a href=\"https://bsky.app/profile/%s/post/%s\">🦋 @%s</a>", h.bsky.Bluesky.Cfg.DID, event.Commit.RKey, ownHandle)
} }
@ -325,7 +328,7 @@ func (h *handler) ProcessPost(event *models.Event) error {
} else { } else {
m := tgbotapi.MessageConfig{} m := tgbotapi.MessageConfig{}
if captionText == "" { if captionText == "" {
m = tgbotapi.NewMessage(cid, fmt.Sprintf(postFormat, ps.ProcessFacets(h.bsky.Bluesky.FetchAliases()), h.bsky.Bluesky.Cfg.DID, event.Commit.RKey, h.bsky.Bluesky.Cfg.Handle)) m = tgbotapi.NewMessage(cid, fmt.Sprintf(postFormat, facets, h.bsky.Bluesky.Cfg.DID, event.Commit.RKey, h.bsky.Bluesky.Cfg.Handle))
} else { } else {
m = tgbotapi.NewMessage(cid, captionText) m = tgbotapi.NewMessage(cid, captionText)
} }