-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
195 lines (168 loc) · 6.11 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
'use strict';
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, './lib/.env') })
const IwgClient = require("./lib/iwg-client");
const HttpServer = require("./lib/http-server");
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const FileSystemHelper = require('./lib/file-system-helper');
const AdapterProvider = require('./lib/adapter-provider');
const HttpClient = require('./lib/http-client');
const AlexaClient = require('./lib/alx-client');
class IwgVpn extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'iwg-vpn',
});
this.on('ready', this.onReady.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
this.clientId = null;
}
async onMessage(msg) {
this.log.silly(`message received: ${JSON.stringify(msg)}`);
if (!this.client) {
return this.sendTo(msg.from, msg.command, { error: 'Not connected yet' }, msg.callback);
}
switch (msg.command) {
case 'get-hosts':
this.sendTo(msg.from, msg.command, this.client.getHosts(), msg.callback);
break;
case 'validate-config':
let params = null;
if (typeof (msg.message) === 'string') {
try {
// hack to extract nested json objects
params = JSON.parse((msg.message || '{}').replace('"{', '{').replace('}"', '}')).config;
} catch (e) {
const response = `Error parsing ${msg.message}`;
this.log.warn(response)
this.sendTo(msg.from, msg.command, { error: response }, msg.callback);
return;
}
}
if (params) {
try {
await this.client.validateConfig((params.remotes || []).filter(r => r.isActive), (params.nats || []).filter(n => n.isActive));
this.sendTo(msg.from, msg.command, '', msg.callback);
} catch (e) {
let response = 'Configuration is invalid';
if (e instanceof Error) {
response = e.message;
}
this.sendTo(msg.from, msg.command, { error: response }, msg.callback);
}
}
break;
}
}
/**
* @param {{ [x: string]: any; }} peersObject
*/
async setPeerStates(peersObject) {
const device = 'Peers';
const keys = Object.keys(peersObject);
const self = this;
await this.deleteDeviceAsync(device);
await this.createDeviceAsync(device);
// create a channel for every peer
// @ts-ignore
await keys.reduce(async (memo, key) => {
await memo;
const peer = peersObject[key];
await self.createChannelAsync(device, peer.name);
const prefix = `${device}.${peer.name}`;
await self.setObjectNotExistsAsync(`${prefix}.address`, {
type: 'state',
common: {
name: 'address',
type: 'string',
role: 'text',
read: true,
write: false
},
native: {}
});
await self.setStateAsync(`${prefix}.address`, peer.address, true);
await self.setObjectNotExistsAsync(`${prefix}.config`, {
type: 'state',
common: {
name: 'config',
type: 'string',
role: 'text',
read: true,
write: false
},
native: {}
});
await self.setStateAsync(`${prefix}.config`, peer.config, true);
}, undefined);
}
async set() {
return await this.setStateAsync(arguments[0], arguments[1], true);
}
async setLocalPeerAddress(...args) {
return await this.set(`local.address`, ...args);
}
async setConnectionStatus(...args) {
return await this.set('info.connection', ...args);
}
async setLatestHandshake(...args) {
return await this.set(`local.handshake`, ...args);
}
async setTransferReceived(...args) {
return await this.set(`local.received`, ...args);
}
async setTransferSent(...args) {
return await this.set(`local.sent`, ...args);
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Reset the connection indicator during startup
this.setConnectionStatus(false);
await AdapterProvider.start(this);
FileSystemHelper.start();
await HttpClient.start();
this.client = new IwgClient();
await this.client.start();
this.httpServer = new HttpServer();
await this.httpServer.start();
await AlexaClient.start(this.config?.params?.alexaEnabled)
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
if (this.client) {
this.client.stop();
}
if (this.httpServer) {
this.httpServer.stop();
}
AlexaClient.cleanup();
callback();
} catch (e) {
callback();
}
}
}
// @ts-ignore parent is a valid property on module
if (module.parent) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new IwgVpn(options);
} else {
// otherwise start the instance directly
new IwgVpn();
}