-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
web_socket.ts
409 lines (387 loc) · 10.8 KB
/
web_socket.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import WS from 'ws'
import dayjs, { Dayjs } from 'dayjs'
import { v4 as uuid } from 'uuid'
import { EventEmitter } from 'events'
import { WebSocketInterface } from '../megalodon'
import proxyAgent, { ProxyConfig } from '../proxy_config'
import MisskeyAPI from './api_client'
/**
* WebSocket
* Misskey is not support http streaming. It supports websocket instead of streaming.
* So this class connect to Misskey server with WebSocket.
*/
export default class WebSocket extends EventEmitter implements WebSocketInterface {
public url: string
public channel: 'user' | 'localTimeline' | 'hybridTimeline' | 'globalTimeline' | 'conversation' | 'list'
public parser: Parser
public headers: { [key: string]: string }
public proxyConfig: ProxyConfig | false = false
public listId: string | null = null
private _accessToken: string
private _reconnectInterval: number
private _reconnectMaxAttempts: number
private _reconnectCurrentAttempts: number
private _connectionClosed: boolean
private _client: WS | null = null
private _channelID: string
private _pongReceivedTimestamp: Dayjs
private _heartbeatInterval: number = 60000
private _pongWaiting: boolean = false
/**
* @param url Full url of websocket: e.g. wss://misskey.io/streaming
* @param channel Channel name is user, localTimeline, hybridTimeline, globalTimeline, conversation or list.
* @param accessToken The access token.
* @param listId This parameter is required when you specify list as channel.
*/
constructor(
url: string,
channel: 'user' | 'localTimeline' | 'hybridTimeline' | 'globalTimeline' | 'conversation' | 'list',
accessToken: string,
listId: string | undefined,
userAgent: string,
proxyConfig: ProxyConfig | false = false
) {
super()
this.url = url
this.parser = new Parser()
this.channel = channel
this.headers = {
'User-Agent': userAgent,
// To avoid: https://github.com/axios/axios/issues/5346
'Accept-Encoding': 'gzip,deflate,compress'
}
if (listId === undefined) {
this.listId = null
} else {
this.listId = listId
}
this.proxyConfig = proxyConfig
this._accessToken = accessToken
this._reconnectInterval = 10000
this._reconnectMaxAttempts = Infinity
this._reconnectCurrentAttempts = 0
this._connectionClosed = false
this._channelID = uuid()
this._pongReceivedTimestamp = dayjs()
}
/**
* Start websocket connection.
*/
public start() {
this._connectionClosed = false
this._resetRetryParams()
this._startWebSocketConnection()
}
/**
* Reset connection and start new websocket connection.
*/
private _startWebSocketConnection() {
this._resetConnection()
this._setupParser()
this._client = this._connect()
this._bindSocket(this._client)
}
/**
* Stop current connection.
*/
public stop() {
this._connectionClosed = true
this._resetConnection()
this._resetRetryParams()
}
/**
* Clean up current connection, and listeners.
*/
private _resetConnection() {
if (this._client) {
this._client.close(1000)
this._client.removeAllListeners()
this._client = null
}
if (this.parser) {
this.parser.removeAllListeners()
}
}
/**
* Resets the parameters used in reconnect.
*/
private _resetRetryParams() {
this._reconnectCurrentAttempts = 0
}
/**
* Connect to the endpoint.
*/
private _connect(): WS {
let options: WS.ClientOptions = {
headers: this.headers
}
if (this.proxyConfig) {
options = Object.assign(options, {
agent: proxyAgent(this.proxyConfig)
})
}
const cli: WS = new WS(`${this.url}?i=${this._accessToken}`, options)
return cli
}
/**
* Connect specified channels in websocket.
*/
private _channel() {
if (!this._client) {
return
}
switch (this.channel) {
case 'conversation':
this._client.send(
JSON.stringify({
type: 'connect',
body: {
channel: 'main',
id: this._channelID
}
})
)
break
case 'user':
this._client.send(
JSON.stringify({
type: 'connect',
body: {
channel: 'main',
id: this._channelID
}
})
)
this._client.send(
JSON.stringify({
type: 'connect',
body: {
channel: 'homeTimeline',
id: this._channelID
}
})
)
break
case 'list':
this._client.send(
JSON.stringify({
type: 'connect',
body: {
channel: 'userList',
id: this._channelID,
params: {
listId: this.listId
}
}
})
)
break
default:
this._client.send(
JSON.stringify({
type: 'connect',
body: {
channel: this.channel,
id: this._channelID
}
})
)
break
}
}
/**
* Reconnects to the same endpoint.
*/
private _reconnect() {
setTimeout(() => {
// Skip reconnect when client is connecting.
// https://github.com/websockets/ws/blob/7.2.1/lib/websocket.js#L365
if (this._client && this._client.readyState === WS.CONNECTING) {
return
}
if (this._reconnectCurrentAttempts < this._reconnectMaxAttempts) {
this._reconnectCurrentAttempts++
this._clearBinding()
if (this._client) {
// In reconnect, we want to close the connection immediately,
// because recoonect is necessary when some problems occur.
this._client.terminate()
}
// Call connect methods
console.log('Reconnecting')
this._client = this._connect()
this._bindSocket(this._client)
}
}, this._reconnectInterval)
}
/**
* Clear binding event for websocket client.
*/
private _clearBinding() {
if (this._client) {
this._client.removeAllListeners('close')
this._client.removeAllListeners('pong')
this._client.removeAllListeners('open')
this._client.removeAllListeners('message')
this._client.removeAllListeners('error')
}
}
/**
* Bind event for web socket client.
* @param client A WebSocket instance.
*/
private _bindSocket(client: WS) {
client.on('close', (code: number, _reason: Buffer) => {
if (code === 1000) {
this.emit('close', {})
} else {
console.log(`Closed connection with ${code}`)
if (!this._connectionClosed) {
this._reconnect()
}
}
})
client.on('pong', () => {
this._pongWaiting = false
this.emit('pong', {})
this._pongReceivedTimestamp = dayjs()
// It is required to anonymous function since get this scope in checkAlive.
setTimeout(() => this._checkAlive(this._pongReceivedTimestamp), this._heartbeatInterval)
})
client.on('open', () => {
this.emit('connect', {})
this._channel()
// Call first ping event.
setTimeout(() => {
client.ping('')
}, 10000)
})
client.on('message', (data: WS.Data, isBinary: boolean) => {
this.parser.parse(data, isBinary, this._channelID)
})
client.on('error', (err: Error) => {
this.emit('error', err)
})
}
/**
* Set up parser when receive message.
*/
private _setupParser() {
this.parser.on('update', (note: MisskeyAPI.Entity.Note) => {
this.emit('update', MisskeyAPI.Converter.note(note))
})
this.parser.on('notification', (notification: MisskeyAPI.Entity.Notification) => {
this.emit('notification', MisskeyAPI.Converter.notification(notification))
})
this.parser.on('conversation', (note: MisskeyAPI.Entity.Note) => {
this.emit('conversation', MisskeyAPI.Converter.noteToConversation(note))
})
this.parser.on('error', (err: Error) => {
this.emit('parser-error', err)
})
}
/**
* Call ping and wait to pong.
*/
private _checkAlive(timestamp: Dayjs) {
const now: Dayjs = dayjs()
// Block multiple calling, if multiple pong event occur.
// It the duration is less than interval, through ping.
if (now.diff(timestamp) > this._heartbeatInterval - 1000 && !this._connectionClosed) {
// Skip ping when client is connecting.
// https://github.com/websockets/ws/blob/7.2.1/lib/websocket.js#L289
if (this._client && this._client.readyState !== WS.CONNECTING) {
this._pongWaiting = true
this._client.ping('')
setTimeout(() => {
if (this._pongWaiting) {
this._pongWaiting = false
this._reconnect()
}
}, 10000)
}
}
}
}
/**
* Parser
* This class provides parser for websocket message.
*/
export class Parser extends EventEmitter {
/**
* @param message Message body of websocket.
* @param channelID Parse only messages which has same channelID.
*/
public parse(data: WS.Data, isBinary: boolean, channelID: string) {
const message = isBinary ? data : data.toString()
if (typeof message !== 'string') {
this.emit('heartbeat', {})
return
}
if (message === '') {
this.emit('heartbeat', {})
return
}
let obj: {
type: string
body: {
id: string
type: string
body: any
}
}
let body: {
id: string
type: string
body: any
}
try {
obj = JSON.parse(message)
if (obj.type !== 'channel') {
return
}
if (!obj.body) {
return
}
body = obj.body
if (body.id !== channelID) {
return
}
} catch (err) {
this.emit('error', new Error(`Error parsing websocket reply: ${message}, error message: ${err}`))
return
}
switch (body.type) {
case 'note':
this.emit('update', body.body as MisskeyAPI.Entity.Note)
break
case 'notification':
this.emit('notification', body.body as MisskeyAPI.Entity.Notification)
break
case 'mention': {
const note = body.body as MisskeyAPI.Entity.Note
if (note.visibility === 'specified') {
this.emit('conversation', note)
}
break
}
// When renote and followed event, the same notification will be received.
case 'renote':
case 'followed':
case 'follow':
case 'unfollow':
case 'receiveFollowRequest':
case 'meUpdated':
case 'readAllNotifications':
case 'readAllUnreadSpecifiedNotes':
case 'readAllAntennas':
case 'readAllUnreadMentions':
case 'unreadNotification':
// Ignore these events
break
default:
this.emit('error', new Error(`Unknown event has received: ${JSON.stringify(body)}`))
break
}
}
}