-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
996 lines (868 loc) · 32.5 KB
/
Copy pathcontent.js
File metadata and controls
996 lines (868 loc) · 32.5 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
// Cache for user locations - persistent storage
let locationCache = new Map();
const CACHE_KEY = 'twitter_location_cache';
const CACHE_EXPIRY_DAYS = 30; // Cache for 30 days
// Rate limiting
const requestQueue = [];
let isProcessingQueue = false;
let lastRequestTime = 0;
const MIN_REQUEST_INTERVAL = 2000; // 2 seconds between requests (increased to avoid rate limits)
const MAX_CONCURRENT_REQUESTS = 2; // Reduced concurrent requests
let activeRequests = 0;
let rateLimitResetTime = 0; // Unix timestamp when rate limit resets
// Observer for dynamically loaded content
let observer = null;
// Extension enabled state
let extensionEnabled = true;
const TOGGLE_KEY = 'extension_enabled';
const DEFAULT_ENABLED = true;
// Track usernames currently being processed to avoid duplicate requests
const processingUsernames = new Set();
// Blocking settings
let blockedCountries = [];
let showFlags = true;
let hiddenCount = 0;
// Load enabled state
async function loadEnabledState() {
try {
const result = await chrome.storage.local.get([TOGGLE_KEY]);
extensionEnabled = result[TOGGLE_KEY] !== undefined ? result[TOGGLE_KEY] : DEFAULT_ENABLED;
console.log('Extension enabled:', extensionEnabled);
} catch (error) {
console.error('Error loading enabled state:', error);
extensionEnabled = DEFAULT_ENABLED;
}
}
// Load blocking settings
async function loadBlockingSettings() {
try {
const result = await chrome.storage.sync.get(['blockedCountries', 'showFlags']);
blockedCountries = result.blockedCountries || [];
showFlags = result.showFlags !== false;
console.log('Blocking settings loaded:', {blockedCountries, showFlags});
} catch (error) {
console.error('Error loading blocking settings:', error);
}
}
// Listen for settings changes from storage
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === 'sync') {
if (changes.blockedCountries) {
blockedCountries = changes.blockedCountries.newValue || [];
console.log('Blocked countries updated:', blockedCountries);
// Reprocess all tweets with new blocklist
unhideAllTweets();
setTimeout(processUsernames, 500);
}
if (changes.showFlags !== undefined) {
showFlags = changes.showFlags.newValue;
console.log('Show flags updated:', showFlags);
if (!showFlags) {
removeAllFlags();
} else {
setTimeout(processUsernames, 500);
}
}
}
});
// Listen for toggle changes from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'extensionToggle') {
extensionEnabled = request.enabled;
console.log('Extension toggled:', extensionEnabled);
if (extensionEnabled) {
// Re-initialize if enabled
setTimeout(() => {
processUsernames();
}, 500);
} else {
// Remove all flags if disabled
removeAllFlags();
}
}
});
// Load cache from persistent storage
async function loadCache() {
try {
if (!chrome.runtime?.id) return;
const result = await chrome.storage.local.get(CACHE_KEY);
if (result[CACHE_KEY]) {
const cached = result[CACHE_KEY];
const now = Date.now();
// Filter out expired entries and null entries (allow retry)
for (const [username, data] of Object.entries(cached)) {
if (data.expiry && data.expiry > now && data.location !== null) {
locationCache.set(username, data.location);
}
}
}
} catch (error) {
// Silently fail
}
}
// Save cache to persistent storage
async function saveCache() {
try {
if (!chrome.runtime?.id) return;
const cacheObj = {};
const now = Date.now();
const expiry = now + (CACHE_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
for (const [username, location] of locationCache.entries()) {
cacheObj[username] = {
location: location,
expiry: expiry,
cachedAt: now
};
}
await chrome.storage.local.set({ [CACHE_KEY]: cacheObj });
} catch (error) {
// Silently fail
}
}
// Save a single entry to cache
async function saveCacheEntry(username, location) {
if (!chrome.runtime?.id) return;
locationCache.set(username, location);
// Save immediately with debounce - only save every 500ms for performance
if (!saveCache.timeout) {
saveCache.timeout = setTimeout(async () => {
await saveCache();
saveCache.timeout = null;
}, 500);
}
}
// Inject script into page context to access fetch with proper cookies
function injectPageScript() {
const script = document.createElement('script');
script.src = chrome.runtime.getURL('pageScript.js');
script.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(script);
// Listen for rate limit info from page script
window.addEventListener('message', (event) => {
if (event.source !== window) return;
if (event.data && event.data.type === '__rateLimitInfo') {
rateLimitResetTime = event.data.resetTime;
const waitTime = event.data.waitTime;
console.log(`Rate limit detected. Will resume requests in ${Math.ceil(waitTime / 1000 / 60)} minutes`);
}
});
}
// Process request queue with rate limiting
async function processRequestQueue() {
if (isProcessingQueue || requestQueue.length === 0) {
return;
}
// Check if we're rate limited
if (rateLimitResetTime > 0) {
const now = Math.floor(Date.now() / 1000);
if (now < rateLimitResetTime) {
const waitTime = (rateLimitResetTime - now) * 1000;
console.log(`Rate limited. Waiting ${Math.ceil(waitTime / 1000 / 60)} minutes...`);
setTimeout(processRequestQueue, Math.min(waitTime, 60000)); // Check every minute max
return;
} else {
// Rate limit expired, reset
rateLimitResetTime = 0;
}
}
isProcessingQueue = true;
while (requestQueue.length > 0 && activeRequests < MAX_CONCURRENT_REQUESTS) {
const now = Date.now();
const timeSinceLastRequest = now - lastRequestTime;
// Wait if needed to respect rate limit
if (timeSinceLastRequest < MIN_REQUEST_INTERVAL) {
await new Promise(resolve => setTimeout(resolve, MIN_REQUEST_INTERVAL - timeSinceLastRequest));
}
const { screenName, resolve, reject } = requestQueue.shift();
activeRequests++;
lastRequestTime = Date.now();
// Make the request
makeLocationRequest(screenName)
.then(location => {
resolve(location);
})
.catch(error => {
reject(error);
})
.finally(() => {
activeRequests--;
// Continue processing queue
setTimeout(processRequestQueue, 200);
});
}
isProcessingQueue = false;
}
// Make actual API request
function makeLocationRequest(screenName) {
return new Promise((resolve, reject) => {
const requestId = Date.now() + Math.random();
// Listen for response via postMessage
const handler = (event) => {
// Only accept messages from the page (not from extension)
if (event.source !== window) return;
if (event.data &&
event.data.type === '__locationResponse' &&
event.data.screenName === screenName &&
event.data.requestId === requestId) {
window.removeEventListener('message', handler);
const location = event.data.location;
const isRateLimited = event.data.isRateLimited || false;
// Only cache if not rate limited (don't cache failures due to rate limiting)
if (!isRateLimited) {
saveCacheEntry(screenName, location || null);
}
resolve(location || null);
}
};
window.addEventListener('message', handler);
// Send fetch request to page script via postMessage
window.postMessage({
type: '__fetchLocation',
screenName,
requestId
}, '*');
// Timeout after 10 seconds
setTimeout(() => {
window.removeEventListener('message', handler);
resolve(null);
}, 10000);
});
}
// Function to query Twitter GraphQL API for user location (with rate limiting)
async function getUserLocation(screenName) {
// Check cache first
if (locationCache.has(screenName)) {
const cached = locationCache.get(screenName);
// Don't return cached null - retry if it was null before (might have been rate limited)
if (cached !== null) {
return cached;
} else {
// Remove from cache to allow retry
locationCache.delete(screenName);
}
}
// Queue the request
return new Promise((resolve, reject) => {
requestQueue.push({ screenName, resolve, reject });
processRequestQueue();
});
}
// Function to extract username from various Twitter UI elements
function extractUsername(element) {
// Try data-testid="UserName" or "User-Name" first (most reliable)
const usernameElement = element.querySelector('[data-testid="UserName"], [data-testid="User-Name"]');
if (usernameElement) {
const links = usernameElement.querySelectorAll('a[href^="/"]');
for (const link of links) {
const href = link.getAttribute('href');
const match = href.match(/^\/([^\/\?]+)/);
if (match && match[1]) {
const username = match[1];
// Filter out common routes
const excludedRoutes = ['home', 'explore', 'notifications', 'messages', 'i', 'compose', 'search', 'settings', 'bookmarks', 'lists', 'communities'];
if (!excludedRoutes.includes(username) &&
!username.startsWith('hashtag') &&
!username.startsWith('search') &&
username.length > 0 &&
username.length < 20) { // Usernames are typically short
return username;
}
}
}
}
// Try finding username links in the entire element (broader search)
const allLinks = element.querySelectorAll('a[href^="/"]');
const seenUsernames = new Set();
for (const link of allLinks) {
const href = link.getAttribute('href');
if (!href) continue;
const match = href.match(/^\/([^\/\?]+)/);
if (!match || !match[1]) continue;
const potentialUsername = match[1];
// Skip if we've already checked this username
if (seenUsernames.has(potentialUsername)) continue;
seenUsernames.add(potentialUsername);
// Filter out routes and invalid usernames
const excludedRoutes = ['home', 'explore', 'notifications', 'messages', 'i', 'compose', 'search', 'settings', 'bookmarks', 'lists', 'communities', 'hashtag'];
if (excludedRoutes.some(route => potentialUsername === route || potentialUsername.startsWith(route))) {
continue;
}
// Skip status/tweet links
if (potentialUsername.includes('status') || potentialUsername.match(/^\d+$/)) {
continue;
}
// Check link text/content for username indicators
const text = link.textContent?.trim() || '';
const linkText = text.toLowerCase();
const usernameLower = potentialUsername.toLowerCase();
// If link text starts with @, it's definitely a username
if (text.startsWith('@')) {
return potentialUsername;
}
// If link text matches the username (without @), it's likely a username
if (linkText === usernameLower || linkText === `@${usernameLower}`) {
return potentialUsername;
}
// Check if link is in a UserName container or has username-like structure
const parent = link.closest('[data-testid="UserName"], [data-testid="User-Name"]');
if (parent) {
// If it's in a UserName container and looks like a username, return it
if (potentialUsername.length > 0 && potentialUsername.length < 20 && !potentialUsername.includes('/')) {
return potentialUsername;
}
}
// Also check if link text is @username format
if (text && text.trim().startsWith('@')) {
const atUsername = text.trim().substring(1);
if (atUsername === potentialUsername) {
return potentialUsername;
}
}
}
// Last resort: look for @username pattern in text content and verify with link
const textContent = element.textContent || '';
const atMentionMatches = textContent.matchAll(/@([a-zA-Z0-9_]+)/g);
for (const match of atMentionMatches) {
const username = match[1];
// Verify it's actually a link in a User-Name container
const link = element.querySelector(`a[href="/${username}"], a[href^="/${username}?"]`);
if (link) {
// Make sure it's in a username context, not just mentioned in tweet text
const isInUserNameContainer = link.closest('[data-testid="UserName"], [data-testid="User-Name"]');
if (isInUserNameContainer) {
return username;
}
}
}
return null;
}
// Helper function to find handle section
function findHandleSection(container, screenName) {
return Array.from(container.querySelectorAll('div')).find(div => {
const link = div.querySelector(`a[href="/${screenName}"]`);
if (link) {
const text = link.textContent?.trim();
return text === `@${screenName}`;
}
return false;
});
}
// Create loading shimmer placeholder
function createLoadingShimmer() {
const shimmer = document.createElement('span');
shimmer.setAttribute('data-twitter-flag-shimmer', 'true');
shimmer.style.display = 'inline-block';
shimmer.style.width = '20px';
shimmer.style.height = '16px';
shimmer.style.marginLeft = '4px';
shimmer.style.marginRight = '4px';
shimmer.style.verticalAlign = 'middle';
shimmer.style.borderRadius = '2px';
shimmer.style.background = 'linear-gradient(90deg, rgba(113, 118, 123, 0.2) 25%, rgba(113, 118, 123, 0.4) 50%, rgba(113, 118, 123, 0.2) 75%)';
shimmer.style.backgroundSize = '200% 100%';
shimmer.style.animation = 'shimmer 1.5s infinite';
// Add animation keyframes if not already added
if (!document.getElementById('twitter-flag-shimmer-style')) {
const style = document.createElement('style');
style.id = 'twitter-flag-shimmer-style';
style.textContent = `
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
`;
document.head.appendChild(style);
}
return shimmer;
}
// Check if a country is blocked
function isCountryBlocked(country) {
if (!country || !blockedCountries.length) return false;
return blockedCountries.some(bc =>
bc.toLowerCase() === country.toLowerCase()
);
}
// Update extension badge
function updateBadge() {
try {
chrome.runtime.sendMessage({ type: 'updateBadge', count: hiddenCount }).catch(() => {});
} catch (e) {
// Ignore if background script not available
}
}
// Hide a tweet element
function hideTweet(tweetArticle, country) {
if (tweetArticle.classList.contains('xcf-hidden')) return;
tweetArticle.classList.add('xcf-hidden');
tweetArticle.dataset.xcfCountry = country;
hiddenCount++;
const flag = getCountryFlag(country);
const placeholder = document.createElement('div');
placeholder.className = 'xcf-placeholder';
placeholder.innerHTML = `
<span class="xcf-placeholder-text">
${flag} Content from ${country} hidden
<button class="xcf-show-btn">Show</button>
</span>
`;
placeholder.querySelector('.xcf-show-btn').addEventListener('click', (e) => {
e.stopPropagation();
tweetArticle.classList.remove('xcf-hidden');
tweetArticle.classList.add('xcf-revealed');
placeholder.remove();
hiddenCount--;
updateBadge();
});
tweetArticle.parentNode.insertBefore(placeholder, tweetArticle);
updateBadge();
}
// Unhide all hidden tweets
function unhideAllTweets() {
document.querySelectorAll('.xcf-hidden').forEach(el => {
el.classList.remove('xcf-hidden');
el.classList.remove('xcf-revealed');
});
document.querySelectorAll('.xcf-placeholder').forEach(el => el.remove());
hiddenCount = 0;
updateBadge();
}
// Function to add flag to username element
async function addFlagToUsername(usernameElement, screenName) {
// Check if flag already added
if (usernameElement.dataset.flagAdded === 'true') {
return;
}
// Check if this username is already being processed (prevent duplicate API calls)
if (processingUsernames.has(screenName)) {
// Wait a bit and check if flag was added by the other process
await new Promise(resolve => setTimeout(resolve, 500));
if (usernameElement.dataset.flagAdded === 'true') {
return;
}
// If still not added, mark this container as waiting
usernameElement.dataset.flagAdded = 'waiting';
return;
}
// Mark as processing to avoid duplicate requests
usernameElement.dataset.flagAdded = 'processing';
processingUsernames.add(screenName);
// Find User-Name container for shimmer placement
const userNameContainer = usernameElement.querySelector('[data-testid="UserName"], [data-testid="User-Name"]');
// Create and insert loading shimmer
const shimmerSpan = createLoadingShimmer();
let shimmerInserted = false;
if (userNameContainer) {
// Try to insert shimmer before handle section (same place flag will go)
const handleSection = findHandleSection(userNameContainer, screenName);
if (handleSection && handleSection.parentNode) {
try {
handleSection.parentNode.insertBefore(shimmerSpan, handleSection);
shimmerInserted = true;
} catch (e) {
// Fallback: insert at end of container
try {
userNameContainer.appendChild(shimmerSpan);
shimmerInserted = true;
} catch (e2) {
console.log('Failed to insert shimmer');
}
}
} else {
// Fallback: insert at end of container
try {
userNameContainer.appendChild(shimmerSpan);
shimmerInserted = true;
} catch (e) {
console.log('Failed to insert shimmer');
}
}
}
try {
console.log(`Processing flag for ${screenName}...`);
// Get location
const location = await getUserLocation(screenName);
console.log(`Location for ${screenName}:`, location);
// Remove shimmer
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
if (!location) {
console.log(`No location found for ${screenName}, marking as failed`);
usernameElement.dataset.flagAdded = 'failed';
return;
}
// Get flag emoji
const flag = getCountryFlag(location);
if (!flag) {
console.log(`No flag found for location: ${location}`);
// Shimmer already removed above, but ensure it's gone
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
usernameElement.dataset.flagAdded = 'failed';
return;
}
console.log(`Found flag ${flag} for ${screenName} (${location})`);
// Find the username link - try multiple strategies
// Priority: Find the @username link, not the display name link
let usernameLink = null;
// Find the User-Name container (reuse from above if available, otherwise find it)
const containerForLink = userNameContainer || usernameElement.querySelector('[data-testid="UserName"], [data-testid="User-Name"]');
// Strategy 1: Find link with @username text content (most reliable - this is the actual handle)
if (containerForLink) {
const containerLinks = containerForLink.querySelectorAll('a[href^="/"]');
for (const link of containerLinks) {
const text = link.textContent?.trim();
const href = link.getAttribute('href');
const match = href.match(/^\/([^\/\?]+)/);
// Prioritize links that have @username as text
if (match && match[1] === screenName) {
if (text === `@${screenName}` || text === screenName) {
usernameLink = link;
break;
}
}
}
}
// Strategy 2: Find any link with @username text in UserName container
if (!usernameLink && containerForLink) {
const containerLinks = containerForLink.querySelectorAll('a[href^="/"]');
for (const link of containerLinks) {
const text = link.textContent?.trim();
if (text === `@${screenName}`) {
usernameLink = link;
break;
}
}
}
// Strategy 3: Find link with exact matching href that has @username text anywhere in element
if (!usernameLink) {
const links = usernameElement.querySelectorAll('a[href^="/"]');
for (const link of links) {
const href = link.getAttribute('href');
const text = link.textContent?.trim();
if ((href === `/${screenName}` || href.startsWith(`/${screenName}?`)) &&
(text === `@${screenName}` || text === screenName)) {
usernameLink = link;
break;
}
}
}
// Strategy 4: Fallback to any matching href (but prefer ones not in display name area)
if (!usernameLink) {
const links = usernameElement.querySelectorAll('a[href^="/"]');
for (const link of links) {
const href = link.getAttribute('href');
const match = href.match(/^\/([^\/\?]+)/);
if (match && match[1] === screenName) {
// Skip if this looks like a display name link (has verification badge nearby)
const hasVerificationBadge = link.closest('[data-testid="User-Name"]')?.querySelector('[data-testid="icon-verified"]');
if (!hasVerificationBadge || link.textContent?.trim() === `@${screenName}`) {
usernameLink = link;
break;
}
}
}
}
if (!usernameLink) {
console.error(`Could not find username link for ${screenName}`);
console.error('Available links in container:', Array.from(usernameElement.querySelectorAll('a[href^="/"]')).map(l => ({
href: l.getAttribute('href'),
text: l.textContent?.trim()
})));
// Remove shimmer on error
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
usernameElement.dataset.flagAdded = 'failed';
return;
}
console.log(`Found username link for ${screenName}:`, usernameLink.href, usernameLink.textContent?.trim());
// Check if flag already exists (check in the entire container, not just parent)
const existingFlag = usernameElement.querySelector('[data-twitter-flag]');
if (existingFlag) {
// Remove shimmer if flag already exists
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
usernameElement.dataset.flagAdded = 'true';
return;
}
// Only add flag if showFlags is enabled
if (!showFlags) {
console.log(`Flags disabled, skipping flag for ${screenName}`);
usernameElement.dataset.flagAdded = 'true';
// Still check for blocking
if (isCountryBlocked(location)) {
const tweetArticle = usernameElement.closest('article[data-testid="tweet"]');
if (tweetArticle && !tweetArticle.classList.contains('xcf-hidden')) {
console.log(`Hiding tweet from blocked country: ${location}`);
hideTweet(tweetArticle, location);
}
}
return;
}
// Add flag emoji - place it next to verification badge, before @ handle
const flagSpan = document.createElement('span');
flagSpan.textContent = ` ${flag}`;
flagSpan.setAttribute('data-twitter-flag', 'true');
flagSpan.style.marginLeft = '4px';
flagSpan.style.marginRight = '4px';
flagSpan.style.display = 'inline';
flagSpan.style.color = 'inherit';
flagSpan.style.verticalAlign = 'middle';
// Use userNameContainer found above, or find it if not found
const containerForFlag = userNameContainer || usernameElement.querySelector('[data-testid="UserName"], [data-testid="User-Name"]');
if (!containerForFlag) {
console.error(`Could not find UserName container for ${screenName}`);
// Remove shimmer on error
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
usernameElement.dataset.flagAdded = 'failed';
return;
}
// Find the verification badge (SVG with data-testid="icon-verified")
const verificationBadge = containerForFlag.querySelector('[data-testid="icon-verified"]');
// Find the handle section - the div that contains the @username link
// The structure is: User-Name > div (display name) > div (handle section with @username)
const handleSection = findHandleSection(containerForFlag, screenName);
let inserted = false;
// Strategy 1: Insert right before the handle section div (which contains @username)
// The handle section is a direct child of User-Name container
if (handleSection && handleSection.parentNode === containerForFlag) {
try {
containerForFlag.insertBefore(flagSpan, handleSection);
inserted = true;
console.log(`✓ Inserted flag before handle section for ${screenName}`);
} catch (e) {
console.log('Failed to insert before handle section:', e);
}
}
// Strategy 2: Find the handle section's parent and insert before it
if (!inserted && handleSection && handleSection.parentNode) {
try {
// Insert before the handle section's parent (if it's not User-Name)
const handleParent = handleSection.parentNode;
if (handleParent !== containerForFlag && handleParent.parentNode) {
handleParent.parentNode.insertBefore(flagSpan, handleParent);
inserted = true;
console.log(`✓ Inserted flag before handle parent for ${screenName}`);
} else if (handleParent === containerForFlag) {
// Handle section is direct child, insert before it
containerForFlag.insertBefore(flagSpan, handleSection);
inserted = true;
console.log(`✓ Inserted flag before handle section (direct child) for ${screenName}`);
}
} catch (e) {
console.log('Failed to insert before handle parent:', e);
}
}
// Strategy 3: Find display name container and insert after it, before handle section
if (!inserted && handleSection) {
try {
// Find the display name link (first link)
const displayNameLink = containerForFlag.querySelector('a[href^="/"]');
if (displayNameLink) {
// Find the div that contains the display name link
const displayNameContainer = displayNameLink.closest('div');
if (displayNameContainer && displayNameContainer.parentNode) {
// Check if handle section is a sibling
if (displayNameContainer.parentNode === handleSection.parentNode) {
displayNameContainer.parentNode.insertBefore(flagSpan, handleSection);
inserted = true;
console.log(`✓ Inserted flag between display name and handle (siblings) for ${screenName}`);
} else {
// Try inserting after display name container
displayNameContainer.parentNode.insertBefore(flagSpan, displayNameContainer.nextSibling);
inserted = true;
console.log(`✓ Inserted flag after display name container for ${screenName}`);
}
}
}
} catch (e) {
console.log('Failed to insert after display name:', e);
}
}
// Strategy 4: Insert at the end of User-Name container (fallback)
if (!inserted) {
try {
containerForFlag.appendChild(flagSpan);
inserted = true;
console.log(`✓ Inserted flag at end of UserName container for ${screenName}`);
} catch (e) {
console.error('Failed to append flag to User-Name container:', e);
}
}
if (inserted) {
// Mark as processed
usernameElement.dataset.flagAdded = 'true';
console.log(`✓ Successfully added flag ${flag} for ${screenName} (${location})`);
// Check if this country is blocked and hide the tweet if so
if (isCountryBlocked(location)) {
const tweetArticle = usernameElement.closest('article[data-testid="tweet"]');
if (tweetArticle && !tweetArticle.classList.contains('xcf-hidden')) {
console.log(`Hiding tweet from blocked country: ${location}`);
hideTweet(tweetArticle, location);
}
}
// Also mark any other containers waiting for this username
const waitingContainers = document.querySelectorAll(`[data-flag-added="waiting"]`);
waitingContainers.forEach(container => {
const waitingUsername = extractUsername(container);
if (waitingUsername === screenName) {
// Try to add flag to this container too
addFlagToUsername(container, screenName).catch(() => {});
}
});
} else {
console.error(`✗ Failed to insert flag for ${screenName} - tried all strategies`);
console.error('Username link:', usernameLink);
console.error('Parent structure:', usernameLink.parentNode);
// Remove shimmer on failure
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
usernameElement.dataset.flagAdded = 'failed';
}
} catch (error) {
console.error(`Error processing flag for ${screenName}:`, error);
// Remove shimmer on error
if (shimmerInserted && shimmerSpan.parentNode) {
shimmerSpan.remove();
}
usernameElement.dataset.flagAdded = 'failed';
} finally {
// Remove from processing set
processingUsernames.delete(screenName);
}
}
// Function to remove all flags (when extension is disabled)
function removeAllFlags() {
const flags = document.querySelectorAll('[data-twitter-flag]');
flags.forEach(flag => flag.remove());
// Also remove any loading shimmers
const shimmers = document.querySelectorAll('[data-twitter-flag-shimmer]');
shimmers.forEach(shimmer => shimmer.remove());
// Reset flag added markers
const containers = document.querySelectorAll('[data-flag-added]');
containers.forEach(container => {
delete container.dataset.flagAdded;
});
console.log('Removed all flags');
}
// Function to process all username elements on the page
async function processUsernames() {
// Check if extension is enabled
if (!extensionEnabled) {
return;
}
// Find all tweet/article containers and user cells
const containers = document.querySelectorAll('article[data-testid="tweet"], [data-testid="UserCell"], [data-testid="User-Names"], [data-testid="User-Name"]');
console.log(`Processing ${containers.length} containers for usernames`);
let foundCount = 0;
let processedCount = 0;
let skippedCount = 0;
for (const container of containers) {
const screenName = extractUsername(container);
if (screenName) {
foundCount++;
const status = container.dataset.flagAdded;
if (!status || status === 'failed') {
processedCount++;
// Process in parallel but limit concurrency
addFlagToUsername(container, screenName).catch(err => {
console.error(`Error processing ${screenName}:`, err);
container.dataset.flagAdded = 'failed';
});
} else {
skippedCount++;
}
} else {
// Debug: log containers that don't have usernames
const hasUserName = container.querySelector('[data-testid="UserName"], [data-testid="User-Name"]');
if (hasUserName) {
console.log('Found UserName container but no username extracted');
}
}
}
if (foundCount > 0) {
console.log(`Found ${foundCount} usernames, processing ${processedCount} new ones, skipped ${skippedCount} already processed`);
} else {
console.log('No usernames found in containers');
}
}
// Initialize observer for dynamically loaded content
function initObserver() {
if (observer) {
observer.disconnect();
}
observer = new MutationObserver((mutations) => {
// Don't process if extension is disabled
if (!extensionEnabled) {
return;
}
let shouldProcess = false;
for (const mutation of mutations) {
if (mutation.addedNodes.length > 0) {
shouldProcess = true;
break;
}
}
if (shouldProcess) {
// Debounce processing
setTimeout(processUsernames, 500);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
// Main initialization
async function init() {
console.log('X Country Filter extension initialized');
// Load enabled state first
await loadEnabledState();
// Load blocking settings
await loadBlockingSettings();
// Load persistent cache
await loadCache();
// Only proceed if extension is enabled
if (!extensionEnabled) {
console.log('Extension is disabled');
return;
}
// Inject page script
injectPageScript();
// Wait a bit for page to fully load
setTimeout(() => {
processUsernames();
}, 2000);
// Set up observer for new content
initObserver();
// Re-process on navigation (Twitter uses SPA)
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
console.log('Page navigation detected, reprocessing usernames');
setTimeout(processUsernames, 2000);
}
}).observe(document, { subtree: true, childList: true });
// Save cache periodically
setInterval(saveCache, 5000); // Save every 5 seconds
}
// Wait for page to load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}