-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
408 lines (328 loc) · 12.9 KB
/
content.js
File metadata and controls
408 lines (328 loc) · 12.9 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
// Substack Notification Filter - Content Script
// This script runs on Substack notification pages and applies filters
console.log('Substack Notification Filter loaded');
// ============================================================================
// CONFIGURATION & STATE
// ============================================================================
let filterConfig = {
keywords: [],
minLikes: 0,
requireFollowed: false,
enabled: true
};
let followedUsers = [];
let whitelistedUsers = [];
let stats = {
totalNotifications: 0,
filteredCount: 0
};
// ============================================================================
// INITIALIZATION
// ============================================================================
async function init() {
console.log('Initializing Substack filter...');
// Load configuration from storage
await loadConfig();
// Initial scan of existing notifications
scanAndFilterNotifications();
// Watch for dynamically loaded notifications (infinite scroll, etc)
observeNotifications();
// Add filter UI to the page
injectFilterUI();
}
// ============================================================================
// CONFIG MANAGEMENT
// ============================================================================
async function loadConfig() {
try {
const result = await chrome.storage.local.get(['filters', 'followedUsers', 'whitelistedUsers', 'stats']);
if (result.filters) {
filterConfig = { ...filterConfig, ...result.filters };
}
if (result.followedUsers) {
followedUsers = result.followedUsers;
}
if (result.whitelistedUsers) {
whitelistedUsers = result.whitelistedUsers;
}
console.log('Loaded config:', filterConfig);
console.log('Followed users:', followedUsers.length);
console.log('Whitelisted users:', whitelistedUsers.length);
} catch (error) {
console.error('Error loading config:', error);
}
}
async function saveStats() {
try {
await chrome.storage.sync.set({ stats });
} catch (error) {
console.error('Error saving stats:', error);
}
}
// ============================================================================
// NOTIFICATION DETECTION
// ============================================================================
function scanAndFilterNotifications() {
// Substack uses dynamic class names, so we look for partial matches
let notificationElements = document.querySelectorAll('[class*="notificationLink"]');
console.log(`Found ${notificationElements.length} notification elements`);
if (notificationElements.length > 0) {
console.log('Sample element class:', notificationElements[0]?.className);
}
// Reset stats before scanning
stats.totalNotifications = notificationElements.length;
stats.filteredCount = 0;
notificationElements.forEach(element => {
processNotification(element);
});
// Check if all notifications are filtered due to empty followed list
if (filterConfig.requireFollowed &&
followedUsers.length === 0 &&
stats.filteredCount === stats.totalNotifications &&
stats.totalNotifications > 0) {
showWarning('All notifications hidden: "Only show from people I follow" is enabled but your followed users list is empty. Add usernames or disable this filter.');
} else if (stats.filteredCount === stats.totalNotifications && stats.totalNotifications > 0) {
showWarning('All notifications are filtered. Try adjusting your filter settings.');
} else {
hideWarning();
}
updateFilterUI();
saveStats();
}
function processNotification(element) {
// Extract notification data
const data = extractNotificationData(element);
// Decide if should be filtered
const shouldFilter = shouldFilterNotification(data);
if (shouldFilter) {
applyFilter(element);
stats.filteredCount++;
} else {
// Ensure it's visible (in case filters were changed)
removeFilter(element);
}
}
// ============================================================================
// DATA EXTRACTION
// ============================================================================
function extractNotificationData(element) {
// Extract all relevant data from Substack notification
const data = {
text: extractText(element),
username: extractUsername(element),
likes: extractLikeCount(element),
type: extractNotificationType(element),
element: element
};
return data;
}
function extractText(element) {
// Comment/note text is in .FeedProseMirror
const textElement = element.querySelector('.FeedProseMirror');
return textElement ? textElement.textContent.trim() : '';
}
function extractUsername(element) {
// Substack username is in a link like href="/@username"
const usernameLink = element.querySelector('a[href^="/@"]');
if (!usernameLink) return '';
// Extract from href: "/@username" -> "username"
const href = usernameLink.getAttribute('href');
return href ? href.replace('/@', '').split('?')[0] : '';
}
function extractLikeCount(element) {
// Substack like count is in a button with class 'like-IrcdrZ'
// The count is in .count-hQZHkH (hidden if 0)
const likeButton = element.querySelector('.like-IrcdrZ');
if (!likeButton) return 0;
const countElement = likeButton.querySelector('.count-hQZHkH');
if (!countElement || countElement.classList.contains('hidden-UUUxXN')) {
return 0; // Hidden means 0 likes
}
const text = countElement.textContent.trim();
const match = text.match(/\d+/);
return match ? parseInt(match[0]) : 0;
}
function extractNotificationType(element) {
// Type is in the text like "replied to your note", "liked your note", etc.
const typeText = element.querySelector('.weight-regular-mUq6Gb.reset-IxiVJZ');
if (!typeText) return 'unknown';
const text = typeText.textContent.toLowerCase();
if (text.includes('replied')) return 'reply';
if (text.includes('liked')) return 'like';
if (text.includes('restack')) return 'restack';
if (text.includes('subscribed')) return 'subscribe';
return 'other';
}
// ============================================================================
// FILTERING LOGIC
// ============================================================================
function shouldFilterNotification(data) {
if (!filterConfig.enabled) return false;
// Whitelisted users are never filtered
if (isWhitelisted(data.username)) {
console.log(`Not filtering - user is whitelisted: ${data.username}`);
return false;
}
// Check if "only followed" is enabled
if (filterConfig.requireFollowed && !isFollowed(data.username)) {
console.log(`Filtering notification - user not followed: ${data.username}`);
return true;
}
// Check keyword filters
if (containsBlockedKeyword(data.text)) {
console.log(`Filtering notification - blocked keyword found: ${data.username}`);
return true;
}
// Check engagement threshold
if (filterConfig.minLikes > 0 && data.likes < filterConfig.minLikes) {
console.log(`Filtering notification - below like threshold: ${data.likes} < ${filterConfig.minLikes}`);
return true;
}
return false;
}
function containsBlockedKeyword(text) {
if (!text || !filterConfig.keywords.length) return false;
const lowerText = text.toLowerCase();
return filterConfig.keywords.some(keyword =>
lowerText.includes(keyword.toLowerCase())
);
}
function isFollowed(username) {
if (!username) return false;
return followedUsers.some(u => u.toLowerCase() === username.toLowerCase());
}
function isWhitelisted(username) {
if (!username) return false;
return whitelistedUsers.some(u => u.toLowerCase() === username.toLowerCase());
}
// ============================================================================
// DOM MANIPULATION
// ============================================================================
function applyFilter(element) {
element.classList.add('ssf-filtered');
element.style.display = 'none';
element.dataset.ssfFiltered = 'true';
}
function removeFilter(element) {
element.classList.remove('ssf-filtered');
element.style.display = '';
element.dataset.ssfFiltered = 'false';
}
// ============================================================================
// UI INJECTION
// ============================================================================
function injectFilterUI() {
// Create a simple UI element showing filter stats
const existingUI = document.getElementById('ssf-ui');
if (existingUI) existingUI.remove();
const ui = document.createElement('div');
ui.id = 'ssf-ui';
ui.className = 'ssf-ui-container';
ui.innerHTML = `
<div class="ssf-stats" id="ssf-stats">
<span>🔍 Substack Filter: </span>
<span id="ssf-visible-count">0</span> visible,
<span id="ssf-filtered-count">0</span> filtered
<button id="ssf-toggle-filtered">Show filtered</button>
</div>
<div class="ssf-warning" id="ssf-warning" style="display: none; padding: 10px; background: #2a2a2a; border: 2px solid #ff6b6b; border-radius: 4px; margin: 10px 0;">
<span style="color: #ff6b6b; font-weight: bold;">⚠️ <span id="ssf-warning-text"></span></span>
</div>
`;
// Insert at the top of main content or body
const targetContainer = document.querySelector('main') || document.body;
if (targetContainer) {
targetContainer.insertBefore(ui, targetContainer.firstChild);
// Add toggle functionality
const toggleBtn = document.getElementById('ssf-toggle-filtered');
if (toggleBtn) {
toggleBtn.addEventListener('click', toggleFilteredDisplay);
}
}
updateFilterUI();
}
function updateFilterUI() {
const visibleCount = stats.totalNotifications - stats.filteredCount;
const visibleEl = document.getElementById('ssf-visible-count');
const filteredEl = document.getElementById('ssf-filtered-count');
if (visibleEl) visibleEl.textContent = visibleCount;
if (filteredEl) filteredEl.textContent = stats.filteredCount;
}
function toggleFilteredDisplay() {
const filteredElements = document.querySelectorAll('[data-ssf-filtered="true"]');
const isCurrentlyHidden = filteredElements[0]?.style.display === 'none';
filteredElements.forEach(element => {
element.style.display = isCurrentlyHidden ? '' : 'none';
});
const button = document.getElementById('ssf-toggle-filtered');
if (button) {
button.textContent = isCurrentlyHidden ? 'Hide filtered' : 'Show filtered';
}
}
function showWarning(message) {
const statsEl = document.getElementById('ssf-stats');
const warningEl = document.getElementById('ssf-warning');
const warningText = document.getElementById('ssf-warning-text');
if (statsEl) statsEl.style.display = 'none';
if (warningEl) warningEl.style.display = 'block';
if (warningText) warningText.textContent = message;
}
function hideWarning() {
const statsEl = document.getElementById('ssf-stats');
const warningEl = document.getElementById('ssf-warning');
if (statsEl) statsEl.style.display = 'block';
if (warningEl) warningEl.style.display = 'none';
}
// ============================================================================
// MUTATION OBSERVER (for dynamic content)
// ============================================================================
function observeNotifications() {
// Watch for new notifications being added to the DOM
const observer = new MutationObserver((mutations) => {
let hasNewNotifications = false;
mutations.forEach((mutation) => {
if (mutation.addedNodes.length > 0) {
hasNewNotifications = true;
}
});
if (hasNewNotifications) {
// Debounce: wait a bit for multiple changes
clearTimeout(window.ssfScanTimeout);
window.ssfScanTimeout = setTimeout(() => {
console.log('New content detected, re-scanning...');
scanAndFilterNotifications();
}, 500);
}
});
// Observe the main content area - Substack typically has notifications in main or a feed container
const container = document.querySelector('main') || document.body;
if (container) {
observer.observe(container, {
childList: true,
subtree: true
});
console.log('Mutation observer initialized on:', container.tagName);
}
}
// ============================================================================
// MESSAGE HANDLING (from popup)
// ============================================================================
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'updateConfig') {
filterConfig = { ...filterConfig, ...request.config };
scanAndFilterNotifications();
sendResponse({ success: true });
} else if (request.action === 'getStats') {
sendResponse({ stats });
}
return true;
});
// ============================================================================
// START
// ============================================================================
// Wait for page to be ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}