aboutsummaryrefslogtreecommitdiff
path: root/backend/notes/app.bsky.feed.post.go
blob: 1c117336663f979505e009ebd8f30a085b6680ed (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
package notes

import (
	"fmt"
	"llostre/backend/general"
	"strings"
	"time"
)

type AppBskyFeedPostRecord struct {
	URI   string `json:"uri"`
	Value struct {
		Text      string `json:"text"`
		CreatedAt string `json:"createdAt"`
		Reply     *struct {
			Parent struct {
				URI string `json:"uri"`
			} `json:"parent"`
		} `json:"reply,omitempty"`
		Facets []struct {
			Index struct {
				ByteStart int `json:"byteStart"`
				ByteEnd   int `json:"byteEnd"`
			} `json:"index"`
			Features []struct {
				Type string `json:"$type"`
				URI  string `json:"uri,omitempty"`
				DID  string `json:"did,omitempty"`
				Tag  string `json:"tag,omitempty"`
			} `json:"features"`
		} `json:"facets,omitempty"`
	} `json:"value"`
}

func AppBskyFeedPostFromRecord(record AppBskyFeedPostRecord, profile *general.Profile) (*Note, error) {
	if record.URI == "" {
		return nil, fmt.Errorf("missing required field: uri")
	}

	createdAt, err := time.Parse(time.RFC3339, record.Value.CreatedAt)
	if err != nil {
		return nil, fmt.Errorf("failed to parse timestamp: %w", err)
	}

	var replyTo *string
	if record.Value.Reply != nil {
		replyTo = &record.Value.Reply.Parent.URI
	}

	parts := strings.Split(record.URI, "/") // at://DID/collection/rkey
	did := parts[2]

	var facets []Facet
	for _, f := range record.Value.Facets {
		for _, feature := range f.Features {
			var value string
			var facetType string

			switch feature.Type {
			case "app.bsky.richtext.facet#link":
				facetType = "link"
				value = feature.URI
			case "app.bsky.richtext.facet#mention":
				facetType = "mention"
				value = feature.DID
			case "app.bsky.richtext.facet#tag":
				facetType = "tag"
				value = feature.Tag
			default:
				continue
			}

			facets = append(facets, Facet{
				ByteStart: f.Index.ByteStart,
				ByteEnd:   f.Index.ByteEnd,
				Type:      facetType,
				Value:     value,
			})
		}
	}

	var handle, displayName, avatarURL string
	if profile != nil {
		handle = profile.Handle
		displayName = profile.DisplayName
		avatarURL = profile.AvatarURL
	} else {
		handle = "handle.invalid"
		displayName = ""
		avatarURL = ""
	}

	return &Note{
		URI:          record.URI,
		AuthorDID:    did,
		AuthorHandle: handle,
		AuthorName:   displayName,
		AvatarURL:    avatarURL,
		CreatedAt:    createdAt,
		Text:         record.Value.Text,
		ReplyTo:      replyTo,
		Facets:       facets,
	}, nil
}