-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseRelayFeed.ts
More file actions
160 lines (136 loc) · 4.41 KB
/
useRelayFeed.ts
File metadata and controls
160 lines (136 loc) · 4.41 KB
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
import { useEffect, useMemo, useRef, useState } from 'react'
import { cacheEvents, loadRecentCachedEvents } from '../lib/eventStore'
import { createSignedTextNote } from '../lib/nostrSigner'
import { RelayManager } from '../lib/relayManager'
import type { NostrEvent, RelayConfig, RelayPublishAck, RelayStatus } from '../types/nostr'
const DEFAULT_RELAYS: RelayConfig[] = [
{ url: 'wss://relay.damus.io', priority: 1, maxRetries: 8 },
{ url: 'wss://nos.lol', priority: 2, maxRetries: 8 },
{ url: 'wss://relay.snort.social', priority: 3, maxRetries: 8 },
]
const FEED_LIMIT = 150
export function useRelayFeed() {
const [events, setEvents] = useState<NostrEvent[]>([])
const [publishAcks, setPublishAcks] = useState<RelayPublishAck[]>([])
const [relayStatuses, setRelayStatuses] = useState<RelayStatus[]>([])
const [isWarmFromCache, setIsWarmFromCache] = useState(false)
const seenEventIdsRef = useRef<Set<string>>(new Set())
const pendingEventsRef = useRef<NostrEvent[]>([])
const flushTimerRef = useRef<number | null>(null)
const managerRef = useRef<RelayManager | null>(null)
const filters = useMemo(
() => [
{
kinds: [1],
since: Math.floor(Date.now() / 1000) - 60 * 60,
limit: 50,
},
],
[],
)
useEffect(() => {
let isMounted = true
const hydrateCache = async () => {
try {
const cachedEvents = await loadRecentCachedEvents(FEED_LIMIT)
if (!isMounted || cachedEvents.length === 0) {
return
}
setEvents(cachedEvents)
for (const event of cachedEvents) {
seenEventIdsRef.current.add(event.id)
}
setIsWarmFromCache(true)
} catch {
// Cache hydration is optional for the feed startup path.
}
}
hydrateCache()
const manager = new RelayManager(DEFAULT_RELAYS, filters, {
onStatusChange: setRelayStatuses,
onPublishAck: (ack) => {
setPublishAcks((current) => [ack, ...current].slice(0, 24))
},
onEvent: (incomingEvent) => {
if (seenEventIdsRef.current.has(incomingEvent.id)) {
return
}
seenEventIdsRef.current.add(incomingEvent.id)
pendingEventsRef.current.push(incomingEvent)
if (flushTimerRef.current !== null) {
return
}
flushTimerRef.current = window.setTimeout(() => {
const buffered = pendingEventsRef.current.splice(0)
flushTimerRef.current = null
if (buffered.length === 0) {
return
}
setEvents((currentEvents) => {
const next = [...buffered, ...currentEvents]
.sort((a, b) => b.created_at - a.created_at)
.slice(0, FEED_LIMIT)
return next
})
void cacheEvents(buffered)
}, 250)
},
})
managerRef.current = manager
manager.connectAll()
return () => {
isMounted = false
if (flushTimerRef.current !== null) {
window.clearTimeout(flushTimerRef.current)
}
manager.disconnectAll()
managerRef.current = null
}
}, [filters])
const publishTextNote = async (
privateKeyInput: string,
content: string,
): Promise<{ ok: boolean; message: string }> => {
const manager = managerRef.current
if (!manager) {
return { ok: false, message: 'Relay manager is not ready yet' }
}
const trimmed = content.trim()
if (!trimmed) {
return { ok: false, message: 'Write something before publishing' }
}
try {
const signedEvent = createSignedTextNote(privateKeyInput, trimmed)
const sentCount = manager.publish(signedEvent)
seenEventIdsRef.current.add(signedEvent.id)
setEvents((currentEvents) =>
[signedEvent, ...currentEvents]
.sort((a, b) => b.created_at - a.created_at)
.slice(0, FEED_LIMIT),
)
void cacheEvents([signedEvent])
if (sentCount === 0) {
return {
ok: false,
message: 'Signed event created, but no relay connection is currently open',
}
}
return {
ok: true,
message: `Signed and sent to ${sentCount} relay${sentCount > 1 ? 's' : ''}`,
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : 'Unable to sign event',
}
}
}
return {
events,
isWarmFromCache,
publishAcks,
publishTextNote,
relayStatuses,
}
}