-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
644 lines (547 loc) · 26.5 KB
/
content.js
File metadata and controls
644 lines (547 loc) · 26.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
console.log("YouTube Context Analyzer: Content script loaded (or injected).");
// Helper function to extract video ID from URL (supports both standard videos and Shorts)
function getYouTubeVideoId() {
const url = window.location.href;
// Check for standard YouTube video URL (/watch?v=)
const standardMatch = url.match(/[?&]v=([^&]+)/);
if (standardMatch) {
return standardMatch[1];
}
// Check for YouTube Shorts URL (/shorts/)
const shortsMatch = url.match(/\/shorts\/([a-zA-Z0-9_-]+)/);
if (shortsMatch) {
return shortsMatch[1];
}
return null;
}
// Function to extract video metadata
function getVideoMetadata() {
const videoId = getYouTubeVideoId();
const title = document.querySelector('meta[property="og:title"]')?.content ||
document.querySelector('title')?.textContent || 'Unknown Video';
const channelName = document.querySelector('ytd-channel-name yt-formatted-string')?.textContent || 'Unknown Channel';
return { videoId, title, channelName };
}
// Extract transcript from page (will be called via executeScript)
function extractTranscriptFromPage() {
return new Promise((resolve, reject) => {
// Check if transcript button is already visible
const transcriptButton = Array.from(document.querySelectorAll('button'))
.find(button => button.textContent?.includes('Show transcript'));
if (!transcriptButton) {
// Try to access "More" dropdown first if transcript button not found
const moreActionsButton = document.querySelector('button[aria-label="More actions"]');
if (moreActionsButton) {
moreActionsButton.click();
// Wait for menu to appear
setTimeout(() => {
const showTranscriptMenuItem = Array.from(document.querySelectorAll('tp-yt-paper-item'))
.find(item => item.textContent?.includes('Show transcript'));
if (showTranscriptMenuItem) {
showTranscriptMenuItem.click();
// Wait for transcript to appear
setTimeout(extractTranscriptText, 1000);
} else {
reject("Transcript option not found in menu");
}
}, 500);
} else {
reject("Transcript button not found and cannot access 'More' menu");
}
} else {
transcriptButton.click();
// Wait for transcript to load
setTimeout(extractTranscriptText, 1000);
}
function extractTranscriptText() {
const transcriptPanel = document.querySelector('ytd-transcript-renderer') ||
document.querySelector('.ytd-transcript-renderer');
if (!transcriptPanel) {
reject("Transcript panel not found after clicking button");
return;
}
// Extract text from transcript segments
const segments = transcriptPanel.querySelectorAll('ytd-transcript-segment-renderer') ||
transcriptPanel.querySelectorAll('.ytd-transcript-segment-renderer');
if (!segments || segments.length === 0) {
reject("No transcript segments found");
return;
}
const transcriptText = Array.from(segments).map(segment => {
const timeElement = segment.querySelector('.segment-timestamp') ||
segment.querySelector('[class*="timestamp"]');
const textElement = segment.querySelector('.segment-text') ||
segment.querySelector('[class*="text"]');
if (timeElement && textElement) {
return `[${timeElement.textContent.trim()}] ${textElement.textContent.trim()}`;
}
return '';
}).filter(text => text.length > 0).join('\n');
resolve(transcriptText);
// Close transcript panel after extraction
const closeButton = document.querySelector('button[aria-label="Close transcript"]') ||
document.querySelector('.ytd-transcript-renderer [aria-label="Close"]');
if (closeButton) {
closeButton.click();
}
}
});
}
// Extract available caption tracks from YouTube player
function getAvailableCaptionTracks() {
return new Promise((resolve, reject) => {
try {
// Try to access the YouTube player's caption tracks
const player = document.querySelector('#movie_player');
if (!player) {
reject("YouTube player not found");
return;
}
// Look for caption/subtitle button
const captionButton = document.querySelector('.ytp-subtitles-button') ||
document.querySelector('[aria-label*="Subtitles"]') ||
document.querySelector('[title*="Subtitles"]');
if (!captionButton) {
reject("Caption button not found in player");
return;
}
// Click the caption button to open the menu
captionButton.click();
setTimeout(() => {
// Look for the settings/gear button in the caption menu
const settingsButton = document.querySelector('.ytp-settings-button') ||
document.querySelector('[aria-label*="Settings"]');
if (settingsButton) {
settingsButton.click();
setTimeout(() => {
// Look for "Subtitles/CC" option in settings menu
const subtitleOption = Array.from(document.querySelectorAll('.ytp-menuitem'))
.find(item => item.textContent?.includes('Subtitles') || item.textContent?.includes('CC'));
if (subtitleOption) {
subtitleOption.click();
setTimeout(() => {
// Extract available languages
const languageItems = document.querySelectorAll('.ytp-menuitem');
const availableLanguages = [];
languageItems.forEach(item => {
const text = item.textContent?.trim();
if (text && text !== 'Off' && text !== 'Subtitles/CC') {
// Parse language info
const langMatch = text.match(/(.+?)(?:\s*\((.+?)\))?$/);
if (langMatch) {
const langName = langMatch[1].trim();
const langType = langMatch[2] || 'Unknown';
// Try to extract language code from attributes or data
const langCode = extractLanguageCode(item, langName);
availableLanguages.push({
name: langName,
code: langCode,
type: langType,
element: item
});
}
}
});
// Close the menu
document.body.click();
resolve(availableLanguages);
}, 500);
} else {
document.body.click();
reject("Subtitles option not found in settings");
}
}, 500);
} else {
document.body.click();
reject("Settings button not found");
}
}, 500);
} catch (error) {
reject(`Error accessing caption tracks: ${error.message}`);
}
});
}
// Extract language code from various sources
function extractLanguageCode(element, languageName) {
// Try to get language code from data attributes
const dataLang = element.getAttribute('data-language-code') ||
element.getAttribute('data-lang') ||
element.getAttribute('lang');
if (dataLang) return dataLang;
// Map common language names to codes
const languageMap = {
'English': 'en',
'Spanish': 'es',
'French': 'fr',
'German': 'de',
'Japanese': 'ja',
'Korean': 'ko',
'Chinese': 'zh',
'Arabic': 'ar',
'Hindi': 'hi',
'Portuguese': 'pt',
'Russian': 'ru',
'Italian': 'it',
'Dutch': 'nl',
'Swedish': 'sv',
'Danish': 'da',
'Norwegian': 'no',
'Finnish': 'fi',
'Turkish': 'tr',
'Polish': 'pl',
'Ukrainian': 'uk',
'Tamil': 'ta',
'Telugu': 'te',
'Bengali': 'bn',
'Malayalam': 'ml',
'Kannada': 'kn',
'Gujarati': 'gu',
'Punjabi': 'pa',
'Marathi': 'mr',
'Urdu': 'ur',
'Thai': 'th',
'Vietnamese': 'vi',
'Indonesian': 'id',
'Malay': 'ms',
'Hebrew': 'he',
'Persian': 'fa'
};
// Try exact match first
if (languageMap[languageName]) {
return languageMap[languageName];
}
// Try partial match
for (const [name, code] of Object.entries(languageMap)) {
if (languageName.toLowerCase().includes(name.toLowerCase()) ||
name.toLowerCase().includes(languageName.toLowerCase())) {
return code;
}
}
// If no match found, return a simplified version of the name
return languageName.toLowerCase().replace(/[^a-z]/g, '').substring(0, 3);
}
// Extract captions for a specific language from the player
function extractCaptionsForLanguage(languageInfo) {
return new Promise((resolve, reject) => {
try {
// Click the caption button to open the menu
const captionButton = document.querySelector('.ytp-subtitles-button') ||
document.querySelector('[aria-label*="Subtitles"]');
if (!captionButton) {
reject("Caption button not found");
return;
}
captionButton.click();
setTimeout(() => {
const settingsButton = document.querySelector('.ytp-settings-button');
if (settingsButton) {
settingsButton.click();
setTimeout(() => {
const subtitleOption = Array.from(document.querySelectorAll('.ytp-menuitem'))
.find(item => item.textContent?.includes('Subtitles') || item.textContent?.includes('CC'));
if (subtitleOption) {
subtitleOption.click();
setTimeout(() => {
// Find and click the specific language
const targetLangItem = Array.from(document.querySelectorAll('.ytp-menuitem'))
.find(item => item.textContent?.includes(languageInfo.name));
if (targetLangItem) {
targetLangItem.click();
// Wait for captions to load and start extracting
setTimeout(() => {
startCaptionExtraction(languageInfo, resolve, reject);
}, 1000);
} else {
document.body.click();
reject(`Language ${languageInfo.name} not found in menu`);
}
}, 500);
} else {
document.body.click();
reject("Subtitles option not found");
}
}, 500);
} else {
document.body.click();
reject("Settings button not found");
}
}, 500);
} catch (error) {
reject(`Error extracting captions for ${languageInfo.name}: ${error.message}`);
}
});
}
// Start extracting caption text as it appears
function startCaptionExtraction(languageInfo, resolve, reject) {
const captionTexts = [];
const extractedTexts = new Set(); // Avoid duplicates
const MAX_CAPTION_ENTRIES = 5000; // Safety limit to prevent unbounded growth
let extractionStartTime = Date.now();
const maxExtractionTime = 30000; // 30 seconds max
let lastCaptionTime = Date.now();
// Ensure playback is running so subtitles render.
try {
const videoEl = document.querySelector('video');
if (videoEl && videoEl.paused) {
videoEl.play().catch(() => {});
}
} catch (_) {
// Ignore playback control issues and continue extraction attempts.
}
const captionExtractor = setInterval(() => {
const currentTime = Date.now();
// Stop if we've been extracting too long without new content, or hit safety limit
if (currentTime - lastCaptionTime > 5000 || currentTime - extractionStartTime > maxExtractionTime || captionTexts.length >= MAX_CAPTION_ENTRIES) {
clearInterval(captionExtractor);
if (captionTexts.length > 0) {
const transcript = captionTexts.join('\n');
resolve({
language: languageInfo,
transcript: transcript,
extractedSegments: captionTexts.length
});
} else {
reject(`No captions found for ${languageInfo.name} after ${(currentTime - extractionStartTime) / 1000}s`);
}
return;
}
// Look for caption elements
const captionElements = document.querySelectorAll('.caption-window .captions-text') ||
document.querySelectorAll('.ytp-caption-segment') ||
document.querySelectorAll('.captions-text') ||
document.querySelectorAll('[class*="caption"]');
captionElements.forEach(element => {
const text = element.textContent?.trim();
if (text && !extractedTexts.has(text)) {
extractedTexts.add(text);
// Try to get timestamp from video player
const player = document.querySelector('#movie_player');
let timestamp = 'Unknown';
if (player && typeof player.getCurrentTime === 'function') {
const seconds = Math.floor(player.getCurrentTime());
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
timestamp = `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}
captionTexts.push(`[${timestamp}] ${text}`);
lastCaptionTime = currentTime;
}
});
}, 200); // Check every 200ms for new captions (reduced from 100ms to save CPU)
// Auto-resolve if no captions appear after 10 seconds
setTimeout(() => {
if (captionTexts.length === 0) {
clearInterval(captionExtractor);
reject(`No captions detected for ${languageInfo.name} after 10 seconds`);
}
}, 10000);
}
// Extract multiple language captions from browser player
function extractMultiLanguageCaptionsFromPlayer(preferredLanguages = []) {
return new Promise(async (resolve, reject) => {
try {
// First, get all available caption tracks
const availableLanguages = await getAvailableCaptionTracks();
if (availableLanguages.length === 0) {
reject("No caption tracks found in player");
return;
}
const results = {
availableLanguages: availableLanguages,
extractedCaptions: {},
errors: []
};
// Determine which languages to extract
let languagesToExtract = availableLanguages;
if (preferredLanguages.length > 0) {
languagesToExtract = availableLanguages.filter(lang =>
preferredLanguages.some(prefLang =>
lang.code === prefLang ||
lang.name.toLowerCase().includes(prefLang.toLowerCase())
)
);
// If no preferred languages found, fall back to first available
if (languagesToExtract.length === 0) {
languagesToExtract = [availableLanguages[0]];
}
}
// Extract captions for each language
for (const langInfo of languagesToExtract) {
try {
const captionData = await extractCaptionsForLanguage(langInfo);
results.extractedCaptions[langInfo.code] = captionData;
} catch (error) {
results.errors.push({
language: langInfo.name,
code: langInfo.code,
error: error.toString()
});
}
// Small delay between language extractions
await new Promise(resolve => setTimeout(resolve, 1000));
}
resolve(results);
} catch (error) {
reject(`Error extracting multi-language captions: ${error.message}`);
}
});
}
// Scrape comments directly from the YouTube page DOM (no API key needed)
function scrapeCommentsFromPage(maxComments = 100) {
return new Promise(async (resolve, reject) => {
try {
// Scroll to comments section to trigger lazy loading
const commentsSection = document.querySelector('ytd-comments#comments') ||
document.querySelector('#comments');
if (commentsSection) {
commentsSection.scrollIntoView({ behavior: 'instant' });
} else {
// Try scrolling down to trigger comment loading
window.scrollBy(0, 800);
}
await new Promise(r => setTimeout(r, 1500));
let previousCount = 0;
let stableCount = 0;
// Scroll progressively to load more comments
for (let i = 0; i < 30; i++) {
const commentElements = document.querySelectorAll('ytd-comment-thread-renderer');
if (commentElements.length >= maxComments) break;
if (commentElements.length === previousCount) {
stableCount++;
if (stableCount >= 4) break; // No new comments loading
} else {
stableCount = 0;
}
previousCount = commentElements.length;
window.scrollBy(0, 600);
await new Promise(r => setTimeout(r, 800));
}
// Extract comment data
const commentElements = document.querySelectorAll('ytd-comment-thread-renderer');
const comments = [];
const seen = new Set();
commentElements.forEach((element, index) => {
if (index >= maxComments) return;
const textEl = element.querySelector('#content-text');
const authorEl = element.querySelector('#author-text span') ||
element.querySelector('#author-text');
const likesEl = element.querySelector('#vote-count-middle');
if (textEl) {
const text = textEl.textContent.trim();
if (text && !seen.has(text)) {
seen.add(text);
comments.push({
text: text,
author: authorEl ? authorEl.textContent.trim() : 'Unknown',
likes: likesEl ? parseInt(likesEl.textContent.trim().replace(/[^0-9]/g, '')) || 0 : 0
});
}
}
});
// Scroll back to top
window.scrollTo(0, 0);
if (comments.length === 0) {
reject("No comments found on page. Comments may be disabled or the page hasn't loaded fully.");
return;
}
resolve(comments);
} catch (error) {
reject(`Error scraping comments: ${error.message}`);
}
});
}
// Handle messages from background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getVideoInfo") {
sendResponse(getVideoMetadata());
return true;
}
if (request.action === "extractTranscriptFromPage") {
extractTranscriptFromPage()
.then(transcript => sendResponse({ success: true, transcript }))
.catch(error => sendResponse({ success: false, error: error.toString() }));
return true; // Keep message channel open for async response
}
if (request.action === "getAvailableCaptionTracks") {
getAvailableCaptionTracks()
.then(tracks => sendResponse({ success: true, tracks }))
.catch(error => sendResponse({ success: false, error: error.toString() }));
return true;
}
if (request.action === "extractCaptionsFromPlayer") {
const preferredLanguages = request.preferredLanguages || [];
extractMultiLanguageCaptionsFromPlayer(preferredLanguages)
.then(results => sendResponse({ success: true, results }))
.catch(error => sendResponse({ success: false, error: error.toString() }));
return true;
}
if (request.action === "extractSingleLanguageCaptions") {
const languageInfo = request.languageInfo;
extractCaptionsForLanguage(languageInfo)
.then(result => sendResponse({ success: true, result }))
.catch(error => sendResponse({ success: false, error: error.toString() }));
return true;
}
if (request.action === "scrapeCommentsFromPage") {
const maxComments = request.maxComments || 100;
scrapeCommentsFromPage(maxComments)
.then(comments => sendResponse({ success: true, comments }))
.catch(error => sendResponse({ success: false, error: error.toString() }));
return true;
}
if (request.action === "displayFactCheck") {
// Display fact check in a floating panel
const panel = document.createElement('div');
panel.className = 'yt-context-analyzer-panel';
panel.style = `
position: fixed;
bottom: 20px;
right: 20px;
width: 300px;
max-height: 400px;
background: white;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
z-index: 9999;
overflow-y: auto;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
`;
const closeBtn = document.createElement('button');
closeBtn.textContent = '×';
closeBtn.style = `
position: absolute;
top: 5px;
right: 5px;
background: none;
border: none;
font-size: 20px;
cursor: pointer;
`;
closeBtn.onclick = () => panel.remove();
const title = document.createElement('h3');
title.textContent = 'Fact Check Result';
title.style = 'margin-top: 0; margin-bottom: 10px;';
const content = document.createElement('div');
if (request.result) {
content.innerHTML = `
<strong>Verdict:</strong> ${request.result.verdict || 'Unknown'}<br>
<strong>Confidence:</strong> ${request.result.confidence ? (request.result.confidence * 100).toFixed(0) + '%' : 'Unknown'}<br>
<strong>Explanation:</strong> ${request.result.explanation || 'No explanation provided.'}
`;
} else if (request.error) {
content.innerHTML = `<p style="color: red;">Error: ${request.error}</p>`;
}
panel.appendChild(closeBtn);
panel.appendChild(title);
panel.appendChild(content);
document.body.appendChild(panel);
// Auto-remove after 30 seconds
setTimeout(() => {
if (document.body.contains(panel)) {
panel.remove();
}
}, 30000);
return true;
}
});