aboutsummaryrefslogtreecommitdiff
path: root/backend/notes/note.go
blob: c427a8f21d4423b26f6aa4b184de88cdcd3cab9a (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
package notes

import (
	"sort"
	"time"
)

type Note struct {
	URI            string    `json:"uri"`
	AuthorDID      string    `json:"authorDID"`
	AuthorHandle   string    `json:"authorHandle"`
	AuthorName     string    `json:"authorName"`
	AuthorNoUnauth bool      `json:"authorNoUnauth"` // author has !no-unauthenticated label
	AvatarURL      string    `json:"avatarURL"`
	Text           string    `json:"text"`
	CreatedAt      time.Time `json:"createdAt"`
	ReplyTo        *string   `json:"replyTo,omitempty"`
	Facets         []Facet   `json:"facets,omitempty"`
	Parents        []Note    `json:"parents,omitempty"`
}

type Facet struct {
	ByteStart int    `json:"byteStart"`
	ByteEnd   int    `json:"byteEnd"`
	Type      string `json:"type"`
	Value     string `json:"value"` // the link destination, whether url, profile or tag
}

func MissingNote(uri string) *Note {
	return &Note{
		URI:       uri,
		AuthorDID: "MISSING",
		Text:      "This post could not be fetched. It may have been deleted.",
		CreatedAt: time.Time{},
	}
}

func isChainContained(smallChain, bigChain []Note) bool {
	if len(smallChain) > len(bigChain) {
		return false
	}

	// check if smallChain is a suffix of bigChain
	offset := len(bigChain) - len(smallChain)
	for i, note := range smallChain {
		if bigChain[offset+i].URI != note.URI {
			return false
		}
	}
	return true
}

func DeduplicateThreads(posts []Note) []Note {
	// sort by parent chain length (longest first)
	sort.Slice(posts, func(i, j int) bool {
		return len(posts[i].Parents) > len(posts[j].Parents)
	})

	filtered := []Note{}
	for _, post := range posts {
		isRedundant := false
		for _, kept := range filtered {
			// check if this post's chain is contained in any kept post
			if isChainContained(post.Parents, kept.Parents) && post.URI == kept.URI {
				isRedundant = true
				break
			}
		}
		if !isRedundant {
			filtered = append(filtered, post)
		}
	}

	return filtered
}