@open-wa/wa-automate 4.76.0 → 5.0.0-alpha.2

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 (125) hide show
  1. package/README.md +14 -165
  2. package/dist/cli-runtime-B7_3MM0c.cjs +798 -0
  3. package/dist/cli-runtime-B7_3MM0c.cjs.map +1 -0
  4. package/dist/cli-runtime-CmpYxFCk.d.cts +31 -0
  5. package/dist/cli-runtime-CmpYxFCk.d.cts.map +1 -0
  6. package/dist/cli.cjs +17 -0
  7. package/dist/cli.cjs.map +1 -0
  8. package/dist/cli.d.cts +2 -0
  9. package/dist/index.cjs +224 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.cts +81 -0
  12. package/dist/index.d.cts.map +1 -0
  13. package/package.json +34 -177
  14. package/CNAME +0 -1
  15. package/_tsconfig.docs.json +0 -140
  16. package/bin/config-schema.json +0 -1
  17. package/bin/oas-type-schemas.json +0 -1
  18. package/bin/server.js +0 -45
  19. package/build/build-config-json-for-bin.ts +0 -56
  20. package/build/generate-oas-types.ts +0 -31
  21. package/dist/api/Client.d.ts +0 -2255
  22. package/dist/api/Client.js +0 -4358
  23. package/dist/api/functions/exposed.enum.d.ts +0 -7
  24. package/dist/api/functions/exposed.enum.js +0 -11
  25. package/dist/api/model/aliases.d.ts +0 -110
  26. package/dist/api/model/aliases.js +0 -3
  27. package/dist/api/model/button.d.ts +0 -24
  28. package/dist/api/model/button.js +0 -2
  29. package/dist/api/model/call.d.ts +0 -51
  30. package/dist/api/model/call.js +0 -18
  31. package/dist/api/model/chat.d.ts +0 -221
  32. package/dist/api/model/chat.js +0 -52
  33. package/dist/api/model/config.d.ts +0 -836
  34. package/dist/api/model/config.js +0 -111
  35. package/dist/api/model/contact.d.ts +0 -143
  36. package/dist/api/model/contact.js +0 -2
  37. package/dist/api/model/errors.d.ts +0 -90
  38. package/dist/api/model/errors.js +0 -117
  39. package/dist/api/model/events.d.ts +0 -120
  40. package/dist/api/model/events.js +0 -127
  41. package/dist/api/model/group-metadata.d.ts +0 -124
  42. package/dist/api/model/group-metadata.js +0 -25
  43. package/dist/api/model/id.d.ts +0 -5
  44. package/dist/api/model/id.js +0 -2
  45. package/dist/api/model/index.d.ts +0 -110
  46. package/dist/api/model/index.js +0 -128
  47. package/dist/api/model/label.d.ts +0 -24
  48. package/dist/api/model/label.js +0 -2
  49. package/dist/api/model/media.d.ts +0 -93
  50. package/dist/api/model/media.js +0 -12
  51. package/dist/api/model/message.d.ts +0 -422
  52. package/dist/api/model/message.js +0 -40
  53. package/dist/api/model/product.d.ts +0 -141
  54. package/dist/api/model/product.js +0 -2
  55. package/dist/api/model/reactions.d.ts +0 -76
  56. package/dist/api/model/reactions.js +0 -2
  57. package/dist/api/model/sessionInfo.d.ts +0 -77
  58. package/dist/api/model/sessionInfo.js +0 -2
  59. package/dist/build/build-postman.d.ts +0 -1
  60. package/dist/build/build-postman.js +0 -262
  61. package/dist/cli/cli-options.d.ts +0 -9
  62. package/dist/cli/cli-options.js +0 -289
  63. package/dist/cli/collections.d.ts +0 -2
  64. package/dist/cli/collections.js +0 -251
  65. package/dist/cli/file-utils.d.ts +0 -1
  66. package/dist/cli/file-utils.js +0 -71
  67. package/dist/cli/index.d.ts +0 -1
  68. package/dist/cli/index.js +0 -231
  69. package/dist/cli/integrations/chatwoot.d.ts +0 -49
  70. package/dist/cli/integrations/chatwoot.js +0 -672
  71. package/dist/cli/integrations/cloudflare.d.ts +0 -6
  72. package/dist/cli/integrations/cloudflare.js +0 -76
  73. package/dist/cli/logo.d.ts +0 -1
  74. package/dist/cli/logo.js +0 -49
  75. package/dist/cli/server.d.ts +0 -24
  76. package/dist/cli/server.js +0 -540
  77. package/dist/cli/setup.d.ts +0 -30
  78. package/dist/cli/setup.js +0 -308
  79. package/dist/config/puppeteer.config.d.ts +0 -11
  80. package/dist/config/puppeteer.config.js +0 -65
  81. package/dist/controllers/auth.d.ts +0 -36
  82. package/dist/controllers/auth.js +0 -322
  83. package/dist/controllers/browser.d.ts +0 -17
  84. package/dist/controllers/browser.js +0 -603
  85. package/dist/controllers/events.d.ts +0 -82
  86. package/dist/controllers/events.js +0 -173
  87. package/dist/controllers/init_patch.d.ts +0 -13
  88. package/dist/controllers/init_patch.js +0 -42
  89. package/dist/controllers/initializer.d.ts +0 -22
  90. package/dist/controllers/initializer.js +0 -511
  91. package/dist/controllers/launch_checks.d.ts +0 -8
  92. package/dist/controllers/launch_checks.js +0 -130
  93. package/dist/controllers/patch_manager.d.ts +0 -37
  94. package/dist/controllers/patch_manager.js +0 -231
  95. package/dist/controllers/popup/index.d.ts +0 -3
  96. package/dist/controllers/popup/index.html +0 -168
  97. package/dist/controllers/popup/index.js +0 -148
  98. package/dist/controllers/script_preloader.d.ts +0 -17
  99. package/dist/controllers/script_preloader.js +0 -88
  100. package/dist/index.d.ts +0 -13
  101. package/dist/index.js +0 -36
  102. package/dist/lib/README.md +0 -5
  103. package/dist/lib/base64.js +0 -1
  104. package/dist/lib/hash.js +0 -1
  105. package/dist/lib/jsSha.min.js +0 -1
  106. package/dist/lib/launch.js +0 -1
  107. package/dist/lib/qr.min.js +0 -1
  108. package/dist/lib/wapi.js +0 -2163
  109. package/dist/logging/custom_transport.d.ts +0 -9
  110. package/dist/logging/custom_transport.js +0 -35
  111. package/dist/logging/logging.d.ts +0 -50
  112. package/dist/logging/logging.js +0 -196
  113. package/dist/structures/Collector.d.ts +0 -202
  114. package/dist/structures/Collector.js +0 -391
  115. package/dist/structures/Dialog.d.ts +0 -55
  116. package/dist/structures/Dialog.js +0 -21
  117. package/dist/structures/MessageCollector.d.ts +0 -78
  118. package/dist/structures/MessageCollector.js +0 -145
  119. package/dist/structures/preProcessors.d.ts +0 -58
  120. package/dist/structures/preProcessors.js +0 -181
  121. package/dist/utils/pid_utils.d.ts +0 -1
  122. package/dist/utils/pid_utils.js +0 -26
  123. package/dist/utils/tools.d.ts +0 -152
  124. package/dist/utils/tools.js +0 -494
  125. package/tos.md +0 -77
@@ -1,540 +0,0 @@
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 (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.setupSocketServer = exports.setupBotPressHandler = exports.setupChatwoot = exports.setupTwilioCompatibleWebhook = exports.setupTunnel = exports.setupMediaMiddleware = exports.listListeners = exports.getCommands = exports.setupMetaProcessMiddleware = exports.setupRefocusDisengageMiddleware = exports.setupSwaggerStatsMiddleware = exports.setupApiDocs = exports.setupAuthenticationLayer = exports.enableCORSRequests = exports.setUpExpressApp = exports.setupHttpServer = exports.server = exports.app = void 0;
39
- //@ts-ignore
40
- const express_1 = __importDefault(require("express"));
41
- const https_1 = __importDefault(require("https"));
42
- const http_1 = __importDefault(require("http"));
43
- const collections_1 = require("./collections");
44
- const express_robots_txt_1 = __importDefault(require("express-robots-txt"));
45
- const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
46
- const axios_1 = __importDefault(require("axios"));
47
- const parse_function_1 = __importDefault(require("parse-function"));
48
- const __1 = require("..");
49
- const qs_1 = __importDefault(require("qs"));
50
- const fs = __importStar(require("fs"));
51
- const xmlbuilder2_1 = require("xmlbuilder2");
52
- const chatwoot_1 = require("./integrations/chatwoot");
53
- const express_ipfilter_1 = require("express-ipfilter");
54
- const helmet_1 = __importDefault(require("helmet"));
55
- const cloudflared_1 = require("cloudflared");
56
- const child_process_1 = require("child_process");
57
- const cloudflare_1 = require("./integrations/cloudflare");
58
- exports.app = (0, express_1.default)();
59
- exports.server = http_1.default.createServer(exports.app);
60
- // will be used to clean up cloudflared tunnel
61
- let stop;
62
- const trimChatId = (chatId) => chatId.replace("@c.us", "").replace("@g.us", "");
63
- const socketListenerCallbacks = {};
64
- // const existingListeners = () => Object.keys(Object.keys(socketListenerCallbacks).flatMap(id=>Object.keys(socketListenerCallbacks[id])).reduce((acc,curr)=>{acc[curr]=true;return acc},{}))
65
- const existingListeners = [];
66
- const getCallbacks = (listener) => Object.keys(socketListenerCallbacks).flatMap(k => socketListenerCallbacks[k]).map(o => o[listener]).filter(x => x);
67
- const setupHttpServer = (cliConfig) => {
68
- //check if there is an allow IP list:
69
- if (cliConfig.allowIps) {
70
- let allowIps = cliConfig.allowIps;
71
- if (!Array.isArray(cliConfig.allowIps))
72
- allowIps = [cliConfig.allowIps];
73
- if (Array.isArray(allowIps) && allowIps.length > 0 && allowIps[0]) {
74
- console.log("Allowed IPs", allowIps);
75
- let allowIpsOptions = {
76
- mode: 'allow',
77
- forbidden: 'You are not authorized to access this page.',
78
- log: false
79
- };
80
- if (cliConfig.verbose)
81
- allowIpsOptions = Object.assign(Object.assign({}, allowIpsOptions), { logLevel: 'deny', log: true });
82
- exports.app.use((0, express_ipfilter_1.IpFilter)(allowIps, allowIpsOptions));
83
- exports.app.use((err, req, res, next) => {
84
- if (err instanceof express_ipfilter_1.IpDeniedError) {
85
- res.status(401);
86
- res.send("Access Denied");
87
- return;
88
- }
89
- next();
90
- });
91
- }
92
- }
93
- if (cliConfig.helmet) {
94
- //@ts-ignore
95
- exports.app.use((0, helmet_1.default)());
96
- }
97
- const privkey = `${process.env.PRIV || cliConfig.privkey || ""}`;
98
- const cert = `${process.env.CERT || cliConfig.cert || ""}`;
99
- if (privkey && cert) {
100
- console.log("HTTPS Mode:", privkey, cert);
101
- const privContents = fs.readFileSync(privkey);
102
- const certContents = fs.readFileSync(cert);
103
- exports.app.use((req, res, next) => {
104
- if (!req.secure && req.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") {
105
- return res.redirect('https://' + req.get('host') + req.url);
106
- }
107
- next();
108
- });
109
- if (privContents && certContents) {
110
- const options = { key: privContents, cert: certContents };
111
- exports.server = https_1.default.createServer(options, exports.app);
112
- cliConfig.https = true;
113
- return;
114
- }
115
- }
116
- exports.server = http_1.default.createServer(exports.app);
117
- };
118
- exports.setupHttpServer = setupHttpServer;
119
- const setUpExpressApp = () => {
120
- exports.app.use((0, express_robots_txt_1.default)({ UserAgent: '*', Disallow: '/' }));
121
- //@ts-ignore
122
- exports.app.use(express_1.default.json({ limit: '99mb' })); //add the limit option so we can send base64 data through the api
123
- setupMetaMiddleware();
124
- };
125
- exports.setUpExpressApp = setUpExpressApp;
126
- const enableCORSRequests = (cliConfig) => __awaiter(void 0, void 0, void 0, function* () {
127
- const { default: cors } = yield Promise.resolve().then(() => __importStar(require('cors')));
128
- exports.app.use(cors(typeof cliConfig.cors === 'object' && cliConfig.cors));
129
- });
130
- exports.enableCORSRequests = enableCORSRequests;
131
- const setupAuthenticationLayer = (cliConfig) => {
132
- exports.app.use((req, res, next) => {
133
- if (req.path === '/' && req.method === 'GET')
134
- return res.redirect('/api-docs/');
135
- if (req.path.startsWith('/api-docs') || req.path.startsWith('/swagger-stats')) {
136
- return next();
137
- }
138
- const apiKey = req.get('key') || req.get('api_key');
139
- if (req.path.includes('chatwoot') && req.query['api_key'] && req.query['api_key'] == cliConfig.key) {
140
- next();
141
- }
142
- else if (!apiKey || apiKey !== cliConfig.key) {
143
- res.status(401).json({ error: 'unauthorised' });
144
- }
145
- else {
146
- next();
147
- }
148
- });
149
- };
150
- exports.setupAuthenticationLayer = setupAuthenticationLayer;
151
- const setupApiDocs = (cliConfig) => {
152
- const swOptions = {
153
- customCss: '.opblock-description { white-space: pre-line }'
154
- };
155
- if (cliConfig.key && cliConfig.preAuthDocs) {
156
- swOptions["swaggerOptions"] = {
157
- authAction: {
158
- api_key: {
159
- name: "api_key",
160
- schema: { type: "apiKey", in: "header", name: "Authorization", description: "" },
161
- value: cliConfig.key
162
- }
163
- }
164
- };
165
- }
166
- exports.app.use('/api-docs', (req, res, next) => {
167
- if (req.originalUrl == "/api-docs")
168
- return res.redirect('api-docs/');
169
- next();
170
- }, swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup(collections_1.collections["swagger"], swOptions));
171
- /**
172
- * Redirect to api docs if no path is specified
173
- */
174
- exports.app.get('/', (req, res) => res.redirect('/api-docs'));
175
- };
176
- exports.setupApiDocs = setupApiDocs;
177
- const setupSwaggerStatsMiddleware = (cliConfig) => __awaiter(void 0, void 0, void 0, function* () {
178
- const { default: swStats } = yield Promise.resolve().then(() => __importStar(require('swagger-stats')));
179
- exports.app.use(swStats.getMiddleware({
180
- elasticsearch: process.env.elastic_url,
181
- elasticsearchUsername: process.env.elastic_un,
182
- elasticsearchPassword: process.env.elastic_pw,
183
- swaggerSpec: collections_1.collections["swagger"],
184
- authentication: !!cliConfig.key,
185
- swaggerOnly: true,
186
- onResponseFinish: function (req, res, rrr) {
187
- ['file', 'base64', 'image', 'webpBase64', 'base64', 'durl', 'thumbnail'].forEach(key => {
188
- if (req.body.args[key])
189
- req.body.args[key] = rrr.http.request.body.args[key] = req.body.args[key].slice(0, 25) || 'EMPTY';
190
- });
191
- if (rrr.http.response.code !== 200 && rrr.http.response.code !== 404) {
192
- rrr.http.response.phrase = res.statusMessage;
193
- }
194
- },
195
- onAuthenticate: function (req, username, password) {
196
- return ((username === "admin") && (password === cliConfig.key));
197
- }
198
- }));
199
- });
200
- exports.setupSwaggerStatsMiddleware = setupSwaggerStatsMiddleware;
201
- const setupRefocusDisengageMiddleware = (cliConfig) => __awaiter(void 0, void 0, void 0, function* () {
202
- exports.app.post('/disengage', (req, res) => {
203
- cliConfig.keepAlive = false;
204
- return res.send({
205
- result: true
206
- });
207
- });
208
- });
209
- exports.setupRefocusDisengageMiddleware = setupRefocusDisengageMiddleware;
210
- const setupMetaMiddleware = () => {
211
- /**
212
- * Collection getter
213
- */
214
- exports.app.get("/meta/:collectiontype", (req, res) => {
215
- const types = Object.keys(collections_1.collections);
216
- const coltype = req.params.collectiontype.replace('.json', '');
217
- if (!coltype)
218
- return res.status(400).send("collection type missing");
219
- if (!types.includes(coltype))
220
- return res.status(404).send(`collection ${coltype} not found`);
221
- return res.send(collections_1.collections[coltype.replace('.json', '')]);
222
- });
223
- /**
224
- * Basic
225
- */
226
- exports.app.get("/meta/basic/commands", (_, res) => res.send((0, exports.getCommands)()));
227
- exports.app.get("/meta/basic/listeners", (_, res) => res.send((0, exports.listListeners)()));
228
- /**
229
- * If you want to list the list of all languages GET https://codegen.openwa.dev/api/gen/clients
230
- *
231
- * See here for request body: https://github.com/swagger-api/swagger-codegen#online-generators
232
- */
233
- exports.app.post("/meta/codegen/:language", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
234
- if (!req.params.language)
235
- return res.status(400).send({
236
- error: `language parameter missing`
237
- });
238
- try {
239
- if (!collections_1.collections["swagger"])
240
- return res.status(404).send(`collection not found`);
241
- const codeGenResponse = yield axios_1.default.post(`https://codegen.openwa.dev/api/gen/clients/${req.params.language}`, Object.assign(Object.assign({}, (req.body || {})), { spec: Object.assign({}, collections_1.collections["swagger"]) }));
242
- return res.send(codeGenResponse.data);
243
- }
244
- catch (error) {
245
- return res.status(400).send({
246
- error: error.message
247
- });
248
- }
249
- }));
250
- };
251
- const setupMetaProcessMiddleware = (client, cliConfig) => {
252
- /**
253
- * Kill the client. End the process.
254
- */
255
- let closing = false;
256
- const nuke = (req, res, restart) => __awaiter(void 0, void 0, void 0, function* () {
257
- res.set("Connection", "close");
258
- res.send(closing ? `Already closing! Stop asking!!` : 'Closing after connections closed. Waiting max 5 seconds');
259
- res.end();
260
- res.connection.end();
261
- res.connection.destroy();
262
- if (closing)
263
- return;
264
- closing = true;
265
- yield client.kill("API_KILL");
266
- __1.log.info("Waiting for maximum ");
267
- if (stop && typeof stop === 'function')
268
- stop();
269
- yield Promise.race([
270
- new Promise((resolve) => exports.server.close(() => {
271
- console.log('Server closed');
272
- resolve(true);
273
- })),
274
- new Promise(resolve => setTimeout(resolve, 5000, 'timeout'))
275
- ]);
276
- if (process.env.pm_id && process.env.PM2_USAGE) {
277
- const cmd = `pm2 ${restart ? 'restart' : 'stop'} ${process.env.pm_id}`;
278
- __1.log.info(`PM2 DETECTED, RUNNING COMMAND: ${cmd}`);
279
- const cmda = cmd.split(' ');
280
- (0, child_process_1.spawn)(cmda[0], cmda.splice(1), { stdio: 'inherit' });
281
- }
282
- else {
283
- if (restart)
284
- setTimeout(function () {
285
- process.on("exit", function () {
286
- (0, child_process_1.spawn)(process.argv.shift(), process.argv, {
287
- cwd: process.cwd(),
288
- detached: true,
289
- stdio: "inherit"
290
- });
291
- });
292
- process.exit();
293
- }, 5000);
294
- else
295
- process.exit(restart ? 0 : 10);
296
- }
297
- });
298
- /**
299
- * Exit code 10 will prevent pm2 process from auto-restarting
300
- */
301
- exports.app.post('/meta/process/exit', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
302
- return yield nuke(req, res, false);
303
- }));
304
- /**
305
- * Will only restart if the process is managed by pm2
306
- *
307
- * Note: Only works when `--pm2` flag is enabled.
308
- */
309
- exports.app.post('/meta/process/restart', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
310
- return yield nuke(req, res, true);
311
- }));
312
- };
313
- exports.setupMetaProcessMiddleware = setupMetaProcessMiddleware;
314
- const getCommands = () => Object.entries(collections_1.collections['swagger'].paths).reduce((acc, [key, value]) => { var _a, _b, _c, _d; acc[key.replace("/", "")] = ((_d = (_c = (_b = (_a = value === null || value === void 0 ? void 0 : value.post) === null || _a === void 0 ? void 0 : _a.requestBody) === null || _b === void 0 ? void 0 : _b.content["application/json"]) === null || _c === void 0 ? void 0 : _c.example) === null || _d === void 0 ? void 0 : _d.args) || {}; return acc; }, {});
315
- exports.getCommands = getCommands;
316
- const listListeners = () => {
317
- return Object.keys(__1.SimpleListener).map(eventKey => __1.SimpleListener[eventKey]);
318
- };
319
- exports.listListeners = listListeners;
320
- const setupMediaMiddleware = () => {
321
- exports.app.use("/media", express_1.default.static('media'));
322
- };
323
- exports.setupMediaMiddleware = setupMediaMiddleware;
324
- const setupTunnel = (cliConfig, PORT) => __awaiter(void 0, void 0, void 0, function* () {
325
- const cfT = cliConfig.cfTunnelHostDomain ? yield (0, cloudflare_1.createCustomDomainTunnel)(cliConfig, PORT) : (0, cloudflared_1.tunnel)({ "--url": `localhost:${PORT}` });
326
- stop = cfT.stop;
327
- const url = yield cfT.url;
328
- const conns = yield Promise.all(cfT.connections);
329
- __1.log.info(`Connections Ready! ${JSON.stringify(conns, null, 2)}`);
330
- cliConfig.apiHost = cliConfig.tunnel = url;
331
- return url;
332
- });
333
- exports.setupTunnel = setupTunnel;
334
- const setupTwilioCompatibleWebhook = (cliConfig, client) => {
335
- const url = cliConfig.twilioWebhook;
336
- client.onMessage((message) => __awaiter(void 0, void 0, void 0, function* () {
337
- var _a;
338
- const waId = trimChatId(message.from);
339
- const fd = {};
340
- fd["To"] = `whatsapp:${trimChatId(message.to)}`;
341
- fd["AccountSid"] = trimChatId(message.to);
342
- fd["WaId"] = waId;
343
- fd["ProfileName"] = ((_a = message === null || message === void 0 ? void 0 : message.chat) === null || _a === void 0 ? void 0 : _a.formattedTitle) || "";
344
- fd["SmsSid"] = message.id;
345
- fd["SmsMessageSid"] = message.id;
346
- fd["MessageSid"] = message.id;
347
- fd["NumSegments"] = "1";
348
- fd["NumSegments"] = "1";
349
- fd["Body"] = message.loc || message.body || message.caption || "";
350
- fd["From"] = `whatsapp:${waId}`;
351
- if (message.mimetype) {
352
- fd["MediaContentType0"] = message.mimetype || "";
353
- fd["MediaUrl0"] = message.cloudUrl || "";
354
- fd["NumMedia"] = "1";
355
- }
356
- if (message.lat) {
357
- fd["Latitude"] = message.lat || "";
358
- fd["Longitude"] = message.lng || "";
359
- }
360
- try {
361
- const { data } = yield (0, axios_1.default)({
362
- method: 'post',
363
- url,
364
- data: qs_1.default.stringify(fd),
365
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
366
- });
367
- const obj = (0, xmlbuilder2_1.convert)(data, { format: "object" });
368
- const msg = obj.Response.Message;
369
- // const toId : string = msg['@to'].match(/\d*/g).filter(x=>x).join("-");
370
- // const to = `${toId}@${toId.includes("-") ? 'g' : 'c'}.us` as ChatId
371
- if (msg.Media) {
372
- return yield client.sendFile(message.from, msg.Media, `file.${msg.Media.split(/[#?]/)[0].split('.').pop().trim()}`, msg['#'] || "");
373
- }
374
- return yield client.sendText(message.from, msg['#']);
375
- }
376
- catch (error) {
377
- __1.log.error("TWILIO-COMPAT WEBHOOK ERROR", url, error.message);
378
- }
379
- }));
380
- };
381
- exports.setupTwilioCompatibleWebhook = setupTwilioCompatibleWebhook;
382
- const setupChatwoot = (cliConfig, client) => __awaiter(void 0, void 0, void 0, function* () {
383
- exports.app.post('/chatwoot', (0, chatwoot_1.chatwootMiddleware)(cliConfig, client));
384
- exports.app.post(`/chatwoot/checkWebhook`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
385
- const { body } = req;
386
- __1.log.info(`chatwoot webhook check request received: ${body.checkCode}`);
387
- yield __1.ev.emitAsync(chatwoot_1.chatwoot_webhook_check_event_name, body);
388
- return res.send({});
389
- }));
390
- // await setupChatwootOutgoingMessageHandler(cliConfig, client);
391
- });
392
- exports.setupChatwoot = setupChatwoot;
393
- const setupBotPressHandler = (cliConfig, client) => {
394
- const u = cliConfig.botPressUrl;
395
- const sendBotPressMessage = (text, chatId, message) => __awaiter(void 0, void 0, void 0, function* () {
396
- const url = `${u.split("/").slice(0, u.split("/").findIndex(x => x == "converse")).join("/")}/converse/${chatId.replace("@c.us", "").replace("@g.us", "")}`;
397
- try {
398
- const { data } = yield axios_1.default.post(url, {
399
- "type": "text",
400
- text,
401
- metadata: message
402
- });
403
- const { responses } = data;
404
- return yield Promise.all(responses.filter(({ type }) => type != "typing").map((response) => {
405
- if (response.type == "text") {
406
- response.text = response.variations ? (response.variations.concat(response.text))[Math.floor(Math.random() * (response.variations.length + 1))] : response.text;
407
- return client.sendText(chatId, response.text);
408
- }
409
- if (response.type == "file") {
410
- return client.sendFile(chatId, response.url, `file.${response.url.split(/[#?]/)[0].split('.').pop().trim()}`, response.title || "");
411
- }
412
- if (response.type == "image") {
413
- return client.sendFile(chatId, response.image, `file.${response.image.split(/[#?]/)[0].split('.').pop().trim()}`, response.title || "");
414
- }
415
- if (response.type == "single-choice") {
416
- if (response["choices"] && response["choices"].length >= 1 && response["choices"].length <= 3) {
417
- return client.sendButtons(chatId, response.text, response["choices"].map(qr => {
418
- return {
419
- id: qr.value,
420
- text: qr.title
421
- };
422
- }), "");
423
- }
424
- }
425
- if (response.type == "quick_replies") {
426
- if (response["quick_replies"] && response["quick_replies"].length >= 1 && response["quick_replies"].length <= 3) {
427
- return client.sendButtons(chatId, response.wrapped.text, response["quick_replies"].map(qr => {
428
- return {
429
- id: qr.payload,
430
- text: qr.title
431
- };
432
- }), "");
433
- }
434
- }
435
- }));
436
- }
437
- catch (error) {
438
- console.error("BOTPRESS API ERROR", url, error.message);
439
- }
440
- });
441
- client.onMessage((message) => __awaiter(void 0, void 0, void 0, function* () {
442
- let text = message.body;
443
- switch (message.type) {
444
- case 'location':
445
- text = `${message.lat},${message.lng}`;
446
- break;
447
- case 'buttons_response':
448
- text = message.selectedButtonId;
449
- break;
450
- case 'document':
451
- case 'image':
452
- case 'audio':
453
- case 'ptt':
454
- case 'video':
455
- if (message.cloudUrl)
456
- text = message.cloudUrl;
457
- break;
458
- default:
459
- text = message.body || "__UNHANDLED__";
460
- break;
461
- }
462
- yield sendBotPressMessage(text, message.from, message);
463
- }));
464
- };
465
- exports.setupBotPressHandler = setupBotPressHandler;
466
- const setupSocketServer = (cliConfig, client) => __awaiter(void 0, void 0, void 0, function* () {
467
- const { Server } = yield Promise.resolve().then(() => __importStar(require("socket.io")));
468
- const socketServerOptions = cliConfig.cors ? {
469
- cors: typeof cliConfig.cors === 'object' ? cliConfig.cors : {
470
- origin: "*",
471
- methods: ["GET", "POST"],
472
- },
473
- } : null;
474
- const io = socketServerOptions ? new Server(exports.server, socketServerOptions) : new Server(exports.server);
475
- if (cliConfig.key) {
476
- io.use((socket, next) => {
477
- if (socket.handshake.auth["apiKey"] == cliConfig.key)
478
- next();
479
- else
480
- next(new Error("Authentication error"));
481
- });
482
- }
483
- io.on("connection", (socket) => {
484
- console.log("Connected to socket:", socket.id);
485
- socket.on('disconnect', (reason) => {
486
- console.log(`Socket ${socket.id} ~ reason: ${reason}`);
487
- socketListenerCallbacks[socket.id] = {};
488
- });
489
- socket.onAny((m, ...args) => __awaiter(void 0, void 0, void 0, function* () {
490
- __1.log.info("🔌", m);
491
- if (m === "register_ev") {
492
- __1.ev.onAny((event, value) => socket.emit(event, value));
493
- }
494
- const callbacks = args.filter(arg => typeof arg === "function");
495
- const objs = args.filter(arg => typeof arg === "object");
496
- if (m === "node_red_init_call") {
497
- if (!collections_1.collections['swagger'])
498
- return callbacks[0]();
499
- return callbacks[0]((0, exports.getCommands)());
500
- }
501
- if (m === "node_red_init_listen") {
502
- return callbacks[0]((0, exports.listListeners)());
503
- }
504
- if (client[m]) {
505
- if (m.startsWith("on") && callbacks[0]) {
506
- //there should only be one instance of the socket callback per listener
507
- if (!socketListenerCallbacks[socket.id])
508
- socketListenerCallbacks[socket.id] = {};
509
- const callback = x => socket.emit(m, x);
510
- let listenerSet = true;
511
- if (!existingListeners.includes(m)) {
512
- listenerSet = yield client[m]((data) => __awaiter(void 0, void 0, void 0, function* () { return Promise.all(getCallbacks(m).map(fn => fn(data))); }));
513
- existingListeners.push(m);
514
- }
515
- callbacks[0](listenerSet);
516
- socketListenerCallbacks[socket.id][m] = callback;
517
- }
518
- else {
519
- let { args } = objs[0];
520
- if (args && !Array.isArray(args))
521
- args = (0, parse_function_1.default)().parse(client[m]).args.map(argName => args[argName]);
522
- else if (!args)
523
- args = [];
524
- try {
525
- const data = yield client[m](...args);
526
- callbacks[0](data);
527
- }
528
- catch (error) {
529
- callbacks[0]({ error: {
530
- message: error.message,
531
- stack: error.stack || ""
532
- } });
533
- }
534
- }
535
- }
536
- return;
537
- }));
538
- });
539
- });
540
- exports.setupSocketServer = setupSocketServer;
@@ -1,30 +0,0 @@
1
- import meow, { AnyFlags } from 'meow';
2
- import { Merge, JsonObject } from 'type-fest';
3
- import { ConfigObject } from '../api/model/config';
4
- import { Spin } from '../controllers/events';
5
- export declare const optionKeys: string[];
6
- export declare const optionKeysWithDefalts: string[];
7
- export declare const PrimitiveConverter: {
8
- Number: number;
9
- Boolean: boolean;
10
- String: string;
11
- };
12
- export declare const cliOptionNames: import("type-fest").Simplify<import("type-fest/source/merge").Merge_<import("type-fest").Simplify<import("type-fest/source/merge").Merge_<{
13
- name?: string;
14
- description?: string;
15
- typeLabel?: string;
16
- }, meow.AnyFlag>>, {
17
- type?: StringConstructor | BooleanConstructor | NumberConstructor;
18
- }>>;
19
- export declare const meowFlags: () => AnyFlags;
20
- export declare const helptext: string;
21
- export declare const envArgs: () => JsonObject;
22
- export declare const configFile: (config?: string) => Promise<JsonObject>;
23
- export declare const cli: () => Promise<{
24
- createConfig: ConfigObject;
25
- cliConfig: Merge<ConfigObject, {
26
- [k: string]: any;
27
- }>;
28
- PORT: number;
29
- spinner: Spin;
30
- }>;