-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgallery.js
More file actions
738 lines (622 loc) · 26 KB
/
Copy pathgallery.js
File metadata and controls
738 lines (622 loc) · 26 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/**
* E-Hentai / ExHentai gallery bootstrap.
* Adds a reader entry on gallery pages and takes over direct single-image links.
*/
// 调试日志开关:从 chrome.storage.local 读取 eh_debug_mode
let debugModeEnabled = false;
try {
if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
chrome.storage.local.get(['eh_debug_mode'], (result) => {
debugModeEnabled = result.eh_debug_mode === true;
});
}
} catch (e) {
// 忽略错误,保持 debugModeEnabled = false
}
/**
* 调试日志函数:仅在 options 页面开启调试模式时输出
* @param {...any} args - 传递给 console.log 的参数
*/
function debugLog(...args) {
if (debugModeEnabled) {
console.log(...args);
}
}
(function() {
'use strict';
function tr(key, params) {
const i18n = window.MGR_I18N;
if (i18n && typeof i18n.t === 'function') {
return i18n.t(key, params);
}
const fallback = {
appName: 'Gallery Reader',
launchFailed: 'Failed to launch reader: {message}'
};
let text = fallback[key] || key;
if (params) {
for (const [name, value] of Object.entries(params)) {
text = text.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value));
}
}
return text;
}
function getHashPage() {
const match = (window.location.hash || '').match(/^#(\d+)$/);
if (!match) return null;
const page = parseInt(match[1], 10);
return Number.isFinite(page) && page > 0 ? page : null;
}
function getPathInfo() {
const pathname = window.location.pathname || '';
const galleryMatch = pathname.match(/^\/g\/(\d+)\/([a-f0-9]+)/i);
if (galleryMatch) {
return {
type: 'gallery',
gid: parseInt(galleryMatch[1], 10),
token: galleryMatch[2],
startPage: getHashPage(),
imgkey: null
};
}
const imageMatch = pathname.match(/^\/s\/([a-f0-9]+)\/(\d+)-(\d+)\/?$/i);
if (imageMatch) {
return {
type: 'image',
gid: parseInt(imageMatch[2], 10),
token: null,
startPage: parseInt(imageMatch[3], 10),
imgkey: imageMatch[1]
};
}
return null;
}
const pathInfo = getPathInfo();
const isImagePage = !!(pathInfo && pathInfo.type === 'image');
const shouldAutoLaunch = isImagePage || !!(pathInfo && pathInfo.type === 'gallery' && pathInfo.startPage);
let imagePageBootObserver = null;
let imagePageBootTimer = null;
function removeImagePageBootMask() {
try {
document.documentElement.classList.remove('gallery-reader-eh-image-boot');
document.getElementById('gallery-reader-eh-image-boot-style')?.remove();
if (imagePageBootObserver) imagePageBootObserver.disconnect();
if (imagePageBootTimer) clearTimeout(imagePageBootTimer);
} catch {}
imagePageBootObserver = null;
imagePageBootTimer = null;
}
function installImagePageBootMask() {
if (!shouldAutoLaunch) return;
try {
document.documentElement.classList.add('gallery-reader-eh-image-boot');
if (!document.getElementById('gallery-reader-eh-image-boot-style')) {
const style = document.createElement('style');
style.id = 'gallery-reader-eh-image-boot-style';
style.textContent = [
'html.gallery-reader-eh-image-boot,',
'html.gallery-reader-eh-image-boot body { background: #111317 !important; }',
'html.gallery-reader-eh-image-boot body > :not(#eh-reader-container) { visibility: hidden !important; }',
'html.gallery-reader-eh-image-boot #eh-reader-container,',
'html.gallery-reader-eh-image-boot #eh-reader-container * { visibility: visible !important; }'
].join('\n');
(document.head || document.documentElement).appendChild(style);
}
imagePageBootObserver = new MutationObserver(() => {
if (document.getElementById('eh-reader-container')) removeImagePageBootMask();
});
imagePageBootObserver.observe(document.documentElement, { childList: true, subtree: true });
imagePageBootTimer = setTimeout(removeImagePageBootMask, 12000);
} catch {}
}
installImagePageBootMask();
// 防止重复注入
if (window.ehGalleryBootstrapInjected) {
return;
}
window.ehGalleryBootstrapInjected = true;
const siteBridge = window.MGR_SITE_BRIDGE;
if (!siteBridge) {
console.error('[Gallery Reader] Shared site bridge is unavailable');
return;
}
debugLog('[Gallery Reader] Gallery bootstrap script loaded');
// 从页面脚本中捕获变量
function extractPageVariables() {
const data = {
gid: pathInfo?.gid || null,
token: pathInfo?.token || null,
startPage: pathInfo?.startPage || null,
imgkey: pathInfo?.imgkey || null,
galleryUrl: null,
galleryPageIndex: null,
initialImageUrl: '',
apiUrl: 'https://api.e-hentai.org/api.php',
apiuid: null,
apikey: null,
title: document.querySelector('#gn')?.textContent || document.title,
baseUrl: `${window.location.origin}/`
};
// 优先从 URL 提取 gid 和 token(最可靠的方法)
// URL 格式: https://e-hentai.org/g/3032923/bf5e303c3d/
const urlMatch = window.location.pathname.match(/\/g\/(\d+)\/([a-f0-9]+)/);
if (urlMatch) {
data.gid = parseInt(urlMatch[1]);
data.token = urlMatch[2];
try {
const galleryUrl = new URL(window.location.href);
galleryUrl.hash = '';
galleryUrl.searchParams.delete('report');
const galleryPageIndex = parseInt(galleryUrl.searchParams.get('p'), 10);
data.galleryPageIndex = Number.isFinite(galleryPageIndex) && galleryPageIndex >= 0
? galleryPageIndex
: 0;
data.galleryUrl = galleryUrl.href;
} catch {
data.galleryUrl = `${window.location.origin}/g/${data.gid}/${data.token}/`;
}
debugLog('[Gallery Reader] Extracted from URL: gid=' + data.gid + ', token=' + data.token);
}
if (isImagePage) {
const nativeBackLink = document.querySelector('#i5 a[href*="/g/"]');
const galleryLinks = [nativeBackLink, ...document.querySelectorAll('a[href*="/g/"]')].filter(Boolean);
let selectedGallery = null;
for (const link of galleryLinks) {
try {
const candidateUrl = new URL(link.getAttribute('href'), window.location.origin);
const candidateMatch = candidateUrl.pathname.match(/\/g\/(\d+)\/([a-f0-9]+)/i);
if (!candidateMatch || parseInt(candidateMatch[1], 10) !== data.gid) continue;
const candidate = { url: candidateUrl, match: candidateMatch };
if (!selectedGallery) selectedGallery = candidate;
if (!candidateUrl.searchParams.has('report')) {
selectedGallery = candidate;
break;
}
} catch {}
}
if (selectedGallery) {
const galleryPageIndex = parseInt(selectedGallery.url.searchParams.get('p'), 10);
const normalizedPageIndex = Number.isFinite(galleryPageIndex) && galleryPageIndex >= 0
? galleryPageIndex
: 0;
const cleanGalleryUrl = new URL(selectedGallery.url.pathname, selectedGallery.url.origin);
if (normalizedPageIndex > 0) cleanGalleryUrl.searchParams.set('p', String(normalizedPageIndex));
data.token = selectedGallery.match[2];
data.galleryUrl = cleanGalleryUrl.href;
data.galleryPageIndex = normalizedPageIndex;
}
}
const initialImage = document.getElementById('img');
if (initialImage) {
data.initialImageUrl = initialImage.currentSrc || initialImage.getAttribute('src') || '';
}
// 遍历所有 script 标签(作为备选或补充)
const scripts = document.querySelectorAll('script');
for (let script of scripts) {
const content = script.textContent;
if (!content) continue;
// 提取 gid(如果 URL 中没有提取到)
if (!data.gid) {
const gidMatch = content.match(/var\s+gid\s*=\s*(\d+);?/);
if (gidMatch) data.gid = parseInt(gidMatch[1]);
}
// 提取 token(如果 URL 中没有提取到)
if (!data.token) {
const tokenMatch = content.match(/var\s+token\s*=\s*["']([^"']+)["'];?/);
if (tokenMatch) data.token = tokenMatch[1];
}
if (!data.startPage) {
const startPageMatch = content.match(/var\s+startpage\s*=\s*(\d+);?/);
if (startPageMatch) data.startPage = parseInt(startPageMatch[1], 10);
}
if (!data.imgkey) {
const startKeyMatch = content.match(/var\s+startkey\s*=\s*["']([^"']+)["'];?/);
if (startKeyMatch) data.imgkey = startKeyMatch[1];
}
// 提取 api_url
const apiMatch = content.match(/var\s+api_url\s*=\s*["']([^"']+)["'];?/);
if (apiMatch) data.apiUrl = apiMatch[1];
// 提取 apiuid
if (!data.apiuid) {
const uidMatch = content.match(/var\s+apiuid\s*=\s*(\d+);?/);
if (uidMatch) data.apiuid = parseInt(uidMatch[1]);
}
// 提取 apikey
if (!data.apikey) {
const keyMatch = content.match(/var\s+apikey\s*=\s*["']([^"']+)["'];?/);
if (keyMatch) data.apikey = keyMatch[1];
}
// 提取 base_url
const baseMatch = content.match(/var\s+base_url\s*=\s*["']([^"']+)["'];?/);
if (baseMatch) data.baseUrl = baseMatch[1];
}
return data;
}
let pageData = extractPageVariables();
debugLog('[Gallery Reader] Page data captured:', pageData);
/**
* 通过 API 获取画廊数据
*/
let galleryMetadata = null;
let galleryMetadataPromise = null;
function fetchGalleryMetadata() {
if (galleryMetadata) return Promise.resolve(galleryMetadata);
if (galleryMetadataPromise) return galleryMetadataPromise;
galleryMetadataPromise = (async () => {
const response = await fetch(pageData.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
method: 'gdata',
gidlist: [[pageData.gid, pageData.token]],
namespace: 1
})
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
if (data.gmetadata && data.gmetadata[0]) {
const metadata = data.gmetadata[0];
debugLog('[Gallery Reader] Gallery metadata:', metadata);
// 如果返回了错误
if (metadata.error) {
throw new Error(metadata.error);
}
galleryMetadata = {
gid: metadata.gid,
token: metadata.token,
title: metadata.title,
title_jpn: metadata.title_jpn,
category: metadata.category,
filecount: metadata.filecount,
tags: metadata.tags
};
return galleryMetadata;
}
throw new Error('No metadata returned');
})().catch((error) => {
console.error('[Gallery Reader] Failed to fetch gallery metadata:', error);
throw error;
}).finally(() => {
galleryMetadataPromise = null;
});
return galleryMetadataPromise;
}
// 缓存正在进行的 Gallery 分页抓取请求,避免重复抓取
const galleryPageFetchCache = new Map(); // galleryPageIndex -> Promise
// 保存每页缩略图数量(在 DOM 被替换前检测)
let detectedThumbsPerPage = 0;
function inferThumbsPerPageFromBacklink() {
const page = Number(pageData.startPage);
const galleryPageIndex = Number(pageData.galleryPageIndex);
if (!Number.isFinite(page) || page < 1 || !Number.isFinite(galleryPageIndex) || galleryPageIndex <= 0) {
return 0;
}
const minimum = Math.ceil(page / (galleryPageIndex + 1));
const maximum = Math.floor((page - 1) / galleryPageIndex);
return minimum === maximum && minimum > 0 ? minimum : 0;
}
function detectThumbsPerPageFromGallery() {
const links = document.querySelectorAll('#gdt a[href*="/s/"]');
if (links.length === 0) return 0;
const galleryPageIndex = Number(pageData.galleryPageIndex);
const firstMatch = (links[0].getAttribute('href') || '').match(/\/s\/[a-f0-9]+\/\d+-(\d+)/i);
if (galleryPageIndex > 0 && firstMatch) {
const firstPage = parseInt(firstMatch[1], 10);
const inferred = (firstPage - 1) / galleryPageIndex;
if (Number.isInteger(inferred) && inferred >= links.length) return inferred;
}
return links.length;
}
function seedKnownImageEntries(imagelist) {
const links = isImagePage
? document.querySelectorAll('a[href*="/s/"]')
: document.querySelectorAll('#gdt a[href*="/s/"]');
links.forEach((link) => {
const href = link.getAttribute('href') || '';
const match = href.match(/\/s\/([a-f0-9]+)\/(\d+)-(\d+)/i);
if (!match || parseInt(match[2], 10) !== pageData.gid) return;
const pageIndex = parseInt(match[3], 10) - 1;
if (imagelist[pageIndex]) imagelist[pageIndex].k = match[1];
});
if (!isImagePage || !Number.isFinite(pageData.startPage)) return;
const currentEntry = imagelist[pageData.startPage - 1];
if (!currentEntry) return;
if (pageData.imgkey) currentEntry.k = pageData.imgkey;
if (/^https?:\/\/[^\s]+\.(?:jpg|jpeg|png|gif|webp|avif)(?:[?#].*)?$/i.test(pageData.initialImageUrl)) {
currentEntry.url = pageData.initialImageUrl;
}
}
function replaceReaderAddress(readerData) {
const startPage = Number(readerData?.startAt);
if (!Number.isFinite(startPage) || startPage < 1 || !readerData?.gallery_url) return;
try {
const readerUrl = new URL(readerData.gallery_url, window.location.origin);
readerUrl.hash = String(startPage);
window.history.replaceState(window.history.state, '', readerUrl.href);
} catch {}
}
/**
* 从 Gallery 分页抓取指定范围的 imgkey
* Gallery 每页显示的缩略图数量取决于用户设置(通常是 20、40 等)
*/
async function fetchImgkeysFromGallery(startPage, endPage) {
try {
// 使用已检测的值,或从 DOM 检测,或默认 20
let thumbsPerPage = detectedThumbsPerPage;
if (thumbsPerPage <= 0) {
const initialThumbnails = document.querySelectorAll('#gdt a[href*="/s/"]').length;
thumbsPerPage = initialThumbnails > 0 ? initialThumbnails : 20;
}
// 计算需要抓取哪个 Gallery 分页
const galleryPageIndex = Math.floor(startPage / thumbsPerPage);
// 检查是否已有进行中的请求
if (galleryPageFetchCache.has(galleryPageIndex)) {
debugLog(`[Gallery Reader] Gallery page ${galleryPageIndex} fetch already in progress, reusing...`);
return galleryPageFetchCache.get(galleryPageIndex);
}
const galleryUrl = `${window.location.origin}/g/${pageData.gid}/${pageData.token}/?p=${galleryPageIndex}`;
debugLog(`[Gallery Reader] Fetching imgkeys from gallery page ${galleryPageIndex} (${thumbsPerPage} thumbs/page):`, galleryUrl);
const fetchPromise = (async () => {
const response = await fetch(galleryUrl);
if (!response.ok) {
throw new Error(`Failed to fetch gallery page: ${response.status}`);
}
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 从缩略图链接提取 imgkey
const thumbnailLinks = doc.querySelectorAll('#gdt a[href*="/s/"]');
debugLog(`[Gallery Reader] Found ${thumbnailLinks.length} thumbnails in gallery page ${galleryPageIndex}`);
if (thumbnailLinks.length > detectedThumbsPerPage) {
detectedThumbsPerPage = thumbnailLinks.length;
}
let updatedCount = 0;
thumbnailLinks.forEach((link, index) => {
const href = link.getAttribute('href');
const match = href.match(/\/s\/([a-f0-9]+)\/\d+-(\d+)/);
if (match) {
const imgkey = match[1];
const pageNum = parseInt(match[2]) - 1; // 转换为 0-based index
if (window.__ehReaderData?.imagelist[pageNum]) {
window.__ehReaderData.imagelist[pageNum].k = imgkey;
updatedCount++;
}
}
});
debugLog(`[Gallery Reader] Updated ${updatedCount} imgkeys for gallery page ${galleryPageIndex}`);
})().finally(() => {
galleryPageFetchCache.delete(galleryPageIndex);
});
// 将 Promise 加入缓存
galleryPageFetchCache.set(galleryPageIndex, fetchPromise);
return fetchPromise;
} catch (error) {
console.error(`[Gallery Reader] Failed to fetch imgkeys:`, error);
throw error;
}
}
/**
* 构造单页 URL(不使用 API,让 content.js 去抓取 HTML)
* Gallery 模式下,直接返回单页 URL,让 MPV 模式的 fetchRealImageUrl 处理
*/
async function fetchPageImageUrl(page) {
try {
const imageEntry = window.__ehReaderData?.imagelist[page];
if (imageEntry?.url) {
return {
pageNumber: page + 1,
pageUrl: imageEntry.url,
imgkey: imageEntry.k || ''
};
}
// 从 imagelist 获取该页的 imgkey
let imgkey = imageEntry?.k || '';
// 如果 imgkey 不存在,动态从 Gallery 页面抓取
if (!imgkey) {
debugLog(`[Gallery Reader] Page ${page} imgkey not cached, fetching from gallery...`);
// 使用已保存的每页数量,或默认 20
const thumbsPerPage = detectedThumbsPerPage > 0 ? detectedThumbsPerPage : 20;
// 只获取当前页所在的 Gallery 页面(不预加载,避免风控)
const currentGalleryPage = Math.floor(page / thumbsPerPage);
await fetchImgkeysFromGallery(currentGalleryPage * thumbsPerPage, (currentGalleryPage + 1) * thumbsPerPage);
// 获取后检查 imgkey
imgkey = window.__ehReaderData?.imagelist[page]?.k || '';
if (!imgkey) {
throw new Error(`Page ${page} imgkey not found after fetching`);
}
}
// 构造单页 URL: https://e-hentai.org/s/{imgkey}/{gid}-{page}
const pageUrl = `${window.location.origin}/s/${imgkey}/${pageData.gid}-${page + 1}`;
debugLog(`[Gallery Reader] Page ${page} URL:`, pageUrl);
// 返回单页 URL,content.js 会自动抓取 HTML 提取图片
return {
pageNumber: page + 1,
pageUrl: pageUrl, // 返回单页 URL 而不是图片 URL
imgkey: imgkey
};
} catch (error) {
console.error(`[Gallery Reader] Failed to construct page URL for ${page}:`, error);
throw error;
}
}
/**
* 启动阅读器
*/
async function launchReader(startPage /* 1-based, optional */) {
siteBridge.markReaderStart(true);
debugLog('[Gallery Reader] Launching reader from Gallery page...');
try {
// 0. 在 DOM 被替换前,检测并保存每页缩略图数量
const galleryPageSize = detectThumbsPerPageFromGallery();
if (galleryPageSize > 0) {
detectedThumbsPerPage = galleryPageSize;
} else if (detectedThumbsPerPage <= 0) {
detectedThumbsPerPage = inferThumbsPerPageFromBacklink() || 20;
}
debugLog(`[Gallery Reader] Detected ${detectedThumbsPerPage} thumbs per gallery page`);
// Start the heavy controller in parallel, but do not block shell mounting on it.
siteBridge.ensureReaderContentScript().catch(() => {});
const metadata = await fetchGalleryMetadata();
const pageCount = parseInt(metadata.filecount);
debugLog(`[Gallery Reader] Gallery has ${pageCount} pages`);
// 2. 构建图片列表(类似 MPV 的 imagelist 格式)
const imagelist = [];
// 初始化所有页面,imgkey 暂时为空
for (let i = 0; i < pageCount; i++) {
imagelist.push({
n: (i + 1).toString(),
k: '', // 图片的 key,稍后按需加载
t: '' // 缩略图 URL
});
}
// Gallery 页提供整页 imgkey;单图页则至少提供当前页及相邻页。
seedKnownImageEntries(imagelist);
debugLog('[Gallery Reader] Imagelist sample:', imagelist.slice(0, 3));
// 3. 构建 pageData(与 content.js 格式兼容)
const readerPageData = {
imagelist: imagelist,
pagecount: pageCount,
gid: pageData.gid,
mpvkey: pageData.token,
gallery_url: pageData.galleryUrl || `${pageData.baseUrl}g/${pageData.gid}/${pageData.token}/`,
galleryPageSize: detectedThumbsPerPage,
title: metadata.title,
source: 'gallery', // 标记数据来源
startAt: (typeof startPage === 'number' && startPage >= 1 && startPage <= pageCount) ? startPage : undefined
};
replaceReaderAddress(readerPageData);
// 4. 挂载到 window(供 content.js 使用)
window.__ehReaderData = readerPageData;
// 5. 创建标记,让 content.js 知道是从 Gallery 启动的
debugLog('[Gallery Reader] Injecting reader UI...');
window.__ehGalleryBootstrap = {
enabled: true,
fetchPageImageUrl: fetchPageImageUrl
};
// 6. 确保主阅读器脚本已加载,再通知 content.js 启动
await siteBridge.startReader(readerPageData);
removeImagePageBootMask();
debugLog('[Gallery Reader] Gallery reader ready event dispatched');
} catch (error) {
window.__ehReaderLaunching = false;
removeImagePageBootMask();
console.error('[Gallery Reader] Failed to launch reader:', error);
alert(tr('launchFailed', { message: error.message || String(error) }));
}
}
/**
* 在 Gallery 页面添加启动按钮
*/
function addLaunchButton() {
// 找到右侧操作区域(#gd5)
const actionPanel = document.querySelector('#gd5');
if (!actionPanel) {
console.warn('[Gallery Reader] Cannot find action panel (#gd5)');
return;
}
const mpvLink = document.querySelector('a[href*="/mpv/"]');
// 检查是否已经有 MPV 链接
if (mpvLink) {
debugLog('[Gallery Reader] MPV link already exists, user has permission');
// 如果有 MPV 权限,可以选择不添加按钮,或者添加一个备用入口
// 这里我们仍然添加,作为备选方案
}
// 创建按钮容器(保持与页面原生风格一致,不加自定义背景)
const buttonContainer = document.createElement('p');
buttonContainer.className = 'g2 gsp';
// 不设置额外样式,避免破坏布局对齐
// 创建图标
const icon = document.createElement('img');
icon.src = 'https://ehgt.org/g/mr.gif';
// 创建按钮
const button = document.createElement('a');
button.href = '#';
button.textContent = tr('appName');
// 使用站点默认链接样式,避免突兀
button.style.cssText = '';
button.onclick = (e) => {
e.preventDefault();
launchReader();
};
buttonContainer.appendChild(icon);
buttonContainer.appendChild(document.createTextNode(' '));
buttonContainer.appendChild(button);
// 插入到 MPV 按钮下方(如果存在)或顶部
let insertAfterRef = null;
if (mpvLink) {
insertAfterRef = mpvLink.closest('p');
}
if (insertAfterRef) {
insertAfterRef.parentNode.insertBefore(buttonContainer, insertAfterRef.nextSibling);
} else {
// 插入到面板顶部
actionPanel.insertBefore(buttonContainer, actionPanel.firstChild);
}
debugLog('[Gallery Reader] Launch button added');
}
// 拦截缩略图点击,直接用我们的阅读器打开并跳转到对应页
function interceptThumbnailClicks() {
const grid = document.getElementById('gdt');
if (!grid) return;
// 放行组合键/中键等原生行为
const shouldBypass = (ev) => ev.ctrlKey || ev.shiftKey || ev.metaKey || ev.altKey || ev.button === 1;
grid.addEventListener('auxclick', (e) => {
// 中键点击等,直接放行
}, true);
grid.addEventListener('click', (e) => {
if (e.defaultPrevented) return;
if (shouldBypass(e)) return; // 保留原站行为(新标签、打开等)
const a = e.target && (e.target.closest ? e.target.closest('a[href*="/s/"]') : null);
if (!a) return;
const href = a.getAttribute('href') || '';
const m = href.match(/\/s\/([a-f0-9]+)\/(\d+)-(\d+)/i);
if (!m) return; // 非预期链接,放行
e.preventDefault();
const pageNum = parseInt(m[3], 10); // 1-based
const now = Date.now();
const cooldownUntil = window.__ehReaderCooldown || 0;
if (cooldownUntil > now || window.__ehReaderLaunching) return;
window.__ehReaderLaunching = true;
window.__ehReaderCooldown = now + 1200; // 1.2s 冷却避免重复触发
launchReader(pageNum).catch(() => { window.__ehReaderLaunching = false; });
}, true); // 捕获阶段优先,减少站内脚本干预
}
// 在 DOM 准备好后立即绑定点击事件
function ensureInterception() {
if (document.getElementById('gdt')) {
// DOM 已准备好,直接执行
interceptThumbnailClicks();
} else if (document.readyState === 'loading') {
// 等待 DOMContentLoaded
document.addEventListener('DOMContentLoaded', interceptThumbnailClicks);
} else {
// DOM 已完全加载但 gdt 还没出现,延迟重试
setTimeout(ensureInterception, 100);
}
}
function initializePage() {
pageData = extractPageVariables();
debugLog('[Gallery Reader] Refreshed page data:', pageData);
if (!pageData.gid || !pageData.token) {
removeImagePageBootMask();
console.warn('[Gallery Reader] Missing gid or token, cannot initialize');
return;
}
if (shouldAutoLaunch) {
detectedThumbsPerPage = inferThumbsPerPageFromBacklink() || detectedThumbsPerPage;
if (window.__ehReaderLaunching) return;
window.__ehReaderLaunching = true;
launchReader(pageData.startPage);
return;
}
addLaunchButton();
ensureInterception();
siteBridge.warmReader(fetchGalleryMetadata);
}
siteBridge.onReady(initializePage);
debugLog('[Gallery Reader] Gallery page script initialized');
})();