verteilen-core 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/index.js +17 -0
  2. package/dist/jest.config.js +8 -0
  3. package/dist/src/client/analysis.js +383 -0
  4. package/dist/src/client/client.js +233 -0
  5. package/dist/src/client/cluster.js +92 -0
  6. package/dist/src/client/execute.js +162 -0
  7. package/dist/src/client/http.js +37 -0
  8. package/dist/src/client/javascript.js +553 -0
  9. package/dist/src/client/job_execute.js +171 -0
  10. package/dist/src/client/job_parameter.js +36 -0
  11. package/dist/src/client/os.js +202 -0
  12. package/dist/src/client/parameter.js +36 -0
  13. package/dist/src/client/resource.js +118 -0
  14. package/dist/src/client/shell.js +118 -0
  15. package/dist/src/interface/base.js +2 -0
  16. package/dist/src/interface/bus.js +2 -0
  17. package/dist/src/interface/enum.js +175 -0
  18. package/dist/src/interface/execute.js +2 -0
  19. package/dist/src/interface/record.js +2 -0
  20. package/dist/src/interface/server.js +28 -0
  21. package/dist/src/interface/struct.js +2 -0
  22. package/dist/src/interface/table.js +2 -0
  23. package/dist/src/interface/ui.js +2 -0
  24. package/dist/src/interface.js +78 -0
  25. package/dist/src/lan/en.json +395 -0
  26. package/dist/src/lan/zh_TW.json +395 -0
  27. package/dist/src/plugins/i18n.js +20 -0
  28. package/dist/src/script/console_manager.js +125 -0
  29. package/dist/src/script/console_server_manager.js +37 -0
  30. package/dist/src/script/execute/base.js +197 -0
  31. package/dist/src/script/execute/feedback.js +188 -0
  32. package/dist/src/script/execute/region_job.js +9 -0
  33. package/dist/src/script/execute/region_project.js +16 -0
  34. package/dist/src/script/execute/region_subtask.js +9 -0
  35. package/dist/src/script/execute/region_task.js +16 -0
  36. package/dist/src/script/execute/runner.js +274 -0
  37. package/dist/src/script/execute/util_parser.js +137 -0
  38. package/dist/src/script/execute_manager.js +309 -0
  39. package/dist/src/script/socket_manager.js +259 -0
  40. package/dist/src/script/webhook_manager.js +8 -0
  41. package/dist/src/script/webhook_server_manager.js +140 -0
  42. package/dist/src/util/server/console_handle.js +248 -0
  43. package/dist/src/util/server/log_handle.js +230 -0
  44. package/dist/test/TEST.js +105 -0
  45. package/dist/test/client/execute.test.js +50 -0
  46. package/dist/test/client/javascript.test.js +75 -0
  47. package/dist/test/client/server.test.js +11 -0
  48. package/dist/test/client/task.test.js +136 -0
  49. package/dist/test/script/parser.test.js +109 -0
  50. package/dist/test/script/socket.test.js +12 -0
  51. package/package.json +2 -2
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src/interface"), exports);
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ module.exports = {
3
+ verbose: true,
4
+ testEnvironment: "node",
5
+ transform: {
6
+ "^.+\.tsx?$": ["ts-jest", {}],
7
+ }
8
+ };
@@ -0,0 +1,383 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.ClientAnalysis = void 0;
46
+ const child_process_1 = require("child_process");
47
+ const interface_1 = require("../interface");
48
+ const client_1 = require("./client");
49
+ const execute_1 = require("./execute");
50
+ const shell_1 = require("./shell");
51
+ const fs_1 = require("fs");
52
+ const path = __importStar(require("path"));
53
+ const os = __importStar(require("os"));
54
+ class ClientAnalysis {
55
+ constructor(_messager, _messager_log, _client) {
56
+ this.resource_wanter = [];
57
+ this.resource_thread = undefined;
58
+ this.resource_cache = undefined;
59
+ this.analysis = (h, source) => {
60
+ const typeMap = {
61
+ 'execute_job': this.execute_job,
62
+ 'release': this.release,
63
+ 'stop_job': this.stop_all,
64
+ 'set_parameter': this.set_parameter,
65
+ 'set_libs': this.set_libs,
66
+ 'shell_folder': this.shell.shell_folder,
67
+ 'open_shell': this.shell.open_shell,
68
+ 'close_shell': this.shell.close_shell,
69
+ 'enter_shell': this.shell.enter_shell,
70
+ 'resource_start': this.resource_start,
71
+ 'resource_end': this.resource_end,
72
+ 'ping': this.pong,
73
+ 'plugin_info': this.plugin_info,
74
+ 'plugin_download': this.plugin_download,
75
+ 'plugin_remove': this.plugin_remove,
76
+ };
77
+ if (h == undefined) {
78
+ this.messager_log('[Client Analysis] Analysis Failed, Value is undefined');
79
+ return 1;
80
+ }
81
+ if (h.message != undefined && h.message.length > 0) {
82
+ this.messager_log(`[Client Analysis] ${h.message}`);
83
+ }
84
+ if (h.data == undefined) {
85
+ this.messager_log('[Client Analysis] Analysis Warn, Data is undefined');
86
+ h.data = 0;
87
+ }
88
+ if (typeMap.hasOwnProperty(h.name)) {
89
+ const castingFunc = typeMap[h.name];
90
+ castingFunc(h.data, source, h.channel);
91
+ return 0;
92
+ }
93
+ else {
94
+ this.messager_log(`[Client Analysis] Analysis Failed, Unknowed header, name: ${h.name}, meta: ${h.meta}`);
95
+ return 2;
96
+ }
97
+ };
98
+ this.execute_job = (job, source, channel) => {
99
+ if (channel == undefined)
100
+ return;
101
+ const target = this.exec_checker(channel);
102
+ target.execute_job(job, source);
103
+ };
104
+ this.release = (dummy, source, channel) => {
105
+ if (channel == undefined)
106
+ return;
107
+ const index = this.exec.findIndex(x => x.uuid == channel);
108
+ if (index == -1)
109
+ return;
110
+ this.exec.splice(index, 1);
111
+ };
112
+ this.set_parameter = (data, source, channel) => {
113
+ if (channel == undefined)
114
+ return;
115
+ const target = this.exec_checker(channel);
116
+ target.set_parameter(data);
117
+ };
118
+ this.set_libs = (data, source, channel) => {
119
+ if (channel == undefined)
120
+ return;
121
+ const target = this.exec_checker(channel);
122
+ target.set_libs(data);
123
+ };
124
+ this.exec_checker = (uuid) => {
125
+ let r = undefined;
126
+ const index = this.exec.findIndex(x => x.uuid == uuid);
127
+ if (index == -1) {
128
+ r = new execute_1.ClientExecute(uuid, this.messager, this.messager_log, this.client);
129
+ this.exec.push(r);
130
+ }
131
+ else {
132
+ r = this.exec[index];
133
+ }
134
+ return r;
135
+ };
136
+ this.pong = (data, source) => {
137
+ const h = { name: 'pong', data: data };
138
+ source.send(JSON.stringify(h));
139
+ };
140
+ this.plugin_info = (data, source) => {
141
+ const pat = path.join(os.homedir(), interface_1.DATA_FOLDER, "plugin.json");
142
+ if ((0, fs_1.existsSync)(pat)) {
143
+ const p = JSON.parse((0, fs_1.readFileSync)(pat).toString());
144
+ const h = { name: 'plugin_info_reply', data: p.plugins };
145
+ source.send(JSON.stringify(h));
146
+ }
147
+ else {
148
+ const p = { plugins: [] };
149
+ const h = { name: 'plugin_info_reply', data: p.plugins };
150
+ (0, fs_1.writeFileSync)(pat, JSON.stringify(p));
151
+ source.send(JSON.stringify(h));
152
+ }
153
+ };
154
+ this.get_releases = (repo, token) => __awaiter(this, void 0, void 0, function* () {
155
+ const qu = yield fetch(`https://api.github.com/repos/${repo}/releases`, {
156
+ headers: {
157
+ Authorization: token ? `token ${token}` : '',
158
+ Accept: "application/vnd.github.v3.raw",
159
+ }
160
+ });
161
+ return qu.text();
162
+ });
163
+ this.filterout = (repo, token, version, filename) => __awaiter(this, void 0, void 0, function* () {
164
+ const text = yield this.get_releases(repo, token);
165
+ const json = JSON.parse(text);
166
+ const v = json.find(x => x.tag_name == version);
167
+ if (!v)
168
+ return;
169
+ const f = v.assets.find(x => x.name == filename);
170
+ if (!f)
171
+ return;
172
+ return f.id;
173
+ });
174
+ this.write_plugin = (t, plugin, source) => {
175
+ const list = this.client.plugins.plugins;
176
+ const index = list.findIndex(x => x.name == plugin.name);
177
+ plugin.token = t ? [t] : [];
178
+ plugin.progress = 0;
179
+ if (index == -1) {
180
+ list.push(plugin);
181
+ }
182
+ else {
183
+ list[index] = plugin;
184
+ }
185
+ this.client.savePlugin();
186
+ this.plugin_info(0, source);
187
+ };
188
+ this.finish_plugin = (plugin, source) => {
189
+ const list = this.client.plugins.plugins;
190
+ const index = list.findIndex(x => x.name == plugin.name);
191
+ plugin.progress = 1;
192
+ if (index == -1) {
193
+ list.push(plugin);
194
+ }
195
+ else {
196
+ list[index] = plugin;
197
+ }
198
+ this.client.savePlugin();
199
+ this.plugin_info(0, source);
200
+ };
201
+ this.plugin_download = (plugin, source) => __awaiter(this, void 0, void 0, function* () {
202
+ const target = plugin.contents.find(x => x.arch == process.arch && x.platform == process.platform);
203
+ if (target == undefined) {
204
+ this.messager_log(`[Plugin] Cannot find target plugin for ${plugin.name} on ${process.platform} ${process.arch}`);
205
+ return;
206
+ }
207
+ const links = target.url.split('/');
208
+ const filename = links[links.length - 1];
209
+ const version = links[links.length - 2];
210
+ const REPO = `${links[3]}/${links[4]}`;
211
+ const dir = path.join(os.homedir(), interface_1.DATA_FOLDER, "exe");
212
+ if (!(0, fs_1.existsSync)(dir))
213
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
214
+ let req = {};
215
+ const tokens = [undefined, ...plugin.token];
216
+ const fileStream = (0, fs_1.createWriteStream)(path.join(dir, target.filename), { flags: 'a' });
217
+ let pass = false;
218
+ for (let t of tokens) {
219
+ if (pass)
220
+ break;
221
+ try {
222
+ const id = yield this.filterout(REPO, t, version, filename);
223
+ req = {
224
+ method: 'GET',
225
+ credentials: 'include',
226
+ headers: {
227
+ Authorization: t ? `token ${t}` : '',
228
+ Accept: "application/octet-stream"
229
+ }
230
+ };
231
+ const url = `https://api.github.com/repos/${REPO}/releases/assets/${id}`;
232
+ fetch(url, req).then((res) => __awaiter(this, void 0, void 0, function* () {
233
+ if (!res.ok) {
234
+ throw new Error(`Failed to download file: ${res.status} ${res.statusText}`);
235
+ }
236
+ this.write_plugin(t, plugin, source);
237
+ return res.blob();
238
+ })).then(blob => {
239
+ return blob.stream().getReader().read();
240
+ })
241
+ .then(reader => {
242
+ if (!reader.done) {
243
+ fileStream.write(Buffer.from(reader.value));
244
+ }
245
+ }).finally(() => {
246
+ this.messager_log(`[Plugin] Downloaded ${plugin.name} successfully`);
247
+ fileStream.end();
248
+ if (process.platform == 'linux') {
249
+ (0, child_process_1.exec)(`chmod +x ${path.join(dir, target.filename)}`, (err) => {
250
+ this.messager_log(`[Plugin] Permission failed ${err === null || err === void 0 ? void 0 : err.message}`);
251
+ });
252
+ }
253
+ this.finish_plugin(plugin, source);
254
+ pass = true;
255
+ });
256
+ }
257
+ catch (err) {
258
+ this.messager_log(`[Plugin] Download failed for ${plugin.name}: ${err.message}`);
259
+ }
260
+ }
261
+ });
262
+ this.plugin_remove = (plugin, source) => {
263
+ this.client.plugins.plugins = this.client.plugins.plugins.filter(x => x.name != plugin.name);
264
+ this.client.savePlugin();
265
+ const dir = path.join(os.homedir(), interface_1.DATA_FOLDER, "exe");
266
+ if (!(0, fs_1.existsSync)(dir))
267
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
268
+ plugin.contents.forEach(x => {
269
+ if ((0, fs_1.existsSync)(path.join(dir, x.filename))) {
270
+ (0, fs_1.rmSync)(path.join(dir, x.filename));
271
+ }
272
+ });
273
+ this.plugin_info(0, source);
274
+ };
275
+ this.resource_start = (data, source) => {
276
+ this.resource_wanter.push(source);
277
+ this.messager_log(`Register resource_wanter!, count: ${this.resource_wanter.length}`);
278
+ if (this.resource_cache != undefined)
279
+ source.send(JSON.stringify(this.resource_cache));
280
+ };
281
+ this.resource_end = (data, source) => {
282
+ const index = this.resource_wanter.findIndex(x => x == source);
283
+ if (index != -1) {
284
+ this.resource_wanter.splice(index, 1);
285
+ this.messager_log(`UnRegister resource_wanter!, count: ${this.resource_wanter.length}`);
286
+ }
287
+ };
288
+ this.update = (client) => {
289
+ this.resource_require();
290
+ if (this.resource_cache != undefined) {
291
+ this.resource_wanter.forEach(x => x.send(JSON.stringify(this.resource_cache)));
292
+ }
293
+ };
294
+ this.disconnect = (source) => {
295
+ this.shell.disconnect(source);
296
+ this.exec.forEach(x => x.stop_job());
297
+ };
298
+ this.stop_all = () => {
299
+ this.exec.forEach(x => x.stop_job());
300
+ };
301
+ this.destroy = () => {
302
+ if (this.resource_thread != undefined)
303
+ this.resource_thread.kill();
304
+ };
305
+ this.resource_require = () => {
306
+ var _a, _b, _c, _d;
307
+ if (this.resource_thread != undefined)
308
+ return;
309
+ const shouldRun = this.resource_thread == undefined && (this.resource_cache == undefined || this.resource_wanter.length > 0);
310
+ if (!shouldRun)
311
+ return;
312
+ this.resource_thread = (0, child_process_1.spawn)(client_1.Client.workerPath(), [], {
313
+ stdio: ['inherit', 'pipe', 'pipe'],
314
+ shell: true,
315
+ windowsHide: true,
316
+ env: Object.assign(Object.assign({}, process.env), { type: "RESOURCE", cache: this.resource_cache == undefined ? undefined : JSON.stringify(this.resource_cache.data) })
317
+ });
318
+ let k = "";
319
+ const workerFeedbackExec = (str) => {
320
+ try {
321
+ const msg = JSON.parse(str);
322
+ if (msg.name == 'messager') {
323
+ this.messager(msg.data, "RESOURCE");
324
+ }
325
+ else if (msg.name == 'messager_log') {
326
+ this.messager_log(msg.data, "RESOURCE");
327
+ }
328
+ else if (msg.name == 'resource') {
329
+ const h = {
330
+ name: 'system_info',
331
+ data: msg.data
332
+ };
333
+ this.resource_cache = h;
334
+ this.resource_wanter.forEach(x => x.send(JSON.stringify(h)));
335
+ }
336
+ else if (msg.name == 'error') {
337
+ if (msg.data instanceof String)
338
+ this.messager_log(msg.data.toString(), "RESOURCE");
339
+ else
340
+ this.messager_log(JSON.stringify(msg.data), "RESOURCE");
341
+ }
342
+ }
343
+ catch (err) {
344
+ console.log("str: " + str);
345
+ console.log(err.name + "\n" + err.message);
346
+ }
347
+ };
348
+ const workerFeedback = (str) => {
349
+ for (let i = 0; i < str.length; i++) {
350
+ if (str[i] != '\n')
351
+ k += str[i];
352
+ else {
353
+ workerFeedbackExec(k);
354
+ k = '';
355
+ }
356
+ }
357
+ };
358
+ this.resource_thread.on('error', (err) => {
359
+ this.messager_log(`[Worker Error] ${err}`);
360
+ });
361
+ this.resource_thread.on('exit', (code, signal) => {
362
+ this.resource_thread = undefined;
363
+ });
364
+ this.resource_thread.on('message', (message, sendHandle) => {
365
+ workerFeedback(message.toString());
366
+ });
367
+ (_a = this.resource_thread.stdout) === null || _a === void 0 ? void 0 : _a.setEncoding('utf8');
368
+ (_b = this.resource_thread.stdout) === null || _b === void 0 ? void 0 : _b.on('data', (chunk) => {
369
+ workerFeedback(chunk.toString());
370
+ });
371
+ (_c = this.resource_thread.stderr) === null || _c === void 0 ? void 0 : _c.setEncoding('utf8');
372
+ (_d = this.resource_thread.stderr) === null || _d === void 0 ? void 0 : _d.on('data', (chunk) => {
373
+ workerFeedback(chunk.toString());
374
+ });
375
+ };
376
+ this.client = _client;
377
+ this.messager = _messager;
378
+ this.messager_log = _messager_log;
379
+ this.shell = new shell_1.ClientShell(_messager, _messager_log, this.client);
380
+ this.exec = [];
381
+ }
382
+ }
383
+ exports.ClientAnalysis = ClientAnalysis;
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.Client = void 0;
46
+ const path = __importStar(require("path"));
47
+ const tcp_port_used_1 = require("tcp-port-used");
48
+ const ws = __importStar(require("ws"));
49
+ const interface_1 = require("../interface");
50
+ const analysis_1 = require("./analysis");
51
+ const fs_1 = require("fs");
52
+ const os = __importStar(require("os"));
53
+ const pem = __importStar(require("pem"));
54
+ const https = __importStar(require("https"));
55
+ class Client {
56
+ get count() {
57
+ return this.sources.length;
58
+ }
59
+ get clients() {
60
+ return this.sources;
61
+ }
62
+ constructor(_messager, _messager_log) {
63
+ this.plugins = { plugins: [] };
64
+ this.httpss = undefined;
65
+ this.client = undefined;
66
+ this.sources = [];
67
+ this.Init = () => __awaiter(this, void 0, void 0, function* () {
68
+ let port_result = interface_1.PORT;
69
+ let canbeuse = false;
70
+ while (!canbeuse) {
71
+ yield (0, tcp_port_used_1.check)(port_result).then(x => {
72
+ canbeuse = !x;
73
+ }).catch(err => {
74
+ canbeuse = true;
75
+ });
76
+ if (!canbeuse)
77
+ port_result += 1;
78
+ }
79
+ const pems = yield this.get_pem();
80
+ this.httpss = https.createServer({ key: pems[0], cert: pems[1], minVersion: 'TLSv1.2', maxVersion: 'TLSv1.3' }, (req, res) => {
81
+ res.writeHead(200);
82
+ res.end('HTTPS server is running');
83
+ });
84
+ this.httpss.addListener('upgrade', (req, res, head) => console.log('UPGRADE:', req.url));
85
+ this.client = new ws.Server({ server: this.httpss });
86
+ this.client.on('listening', () => {
87
+ this.messager_log('[Server] Listen PORT: ' + port_result.toString());
88
+ });
89
+ this.client.on('error', (err) => {
90
+ this.messager_log(`[Server] Error ${err.name}\n\t${err.message}\n\t${err.stack}`);
91
+ });
92
+ this.client.on('close', () => {
93
+ this.messager_log('[Server] Close !');
94
+ this.Release();
95
+ });
96
+ this.client.on('connection', (ws, request) => {
97
+ const a = new analysis_1.ClientAnalysis(this.messager, this.messager_log, this);
98
+ this.analysis.push(a);
99
+ this.sources.push(ws);
100
+ this.messager_log(`[Server] New Connection detected, ${ws.url}`);
101
+ ws.on('close', (code, reason) => {
102
+ const index = this.sources.findIndex(x => x == ws);
103
+ if (index != -1)
104
+ this.sources.splice(index, 1);
105
+ this.messager_log(`[Source] Close ${code} ${reason}`);
106
+ a.disconnect(ws);
107
+ });
108
+ ws.on('error', (err) => {
109
+ this.messager_log(`[Source] Error ${err.name}\n\t${err.message}\n\t${err.stack}`);
110
+ });
111
+ ws.on('open', () => {
112
+ this.messager_log(`[Source] New source is connected, URL: ${ws === null || ws === void 0 ? void 0 : ws.url}`);
113
+ });
114
+ ws.on('message', (data, isBinery) => {
115
+ const h = JSON.parse(data.toString());
116
+ a.analysis(h, ws);
117
+ });
118
+ });
119
+ this.httpss.listen(port_result, () => {
120
+ this.messager_log('[Server] Select Port: ' + port_result.toString());
121
+ });
122
+ });
123
+ this.Destroy = () => {
124
+ if (this.client == undefined)
125
+ return;
126
+ this.client.close((err) => {
127
+ this.messager_log(`[Client] Close error ${err}`);
128
+ });
129
+ this.Release();
130
+ };
131
+ this.Release = () => {
132
+ this.analysis.forEach(x => x.stop_all());
133
+ this.analysis.forEach(x => x.destroy());
134
+ this.analysis = [];
135
+ };
136
+ this.savePlugin = () => {
137
+ const f = path.join(os.homedir(), interface_1.DATA_FOLDER);
138
+ const pluginPath = path.join(f, 'plugin.json');
139
+ if (!(0, fs_1.existsSync)(f))
140
+ (0, fs_1.mkdirSync)(f, { recursive: true });
141
+ (0, fs_1.writeFileSync)(pluginPath, JSON.stringify(this.plugins, null, 4));
142
+ };
143
+ this.update = () => {
144
+ this.analysis.forEach(x => x.update(this));
145
+ };
146
+ this.loadPlugins = () => {
147
+ const f = path.join(os.homedir(), interface_1.DATA_FOLDER);
148
+ const pluginPath = path.join(f, 'plugin.json');
149
+ if (!(0, fs_1.existsSync)(f))
150
+ (0, fs_1.mkdirSync)(f, { recursive: true });
151
+ if (!(0, fs_1.existsSync)(pluginPath)) {
152
+ (0, fs_1.writeFileSync)(pluginPath, JSON.stringify(this.plugins, null, 4));
153
+ }
154
+ else {
155
+ this.plugins = JSON.parse((0, fs_1.readFileSync)(pluginPath).toString());
156
+ }
157
+ };
158
+ this.get_pem = () => {
159
+ return new Promise((resolve) => {
160
+ const pemFolder = path.join(os.homedir(), interface_1.DATA_FOLDER, 'pem');
161
+ if (!(0, fs_1.existsSync)(pemFolder))
162
+ (0, fs_1.mkdirSync)(pemFolder);
163
+ const clientKey = path.join(pemFolder, "client_clientkey.pem");
164
+ const certificate = path.join(pemFolder, "client_certificate.pem");
165
+ if (!(0, fs_1.existsSync)(clientKey) || !(0, fs_1.existsSync)(certificate)) {
166
+ pem.createCertificate({ selfSigned: true }, (err, keys) => {
167
+ (0, fs_1.writeFileSync)(clientKey, keys.clientKey, { encoding: 'utf8' });
168
+ (0, fs_1.writeFileSync)(certificate, keys.certificate, { encoding: 'utf8' });
169
+ resolve([keys.clientKey, keys.certificate]);
170
+ });
171
+ }
172
+ else {
173
+ resolve([(0, fs_1.readFileSync)(clientKey, 'utf8').toString(), (0, fs_1.readFileSync)(certificate, 'utf8').toString()]);
174
+ }
175
+ });
176
+ };
177
+ this.messager = _messager;
178
+ this.messager_log = _messager_log;
179
+ this.analysis = [];
180
+ this.updatehandle = setInterval(this.update, interface_1.CLIENT_UPDATETICK);
181
+ this.loadPlugins();
182
+ }
183
+ Dispose() {
184
+ clearInterval(this.updatehandle);
185
+ }
186
+ }
187
+ exports.Client = Client;
188
+ Client.workerPath = (filename = "worker", extension = ".exe") => {
189
+ var _a;
190
+ const isExe = ((_a = process.pkg) === null || _a === void 0 ? void 0 : _a.entrypoint) != undefined;
191
+ const exe = process.platform == 'win32' ? filename + extension : filename;
192
+ let workerExe = "";
193
+ let p = 0;
194
+ if (isExe && path.basename(process.execPath) == (process.platform ? "app.exe" : 'app')) {
195
+ workerExe = path.join(process.execPath, "..", "bin", exe);
196
+ p = 1;
197
+ }
198
+ else if ((process.mainModule && process.mainModule.filename.indexOf('app.asar') !== -1) ||
199
+ process.argv.filter(a => a.indexOf('app.asar') !== -1).length > 0) {
200
+ workerExe = path.join("bin", exe);
201
+ p = 2;
202
+ }
203
+ else if (process.env.NODE_ENV === 'development') {
204
+ workerExe = path.join(process.cwd(), "bin", exe);
205
+ p = 3;
206
+ }
207
+ else {
208
+ workerExe = Client.isTypescript() ? path.join(__dirname, "bin", exe) : path.join(__dirname, "..", "bin", exe);
209
+ p = 4;
210
+ }
211
+ return workerExe;
212
+ };
213
+ Client.isTypescript = () => {
214
+ const extension = path.extname(__filename);
215
+ if (extension === ".ts") {
216
+ return true;
217
+ }
218
+ const lastArg = process.execArgv[process.execArgv.length - 1];
219
+ if (lastArg && path.parse(lastArg).name.indexOf("ts-node") > 0) {
220
+ return true;
221
+ }
222
+ try {
223
+ return process[Symbol.for("ts-node.register.instance")] ||
224
+ (process.env.NODE_ENV === "test" &&
225
+ process.env.ACTIONHERO_TEST_FILE_EXTENSION !== "js")
226
+ ? true
227
+ : false;
228
+ }
229
+ catch (error) {
230
+ console.error(error);
231
+ return false;
232
+ }
233
+ };