-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.js
245 lines (214 loc) · 8.57 KB
/
main.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
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const adapterName = require('./package.json').name.split('.').pop();
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const SocketIO = require('./lib/socketIO.js');
const socketio = require('socket.io');
const { WebServer } = require('@iobroker/webserver');
let webServer = null;
let secret = 'Zgfr56gFe87jJOM'; // Will be generated by first start
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, { name: adapterName });
adapter = new utils.Adapter(options);
adapter.on('objectChange', (id, obj) => {
if (webServer && webServer.io) {
webServer.io.publishAll('objectChange', id, obj);
}
});
adapter.on('stateChange', (id, state) => {
if (webServer && webServer.io) {
webServer.io.publishAll('stateChange', id, state);
}
});
adapter.on('fileChange', (id, fileName, size) => {
if (webServer && webServer.io) {
webServer.io.publishFileAll(id, fileName, size);
}
});
adapter.on('unload', callback => {
try {
adapter.setState && adapter.setState('info.connected', '', true);
adapter.setState && adapter.setState('info.connection', false, true);
adapter.log.info(
`terminating http${webServer.settings.secure ? 's' : ''} server on port ${webServer.settings.port}`
);
webServer.io.close();
webServer.server.close();
callback();
} catch (e) {
callback();
}
});
adapter.on('ready', () => {
if (adapter.config.auth) {
// Generate secret for session manager
adapter.getForeignObject('system.config', (err, obj) => {
if (!err && obj) {
if (!obj.native || !obj.native.secret) {
obj.native = obj.native || {};
require('node:crypto').randomBytes(24, (ex, buf) => {
secret = buf.toString('hex');
adapter.extendForeignObject('system.config', { native: { secret: secret } });
main();
});
} else {
secret = obj.native.secret;
main();
}
} else {
adapter.log.error('Cannot find object system.config');
}
});
} else {
main();
}
});
adapter.on('message', obj => {
if (!obj || obj.command !== 'im') {
// if not instance message
return;
}
if (webServer && webServer.io) {
// to make messages shorter, we code the answer as:
// m - message type
// s - socket ID
// d - data
webServer.io.publishInstanceMessageAll(obj.from, obj.message.m, obj.message.s, obj.message.d);
}
});
adapter.on('log', obj => webServer && webServer.io && webServer.io.sendLog(obj));
return adapter;
}
function main() {
if (adapter.config.secure) {
// Load certificates
adapter.getCertificates((err, certificates, leConfig) => {
adapter.config.certificates = certificates;
adapter.config.leConfig = leConfig;
webServer = initWebServer(adapter.config);
});
} else {
webServer = initWebServer(adapter.config);
}
}
//settings: {
// "port": 8080,
// "auth": false,
// "secure": false,
// "bind": "0.0.0.0", // "::"
//}
function initWebServer(settings) {
const server = {
app: null,
server: null,
io: null,
settings
};
let store = null;
settings.port = parseInt(settings.port, 10) || 0;
if (settings.port) {
if (settings.secure && !settings.certificates) {
return null;
}
settings.crossDomain = true;
settings.ttl = settings.ttl || 3600;
settings.forceWebSockets = settings.forceWebSockets || false;
if (settings.auth) {
const session = require('express-session');
const AdapterStore = utils.commonTools.session(session, settings.ttl);
// Authentication checked by server itself
store = new AdapterStore({ adapter });
settings.forceWebSockets = settings.forceWebSockets || false;
}
adapter.getPort(
settings.port,
!settings.bind || settings.bind === '0.0.0.0' ? undefined : settings.bind || undefined,
async port => {
if (parseInt(port, 10) !== settings.port && !adapter.config.findNextPort) {
adapter.log.error(`port ${settings.port} already in use`);
return adapter.terminate
? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
: process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
}
settings.port = port;
try {
const webserver = new WebServer({
app: server.app,
adapter,
secure: adapter.config.secure
});
// initialize and you can use your server as known
server.server = await webserver.init();
} catch (err) {
adapter.log.error(`Cannot create webserver: ${err}`);
adapter.terminate
? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
: process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
return;
}
if (!server.server) {
adapter.log.error(`Cannot create webserver`);
adapter.terminate
? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
: process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
return;
}
let serverListening = false;
server.server.on('error', e => {
if (e.toString().includes('EACCES') && port <= 1024) {
adapter.log.error(
`node.js process has no rights to start server on the port ${port}.\n` +
'Do you know that on linux you need special permissions for ports under 1024?\n' +
'You can call in shell following scrip to allow it for node.js: "iobroker fix"'
);
} else {
adapter.log.error(`Cannot start server on ${settings.bind || '0.0.0.0'}:${port}: ${e}`);
}
if (!serverListening) {
adapter.terminate
? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
: process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
}
});
// Start the web server
server.server.listen(
settings.port,
!settings.bind || settings.bind === '0.0.0.0' ? undefined : settings.bind || undefined,
() => {
adapter.setState('info.connection', true, true);
serverListening = true;
}
);
server.io = new SocketIO(settings, adapter);
const socketOptions = {
pingInterval: 120000,
pingTimeout: 30000,
cors: {
// for socket.4.x
origin: `*`,
allowedHeaders: ['*'],
credentials: true
}
};
server.io.start(server.server, socketio, { store, secret }, socketOptions);
}
);
} else {
adapter.log.error('port missing');
adapter.terminate
? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION)
: process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
}
return server;
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}