forked from smooth80/bouncer.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
122 lines (106 loc) · 2.81 KB
/
index.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
'use strict'
const uWebSockets = require('uWebSockets.js')
const UWSRoomManager = require('./lib/api')
const serve = require('./server')
/**
* @desc this is the default export
* @param {BouncerConfig} userConfig
* @type BouncerJs
*/
class BouncerJs extends UWSRoomManager {
constructor(userConfig = {}) {
super(userConfig)
if (this.config.debug) {
console.info(`${this.config.logo} with config:`, this.config)
}
this.router = this.createRouter()
this.router
.ws('/*', {
message: (ws, message) => this.onMessage(ws, message),
close: (ws) => this.onClose(ws)
})
.listen(parseInt(this.config.port), (listenSocket) =>
this.onListen(listenSocket)
)
}
/**
* internal / override if necessary in class extends BouncerJd
* @returns uWebSockets.SSLApp|uWebSockets.App
*/
createRouter() {
// if user provides ssl in configuration
// SSLApp is started
// otherwise App is started
const startRouter = this.config.ssl ? uWebSockets.SSLApp : uWebSockets.App
const ssl = this.config.ssl || {}
return startRouter({
key_file_name: ssl.key,
cert_file_name: ssl.cert,
passphrase: ssl.passphrase
})
}
/**
* internal / override if necessary in class extends BouncerJd
* @param {number} port
*/
onListen(listenSocket) {
if (listenSocket) {
const plugins = Object.keys(this.config.plugins)
if (plugins.length) {
console.info(
`${this.config.logo} with: ${plugins.join(', ')} on port: ${
this.config.port
}`
)
} else {
console.info(`${this.config.logo} on port: ${this.config.port}`)
}
}
}
/**
* internal / override if necessary in class extends BouncerJd
* @desc on disconnect leave socket ws.topic
* @param {WebSocket} ws
*/
onClose(ws) {
try {
for (const topic of ws.topics) {
this.leave(ws, topic)
}
} catch (err) {
// socket already closed
}
}
/**
* internal / override if necessary in class extends BouncerJd
* @desc this is Join + run plugins + leave
* @param {WebSocket} ws
* @param {ArrayBuffer} message
*/
onMessage(ws, message) {
const utf8 = Buffer.from(message).toString()
try {
const { event, data } = JSON.parse(utf8)
// Optional join: sets ws.topic
if (event === this.config.join) {
this.join(ws, data)
}
// Optional leave: removes ws.topic
if (event === this.config.leave) {
this.leave(ws, data)
}
this.onEvent(ws, event, data)
} catch (err) {
console.error(err)
}
}
/**
* call to serve static files folder directory
* @param {string} dist
* @returns BouncerJS
*/
serve(dist = 'dist') {
return serve(dist, this)
}
}
module.exports = BouncerJs