-
Notifications
You must be signed in to change notification settings - Fork 1
/
NostrSubscriber.kt
210 lines (180 loc) · 8.02 KB
/
NostrSubscriber.kt
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package com.dluvian.voyage.data.nostr
import com.dluvian.nostr_kt.removeTrailingSlashes
import com.dluvian.voyage.core.EventIdHex
import com.dluvian.voyage.core.FEED_RESUB_SPAN_THRESHOLD_SECS
import com.dluvian.voyage.core.PubkeyHex
import com.dluvian.voyage.core.RESUB_TIMEOUT
import com.dluvian.voyage.core.createReplyAndVoteFilters
import com.dluvian.voyage.core.model.ParentUI
import com.dluvian.voyage.core.textNoteAndRepostKinds
import com.dluvian.voyage.data.account.IPubkeyProvider
import com.dluvian.voyage.data.model.FeedSetting
import com.dluvian.voyage.data.model.HomeFeedSetting
import com.dluvian.voyage.data.model.ProfileFeedSetting
import com.dluvian.voyage.data.model.TopicFeedSetting
import com.dluvian.voyage.data.provider.FriendProvider
import com.dluvian.voyage.data.provider.RelayProvider
import com.dluvian.voyage.data.provider.TopicProvider
import com.dluvian.voyage.data.provider.WebOfTrustProvider
import com.dluvian.voyage.data.room.dao.RootPostDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rust.nostr.protocol.Filter
import rust.nostr.protocol.Kind
import rust.nostr.protocol.KindEnum
import rust.nostr.protocol.Nip19Event
import rust.nostr.protocol.Nip19Profile
import rust.nostr.protocol.PublicKey
import rust.nostr.protocol.Timestamp
import java.util.concurrent.atomic.AtomicBoolean
class NostrSubscriber(
topicProvider: TopicProvider,
val subCreator: SubscriptionCreator,
private val friendProvider: FriendProvider,
private val relayProvider: RelayProvider,
private val webOfTrustProvider: WebOfTrustProvider,
private val pubkeyProvider: IPubkeyProvider,
private val subBatcher: SubBatcher,
private val rootPostDao: RootPostDao,
) {
private val scope = CoroutineScope(Dispatchers.IO)
private val feedSubscriber = NostrFeedSubscriber(
scope = scope,
relayProvider = relayProvider,
topicProvider = topicProvider,
friendProvider = friendProvider
)
suspend fun subFeed(until: Long, limit: Int, setting: FeedSetting) {
val adjustedLimit = (4 * limit).toULong() // We don't know if we receive enough root posts
val subscriptions = when (setting) {
is HomeFeedSetting -> feedSubscriber.getHomeFeedSubscriptions(
until = until.toULong(),
since = getCachedSinceTimestamp(setting = setting, until = until, pageSize = limit),
limit = adjustedLimit
)
is TopicFeedSetting -> feedSubscriber.getTopicFeedSubscription(
topic = setting.topic,
until = until.toULong(),
since = getCachedSinceTimestamp(setting = setting, until = until, pageSize = limit),
// Smaller than adjustedLimit, bc posts with topics tend to be root
limit = (2.5 * limit).toULong()
)
is ProfileFeedSetting -> feedSubscriber.getProfileFeedSubscription(
pubkey = setting.pubkey,
until = until.toULong(),
since = getCachedSinceTimestamp(setting = setting, until = until, pageSize = limit),
limit = adjustedLimit
)
}
subscriptions.forEach { (relay, filters) ->
subCreator.subscribe(relayUrl = relay, filters = filters)
}
}
// No lazySubProfile bc we always don't save fields in db
suspend fun subProfile(nprofile: Nip19Profile) {
val profileFilter = Filter().kind(kind = Kind.fromEnum(KindEnum.Metadata))
.author(author = nprofile.publicKey())
.until(timestamp = Timestamp.now())
.limit(1u)
val filters = listOf(profileFilter)
relayProvider.getObserveRelays(nprofile = nprofile).forEach { relay ->
subCreator.subscribe(relayUrl = relay, filters = filters)
}
}
suspend fun subPost(nevent: Nip19Event) {
val postFilter = Filter()
.kinds(kinds = textNoteAndRepostKinds)
.id(id = nevent.eventId())
.limit(limit = 1u)
val filters = listOf(postFilter)
relayProvider.getObserveRelays(nevent = nevent, includeConnected = true).forEach { relay ->
subCreator.subscribe(relayUrl = relay, filters = filters)
}
}
private val votesAndRepliesCache = mutableSetOf<EventIdHex>()
private var lastUpdate = System.currentTimeMillis()
private val isSubbingVotesAndReplies = AtomicBoolean(false)
suspend fun subVotesAndReplies(posts: Collection<ParentUI>) {
if (posts.isEmpty()) return
if (isSubbingVotesAndReplies.compareAndSet(false, true)) {
scope.launch(Dispatchers.Default) {
val currentMillis = System.currentTimeMillis()
if (currentMillis - lastUpdate > RESUB_TIMEOUT) {
votesAndRepliesCache.clear()
lastUpdate = currentMillis
}
val newIds = posts.map { it.getRelevantId() } - votesAndRepliesCache
if (newIds.isEmpty()) return@launch
votesAndRepliesCache.addAll(newIds)
val newPostsByAuthor = posts
.filter { newIds.contains(it.getRelevantId()) }
.groupBy { it.pubkey }
// Repliers and voters publish to authors read relays
val relaysByAuthor = relayProvider.getReadRelays(pubkeys = newPostsByAuthor.keys)
val myReadRelays = relayProvider.getReadRelays().toSet()
val votePubkeys = getVotePubkeys()
relaysByAuthor.forEach { (author, relays) ->
val adjustedRelays = myReadRelays + relays
adjustedRelays.forEach { relay ->
subBatcher.submitVotesAndReplies(
relayUrl = relay,
eventIds = newPostsByAuthor[author]?.map { it.getRelevantId() }
?: emptyList(),
votePubkeys = votePubkeys
)
}
}
}.invokeOnCompletion {
isSubbingVotesAndReplies.set(false)
}
}
}
fun subVotesAndReplies(nevent: Nip19Event) {
val filters = createReplyAndVoteFilters(
ids = listOf(nevent.eventId()),
votePubkeys = getVotePubkeys().map { PublicKey.fromHex(it) },
timestamp = Timestamp.now()
)
nevent.relays()
.map { it.removeTrailingSlashes() }
.toSet() + relayProvider.getReadRelays()
.forEach { relay ->
subCreator.subscribe(relayUrl = relay, filters = filters)
}
}
private fun getVotePubkeys(): List<PubkeyHex> {
val pubkeys = mutableSetOf(pubkeyProvider.getPubkeyHex())
pubkeys.addAll(friendProvider.getFriendPubkeys())
pubkeys.addAll(webOfTrustProvider.getWebOfTrustPubkeys())
return pubkeys.toList()
}
private suspend fun getCachedSinceTimestamp(
setting: FeedSetting,
until: Long,
pageSize: Int
): ULong {
val pageSizeAndHalfOfNext = pageSize.times(1.5).toInt()
val timestamps = when (setting) {
HomeFeedSetting -> rootPostDao.getHomeRootPostsCreatedAt(
until = until,
size = pageSizeAndHalfOfNext
)
is ProfileFeedSetting -> rootPostDao.getProfileRootPostsCreatedAt(
pubkey = setting.pubkey,
until = until,
size = pageSizeAndHalfOfNext,
)
is TopicFeedSetting -> rootPostDao.getTopicRootPostsCreatedAt(
topic = setting.topic,
until = until,
size = pageSizeAndHalfOfNext
)
}
if (timestamps.size < pageSizeAndHalfOfNext) return 1uL
val min = timestamps.min()
val max = timestamps.max()
val selectedSince = if (max - min <= FEED_RESUB_SPAN_THRESHOLD_SECS) max else min
return (selectedSince + 1).toULong()
}
}