-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage-script.js
More file actions
215 lines (191 loc) · 6.78 KB
/
page-script.js
File metadata and controls
215 lines (191 loc) · 6.78 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
// YouTube → Claude Transcriber — Page Context Script (MAIN world)
// Extracts caption tracks from YouTube's player and fetches transcript XML
window.addEventListener('ytc-request', async (e) => {
const { videoId, requestId, preferLang, includeTimestamps } = e.detail;
try {
const result = await getTranscript(videoId, preferLang || 'auto', includeTimestamps !== false);
window.dispatchEvent(new CustomEvent('ytc-response', {
detail: { requestId, ...result }
}));
} catch (err) {
window.dispatchEvent(new CustomEvent('ytc-response', {
detail: { requestId, success: false, error: err.message || 'Unknown error occurred' }
}));
}
});
function getCaptionTracks() {
// Method 1: movie_player.getPlayerResponse()
try {
const player = document.querySelector('#movie_player');
if (player?.getPlayerResponse) {
const pr = player.getPlayerResponse();
const tracks = pr?.captions?.playerCaptionsTracklistRenderer?.captionTracks;
if (tracks?.length) return tracks;
}
} catch (_) { /* fallthrough */ }
// Method 2: ytInitialPlayerResponse global
try {
const pr = window.ytInitialPlayerResponse;
const tracks = pr?.captions?.playerCaptionsTracklistRenderer?.captionTracks;
if (tracks?.length) return tracks;
} catch (_) { /* fallthrough */ }
// Method 3: Parse from inline scripts
try {
const scripts = document.querySelectorAll('script');
for (const script of scripts) {
const text = script.textContent || '';
if (text.includes('captionTracks')) {
const match = text.match(/"captionTracks":\s*(\[.*?\])/);
if (match) {
const tracks = JSON.parse(match[1]);
if (tracks?.length) return tracks;
}
}
}
} catch (_) { /* fallthrough */ }
return null;
}
async function getPotToken(videoId) {
try {
const cacheKey = `yt-caption-potoken-${videoId}`;
const cached = sessionStorage.getItem(cacheKey);
if (cached) return cached;
const ccButton = document.querySelector('.ytp-subtitles-button.ytp-button') ||
document.querySelector('button[data-tooltip-target-id="ytp-captions-button"]');
if (!ccButton) return '';
performance.clearResourceTimings();
ccButton.click();
ccButton.click();
let pot = null;
for (let i = 0; i <= 500; i += 50) {
await new Promise(r => setTimeout(r, 50));
const entries = performance.getEntriesByType('resource')
.filter(e => e.name.includes('/api/timedtext?'));
const entry = entries[entries.length - 1];
if (entry) {
try {
pot = new URL(entry.name).searchParams.get('pot');
if (pot) break;
} catch (_) { /* ignore malformed URL */ }
}
}
if (pot) {
sessionStorage.setItem(cacheKey, pot);
return pot;
}
return '';
} catch (_) {
return '';
}
}
function parseXML(xmlText) {
const segments = [];
const regex = /<text\s+start="([^"]*)"(?:\s+dur="([^"]*)")?\s*>([\s\S]*?)<\/text>/g;
let match;
while ((match = regex.exec(xmlText)) !== null) {
segments.push({
start: parseFloat(match[1] || '0'),
duration: parseFloat(match[2] || '0'),
text: decodeXMLEntities(match[3] || '')
});
}
return segments;
}
function decodeXMLEntities(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(parseInt(n)))
.replace(/\n/g, ' ')
.trim();
}
function formatTime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
async function getTranscript(videoId, preferLang = 'auto', includeTimestamps = true) {
if (!videoId) {
return { success: false, error: 'No video ID found. Please navigate to a YouTube video.' };
}
const tracks = getCaptionTracks();
if (!tracks || tracks.length === 0) {
return { success: false, error: 'No captions available for this video. It may not have subtitles, or it may be age-restricted.' };
}
let track;
if (preferLang && preferLang !== 'auto') {
track = tracks.find(t => t.languageCode === preferLang) ||
tracks.find(t => t.languageCode?.startsWith(preferLang));
}
if (!track) {
track = tracks.find(t => t.languageCode === 'en') ||
tracks.find(t => t.languageCode?.startsWith('en')) ||
tracks[0];
}
const captionUrl = track.baseUrl;
if (!captionUrl) {
return { success: false, error: 'Caption track found but has no URL. Try refreshing the page.' };
}
const methods = [
async () => {
const pot = await getPotToken(videoId);
let url = captionUrl;
if (pot) url += `&pot=${pot}&c=WEB`;
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
return await resp.text();
},
async () => {
const resp = await fetch(captionUrl, { credentials: 'omit', headers: { 'Cookie': '' } });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
return await resp.text();
},
async () => {
const pot = await getPotToken(videoId);
let url = captionUrl + '&fmt=json3';
if (pot) url += `&pot=${pot}&c=WEB`;
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json();
const events = data.events?.filter(e => e.segs) || [];
return events.map(e => ({
start: (e.tStartMs || 0) / 1000,
duration: (e.dDurationMs || 0) / 1000,
text: e.segs.map(s => s.utf8 || '').join('')
}));
}
];
for (const method of methods) {
try {
const result = await method();
let segments;
if (typeof result === 'string') {
if (!result || result.trim().length === 0) throw new Error('Empty response');
segments = parseXML(result);
} else {
segments = result;
}
if (segments && segments.length > 0) {
const transcript = segments
.filter(s => s.text && s.text.trim())
.map(s => includeTimestamps ? `[${formatTime(s.start)}] ${s.text.trim()}` : s.text.trim())
.join('\n');
if (!transcript.trim()) throw new Error('Transcript parsed but contained no text');
return {
success: true,
transcript,
segmentCount: segments.length,
language: track.languageCode || track.name?.simpleText || 'unknown'
};
}
} catch (_) {
// Try next method
}
}
return { success: false, error: 'Could not fetch captions. The video may be age-restricted or region-locked. Try refreshing the page.' };
}