-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
453 lines (382 loc) · 14.3 KB
/
content.js
File metadata and controls
453 lines (382 loc) · 14.3 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
async function extractPageContent() {
const title = document.title;
let content = '';
let extractMethod = '';
// YouTubeページでの字幕取得を優先
if (window.location.hostname === 'www.youtube.com' && window.location.pathname === '/watch') {
console.log('🔍 [Dify Extension] YouTube video detected, attempting subtitle extraction');
const subtitleResult = await extractYouTubeSubtitles();
if (subtitleResult && subtitleResult.transcript) {
content = subtitleResult.transcript;
extractMethod = `YouTube字幕から抽出(${subtitleResult.language})${subtitleResult.isAutoGenerated ? ' - 自動生成' : ' - 手動作成'}`;
return {
title,
content: content.trim(),
url: window.location.href,
extractMethod,
contentLength: content.trim().length
};
}
console.log('🔍 [Dify Extension] YouTube subtitle extraction failed, falling back to default method');
}
// カスタムセレクタの設定を確認
const { extractSelectors } = await chrome.storage.sync.get(['extractSelectors']);
if (extractSelectors && extractSelectors.trim()) {
// 上級者設定: カスタムセレクタを使用
const customSelectors = extractSelectors.split(',').map(s => s.trim());
for (const selector of customSelectors) {
try {
const element = document.querySelector(selector);
if (element) {
content = element.innerText;
extractMethod = `カスタムセレクタ「${selector}」から抽出`;
break;
}
} catch (error) {
console.warn('Invalid selector:', selector);
}
}
}
if (!content) {
// デフォルト設定: body全体から取得(不要な要素を除外)
const bodyClone = document.body.cloneNode(true);
// 不要な要素を削除
const unwantedSelectors = [
'script', 'style', 'noscript', 'iframe', 'object', 'embed',
'header', 'nav', 'footer', 'aside', '.advertisement', '.ads',
'.social-share', '.comments', '.sidebar', '.menu', '.navigation',
'[class*="ad-"]', '[id*="ad-"]', '[class*="advertisement"]',
'[class*="social"]', '[class*="share"]', '[class*="comment"]',
'.cookie-notice', '.popup', '.modal', '.overlay',
'#dify-floating-button' // 自身のフローティングボタンを除外
];
unwantedSelectors.forEach(selector => {
try {
const elements = bodyClone.querySelectorAll(selector);
elements.forEach(el => el.remove());
} catch (error) {
console.warn('Selector removal failed:', selector);
}
});
// テキストを取得
content = bodyClone.innerText || bodyClone.textContent || '';
// 空行の除去と整理
content = content
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
.join('\n')
.replace(/\n{3,}/g, '\n\n'); // 3つ以上の連続改行を2つに
extractMethod = 'body全体から抽出(不要要素除外済み)';
}
return {
title,
content: content.trim(),
url: window.location.href,
extractMethod,
contentLength: content.trim().length
};
}
// YouTube字幕抽出機能
async function extractYouTubeSubtitles() {
try {
console.log('🔍 [Dify Extension] Starting YouTube subtitle extraction');
// ytInitialPlayerResponseの取得を試行
let playerResponse = window.ytInitialPlayerResponse;
// グローバル変数が利用できない場合はHTMLから抽出
if (!playerResponse) {
try {
const scriptTags = document.querySelectorAll('script');
for (const script of scriptTags) {
if (script.textContent.includes('ytInitialPlayerResponse')) {
const match = script.textContent.match(/ytInitialPlayerResponse\s*=\s*({.+?});/);
if (match) {
playerResponse = JSON.parse(match[1]);
break;
}
}
}
} catch (error) {
console.error('🔍 [Dify Extension] ytInitialPlayerResponse parsing error:', error);
return null;
}
}
if (!playerResponse) {
console.log('🔍 [Dify Extension] ytInitialPlayerResponse not found');
return null;
}
// 字幕トラックの確認
const captionTracks = playerResponse?.captions?.playerCaptionsTracklistRenderer?.captionTracks;
if (!captionTracks || captionTracks.length === 0) {
console.log('🔍 [Dify Extension] No subtitle tracks available');
return null;
}
console.log('🔍 [Dify Extension] Found', captionTracks.length, 'subtitle tracks');
// 優先言語順で字幕を取得(日本語 > 英語 > その他)
const preferredLanguages = ['ja', 'en'];
let selectedTrack = null;
// まず手動作成字幕を探す
for (const lang of preferredLanguages) {
selectedTrack = captionTracks.find(track =>
track.languageCode === lang && !track.vssId.includes('.a.')
);
if (selectedTrack) {
console.log('🔍 [Dify Extension] Found manual subtitle in', lang);
break;
}
}
// 手動字幕がない場合は自動生成字幕を使用
if (!selectedTrack) {
for (const lang of preferredLanguages) {
selectedTrack = captionTracks.find(track =>
track.languageCode === lang && track.vssId.includes('.a.')
);
if (selectedTrack) {
console.log('🔍 [Dify Extension] Found auto-generated subtitle in', lang);
break;
}
}
}
// どちらもない場合は最初のトラックを使用
if (!selectedTrack) {
selectedTrack = captionTracks[0];
console.log('🔍 [Dify Extension] Using first available subtitle track');
}
if (!selectedTrack || !selectedTrack.baseUrl) {
console.log('🔍 [Dify Extension] No suitable subtitle track found');
return null;
}
// 字幕データの取得
try {
console.log('🔍 [Dify Extension] Fetching subtitle data from:', selectedTrack.baseUrl);
const response = await fetch(selectedTrack.baseUrl + '&fmt=json3');
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const captionData = await response.json();
console.log('🔍 [Dify Extension] Subtitle data fetched successfully');
// 字幕テキストの整形
const transcript = processYouTubeTranscript(captionData);
if (!transcript || transcript.length < 10) {
console.log('🔍 [Dify Extension] Transcript too short or empty');
return null;
}
return {
language: selectedTrack.languageCode,
languageName: selectedTrack.name?.simpleText || selectedTrack.languageCode,
isAutoGenerated: selectedTrack.vssId.includes('.a.'),
transcript: transcript
};
} catch (fetchError) {
console.error('🔍 [Dify Extension] Failed to fetch subtitle data:', fetchError);
return null;
}
} catch (error) {
console.error('🔍 [Dify Extension] YouTube subtitle extraction error:', error);
return null;
}
}
// YouTube字幕データの整形処理
function processYouTubeTranscript(captionData) {
try {
if (!captionData || !captionData.events) {
return '';
}
const transcriptSegments = [];
let currentParagraph = [];
let lastEndTime = 0;
captionData.events
.filter(event => event.segs && event.segs.length > 0)
.forEach(event => {
const text = event.segs
.map(seg => seg.utf8 || '')
.join('')
.trim();
if (text) {
const startTimeMs = event.tStartMs || 0;
const durationMs = event.dDurationMs || 0;
// 5秒以上の間隔が空いた場合は段落を分ける
if (startTimeMs - lastEndTime > 5000 && currentParagraph.length > 0) {
transcriptSegments.push(currentParagraph.join(' '));
currentParagraph = [];
}
currentParagraph.push(text);
lastEndTime = startTimeMs + durationMs;
}
});
// 最後の段落を追加
if (currentParagraph.length > 0) {
transcriptSegments.push(currentParagraph.join(' '));
}
// 段落を改行で結合し、読みやすい形式にする
return transcriptSegments
.filter(segment => segment.trim().length > 0)
.join('\n\n')
.replace(/\s+/g, ' ') // 複数のスペースを1つに
.trim();
} catch (error) {
console.error('🔍 [Dify Extension] Error processing transcript:', error);
return '';
}
}
// 時間をフォーマット(ミリ秒 → mm:ss形式)
function formatTime(milliseconds) {
const totalSeconds = Math.floor(milliseconds / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('🔍 [Dify Extension] Content script received message:', request);
if (request.action === 'extractContent') {
console.log('🔍 [Dify Extension] Starting content extraction in content script');
extractPageContent().then(pageData => {
console.log('🔍 [Dify Extension] Content extraction completed:', {
title: pageData.title,
contentLength: pageData.contentLength,
extractMethod: pageData.extractMethod
});
sendResponse(pageData);
}).catch(error => {
console.error('🔍 [Dify Extension] Content extraction failed:', error);
sendResponse({ error: error.message });
});
return true; // 非同期レスポンスを示す
}
});
function createFloatingButton() {
const button = document.createElement('div');
button.id = 'dify-floating-button';
button.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
width: 60px;
height: 60px;
background: #4f46e5;
border-radius: 50%;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
cursor: move;
z-index: 10000;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 24px;
transition: transform 0.2s ease;
user-select: none;
`;
button.innerHTML = '💬';
let isDragging = false;
let dragStartX = null;
let dragStartY = null;
let buttonStartX = 0;
let buttonStartY = 0;
function getButtonPosition() {
const rect = button.getBoundingClientRect();
return {
x: rect.left,
y: rect.top
};
}
function setButtonPosition(x, y) {
const maxX = window.innerWidth - 60;
const maxY = window.innerHeight - 60;
x = Math.max(0, Math.min(x, maxX));
y = Math.max(0, Math.min(y, maxY));
button.style.left = x + 'px';
button.style.top = y + 'px';
button.style.right = 'auto';
button.style.bottom = 'auto';
}
// フローティングボタンのクリックハンドラー(サイドパネルを開く)
const clickHandler = () => {
console.log('🔍 [Dify Extension] Floating button clicked, opening side panel');
chrome.runtime.sendMessage({ action: 'openSidePanel' });
};
button.addEventListener('mousedown', (e) => {
isDragging = false;
dragStartX = e.clientX;
dragStartY = e.clientY;
const pos = getButtonPosition();
buttonStartX = pos.x;
buttonStartY = pos.y;
button.style.cursor = 'grabbing';
button.style.transition = 'none';
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (dragStartX === null) return;
const deltaX = e.clientX - dragStartX;
const deltaY = e.clientY - dragStartY;
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if (distance > 5 && !isDragging) {
isDragging = true;
}
if (isDragging) {
setButtonPosition(buttonStartX + deltaX, buttonStartY + deltaY);
}
});
document.addEventListener('mouseup', (e) => {
if (dragStartX === null) return;
const deltaX = Math.abs(e.clientX - dragStartX);
const deltaY = Math.abs(e.clientY - dragStartY);
if (!isDragging && deltaX < 5 && deltaY < 5) {
clickHandler();
}
isDragging = false;
dragStartX = null;
dragStartY = null;
button.style.cursor = 'move';
button.style.transition = 'transform 0.2s ease';
});
button.addEventListener('mouseenter', () => {
if (!isDragging) {
button.style.transform = 'scale(1.1)';
}
});
button.addEventListener('mouseleave', () => {
if (!isDragging) {
button.style.transform = 'scale(1)';
}
});
document.body.appendChild(button);
}
chrome.storage.sync.get(['isEnabled', 'blacklist'], (result) => {
console.log('🔍 [Dify Extension] Storage check result:', result);
// 拡張機能が無効な場合はボタンを作成しない
if (result.isEnabled === false) {
console.log('🔍 [Dify Extension] Extension is disabled, not creating button');
return;
}
// ブラックリストをチェック
const hostname = window.location.hostname;
const blacklist = result.blacklist || [];
if (blacklist.includes(hostname)) {
console.log('🔍 [Dify Extension] Site is blacklisted, not creating floating button:', hostname);
return;
}
console.log('🔍 [Dify Extension] Creating floating button');
createFloatingButton();
});
window.addEventListener('load', () => {
console.log('🔍 [Dify Extension] Page loaded, checking for button');
const existingButton = document.getElementById('dify-floating-button');
if (!existingButton) {
console.log('🔍 [Dify Extension] Button not found, recreating');
chrome.storage.sync.get(['isEnabled', 'blacklist'], (result) => {
// 拡張機能が無効な場合はボタンを作成しない
if (result.isEnabled === false) {
return;
}
// ブラックリストをチェック
const hostname = window.location.hostname;
const blacklist = result.blacklist || [];
if (blacklist.includes(hostname)) {
console.log('🔍 [Dify Extension] Site is blacklisted, not recreating floating button:', hostname);
return;
}
createFloatingButton();
});
}
});