-
-
Notifications
You must be signed in to change notification settings - Fork 441
/
base.ts
367 lines (311 loc) · 10.7 KB
/
base.ts
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import EventEmitter from 'eventemitter3'
import { OPCODE } from './data'
import { EVENT, WebSocketEvents } from './events'
import { WebSocketMessages, WebSocketPayloads, SignalProvidePayload, SignalCandidatePayload } from './messages'
export interface BaseEvents {
info: (...message: any[]) => void
warn: (...message: any[]) => void
debug: (...message: any[]) => void
error: (error: Error) => void
}
export abstract class BaseClient extends EventEmitter<BaseEvents> {
protected _ws?: WebSocket
protected _peer?: RTCPeerConnection
protected _channel?: RTCDataChannel
protected _timeout?: number
protected _displayname?: string
protected _state: RTCIceConnectionState = 'disconnected'
protected _id = ''
protected _candidates: RTCIceCandidate[] = []
get id() {
return this._id
}
get supported() {
return typeof RTCPeerConnection !== 'undefined' && typeof RTCPeerConnection.prototype.addTransceiver !== 'undefined'
}
get socketOpen() {
return typeof this._ws !== 'undefined' && this._ws.readyState === WebSocket.OPEN
}
get peerConnected() {
return typeof this._peer !== 'undefined' && ['connected', 'checking', 'completed'].includes(this._state)
}
get connected() {
return this.peerConnected && this.socketOpen
}
public connect(url: string, password: string, displayname: string) {
if (this.socketOpen) {
this.emit('warn', `attempting to create websocket while connection open`)
return
}
if (!this.supported) {
this.onDisconnected(new Error('browser does not support webrtc (RTCPeerConnection missing)'))
return
}
this._displayname = displayname
this[EVENT.CONNECTING]()
try {
this._ws = new WebSocket(`${url}?password=${encodeURIComponent(password)}`)
this.emit('debug', `connecting to ${this._ws.url}`)
this._ws.onmessage = this.onMessage.bind(this)
this._ws.onerror = (event) => this.onError.bind(this)
this._ws.onclose = (event) => this.onDisconnected.bind(this, new Error('websocket closed'))
this._timeout = window.setTimeout(this.onTimeout.bind(this), 15000)
} catch (err: any) {
this.onDisconnected(err)
}
}
protected disconnect() {
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = undefined
}
if (this._ws) {
// reset all events
this._ws.onmessage = () => {}
this._ws.onerror = () => {}
this._ws.onclose = () => {}
try {
this._ws.close()
} catch (err) {}
this._ws = undefined
}
if (this._channel) {
// reset all events
this._channel.onmessage = () => {}
this._channel.onerror = () => {}
this._channel.onclose = () => {}
try {
this._channel.close()
} catch (err) {}
this._channel = undefined
}
if (this._peer) {
// reset all events
this._peer.onconnectionstatechange = () => {}
this._peer.onsignalingstatechange = () => {}
this._peer.oniceconnectionstatechange = () => {}
this._peer.ontrack = () => {}
try {
this._peer.close()
} catch (err) {}
this._peer = undefined
}
this._state = 'disconnected'
this._displayname = undefined
this._id = ''
}
public sendData(event: 'wheel' | 'mousemove', data: { x: number; y: number }): void
public sendData(event: 'mousedown' | 'mouseup' | 'keydown' | 'keyup', data: { key: number }): void
public sendData(event: string, data: any) {
if (!this.connected) {
this.emit('warn', `attempting to send data while disconnected`)
return
}
let buffer: ArrayBuffer
let payload: DataView
switch (event) {
case 'mousemove':
buffer = new ArrayBuffer(7)
payload = new DataView(buffer)
payload.setUint8(0, OPCODE.MOVE)
payload.setUint16(1, 4, true)
payload.setUint16(3, data.x, true)
payload.setUint16(5, data.y, true)
break
case 'wheel':
buffer = new ArrayBuffer(7)
payload = new DataView(buffer)
payload.setUint8(0, OPCODE.SCROLL)
payload.setUint16(1, 4, true)
payload.setInt16(3, data.x, true)
payload.setInt16(5, data.y, true)
break
case 'keydown':
case 'mousedown':
buffer = new ArrayBuffer(11)
payload = new DataView(buffer)
payload.setUint8(0, OPCODE.KEY_DOWN)
payload.setUint16(1, 8, true)
payload.setBigUint64(3, BigInt(data.key), true)
break
case 'keyup':
case 'mouseup':
buffer = new ArrayBuffer(11)
payload = new DataView(buffer)
payload.setUint8(0, OPCODE.KEY_UP)
payload.setUint16(1, 8, true)
payload.setBigUint64(3, BigInt(data.key), true)
break
default:
this.emit('warn', `unknown data event: ${event}`)
}
// @ts-ignore
if (typeof buffer !== 'undefined') {
this._channel!.send(buffer)
}
}
public sendMessage(event: WebSocketEvents, payload?: WebSocketPayloads) {
if (!this.connected) {
this.emit('warn', `attempting to send message while disconnected`)
return
}
this.emit('debug', `sending event '${event}' ${payload ? `with payload: ` : ''}`, payload)
this._ws!.send(JSON.stringify({ event, ...payload }))
}
public async createPeer(sdp: string, lite: boolean, servers: RTCIceServer[]) {
this.emit('debug', `creating peer`)
if (!this.socketOpen) {
this.emit(
'warn',
`attempting to create peer with no websocket: `,
this._ws ? `state: ${this._ws.readyState}` : 'no socket',
)
return
}
if (this.peerConnected) {
this.emit('warn', `attempting to create peer while connected`)
return
}
this._peer = new RTCPeerConnection()
if (lite !== true) {
this._peer = new RTCPeerConnection({
iceServers: servers,
})
}
this._peer.onconnectionstatechange = (event) => {
this.emit('debug', `peer connection state changed`, this._peer ? this._peer.connectionState : undefined)
}
this._peer.onsignalingstatechange = (event) => {
this.emit('debug', `peer signaling state changed`, this._peer ? this._peer.signalingState : undefined)
}
this._peer.oniceconnectionstatechange = (event) => {
this._state = this._peer!.iceConnectionState
this.emit('debug', `peer ice connection state changed: ${this._peer!.iceConnectionState}`)
switch (this._state) {
case 'checking':
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = undefined
}
break
case 'connected':
this.onConnected()
break
case 'disconnected':
this[EVENT.RECONNECTING]()
break
// https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling#ice_connection_state
// We don't watch the disconnected signaling state here as it can indicate temporary issues and may
// go back to a connected state after some time. Watching it would close the video call on any temporary
// network issue.
case 'failed':
this.onDisconnected(new Error('peer failed'))
break
case 'closed':
this.onDisconnected(new Error('peer closed'))
break
}
}
this._peer.ontrack = this.onTrack.bind(this)
this._peer.addTransceiver('audio', { direction: 'recvonly' })
this._peer.addTransceiver('video', { direction: 'recvonly' })
this._channel = this._peer.createDataChannel('data')
this._channel.onerror = this.onError.bind(this)
this._channel.onmessage = this.onData.bind(this)
this._channel.onclose = this.onDisconnected.bind(this, new Error('peer data channel closed'))
this._peer.setRemoteDescription({ type: 'offer', sdp })
for (const candidate of this._candidates) {
this._peer.addIceCandidate(candidate)
}
this._candidates = []
try {
const d = await this._peer.createAnswer()
this._peer!.setLocalDescription(d)
this._ws!.send(
JSON.stringify({
event: EVENT.SIGNAL.ANSWER,
sdp: d.sdp,
displayname: this._displayname,
}),
)
} catch (err: any) {
this.emit('error', err)
}
}
private onMessage(e: MessageEvent) {
const { event, ...payload } = JSON.parse(e.data) as WebSocketMessages
this.emit('debug', `received websocket event ${event} ${payload ? `with payload: ` : ''}`, payload)
if (event === EVENT.SIGNAL.PROVIDE) {
const { sdp, lite, ice, id } = payload as SignalProvidePayload
this._id = id
this.createPeer(sdp, lite, ice)
return
}
if (event === EVENT.SIGNAL.CANDIDATE) {
const { data } = payload as SignalCandidatePayload
const candidate: RTCIceCandidate = JSON.parse(data)
if (this._peer) {
this._peer.addIceCandidate(candidate)
} else {
this._candidates.push(candidate)
}
return
}
// @ts-ignore
if (typeof this[event] === 'function') {
// @ts-ignore
this[event](payload)
} else {
this[EVENT.MESSAGE](event, payload)
}
}
private onData(e: MessageEvent) {
this[EVENT.DATA](e.data)
}
private onTrack(event: RTCTrackEvent) {
this.emit('debug', `received ${event.track.kind} track from peer: ${event.track.id}`, event)
const stream = event.streams[0]
if (!stream) {
this.emit('warn', `no stream provided for track ${event.track.id}(${event.track.label})`)
return
}
this[EVENT.TRACK](event)
}
private onError(event: Event) {
this.emit('error', (event as ErrorEvent).error)
}
private onConnected() {
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = undefined
}
if (!this.connected) {
this.emit('warn', `onConnected called while being disconnected`)
return
}
this.emit('debug', `connected`)
this[EVENT.CONNECTED]()
}
private onTimeout() {
this.emit('debug', `connection timeout`)
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = undefined
}
this.onDisconnected(new Error('connection timeout'))
}
protected onDisconnected(reason?: Error) {
this.disconnect()
this.emit('debug', `disconnected:`, reason)
this[EVENT.DISCONNECTED](reason)
}
protected [EVENT.MESSAGE](event: string, payload: any) {
this.emit('warn', `unhandled websocket event '${event}':`, payload)
}
protected abstract [EVENT.RECONNECTING](): void
protected abstract [EVENT.CONNECTING](): void
protected abstract [EVENT.CONNECTED](): void
protected abstract [EVENT.DISCONNECTED](reason?: Error): void
protected abstract [EVENT.TRACK](event: RTCTrackEvent): void
protected abstract [EVENT.DATA](data: any): void
}