-
Notifications
You must be signed in to change notification settings - Fork 0
/
hypercore-fetch-chat.js
197 lines (156 loc) · 4.24 KB
/
hypercore-fetch-chat.js
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
/*
global Event, EventTarget
*/
import LRU from './LRU.js'
const DEFAULT_NAME = 'Anonymous'
const DEFAULT_URL = 'hyper://blog.mauve.moe/'
const EXTENSION_NAME = 'hyperchat-example-1'
const EVENTS_FOLDER = '/$/extensions/'
const BROADCAST_DELAY = 3000
const CLOSED_STATE = 2
export class ErrorEvent extends Event {
constructor (error) {
super('error')
this.error = error
}
}
export class TextEvent extends Event {
constructor (content, username, fromID) {
super('text')
this.content = content
this.username = username
this.fromID = fromID
}
}
export class IdentityEvent extends Event {
constructor (username, fromID) {
super('identity')
this.username = username
this.fromID = fromID
}
}
export default class Chat extends EventTarget {
constructor (url = DEFAULT_URL, {
fetch = globalThis.fetch,
EventSource = globalThis.EventSource,
extensionName = EXTENSION_NAME,
username = DEFAULT_NAME
} = {}) {
super()
this.fetch = fetch
this.EventSource = EventSource
this.url = url
this.extensionName = extensionName
this._username = username
this.source = null
this.seenMessages = new LRU()
this.seenPeople = new LRU()
}
get eventsURL () {
return new URL(EVENTS_FOLDER, this.url).href
}
get extensionURL () {
return this.eventsURL + this.extensionName
}
get username () {
return this._username
}
set username (newUsername) {
this._username = newUsername
this.broadcastIdentity()
}
async open () {
if (this.source && this.source.readyState !== CLOSED_STATE) {
throw new Error('Already opened')
}
// Start listening for extension events
this.source = new this.EventSource(this.eventsURL)
this.source.addEventListener(this.extensionName, (e) => this.onEvent(e))
// Load up the extension
await this.getPeers()
// Wait a bit and then tell everybody we exist
setTimeout(() => this.broadcastIdentity(), BROADCAST_DELAY)
}
async onEvent (e) {
const { data, lastEventId: peerID } = e
try {
const parsed = JSON.parse(data)
const { id, type, from: rawFrom, content, username } = parsed
const fromID = rawFrom || peerID
if (!id) throw new Error('No ID in message')
if (this.seenMessages.has(id)) return
this.seenMessages.track(id)
if (type === 'text') {
this.seenPeople.track(fromID)
this.dispatchEvent(new TextEvent(content, username, fromID))
} else if (type === 'identity') {
// Ignore them if we've seen them before
if (!this.seenPeople.has(fromID)) {
this.seenPeople.track(fromID)
// If they're new, we should tell them we exist
await this.broadcastIdentity()
this.dispatchEvent(new IdentityEvent(username, fromID))
}
} else {
throw new Error('Invalid message type ' + type)
}
await this.broadcastMessage({ ...parsed, from: fromID })
} catch (e) {
this.onError(e)
}
}
async getPeers () {
const { fetch } = this
const response = await fetch(this.extensionURL)
await response.json()
}
async sendText (content) {
const { username } = this
await this.broadcastMessage({
type: 'text',
username,
content
})
this.dispatchEvent(new TextEvent(content, username, 'local'))
}
async broadcastMessage (message) {
if (!message.id) message.id = makeID()
this.seenMessages.track(message.id)
const { fetch } = this
const response = await fetch(this.extensionURL, {
method: 'POST',
body: JSON.stringify(message)
})
await response.text()
}
async broadcastIdentity () {
const { username } = this
try {
await this.broadcastMessage({
type: 'identity',
username
})
} catch (e) {
this.onError(e)
}
}
onError (e) {
console.error(e.stack)
this.dispatchEvent(new ErrorEvent(e))
}
async close () {
if (this.source && this.source.readyState !== CLOSED_STATE) {
this.source.close()
}
}
}
function makeID () {
return new Uint8Array([
Math.random() * 256,
Math.random() * 256,
Math.random() * 256,
Math.random() * 256,
Math.random() * 256,
Math.random() * 256
]).join('')
}