-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfirehose.js
366 lines (336 loc) · 11.6 KB
/
firehose.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
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
const WebSocket = require('ws')
const EventEmitter = require('events')
const FileSystem = require('fs')
const { URL } = require('url')
const Request = require('request')
const Package = require('./package.json')
const Cheerio = require('cheerio')
require('colors')
const _uniq = require('lodash.uniq')
const normalizeURL = require('normalize-url')
const EventSource = require('eventsource')
class FirehoseEvents extends EventEmitter {}
class Firehose {
constructor (servers = ['mastodon.social'], spread = false, autostart = true) {
this.servers = _uniq(servers)
this.blacklist = ['t.co', 'youtube.com', 'twitter.com'] // not mastodon servers, ignore
this.activeSockets = []
this.activeStreams = []
this.events = new FirehoseEvents()
this.spread = spread
if (autostart) this.init()
}
init () {
this.connectAll()
setInterval(() => {
this.activeSockets.forEach((socket, index) => {
if (socket.readyState === WebSocket.CLOSED) this.activeSockets.splice(index, 1)
})
this.activeStreams.forEach((stream, index) => {
if (stream.readyState === 2) this.activeStreams.splice(index, 1)
})
this.cleanDupes()
}, 10000)
}
/** List of active WebSocket connections and Event Streams
* @returns number[] Two-value array
*/
get connections () {
return [
this.activeSockets.filter(socket => socket.readyState === 1).length,
this.activeStreams.filter(eventStream => eventStream.readyState === 1).length
]
}
disconnect () {
return new Promise((resolve, reject) => {
this.activeSockets.forEach((socket, index) => {
socket.removeAllListeners()
socket.close()
socket.terminate()
})
for (let i = 0; i < this.activeSockets.length; i++) delete this.activeSockets[i]
this.events.removeAllListeners()
resolve(true)
})
}
checkInstance (incHost, skipChecks = false) {
const host = incHost.toLowerCase()
return new Promise((resolve, reject) => {
// Skips everything, useful for reconnects
if (skipChecks) resolve(true)
// fail when it's blacklisted, saves bandwidth
if (this.blacklist.indexOf(host) > -1) reject(new Error())
if (this.servers.indexOf(host) > -1) reject(new Error())
// stop bugging me about errors
const fail = () => {
this.blacklist.push(host)
reject(new Error())
return new Error()
}
Request.get(`http://${host}/api/v1/instance`, (NastyError, response, body) => {
if (NastyError || !response) return fail()
if (response.statusCode !== 200) return fail()
const ct = response.headers['content-type']
if (ct == null || ct.indexOf('application/json') === -1) return fail()
let jsonBody
try {
jsonBody = JSON.parse(body)
if (typeof jsonBody !== 'object' || jsonBody == null) return fail()
if (jsonBody.uri === host) resolve(true)
} catch (err) {
return fail()
}
})
})
}
cleanDupes () {
const allSockets = _uniq(this.activeSockets.map(socket => socket != null ? (new URL(socket.url)).host : null))
let seen = {}
allSockets.forEach((host, index) => {
if (seen.hasOwnProperty(host)) {
const socket = this.activeSockets[index]
if (socket && socket.url) {
this.events.emit('system:cleanup', host)
socket.close() // safe disconnect
}
this.activeSockets[index] = null
return false
} else {
return (seen[host] = true)
}
})
// removal of null sockets
for (let k = 0; k < this.activeSockets.length; k++) {
if (this.activeSockets[k] == null) {
delete this.activeSockets[k]
k--
}
}
const allStreams = _uniq(this.activeStreams.map(stream => stream != null ? (new URL(stream.url)).host : null))
let seenStreams = {}
allStreams.forEach((host, index) => {
if (seenStreams.hasOwnProperty(host)) {
const stream = this.activeStreams[index]
if (stream && stream.url) {
this.events.emit('system:cleanup', host)
stream.close() // safe disconnect
}
this.activeStreams[index] = null
return false
} else {
return (seenStreams[host] = true)
}
})
// removal of null streams
for (let k = 0; k < this.activeStreams.length; k++) {
if (this.activeStreams[k] == null) {
delete this.activeStreams[k]
k--
}
}
// let allSocketHosts = []
// for (let k = 0; k < this.activeSockets.length; k++) {
// const socket = this.activeSockets[k]
// if (socket == null) continue // yeah just skip if it's null/undefined
// const socketHost = (new URL(socket.url)).host
// // checks to see if it's a new instance or not
// if (this.servers.indexOf(socketHost) === -1) this.servers.push(socketHost)
// // if the socket host already exists, it's a duplicate. remove it
// if (allSocketHosts.indexOf(socketHost) === -1) {
// allSocketHosts.push(socketHost)
// } else {
// this.events.emit('system:cleanup', socketHost)
// socket.terminate()
// this.activeSockets.splice(k, 1)
// k--
// }
// }
}
addServer (incHost, force = false) {
const host = incHost.toLowerCase()
this.servers.push(host)
const actives = this.activeSockets.map(socket => (new URL(socket.url).host))
if (force || (actives.indexOf(host) === -1 && this.blacklist.indexOf(host) === -1)) {
const failure = () => { const a = this.servers.indexOf(host); if (a > -1) this.servers.splice(a, 1); this.blacklist.push(host) }
this.checkInstance(host, force)
.then(() => {
this.connectToServer(host)
.then(() => {
this.updateServers()
})
.catch(() => failure())
})
.catch(() => failure()) // ignore
} else {
const a = this.servers.indexOf(host)
if (a > -1) this.servers.splice(a, 1)
}
}
updateServers () {
// unless there's errors, make the list add-only
if (!this.spread) FileSystem.writeFileSync('.servers.json', JSON.stringify(this.servers))
}
connectAll () {
let k = 0
const connect = async () => {
if (k < this.servers.length) {
const host = this.servers[k]
const failure = () => { const a = this.servers.indexOf(host); if (a > -1) this.servers.splice(a, 1) }
this.connectToServerFallback(this.servers[k])
.then(() => true)
.catch(() => failure())
k++
connect()
}
}
connect()
}
discovery (status) {
if (status.url) {
const host = (new URL(status.url)).host
if (this.servers.indexOf(host)) {
this.addServer(host.toLowerCase())
this.events.emit('system:discovery', host)
}
}
if (status.content) {
// checks for all links
const $ = Cheerio.load(status.content)
const clickLinks = $('*').toArray().map(el => $(el).attr('href')).filter(text => text != null)
if (clickLinks.length) {
_uniq(clickLinks).forEach(val => {
const host = (new URL(val)).host
this.addServer(host.toLowerCase())
this.events.emit('system:discovery', host)
})
}
}
if (status.mentions.length !== 0) {
status.mentions.forEach(mention => {
const url = new URL(mention.url)
this.addServer(url.host.toLowerCase())
this.events.emit('system:discovery', url.host)
})
}
}
get signature () {
return (new Array(4)).fill(0).map(() => Math.round(Math.random() * 10e8).toString(16)).join('')
}
generateHeaders (host) {
return {
'user-agent': `${Package.client} (${Package.version}) Integrity/${this.signature}`,
'origin': normalizeURL(host),
'referer': normalizeURL(host)
}
}
connectToServer (incHost) {
const host = incHost.toLowerCase()
return new Promise((resolve, reject) => {
let stream
if (!this.spread) stream = 'public:local'
else stream = 'public' // The true firehose
const socket = new WebSocket(`wss://${host}/api/v1/streaming/?stream=${stream}`, {
headers: this.generateHeaders()
})
let interval = false
socket.problematic = false
socket.on('open', () => {
this.events.emit('servers:connected', socket.url)
interval = setInterval(() => {
try {
socket.pong('')
} catch (err) {
[err].pop() // shut up useless errors
}
}, 5000)
socket.pong('')
resolve(socket)
})
socket.on('error', err => {
if (interval !== false) clearInterval(interval)
socket.problematic = true
this.blacklist.push(host)
this.events.emit('servers:error', host, err.message)
const ind = this.servers.indexOf(host)
if (ind > -1) this.servers.splice(ind, 1)
this.updateServers()
})
socket.on('message', raw => {
let data
try {
data = JSON.parse(raw)
} catch (err) {
return false
}
if (data.event === 'delete') {
this.events.emit('servers:posts:delete', {
id: data.payload,
host: host
})
} else if (data.event === 'update') {
const status = JSON.parse(data.payload)
status.host = host
this.events.emit('servers:posts:update', status, host)
// this.discovery(status)
}
})
socket.on('close', (ws, code, reason) => {
if (interval !== false) clearInterval(interval)
// const a = this.servers.indexOf(host)
// if (a > -1) this.servers.splice(a, 1)
this.events.emit('servers:disconnect', host, code, reason, socket.problematic)
socket.terminate()
socket.removeAllListeners()
const b = this.activeSockets.map(socket => socket.url).indexOf(host)
if (b > -1) this.activeSockets.splice(b, 1)
})
this.activeSockets.push(socket)
})
}
connectToServerFallback (incHost) {
const host = incHost.toLowerCase()
return new Promise((resolve, reject) => {
let endpoint
if (!this.spread) endpoint = '/api/v1/streaming/public/local'
else endpoint = '/api/v1/streaming/public' // The true firehose
const events = new EventSource(normalizeURL(host, { normalizeHttp: true }) + endpoint, {
headers: this.generateHeaders(host)
})
events.problematic = false
events.onopen = () => {
this.events.emit('servers:connected', events.url)
resolve(events)
}
events.addEventListener('update', raw => {
let status
try {
status = JSON.parse(raw.data)
} catch (err) {
return false
}
status.host = host
this.events.emit('servers:posts:update', status, host)
})
events.addEventListener('delete', id => {
this.events.emit('servers:posts:delete', {
id: id.data,
host
})
})
events.onerror = (err) => {
events.problematic = true
this.events.emit('servers:error', host, err.message)
this.events.emit('servers:disconnect', host, err.status, err.message, events.problematic)
events.close()
const a = this.activeStreams.map(eventStream => eventStream.url).indexOf(events.url)
if (a > -1) this.activeStreams.splice(a, 1)
const b = this.servers.indexOf(host)
if (b > -1) this.servers.splice(b, 1)
this.blacklist.push(host)
this.updateServers()
}
this.activeStreams.push(events)
})
}
}
module.exports = Firehose