Repository navigation
Expand file tree
/
Copy pathcontent.ts
More file actions
549 lines (501 loc) · 20.1 KB
/
Copy pathcontent.ts
File metadata and controls
549 lines (501 loc) · 20.1 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
import "../styles/overlay.css";
// DeAlter — hide AI-disclosed videos from the YouTube feed.
//
// For each video card that scrolls into view, we ask YouTube's own internal
// endpoint whether the video carries an "altered or synthetic content"
// disclosure, and hide the card if it does. Everything runs locally; the only
// network call is to YouTube itself.
//
// Three things keep this cheap and well-behaved at scale:
// 1. Verdicts are cached PERSISTENTLY (across sessions) so a video is looked
// up at most once, ever — most of the feed is repeat content.
// 2. We only look up cards the user actually scrolls near (Intersection
// Observer), not every card YouTube renders off-screen.
// 3. On HTTP 429 we back off exponentially and pause, so we never hammer.
export default defineContentScript({
matches: ["*://*.youtube.com/*"],
runAt: "document_idle",
main() {
// The node YouTube uses for the "How this was made" disclosure panel.
// If they rename it and videos stop being caught, update this one string.
const DISCLOSURE_KEY = "howThisWasMadeSectionViewModel";
// Wording inside that panel for AI / altered content. We only match these
// WITHIN the disclosure node, never across the whole response, so titles
// and related-video sidebars can't cause a false match. (keep lowercase)
//
// YouTube's current copy is "Made with AI" with body "Sounds or visuals were
// altered or fully generated"; older copy used "altered or synthetic" /
// "...synthetically generated". Keep both so we catch each variant.
//
// IMPORTANT: this node is OVERLOADED — it also carries non-AI disclosures:
// • "Captured with a camera" (content credentials / real footage)
// • "Audio tracks ... were automatically generated" (auto-dubbing, help
// 15569972) — a normal video with translated audio.
// Neither must be hidden. So match AI-SPECIFIC phrases only — never a bare
// "generated" token, or every auto-dubbed video gets wrongly hidden.
const NEEDLES = [
"made with ai",
"altered or fully generated",
"fully generated",
"altered or synthetic",
"synthetically generated",
"altered or synthetically generated",
"digitally generated",
"significantly edited or digitally generated",
];
// Public web values used only as a fallback if scraping the page fails.
const FALLBACK_KEY = "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8";
const FALLBACK_CLIENT_VERSION = "2.20991010.00.00";
// Containers that represent a single video card across YouTube surfaces.
const CARD_SELECTORS = [
"ytd-rich-item-renderer",
"ytd-video-renderer",
"ytd-compact-video-renderer",
"ytd-grid-video-renderer",
"ytd-playlist-video-renderer",
];
const CACHE_KEY = "verdictCache"; // storage key for the persistent cache
const CACHE_CAP = 8000; // most-recent N verdicts kept on disk
const MAX_WORKERS = 3; // concurrent lookups (kept low on purpose)
const VIEWPORT_MARGIN = "300px"; // look up cards this far before they show
let enabled = true;
let sessionCount = 0; // unique videos hidden since this page loaded
const sessionHidden = new Set<string>(); // videoIds counted this session
// Persistent tallies shown in the popup: hidden today (resets at local
// midnight) and hidden all-time (cumulative).
let todayCount = 0;
let todayDate = ""; // local YYYY-MM-DD the todayCount belongs to
let allTimeCount = 0;
const localDay = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
const verdict = new Map<string, boolean>(); // videoId -> AI? (persistent)
const idToCards = new Map<string, Set<HTMLElement>>(); // videoId -> cards
const queue: string[] = []; // videoIds awaiting a lookup
const queued = new Set<string>(); // dedupe guard for `queue`
let running = 0; // active worker count
let pausedUntil = 0; // epoch ms; lookups wait until this passes
let backoff = 0; // current backoff window in ms
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
// ---- talk to YouTube's internal endpoint --------------------------------
let ctx: { key: string; ver: string } | null = null;
function getCtx() {
if (ctx) return ctx;
const html = document.documentElement.innerHTML;
const key =
html.match(/"INNERTUBE_API_KEY":"([^"]+)"/)?.[1] || FALLBACK_KEY;
const ver =
html.match(/"INNERTUBE_CONTEXT_CLIENT_VERSION":"([^"]+)"/)?.[1] ||
html.match(/"clientVersion":"(2\.[^"]+)"/)?.[1] ||
FALLBACK_CLIENT_VERSION;
ctx = { key, ver };
return ctx;
}
class RateLimited extends Error {}
async function lookup(videoId: string): Promise<boolean> {
const { key, ver } = getCtx();
const res = await fetch(
`https://www.youtube.com/youtubei/v1/next?key=${key}&prettyPrint=false`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-YouTube-Client-Name": "1",
"X-YouTube-Client-Version": ver,
},
// hl:"en" forces English disclosure text so matching stays stable
// no matter what language the viewer's YouTube is set to.
body: JSON.stringify({
context: {
client: {
clientName: "WEB",
clientVersion: ver,
hl: "en",
gl: "US",
},
},
videoId,
}),
},
);
if (res.status === 429 || res.status === 503) throw new RateLimited();
if (!res.ok) throw new Error("next " + res.status);
const raw = await res.text();
// Fast path: if the disclosure panel isn't in the response at all, stop.
if (!raw.toLowerCase().includes(DISCLOSURE_KEY.toLowerCase())) return false;
let json: unknown;
try {
json = JSON.parse(raw);
} catch {
return false;
}
return disclosureIsSynthetic(json);
}
// Flatten every string inside a subtree into one lowercased blob.
function collectText(node: unknown): string {
const out: string[] = [];
const stack: unknown[] = [node];
while (stack.length) {
const c = stack.pop();
if (typeof c === "string") out.push(c);
else if (Array.isArray(c)) for (const v of c) stack.push(v);
else if (c && typeof c === "object")
for (const k in c as Record<string, unknown>)
stack.push((c as Record<string, unknown>)[k]);
}
return out.join(" ").toLowerCase();
}
// True ONLY when the "How this was made" disclosure node itself says the
// content is altered/synthetic. Ignores titles, descriptions and the
// related-videos sidebar, and skips the "Captured with a camera" variant.
function disclosureIsSynthetic(json: unknown): boolean {
const stack: unknown[] = [json];
while (stack.length) {
const cur = stack.pop();
if (Array.isArray(cur)) {
for (const v of cur) stack.push(v);
} else if (cur && typeof cur === "object") {
const obj = cur as Record<string, unknown>;
for (const k in obj) {
if (k === DISCLOSURE_KEY) {
const text = collectText(obj[k]);
if (NEEDLES.some((n) => text.includes(n))) return true;
}
stack.push(obj[k]);
}
}
}
return false;
}
// ---- persistent verdict cache -------------------------------------------
let saveTimer: ReturnType<typeof setTimeout> | null = null;
function saveCacheSoon() {
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
// Keep only the most recent CACHE_CAP entries (Map preserves order).
const entries = [...verdict.entries()];
const trimmed = entries.slice(Math.max(0, entries.length - CACHE_CAP));
browser.storage.local
.set({ [CACHE_KEY]: trimmed.map(([id, v]) => [id, v ? 1 : 0]) })
.catch(() => {});
}, 1000);
}
// ---- worker pool --------------------------------------------------------
function enqueue(id: string) {
if (verdict.has(id)) {
if (verdict.get(id)) applyVerdict(id);
return;
}
if (queued.has(id)) return;
queued.add(id);
queue.push(id);
kick();
}
function kick() {
for (let i = running; i < MAX_WORKERS; i++) pump();
}
async function pump() {
if (running >= MAX_WORKERS) return;
running++;
try {
while (enabled && queue.length) {
const wait = pausedUntil - Date.now();
if (wait > 0) {
await sleep(wait);
continue;
}
const id = queue.shift()!;
queued.delete(id);
if (verdict.has(id)) {
if (verdict.get(id)) applyVerdict(id);
continue;
}
try {
const isAi = await lookup(id);
verdict.set(id, isAi);
saveCacheSoon();
backoff = 0;
if (isAi) applyVerdict(id);
} catch (err) {
if (err instanceof RateLimited) {
// Throttled: pause everyone, retry this id after a backoff.
backoff = backoff ? Math.min(backoff * 2, 60_000) : 2_000;
pausedUntil = Date.now() + backoff;
queued.add(id);
queue.unshift(id);
}
// Any other error: fail open (never hide because a check broke).
}
}
} finally {
running--;
}
}
// ---- feed scanning + hiding ---------------------------------------------
function idFromHref(href: string | null): string | null {
return href?.match(/[?&]v=([\w-]{11})/)?.[1] ?? null;
}
function cardFor(anchor: Element): HTMLElement | null {
for (const sel of CARD_SELECTORS) {
const el = anchor.closest<HTMLElement>(sel);
if (el) return el;
}
return null;
}
// The card's "Hidden by DeAlter" overlay: a quiet centered chip
// (brand sparkle icon + label). Same at every card size.
const PLACEHOLDER_HTML =
'<div class="dealter-ph-chip">' +
'<svg viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg">' +
'<rect x="6" y="6" width="116" height="116" rx="30" fill="#242c4e"/>' +
'<path d="M64,22 Q76.6,51.4 106,64 Q76.6,76.6 64,106 Q51.4,76.6 22,64 Q51.4,51.4 64,22 Z" fill="#3b82f6"/>' +
'<line x1="32" y1="32" x2="96" y2="96" stroke="#242c4e" stroke-width="16" stroke-linecap="round"/>' +
'<line x1="32" y1="32" x2="96" y2="96" stroke="#3b82f6" stroke-width="9" stroke-linecap="round"/></svg>' +
'<span class="dealter-ph-label">Hidden by DeAlter' +
'<span class="dim"> · AI-generated</span></span>' +
"</div>";
const SLIM_ROW_PX = 56;
// A card "owns its row" when it spans (nearly) the full width of its
// container — a search/sidebar row, or a homepage grid collapsed to one
// column. This is layout-based, so it stays correct as the window resizes.
function ownsRow(card: HTMLElement): boolean {
const parent = card.parentElement;
if (!parent) return false;
const cw = card.offsetWidth;
const pw = parent.offsetWidth;
return pw > 0 && cw / pw >= 0.9;
}
// Collapse full-row cards to a slim strip (animated); leave grid tiles full.
// Re-runnable: flips a card between slim and full as the layout changes.
function applyCollapse(card: HTMLElement) {
const slim = ownsRow(card);
const collapsing = card.classList.contains("dealter-collapsing");
if (slim && !collapsing) {
card.classList.add("dealter-collapsing");
const h = card.offsetHeight;
if (h > SLIM_ROW_PX) {
card.style.height = h + "px";
requestAnimationFrame(() => {
card.style.height = SLIM_ROW_PX + "px";
});
} else {
card.style.height = SLIM_ROW_PX + "px";
}
} else if (!slim && collapsing) {
card.classList.remove("dealter-collapsing");
card.style.removeProperty("height");
}
}
// Replace the card in place instead of removing it: keep its box (so the
// grid never reflows/flickers) and lay the quiet chip over it.
function hide(card: HTMLElement) {
if (card.dataset.dealterHidden === "1") return;
card.dataset.dealterHidden = "1";
card.classList.add("dealter-hidden");
if (!card.querySelector(":scope > .dealter-ph")) {
const ph = document.createElement("div");
ph.className = "dealter-ph";
ph.innerHTML = PLACEHOLDER_HTML;
card.appendChild(ph);
}
applyCollapse(card);
}
function applyVerdict(id: string) {
const cards = idToCards.get(id);
if (!cards) return;
for (const card of cards) {
observer.unobserve(card);
hide(card);
}
if (!sessionHidden.has(id)) {
sessionHidden.add(id);
sessionCount++;
const day = localDay();
if (todayDate !== day) {
todayDate = day;
todayCount = 0;
}
todayCount++;
allTimeCount++;
browser.storage.local
.set({
count: sessionCount,
hiddenToday: todayCount,
hiddenTodayDate: todayDate,
hiddenAllTime: allTimeCount,
})
.catch(() => {});
}
}
function unhideAll() {
document
.querySelectorAll<HTMLElement>('[data-dealter-hidden="1"]')
.forEach((el) => {
el.classList.remove("dealter-hidden", "dealter-collapsing");
el.style.removeProperty("height");
el.querySelector(":scope > .dealter-ph")?.remove();
delete el.dataset.dealterHidden;
});
}
// Re-hide every card we already know is AI. Needed when the user toggles the
// extension back on: scan() skips elements it has already seen, so without
// this the previously-hidden cards would stay visible until re-rendered.
function reapplyHidden() {
for (const [id, cards] of idToCards) {
if (!verdict.get(id)) continue;
for (const card of cards) if (card.isConnected) hide(card);
}
}
// Bound memory on long infinite-scroll: forget cards YouTube has removed
// from the DOM. Only DISCONNECTED nodes are touched, so cards YouTube
// recycles in place (still connected) are never disturbed. A pruned node is
// also wiped and un-"seen" so that, if YouTube later reuses it for a new
// video, scan() re-evaluates it from scratch instead of trusting stale state.
function pruneDetached() {
for (const [id, cards] of idToCards) {
for (const card of cards) {
if (card.isConnected) continue;
cards.delete(card);
seenCards.delete(card);
card.querySelector(":scope > .dealter-ph")?.remove();
card.classList.remove("dealter-hidden", "dealter-collapsing");
card.style.removeProperty("height");
delete card.dataset.dealterHidden;
delete card.dataset.dealterId;
}
if (cards.size === 0) idToCards.delete(id);
}
}
// A card scrolls within VIEWPORT_MARGIN of the viewport -> evaluate it.
const observer = new IntersectionObserver(
(entries) => {
if (!enabled) return;
for (const e of entries) {
if (!e.isIntersecting) continue;
const card = e.target as HTMLElement;
// One lookup per card is enough — stop watching once it's queued.
observer.unobserve(card);
const id = card.dataset.dealterId;
if (id) enqueue(id);
}
},
{ rootMargin: VIEWPORT_MARGIN },
);
const seenCards = new WeakSet<HTMLElement>();
let lastPrune = 0;
function scan() {
if (!enabled) return;
document.querySelectorAll('a[href*="/watch?v="]').forEach((a) => {
const card = cardFor(a);
if (!card || seenCards.has(card)) return;
const id = idFromHref(a.getAttribute("href"));
if (!id) return;
seenCards.add(card);
card.dataset.dealterId = id;
let cards = idToCards.get(id);
if (!cards) idToCards.set(id, (cards = new Set()));
cards.add(card);
// Known verdict -> act now; otherwise watch until it nears the viewport.
if (verdict.has(id)) {
if (verdict.get(id)) hide(card);
} else {
observer.observe(card);
}
});
// Drop forgotten DOM nodes at most every 5s (cheap, keeps idToCards small).
const now = Date.now();
if (now - lastPrune > 5000) {
lastPrune = now;
pruneDetached();
}
}
let scanTimer: ReturnType<typeof setTimeout> | null = null;
function scheduleScan() {
if (!enabled) return;
if (scanTimer) clearTimeout(scanTimer);
scanTimer = setTimeout(scan, 400);
}
// ---- wiring -------------------------------------------------------------
function start() {
browser.storage.local
.get([
"enabled",
CACHE_KEY,
"cacheVersion",
"hiddenToday",
"hiddenTodayDate",
"hiddenAllTime",
])
.then((r) => {
enabled = r.enabled !== false; // default ON
// Drop the verdict cache whenever the extension version changes, so a
// detection fix (e.g. new disclosure wording) re-evaluates videos
// instead of trusting stale "clean" verdicts. No manual clear needed.
const version = browser.runtime.getManifest().version;
const stored = r[CACHE_KEY];
if (r.cacheVersion === version && Array.isArray(stored)) {
for (const pair of stored) {
if (Array.isArray(pair) && pair.length === 2) {
verdict.set(String(pair[0]), pair[1] === 1 || pair[1] === true);
}
}
} else if (r.cacheVersion !== version) {
browser.storage.local
.set({ [CACHE_KEY]: [], cacheVersion: version })
.catch(() => {});
}
// Restore persistent tallies; roll "today" over if the day changed.
allTimeCount = typeof r.hiddenAllTime === "number" ? r.hiddenAllTime : 0;
const day = localDay();
if (r.hiddenTodayDate === day && typeof r.hiddenToday === "number") {
todayDate = day;
todayCount = r.hiddenToday;
} else {
todayDate = day;
todayCount = 0;
browser.storage.local
.set({ hiddenToday: 0, hiddenTodayDate: day })
.catch(() => {});
}
// Fresh session counter every full page load.
sessionCount = 0;
browser.storage.local.set({ count: 0 }).catch(() => {});
if (enabled) scheduleScan();
})
.catch(() => {
if (enabled) scheduleScan();
});
browser.storage.onChanged.addListener((changes, area) => {
if (area !== "local" || !changes.enabled) return;
enabled = changes.enabled.newValue !== false;
if (enabled) {
reapplyHidden();
scheduleScan();
kick();
} else {
unhideAll();
}
});
new MutationObserver(scheduleScan).observe(document.documentElement, {
childList: true,
subtree: true,
});
// YouTube is a single-page app; this fires on every in-app navigation.
window.addEventListener("yt-navigate-finish", scheduleScan);
// Re-evaluate slim/full for every hidden card when the window resizes
// (e.g. the homepage grid dropping to a single column and back).
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
window.addEventListener("resize", () => {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
document
.querySelectorAll<HTMLElement>('[data-dealter-hidden="1"]')
.forEach(applyCollapse);
}, 150);
});
}
start();
},
});