codebydante commited on
Commit
2588714
·
verified ·
1 Parent(s): d0a1894

Subida inicial de ImageNinja HD en la raíz del repositorio

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ baa2d01c-243a-46ba-8e3e-26825045023b.txt filter=lfs diff=lfs merge=lfs -text
_metadata/generated_indexed_rulesets/_ruleset1 ADDED
Binary file (971 Bytes). View file
 
assets/icons/icon.svg ADDED
baa2d01c-243a-46ba-8e3e-26825045023b.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35f993dd108bc169dca769c0d527f26c9f0dba70ae17566af81646811b237d83
3
+ size 146940
manifest.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "Descargador de Imágenes",
4
+ "version": "1.0",
5
+ "description": "Descarga todas las imágenes de la página web donde te encuentres.",
6
+ "icons": {
7
+ "128": "assets/icons/icon.svg"
8
+ },
9
+ "permissions": [
10
+ "activeTab",
11
+ "scripting",
12
+ "downloads",
13
+ "storage",
14
+ "declarativeNetRequest",
15
+ "declarativeNetRequestWithHostAccess"
16
+ ],
17
+ "background": {
18
+ "service_worker": "src/background/background.js"
19
+ },
20
+ "host_permissions": [
21
+ "<all_urls>"
22
+ ],
23
+ "declarative_net_request": {
24
+ "rule_resources": [
25
+ {
26
+ "id": "ruleset_1",
27
+ "enabled": true,
28
+ "path": "rules.json"
29
+ }
30
+ ]
31
+ },
32
+ "action": {
33
+ "default_popup": "src/popup/popup.html",
34
+ "default_title": "Descargar Imágenes",
35
+ "default_icon": "assets/icons/icon.svg"
36
+ }
37
+ }
rules.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": 1,
4
+ "priority": 1,
5
+ "action": {
6
+ "type": "modifyHeaders",
7
+ "requestHeaders": [
8
+ {
9
+ "header": "Referer",
10
+ "operation": "set",
11
+ "value": "https://www.poringa.net/"
12
+ },
13
+ {
14
+ "header": "Origin",
15
+ "operation": "set",
16
+ "value": "https://www.poringa.net"
17
+ }
18
+ ],
19
+ "responseHeaders": [
20
+ {
21
+ "header": "Cross-Origin-Resource-Policy",
22
+ "operation": "remove"
23
+ },
24
+ {
25
+ "header": "Access-Control-Allow-Origin",
26
+ "operation": "set",
27
+ "value": "*"
28
+ }
29
+ ]
30
+ },
31
+ "condition": {
32
+ "urlFilter": "poringa.net",
33
+ "resourceTypes": ["main_frame", "sub_frame", "stylesheet", "script", "image", "font", "object", "xmlhttprequest", "ping", "csp_report", "media", "websocket", "other"]
34
+ }
35
+ }
36
+ ]
src/background/background.js ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const downloadMap = new Map();
2
+ const activeSessions = new Map();
3
+
4
+ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
5
+ if (request.action === 'registerDownload') {
6
+ downloadMap.set(request.url, request.filename);
7
+ sendResponse({ success: true });
8
+ return true;
9
+ }
10
+
11
+ if (request.action === 'startBackgroundDownloads') {
12
+ startBackgroundQueue(request);
13
+ sendResponse({ success: true });
14
+ return true;
15
+ }
16
+
17
+ if (request.action === 'getDownloadProgress') {
18
+ const session = activeSessions.get(request.comicUrl);
19
+ if (session) {
20
+ sendResponse(session);
21
+ } else {
22
+ sendResponse({ downloading: false });
23
+ }
24
+ return true;
25
+ }
26
+ });
27
+
28
+ chrome.downloads.onDeterminingFilename.addListener((item, suggest) => {
29
+ if (downloadMap.has(item.url)) {
30
+ suggest({ filename: downloadMap.get(item.url), conflictAction: 'uniquify' });
31
+ } else {
32
+ suggest();
33
+ }
34
+ });
35
+
36
+ function arrayBufferToBase64(buffer) {
37
+ let binary = '';
38
+ const bytes = new Uint8Array(buffer);
39
+ const len = bytes.byteLength;
40
+ for (let i = 0; i < len; i++) {
41
+ binary += String.fromCharCode(bytes[i]);
42
+ }
43
+ return btoa(binary);
44
+ }
45
+
46
+ function getExtension(url) {
47
+ const cleanUrl = url.split(/[#?]/)[0];
48
+ const parts = cleanUrl.split('.');
49
+ if (parts.length > 1) {
50
+ const ext = parts.pop().toLowerCase();
51
+ if (['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg', 'avif', 'bmp', 'tiff', 'tif', 'ico', 'heic', 'heif', 'jxl'].includes(ext)) {
52
+ return ext;
53
+ }
54
+ }
55
+ return 'jpg';
56
+ }
57
+
58
+ function getQualityFolder(width, height) {
59
+ const max = Math.max(width, height);
60
+ const min = Math.min(width, height);
61
+ if (min >= 2160 || max >= 3840) return '4K';
62
+ if (min >= 1440 || max >= 2560) return '2K';
63
+ if (min >= 1080 || max >= 1920) return '1080p';
64
+ if (min >= 720 || max >= 1280) return '720p';
65
+ return 'Normal';
66
+ }
67
+
68
+ async function startBackgroundQueue({ toDownload, baseSf, uniqueSf, is3Hentai, isForcePNG, separateQuality, renameSequential, comicUrl }) {
69
+ const finalComicUrl = comicUrl || (toDownload[0]?.src || toDownload[0] || 'default');
70
+ const session = {
71
+ downloading: true,
72
+ completed: 0,
73
+ total: toDownload.length
74
+ };
75
+ activeSessions.set(finalComicUrl, session);
76
+
77
+ const total = toDownload.length;
78
+ let completed = 0;
79
+
80
+ const limit = is3Hentai ? 3 : total;
81
+ let active = 0;
82
+ let i = 0;
83
+
84
+ const broadcastProgress = () => {
85
+ chrome.runtime.sendMessage({
86
+ action: 'downloadProgress',
87
+ comicUrl: finalComicUrl,
88
+ completed: completed,
89
+ total: total,
90
+ downloading: true
91
+ }).catch(() => {
92
+ // Ignore error when popup is closed
93
+ });
94
+ session.completed = completed;
95
+ session.total = total;
96
+ };
97
+
98
+ const runNext = async () => {
99
+ if (i >= total) {
100
+ if (completed === total) {
101
+ activeSessions.delete(finalComicUrl);
102
+ chrome.runtime.sendMessage({
103
+ action: 'downloadProgress',
104
+ comicUrl: finalComicUrl,
105
+ completed: completed,
106
+ total: total,
107
+ downloading: false
108
+ }).catch(() => {});
109
+ }
110
+ return;
111
+ }
112
+
113
+ const idx = i++;
114
+ const img = toDownload[idx];
115
+ active++;
116
+
117
+ try {
118
+ const url = img.src || img;
119
+ const width = img.width || 0;
120
+ const height = img.height || 0;
121
+ const ext = isForcePNG ? 'png' : getExtension(url);
122
+
123
+ let sf = uniqueSf || baseSf || 'comics_completos';
124
+ if (separateQuality && width > 0 && height > 0) {
125
+ const quality = getQualityFolder(width, height);
126
+ sf = `${sf}/${quality}`;
127
+ }
128
+
129
+ let name = url.split('/').pop().split(/[#?]/)[0].slice(0, 50) || `img_${idx + 1}`;
130
+ if (renameSequential) {
131
+ const padLength = Math.max(2, String(total).length);
132
+ name = `pag_${String(idx + 1).padStart(padLength, '0')}`;
133
+ }
134
+
135
+ const filename = `${sf}/${name}.${ext}`;
136
+ const requiresBlobFetch = url.includes('poringa.') || url.includes('chochox.') || url.includes('gold-usergeneratedcontent.net') || url.includes('nhentaimg.com') || url.includes('sexkomix') || url.includes('3hentai.xyz') || url.includes('3hentai.net') || url.includes('vercomicsporno.com') || url.includes('lectorhentai.com') || url.includes('hentaimode.com') || url.includes('giolandscaping.com') || isForcePNG;
137
+
138
+ if (requiresBlobFetch) {
139
+ try {
140
+ const resp = await fetch(url);
141
+ if (!resp.ok) throw new Error('Fetch failed');
142
+ const blob = await resp.blob();
143
+
144
+ const buffer = await blob.arrayBuffer();
145
+ const base64 = arrayBufferToBase64(buffer);
146
+ const dataUrl = `data:${blob.type};base64,${base64}`;
147
+
148
+ await new Promise((resolve) => {
149
+ downloadMap.set(dataUrl, filename);
150
+ chrome.downloads.download({ url: dataUrl, filename: filename, saveAs: false }, () => resolve());
151
+ });
152
+ } catch (e) {
153
+ console.warn("Background fetch failed, falling back to direct download", e);
154
+ await new Promise((resolve) => {
155
+ downloadMap.set(url, filename);
156
+ chrome.downloads.download({ url: url, filename: filename, saveAs: false }, () => resolve());
157
+ });
158
+ }
159
+ } else {
160
+ await new Promise((resolve) => {
161
+ downloadMap.set(url, filename);
162
+ chrome.downloads.download({ url: url, filename: filename, saveAs: false }, () => resolve());
163
+ });
164
+ }
165
+ } catch (err) {
166
+ console.error("Background download error:", err);
167
+ }
168
+
169
+ active--;
170
+ completed++;
171
+ broadcastProgress();
172
+ runNext();
173
+ };
174
+
175
+ for (let j = 0; j < Math.min(limit, total); j++) {
176
+ runNext();
177
+ }
178
+ }
src/popup/modules/downloader.js ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { DOM } from './state.js';
2
+ import { getExtension } from './filters.js';
3
+
4
+ export function getQualityFolder(width, height) {
5
+ const max = Math.max(width, height);
6
+ const min = Math.min(width, height);
7
+ if (min >= 2160 || max >= 3840) return '4K';
8
+ if (min >= 1440 || max >= 2560) return '2K';
9
+ if (min >= 1080 || max >= 1920) return '1080p';
10
+ if (min >= 720 || max >= 1280) return '720p';
11
+ return 'Normal';
12
+ }
13
+
14
+ export function convertWebpToPng(blob) {
15
+ return new Promise((resolve, reject) => {
16
+ const img = new Image();
17
+ const url = URL.createObjectURL(blob);
18
+ img.onload = () => {
19
+ URL.revokeObjectURL(url);
20
+ const canvas = document.createElement('canvas');
21
+ canvas.width = img.naturalWidth;
22
+ canvas.height = img.naturalHeight;
23
+ const ctx = canvas.getContext('2d');
24
+ ctx.drawImage(img, 0, 0);
25
+ canvas.toBlob((pngBlob) => {
26
+ if (pngBlob) {
27
+ resolve(pngBlob);
28
+ } else {
29
+ reject(new Error('Canvas conversion to PNG failed'));
30
+ }
31
+ }, 'image/png');
32
+ };
33
+ img.onerror = (e) => {
34
+ URL.revokeObjectURL(url);
35
+ reject(e);
36
+ };
37
+ img.src = url;
38
+ });
39
+ }
40
+
41
+ export async function getUniqueSubfolder(baseFolder) {
42
+ return baseFolder || 'comics_completos';
43
+ }
44
+
45
+ export async function downloadImage(img, idx = 0, totalItems = 1, uniqueSf = null) {
46
+ const url = img.src || img; // Fallback
47
+ const width = img.width || 0;
48
+ const height = img.height || 0;
49
+
50
+ const isForcePNG = DOM.forcePNG && DOM.forcePNG.checked;
51
+ const ext = isForcePNG ? 'png' : (getExtension(url) === 'desconocido' ? 'jpg' : getExtension(url));
52
+
53
+ let sf = uniqueSf;
54
+ if (!sf) {
55
+ sf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || 'comics_completos';
56
+ }
57
+
58
+ if (DOM.separateQuality && DOM.separateQuality.checked && width > 0 && height > 0) {
59
+ const quality = getQualityFolder(width, height);
60
+ sf = `${sf}/${quality}`;
61
+ }
62
+
63
+ let name = url.split('/').pop().split(/[#?]/)[0].slice(0, 50) || `img_${idx + 1}`;
64
+
65
+ if (DOM.renameSequential && DOM.renameSequential.checked) {
66
+ const padLength = Math.max(2, String(totalItems).length);
67
+ name = `pag_${String(idx + 1).padStart(padLength, '0')}`;
68
+ }
69
+
70
+ const filename = `${sf}/${name}.${ext}`;
71
+
72
+ const requiresBlobFetch = url.includes('poringa.') || url.includes('chochox.') || url.includes('gold-usergeneratedcontent.net') || url.includes('nhentaimg.com') || url.includes('sexkomix') || url.includes('3hentai.xyz') || url.includes('3hentai.net') || url.includes('vercomicsporno.com') || url.includes('lectorhentai.com') || url.includes('hentaimode.com') || url.includes('giolandscaping.com') || isForcePNG;
73
+
74
+ if (requiresBlobFetch) {
75
+ return new Promise((resolve) => {
76
+ fetch(url)
77
+ .then(r => { if(!r.ok) throw new Error('Fetch failed'); return r.blob(); })
78
+ .then(async (blob) => {
79
+ let finalBlob = blob;
80
+ if (isForcePNG && blob.type !== 'image/png') {
81
+ try {
82
+ finalBlob = await convertWebpToPng(blob);
83
+ } catch (e) {
84
+ console.warn("PNG conversion failed, falling back to original blob", e);
85
+ }
86
+ }
87
+ const reader = new FileReader();
88
+ reader.onloadend = () => {
89
+ const dataUrl = reader.result;
90
+ chrome.runtime.sendMessage({ action: 'registerDownload', url: dataUrl, filename: filename }, () => {
91
+ chrome.downloads.download({ url: dataUrl, filename: filename, saveAs: false }, () => resolve());
92
+ });
93
+ };
94
+ reader.readAsDataURL(finalBlob);
95
+ })
96
+ .catch(e => {
97
+ console.warn("Blob fetch failed, falling back to direct download", e);
98
+ chrome.runtime.sendMessage({ action: 'registerDownload', url: url, filename: filename }, () => {
99
+ chrome.downloads.download({ url, filename: filename, saveAs: false }, () => resolve());
100
+ });
101
+ });
102
+ });
103
+ }
104
+
105
+ return new Promise((resolve) => {
106
+ chrome.runtime.sendMessage({ action: 'registerDownload', url: url, filename: filename }, () => {
107
+ chrome.downloads.download({ url, filename: filename, saveAs: false }, () => resolve());
108
+ });
109
+ });
110
+ }
src/popup/modules/filters.js ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { state, DOM } from './state.js';
2
+ import { render } from '../popup.js';
3
+
4
+ export function getExtension(url) {
5
+ let e = url.split('.').pop().split(/[#?]/)[0].toLowerCase();
6
+ return ['jpg','jpeg','png','webp','gif','svg','avif','bmp','tiff','tif','ico','heic','heif','jxl'].includes(e) ? e : 'desconocido';
7
+ }
8
+
9
+ export function applyFilters() {
10
+ const w = parseInt(DOM.minWidth.value) || 0;
11
+ const h = parseInt(DOM.minHeight.value) || 0;
12
+ const text = DOM.filterUrl.value.toLowerCase();
13
+ const ext = DOM.filterExt.value;
14
+
15
+ state.filteredImages = state.allImages.filter(img => {
16
+ if (DOM.cleanBrokenToggle && DOM.cleanBrokenToggle.checked && img.isBroken) return false;
17
+
18
+ // Exempt direct links, kemono thumbs, and actively searching HD images from size filtering initially
19
+ const isExempt = img.hdSearching || (!img.hdFound && (img.isDirectLink || img.isKemonoThumb));
20
+ if (!isExempt && (img.width < w || img.height < h)) return false;
21
+ if (ext !== 'all' && getExtension(img.src) !== ext) return false;
22
+ if (text && !img.src.toLowerCase().includes(text)) return false;
23
+ return true;
24
+ });
25
+
26
+ if (DOM.smartComic && DOM.smartComic.checked && state.filteredImages.length > 0) {
27
+ const dirInfo = {};
28
+ state.filteredImages.forEach(img => {
29
+ if (img.hdSearching || (!img.hdFound && (img.isDirectLink || img.isKemonoThumb))) return;
30
+ try {
31
+ const url = img.originalSrc || img.src;
32
+ if (!url.startsWith('http')) return;
33
+ const urlObj = new URL(url);
34
+ const pathStr = urlObj.pathname;
35
+ const dirPath = urlObj.origin + pathStr.substring(0, pathStr.lastIndexOf('/'));
36
+
37
+ if (!dirInfo[dirPath]) dirInfo[dirPath] = 0;
38
+ if (img.width >= 300 && img.height >= 300) {
39
+ dirInfo[dirPath] += 2;
40
+ } else {
41
+ dirInfo[dirPath] += 1;
42
+ }
43
+ } catch(e) {}
44
+ });
45
+
46
+ let mainDir = '';
47
+ let maxScore = 0;
48
+ for (const [dir, score] of Object.entries(dirInfo)) {
49
+ if (score > maxScore) {
50
+ maxScore = score;
51
+ mainDir = dir;
52
+ }
53
+ }
54
+
55
+ state.filteredImages = state.filteredImages.filter(img => {
56
+ if (img.hdSearching || (!img.hdFound && (img.isDirectLink || img.isKemonoThumb))) return true;
57
+
58
+ try {
59
+ const url = img.originalSrc || img.src;
60
+ const urlObj = new URL(url);
61
+ const pathStr = urlObj.pathname;
62
+ const dirPath = urlObj.origin + pathStr.substring(0, pathStr.lastIndexOf('/'));
63
+
64
+ if (maxScore >= 4) {
65
+ return dirPath === mainDir && img.width >= 300 && img.height >= 300;
66
+ } else {
67
+ return img.width >= 300 && img.height >= 300;
68
+ }
69
+ } catch {
70
+ return true;
71
+ }
72
+ });
73
+ }
74
+
75
+ // Limpiar selección de lo que ya no es visible
76
+ const visibleSrcs = new Set(state.filteredImages.map(i => i.src));
77
+ state.selectedImages.forEach(src => {
78
+ if (!visibleSrcs.has(src)) state.selectedImages.delete(src);
79
+ });
80
+
81
+ render();
82
+ }
src/popup/modules/scrapers.js ADDED
@@ -0,0 +1,881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export async function getImagesFromPageDOM() {
2
+ const isHentaiMode = window.location.hostname.includes('hentaimode.com');
3
+ if (isHentaiMode) {
4
+ try {
5
+ if (typeof window.ts_reader !== 'undefined') {
6
+ let images = null;
7
+ if (window.ts_reader.sources && window.ts_reader.sources[0] && window.ts_reader.sources[0].images) {
8
+ images = window.ts_reader.sources[0].images;
9
+ } else if (window.ts_reader.params && window.ts_reader.params.sources && window.ts_reader.params.sources[0] && window.ts_reader.params.sources[0].images) {
10
+ images = window.ts_reader.params.sources[0].images;
11
+ }
12
+
13
+ if (images && images.length > 0) {
14
+ return images.map(src => {
15
+ let finalSrc = src;
16
+ try {
17
+ finalSrc = new URL(finalSrc, window.location.href).href;
18
+ } catch (e) {}
19
+ return {
20
+ src: finalSrc,
21
+ width: 0,
22
+ height: 0,
23
+ inLink: false,
24
+ linkHref: null,
25
+ isKemonoThumb: false,
26
+ isDirectLink: true
27
+ };
28
+ });
29
+ }
30
+ }
31
+
32
+ const isMangaDetailsPage = !window.location.pathname.includes('/leer/');
33
+
34
+ if (isMangaDetailsPage) {
35
+ const title = document.querySelector('h1, .post-title h1, .manga-title h1')?.textContent?.trim() || document.title;
36
+ const coverEl = document.querySelector('.summary_image img, .manga-cover img, .summary-image img, .manga-info img, img.cover');
37
+ const cover = coverEl ? (coverEl.getAttribute('data-src') || coverEl.getAttribute('data-lazy-src') || coverEl.getAttribute('src') || '') : '';
38
+
39
+ const chapters = [];
40
+ const seenChapters = new Set();
41
+ const chapterLinks = document.querySelectorAll('a[href*="/leer/"]');
42
+ chapterLinks.forEach(a => {
43
+ let href = a.href;
44
+ if (href) {
45
+ try {
46
+ href = new URL(href, window.location.href).href;
47
+ } catch(e) {}
48
+ if (!seenChapters.has(href)) {
49
+ seenChapters.add(href);
50
+ chapters.push(href);
51
+ }
52
+ }
53
+ });
54
+
55
+ if (chapters.length > 0) {
56
+ chapters.reverse();
57
+ const results = [];
58
+ const seenImages = new Set();
59
+
60
+ for (const url of chapters) {
61
+ try {
62
+ const resp = await fetch(url);
63
+ if (resp.ok) {
64
+ const html = await resp.text();
65
+
66
+ const match = html.match(/ts_reader\s*=\s*({[\s\S]*?});/);
67
+ if (match) {
68
+ try {
69
+ const data = JSON.parse(match[1]);
70
+ let images = null;
71
+ if (data.sources && data.sources[0] && data.sources[0].images) {
72
+ images = data.sources[0].images;
73
+ } else if (data.params && data.params.sources && data.params.sources[0] && data.params.sources[0].images) {
74
+ images = data.params.sources[0].images;
75
+ }
76
+
77
+ if (images && images.length > 0) {
78
+ images.forEach(src => {
79
+ let finalSrc = src;
80
+ try {
81
+ finalSrc = new URL(finalSrc, url).href;
82
+ } catch (e) {}
83
+ if (finalSrc.startsWith('http') && !seenImages.has(finalSrc)) {
84
+ seenImages.add(finalSrc);
85
+ results.push({
86
+ src: finalSrc,
87
+ width: 0,
88
+ height: 0,
89
+ inLink: false,
90
+ linkHref: null,
91
+ isKemonoThumb: false,
92
+ isDirectLink: true
93
+ });
94
+ }
95
+ });
96
+ continue;
97
+ }
98
+ } catch(e) {}
99
+ }
100
+
101
+ const doc = new DOMParser().parseFromString(html, 'text/html');
102
+ const selectors = [
103
+ '.reading-content img',
104
+ '.wp-manga-chapter-img img',
105
+ '.wp-manga-chapter-img',
106
+ '.page-break img',
107
+ '.viewer-pages img',
108
+ '#viewer img',
109
+ '#viewer-container img',
110
+ '.chapter-images img',
111
+ '.reader-images img',
112
+ '#reader img',
113
+ '.reader img',
114
+ '#readerarea img'
115
+ ];
116
+
117
+ doc.querySelectorAll(selectors.join(', ')).forEach(img => {
118
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src');
119
+ if (src && !src.includes('readerarea.svg')) {
120
+ try {
121
+ src = new URL(src, url).href;
122
+ } catch(e) {}
123
+ if (src.startsWith('http') && !seenImages.has(src)) {
124
+ seenImages.add(src);
125
+ results.push({
126
+ src: src,
127
+ width: img.naturalWidth || img.width || 0,
128
+ height: img.naturalHeight || img.height || 0,
129
+ inLink: false,
130
+ linkHref: null,
131
+ isKemonoThumb: false,
132
+ isDirectLink: true
133
+ });
134
+ }
135
+ }
136
+ });
137
+ }
138
+ } catch(err) {}
139
+ }
140
+ if (results.length > 0) {
141
+ return results;
142
+ }
143
+ }
144
+ }
145
+
146
+ const results = [];
147
+ const seen = new Set();
148
+ const selectors = [
149
+ '.reading-content img',
150
+ '.wp-manga-chapter-img img',
151
+ '.wp-manga-chapter-img',
152
+ '.page-break img',
153
+ '.viewer-pages img',
154
+ '#viewer img',
155
+ '#viewer-container img',
156
+ '.chapter-images img',
157
+ '.reader-images img',
158
+ '#reader img',
159
+ '.reader img',
160
+ '#readerarea img'
161
+ ];
162
+
163
+ document.querySelectorAll(selectors.join(', ')).forEach(img => {
164
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src');
165
+ if (src && !src.includes('readerarea.svg')) {
166
+ try {
167
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
168
+ src = new URL(src, window.location.href).href;
169
+ }
170
+ } catch(e) {}
171
+ if (src.startsWith('http') && !seen.has(src)) {
172
+ seen.add(src);
173
+ results.push({
174
+ src: src,
175
+ width: img.naturalWidth || img.width || 0,
176
+ height: img.naturalHeight || img.height || 0,
177
+ inLink: false,
178
+ linkHref: null,
179
+ isKemonoThumb: false,
180
+ isDirectLink: true
181
+ });
182
+ }
183
+ }
184
+ });
185
+
186
+ if (results.length < 3) {
187
+ try {
188
+ const resp = await fetch(window.location.href);
189
+ if (resp.ok) {
190
+ const html = await resp.text();
191
+ const doc = new DOMParser().parseFromString(html, 'text/html');
192
+ doc.querySelectorAll(selectors.join(', ')).forEach(img => {
193
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src');
194
+ if (src && !src.includes('readerarea.svg')) {
195
+ try {
196
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
197
+ src = new URL(src, window.location.href).href;
198
+ }
199
+ } catch(e) {}
200
+ if (src.startsWith('http') && !seen.has(src)) {
201
+ seen.add(src);
202
+ results.push({
203
+ src: src,
204
+ width: img.naturalWidth || img.width || 0,
205
+ height: img.naturalHeight || img.height || 0,
206
+ inLink: false,
207
+ linkHref: null,
208
+ isKemonoThumb: false,
209
+ isDirectLink: true
210
+ });
211
+ }
212
+ }
213
+ });
214
+ }
215
+ } catch(err) {}
216
+ }
217
+
218
+ if (results.length === 0) {
219
+ document.querySelectorAll('img').forEach(img => {
220
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('data-opt-src') || img.src;
221
+ if (src && !src.includes('readerarea.svg')) {
222
+ try {
223
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
224
+ src = new URL(src, window.location.href).href;
225
+ }
226
+ } catch(e) {}
227
+ if (src.startsWith('http') && !src.includes('logo') && !src.includes('banner') && !seen.has(src)) {
228
+ seen.add(src);
229
+ results.push({
230
+ src: src,
231
+ width: img.naturalWidth || img.width || 0,
232
+ height: img.naturalHeight || img.height || 0,
233
+ inLink: false,
234
+ linkHref: null,
235
+ isKemonoThumb: false,
236
+ isDirectLink: true
237
+ });
238
+ }
239
+ }
240
+ });
241
+ }
242
+
243
+ if (results.length > 0) {
244
+ return results;
245
+ }
246
+ } catch (e) {
247
+ console.error("HentaiMode parser error:", e);
248
+ }
249
+ }
250
+
251
+ const isLectorHentai = window.location.hostname.includes('lectorhentai.com');
252
+ if (isLectorHentai) {
253
+ try {
254
+ if (typeof window.ts_reader !== 'undefined') {
255
+ let images = null;
256
+ if (window.ts_reader.sources && window.ts_reader.sources[0] && window.ts_reader.sources[0].images) {
257
+ images = window.ts_reader.sources[0].images;
258
+ } else if (window.ts_reader.params && window.ts_reader.params.sources && window.ts_reader.params.sources[0] && window.ts_reader.params.sources[0].images) {
259
+ images = window.ts_reader.params.sources[0].images;
260
+ }
261
+
262
+ if (images && images.length > 0) {
263
+ return images.map(src => {
264
+ let finalSrc = src;
265
+ try {
266
+ finalSrc = new URL(finalSrc, window.location.href).href;
267
+ } catch (e) {}
268
+ return {
269
+ src: finalSrc,
270
+ width: 0,
271
+ height: 0,
272
+ inLink: false,
273
+ linkHref: null,
274
+ isKemonoThumb: false,
275
+ isDirectLink: true
276
+ };
277
+ });
278
+ }
279
+ }
280
+
281
+ const isMangaDetailsPage = window.location.pathname.includes('/manga/') &&
282
+ !window.location.pathname.includes('/capitulo') &&
283
+ !window.location.pathname.includes('/chapter') &&
284
+ !window.location.pathname.includes('/read/') &&
285
+ !window.location.pathname.includes('/lector/');
286
+ const hasReaderElement = document.querySelector('.reading-content, .wp-manga-chapter-img, .page-break, #viewer, .chapter-images, #readerarea');
287
+
288
+ if (isMangaDetailsPage && !hasReaderElement) {
289
+ const title = document.querySelector('h1, .post-title h1, .manga-title h1')?.textContent?.trim() || document.title;
290
+ const coverEl = document.querySelector('.summary_image img, .manga-cover img, .summary-image img, .manga-info img');
291
+ const cover = coverEl ? (coverEl.getAttribute('data-src') || coverEl.getAttribute('data-lazy-src') || coverEl.getAttribute('src') || '') : '';
292
+
293
+ const chapters = [];
294
+ const seenChapters = new Set();
295
+ const chapterLinks = document.querySelectorAll('.wp-manga-chapter a, .listing-chapters_wrap a, a[href*="/capitulo-"], a[href*="/chapter-"], a[href*="/read/"], a[href*="/lector/"]');
296
+ chapterLinks.forEach(a => {
297
+ let href = a.href;
298
+ if (href) {
299
+ try {
300
+ href = new URL(href, window.location.href).href;
301
+ } catch(e) {}
302
+ if (!seenChapters.has(href)) {
303
+ seenChapters.add(href);
304
+ chapters.push(href);
305
+ }
306
+ }
307
+ });
308
+
309
+ if (chapters.length === 0) {
310
+ document.querySelectorAll('a').forEach(a => {
311
+ let href = a.href;
312
+ if (href && (href.includes('/capitulo-') || href.includes('/chapter-') || href.includes('/read/') || href.includes('/lector/') || a.textContent.toLowerCase().includes('capítulo') || a.textContent.toLowerCase().includes('cap.') || a.textContent.toLowerCase().includes('chapter') || a.textContent.toLowerCase().includes('ch.'))) {
313
+ try {
314
+ href = new URL(href, window.location.href).href;
315
+ } catch(e) {}
316
+ if (!seenChapters.has(href)) {
317
+ seenChapters.add(href);
318
+ chapters.push(href);
319
+ }
320
+ }
321
+ });
322
+ }
323
+
324
+ if (chapters.length > 0) {
325
+ chapters.reverse();
326
+
327
+ const results = [];
328
+ const seenImages = new Set();
329
+ const selectors = [
330
+ '.reading-content img',
331
+ '.wp-manga-chapter-img img',
332
+ '.wp-manga-chapter-img',
333
+ '.page-break img',
334
+ '.viewer-pages img',
335
+ '#viewer img',
336
+ '.chapter-images img',
337
+ '#readerarea img'
338
+ ];
339
+
340
+ for (const url of chapters) {
341
+ try {
342
+ const resp = await fetch(url);
343
+ if (resp.ok) {
344
+ const html = await resp.text();
345
+
346
+ const match = html.match(/ts_reader\s*=\s*({[\s\S]*?});/);
347
+ if (match) {
348
+ try {
349
+ const data = JSON.parse(match[1]);
350
+ let images = null;
351
+ if (data.sources && data.sources[0] && data.sources[0].images) {
352
+ images = data.sources[0].images;
353
+ } else if (data.params && data.params.sources && data.params.sources[0] && data.params.sources[0].images) {
354
+ images = data.params.sources[0].images;
355
+ }
356
+
357
+ if (images && images.length > 0) {
358
+ images.forEach(src => {
359
+ let finalSrc = src;
360
+ try {
361
+ finalSrc = new URL(finalSrc, url).href;
362
+ } catch (e) {}
363
+ if (finalSrc.startsWith('http') && !seenImages.has(finalSrc)) {
364
+ seenImages.add(finalSrc);
365
+ results.push({
366
+ src: finalSrc,
367
+ width: 0,
368
+ height: 0,
369
+ inLink: false,
370
+ linkHref: null,
371
+ isKemonoThumb: false,
372
+ isDirectLink: true
373
+ });
374
+ }
375
+ });
376
+ continue;
377
+ }
378
+ } catch(e) {}
379
+ }
380
+
381
+ const doc = new DOMParser().parseFromString(html, 'text/html');
382
+
383
+ doc.querySelectorAll(selectors.join(', ')).forEach(img => {
384
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src');
385
+ if (src && !src.includes('readerarea.svg')) {
386
+ try {
387
+ src = new URL(src, url).href;
388
+ } catch(e) {}
389
+ if (src.startsWith('http') && !seenImages.has(src)) {
390
+ seenImages.add(src);
391
+ results.push({
392
+ src: src,
393
+ width: img.naturalWidth || img.width || 0,
394
+ height: img.naturalHeight || img.height || 0,
395
+ inLink: false,
396
+ linkHref: null,
397
+ isKemonoThumb: false,
398
+ isDirectLink: true
399
+ });
400
+ }
401
+ }
402
+ });
403
+
404
+ if (results.length === 0) {
405
+ doc.querySelectorAll('img').forEach(img => {
406
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('data-opt-src') || img.src;
407
+ if (src && !src.includes('readerarea.svg')) {
408
+ try {
409
+ src = new URL(src, url).href;
410
+ } catch(e) {}
411
+ if (src.startsWith('http') && !src.includes('logo') && !src.includes('banner') && !seenImages.has(src)) {
412
+ seenImages.add(src);
413
+ results.push({
414
+ src: src,
415
+ width: img.naturalWidth || img.width || 0,
416
+ height: img.naturalHeight || img.height || 0,
417
+ inLink: false,
418
+ linkHref: null,
419
+ isKemonoThumb: false,
420
+ isDirectLink: true
421
+ });
422
+ }
423
+ }
424
+ });
425
+ }
426
+ }
427
+ } catch(err) {}
428
+ }
429
+
430
+ if (results.length > 0) {
431
+ return results;
432
+ }
433
+ }
434
+ }
435
+
436
+ const results = [];
437
+ const seen = new Set();
438
+ const selectors = [
439
+ '.reading-content img',
440
+ '.wp-manga-chapter-img img',
441
+ '.wp-manga-chapter-img',
442
+ '.page-break img',
443
+ '.viewer-pages img',
444
+ '#viewer img',
445
+ '.chapter-images img',
446
+ '#readerarea img'
447
+ ];
448
+
449
+ document.querySelectorAll(selectors.join(', ')).forEach(img => {
450
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src');
451
+ if (src) {
452
+ try {
453
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
454
+ src = new URL(src, window.location.href).href;
455
+ }
456
+ } catch(e) {}
457
+ if (src.startsWith('http') && !seen.has(src)) {
458
+ seen.add(src);
459
+ results.push({
460
+ src: src,
461
+ width: img.naturalWidth || img.width || 0,
462
+ height: img.naturalHeight || img.height || 0,
463
+ inLink: false,
464
+ linkHref: null,
465
+ isKemonoThumb: false,
466
+ isDirectLink: true
467
+ });
468
+ }
469
+ }
470
+ });
471
+
472
+ if (results.length < 3) {
473
+ try {
474
+ const resp = await fetch(window.location.href);
475
+ if (resp.ok) {
476
+ const html = await resp.text();
477
+ const doc = new DOMParser().parseFromString(html, 'text/html');
478
+ doc.querySelectorAll(selectors.join(', ')).forEach(img => {
479
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src');
480
+ if (src) {
481
+ try {
482
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
483
+ src = new URL(src, window.location.href).href;
484
+ }
485
+ } catch(e) {}
486
+ if (src.startsWith('http') && !seen.has(src)) {
487
+ seen.add(src);
488
+ results.push({
489
+ src: src,
490
+ width: img.naturalWidth || img.width || 0,
491
+ height: img.naturalHeight || img.height || 0,
492
+ inLink: false,
493
+ linkHref: null,
494
+ isKemonoThumb: false,
495
+ isDirectLink: true
496
+ });
497
+ }
498
+ }
499
+ });
500
+ }
501
+ } catch(err) {}
502
+ }
503
+
504
+ if (results.length === 0) {
505
+ document.querySelectorAll('img').forEach(img => {
506
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('data-opt-src') || img.src;
507
+ if (src) {
508
+ try {
509
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
510
+ src = new URL(src, window.location.href).href;
511
+ }
512
+ } catch(e) {}
513
+ if (src.startsWith('http') && !src.includes('logo') && !src.includes('banner') && !seen.has(src)) {
514
+ seen.add(src);
515
+ results.push({
516
+ src: src,
517
+ width: img.naturalWidth || img.width || 0,
518
+ height: img.naturalHeight || img.height || 0,
519
+ inLink: false,
520
+ linkHref: null,
521
+ isKemonoThumb: false,
522
+ isDirectLink: true
523
+ });
524
+ }
525
+ }
526
+ });
527
+ }
528
+
529
+ if (results.length > 0) {
530
+ return results;
531
+ }
532
+ } catch (e) {
533
+ console.error("LectorHentai parser error:", e);
534
+ }
535
+ }
536
+
537
+ const isVerComicsPorno = window.location.hostname.includes('vercomicsporno.com');
538
+ if (isVerComicsPorno) {
539
+ try {
540
+ const results = [];
541
+ const seen = new Set();
542
+ document.querySelectorAll('.wp-content img, .posts img').forEach(img => {
543
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('src');
544
+ if (src) {
545
+ try {
546
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
547
+ src = new URL(src, window.location.href).href;
548
+ }
549
+ } catch(e) {}
550
+ if (
551
+ src.startsWith('http') &&
552
+ src.includes('/wp-content/uploads/') &&
553
+ !src.includes('avatar.jpg') &&
554
+ !src.includes('/avatar') &&
555
+ !src.match(/-\d+x\d+\.(jpg|jpeg|png|webp|gif)$/i) &&
556
+ !seen.has(src)
557
+ ) {
558
+ seen.add(src);
559
+ results.push({
560
+ src: src,
561
+ width: img.naturalWidth || img.width || 0,
562
+ height: img.naturalHeight || img.height || 0,
563
+ inLink: false,
564
+ linkHref: null,
565
+ isKemonoThumb: false,
566
+ isDirectLink: true
567
+ });
568
+ }
569
+ }
570
+ });
571
+ if (results.length > 0) {
572
+ return results;
573
+ }
574
+ } catch (e) {
575
+ console.error("vercomicsporno parser error:", e);
576
+ }
577
+ }
578
+
579
+ const isSexkomix = window.location.hostname.includes('sexkomix');
580
+ if (isSexkomix) {
581
+ try {
582
+ const results = [];
583
+ const seen = new Set();
584
+ document.querySelectorAll('ul#comix_pages_ul > li img').forEach(img => {
585
+ let src = img.getAttribute('data-src') || img.getAttribute('src');
586
+ if (src) {
587
+ try {
588
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
589
+ src = new URL(src, window.location.href).href;
590
+ }
591
+ } catch(e) {}
592
+ if (src.startsWith('http') && !seen.has(src)) {
593
+ seen.add(src);
594
+ results.push({
595
+ src: src,
596
+ width: img.naturalWidth || img.width || 0,
597
+ height: img.naturalHeight || img.height || 0,
598
+ inLink: false,
599
+ linkHref: null,
600
+ isKemonoThumb: false,
601
+ isDirectLink: true
602
+ });
603
+ }
604
+ }
605
+ });
606
+ if (results.length > 0) {
607
+ return results;
608
+ }
609
+ } catch (e) {
610
+ console.error("sexkomix parser error:", e);
611
+ }
612
+ }
613
+
614
+ const isNHentai = window.location.hostname.includes('nhentai.xxx') || window.location.hostname.includes('nhentai.net') || window.location.hostname.includes('nhentai.to');
615
+ if (isNHentai) {
616
+ try {
617
+ const g_th = window.g_th;
618
+ if (g_th) {
619
+ const g_th_fl = g_th.fl || g_th;
620
+ let baseUrl = '';
621
+ const mediaServer = window.media_server;
622
+ const imageDir = document.getElementById('image_dir')?.value;
623
+ const galleryId = document.getElementById('gallery_id')?.value;
624
+ if (mediaServer && imageDir && galleryId) {
625
+ baseUrl = `https://${mediaServer}/${imageDir}/${galleryId}`;
626
+ }
627
+ if (!baseUrl) {
628
+ const mainImg = document.querySelector('.fw_img img');
629
+ const mainSrc = mainImg ? (mainImg.getAttribute('data-src') || mainImg.getAttribute('src')) : null;
630
+ if (mainSrc && mainSrc.startsWith('http')) {
631
+ const lastSlash = mainSrc.lastIndexOf('/');
632
+ baseUrl = mainSrc.substring(0, lastSlash);
633
+ }
634
+ }
635
+ if (!baseUrl) {
636
+ const thumbImg = document.querySelector('.gallery_thumbs img, .gt_th img, #thumbs_append img');
637
+ const thumbSrc = thumbImg ? (thumbImg.getAttribute('data-src') || thumbImg.getAttribute('src')) : null;
638
+ if (thumbSrc && thumbSrc.startsWith('http')) {
639
+ const lastSlash = thumbSrc.lastIndexOf('/');
640
+ baseUrl = thumbSrc.substring(0, lastSlash);
641
+ }
642
+ }
643
+ if (baseUrl) {
644
+ const totalPages = Object.keys(g_th_fl).length;
645
+ const results = [];
646
+ for (let i = 1; i <= totalPages; i++) {
647
+ const pageData = g_th_fl[String(i)];
648
+ if (pageData) {
649
+ const parts = pageData.split(',');
650
+ const code = parts[0];
651
+ const w = parseInt(parts[1]) || 0;
652
+ const h = parseInt(parts[2]) || 0;
653
+ let ext = 'jpg';
654
+ if (code === 'w') ext = 'webp';
655
+ else if (code === 'p') ext = 'png';
656
+ else if (code === 'j') ext = 'jpg';
657
+
658
+ const src = `${baseUrl}/${i}.${ext}`;
659
+ results.push({
660
+ src: src,
661
+ width: w,
662
+ height: h,
663
+ inLink: false,
664
+ linkHref: null,
665
+ isKemonoThumb: false
666
+ });
667
+ }
668
+ }
669
+ if (results.length > 0) {
670
+ return results;
671
+ }
672
+ }
673
+ }
674
+ } catch (e) {
675
+ console.error("nhentai parser error:", e);
676
+ }
677
+ }
678
+
679
+ const is3Hentai = window.location.hostname.includes('3hentai.net');
680
+ if (is3Hentai) {
681
+ try {
682
+ const results = [];
683
+ const seen = new Set();
684
+
685
+ const readerPages = window.readerPages;
686
+ if (readerPages && readerPages.pages && readerPages.baseUriImg) {
687
+ const baseUriImg = readerPages.baseUriImg;
688
+ const totalPages = readerPages.lastPage || Object.keys(readerPages.pages).length;
689
+
690
+ for (let i = 1; i <= totalPages; i++) {
691
+ const pageData = readerPages.pages[String(i)];
692
+ if (pageData && pageData.f) {
693
+ const src = baseUriImg.replace('%s', pageData.f);
694
+ if (!seen.has(src)) {
695
+ seen.add(src);
696
+ results.push({
697
+ src: src,
698
+ width: pageData.w || 0,
699
+ height: pageData.h || 0,
700
+ inLink: false,
701
+ linkHref: null,
702
+ isKemonoThumb: false
703
+ });
704
+ }
705
+ }
706
+ }
707
+ }
708
+
709
+ if (results.length === 0) {
710
+ const thumbs = document.querySelectorAll('#thumbnail-gallery img, .single-thumb img, .single-thumb-col img');
711
+ thumbs.forEach(img => {
712
+ let src = img.getAttribute('data-src') || img.getAttribute('src');
713
+ if (src) {
714
+ try {
715
+ if (!src.startsWith('data:') && !src.startsWith('blob:')) {
716
+ src = new URL(src, window.location.href).href;
717
+ }
718
+ } catch(e) {}
719
+
720
+ const match = src.match(/^(.*\/)(\d+)t\.(jpg|png|webp|jpeg|gif)$/i);
721
+ if (match) {
722
+ const base = match[1];
723
+ const pageNum = match[2];
724
+ const ext = match[3];
725
+ const fullSrc = `${base}${pageNum}.${ext}`;
726
+
727
+ if (!seen.has(fullSrc)) {
728
+ seen.add(fullSrc);
729
+ results.push({
730
+ src: fullSrc,
731
+ width: img.naturalWidth || img.width || 0,
732
+ height: img.naturalHeight || img.height || 0,
733
+ inLink: false,
734
+ linkHref: null,
735
+ isKemonoThumb: false
736
+ });
737
+ }
738
+ }
739
+ }
740
+ });
741
+ }
742
+
743
+ if (results.length > 0) {
744
+ return results;
745
+ }
746
+ } catch (e) {
747
+ console.error("3hentai parser error:", e);
748
+ }
749
+ }
750
+
751
+ const isHentaiera = window.location.hostname.includes('hentaiera.com') && window.location.pathname.includes('/view/');
752
+ if (isHentaiera) {
753
+ try {
754
+ const pagesInput = document.getElementById('pages');
755
+ const gimg = document.getElementById('gimg');
756
+ const g_th = window.g_th;
757
+ if (pagesInput && gimg && g_th) {
758
+ const totalPages = parseInt(pagesInput.value) || 0;
759
+ const firstImgSrc = gimg.src || gimg.getAttribute('data-src');
760
+ if (firstImgSrc && totalPages > 0) {
761
+ const lastSlashIdx = firstImgSrc.lastIndexOf('/');
762
+ const baseUrl = firstImgSrc.substring(0, lastSlashIdx);
763
+ const results = [];
764
+ for (let i = 1; i <= totalPages; i++) {
765
+ const pageData = g_th[String(i)];
766
+ if (pageData) {
767
+ const parts = pageData.split(',');
768
+ const code = parts[0];
769
+ const w = parseInt(parts[1]) || 0;
770
+ const h = parseInt(parts[2]) || 0;
771
+ let ext = 'jpg';
772
+ if (code === 'w') ext = 'webp';
773
+ else if (code === 'p') ext = 'png';
774
+ else if (code === 'j') ext = 'jpg';
775
+
776
+ const src = `${baseUrl}/${i}.${ext}`;
777
+ results.push({
778
+ src: src,
779
+ width: w,
780
+ height: h,
781
+ inLink: false,
782
+ linkHref: null,
783
+ isKemonoThumb: false
784
+ });
785
+ }
786
+ }
787
+ if (results.length > 0) {
788
+ return results;
789
+ }
790
+ }
791
+ }
792
+ } catch (e) {
793
+ console.error("Hentaiera parser error:", e);
794
+ }
795
+ }
796
+
797
+ const isHitomi = window.location.hostname.includes('hitomi.la');
798
+ if (isHitomi) {
799
+ try {
800
+ const match = window.location.href.match(/([0-9]+)\.html/);
801
+ if (match) {
802
+ const galleryId = match[1];
803
+
804
+ const loadScript = (src) => {
805
+ return new Promise((resolve, reject) => {
806
+ const script = document.createElement('script');
807
+ script.src = src;
808
+ script.onload = resolve;
809
+ script.onerror = () => reject(new Error(`Failed to load ${src}`));
810
+ (document.head || document.documentElement).appendChild(script);
811
+ });
812
+ };
813
+
814
+ if (typeof window.galleryinfo === 'undefined' || !window.galleryinfo || !window.galleryinfo.files) {
815
+ await loadScript(`https://ltn.hitomi.la/galleries/${galleryId}.js`);
816
+ }
817
+ if (typeof window.url_from_url_from_hash === 'undefined') {
818
+ await loadScript('https://ltn.hitomi.la/common.js');
819
+ }
820
+ if (typeof window.gg === 'undefined' || !window.gg || !window.gg.m || !window.gg.s || !window.gg.b) {
821
+ await loadScript('https://ltn.hitomi.la/gg.js');
822
+ }
823
+
824
+ if (window.galleryinfo && window.galleryinfo.files) {
825
+ const results = [];
826
+ window.galleryinfo.files.forEach((file) => {
827
+ let src = '';
828
+ try {
829
+ src = window.url_from_url_from_hash(galleryId, file, 'webp', undefined, undefined);
830
+ } catch (e) {
831
+ console.error("url_from_url_from_hash failed", e);
832
+ }
833
+ if (src) {
834
+ results.push({
835
+ src: src,
836
+ width: file.width || 0,
837
+ height: file.height || 0,
838
+ inLink: false,
839
+ linkHref: null,
840
+ isKemonoThumb: false
841
+ });
842
+ }
843
+ });
844
+ if (results.length > 0) {
845
+ return results;
846
+ }
847
+ }
848
+ }
849
+ } catch (e) {
850
+ console.error("Hitomi parser error:", e);
851
+ }
852
+ }
853
+
854
+ const results = [];
855
+ document.querySelectorAll('img').forEach(img => {
856
+ let p = img.parentElement, inLink = false, linkHref = null;
857
+ while(p && p.tagName !== 'BODY') {
858
+ if (p.tagName === 'A') { inLink = true; linkHref = p.href; break; }
859
+ p = p.parentElement;
860
+ }
861
+ let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-opt-src') || img.src;
862
+
863
+ try {
864
+ if (src && !src.startsWith('data:') && !src.startsWith('blob:')) {
865
+ src = new URL(src, window.location.href).href;
866
+ }
867
+ } catch(e) {}
868
+
869
+ if (src?.startsWith('http')) {
870
+ const isKemonoThumb = src.includes('kemono.') && src.includes('/thumbnail/data/');
871
+ results.push({ src, width: img.naturalWidth || 0, height: img.naturalHeight || 0, inLink, linkHref, isKemonoThumb });
872
+ }
873
+ });
874
+
875
+ document.querySelectorAll('.post__files a, .post__file a, .fileThumb, a[href*="kemono."]').forEach(a => {
876
+ if (a.href.match(/\.(jpg|jpeg|png|webp|gif|svg|avif|bmp|tiff|tif|ico|heic|heif|jxl)$/i)) {
877
+ results.push({ src: a.href, width: 0, height: 0, inLink: true, linkHref: a.href, isDirectLink: true });
878
+ }
879
+ });
880
+ return results;
881
+ }
src/popup/modules/settings.js ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { DOM } from './state.js';
2
+
3
+ export function saveSettings() {
4
+ if (typeof chrome === 'undefined' || !chrome.storage) return;
5
+ const settings = {
6
+ filterUrl: DOM.filterUrl.value,
7
+ filterExt: DOM.filterExt.value,
8
+ minWidth: DOM.minWidth.value,
9
+ minHeight: DOM.minHeight.value,
10
+ forceHD: DOM.forceHD.checked,
11
+ separateQuality: DOM.separateQuality.checked,
12
+ renameSequential: DOM.renameSequential.checked,
13
+ smartComic: DOM.smartComic.checked,
14
+ forcePNG: DOM.forcePNG.checked,
15
+ subfolder: DOM.subfolderInput.value,
16
+ selectAll: DOM.selectAll.checked,
17
+ cleanBroken: DOM.cleanBrokenToggle ? DOM.cleanBrokenToggle.checked : false,
18
+ filtersCollapsed: DOM.collapsibleFilters ? DOM.collapsibleFilters.classList.contains('collapsed') : false
19
+ };
20
+ chrome.storage.local.set({ extensionSettings: settings });
21
+ }
22
+
23
+ export async function loadSettings() {
24
+ return new Promise((resolve) => {
25
+ if (typeof chrome === 'undefined' || !chrome.storage) return resolve();
26
+ chrome.storage.local.get(['extensionSettings'], (res) => {
27
+ const s = res.extensionSettings;
28
+ if (s) {
29
+ DOM.filterUrl.value = s.filterUrl || '';
30
+ DOM.filterExt.value = s.filterExt || 'all';
31
+ DOM.minWidth.value = s.minWidth ?? 0;
32
+ DOM.minWidthVal.value = s.minWidth ?? 0;
33
+ DOM.minHeight.value = s.minHeight ?? 0;
34
+ DOM.minHeightVal.value = s.minHeight ?? 0;
35
+ DOM.forceHD.checked = !!s.forceHD;
36
+ DOM.separateQuality.checked = !!s.separateQuality;
37
+ DOM.renameSequential.checked = s.renameSequential !== false; // Activo por defecto
38
+ DOM.smartComic.checked = s.smartComic !== false;
39
+ DOM.forcePNG.checked = !!s.forcePNG;
40
+ DOM.subfolderInput.value = s.subfolder || '';
41
+ DOM.selectAll.checked = !!s.selectAll;
42
+ if (DOM.cleanBrokenToggle) {
43
+ DOM.cleanBrokenToggle.checked = !!s.cleanBroken;
44
+ }
45
+ if (DOM.collapsibleFilters && s.filtersCollapsed) {
46
+ DOM.collapsibleFilters.classList.add('collapsed');
47
+ if (DOM.toggleFiltersBtn) {
48
+ DOM.toggleFiltersBtn.classList.add('collapsed');
49
+ }
50
+ }
51
+ }
52
+ resolve();
53
+ });
54
+ });
55
+ }
src/popup/modules/state.js ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // --- ESTADO GLOBAL ---
2
+ export const state = {
3
+ allImages: [],
4
+ filteredImages: [],
5
+ selectedImages: new Set(),
6
+ lastSelectedIdx: -1,
7
+ isHDSearching: false,
8
+ downloadMap: new Map(),
9
+ isDragging: false,
10
+ dragMode: true,
11
+ dragStartIdx: -1,
12
+ dragSavedSelection: new Set()
13
+ };
14
+
15
+ // --- ELEMENTOS DEL DOM ---
16
+ export const DOM = {
17
+ grid: document.getElementById('imageGrid'),
18
+ filterUrl: document.getElementById('filterUrl'),
19
+ filterExt: document.getElementById('filterExt'),
20
+ minWidth: document.getElementById('minWidth'),
21
+ minWidthVal: document.getElementById('minWidthVal'),
22
+ minHeight: document.getElementById('minHeight'),
23
+ minHeightVal: document.getElementById('minHeightVal'),
24
+ forceHD: document.getElementById('forceHD'),
25
+ separateQuality: document.getElementById('separateQuality'),
26
+ renameSequential: document.getElementById('renameSequential'),
27
+ smartComic: document.getElementById('smartComic'),
28
+ forcePNG: document.getElementById('forcePNG'),
29
+ selectAll: document.getElementById('selectAll'),
30
+ selectedCount: document.getElementById('selectedCount'),
31
+ totalCount: document.getElementById('totalCount'),
32
+ downloadBtn: document.getElementById('downloadBtn'),
33
+ btnCounter: document.getElementById('btnCounter'),
34
+ fullscreenBtn: document.getElementById('fullscreenBtn'),
35
+ subfolderInput: document.getElementById('subfolder'),
36
+ cleanBrokenToggle: document.getElementById('cleanBrokenToggle'),
37
+ // Búsqueda Secuencial
38
+ toggleSeqBtn: document.getElementById('toggleSeqBtn'),
39
+ seqPanel: document.getElementById('seqPanel'),
40
+ seqUrlPattern: document.getElementById('seqUrlPattern'),
41
+ seqStart: document.getElementById('seqStart'),
42
+ seqEnd: document.getElementById('seqEnd'),
43
+ seqSelector: document.getElementById('seqSelector'),
44
+ seqStartBtn: document.getElementById('seqStartBtn'),
45
+ seqProgress: document.getElementById('seqProgress'),
46
+ seqProgressText: document.getElementById('seqProgressText'),
47
+ seqProgressStatus: document.getElementById('seqProgressStatus'),
48
+ seqProgressBar: document.getElementById('seqProgressBar'),
49
+ collapsibleFilters: document.getElementById('collapsibleFilters'),
50
+ toggleFiltersBtn: document.getElementById('toggleFiltersBtn'),
51
+ // Panel Pegar Enlaces
52
+ togglePasteBtn: document.getElementById('togglePasteBtn'),
53
+ pastePanel: document.getElementById('pastePanel'),
54
+ pasteLinksTextarea: document.getElementById('pasteLinksTextarea'),
55
+ clearPastedBtn: document.getElementById('clearPastedBtn'),
56
+ processPastedBtn: document.getElementById('processPastedBtn'),
57
+ downloadPastedBtn: document.getElementById('downloadPastedBtn'),
58
+ pasteStatus: document.getElementById('pasteStatus')
59
+ };
src/popup/popup.css ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg-color: #0b0c10;
3
+ --surface-color: #12141a;
4
+ --border-color: #272a33;
5
+ --text-color: #c9d1d9;
6
+ --text-muted: #8b949e;
7
+ --accent-color: #e11d48; /* Rojo Carmesí */
8
+ --accent-hover: #be123c; /* Rojo Oscuro */
9
+ --danger-color: #f85149;
10
+ }
11
+
12
+ body {
13
+ min-width: 800px;
14
+ min-height: 560px;
15
+ width: 100vw;
16
+ height: 100vh;
17
+ margin: 0;
18
+ /* removed fixed sizes */
19
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
20
+ background-color: var(--bg-color);
21
+ color: var(--text-color);
22
+ display: flex;
23
+ flex-direction: column;
24
+ overflow: hidden;
25
+ }
26
+
27
+ ::-webkit-scrollbar { width: 8px; height: 8px; }
28
+ ::-webkit-scrollbar-track { background: var(--bg-color); }
29
+ ::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 4px; }
30
+ ::-webkit-scrollbar-thumb:hover { background: #555; }
31
+
32
+ .header-panel {
33
+ padding: 10px 14px;
34
+ background: linear-gradient(180deg, var(--surface-color) 0%, var(--bg-color) 100%);
35
+ border-bottom: 1px solid var(--border-color);
36
+ display: flex;
37
+ flex-direction: column;
38
+ gap: 10px;
39
+ flex-shrink: 0;
40
+ }
41
+
42
+ .header-row {
43
+ display: grid;
44
+ grid-template-columns: 1fr 1fr;
45
+ gap: 14px;
46
+ }
47
+
48
+ .group-title {
49
+ font-size: 10px;
50
+ text-transform: uppercase;
51
+ letter-spacing: 0.5px;
52
+ color: var(--text-muted);
53
+ font-weight: 600;
54
+ margin-bottom: 4px;
55
+ display: flex;
56
+ align-items: center;
57
+ gap: 4px;
58
+ }
59
+
60
+ .info-icon {
61
+ background: rgba(255,255,255,0.1);
62
+ color: #fff;
63
+ border-radius: 50%;
64
+ width: 12px;
65
+ height: 12px;
66
+ display: inline-flex;
67
+ align-items: center;
68
+ justify-content: center;
69
+ font-size: 9px;
70
+ font-family: monospace;
71
+ font-weight: bold;
72
+ cursor: help;
73
+ }
74
+
75
+ input[type="text"], input[type="number"], select {
76
+ background-color: rgba(255, 255, 255, 0.02);
77
+ color: var(--text-color);
78
+ border: 1px solid var(--border-color);
79
+ border-radius: 6px;
80
+ padding: 6px 8px;
81
+ font-size: 12px;
82
+ outline: none;
83
+ transition: all 0.2s;
84
+ }
85
+
86
+ input[type="text"]:focus, input[type="number"]:focus, select:focus {
87
+ border-color: var(--accent-color);
88
+ background-color: rgba(225, 29, 72, 0.05); /* Rojo transparente */
89
+ }
90
+
91
+ /* Solucionar el menú desplegable blanco en Windows */
92
+ select option {
93
+ background-color: var(--surface-color);
94
+ color: var(--text-color);
95
+ }
96
+
97
+ .flex-row { display: flex; gap: 6px; width: 100%; align-items: center; }
98
+ .flex-row input[type="text"] { flex-grow: 1; }
99
+ .flex-row select { width: 110px; }
100
+
101
+ .sliders-container {
102
+ display: flex;
103
+ gap: 8px;
104
+ }
105
+
106
+ .slider-box {
107
+ flex: 1;
108
+ display: flex;
109
+ align-items: center;
110
+ gap: 6px;
111
+ background: rgba(255,255,255,0.02);
112
+ padding: 4px 8px;
113
+ border-radius: 6px;
114
+ border: 1px solid var(--border-color);
115
+ }
116
+
117
+ .slider-box span { font-size: 11px; color: var(--text-muted); font-weight: 500; }
118
+ .slider-box input[type="range"] { flex-grow: 1; height: 3px; accent-color: var(--accent-color); }
119
+ .slider-box input[type="number"] { width: 40px; padding: 2px; text-align: center; border: none; background: rgba(0,0,0,0.2); }
120
+
121
+ .options-grid {
122
+ display: grid;
123
+ grid-template-columns: 1fr 1fr;
124
+ gap: 8px;
125
+ }
126
+
127
+ .custom-checkbox {
128
+ display: flex;
129
+ align-items: flex-start;
130
+ gap: 8px;
131
+ padding: 6px 8px;
132
+ background: rgba(255,255,255,0.02);
133
+ border: 1px solid var(--border-color);
134
+ border-radius: 6px;
135
+ cursor: pointer;
136
+ transition: all 0.2s;
137
+ }
138
+
139
+ .custom-checkbox:hover {
140
+ background: rgba(255,255,255,0.05);
141
+ border-color: #444c56;
142
+ }
143
+
144
+ .custom-checkbox input[type="checkbox"] {
145
+ margin-top: 2px;
146
+ accent-color: var(--accent-color);
147
+ width: 13px;
148
+ height: 13px;
149
+ cursor: pointer;
150
+ }
151
+
152
+ .checkbox-text {
153
+ display: flex;
154
+ flex-direction: column;
155
+ gap: 1px;
156
+ }
157
+
158
+ .checkbox-text b { font-size: 11.5px; font-weight: 500; color: #fff; }
159
+ .checkbox-text small { font-size: 9.5px; color: var(--text-muted); line-height: 1.2; }
160
+
161
+ .select-bar {
162
+ margin-top: 0px;
163
+ padding-top: 8px;
164
+ border-top: 1px dashed var(--border-color);
165
+ display: flex;
166
+ align-items: center;
167
+ justify-content: space-between;
168
+ }
169
+
170
+ .select-all-label {
171
+ display: flex;
172
+ align-items: center;
173
+ gap: 8px;
174
+ font-size: 13px;
175
+ font-weight: 500;
176
+ cursor: pointer;
177
+ }
178
+
179
+ .select-all-label input {
180
+ accent-color: var(--accent-color);
181
+ width: 16px;
182
+ height: 16px;
183
+ cursor: pointer;
184
+ }
185
+
186
+ /* GRID DE IMÁGENES */
187
+ .grid-container {
188
+ flex-grow: 1;
189
+ overflow-y: auto;
190
+ padding: 14px;
191
+ display: grid;
192
+ grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
193
+ grid-auto-rows: max-content;
194
+ align-content: start;
195
+ gap: 16px;
196
+ background-color: var(--bg-color);
197
+ }
198
+
199
+ .image-card {
200
+ position: relative;
201
+ background-color: var(--surface-color);
202
+ border: 1px solid var(--border-color);
203
+ border-radius: 8px;
204
+ overflow: hidden;
205
+ display: flex;
206
+ flex-direction: column;
207
+ transition: all 0.2s;
208
+ }
209
+
210
+ .image-card.selected {
211
+ border-color: var(--accent-color);
212
+ box-shadow: 0 0 0 2px rgba(225, 29, 72, 0.3); /* Resplandor rojo */
213
+ }
214
+
215
+ .image-wrapper {
216
+ position: relative;
217
+ width: 100%;
218
+ aspect-ratio: 1 / 1.4;
219
+ background-color: rgba(0,0,0,0.5);
220
+ display: flex;
221
+ align-items: center;
222
+ justify-content: center;
223
+ }
224
+
225
+ .image-wrapper img {
226
+ max-width: 100%;
227
+ max-height: 100%;
228
+ object-fit: contain;
229
+ }
230
+
231
+ .card-checkbox {
232
+ position: absolute;
233
+ top: 8px;
234
+ left: 8px;
235
+ width: 20px;
236
+ height: 20px;
237
+ accent-color: var(--accent-color);
238
+ cursor: pointer;
239
+ z-index: 10;
240
+ background: rgba(0,0,0,0.6);
241
+ border-radius: 4px;
242
+ box-shadow: 0 2px 4px rgba(0,0,0,0.3);
243
+ }
244
+
245
+ .card-actions {
246
+ position: absolute;
247
+ top: 8px;
248
+ right: 8px;
249
+ display: flex;
250
+ gap: 6px;
251
+ background: rgba(0, 0, 0, 0.7);
252
+ padding: 4px;
253
+ border-radius: 6px;
254
+ z-index: 10;
255
+ backdrop-filter: blur(4px);
256
+ }
257
+
258
+ .icon-btn {
259
+ background: none;
260
+ border: none;
261
+ color: #fff;
262
+ cursor: pointer;
263
+ padding: 5px;
264
+ border-radius: 4px;
265
+ display: flex;
266
+ align-items: center;
267
+ justify-content: center;
268
+ transition: background 0.2s;
269
+ }
270
+
271
+ .icon-btn:hover { background-color: rgba(255,255,255,0.2); }
272
+ .icon-btn svg {
273
+ width: 16px;
274
+ height: 16px;
275
+ fill: none;
276
+ stroke: currentColor;
277
+ stroke-width: 2;
278
+ stroke-linecap: round;
279
+ stroke-linejoin: round;
280
+ }
281
+
282
+ .card-info {
283
+ padding: 8px;
284
+ font-size: 11px;
285
+ color: var(--text-color);
286
+ display: flex;
287
+ flex-direction: column;
288
+ gap: 6px;
289
+ background: var(--surface-color);
290
+ }
291
+
292
+ .url-bar {
293
+ background: rgba(0,0,0,0.7);
294
+ padding: 5px;
295
+ position: absolute;
296
+ bottom: 0;
297
+ left: 0;
298
+ right: 0;
299
+ font-size: 10px;
300
+ color: #ddd;
301
+ white-space: nowrap;
302
+ overflow: hidden;
303
+ text-overflow: ellipsis;
304
+ backdrop-filter: blur(2px);
305
+ }
306
+
307
+ .footer {
308
+ padding: 14px 16px;
309
+ background-color: var(--surface-color);
310
+ border-top: 1px solid var(--border-color);
311
+ display: flex;
312
+ justify-content: space-between;
313
+ align-items: center;
314
+ gap: 12px;
315
+ flex-shrink: 0;
316
+ }
317
+
318
+ .footer-inputs {
319
+ display: flex;
320
+ gap: 5px;
321
+ flex-grow: 1;
322
+ }
323
+
324
+ .btn-download {
325
+ background-color: var(--accent-color);
326
+ color: #fff; /* Que se lea bien sobre el rojo */
327
+ border: none;
328
+ border-radius: 6px;
329
+ padding: 10px 16px;
330
+ font-size: 14px;
331
+ font-weight: 600;
332
+ cursor: pointer;
333
+ display: flex;
334
+ align-items: center;
335
+ gap: 8px;
336
+ white-space: nowrap;
337
+ transition: all 0.2s;
338
+ box-shadow: 0 4px 14px 0 rgba(225, 29, 72, 0.2); /* Sombra roja */
339
+ }
340
+
341
+ .btn-download:hover {
342
+ background-color: var(--accent-hover);
343
+ transform: translateY(-1px);
344
+ }
345
+ .btn-download:disabled {
346
+ background-color: #30363d;
347
+ color: #8b949e;
348
+ cursor: not-allowed;
349
+ box-shadow: none;
350
+ transform: none;
351
+ }
352
+
353
+ .btn-clean {
354
+ background-color: rgba(255, 255, 255, 0.05);
355
+ border: 1px solid var(--border-color);
356
+ color: var(--text-muted);
357
+ border-radius: 4px;
358
+ padding: 4px 8px;
359
+ font-size: 11px;
360
+ cursor: pointer;
361
+ display: flex;
362
+ align-items: center;
363
+ gap: 4px;
364
+ transition: all 0.2s;
365
+ }
366
+ .btn-clean:hover {
367
+ background-color: rgba(225, 29, 72, 0.1);
368
+ border-color: var(--accent-color);
369
+ color: #fff;
370
+ }
371
+
372
+ .loader {
373
+ display: flex;
374
+ flex-direction: column;
375
+ align-items: center;
376
+ justify-content: center;
377
+ height: 100%;
378
+ color: var(--text-muted);
379
+ grid-column: span 4;
380
+ }
381
+
382
+ /* PANEL BÚSQUEDA SECUENCIAL */
383
+ .sequential-search-panel {
384
+ margin-top: 5px;
385
+ padding: 0 4px;
386
+ animation: slideDown 0.2s ease-out;
387
+ }
388
+
389
+ .seq-grid {
390
+ display: flex;
391
+ flex-direction: column;
392
+ gap: 8px;
393
+ background: rgba(255, 255, 255, 0.02);
394
+ border: 1px solid var(--border-color);
395
+ padding: 10px;
396
+ border-radius: 8px;
397
+ }
398
+
399
+ .seq-row-url {
400
+ display: flex;
401
+ width: 100%;
402
+ }
403
+
404
+ .seq-row-inputs {
405
+ display: flex;
406
+ gap: 8px;
407
+ align-items: center;
408
+ flex-wrap: wrap;
409
+ }
410
+
411
+ .seq-input-box {
412
+ display: flex;
413
+ align-items: center;
414
+ gap: 6px;
415
+ font-size: 11px;
416
+ color: var(--text-muted);
417
+ }
418
+
419
+ .seq-input-box span {
420
+ white-space: nowrap;
421
+ }
422
+
423
+ .progress-bar-bg {
424
+ background: rgba(255, 255, 255, 0.08);
425
+ height: 6px;
426
+ border-radius: 3px;
427
+ overflow: hidden;
428
+ margin-top: 4px;
429
+ border: 1px solid rgba(255,255,255,0.02);
430
+ }
431
+
432
+ .progress-bar-fill {
433
+ background: linear-gradient(90deg, var(--accent-color) 0%, #ff527b 100%);
434
+ height: 100%;
435
+ width: 0%;
436
+ transition: width 0.25s ease-out;
437
+ box-shadow: 0 0 8px var(--accent-color);
438
+ }
439
+
440
+ @keyframes slideDown {
441
+ from { opacity: 0; transform: translateY(-8px); }
442
+ to { opacity: 1; transform: translateY(0); }
443
+ }
444
+
445
+ /* FILTROS COLAPSABLES */
446
+ .collapsible-filters {
447
+ max-height: 500px;
448
+ opacity: 1;
449
+ overflow: hidden;
450
+ transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1),
451
+ opacity 0.2s ease-in-out,
452
+ padding-bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1);
453
+ }
454
+
455
+ .collapsible-filters.collapsed {
456
+ max-height: 0;
457
+ opacity: 0;
458
+ pointer-events: none;
459
+ }
460
+
461
+ #toggleFiltersBtn svg {
462
+ transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
463
+ }
464
+
465
+ #toggleFiltersBtn.collapsed svg {
466
+ transform: rotate(180deg);
467
+ }
468
+
469
+ /* MANGA DETAILS VIEW DESIGN */
470
+ .manga-details-container {
471
+ display: flex;
472
+ flex-direction: column;
473
+ gap: 16px;
474
+ padding: 20px;
475
+ background: rgba(18, 20, 26, 0.6);
476
+ backdrop-filter: blur(10px);
477
+ border-radius: 12px;
478
+ border: 1px solid var(--border-color);
479
+ max-width: 740px;
480
+ margin: 10px auto;
481
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
482
+ animation: slideDown 0.3s ease-out;
483
+ }
484
+
485
+ .manga-details-header {
486
+ display: flex;
487
+ gap: 20px;
488
+ align-items: flex-start;
489
+ border-bottom: 1px solid var(--border-color);
490
+ padding-bottom: 16px;
491
+ }
492
+
493
+ .manga-details-cover {
494
+ width: 90px;
495
+ height: 120px;
496
+ object-fit: cover;
497
+ border-radius: 8px;
498
+ border: 1px solid var(--border-color);
499
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
500
+ background-color: var(--bg-color);
501
+ }
502
+
503
+ .manga-details-info {
504
+ display: flex;
505
+ flex-direction: column;
506
+ gap: 6px;
507
+ justify-content: center;
508
+ }
509
+
510
+ .manga-details-title {
511
+ font-size: 18px;
512
+ font-weight: 700;
513
+ color: #ffffff;
514
+ margin: 0;
515
+ line-height: 1.3;
516
+ }
517
+
518
+ .manga-details-meta {
519
+ font-size: 13px;
520
+ color: var(--text-muted);
521
+ margin: 0;
522
+ }
523
+
524
+ .manga-details-meta b {
525
+ color: var(--text-color);
526
+ }
527
+
528
+ .badge-madara {
529
+ align-self: flex-start;
530
+ background: rgba(225, 29, 72, 0.15);
531
+ color: var(--accent-color);
532
+ font-size: 10px;
533
+ font-weight: 700;
534
+ text-transform: uppercase;
535
+ padding: 3px 8px;
536
+ border-radius: 4px;
537
+ border: 1px solid rgba(225, 29, 72, 0.3);
538
+ margin-top: 4px;
539
+ }
540
+
541
+ .manga-chapters-title {
542
+ font-size: 13px;
543
+ font-weight: 600;
544
+ color: var(--text-muted);
545
+ text-transform: uppercase;
546
+ letter-spacing: 0.5px;
547
+ margin-bottom: 4px;
548
+ }
549
+
550
+ .manga-chapters-list {
551
+ display: flex;
552
+ flex-direction: column;
553
+ gap: 8px;
554
+ max-height: 280px;
555
+ overflow-y: auto;
556
+ padding-right: 4px;
557
+ }
558
+
559
+ .manga-chapter-item {
560
+ display: flex;
561
+ justify-content: space-between;
562
+ align-items: center;
563
+ padding: 10px 14px;
564
+ background: rgba(255, 255, 255, 0.02);
565
+ border: 1px solid var(--border-color);
566
+ border-radius: 8px;
567
+ transition: all 0.2s ease;
568
+ }
569
+
570
+ .manga-chapter-item:hover {
571
+ background: rgba(255, 255, 255, 0.04);
572
+ border-color: rgba(255, 255, 255, 0.1);
573
+ }
574
+
575
+ .chapter-name {
576
+ font-size: 13px;
577
+ font-weight: 500;
578
+ color: var(--text-color);
579
+ white-space: nowrap;
580
+ overflow: hidden;
581
+ text-overflow: ellipsis;
582
+ max-width: 320px;
583
+ }
584
+
585
+ .chapter-actions {
586
+ display: flex;
587
+ gap: 8px;
588
+ align-items: center;
589
+ }
590
+
591
+ .btn-chapter-download {
592
+ background: var(--accent-color);
593
+ color: white;
594
+ border: none;
595
+ border-radius: 6px;
596
+ padding: 6px 12px;
597
+ font-size: 11px;
598
+ font-weight: 600;
599
+ cursor: pointer;
600
+ transition: all 0.2s ease;
601
+ }
602
+
603
+ .btn-chapter-download:hover {
604
+ background: var(--accent-hover);
605
+ box-shadow: 0 0 10px rgba(225, 29, 72, 0.4);
606
+ }
607
+
608
+ .btn-chapter-download:disabled {
609
+ background: var(--border-color);
610
+ color: var(--text-muted);
611
+ cursor: not-allowed;
612
+ box-shadow: none;
613
+ }
614
+
615
+ .chapter-download-progress {
616
+ display: flex;
617
+ align-items: center;
618
+ gap: 10px;
619
+ min-width: 160px;
620
+ }
621
+
622
+ .chapter-download-progress .progress-bar-bg {
623
+ flex-grow: 1;
624
+ height: 4px;
625
+ margin-top: 0;
626
+ }
627
+
628
+ .chapter-download-progress .progress-text {
629
+ font-size: 10px;
630
+ color: var(--text-muted);
631
+ white-space: nowrap;
632
+ min-width: 65px;
633
+ text-align: right;
634
+ }
src/popup/popup.html ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="es">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <link rel="stylesheet" href="popup.css">
6
+ </head>
7
+ <body>
8
+
9
+ <div class="header-panel">
10
+
11
+ <div class="collapsible-filters" id="collapsibleFilters">
12
+ <div class="header-row">
13
+ <!-- Filtros Principales -->
14
+ <div>
15
+ <div class="group-title">
16
+ Filtros de Contenido
17
+ <span class="info-icon" title="Usa un texto para buscar en las URLs o filtra por formato (jpg, png, etc.)">?</span>
18
+ </div>
19
+ <div class="flex-row">
20
+ <input type="text" id="filterUrl" placeholder="Buscar palabras clave en la URL..." title="Escribe palabras clave para filtrar imágenes" />
21
+ <select id="filterExt" title="Filtrar por extensión">
22
+ <option value="all">Formato: Todos</option>
23
+ <option value="jpg">Solo JPG</option>
24
+ <option value="jpeg">Solo JPEG</option>
25
+ <option value="png">Solo PNG</option>
26
+ <option value="webp">Solo WEBP</option>
27
+ <option value="gif">Solo GIF</option>
28
+ <option value="svg">Solo SVG</option>
29
+ <option value="avif">Solo AVIF</option>
30
+ <option value="bmp">Solo BMP</option>
31
+ <option value="tiff">Solo TIFF</option>
32
+ <option value="tif">Solo TIF</option>
33
+ <option value="ico">Solo ICO</option>
34
+ <option value="heic">Solo HEIC</option>
35
+ <option value="heif">Solo HEIF</option>
36
+ <option value="jxl">Solo JXL</option>
37
+ </select>
38
+ </div>
39
+ </div>
40
+
41
+ <!-- Tamaño Mínimo -->
42
+ <div>
43
+ <div class="group-title">
44
+ Tamaño Mínimo Requerido
45
+ <span class="info-icon" title="Oculta logos pequeños, iconos y botones ajustando el tamaño mínimo.">?</span>
46
+ </div>
47
+ <div class="sliders-container">
48
+ <div class="slider-box" title="Filtra imágenes más pequeñas que este ancho">
49
+ <span>Ancho</span>
50
+ <input type="range" id="minWidth" min="0" max="2500" value="0" step="10">
51
+ <input type="number" id="minWidthVal" value="0">
52
+ </div>
53
+ <div class="slider-box" title="Filtra imágenes más pequeñas que este alto">
54
+ <span>Alto</span>
55
+ <input type="range" id="minHeight" min="0" max="2500" value="0" step="10">
56
+ <input type="number" id="minHeightVal" value="0">
57
+ </div>
58
+ </div>
59
+ </div>
60
+ </div>
61
+
62
+ <!-- Opciones Avanzadas -->
63
+ <div>
64
+ <div class="options-grid">
65
+ <label class="custom-checkbox" title="Especial para galerías de Cómics: Abre las miniaturas en la sombra para atraparlas en Calidad Original.">
66
+ <input type="checkbox" id="forceHD">
67
+ <div class="checkbox-text">
68
+ <b>Forzar HD (Lhentai/Galerías)</b>
69
+ <small>Extracción profunda original</small>
70
+ </div>
71
+ </label>
72
+
73
+ <label class="custom-checkbox" title="Crea subcarpetas automáticas (4K, 1080p, etc.) según la resolución de cada imagen.">
74
+ <input type="checkbox" id="separateQuality">
75
+ <div class="checkbox-text">
76
+ <b>Separar por Calidad</b>
77
+ <small>Carpetas (4K, 1080p...)</small>
78
+ </div>
79
+ </label>
80
+
81
+ <label class="custom-checkbox" title="Renombra los archivos como pag_01, pag_02 de acuerdo a su orden en la página, ignorando el nombre original.">
82
+ <input type="checkbox" id="renameSequential" checked>
83
+ <div class="checkbox-text">
84
+ <b>Renombrar a "pag_X"</b>
85
+ <small>Ordena pag_01, pag_02...</small>
86
+ </div>
87
+ </label>
88
+
89
+ <label class="custom-checkbox" title="Modo Inteligente: Detecta y selecciona automáticamente solo las páginas del cómic, ignorando banners, menús y publicidad.">
90
+ <input type="checkbox" id="smartComic" checked>
91
+ <div class="checkbox-text">
92
+ <b>Modo Solo Cómic 🎯</b>
93
+ <small>Filtra logos y banners</small>
94
+ </div>
95
+ </label>
96
+
97
+ <label class="custom-checkbox" title="Convierte y descarga las imágenes en formato PNG (equivalente al guardado manual de Hitomi).">
98
+ <input type="checkbox" id="forcePNG">
99
+ <div class="checkbox-text">
100
+ <b>Forzar PNG (Formato Original)</b>
101
+ <small>Convierte WebP a PNG al descargar</small>
102
+ </div>
103
+ </label>
104
+ </div>
105
+ </div>
106
+
107
+ <!-- Panel Búsqueda Secuencial (Collapsible) -->
108
+ <div class="sequential-search-panel" id="seqPanel" style="display: none;">
109
+ <div class="group-title" style="margin-top: 5px;">
110
+ Búsqueda Secuencial por Paginación
111
+ <span class="info-icon" title="Carga secuencialmente múltiples páginas de un cómic cambiando el número de página en la URL. Usa {page} para definir dónde cambia el número.">?</span>
112
+ </div>
113
+ <div class="seq-grid">
114
+ <div class="seq-row-url">
115
+ <input type="text" id="seqUrlPattern" placeholder="URL con {page}, ej: https://hentaiera.com/view/1473007/{page}/" title="Usa {page} donde va el número de página" style="width: 100%;" />
116
+ </div>
117
+ <div class="seq-row-inputs">
118
+ <div class="seq-input-box">
119
+ <span>Desde:</span>
120
+ <input type="number" id="seqStart" value="1" min="1" style="width: 55px;" />
121
+ </div>
122
+ <div class="seq-input-box">
123
+ <span>Hasta:</span>
124
+ <input type="number" id="seqEnd" value="10" min="1" style="width: 55px;" />
125
+ </div>
126
+ <div class="seq-input-box" style="flex-grow: 1;">
127
+ <span>Selector CSS:</span>
128
+ <input type="text" id="seqSelector" value="#gimg, #image-container img, .fit-horizontal img, .gallery-image img, figure img, .post__content img" placeholder="Selector CSS del img" title="Opcional. Selectores de la imagen principal separados por comas." style="width: 100%;" />
129
+ </div>
130
+ <button id="seqStartBtn" class="btn-clean" style="height: 28px; padding: 0 12px; font-weight: bold; background: var(--accent-color); color: white; border: none; cursor: pointer;">Buscar</button>
131
+ </div>
132
+ <div id="seqProgress" style="display: none; font-size: 11px; color: var(--text-muted); margin-top: 4px;">
133
+ <div style="display: flex; justify-content: space-between; margin-bottom: 2px;">
134
+ <span>Progreso: <span id="seqProgressText">0/0</span></span>
135
+ <span id="seqProgressStatus" style="font-weight: 500;">Iniciando...</span>
136
+ </div>
137
+ <div class="progress-bar-bg"><div id="seqProgressBar" class="progress-bar-fill"></div></div>
138
+ </div>
139
+ </div>
140
+ </div>
141
+
142
+ <!-- Panel Pegar Enlaces (Collapsible) -->
143
+ <div class="sequential-search-panel" id="pastePanel" style="display: none; margin-top: 8px;">
144
+ <div class="group-title" style="margin-top: 5px;">
145
+ Pegar Enlaces Directos de Imágenes
146
+ <span class="info-icon" title="Pega enlaces directos de imágenes (uno por línea o separados por espacios) para agregarlos a la galería y descargarlos en la carpeta elegida.">?</span>
147
+ </div>
148
+ <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 6px;">
149
+ <textarea id="pasteLinksTextarea" rows="4" placeholder="Pega aquí todos los enlaces de imágenes (uno por línea o separados por espacio)..." style="width: 100%; box-sizing: border-box; background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); color: #fff; border-radius: 6px; padding: 8px; font-family: monospace; font-size: 11px; resize: vertical;"></textarea>
150
+ <div style="display: flex; gap: 8px; justify-content: space-between; align-items: center; flex-wrap: wrap;">
151
+ <span id="pasteStatus" style="font-size: 11px; color: var(--accent-color); font-weight: 500;"></span>
152
+ <div style="display: flex; gap: 8px;">
153
+ <button id="clearPastedBtn" class="btn-clean" style="height: 28px; padding: 0 12px; font-size: 11px; cursor: pointer;">Limpiar</button>
154
+ <button id="processPastedBtn" class="btn-clean" style="height: 28px; padding: 0 14px; font-weight: bold; background: var(--accent-color); color: white; border: none; cursor: pointer; border-radius: 4px;">
155
+ 📥 Cargar Enlaces
156
+ </button>
157
+ <button id="downloadPastedBtn" class="btn-clean" style="height: 28px; padding: 0 14px; font-weight: bold; background: #10b981; color: white; border: none; cursor: pointer; border-radius: 4px;">
158
+ ⬇️ Descargar Ahora
159
+ </button>
160
+ </div>
161
+ </div>
162
+ </div>
163
+ </div>
164
+ </div>
165
+
166
+ <!-- Barra Inferior Cabecera -->
167
+ <div class="select-bar">
168
+ <label class="select-all-label">
169
+ <input type="checkbox" id="selectAll">
170
+ Seleccionar Todo (<span id="selectedCount">0</span> de <span id="totalCount">0</span>)
171
+ </label>
172
+ <div style="display: flex; gap: 8px; align-items: center;">
173
+ <button id="toggleFiltersBtn" class="btn-clean" title="Contraer/Expandir filtros" style="cursor: pointer; display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0;">
174
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="width: 16px; height: 16px; transition: transform 0.2s;"><polyline points="18 15 12 9 6 15"></polyline></svg>
175
+ </button>
176
+ <button id="toggleSeqBtn" class="btn-clean" title="Abrir panel de búsqueda secuencial para cómics paginados" style="cursor: pointer; display: flex; align-items: center; gap: 4px;">
177
+ 🔄 Paginación
178
+ </button>
179
+ <button id="togglePasteBtn" class="btn-clean" title="Pegar lista de enlaces de imágenes para descargar" style="cursor: pointer; display: flex; align-items: center; gap: 4px;">
180
+ 📋 Pegar Enlaces
181
+ </button>
182
+ <label class="btn-clean" style="cursor: pointer;" title="Ocultar automáticamente imágenes que no cargan">
183
+ <input type="checkbox" id="cleanBrokenToggle" style="accent-color: var(--accent-color); margin: 0;">
184
+ Ocultar Rotas
185
+ </label>
186
+ <span style="font-size: 11px; color: var(--text-muted);">
187
+ Imágenes listas para guardar
188
+ </span>
189
+ </div>
190
+ </div>
191
+
192
+ </div>
193
+
194
+ <div class="grid-container" id="imageGrid">
195
+ <div class="loader">
196
+ <h3 style="margin: 0;">Analizando página...</h3>
197
+ <p style="font-size: 13px;">Buscando imágenes disponibles</p>
198
+ </div>
199
+ </div>
200
+
201
+ <div class="footer">
202
+ <div class="footer-inputs">
203
+ <!-- Botón Pantalla Completa -->
204
+ <button id="fullscreenBtn" class="icon-btn" title="Pantalla Completa" style="background: rgba(255,255,255,0.1); margin-right: 5px; padding: 0 10px; border-radius: 6px;">
205
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="fill: none; width: 18px; height: 18px; display: block;"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path></svg>
206
+ </button>
207
+
208
+ <!-- Input 100% de la subcarpeta -->
209
+ <input type="text" id="subfolder" placeholder="Ej: Dragon_Ball_Z_Caps" title="Se creará esta carpeta dentro de 'Descargas'. Déjalo vacío para 'comics_completos'" style="width: 100%;">
210
+ </div>
211
+ <button id="downloadBtn" class="btn-download" disabled>
212
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
213
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
214
+ <polyline points="7 10 12 15 17 10"></polyline>
215
+ <line x1="12" y1="15" x2="12" y2="3"></line>
216
+ </svg>
217
+ Descargar (<span id="btnCounter">0</span>)
218
+ </button>
219
+ </div>
220
+
221
+ <script type="module" src="popup.js"></script>
222
+ </body>
223
+ </html>
src/popup/popup.js ADDED
@@ -0,0 +1,916 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { state, DOM } from './modules/state.js';
2
+ import { loadSettings, saveSettings } from './modules/settings.js';
3
+ import { applyFilters, getExtension } from './modules/filters.js';
4
+ import { getImagesFromPageDOM } from './modules/scrapers.js';
5
+ import { downloadImage, getUniqueSubfolder } from './modules/downloader.js';
6
+
7
+ // --- INICIALIZACIÓN ---
8
+ document.addEventListener('DOMContentLoaded', async () => {
9
+ await loadSettings();
10
+ initListeners();
11
+
12
+ const params = new URLSearchParams(window.location.search);
13
+ const targetTabId = params.get('tabId');
14
+ let tab;
15
+
16
+ if (targetTabId) {
17
+ try {
18
+ tab = await chrome.tabs.get(parseInt(targetTabId));
19
+ DOM.fullscreenBtn.title = 'Minimizar a Ventana Flotante';
20
+ DOM.fullscreenBtn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="fill: none; width: 18px; height: 18px; display: block;"><path d="M8 3v3h-3m18 2h-3V5m-18 11h3v3m10 2v-3h3m-5-5l7-7M3 21l7-7"></path></svg>';
21
+ DOM.fullscreenBtn.onclick = () => window.close();
22
+ } catch(e) {
23
+ console.error("No se pudo obtener el tab original", e);
24
+ }
25
+ } else {
26
+ const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
27
+ tab = tabs[0];
28
+ }
29
+
30
+ if (!tab) return;
31
+ window.currentContextTabId = tab.id;
32
+ window.currentContextTabUrl = tab.url;
33
+ window.currentContextTabTitle = tab.title;
34
+
35
+ if (tab.url) {
36
+ let suggestedPattern = tab.url;
37
+ let suggestedStart = 1;
38
+ let suggestedEnd = 10;
39
+
40
+ if (tab.url.includes('hentaiera.com/view/')) {
41
+ suggestedPattern = tab.url.replace(/\/view\/(\d+)\/(\d+)\/?/, '/view/$1/{page}/');
42
+ suggestedStart = 1;
43
+ try {
44
+ chrome.scripting.executeScript({
45
+ target: { tabId: tab.id },
46
+ world: 'MAIN',
47
+ function: () => document.getElementById('pages')?.value || '15'
48
+ }, (res) => {
49
+ if (res?.[0]?.result) {
50
+ const pagesVal = parseInt(res[0].result);
51
+ if (pagesVal && DOM.seqEnd) DOM.seqEnd.value = pagesVal;
52
+ }
53
+ });
54
+ } catch (e) {}
55
+ } else {
56
+ const numRegex = /(\/|-|_|=)(\d+)(\/|\.html|\.htm|$|\?|&)/i;
57
+ const match = tab.url.match(numRegex);
58
+ if (match) {
59
+ suggestedPattern = tab.url.replace(numRegex, `$1{page}$3`);
60
+ suggestedStart = 1;
61
+ suggestedEnd = Math.max(10, parseInt(match[2]));
62
+ }
63
+ }
64
+
65
+ if (DOM.seqUrlPattern) {
66
+ DOM.seqUrlPattern.value = suggestedPattern;
67
+ DOM.seqStart.value = suggestedStart;
68
+ DOM.seqEnd.value = suggestedEnd;
69
+ }
70
+ }
71
+
72
+ const isHitomi = tab.url && tab.url.includes('hitomi.la');
73
+ const isHentaiera = tab.url && tab.url.includes('hentaiera.com') && tab.url.includes('/view/');
74
+ const isNHentai = tab.url && (tab.url.includes('nhentai.xxx') || tab.url.includes('nhentai.net') || tab.url.includes('nhentai.to'));
75
+ const is3Hentai = tab.url && tab.url.includes('3hentai.net');
76
+ const isVerComicsPorno = tab.url && tab.url.includes('vercomicsporno.com');
77
+ const isLectorHentai = tab.url && tab.url.includes('lectorhentai.com');
78
+ const isHentaiMode = tab.url && tab.url.includes('hentaimode.com');
79
+ if (isHitomi || isHentaiera || isNHentai || is3Hentai || isVerComicsPorno || isLectorHentai || isHentaiMode) {
80
+ DOM.forceHD.checked = false;
81
+ DOM.forceHD.disabled = true;
82
+ }
83
+
84
+ try {
85
+ if (chrome.declarativeNetRequest && tab.url) {
86
+ await chrome.declarativeNetRequest.updateDynamicRules({
87
+ removeRuleIds: [999, 998, 997, 996, 995],
88
+ addRules: [
89
+ {
90
+ id: 999,
91
+ priority: 2,
92
+ action: {
93
+ type: "modifyHeaders",
94
+ requestHeaders: [
95
+ { header: "Referer", operation: "set", value: tab.url },
96
+ { header: "Origin", operation: "set", value: new URL(tab.url).origin }
97
+ ],
98
+ responseHeaders: [
99
+ { header: "Access-Control-Allow-Origin", operation: "set", value: "*" },
100
+ { header: "Cross-Origin-Resource-Policy", operation: "remove" }
101
+ ]
102
+ },
103
+ condition: {
104
+ urlFilter: new URL(tab.url).hostname.replace('www.', ''),
105
+ resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"]
106
+ }
107
+ },
108
+ {
109
+ id: 998,
110
+ priority: 2,
111
+ action: {
112
+ type: "modifyHeaders",
113
+ requestHeaders: [
114
+ { header: "Referer", operation: "set", value: "https://hitomi.la/" },
115
+ { header: "Origin", operation: "set", value: "https://hitomi.la" }
116
+ ],
117
+ responseHeaders: [
118
+ { header: "Access-Control-Allow-Origin", operation: "set", value: "*" },
119
+ { header: "Cross-Origin-Resource-Policy", operation: "remove" }
120
+ ]
121
+ },
122
+ condition: {
123
+ urlFilter: "gold-usergeneratedcontent.net",
124
+ resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"]
125
+ }
126
+ },
127
+ {
128
+ id: 997,
129
+ priority: 2,
130
+ action: {
131
+ type: "modifyHeaders",
132
+ requestHeaders: [
133
+ { header: "Referer", operation: "set", value: tab.url },
134
+ { header: "Origin", operation: "set", value: new URL(tab.url).origin }
135
+ ],
136
+ responseHeaders: [
137
+ { header: "Access-Control-Allow-Origin", operation: "set", value: "*" },
138
+ { header: "Cross-Origin-Resource-Policy", operation: "remove" }
139
+ ]
140
+ },
141
+ condition: {
142
+ urlFilter: "nhentaimg.com",
143
+ resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"]
144
+ }
145
+ },
146
+ {
147
+ id: 996,
148
+ priority: 2,
149
+ action: {
150
+ type: "modifyHeaders",
151
+ requestHeaders: [
152
+ { header: "Referer", operation: "set", value: tab.url.includes('3hentai.net') ? tab.url : "https://3hentai.net/" },
153
+ { header: "Origin", operation: "set", value: tab.url.includes('3hentai.net') ? new URL(tab.url).origin : "https://3hentai.net" }
154
+ ],
155
+ responseHeaders: [
156
+ { header: "Access-Control-Allow-Origin", operation: "set", value: "*" },
157
+ { header: "Cross-Origin-Resource-Policy", operation: "remove" }
158
+ ]
159
+ },
160
+ condition: {
161
+ urlFilter: "3hentai.xyz",
162
+ resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"]
163
+ }
164
+ },
165
+ {
166
+ id: 995,
167
+ priority: 2,
168
+ action: {
169
+ type: "modifyHeaders",
170
+ requestHeaders: [
171
+ { header: "Referer", operation: "set", value: "https://lectorhentai.com/" },
172
+ { header: "Origin", operation: "set", value: "https://lectorhentai.com" }
173
+ ],
174
+ responseHeaders: [
175
+ { header: "Access-Control-Allow-Origin", operation: "set", value: "*" },
176
+ { header: "Cross-Origin-Resource-Policy", operation: "remove" }
177
+ ]
178
+ },
179
+ condition: {
180
+ urlFilter: "giolandscaping.com",
181
+ resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"]
182
+ }
183
+ }
184
+ ]
185
+ });
186
+ }
187
+ } catch (e) {
188
+ console.error("Dynamic DNR failed", e);
189
+ }
190
+
191
+ chrome.scripting.executeScript({
192
+ target: { tabId: tab.id },
193
+ world: (isHitomi || isHentaiera || isNHentai || is3Hentai || isLectorHentai || isHentaiMode) ? 'MAIN' : 'ISOLATED',
194
+ function: getImagesFromPageDOM,
195
+ }, (results) => {
196
+ if (chrome.runtime.lastError || !results?.[0]?.result) {
197
+ DOM.grid.innerHTML = '<div class="loader"><p style="color: var(--danger-color)">Error al obtener imágenes.</p></div>';
198
+ return;
199
+ }
200
+
201
+ const res = results[0].result;
202
+
203
+ const uniqueMap = new Map();
204
+ res.forEach(img => {
205
+ if (!uniqueMap.has(img.src) && img.src.startsWith('http')) {
206
+ uniqueMap.set(img.src, img);
207
+ }
208
+ });
209
+
210
+ state.allImages = Array.from(uniqueMap.values());
211
+ if (DOM.selectAll.checked) {
212
+ state.allImages.forEach(img => state.selectedImages.add(img.src));
213
+ }
214
+ applyFilters();
215
+
216
+ if (DOM.forceHD.checked) {
217
+ updateHDUrls();
218
+ }
219
+ });
220
+
221
+ // Check if background is currently downloading
222
+ if (window.currentContextTabUrl) {
223
+ chrome.runtime.sendMessage({ action: 'getDownloadProgress', comicUrl: window.currentContextTabUrl }, (resp) => {
224
+ if (resp && resp.downloading) {
225
+ showDownloadingState(resp.completed, resp.total);
226
+ }
227
+ });
228
+ }
229
+ });
230
+
231
+ function initListeners() {
232
+ const handleSizeInput = (slider, valBox) => {
233
+ valBox.value = slider.value;
234
+ applyFilters();
235
+ if (DOM.forceHD.checked) updateHDUrls();
236
+ saveSettings();
237
+ };
238
+
239
+ DOM.minWidth.addEventListener('input', () => handleSizeInput(DOM.minWidth, DOM.minWidthVal));
240
+ DOM.minHeight.addEventListener('input', () => handleSizeInput(DOM.minHeight, DOM.minHeightVal));
241
+ DOM.minWidthVal.addEventListener('input', () => { DOM.minWidth.value = DOM.minWidthVal.value; applyFilters(); saveSettings(); });
242
+ DOM.minHeightVal.addEventListener('input', () => { DOM.minHeight.value = DOM.minHeightVal.value; applyFilters(); saveSettings(); });
243
+
244
+ DOM.minWidth.addEventListener('change', saveSettings);
245
+ DOM.minHeight.addEventListener('change', saveSettings);
246
+
247
+ DOM.filterUrl.addEventListener('input', () => { applyFilters(); saveSettings(); });
248
+ DOM.filterExt.addEventListener('change', () => { applyFilters(); saveSettings(); });
249
+ DOM.forceHD.addEventListener('change', () => { updateHDUrls(); saveSettings(); });
250
+ DOM.separateQuality.addEventListener('change', saveSettings);
251
+ DOM.renameSequential.addEventListener('change', saveSettings);
252
+ DOM.smartComic.addEventListener('change', () => { applyFilters(); saveSettings(); });
253
+ DOM.forcePNG.addEventListener('change', saveSettings);
254
+ DOM.subfolderInput.addEventListener('input', saveSettings);
255
+
256
+ DOM.selectAll.addEventListener('change', (e) => {
257
+ if (e.target.checked) {
258
+ state.filteredImages.forEach(img => state.selectedImages.add(img.src));
259
+ } else {
260
+ state.selectedImages.clear();
261
+ }
262
+ updateSelectionVisuals();
263
+ saveSettings();
264
+ });
265
+
266
+ DOM.downloadBtn.addEventListener('click', async () => {
267
+ const toDownload = state.filteredImages.filter(img => state.selectedImages.has(img.src));
268
+ if (toDownload.length === 0) return;
269
+
270
+ const baseSf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || (window.currentContextTabTitle ? window.currentContextTabTitle.replace(/[\\:*?"<>|]/g, "").trim().slice(0, 80) : 'comics_completos');
271
+ const uniqueSf = await getUniqueSubfolder(baseSf);
272
+
273
+ const is3Hentai = window.currentContextTabUrl && window.currentContextTabUrl.includes('3hentai.net');
274
+
275
+ if (is3Hentai) {
276
+ chrome.runtime.sendMessage({
277
+ action: 'startBackgroundDownloads',
278
+ toDownload,
279
+ baseSf,
280
+ uniqueSf,
281
+ is3Hentai,
282
+ isForcePNG: DOM.forcePNG && DOM.forcePNG.checked,
283
+ separateQuality: DOM.separateQuality && DOM.separateQuality.checked,
284
+ renameSequential: DOM.renameSequential && DOM.renameSequential.checked,
285
+ comicUrl: window.currentContextTabUrl
286
+ }, () => {
287
+ showDownloadingState(0, toDownload.length);
288
+ });
289
+ } else {
290
+ // Original parallel behavior
291
+ toDownload.forEach((img, idx) => downloadImage(img, idx, toDownload.length, uniqueSf));
292
+ }
293
+ });
294
+
295
+ if (DOM.fullscreenBtn) {
296
+ DOM.fullscreenBtn.addEventListener('click', () => {
297
+ const params = new URLSearchParams(window.location.search);
298
+ if (!params.has('tabId') && window.currentContextTabId) {
299
+ chrome.tabs.create({ url: chrome.runtime.getURL('popup.html?tabId=' + window.currentContextTabId) });
300
+ }
301
+ });
302
+ }
303
+
304
+ window.addEventListener('mouseup', () => state.isDragging = false);
305
+ window.addEventListener('mouseleave', () => state.isDragging = false);
306
+
307
+ if (DOM.cleanBrokenToggle) {
308
+ DOM.cleanBrokenToggle.addEventListener('change', () => {
309
+ applyFilters();
310
+ saveSettings();
311
+ });
312
+ }
313
+
314
+ if (DOM.toggleFiltersBtn) {
315
+ if (DOM.toggleFiltersBtn.classList.contains('collapsed')) {
316
+ DOM.toggleFiltersBtn.title = "Expandir filtros";
317
+ } else {
318
+ DOM.toggleFiltersBtn.title = "Contraer filtros";
319
+ }
320
+
321
+ DOM.toggleFiltersBtn.addEventListener('click', () => {
322
+ const isCollapsed = DOM.collapsibleFilters.classList.toggle('collapsed');
323
+ DOM.toggleFiltersBtn.classList.toggle('collapsed', isCollapsed);
324
+ DOM.toggleFiltersBtn.title = isCollapsed ? "Expandir filtros" : "Contraer filtros";
325
+ saveSettings();
326
+ });
327
+ }
328
+
329
+ if (DOM.toggleSeqBtn) {
330
+ DOM.toggleSeqBtn.addEventListener('click', () => {
331
+ if (DOM.seqPanel.style.display === 'none') {
332
+ DOM.seqPanel.style.display = 'block';
333
+ DOM.toggleSeqBtn.style.backgroundColor = 'rgba(225, 29, 72, 0.15)';
334
+ DOM.toggleSeqBtn.style.borderColor = 'var(--accent-color)';
335
+ DOM.toggleSeqBtn.style.color = '#fff';
336
+ } else {
337
+ DOM.seqPanel.style.display = 'none';
338
+ DOM.toggleSeqBtn.style.backgroundColor = '';
339
+ DOM.toggleSeqBtn.style.borderColor = '';
340
+ DOM.toggleSeqBtn.style.color = '';
341
+ }
342
+ });
343
+ }
344
+
345
+ if (DOM.seqStartBtn) {
346
+ DOM.seqStartBtn.addEventListener('click', startSequentialSearch);
347
+ }
348
+
349
+ if (DOM.togglePasteBtn) {
350
+ DOM.togglePasteBtn.addEventListener('click', () => {
351
+ if (DOM.pastePanel.style.display === 'none') {
352
+ DOM.pastePanel.style.display = 'block';
353
+ DOM.togglePasteBtn.style.backgroundColor = 'rgba(225, 29, 72, 0.15)';
354
+ DOM.togglePasteBtn.style.borderColor = 'var(--accent-color)';
355
+ DOM.togglePasteBtn.style.color = '#fff';
356
+ } else {
357
+ DOM.pastePanel.style.display = 'none';
358
+ DOM.togglePasteBtn.style.backgroundColor = '';
359
+ DOM.togglePasteBtn.style.borderColor = '';
360
+ DOM.togglePasteBtn.style.color = '';
361
+ }
362
+ });
363
+ }
364
+
365
+ if (DOM.clearPastedBtn) {
366
+ DOM.clearPastedBtn.addEventListener('click', () => {
367
+ DOM.pasteLinksTextarea.value = '';
368
+ if (DOM.pasteStatus) DOM.pasteStatus.textContent = '';
369
+ });
370
+ }
371
+
372
+ if (DOM.processPastedBtn) {
373
+ DOM.processPastedBtn.addEventListener('click', () => processPastedLinks(false));
374
+ }
375
+
376
+ if (DOM.downloadPastedBtn) {
377
+ DOM.downloadPastedBtn.addEventListener('click', () => processPastedLinks(true));
378
+ }
379
+ }
380
+
381
+ async function processPastedLinks(shouldDownload = false) {
382
+ const rawText = DOM.pasteLinksTextarea ? DOM.pasteLinksTextarea.value : '';
383
+ if (!rawText || !rawText.trim()) {
384
+ if (DOM.pasteStatus) {
385
+ DOM.pasteStatus.style.color = 'var(--danger-color)';
386
+ DOM.pasteStatus.textContent = '❌ Pega algunos enlaces primero.';
387
+ }
388
+ return;
389
+ }
390
+
391
+ const extractedUrls = rawText.match(/https?:\/\/[^\s"']+/gi) || [];
392
+ if (extractedUrls.length === 0) {
393
+ if (DOM.pasteStatus) {
394
+ DOM.pasteStatus.style.color = 'var(--danger-color)';
395
+ DOM.pasteStatus.textContent = '❌ No se encontraron enlaces válidos (http/https).';
396
+ }
397
+ return;
398
+ }
399
+
400
+ const existingSrcs = new Set(state.allImages.map(img => img.src));
401
+ let addedCount = 0;
402
+
403
+ extractedUrls.forEach((url, i) => {
404
+ const cleanUrl = url.trim();
405
+ if (!existingSrcs.has(cleanUrl)) {
406
+ existingSrcs.add(cleanUrl);
407
+ const imgObj = {
408
+ src: cleanUrl,
409
+ alt: `Imagen Pegada ${i + 1}`,
410
+ width: 0,
411
+ height: 0,
412
+ isDirectLink: true
413
+ };
414
+ state.allImages.push(imgObj);
415
+ addedCount++;
416
+ }
417
+ state.selectedImages.add(cleanUrl);
418
+ });
419
+
420
+ if (DOM.selectAll) DOM.selectAll.checked = true;
421
+ applyFilters();
422
+
423
+ if (DOM.pasteStatus) {
424
+ DOM.pasteStatus.style.color = '#10b981';
425
+ DOM.pasteStatus.textContent = `¡${extractedUrls.length} enlaces listos (${addedCount} nuevos cargados en la galería)!`;
426
+ }
427
+
428
+ if (shouldDownload) {
429
+ const toDownload = state.filteredImages.filter(img => state.selectedImages.has(img.src));
430
+ if (toDownload.length === 0) return;
431
+
432
+ const baseSf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || (window.currentContextTabTitle ? window.currentContextTabTitle.replace(/[\\:*?"<>|]/g, "").trim().slice(0, 80) : 'comics_completos');
433
+ const uniqueSf = await getUniqueSubfolder(baseSf);
434
+
435
+ if (DOM.pasteStatus) {
436
+ DOM.pasteStatus.textContent = `⬇️ Descargando ${toDownload.length} imágenes a '${uniqueSf}'...`;
437
+ }
438
+
439
+ toDownload.forEach((img, idx) => downloadImage(img, idx, toDownload.length, uniqueSf));
440
+ }
441
+ }
442
+
443
+ async function updateHDUrls() {
444
+ const isHitomi = window.currentContextTabUrl && window.currentContextTabUrl.includes('hitomi.la');
445
+ const isHentaiera = window.currentContextTabUrl && window.currentContextTabUrl.includes('hentaiera.com');
446
+ const isNHentai = window.currentContextTabUrl && (window.currentContextTabUrl.includes('nhentai.xxx') || window.currentContextTabUrl.includes('nhentai.net') || window.currentContextTabUrl.includes('nhentai.to'));
447
+ const is3Hentai = window.currentContextTabUrl && window.currentContextTabUrl.includes('3hentai.net');
448
+ const isVerComicsPorno = window.currentContextTabUrl && window.currentContextTabUrl.includes('vercomicsporno.com');
449
+ if (isHitomi || isHentaiera || isNHentai || is3Hentai || isVerComicsPorno) {
450
+ DOM.forceHD.checked = false;
451
+ DOM.forceHD.disabled = true;
452
+ return;
453
+ }
454
+
455
+ if (!DOM.forceHD.checked) {
456
+ state.allImages.forEach(img => {
457
+ if (img.originalSrc) {
458
+ img.src = img.originalSrc;
459
+ img.width = img.origWidth;
460
+ img.height = img.origHeight;
461
+ }
462
+ img.hdSearching = false;
463
+ img.hdFound = false;
464
+ });
465
+ applyFilters();
466
+ return;
467
+ }
468
+
469
+ state.allImages.forEach(img => {
470
+ if (!img.originalSrc) {
471
+ img.originalSrc = img.src;
472
+ img.origWidth = img.width;
473
+ img.origHeight = img.height;
474
+ }
475
+ });
476
+
477
+ state.filteredImages.forEach(img => {
478
+ if (img.inLink && img.linkHref && !img.hdFound && !img.hdSearching) {
479
+ img.hdSearching = true;
480
+ }
481
+ if (!img.hdFound && img.src.includes('kemono.') && img.src.includes('/thumbnail/data/')) {
482
+ img.src = img.src.replace('/thumbnail/data/', '/data/');
483
+ img.linkHref = img.src;
484
+ img.hdSearching = true;
485
+ }
486
+ });
487
+
488
+ render();
489
+
490
+ let queue = state.filteredImages.map((img, idx) => ({img, idx})).filter(x => x.img.hdSearching);
491
+ const limit = 5;
492
+ let active = 0;
493
+
494
+ await new Promise(resolve => {
495
+ if (queue.length === 0) return resolve();
496
+
497
+ const processNext = async () => {
498
+ if (queue.length === 0 && active === 0) return resolve();
499
+
500
+ while (active < limit && queue.length > 0) {
501
+ active++;
502
+ const {img, idx} = queue.shift();
503
+
504
+ try {
505
+ const resp = await fetch(img.linkHref);
506
+ const html = await resp.text();
507
+ const doc = new DOMParser().parseFromString(html, 'text/html');
508
+
509
+ let foundSrc = doc.querySelector('#image-container img, .fit-horizontal img, #gimg, .gallery-image img, figure img, .post__content img')?.getAttribute('src');
510
+
511
+ if (!foundSrc && img.linkHref.match(/\.(jpg|jpeg|png|webp|gif|svg|avif|bmp|tiff|tif|ico|heic|heif|jxl)$/i)) foundSrc = img.linkHref;
512
+
513
+ if (!foundSrc) {
514
+ const folder = (new URL(img.originalSrc)).pathname.split('/').slice(0,-1).join('/');
515
+ foundSrc = Array.from(doc.querySelectorAll('img'))
516
+ .map(i => i.getAttribute('src'))
517
+ .find(s => s?.includes(folder) && !s.match(/t\.(jpg|jpeg|png|webp|gif|svg|avif|bmp|tiff|tif|ico|heic|heif|jxl)$/i) && !s.includes('logo'));
518
+ }
519
+
520
+ if (foundSrc) {
521
+ const fullUrl = foundSrc.startsWith('http') ? foundSrc : new URL(foundSrc, img.linkHref).href;
522
+ img.src = fullUrl;
523
+ await new Promise(r => {
524
+ const t = new Image();
525
+ t.onload = () => { img.width = t.naturalWidth; img.height = t.naturalHeight; img.hdFound = true; r(); };
526
+ t.onerror = r;
527
+ t.src = fullUrl;
528
+ });
529
+ }
530
+ } catch {}
531
+
532
+ img.hdSearching = false;
533
+ updateCardForHD(idx);
534
+ active--;
535
+ processNext();
536
+ }
537
+ };
538
+ processNext();
539
+ });
540
+ }
541
+
542
+ function updateCardForHD(idx) {
543
+ const cards = DOM.grid.querySelectorAll('.image-card');
544
+ const card = cards[idx];
545
+ if (!card) return;
546
+ const img = state.filteredImages[idx];
547
+
548
+ let info = `${img.width} × ${img.height}`;
549
+ let style = '';
550
+ if (DOM.forceHD.checked) {
551
+ if (img.hdSearching) { info = '🔎 Buscando...'; style = 'color: #f39c12; font-size: 11px;'; }
552
+ else if (img.hdFound) { info = `🌟 HD: ${img.width}×${img.height}`; style = 'color: #2ecc71; font-weight: bold;'; }
553
+ else { info = '❌ Normal'; style = 'color: #e74c3c; font-size: 11px;'; }
554
+ }
555
+
556
+ const span = card.querySelector('.card-info span');
557
+ if (span) {
558
+ span.innerHTML = info;
559
+ span.setAttribute('style', style);
560
+ }
561
+
562
+ if (img.hdFound) {
563
+ const imgEl = card.querySelector('.image-wrapper img');
564
+ if (imgEl && imgEl.src !== img.src) imgEl.src = img.src;
565
+ const urlBar = card.querySelector('.url-bar');
566
+ if (urlBar && urlBar.textContent !== img.src) urlBar.textContent = img.src;
567
+ }
568
+ }
569
+
570
+ export function render() {
571
+ const scroll = DOM.grid.scrollTop;
572
+ DOM.grid.innerHTML = '';
573
+
574
+ if (state.filteredImages.length === 0) {
575
+ DOM.grid.innerHTML = '<div class="loader"><p>No se encontraron imágenes.</p></div>';
576
+ } else {
577
+ state.filteredImages.forEach((img, idx) => {
578
+ const isSelected = state.selectedImages.has(img.src);
579
+ const card = document.createElement('div');
580
+ card.className = `image-card ${isSelected ? 'selected' : ''}`;
581
+
582
+ let info = `${img.width} × ${img.height}`;
583
+ let style = '';
584
+ if (DOM.forceHD.checked) {
585
+ if (img.hdSearching) { info = '🔎 Buscando...'; style = 'color: #f39c12; font-size: 11px;'; }
586
+ else if (img.hdFound) { info = `🌟 HD: ${img.width}×${img.height}`; style = 'color: #2ecc71; font-weight: bold;'; }
587
+ else { info = '❌ Normal'; style = 'color: #e74c3c; font-size: 11px;'; }
588
+ }
589
+
590
+ card.innerHTML = `
591
+ <input type="checkbox" class="card-checkbox" ${isSelected ? 'checked' : ''}>
592
+ <div class="card-actions">
593
+ <button class="icon-btn btn-ext"><svg viewBox="0 0 24 24"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg></button>
594
+ <button class="icon-btn btn-dl"><svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg></button>
595
+ </div>
596
+ <div class="image-wrapper"><img src="${img.src}" loading="lazy" /><div class="url-bar">${img.src}</div></div>
597
+ <div class="card-info"><span style="${style}">${info}</span></div>
598
+ `;
599
+
600
+ card.querySelector('.btn-ext').onclick = (e) => { e.stopPropagation(); chrome.tabs.create({ url: img.src }); };
601
+ card.querySelector('.btn-dl').onclick = async (e) => {
602
+ e.stopPropagation();
603
+ const baseSf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || (window.currentContextTabTitle ? window.currentContextTabTitle.replace(/[\\:*?"<>|]/g, "").trim().slice(0, 80) : 'comics_completos');
604
+ const uniqueSf = await getUniqueSubfolder(baseSf);
605
+ downloadImage(img, idx, state.filteredImages.length, uniqueSf);
606
+ };
607
+
608
+ const imgEl = card.querySelector('img');
609
+ imgEl.addEventListener('dragstart', (e) => e.preventDefault());
610
+ imgEl.addEventListener('load', () => {
611
+ if ((img.width === 0 || img.height === 0) && imgEl.naturalWidth > 0) {
612
+ img.width = imgEl.naturalWidth;
613
+ img.height = imgEl.naturalHeight;
614
+ const infoSpan = card.querySelector('.card-info span');
615
+ if (infoSpan && !DOM.forceHD.checked) {
616
+ infoSpan.textContent = `${img.width} × ${img.height}`;
617
+ }
618
+ }
619
+ });
620
+ imgEl.addEventListener('error', () => {
621
+ img.isBroken = true;
622
+ if (DOM.cleanBrokenToggle && DOM.cleanBrokenToggle.checked) {
623
+ card.style.display = 'none';
624
+ state.selectedImages.delete(img.src);
625
+ updateSelectionVisuals();
626
+ }
627
+ });
628
+
629
+ card.addEventListener('mousedown', (e) => {
630
+ if (e.target.closest('.card-actions')) return;
631
+ e.preventDefault();
632
+ if (e.shiftKey) {
633
+ toggleSelection(idx, true);
634
+ } else {
635
+ state.isDragging = true;
636
+ state.dragStartIdx = idx;
637
+ state.dragMode = !state.selectedImages.has(img.src);
638
+ state.dragSavedSelection = new Set(state.selectedImages);
639
+ updateDragSelection(idx);
640
+ }
641
+ });
642
+
643
+ card.addEventListener('mouseenter', (e) => {
644
+ if (state.isDragging) {
645
+ updateDragSelection(idx);
646
+ }
647
+ });
648
+
649
+ DOM.grid.appendChild(card);
650
+ });
651
+ }
652
+
653
+ updateSelectionVisuals();
654
+ DOM.grid.scrollTop = scroll;
655
+ }
656
+
657
+ function updateSelectionVisuals() {
658
+ const cards = DOM.grid.querySelectorAll('.image-card');
659
+ state.filteredImages.forEach((img, idx) => {
660
+ const isSelected = state.selectedImages.has(img.src);
661
+ const card = cards[idx];
662
+ if (card) {
663
+ if (isSelected) card.classList.add('selected');
664
+ else card.classList.remove('selected');
665
+
666
+ const checkbox = card.querySelector('.card-checkbox');
667
+ if (checkbox) checkbox.checked = isSelected;
668
+ }
669
+ });
670
+
671
+ DOM.selectedCount.textContent = state.selectedImages.size;
672
+ DOM.btnCounter.textContent = state.selectedImages.size;
673
+ DOM.selectAll.checked = state.filteredImages.length > 0 && state.selectedImages.size === state.filteredImages.length;
674
+ DOM.downloadBtn.disabled = state.selectedImages.size === 0;
675
+ DOM.totalCount.textContent = state.filteredImages.length;
676
+ }
677
+
678
+ function updateDragSelection(currentIdx) {
679
+ state.selectedImages = new Set(state.dragSavedSelection);
680
+ const start = Math.min(state.dragStartIdx, currentIdx);
681
+ const end = Math.max(state.dragStartIdx, currentIdx);
682
+
683
+ for (let i = start; i <= end; i++) {
684
+ const src = state.filteredImages[i].src;
685
+ if (state.dragMode) state.selectedImages.add(src);
686
+ else state.selectedImages.delete(src);
687
+ }
688
+
689
+ state.lastSelectedIdx = currentIdx;
690
+ updateSelectionVisuals();
691
+ }
692
+
693
+ function toggleSelection(idx, shift, forceState = null) {
694
+ const img = state.filteredImages[idx];
695
+ const isCurrentlySelected = state.selectedImages.has(img.src);
696
+
697
+ if (shift && state.lastSelectedIdx !== -1) {
698
+ const start = Math.min(state.lastSelectedIdx, idx);
699
+ const end = Math.max(state.lastSelectedIdx, idx);
700
+ const shouldSelect = !state.selectedImages.has(state.filteredImages[state.lastSelectedIdx].src);
701
+
702
+ for (let i = start; i <= end; i++) {
703
+ const src = state.filteredImages[i].src;
704
+ if (shouldSelect) state.selectedImages.add(src);
705
+ else state.selectedImages.delete(src);
706
+ }
707
+ } else {
708
+ if (forceState !== null) {
709
+ if (forceState) state.selectedImages.add(img.src);
710
+ else state.selectedImages.delete(img.src);
711
+ } else {
712
+ if (isCurrentlySelected) state.selectedImages.delete(img.src);
713
+ else state.selectedImages.add(img.src);
714
+ }
715
+ state.lastSelectedIdx = idx;
716
+ }
717
+ updateSelectionVisuals();
718
+ }
719
+
720
+ async function startSequentialSearch() {
721
+ const urlPattern = DOM.seqUrlPattern.value.trim();
722
+ const startPage = parseInt(DOM.seqStart.value) || 1;
723
+ const endPage = parseInt(DOM.seqEnd.value) || 1;
724
+ const customSelector = DOM.seqSelector.value.trim();
725
+
726
+ if (!urlPattern.includes('{page}')) {
727
+ alert('Por favor, introduce una URL con el marcador {page} para poder paginar.');
728
+ return;
729
+ }
730
+
731
+ if (startPage > endPage) {
732
+ alert('La página de inicio ("Desde") no puede ser mayor que la página final ("Hasta").');
733
+ return;
734
+ }
735
+
736
+ DOM.seqStartBtn.disabled = true;
737
+ DOM.seqStartBtn.textContent = 'Buscando...';
738
+ DOM.seqUrlPattern.disabled = true;
739
+ DOM.seqStart.disabled = true;
740
+ DOM.seqEnd.disabled = true;
741
+ DOM.seqSelector.disabled = true;
742
+ DOM.seqProgress.style.display = 'block';
743
+
744
+ state.allImages = [];
745
+ state.selectedImages.clear();
746
+ applyFilters();
747
+
748
+ const totalPages = endPage - startPage + 1;
749
+ let loadedCount = 0;
750
+
751
+ DOM.seqProgressText.textContent = `0 / ${totalPages}`;
752
+ DOM.seqProgressStatus.textContent = 'Iniciando búsqueda...';
753
+ DOM.seqProgressBar.style.width = '0%';
754
+
755
+ const queue = [];
756
+ for (let p = startPage; p <= endPage; p++) {
757
+ queue.push(p);
758
+ }
759
+
760
+ const limit = 3;
761
+ let activeCount = 0;
762
+
763
+ const processNext = async () => {
764
+ if (queue.length === 0 && activeCount === 0) {
765
+ DOM.seqStartBtn.disabled = false;
766
+ DOM.seqStartBtn.textContent = 'Buscar';
767
+ DOM.seqUrlPattern.disabled = false;
768
+ DOM.seqStart.disabled = false;
769
+ DOM.seqEnd.disabled = false;
770
+ DOM.seqSelector.disabled = false;
771
+ DOM.seqProgressStatus.textContent = '¡Búsqueda completa!';
772
+
773
+ state.allImages.forEach(img => state.selectedImages.add(img.src));
774
+ updateSelectionVisuals();
775
+ return;
776
+ }
777
+
778
+ while (activeCount < limit && queue.length > 0) {
779
+ activeCount++;
780
+ const pageNum = queue.shift();
781
+ const pageUrl = urlPattern.replace('{page}', pageNum);
782
+
783
+ DOM.seqProgressStatus.textContent = `Cargando página ${pageNum}...`;
784
+
785
+ try {
786
+ const resp = await fetch(pageUrl);
787
+ if (!resp.ok) throw new Error(`HTTP error ${resp.status}`);
788
+
789
+ const html = await resp.text();
790
+ const doc = new DOMParser().parseFromString(html, 'text/html');
791
+
792
+ let foundSrc = '';
793
+ if (customSelector) {
794
+ foundSrc = doc.querySelector(customSelector)?.getAttribute('src') || doc.querySelector(customSelector)?.getAttribute('data-src');
795
+ }
796
+
797
+ if (!foundSrc) {
798
+ const standardSelectors = '#gimg, #image-container img, .fit-horizontal img, .gallery-image img, figure img, .post__content img';
799
+ foundSrc = doc.querySelector(standardSelectors)?.getAttribute('src') || doc.querySelector(standardSelectors)?.getAttribute('data-src');
800
+ }
801
+
802
+ if (!foundSrc) {
803
+ const imgs = Array.from(doc.querySelectorAll('img'));
804
+ let bestImg = null;
805
+ let bestScore = 0;
806
+
807
+ imgs.forEach(img => {
808
+ const src = img.getAttribute('src') || img.getAttribute('data-src') || img.getAttribute('data-lazy-src');
809
+ if (!src || src.startsWith('data:') || src.startsWith('blob:')) return;
810
+ if (src.includes('logo') || src.includes('banner') || src.includes('avatar') || src.includes('icon')) return;
811
+
812
+ let score = 10;
813
+ const filename = src.split('/').pop();
814
+ if (filename.match(/\d+/)) score += 20;
815
+ if (img.width >= 300 || img.height >= 300) score += 50;
816
+
817
+ if (score > bestScore) {
818
+ bestScore = score;
819
+ bestImg = src;
820
+ }
821
+ });
822
+
823
+ if (bestImg) {
824
+ foundSrc = bestImg;
825
+ }
826
+ }
827
+
828
+ if (foundSrc) {
829
+ const fullUrl = foundSrc.startsWith('http') ? foundSrc : new URL(foundSrc, pageUrl).href;
830
+
831
+ const imgObj = {
832
+ src: fullUrl,
833
+ width: 0,
834
+ height: 0,
835
+ inLink: false,
836
+ linkHref: null,
837
+ isKemonoThumb: false,
838
+ originalSrc: fullUrl,
839
+ origWidth: 0,
840
+ origHeight: 0
841
+ };
842
+
843
+ await new Promise(resolve => {
844
+ const t = new Image();
845
+ t.onload = () => {
846
+ imgObj.width = t.naturalWidth;
847
+ imgObj.height = t.naturalHeight;
848
+ imgObj.origWidth = t.naturalWidth;
849
+ imgObj.origHeight = t.naturalHeight;
850
+ resolve();
851
+ };
852
+ t.onerror = () => { resolve(); };
853
+ t.src = fullUrl;
854
+ });
855
+
856
+ if (!state.allImages.some(img => img.src === imgObj.src)) {
857
+ state.allImages.push(imgObj);
858
+ state.selectedImages.add(imgObj.src);
859
+ applyFilters();
860
+ }
861
+ }
862
+ } catch (err) {
863
+ console.error(`Error al cargar página ${pageNum}:`, err);
864
+ }
865
+
866
+ loadedCount++;
867
+ activeCount--;
868
+
869
+ const progressPercent = (loadedCount / totalPages) * 100;
870
+ DOM.seqProgressText.textContent = `${loadedCount} / ${totalPages}`;
871
+ DOM.seqProgressBar.style.width = `${progressPercent}%`;
872
+
873
+ processNext();
874
+ }
875
+ };
876
+
877
+ processNext();
878
+ }
879
+
880
+ let originalHTML = '';
881
+
882
+ function showDownloadingState(completed, total) {
883
+ if (!originalHTML) {
884
+ originalHTML = DOM.downloadBtn.innerHTML;
885
+ }
886
+ DOM.downloadBtn.disabled = true;
887
+ const percentage = Math.round((completed / total) * 100);
888
+ DOM.downloadBtn.innerHTML = `
889
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
890
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
891
+ <polyline points="7 10 12 15 17 10"></polyline>
892
+ <line x1="12" y1="15" x2="12" y2="3"></line>
893
+ </svg>
894
+ Descargando... ${percentage}% (${completed}/${total})
895
+ `;
896
+ }
897
+
898
+ function restoreDownloadButton() {
899
+ if (originalHTML) {
900
+ DOM.downloadBtn.disabled = false;
901
+ DOM.downloadBtn.innerHTML = originalHTML;
902
+ originalHTML = '';
903
+ }
904
+ updateSelectionVisuals();
905
+ }
906
+
907
+ chrome.runtime.onMessage.addListener((request) => {
908
+ if (request.action === 'downloadProgress' && request.comicUrl === window.currentContextTabUrl) {
909
+ if (request.downloading) {
910
+ showDownloadingState(request.completed, request.total);
911
+ } else {
912
+ restoreDownloadButton();
913
+ }
914
+ }
915
+ });
916
+