/
relationship.go
113 lines (95 loc) · 2.56 KB
/
relationship.go
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
105
106
107
108
109
110
111
112
113
package repository
import (
"context"
"github.com/nbd-wtf/go-nostr"
"github.com/uakihir0/nostr-rest/server/domain"
"github.com/uakihir0/nostr-rest/server/util"
)
type RelayRelationShipRepository struct {
FollowingsCache StringCacheMap
FollowersCache StringCacheMap
}
var relationShipRepositoryLock = util.Lock[RelayRelationShipRepository]{}
var _ domain.RelationShipRepository = (*RelayRelationShipRepository)(nil)
// NewRelayRelationShipRepository
// Create a new relay relationship repository
func NewRelayRelationShipRepository() *RelayRelationShipRepository {
return relationShipRepositoryLock.Once(
func() *RelayRelationShipRepository {
return &RelayRelationShipRepository{
FollowingsCache: NewStringCacheMap(200),
FollowersCache: NewStringCacheMap(200),
}
},
)
}
var followingsLimitMap = util.NewLimitMap(1)
// GetFollowings
// Get public keys of users specific user is following
func (r *RelayRelationShipRepository) GetFollowings(
pk domain.UserPubKey,
) ([]domain.UserPubKey, error) {
ctx := context.Background()
followingsLimitMap.Acquire(ctx, string(pk))
defer followingsLimitMap.Release(string(pk))
// Get events from cache or query
events := ManageEventsFromString(
r.FollowingsCache, string(pk),
func() []*nostr.Event {
return QuerySyncAll(
ctx,
[]nostr.Filter{{
Kinds: []int{3},
Authors: []string{string(pk)},
}},
)
},
)
// Distinct user public keys
pkMap := make(map[string]bool)
pks := make([]domain.UserPubKey, 0)
for _, event := range events {
for _, tag := range event.Tags {
if !pkMap[tag[1]] {
pkMap[tag[1]] = true
pks = append(pks, domain.UserPubKey(tag[1]))
}
}
}
return pks, nil
}
var followersLimitMap = util.NewLimitMap(1)
// GetFollowers
// Get public keys of users specific user is followed by
func (r *RelayRelationShipRepository) GetFollowers(
pk domain.UserPubKey,
) ([]domain.UserPubKey, error) {
ctx := context.Background()
followersLimitMap.Acquire(ctx, string(pk))
defer followersLimitMap.Release(string(pk))
// Get events from cache or query
events := ManageEventsFromString(
r.FollowingsCache, string(pk),
func() []*nostr.Event {
return QuerySyncAll(
ctx,
[]nostr.Filter{{
Kinds: []int{3},
Tags: map[string][]string{
"p": {string(pk)},
},
}},
)
},
)
// Distinct user public keys
pkMap := make(map[string]bool)
pks := make([]domain.UserPubKey, 0)
for _, event := range events {
if !pkMap[event.PubKey] {
pkMap[event.PubKey] = true
pks = append(pks, domain.UserPubKey(event.PubKey))
}
}
return pks, nil
}