waengine 1.7.3 → 1.7.4

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.
@@ -0,0 +1,538 @@
1
+ import { getStorage } from "./storage.js";
2
+ import crypto from 'crypto';
3
+
4
+ export class CrossPlatformIntegration {
5
+ constructor(client) {
6
+ this.client = client;
7
+ this.storage = getStorage();
8
+ this.platforms = new Map();
9
+ this.webhooks = new Map();
10
+ this.apiEndpoints = new Map();
11
+ this.syncQueue = [];
12
+
13
+ this.initializePlatforms();
14
+ }
15
+
16
+ // ===== PLATFORM INITIALIZATION =====
17
+
18
+ initializePlatforms() {
19
+ // Supported platforms
20
+ this.supportedPlatforms = [
21
+ 'telegram', 'discord', 'slack', 'teams', 'facebook',
22
+ 'instagram', 'twitter', 'email', 'sms', 'web'
23
+ ];
24
+
25
+ // Load existing platform configurations
26
+ this.loadPlatformConfigs();
27
+ }
28
+
29
+ loadPlatformConfigs() {
30
+ const configs = this.storage.read.from("crossplatform").get("platforms") || {};
31
+
32
+ Object.entries(configs).forEach(([platform, config]) => {
33
+ this.platforms.set(platform, {
34
+ ...config,
35
+ status: 'disconnected',
36
+ lastSync: null
37
+ });
38
+ });
39
+ }
40
+
41
+ // ===== PLATFORM MANAGEMENT =====
42
+
43
+ /**
44
+ * Add platform integration
45
+ */
46
+ async addPlatform(platform, config) {
47
+ if (!this.supportedPlatforms.includes(platform)) {
48
+ throw new Error(`Platform ${platform} not supported`);
49
+ }
50
+
51
+ const platformConfig = {
52
+ platform,
53
+ ...config,
54
+ status: 'connected',
55
+ addedAt: Date.now(),
56
+ lastSync: null
57
+ };
58
+
59
+ this.platforms.set(platform, platformConfig);
60
+ this.storage.write.in("crossplatform").set(`platforms.${platform}`, platformConfig);
61
+
62
+ // Initialize platform-specific handlers
63
+ await this.initializePlatformHandlers(platform, config);
64
+
65
+ return platformConfig;
66
+ }
67
+
68
+ /**
69
+ * Remove platform integration
70
+ */
71
+ async removePlatform(platform) {
72
+ this.platforms.delete(platform);
73
+ this.storage.delete.from("crossplatform").key(`platforms.${platform}`);
74
+
75
+ // Clean up webhooks and endpoints
76
+ this.webhooks.delete(platform);
77
+ this.apiEndpoints.delete(platform);
78
+
79
+ return true;
80
+ }
81
+
82
+ /**
83
+ * Get platform status
84
+ */
85
+ getPlatformStatus(platform) {
86
+ return this.platforms.get(platform) || null;
87
+ }
88
+
89
+ /**
90
+ * List all platforms
91
+ */
92
+ listPlatforms() {
93
+ return Array.from(this.platforms.entries()).map(([name, config]) => ({
94
+ name,
95
+ status: config.status,
96
+ lastSync: config.lastSync,
97
+ addedAt: config.addedAt
98
+ }));
99
+ }
100
+
101
+ // ===== MESSAGE SYNCHRONIZATION =====
102
+
103
+ /**
104
+ * Sync message to all platforms
105
+ */
106
+ async syncMessage(message, options = {}) {
107
+ const activePlatforms = Array.from(this.platforms.entries())
108
+ .filter(([, config]) => config.status === 'connected');
109
+
110
+ const syncPromises = activePlatforms.map(([platform, config]) =>
111
+ this.syncToPlatform(platform, message, options)
112
+ );
113
+
114
+ const results = await Promise.allSettled(syncPromises);
115
+
116
+ // Log sync results
117
+ results.forEach((result, index) => {
118
+ const [platform] = activePlatforms[index];
119
+ if (result.status === 'fulfilled') {
120
+ this.updateLastSync(platform);
121
+ } else {
122
+ console.error(`❌ Sync to ${platform} failed:`, result.reason);
123
+ }
124
+ });
125
+
126
+ return results;
127
+ }
128
+
129
+ /**
130
+ * Sync to specific platform
131
+ */
132
+ async syncToPlatform(platform, message, options) {
133
+ const config = this.platforms.get(platform);
134
+ if (!config) throw new Error(`Platform ${platform} not configured`);
135
+
136
+ switch (platform) {
137
+ case 'telegram':
138
+ return await this.syncToTelegram(message, config, options);
139
+ case 'discord':
140
+ return await this.syncToDiscord(message, config, options);
141
+ case 'slack':
142
+ return await this.syncToSlack(message, config, options);
143
+ case 'email':
144
+ return await this.syncToEmail(message, config, options);
145
+ case 'web':
146
+ return await this.syncToWeb(message, config, options);
147
+ default:
148
+ return await this.syncViaWebhook(platform, message, config, options);
149
+ }
150
+ }
151
+
152
+ // ===== PLATFORM-SPECIFIC SYNC METHODS =====
153
+
154
+ async syncToTelegram(message, config, options) {
155
+ const telegramMessage = this.formatForTelegram(message);
156
+
157
+ const response = await fetch(`https://api.telegram.org/bot${config.botToken}/sendMessage`, {
158
+ method: 'POST',
159
+ headers: { 'Content-Type': 'application/json' },
160
+ body: JSON.stringify({
161
+ chat_id: config.chatId,
162
+ text: telegramMessage.text,
163
+ parse_mode: 'Markdown'
164
+ })
165
+ });
166
+
167
+ return await response.json();
168
+ }
169
+
170
+ async syncToDiscord(message, config, options) {
171
+ const discordMessage = this.formatForDiscord(message);
172
+
173
+ const response = await fetch(config.webhookUrl, {
174
+ method: 'POST',
175
+ headers: { 'Content-Type': 'application/json' },
176
+ body: JSON.stringify({
177
+ content: discordMessage.text,
178
+ username: config.username || 'WAEngine Bot'
179
+ })
180
+ });
181
+
182
+ return response.ok;
183
+ }
184
+
185
+ async syncToSlack(message, config, options) {
186
+ const slackMessage = this.formatForSlack(message);
187
+
188
+ const response = await fetch(config.webhookUrl, {
189
+ method: 'POST',
190
+ headers: { 'Content-Type': 'application/json' },
191
+ body: JSON.stringify({
192
+ text: slackMessage.text,
193
+ channel: config.channel,
194
+ username: config.username || 'WAEngine Bot'
195
+ })
196
+ });
197
+
198
+ return response.ok;
199
+ }
200
+
201
+ async syncToEmail(message, config, options) {
202
+ // Simplified email sync (would need proper email service integration)
203
+ const emailData = {
204
+ to: config.recipients,
205
+ subject: `WhatsApp Message from ${message.sender}`,
206
+ body: this.formatForEmail(message),
207
+ timestamp: Date.now()
208
+ };
209
+
210
+ // Store for email service to process
211
+ this.storage.write.in("crossplatform").push("emailQueue", emailData);
212
+
213
+ return { queued: true, emailData };
214
+ }
215
+
216
+ async syncToWeb(message, config, options) {
217
+ const webMessage = this.formatForWeb(message);
218
+
219
+ // Store for web dashboard
220
+ this.storage.write.in("crossplatform").push(`web.${config.dashboardId}.messages`, {
221
+ ...webMessage,
222
+ timestamp: Date.now()
223
+ });
224
+
225
+ // Emit to websocket if configured
226
+ if (config.websocketUrl) {
227
+ // Would emit to websocket here
228
+ }
229
+
230
+ return { stored: true, webMessage };
231
+ }
232
+
233
+ async syncViaWebhook(platform, message, config, options) {
234
+ if (!config.webhookUrl) {
235
+ throw new Error(`No webhook URL configured for ${platform}`);
236
+ }
237
+
238
+ const formattedMessage = this.formatForGeneric(message);
239
+
240
+ const response = await fetch(config.webhookUrl, {
241
+ method: 'POST',
242
+ headers: {
243
+ 'Content-Type': 'application/json',
244
+ 'User-Agent': 'WAEngine-CrossPlatform/1.0'
245
+ },
246
+ body: JSON.stringify({
247
+ platform: 'whatsapp',
248
+ message: formattedMessage,
249
+ timestamp: Date.now()
250
+ })
251
+ });
252
+
253
+ return await response.json();
254
+ }
255
+
256
+ // ===== MESSAGE FORMATTING =====
257
+
258
+ formatForTelegram(message) {
259
+ return {
260
+ text: `*WhatsApp Message*\n\n` +
261
+ `From: ${message.sender}\n` +
262
+ `Message: ${message.text}\n` +
263
+ `Time: ${new Date().toLocaleString()}`
264
+ };
265
+ }
266
+
267
+ formatForDiscord(message) {
268
+ return {
269
+ text: `**WhatsApp Message**\n\n` +
270
+ `**From:** ${message.sender}\n` +
271
+ `**Message:** ${message.text}\n` +
272
+ `**Time:** ${new Date().toLocaleString()}`
273
+ };
274
+ }
275
+
276
+ formatForSlack(message) {
277
+ return {
278
+ text: `*WhatsApp Message*\n\n` +
279
+ `*From:* ${message.sender}\n` +
280
+ `*Message:* ${message.text}\n` +
281
+ `*Time:* ${new Date().toLocaleString()}`
282
+ };
283
+ }
284
+
285
+ formatForEmail(message) {
286
+ return `
287
+ <h2>WhatsApp Message</h2>
288
+ <p><strong>From:</strong> ${message.sender}</p>
289
+ <p><strong>Message:</strong> ${message.text}</p>
290
+ <p><strong>Time:</strong> ${new Date().toLocaleString()}</p>
291
+ <p><strong>Chat:</strong> ${message.isGroup ? 'Group' : 'Private'}</p>
292
+ `;
293
+ }
294
+
295
+ formatForWeb(message) {
296
+ return {
297
+ id: `msg_${Date.now()}`,
298
+ sender: message.sender,
299
+ text: message.text,
300
+ isGroup: message.isGroup,
301
+ chatId: message.chatId,
302
+ timestamp: Date.now(),
303
+ platform: 'whatsapp'
304
+ };
305
+ }
306
+
307
+ formatForGeneric(message) {
308
+ return {
309
+ sender: message.sender,
310
+ text: message.text,
311
+ isGroup: message.isGroup,
312
+ chatId: message.chatId,
313
+ timestamp: Date.now(),
314
+ type: message.type || 'text'
315
+ };
316
+ }
317
+
318
+ // ===== WEBHOOK MANAGEMENT =====
319
+
320
+ /**
321
+ * Register webhook for platform
322
+ */
323
+ registerWebhook(platform, url, secret = null) {
324
+ this.webhooks.set(platform, {
325
+ url,
326
+ secret,
327
+ registeredAt: Date.now()
328
+ });
329
+
330
+ this.storage.write.in("crossplatform").set(`webhooks.${platform}`, {
331
+ url,
332
+ secret,
333
+ registeredAt: Date.now()
334
+ });
335
+
336
+ return true;
337
+ }
338
+
339
+ /**
340
+ * Handle incoming webhook
341
+ */
342
+ async handleWebhook(platform, data, signature = null) {
343
+ const webhook = this.webhooks.get(platform);
344
+ if (!webhook) {
345
+ throw new Error(`No webhook registered for ${platform}`);
346
+ }
347
+
348
+ // Verify signature if secret is set
349
+ if (webhook.secret && signature) {
350
+ const isValid = this.verifyWebhookSignature(data, signature, webhook.secret);
351
+ if (!isValid) {
352
+ throw new Error('Invalid webhook signature');
353
+ }
354
+ }
355
+
356
+ // Process webhook data
357
+ const processedMessage = this.processWebhookData(platform, data);
358
+
359
+ // Emit to WhatsApp if configured
360
+ if (processedMessage && this.client) {
361
+ await this.forwardToWhatsApp(processedMessage);
362
+ }
363
+
364
+ return processedMessage;
365
+ }
366
+
367
+ /**
368
+ * Verify webhook signature
369
+ */
370
+ verifyWebhookSignature(data, signature, secret) {
371
+ // Simplified signature verification
372
+ const expectedSignature = crypto
373
+ .createHmac('sha256', secret)
374
+ .update(JSON.stringify(data))
375
+ .digest('hex');
376
+
377
+ return signature === expectedSignature;
378
+ }
379
+
380
+ /**
381
+ * Process webhook data
382
+ */
383
+ processWebhookData(platform, data) {
384
+ // Platform-specific data processing
385
+ switch (platform) {
386
+ case 'telegram':
387
+ return this.processTelegramWebhook(data);
388
+ case 'discord':
389
+ return this.processDiscordWebhook(data);
390
+ case 'slack':
391
+ return this.processSlackWebhook(data);
392
+ default:
393
+ return this.processGenericWebhook(data);
394
+ }
395
+ }
396
+
397
+ processTelegramWebhook(data) {
398
+ if (data.message) {
399
+ return {
400
+ platform: 'telegram',
401
+ sender: data.message.from.username || data.message.from.first_name,
402
+ text: data.message.text,
403
+ timestamp: data.message.date * 1000,
404
+ originalData: data
405
+ };
406
+ }
407
+ return null;
408
+ }
409
+
410
+ processDiscordWebhook(data) {
411
+ return {
412
+ platform: 'discord',
413
+ sender: data.author?.username || 'Unknown',
414
+ text: data.content,
415
+ timestamp: Date.now(),
416
+ originalData: data
417
+ };
418
+ }
419
+
420
+ processSlackWebhook(data) {
421
+ return {
422
+ platform: 'slack',
423
+ sender: data.user_name || 'Unknown',
424
+ text: data.text,
425
+ timestamp: Date.now(),
426
+ originalData: data
427
+ };
428
+ }
429
+
430
+ processGenericWebhook(data) {
431
+ return {
432
+ platform: 'generic',
433
+ sender: data.sender || 'Unknown',
434
+ text: data.message || data.text || '',
435
+ timestamp: data.timestamp || Date.now(),
436
+ originalData: data
437
+ };
438
+ }
439
+
440
+ // ===== WHATSAPP FORWARDING =====
441
+
442
+ /**
443
+ * Forward message to WhatsApp
444
+ */
445
+ async forwardToWhatsApp(message) {
446
+ const config = this.storage.read.from("crossplatform").get("whatsappForwarding");
447
+ if (!config || !config.enabled) return;
448
+
449
+ const targetChat = config.targetChat;
450
+ if (!targetChat) return;
451
+
452
+ const forwardText = `📱 **${message.platform.toUpperCase()} Message**\n\n` +
453
+ `👤 From: ${message.sender}\n` +
454
+ `💬 Message: ${message.text}\n` +
455
+ `🕐 Time: ${new Date(message.timestamp).toLocaleString()}`;
456
+
457
+ await this.client.socket.sendMessage(targetChat, { text: forwardText });
458
+ }
459
+
460
+ // ===== UTILITY METHODS =====
461
+
462
+ updateLastSync(platform) {
463
+ const config = this.platforms.get(platform);
464
+ if (config) {
465
+ config.lastSync = Date.now();
466
+ this.platforms.set(platform, config);
467
+ this.storage.write.in("crossplatform").set(`platforms.${platform}.lastSync`, config.lastSync);
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Get cross-platform statistics
473
+ */
474
+ getCrossPlatformStats() {
475
+ const platforms = this.listPlatforms();
476
+ const webhooks = Array.from(this.webhooks.keys());
477
+ const emailQueue = this.storage.read.from("crossplatform").get("emailQueue") || [];
478
+
479
+ return {
480
+ platforms: {
481
+ total: platforms.length,
482
+ connected: platforms.filter(p => p.status === 'connected').length,
483
+ list: platforms
484
+ },
485
+ webhooks: {
486
+ total: webhooks.length,
487
+ list: webhooks
488
+ },
489
+ sync: {
490
+ queueSize: this.syncQueue.length,
491
+ emailQueue: emailQueue.length,
492
+ lastSync: Math.max(...platforms.map(p => p.lastSync || 0))
493
+ }
494
+ };
495
+ }
496
+
497
+ /**
498
+ * Test platform connection
499
+ */
500
+ async testPlatformConnection(platform) {
501
+ const config = this.platforms.get(platform);
502
+ if (!config) {
503
+ throw new Error(`Platform ${platform} not configured`);
504
+ }
505
+
506
+ try {
507
+ const testMessage = {
508
+ sender: 'WAEngine Test',
509
+ text: 'Connection test message',
510
+ isGroup: false,
511
+ chatId: 'test'
512
+ };
513
+
514
+ await this.syncToPlatform(platform, testMessage, { test: true });
515
+
516
+ config.status = 'connected';
517
+ this.platforms.set(platform, config);
518
+
519
+ return { success: true, platform, status: 'connected' };
520
+ } catch (error) {
521
+ config.status = 'error';
522
+ this.platforms.set(platform, config);
523
+
524
+ return { success: false, platform, status: 'error', error: error.message };
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Export cross-platform data
530
+ */
531
+ exportData() {
532
+ return {
533
+ platforms: Object.fromEntries(this.platforms),
534
+ webhooks: Object.fromEntries(this.webhooks),
535
+ stats: this.getCrossPlatformStats()
536
+ };
537
+ }
538
+ }