-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
3769 lines (3267 loc) · 131 KB
/
background.js
File metadata and controls
3769 lines (3267 loc) · 131 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MESSENGER CRM EXTENSION - BACKGROUND SERVICE WORKER
*
* This is the main background service worker for the Messenger CRM browser extension.
* It handles communication between the web app, content scripts, and manages bulk messaging operations.
*
* KEY RESPONSIBILITIES:
* 1. Bulk Message Campaign Execution - Orchestrates sending messages to multiple contacts
* 2. Data Synchronization - Syncs contacts, tags, and templates between web app and extension
* 3. Message Routing - Routes messages between content scripts, popup, and web app
* 4. Contact Management - Handles saving and updating contact information
* 5. Extension Storage - Manages local storage of CRM data
*
* ARCHITECTURE OVERVIEW:
* - Service Worker (this file) - Background processing and message routing
* - Content Scripts - Inject functionality into Facebook/Messenger pages
* - Popup - User interface for quick actions
* - Web App Communication - Bidirectional sync with the main CRM dashboard
*
* SECURITY FEATURES:
* - Origin validation for external messages
* - Sanctum token authentication (Laravel backend)
* - Secure data storage in Chrome extension storage
*
* @version 3.0.0
* @author Messenger CRM Team
*/
// No external dependencies needed — Firebase has been fully removed
/* ===============================
SERVICE WORKER KEEP-ALIVE (MV3)
===============================
Chrome Manifest V3 service workers can be terminated after 30 seconds of inactivity.
This keep-alive mechanism prevents termination during long-running operations
like bulk messaging campaigns.
*/
let keepAlivePort;
/**
* Establishes a keep-alive connection to prevent service worker termination
* This is critical for bulk messaging operations that can take hours to complete
*/
chrome.runtime.onConnect.addListener(port => {
if (port.name === 'keepAlive') {
keepAlivePort = port;
console.log('[Background] Keep-alive connection established');
port.onDisconnect.addListener(() => {
console.log('[Background] Keep-alive connection lost');
keepAlivePort = null;
});
}
});
/**
* Maintains service worker activity by creating a port connection
* Called periodically and during long operations
*/
function stayAlive() {
if (!keepAlivePort) chrome.runtime.connect({ name: 'keepAlive' });
}
/* ===============================
DATA MIGRATION AND CLEANUP
===============================
Removes contacts with pending friend request status from storage
on startup.
*/
/**
* Clean up contacts that have pending friend request status
* These should not be in the contacts list - only accepted friends should be contacts
*/
async function cleanupPendingFriendRequestContacts() {
try {
const result = await chrome.storage.local.get(['contacts']);
let contacts = result.contacts || [];
const originalCount = contacts.length;
// Remove contacts that have pending friend request status
contacts = contacts.filter(contact => {
if (contact.friendRequestStatus && contact.friendRequestStatus.status === 'pending') {
console.log('[Background] Removing pending friend request contact:', contact.name);
return false;
}
return true;
});
const removedCount = originalCount - contacts.length;
if (removedCount > 0) {
console.log(`[Background] Cleaned up ${removedCount} pending friend request contacts`);
await chrome.storage.local.set({ contacts });
} else {
console.log('[Background] No pending friend request contacts found to clean up');
}
} catch (error) {
console.error('[Background] Error cleaning up pending friend request contacts:', error);
}
}
// Run cleanup on extension startup
cleanupPendingFriendRequestContacts();
/* ===============================
BULK SEND PROGRESS STATE
===============================
Tracks active campaign state (progress, counts, timing) and friend
request refresh state; notifyProgress() broadcasts to popup + webapp.
*/
let bulkSendProgress = {
isActive: false,
currentIndex: 0,
totalCount: 0,
successCount: 0,
failureCount: 0,
startTime: null
};
let friendRequestRefreshState = {
isActive: false,
startTime: null,
status: 'idle', // 'idle', 'checking', 'completed', 'error'
progress: '',
results: null,
error: null
};
function notifyProgress() {
// Notify popup
chrome.runtime.sendMessage({
type: 'BULK_PROGRESS_UPDATE',
progress: { ...bulkSendProgress }
}).catch(() => { /* popup closed */ });
// Also sync with webapp
syncBulkProgressToWebapp();
}
async function syncBulkProgressToWebapp() {
console.log('[Background] 🚨🚨🚨 WEBAPP SYNC: syncBulkProgressToWebapp called with progress:', bulkSendProgress);
try {
// Find webapp tabs
const tabs = await chrome.tabs.query({ url: CONFIG.WEB_APP_TAB_PATTERNS });
console.log('[Background] 🔍 Tab query results for progress sync:', {
totalTabs: tabs.length,
tabUrls: tabs.map(tab => ({ id: tab.id, url: tab.url }))
});
// Filter to include webapp urls
const webappTabs = tabs.filter(tab => tab.url);
console.log('[Background] 🎯 Filtered webapp tabs for progress sync:', {
webappTabsCount: webappTabs.length,
webappTabs: webappTabs.map(tab => ({ id: tab.id, url: tab.url })),
progressData: { ...bulkSendProgress }
});
// Send progress to each webapp tab
for (const tab of webappTabs) {
try {
await chrome.tabs.sendMessage(tab.id, {
source: 'crm-extension',
type: 'BULK_SEND_PROGRESS_UPDATE',
payload: { ...bulkSendProgress }
});
console.log('[Background] ✅ Successfully sent progress to webapp tab', tab.id);
} catch (error) {
// Tab might not have content script loaded yet
console.log('[Background] ❌ Could not sync progress to webapp tab', tab.id, 'Error:', error.message);
}
}
} catch (error) {
console.log('[Background] ❌ Error syncing progress to webapp:', error);
}
}
async function notifyWebappBulkSendStarted(data) {
console.log('[Background] 🚨🚨🚨 WEBAPP SYNC: notifyWebappBulkSendStarted called with data:', data);
try {
const tabs = await chrome.tabs.query({ url: CONFIG.WEB_APP_TAB_PATTERNS });
console.log('[Background] 🔍 Tab query results for bulk send started notification:', {
totalTabs: tabs.length,
tabUrls: tabs.map(tab => ({ id: tab.id, url: tab.url }))
});
const webappTabs = tabs.filter(tab => tab.url);
console.log('[Background] 🎯 Filtered webapp tabs for bulk send started notification:', {
webappTabsCount: webappTabs.length,
webappTabs: webappTabs.map(tab => ({ id: tab.id, url: tab.url })),
notificationData: data
});
for (const tab of webappTabs) {
try {
await chrome.tabs.sendMessage(tab.id, {
source: 'crm-extension',
type: 'BULK_SEND_STARTED',
payload: data
});
console.log('[Background] ✅ Successfully notified webapp of bulk send start on tab', tab.id);
} catch (error) {
console.log('[Background] ❌ Could not notify webapp of bulk send start on tab', tab.id, 'Error:', error.message);
}
}
} catch (error) {
console.log('[Background] ❌ Error notifying webapp of bulk send start:', error);
}
}
async function notifyWebappBulkSendComplete(stats) {
try {
const tabs = await chrome.tabs.query({ url: CONFIG.WEB_APP_TAB_PATTERNS });
const webappTabs = tabs.filter(tab => tab.url);
for (const tab of webappTabs) {
chrome.tabs.sendMessage(tab.id, {
source: 'crm-extension',
type: 'BULK_SEND_COMPLETE',
payload: stats
}).catch(() => {
console.log('[Background] Could not notify webapp of bulk send complete on tab', tab.id);
});
}
} catch (error) {
console.log('[Background] Error notifying webapp of bulk send complete:', error);
}
}
function resetProgress() {
console.log('[Background] 🔄 Resetting progress from:', bulkSendProgress);
bulkSendProgress = {
isActive: false,
currentIndex: 0,
totalCount: 0,
successCount: 0,
failureCount: 0,
startTime: null,
cancelled: false // Explicitly reset cancelled flag
};
console.log('[Background] 🔄 Progress reset to:', bulkSendProgress);
notifyProgress();
}
function notifyFriendRequestProgress() {
// Notify popup
chrome.runtime.sendMessage({
type: 'FRIEND_REQUEST_REFRESH_UPDATE',
refreshState: { ...friendRequestRefreshState }
}).catch(() => { /* popup might be closed */ });
// Also sync with webapp
syncFriendRequestProgressToWebapp();
}
async function syncFriendRequestProgressToWebapp() {
try {
// Find webapp tabs
const tabs = await chrome.tabs.query({ url: CONFIG.WEB_APP_TAB_PATTERNS });
console.log('[Background] 🔍 Tab query results for friend request progress sync:', {
totalTabs: tabs.length,
tabUrls: tabs.map(tab => ({ id: tab.id, url: tab.url }))
});
// Filter to include webapp urls
const webappTabs = tabs.filter(tab => tab.url);
console.log('[Background] 🎯 Filtered webapp tabs for friend request progress sync:', {
webappTabsCount: webappTabs.length,
webappTabs: webappTabs.map(tab => ({ id: tab.id, url: tab.url })),
refreshState: { ...friendRequestRefreshState }
});
// Send progress to each webapp tab
for (const tab of webappTabs) {
try {
await chrome.tabs.sendMessage(tab.id, {
source: 'crm-extension',
type: 'FRIEND_REQUEST_REFRESH_UPDATE',
payload: { ...friendRequestRefreshState }
});
console.log('[Background] ✅ Successfully sent friend request progress to webapp tab', tab.id);
} catch (error) {
console.log('[Background] ❌ Could not sync friend request progress to webapp tab', tab.id, 'Error:', error.message);
}
}
} catch (error) {
console.log('[Background] ❌ Error syncing friend request progress to webapp:', error);
}
}
function resetFriendRequestRefreshState() {
friendRequestRefreshState = {
isActive: false,
startTime: null,
status: 'idle',
progress: '',
results: null,
error: null
};
notifyFriendRequestProgress();
}
/* ===============================
BULK MESSAGING ENGINE
===============================
Core campaign orchestrator — opens Messenger tabs, sends messages
sequentially with configurable delay, batch size, and batch wait;
reports progress to backend campaign endpoint; handles cancellation.
*/
const sleep = ms => new Promise(r => setTimeout(r, ms));
function fillTemplate(tpl, { name }) {
const [first = '', ...rest] = (name || '').trim().split(' ');
return tpl
.replace(/\{first_name\}/gi, first)
.replace(/\{last_name\}/gi, rest.join(' '))
.replace(/\{full_name\}/gi, name);
}
/* ===============================
AUTHENTICATED API HELPER
===============================
Wrapper for fetch() that attaches Bearer token from chrome.storage,
used by all backend API calls from the service worker.
*/
async function getAuthToken() {
const result = await chrome.storage.local.get(['crmFixedJwtToken']);
return result.crmFixedJwtToken || null;
}
/**
* Wrap fetch with an AbortController timeout. MV3 service workers die at
* 5 minutes, and a hung request silently burns quota; fail fast at 30s
* so the caller's catch path runs instead.
*/
async function fetchWithTimeout(url, options = {}, timeoutMs = 30000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
/**
* If the response indicates the token is dead (401), clear stored
* credentials so stale tokens don't persist silently.
* Returns true when a 401 was handled (caller should bail early).
*/
async function handleAuthFailure(response) {
if (response && response.status === 401) {
try {
if (self.fixedJwtAuth?.clearCredentials) {
await self.fixedJwtAuth.clearCredentials();
} else {
await chrome.storage.local.remove(['crmFixedJwtToken']);
}
} catch (e) {
console.warn('[Background] Failed to clear credentials on 401:', e.message);
}
chrome.runtime.sendMessage({ type: 'AUTH_REVOKED' }).catch(() => {});
return true;
}
return false;
}
async function campaignApiCall(method, path, body) {
const token = await getAuthToken();
if (!token) return null;
try {
const res = await fetchWithTimeout(`${CONFIG.API_BASE_URL}${path}`, {
method,
headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
});
if (await handleAuthFailure(res)) return null;
if (!res.ok) return null;
return await res.json();
} catch (e) {
console.warn('[Background] Campaign API call failed:', path, e.message);
return null;
}
}
async function createAndStartCampaign(recipients, template, delaySec, selectedTagIds) {
const name = `Extension Campaign ${new Date().toLocaleString()}`;
const created = await campaignApiCall('POST', '/campaigns', {
name,
message: template,
delay: delaySec,
recipientContactIds: recipients.map(r => r.id || r.userId).filter(Boolean),
selectedTagIds: selectedTagIds || [],
totalRecipients: recipients.length,
});
if (!created?.success) return null;
const campaignId = created.data?.id;
if (!campaignId) return null;
await campaignApiCall('POST', `/campaigns/${campaignId}/start`, null);
return campaignId;
}
async function reportCampaignProgress(campaignId, currentIndex, successCount, failureCount) {
if (!campaignId) return;
await campaignApiCall('PUT', `/campaigns/${campaignId}/progress`, {
currentIndex,
successCount,
failureCount,
});
}
async function completeCampaign(campaignId, successCount, failureCount, cancelled) {
if (!campaignId) return;
await campaignApiCall('POST', `/campaigns/${campaignId}/complete`, {
status: cancelled ? 'cancelled' : 'completed',
successCount,
failureCount,
});
}
async function sendSequentially(users, template, delaySec, batchSize = 0, batchWaitMinutes = 5, campaignId = null) {
console.log('[Background] 🚀 sendSequentially called with', users.length, 'users');
console.log('[Background] Template preview:', template.substring(0, 100) + '...');
console.log('[Background] Delay between messages:', delaySec, 'seconds');
console.log('[Background] Batch settings:', { batchSize, batchWaitMinutes });
console.log('[Background] First user sample:', users[0]);
stayAlive();
bulkSendProgress = {
isActive: true,
currentIndex: 0,
totalCount: users.length,
successCount: 0,
failureCount: 0,
startTime: Date.now(),
cancelled: false,
campaignId: campaignId || null,
};
notifyProgress();
// Notify webapp that bulk send started
await notifyWebappBulkSendStarted({
totalCount: users.length,
startTime: bulkSendProgress.startTime,
template: template,
campaignId: campaignId,
});
for (let i = 0; i < users.length; i++) {
// Check if cancelled before processing each user
if (bulkSendProgress.cancelled || !bulkSendProgress.isActive) {
console.log('[Background] 🛑 Bulk send cancelled at index', i, 'cancelled flag:', bulkSendProgress.cancelled, 'isActive:', bulkSendProgress.isActive);
break;
}
const user = users[i];
bulkSendProgress.currentIndex = i + 1;
const personalMsg = fillTemplate(template, user);
let hitRateLimit = false;
try {
// Pass the entire contact object instead of just userId
await sendToUser(user, personalMsg);
bulkSendProgress.successCount++;
console.log(`[Background] ✅ Sent to ${user.name} (${user.source || 'messenger'})`);
} catch (error) {
bulkSendProgress.failureCount++;
console.error(`[Background] ❌ Failed for ${user.name}`, error);
if (error && error.rateLimited) {
hitRateLimit = true;
}
}
notifyProgress();
// Facebook 24h message-request cap hit — stop the whole campaign,
// further sends will only rack up failures and risk an account flag.
if (hitRateLimit) {
console.warn('[Background] 🛑 Rate limit detected — aborting bulk send');
bulkSendProgress.cancelled = true;
bulkSendProgress.isActive = false;
bulkSendProgress.rateLimited = true;
break;
}
// Sync progress to backend every 10 messages (for extension-initiated campaigns)
if (campaignId && bulkSendProgress.currentIndex % 10 === 0) {
reportCampaignProgress(
campaignId,
bulkSendProgress.currentIndex,
bulkSendProgress.successCount,
bulkSendProgress.failureCount
);
}
// Check cancellation again before delay
if (bulkSendProgress.cancelled || !bulkSendProgress.isActive) {
console.log('[Background] 🛑 Bulk send cancelled after sending to', user.name, 'cancelled flag:', bulkSendProgress.cancelled, 'isActive:', bulkSendProgress.isActive);
break;
}
// Regular delay between messages
if (delaySec && i < users.length - 1) {
const jitter = Math.random() * 1000;
await sleep(delaySec * 1000 + jitter);
}
// Batch waiting: if batch size is set and we've completed a batch, wait
console.log(`[Background] 🔍 Batch check: batchSize=${batchSize}, i=${i}, (i+1)%batchSize=${(i + 1) % batchSize}`);
if (batchSize && batchSize > 0 && (i + 1) % batchSize === 0 && i < users.length - 1) {
const batchNumber = Math.floor((i + 1) / batchSize);
const waitMinutes = batchWaitMinutes || 5; // Default to 5 minutes if not specified
console.log(`[Background] 📦 Completed batch ${batchNumber}, waiting ${waitMinutes} minutes...`);
console.log(`[Background] 📦 Current message: ${i + 1}/${users.length}`);
// Notify progress with batch wait status
notifyProgress();
// Wait for the specified number of minutes
const waitTimeMs = waitMinutes * 60 * 1000;
console.log(`[Background] ⏳ Sleeping for ${waitTimeMs}ms (${waitMinutes} minutes)...`);
await sleep(waitTimeMs);
console.log(`[Background] ✅ Batch wait complete, resuming sending...`);
// Check cancellation after batch wait
if (bulkSendProgress.cancelled || !bulkSendProgress.isActive) {
console.log('[Background] 🛑 Bulk send cancelled during batch wait');
break;
}
}
}
// Update final status
bulkSendProgress.isActive = false;
const wasCancelled = bulkSendProgress.cancelled;
notifyProgress();
const completionStats = {
total: bulkSendProgress.totalCount,
success: bulkSendProgress.successCount,
failed: bulkSendProgress.failureCount,
duration: Date.now() - bulkSendProgress.startTime,
cancelled: wasCancelled,
rateLimited: !!bulkSendProgress.rateLimited,
};
// Notify popup
chrome.runtime.sendMessage({
type: 'BULK_SEND_COMPLETE',
stats: completionStats
}).catch(() => {});
// Sync final counts to backend (for extension-initiated campaigns)
if (campaignId) {
await reportCampaignProgress(
campaignId,
bulkSendProgress.totalCount,
bulkSendProgress.successCount,
bulkSendProgress.failureCount
);
await completeCampaign(
campaignId,
bulkSendProgress.successCount,
bulkSendProgress.failureCount,
wasCancelled
);
}
// Notify webapp
await notifyWebappBulkSendComplete({ ...completionStats, campaignId });
}
/* ===============================
MESSENGER TAB MANAGEMENT
===============================
Opens Messenger conversation tabs and waits for page load before
injecting messages.
*/
async function sendToUser(contact, text) {
const messengerUrl = `https://www.facebook.com/messages/t/${contact.userId}`;
console.log('[Background] Opening chat URL:', messengerUrl);
const tab = await chrome.tabs.create({
url: messengerUrl,
active: false
});
await new Promise((res, rej) => {
const timeoutId = setTimeout(() => {
chrome.tabs.onUpdated.removeListener(onUpdated);
rej(new Error('Page load timeout'));
}, 30000);
const onUpdated = (id, info) => {
if (id === tab.id && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(onUpdated);
clearTimeout(timeoutId);
res();
}
};
chrome.tabs.onUpdated.addListener(onUpdated);
}).catch(err => {
console.error(`[Background] ${err.message} for ${messengerUrl}`);
chrome.tabs.remove(tab.id).catch(() => {});
throw err;
});
// Small extra delay for Lexical editor to fully initialize
await sleep(2000);
// Generate unique execution ID
const executionId = `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: realSendBackground,
args: [text, executionId, contact.userId]
});
await sleep(20000);
// Read the outcome flag set by the in-page script (e.g. rate_limit).
let sendResult = null;
try {
const [{ result } = {}] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => window.crmSendResult || null,
});
sendResult = result;
} catch (_) { /* tab may have closed — ignore */ }
chrome.tabs.remove(tab.id).catch(() => {});
if (sendResult === 'rate_limit') {
const err = new Error("Facebook message request limit reached");
err.rateLimited = true;
throw err;
}
}
/* ===============================
FRIEND REQUEST AUTOMATION
===============================
Automates sending friend requests from Facebook group pages —
clicks Add Friend buttons, handles confirmation dialogs, tracks
request status.
*/
function realSendBackground(rawText, executionId, userId) {
console.log(`[CRM Send] Script started for user ${userId}, exec: ${executionId}`, { rawText });
if (window.crmActiveExecution) {
console.log(`[CRM Send] Another execution already running, aborting ${executionId}`);
return;
}
window.crmActiveExecution = executionId;
window.crmSendResult = null;
const TIMEOUT = 20000;
const start = Date.now();
const cleanup = (reason) => {
console.log(`[CRM Send] Done (${reason}) — exec: ${executionId}`);
if (window.crmActiveExecution === executionId) window.crmActiveExecution = null;
};
// Facebook surfaces a "You've reached the message request limit" banner when
// non-friend message requests are throttled (24h limit). Detect it early so
// the bulk send can abort instead of burning through the contact list.
const detectRateLimit = () => {
try {
const text = document.body?.innerText || '';
if (/reached the message request limit/i.test(text) ||
/limit to how many requests you can send/i.test(text)) {
console.warn('[CRM Send] 🚫 Message request limit banner detected');
window.crmSendResult = 'rate_limit';
return true;
}
} catch (_) {}
return false;
};
const simulateRealClick = (element) => {
const rect = element.getBoundingClientRect();
const opts = {
bubbles: true, cancelable: true, view: window,
clientX: rect.left + rect.width / 2,
clientY: rect.top + rect.height / 2
};
element.dispatchEvent(new PointerEvent('pointerdown', { ...opts, pointerId: 1 }));
element.dispatchEvent(new MouseEvent('mousedown', opts));
element.dispatchEvent(new PointerEvent('pointerup', { ...opts, pointerId: 1 }));
element.dispatchEvent(new MouseEvent('mouseup', opts));
element.dispatchEvent(new MouseEvent('click', opts));
};
// ── Step 1: Wait for message input (with Accept/Continue button handling) ──
const waitForMessageInput = (attempt = 0) => {
if (window.crmActiveExecution !== executionId) return;
if (Date.now() - start > TIMEOUT) {
console.warn(`[CRM Send] Timeout waiting for message input`);
cleanup('timeout');
return;
}
if (detectRateLimit()) {
cleanup('rate_limit');
return;
}
console.log(`[CRM Send] Looking for message input (attempt ${attempt + 1})...`);
// Check for Accept button (message request)
if (attempt <= 2) {
let acceptBtn = document.querySelector('[aria-label="Accept"][role="button"]');
if (!acceptBtn) {
const buttons = document.querySelectorAll('div[role="button"]');
for (const btn of buttons) {
if (btn.textContent?.trim() === 'Accept') { acceptBtn = btn; break; }
}
}
if (acceptBtn) {
console.log(`[CRM Send] Found Accept button, clicking...`);
simulateRealClick(acceptBtn);
setTimeout(() => waitForMessageInput(attempt + 1), 3000);
return;
}
}
// Check for Continue button
if (attempt <= 2) {
const allButtons = document.querySelectorAll('div[role="button"], span, button');
for (const el of allButtons) {
if (el.textContent?.trim() === 'Continue') {
console.log(`[CRM Send] Found Continue button, clicking...`);
simulateRealClick(el);
setTimeout(() => waitForMessageInput(attempt + 1), 3000);
return;
}
}
}
// Look for the message input
const messageBox = document.querySelector('div[contenteditable="true"][role="textbox"]') ||
document.querySelector('div[contenteditable="true"]:not([role="button"])') ||
document.querySelector('.notranslate[contenteditable="true"]');
if (!messageBox) {
setTimeout(() => waitForMessageInput(attempt + 1), 1000);
return;
}
console.log(`[CRM Send] Found message input:`, messageBox.tagName, messageBox.className.substring(0, 50));
insertAndSend(messageBox);
};
// ── Step 2: Insert text and send ──
const insertAndSend = (messageBox) => {
// Personalize the message
let userName = 'there';
let fullName = 'there';
let lastName = '';
try {
const title = document.title || '';
let extracted = null;
if (title.includes(' | Messenger')) extracted = title.split(' | Messenger')[0].trim();
else if (title.includes('—')) extracted = title.split('—')[1]?.trim();
if (extracted && extracted !== 'Messenger' && extracted.length > 0) {
fullName = extracted;
const parts = extracted.split(' ');
userName = parts[0] || 'there';
lastName = parts.slice(1).join(' ');
}
} catch (e) {}
const message = rawText
.replace(/\{name\}/gi, userName)
.replace(/\{first_name\}/gi, userName)
.replace(/\{firstname\}/gi, userName)
.replace(/\{last_name\}/gi, lastName)
.replace(/\{lastname\}/gi, lastName)
.replace(/\{full_name\}/gi, fullName)
.replace(/\{fullname\}/gi, fullName);
console.log(`[CRM Send] Message to insert:`, message);
// Click the message box to activate Lexical focus
simulateRealClick(messageBox);
messageBox.focus();
// Wait for Lexical to register focus, then insert
setTimeout(() => {
messageBox.focus();
// Try each insertion method and verify after each
tryInsertMethods(messageBox, message, 0);
}, 500);
};
const insertMethods = [
// Method 1: execCommand (works best when tab is active and focused)
(box, msg) => {
const result = document.execCommand('insertText', false, msg);
console.log(`[CRM Send] execCommand insertText returned: ${result}, content: "${box.textContent.substring(0, 50)}"`);
return box.textContent.trim().length > 0;
},
// Method 2: Clipboard paste (works with Lexical's paste handler)
(box, msg) => {
const dt = new DataTransfer();
dt.setData('text/plain', msg);
const evt = new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: dt });
box.dispatchEvent(evt);
console.log(`[CRM Send] ClipboardEvent paste dispatched, content: "${box.textContent.substring(0, 50)}"`);
return false; // Async — check later
},
// Method 3: InputEvent beforeinput (Lexical's input handler)
(box, msg) => {
box.dispatchEvent(new InputEvent('beforeinput', {
bubbles: true, cancelable: true, inputType: 'insertText', data: msg
}));
box.dispatchEvent(new InputEvent('input', {
bubbles: true, inputType: 'insertText', data: msg
}));
console.log(`[CRM Send] beforeinput dispatched, content: "${box.textContent.substring(0, 50)}"`);
return box.textContent.trim().length > 0;
},
// Method 4: Direct DOM (last resort)
(box, msg) => {
box.innerHTML = '';
msg.split('\n').forEach(line => {
const p = document.createElement('p');
p.setAttribute('dir', 'auto');
p.appendChild(line.length > 0 ? document.createTextNode(line) : document.createElement('br'));
box.appendChild(p);
});
box.dispatchEvent(new Event('input', { bubbles: true }));
console.log(`[CRM Send] DOM fallback, content: "${box.textContent.substring(0, 50)}"`);
return box.textContent.trim().length > 0;
}
];
const tryInsertMethods = (messageBox, message, methodIndex) => {
if (methodIndex >= insertMethods.length) {
console.log(`[CRM Send] All insertion methods exhausted. Proceeding to send anyway.`);
setTimeout(() => trySend(messageBox, 0), 1000);
return;
}
console.log(`[CRM Send] Trying insertion method ${methodIndex + 1}/${insertMethods.length}...`);
try {
const immediate = insertMethods[methodIndex](messageBox, message);
if (immediate) {
console.log(`[CRM Send] Method ${methodIndex + 1} succeeded immediately!`);
setTimeout(() => trySend(messageBox, 0), 1000);
return;
}
} catch (e) {
console.log(`[CRM Send] Method ${methodIndex + 1} threw:`, e.message);
}
// Check after a delay (for async methods like paste)
setTimeout(() => {
if (messageBox.textContent.trim().length > 0) {
console.log(`[CRM Send] Method ${methodIndex + 1} succeeded after delay!`);
setTimeout(() => trySend(messageBox, 0), 1000);
} else {
console.log(`[CRM Send] Method ${methodIndex + 1} did not insert text, trying next...`);
tryInsertMethods(messageBox, message, methodIndex + 1);
}
}, 500);
};
// ── Step 3: Find and click send button ──
const trySend = (messageBox, attempt) => {
if (window.crmActiveExecution !== executionId) return;
console.log(`[CRM Send] Looking for send button (attempt ${attempt + 1}/5)...`);
let sendButton = null;
// Find SVG with "Press enter to send" title
const svgTitles = document.querySelectorAll('svg title');
for (const title of svgTitles) {
if (title.textContent?.trim().toLowerCase().includes('press enter to send')) {
let parent = title.closest('svg')?.parentElement;
while (parent && parent !== document.body) {
if (parent.getAttribute('role') === 'button' || parent.tagName === 'BUTTON') {
sendButton = parent;
break;
}
parent = parent.parentElement;
}
if (!sendButton) sendButton = title.closest('svg')?.parentElement;
break;
}
}
if (!sendButton) {
sendButton = document.querySelector('[aria-label*="Press enter to send"]') ||
document.querySelector('[aria-label*="Send"]') ||
document.querySelector('[data-testid="send-button"]');
}
if (sendButton) {
console.log(`[CRM Send] Found send button, clicking...`);
simulateRealClick(sendButton);
cleanup('message sent');
return;
}
if (attempt < 4) {
setTimeout(() => trySend(messageBox, attempt + 1), 1000);
return;
}
// Final fallback: Enter key
console.log(`[CRM Send] Send button not found, trying Enter key...`);
messageBox.focus();
const enterOpts = { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true };
messageBox.dispatchEvent(new KeyboardEvent('keydown', enterOpts));
messageBox.dispatchEvent(new KeyboardEvent('keypress', enterOpts));
messageBox.dispatchEvent(new KeyboardEvent('keyup', enterOpts));
cleanup('enter key sent');
};
// ── Start ──
// Small delay for page to settle
setTimeout(() => waitForMessageInput(0), 1500);
}
/* ===============================
FRIEND REQUEST TRACKING
===============================
Persists friend request data to chrome.storage and syncs to
backend; handles status transitions (pending -> accepted/declined);
updates associated contacts.
*/
/**
* Track a new friend request
*/
async function handleTrackFriendRequest(requestData, sendResponse) {
try {
console.log('[Background] 🤝 Tracking friend request:', requestData);
// Load existing friend requests and contacts
const result = await chrome.storage.local.get(['friendRequests', 'contacts', 'friendRequestStats']);
let friendRequests = result.friendRequests || [];
let contacts = result.contacts || [];
let stats = result.friendRequestStats || {
total: 0,
pending: 0,
accepted: 0
};
// Check if this friend request is already tracked
const existingRequest = friendRequests.find(req => req.userId === requestData.userId);
if (existingRequest) {
console.log('[Background] ⚠️ Friend request already tracked for user:', requestData.userId);
sendResponse({ success: false, error: 'Friend request already tracked' });
return;
}
// Create friend request record
const friendRequest = {
id: 'fr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
userId: requestData.userId,
name: requestData.name,
profilePicture: requestData.profilePicture,
groupId: requestData.groupId,
status: requestData.status,
sentAt: requestData.sentAt,
respondedAt: requestData.respondedAt || null,
lastChecked: new Date().toISOString()
};
// Add to friend requests
friendRequests.push(friendRequest);
// Update stats
stats.total++;
if (requestData.status === 'pending') {
stats.pending++;
}