document.addEventListener('DOMContentLoaded', async () => { const statusDiv = document.getElementById('status'); const list = document.getElementById('video-list'); const copyAllBtn = document.getElementById('copy-all'); const deepScanBtn = document.getElementById('deep-scan'); const countBadge = document.getElementById('count-badge'); // Info Panel Logic const infoBtn = document.getElementById('info-btn'); const infoPanel = document.getElementById('info-panel'); if (infoBtn && infoPanel) { infoBtn.addEventListener('click', () => { if (infoPanel.style.display === 'none') { infoPanel.style.display = 'block'; infoBtn.style.color = '#fff'; } else { infoPanel.style.display = 'none'; infoBtn.style.color = 'var(--text-muted)'; } }); } // Toggle Elements const toggleVideo = document.getElementById('toggle-video'); const toggleKemono = document.getElementById('toggle-kemono'); const toggleKemonoDownloads = document.getElementById('toggle-kemono-downloads'); const toggleKemonoImages = document.getElementById('toggle-kemono-images'); const toggleFacebook = document.getElementById('toggle-facebook'); const toggleTiktok = document.getElementById('toggle-tiktok'); const containerVideo = document.getElementById('container-video'); const cardVideo = document.getElementById('card-video'); const cardKemono = document.getElementById('card-kemono'); const cardKemonoDownloads = document.getElementById('card-kemono-downloads'); const cardKemonoImages = document.getElementById('card-kemono-images'); const cardFacebook = document.getElementById('card-facebook'); const cardTiktok = document.getElementById('card-tiktok'); const noToolsMsg = document.getElementById('no-tools-msg'); // Domain Filtering try { let [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (activeTab && activeTab.url) { const urlStr = activeTab.url.toLowerCase(); let showVideo = urlStr.includes('erome.com'); let showKemono = urlStr.includes('kemono.'); let showFacebook = urlStr.includes('facebook.com'); let showTiktok = urlStr.includes('tiktok.com'); cardVideo.style.display = showVideo ? 'block' : 'none'; cardKemono.style.display = showKemono ? 'block' : 'none'; cardKemonoDownloads.style.display = showKemono ? 'block' : 'none'; cardKemonoImages.style.display = showKemono ? 'block' : 'none'; cardFacebook.style.display = showFacebook ? 'block' : 'none'; cardTiktok.style.display = showTiktok ? 'block' : 'none'; if (!showVideo && !showKemono && !showFacebook && !showTiktok) { noToolsMsg.style.display = 'flex'; } // Sync Kemono toggle state if already active if (showKemono) { chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: () => !!window.__kemonoSelectorActive }, (results) => { if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { toggleKemono.checked = true; } }); chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: () => !!window.__kemonoDownloadsActive }, (results) => { if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { toggleKemonoDownloads.checked = true; } }); chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: () => !!window.__kemonoImagesActive }, (results) => { if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { toggleKemonoImages.checked = true; } }); } // Sync Facebook toggle state if already active if (showFacebook) { chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: () => !!window.__fbSelectorActive }, (results) => { if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { toggleFacebook.checked = true; } }); } // Sync TikTok toggle state if already active if (showTiktok) { chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: () => !!window.__ttSelectorActive }, (results) => { if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { toggleTiktok.checked = true; } }); } } } catch (e) { console.error("No se pudo filtrar por dominio", e); } // Toggle Logic para Erome/Video toggleVideo.addEventListener('change', () => { if (toggleVideo.checked) { containerVideo.style.display = 'block'; countBadge.style.display = list.children.length > 0 ? 'inline-block' : 'none'; if (list.children.length === 0 && (!statusDiv.innerHTML.includes('Escaneando álbum') && !statusDiv.innerHTML.includes('Completada'))) { performQuickScan(); } } else { containerVideo.style.display = 'none'; countBadge.style.display = 'none'; } }); // Toggle Logic para Kemono toggleKemono.addEventListener('change', async () => { try { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab || !tab.url || tab.url.startsWith('chrome://')) { toggleKemono.checked = false; showError("No se puede inyectar en esta página."); return; } if (toggleKemono.checked) { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { if (window.__kemonoSelectorActive) return; window.__kemonoSelectorActive = true; const selectedLinks = new Set(); const container = document.createElement('div'); container.id = 'kemono-floating-ui'; container.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: #18181b; color: #fff; padding: 15px; border-radius: 10px; border: 1px solid #27272a; z-index: 999999; font-family: sans-serif; box-shadow: 0 4px 12px rgba(0,0,0,0.5); display: flex; flex-direction: column; gap: 10px; min-width: 200px; `; const countDisplay = document.createElement('div'); countDisplay.textContent = '0 enlaces seleccionados'; countDisplay.style.fontWeight = 'bold'; countDisplay.style.textAlign = 'center'; countDisplay.style.fontSize = '14px'; const copyBtn = document.createElement('button'); copyBtn.textContent = 'Copiar Enlaces'; copyBtn.style.cssText = ` background: #8b5cf6; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const selectAllBtn = document.createElement('button'); selectAllBtn.textContent = 'Seleccionar Todos'; selectAllBtn.style.cssText = ` background: #3f3f46; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; const closeBtn = document.createElement('button'); closeBtn.id = 'kemono-close-btn'; closeBtn.textContent = 'Cerrar Selector'; closeBtn.style.cssText = ` background: #27272a; color: white; border: 1px solid #3f3f46; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 13px; `; container.appendChild(countDisplay); container.appendChild(selectAllBtn); container.appendChild(copyBtn); container.appendChild(closeBtn); document.body.appendChild(container); const style = document.createElement('style'); style.id = 'kemono-style'; style.textContent = ` .kemono-selector-hover { outline: 3px solid #8b5cf6 !important; cursor: crosshair !important; transition: all 0.2s; } .kemono-selector-selected { outline: 4px solid #10b981 !important; opacity: 0.8; position: relative; } .kemono-selector-selected::after { content: '✓'; position: absolute; top: 10px; right: 10px; background: #10b981; color: white; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; z-index: 10; box-shadow: 0 2px 5px rgba(0,0,0,0.5); } .kemono-selector-selected a { pointer-events: none; } `; document.head.appendChild(style); const getPostCard = (el) => el.closest('.post-card'); let isDragging = false; let dragMode = null; // 'select' o 'deselect' const mouseOver = (e) => { const card = getPostCard(e.target); if (card) { if (isDragging) { e.preventDefault(); e.stopPropagation(); const link = card.querySelector('a'); if (!link) return; const url = link.href; if (dragMode === 'select' && !selectedLinks.has(url)) { selectedLinks.add(url); card.classList.add('kemono-selector-selected'); card.classList.remove('kemono-selector-hover'); } else if (dragMode === 'deselect' && selectedLinks.has(url)) { selectedLinks.delete(url); card.classList.remove('kemono-selector-selected'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } else { if (!card.classList.contains('kemono-selector-selected')) { card.classList.add('kemono-selector-hover'); } } } }; const mouseOut = (e) => { const card = getPostCard(e.target); if (card) { card.classList.remove('kemono-selector-hover'); } }; const mouseDown = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); // Evita arrastrar la imagen por defecto del navegador isDragging = true; const link = card.querySelector('a'); if (!link) return; const url = link.href; if (selectedLinks.has(url)) { dragMode = 'deselect'; selectedLinks.delete(url); card.classList.remove('kemono-selector-selected'); } else { dragMode = 'select'; selectedLinks.add(url); card.classList.add('kemono-selector-selected'); card.classList.remove('kemono-selector-hover'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } }; const mouseUp = (e) => { isDragging = false; dragMode = null; }; const dragStart = (e) => { const card = getPostCard(e.target); if (card) e.preventDefault(); }; const click = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); // Evita saltar al enlace de kemono e.stopPropagation(); } }; document.addEventListener('mouseover', mouseOver, true); document.addEventListener('mouseout', mouseOut, true); document.addEventListener('mousedown', mouseDown, true); window.addEventListener('mouseup', mouseUp, true); document.addEventListener('dragstart', dragStart, true); document.addEventListener('click', click, true); selectAllBtn.onclick = () => { const cards = document.querySelectorAll('.post-card'); let allSelected = true; cards.forEach(card => { const link = card.querySelector('a'); if (link && !selectedLinks.has(link.href)) { allSelected = false; } }); if (allSelected && selectedLinks.size > 0) { // Si todo lo de la pantalla está seleccionado, deseleccionar cards.forEach(card => { card.classList.remove('kemono-selector-selected'); const link = card.querySelector('a'); if (link) selectedLinks.delete(link.href); }); selectAllBtn.textContent = 'Seleccionar Todos'; } else { // Seleccionar todo lo que no esté marcado cards.forEach(card => { const link = card.querySelector('a'); if (link && !selectedLinks.has(link.href)) { selectedLinks.add(link.href); card.classList.add('kemono-selector-selected'); card.classList.remove('kemono-selector-hover'); } }); selectAllBtn.textContent = 'Deseleccionar Todos'; } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; }; copyBtn.onclick = () => { if (selectedLinks.size === 0) return; const text = Array.from(selectedLinks).join('\n'); navigator.clipboard.writeText(text).then(() => { const ogText = copyBtn.textContent; copyBtn.textContent = '¡Copiados!'; copyBtn.style.background = '#10b981'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#8b5cf6'; }, 2000); }); }; // Handle close / reset closeBtn.onclick = () => { document.removeEventListener('mouseover', mouseOver, true); document.removeEventListener('mouseout', mouseOut, true); document.removeEventListener('mousedown', mouseDown, true); window.removeEventListener('mouseup', mouseUp, true); document.removeEventListener('dragstart', dragStart, true); document.removeEventListener('click', click, true); container.remove(); style.remove(); document.querySelectorAll('.kemono-selector-selected').forEach(el => el.classList.remove('kemono-selector-selected')); document.querySelectorAll('.kemono-selector-hover').forEach(el => el.classList.remove('kemono-selector-hover')); window.__kemonoSelectorActive = false; // Let the popup know to turn off the toggle if it's still open window.dispatchEvent(new Event('KEMONO_OFF')); }; } }, (results) => { if (chrome.runtime.lastError) { toggleKemono.checked = false; showError("No se pudo inyectar el código. Estás en una web válida?"); } }); } else { // If turning OFF, simulate close button click in the page chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { const closeBtn = document.getElementById('kemono-close-btn'); if (closeBtn) closeBtn.click(); } }); } } catch (err) { console.error(err); toggleKemono.checked = false; showError("Ocurrió un error."); } }); // Toggle Logic para Kemono Descargas toggleKemonoDownloads.addEventListener('change', async () => { try { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab || !tab.url || tab.url.startsWith('chrome://')) { toggleKemonoDownloads.checked = false; showError("No se puede inyectar en esta página."); return; } if (toggleKemonoDownloads.checked) { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { if (window.__kemonoDownloadsActive) return; window.__kemonoDownloadsActive = true; const selectedLinks = new Set(); const container = document.createElement('div'); container.id = 'kemono-dl-floating-ui'; container.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: #18181b; color: #fff; padding: 15px; border-radius: 10px; border: 1px solid #27272a; z-index: 999999; font-family: sans-serif; box-shadow: 0 4px 12px rgba(0,0,0,0.5); display: flex; flex-direction: column; gap: 10px; min-width: 200px; `; const countDisplay = document.createElement('div'); countDisplay.textContent = '0 enlaces seleccionados'; countDisplay.style.fontWeight = 'bold'; countDisplay.style.textAlign = 'center'; countDisplay.style.fontSize = '14px'; const selectAllBtn = document.createElement('button'); selectAllBtn.textContent = 'Seleccionar Todos'; selectAllBtn.style.cssText = ` background: #3f3f46; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; const copyBtn = document.createElement('button'); copyBtn.textContent = 'Procesar Enlaces'; copyBtn.style.cssText = ` background: #fbbf24; color: #000; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const finalCopyBtn = document.createElement('button'); finalCopyBtn.textContent = 'Copiar Enlaces Procesados'; finalCopyBtn.style.cssText = ` background: #10b981; color: #fff; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; display: none; `; const closeBtn = document.createElement('button'); closeBtn.id = 'kemono-dl-close-btn'; closeBtn.textContent = 'Cerrar Selector'; closeBtn.style.cssText = ` background: #27272a; color: white; border: 1px solid #3f3f46; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 13px; `; const uploadTxtBtn = document.createElement('button'); uploadTxtBtn.textContent = 'Cargar TXT'; uploadTxtBtn.style.cssText = ` background: #6366f1; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; uploadTxtBtn.onmouseover = () => uploadTxtBtn.style.background = '#4f46e5'; uploadTxtBtn.onmouseout = () => uploadTxtBtn.style.background = '#6366f1'; const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.txt'; fileInput.multiple = true; fileInput.style.display = 'none'; uploadTxtBtn.onclick = () => fileInput.click(); fileInput.onchange = async (e) => { const files = e.target.files; if (!files || files.length === 0) return; let totalAddedCount = 0; for (let i = 0; i < files.length; i++) { const text = await files[i].text(); const regex = /(https?:\/\/(kemono\.cr|kemono\.su|kemono\.party)\/[a-zA-Z0-9_-]+\/user\/[a-zA-Z0-9_-]+\/post\/[0-9]+)/gi; let matches; while ((matches = regex.exec(text)) !== null) { const url = matches[0].split('?')[0]; if (!selectedLinks.has(url)) { selectedLinks.add(url); totalAddedCount++; } } } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; uploadTxtBtn.textContent = `+${totalAddedCount} Enlaces Agregados!`; setTimeout(() => uploadTxtBtn.textContent = 'Cargar TXT', 3000); }; container.appendChild(countDisplay); container.appendChild(uploadTxtBtn); container.appendChild(fileInput); container.appendChild(selectAllBtn); container.appendChild(copyBtn); container.appendChild(finalCopyBtn); container.appendChild(closeBtn); document.body.appendChild(container); const style = document.createElement('style'); style.id = 'kemono-dl-style'; style.textContent = ` .kemono-dl-selector-hover { outline: 3px solid #fbbf24 !important; cursor: crosshair !important; transition: all 0.2s; } .kemono-dl-selector-selected { outline: 4px solid #f59e0b !important; opacity: 0.8; position: relative; } .kemono-dl-selector-selected::after { content: '✓'; position: absolute; top: 10px; right: 10px; background: #f59e0b; color: white; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; z-index: 10; box-shadow: 0 2px 5px rgba(0,0,0,0.5); } .kemono-dl-success::after { background: #10b981 !important; transform: scale(1.15); transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), background 0.3s; } `; document.head.appendChild(style); const getPostCard = (el) => el.closest('.post-card'); let isDragging = false; let dragMode = null; const mouseOver = (e) => { const card = getPostCard(e.target); if (card) { if (isDragging) { e.preventDefault(); e.stopPropagation(); const link = card.querySelector('a'); if (!link) return; const url = link.href; if (dragMode === 'select' && !selectedLinks.has(url)) { selectedLinks.add(url); card.classList.add('kemono-dl-selector-selected'); card.classList.remove('kemono-dl-selector-hover'); } else if (dragMode === 'deselect' && selectedLinks.has(url)) { selectedLinks.delete(url); card.classList.remove('kemono-dl-selector-selected'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } else { if (!card.classList.contains('kemono-dl-selector-selected')) { card.classList.add('kemono-dl-selector-hover'); } } } }; const mouseOut = (e) => { const card = getPostCard(e.target); if (card) { card.classList.remove('kemono-dl-selector-hover'); } }; const mouseDown = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); isDragging = true; const link = card.querySelector('a'); if (!link) return; const url = link.href; if (selectedLinks.has(url)) { dragMode = 'deselect'; selectedLinks.delete(url); card.classList.remove('kemono-dl-selector-selected'); } else { dragMode = 'select'; selectedLinks.add(url); card.classList.add('kemono-dl-selector-selected'); card.classList.remove('kemono-dl-selector-hover'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } }; const mouseUp = (e) => { isDragging = false; dragMode = null; }; const dragStart = (e) => { const card = getPostCard(e.target); if (card) e.preventDefault(); }; const click = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); e.stopPropagation(); } }; document.addEventListener('mouseover', mouseOver, true); document.addEventListener('mouseout', mouseOut, true); document.addEventListener('mousedown', mouseDown, true); window.addEventListener('mouseup', mouseUp, true); document.addEventListener('dragstart', dragStart, true); document.addEventListener('click', click, true); selectAllBtn.onclick = () => { const cards = document.querySelectorAll('.post-card'); let allSelected = true; cards.forEach(card => { const link = card.querySelector('a'); if (link && !selectedLinks.has(link.href)) { allSelected = false; } }); if (allSelected && selectedLinks.size > 0) { cards.forEach(card => { card.classList.remove('kemono-dl-selector-selected'); const link = card.querySelector('a'); if (link) selectedLinks.delete(link.href); }); selectAllBtn.textContent = 'Seleccionar Todos'; } else { cards.forEach(card => { const link = card.querySelector('a'); if (link && !selectedLinks.has(link.href)) { selectedLinks.add(link.href); card.classList.add('kemono-dl-selector-selected'); card.classList.remove('kemono-dl-selector-hover'); } }); selectAllBtn.textContent = 'Deseleccionar Todos'; } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; }; copyBtn.onclick = async () => { if (selectedLinks.size === 0) return; const ogText = copyBtn.textContent; try { copyBtn.textContent = 'Analizando en Navegador... 0%'; copyBtn.style.background = '#f59e0b'; copyBtn.style.color = '#fff'; copyBtn.disabled = true; finalCopyBtn.style.display = 'none'; const uniqueUrls = [...new Set([...selectedLinks].map(u => u.replace(/\/$/, '')))]; const total = uniqueUrls.length; let outputWithLinks = `\n=========================================\nNUEVA EXTRACCION - ${new Date().toLocaleString()}\nPOSTS CON ENLACES\n=========================================\n\n`; let outputNoLinks = `\n=========================================\nNUEVA EXTRACCION - ${new Date().toLocaleString()}\nPOSTS SIN ENLACES (O ERRORES)\n=========================================\n\n`; let hasLinksElements = false; let hasNoLinksElements = false; let count = 0; const CONCURRENCY_LIMIT = 4; let queue = [...uniqueUrls]; const extractWorker = async (workerId) => { let iframe = document.createElement('iframe'); iframe.id = `kemono-extractor-frame-${workerId}`; iframe.style.width = '1px'; iframe.style.height = '1px'; iframe.style.opacity = '0'; iframe.style.pointerEvents = 'none'; iframe.style.position = 'fixed'; iframe.style.bottom = '0'; document.body.appendChild(iframe); while (queue.length > 0) { const url = queue.shift(); count++; copyBtn.textContent = `Analizando páginas... ${Math.round((count/total)*100)}%`; let postText = ""; try { let loaded = false; iframe.onload = () => { loaded = true; }; iframe.src = url; let waitTimer = 0; while (!loaded && waitTimer < 15000) { await new Promise(r => setTimeout(r, 200)); waitTimer += 200; } await new Promise(r => setTimeout(r, 2500 + Math.random() * 500)); const doc = iframe.contentDocument; if (!doc) throw new Error("Página bloqueada o inaccesible"); let titleEl = doc.querySelector('.post__title span') || doc.querySelector('.post__title') || doc.querySelector('h1'); let title = titleEl ? titleEl.innerText.trim() : 'Desconocido'; let authorEl = doc.querySelector('.post__user-name') || doc.querySelector('.post__author'); let author = authorEl ? authorEl.innerText.trim() : 'Desconocido'; let downloadLinks = []; const isImage = (str) => /\.(jpg|jpeg|png|webp|gif|avif|bmp)(\?|$|\w)/i.test(str || ''); const isValid = (h, fallbackName = '') => { if (!h) return false; if (isImage(h) || isImage(fallbackName)) return false; if (h.includes('/posts/archives/')) return false; // Permitir URLs externas, O si es interna (kemono), exigir que sea /downloads o /data const isExternal = !h.includes('kemono.cr') && !h.includes('kemono.su') && h.startsWith('http'); const isLocalValid = h.includes('/downloads') || h.includes('/data/'); return isExternal || isLocalValid; }; doc.querySelectorAll('a.post__attachment-link, .post__attachment a').forEach(a => { let href = a.getAttribute('href'); let name = a.getAttribute('download') || a.innerText.trim(); if (isValid(href, name)) { if (!href.startsWith('http')) href = new URL(href, url).href; downloadLinks.push(href); } }); doc.querySelectorAll('.post__content a, .post__body a').forEach(a => { let href = a.getAttribute('href'); if (isValid(href)) { downloadLinks.push(href); } }); let contentEl = doc.querySelector('.post__content') || doc.querySelector('.post__body'); let contentText = contentEl ? contentEl.innerHTML : ''; let textUrls = contentText.match(/(https?:\/\/[^\s<"']+)/g) || []; textUrls.forEach(href => { if (isValid(href)) { downloadLinks.push(href); } }); downloadLinks = [...new Set(downloadLinks)]; // Si aún no encontramos el texto de PostData (por si usan initial_state script) if (downloadLinks.length === 0) { let scripts = Array.from(doc.querySelectorAll('script')); for(let s of scripts) { if (s.innerText.includes('postData') || s.innerText.includes('__NUXT__')) { let jsonMatch = s.innerText.match(/(https?:\/\/[^\s<"'\\]+)/g) || []; jsonMatch.forEach(href => { try { let cleanHref = href.replace(/\\u0026/g, '&'); if (isValid(cleanHref)) { downloadLinks.push(cleanHref); } } catch(e) {} }); } } // Apply URL fix if missing domain on Nuxt paths downloadLinks = downloadLinks.map(h => h.startsWith('http') ? h : new URL(h, url).href); downloadLinks = [...new Set(downloadLinks)]; } postText = `Titulo: ${title}\nEnlace original: ${url}\nAutor: ${author}\nEnlaces de descarga:\n`; if (downloadLinks.length > 0) { postText += downloadLinks.map((link, idx) => `(${idx + 1}) ${link}`).join('\n') + '\n\n'; outputWithLinks += postText; hasLinksElements = true; try { const urlPath = new URL(url).pathname; const cardAnchor = document.querySelector(`.post-card a[href="${urlPath}"]`) || document.querySelector(`.post-card a[href$="${urlPath}"]`); if (cardAnchor) { const card = cardAnchor.closest('.post-card'); if (card) { card.classList.add('kemono-dl-success'); setTimeout(() => card.classList.remove('kemono-dl-success'), 150); setTimeout(() => card.classList.add('kemono-dl-success'), 300); } } } catch(e) {} } else { postText += "No hay enlaces detectados\n\n"; outputNoLinks += postText; hasNoLinksElements = true; } } catch (err) { let errorText = `ERROR AL CARGAR: ${url} -> ${err.message}\n\n`; outputNoLinks += errorText; hasNoLinksElements = true; } } document.body.removeChild(iframe); }; const workers = []; for (let i = 0; i < CONCURRENCY_LIMIT; i++) { workers.push((async () => { await new Promise(r => setTimeout(r, i * 700)); await extractWorker(i); })()); } await Promise.all(workers); copyBtn.textContent = 'Enviando a Descargas...'; const port = chrome.runtime.connect({ name: "kemono-native-proxy" }); port.onMessage.addListener((msg) => { if (msg.status === "done") { copyBtn.textContent = '¡Guardado en Descargas!'; copyBtn.style.background = '#10b981'; selectedLinks.clear(); countDisplay.textContent = '0 enlaces seleccionados'; document.querySelectorAll('.kemono-dl-selector-selected').forEach(el => el.classList.remove('kemono-dl-selector-selected')); setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#fbbf24'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 4000); port.disconnect(); } else if (msg.status === "error") { console.error("Native Error:", msg.message); copyBtn.textContent = 'Error en Python'; copyBtn.style.background = '#ef4444'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#fbbf24'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 4000); port.disconnect(); } }); port.onDisconnect.addListener(() => { if (chrome.runtime.lastError) { console.error("Desconectado de Host: ", chrome.runtime.lastError.message); if (chrome.runtime.lastError.message.includes("host not found")) { alert("Error: No se encontró el Host de Python para Kemono.\nAsegúrate de ejecutar el archivo 'instalar_python_host.bat' con el ID correcto de esta extensión."); } copyBtn.textContent = 'Fallo de conexion'; copyBtn.style.background = '#ef4444'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#fbbf24'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 4000); } }); port.postMessage({ type: "SAVE_KEMONO", textLinks: hasLinksElements ? outputWithLinks : "", textNoLinks: hasNoLinksElements ? outputNoLinks : "" }); } catch (err) { copyBtn.textContent = 'Error inesperado'; copyBtn.style.background = '#ef4444'; copyBtn.style.color = '#fff'; console.error(err); setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#fbbf24'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 3000); } }; finalCopyBtn.onclick = () => {}; closeBtn.onclick = () => { document.removeEventListener('mouseover', mouseOver, true); document.removeEventListener('mouseout', mouseOut, true); document.removeEventListener('mousedown', mouseDown, true); window.removeEventListener('mouseup', mouseUp, true); document.removeEventListener('dragstart', dragStart, true); document.removeEventListener('click', click, true); container.remove(); style.remove(); document.querySelectorAll('.kemono-dl-selector-selected').forEach(el => el.classList.remove('kemono-dl-selector-selected')); document.querySelectorAll('.kemono-dl-selector-hover').forEach(el => el.classList.remove('kemono-dl-selector-hover')); window.__kemonoDownloadsActive = false; }; } }, (results) => { if (chrome.runtime.lastError) { toggleKemonoDownloads.checked = false; showError("No se pudo inyectar el código. Estás en una web válida?"); } }); } else { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { const closeBtn = document.getElementById('kemono-dl-close-btn'); if (closeBtn) closeBtn.click(); } }); } } catch (err) { console.error(err); toggleKemonoDownloads.checked = false; showError("Ocurrió un error."); } }); // Toggle Logic para Kemono Imagenes toggleKemonoImages.addEventListener('change', async () => { try { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab || !tab.url || tab.url.startsWith('chrome://')) { toggleKemonoImages.checked = false; showError("No se puede inyectar en esta página."); return; } if (toggleKemonoImages.checked) { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { if (window.__kemonoImagesActive) return; window.__kemonoImagesActive = true; const selectedLinks = new Set(); const duplicatedLinks = []; const container = document.createElement('div'); container.id = 'kemono-img-floating-ui'; container.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: #18181b; color: #fff; padding: 15px; border-radius: 10px; border: 1px solid #27272a; z-index: 999999; font-family: sans-serif; box-shadow: 0 4px 12px rgba(0,0,0,0.5); display: flex; flex-direction: column; gap: 10px; min-width: 200px; `; const countDisplay = document.createElement('div'); countDisplay.textContent = '0 enlaces seleccionados'; countDisplay.style.fontWeight = 'bold'; countDisplay.style.textAlign = 'center'; countDisplay.style.fontSize = '14px'; const selectAllBtn = document.createElement('button'); selectAllBtn.textContent = 'Seleccionar Todos'; selectAllBtn.style.cssText = ` background: #3f3f46; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; const copyBtn = document.createElement('button'); copyBtn.textContent = 'Procesar Imágenes'; copyBtn.style.cssText = ` background: #14b8a6; color: #000; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const finalCopyBtn = document.createElement('button'); finalCopyBtn.textContent = 'Copiar Enlaces Procesados'; finalCopyBtn.style.cssText = ` background: #10b981; color: #fff; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; display: none; `; const closeBtn = document.createElement('button'); closeBtn.id = 'kemono-img-close-btn'; closeBtn.textContent = 'Cerrar Selector'; closeBtn.style.cssText = ` background: #27272a; color: white; border: 1px solid #3f3f46; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 13px; `; const uploadTxtBtn = document.createElement('button'); uploadTxtBtn.textContent = 'Cargar TXT'; uploadTxtBtn.style.cssText = ` background: #6366f1; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; uploadTxtBtn.onmouseover = () => uploadTxtBtn.style.background = '#4f46e5'; uploadTxtBtn.onmouseout = () => uploadTxtBtn.style.background = '#6366f1'; const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.txt'; fileInput.multiple = true; fileInput.style.display = 'none'; uploadTxtBtn.onclick = () => fileInput.click(); fileInput.onchange = async (e) => { const files = e.target.files; if (!files || files.length === 0) return; let totalAddedCount = 0; for (let i = 0; i < files.length; i++) { const text = await files[i].text(); const regex = /(https?:\/\/(kemono\.cr|kemono\.su|kemono\.party)\/[a-zA-Z0-9_-]+\/user\/[a-zA-Z0-9_-]+\/post\/[0-9]+)/gi; let matches; while ((matches = regex.exec(text)) !== null) { const url = matches[0].split('?')[0]; if (!selectedLinks.has(url)) { selectedLinks.add(url); totalAddedCount++; } else { duplicatedLinks.push(url); } } } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; uploadTxtBtn.textContent = `+${totalAddedCount} Enlaces Agregados!`; setTimeout(() => uploadTxtBtn.textContent = 'Cargar TXT', 3000); }; container.appendChild(countDisplay); container.appendChild(uploadTxtBtn); container.appendChild(fileInput); container.appendChild(selectAllBtn); container.appendChild(copyBtn); container.appendChild(finalCopyBtn); container.appendChild(closeBtn); document.body.appendChild(container); const style = document.createElement('style'); style.id = 'kemono-img-style'; style.textContent = ` .kemono-img-selector-hover { outline: 3px solid #14b8a6 !important; cursor: crosshair !important; transition: all 0.2s; } .kemono-img-selector-selected { outline: 4px solid #0d9488 !important; opacity: 0.8; position: relative; } .kemono-img-selector-selected::after { content: '✓'; position: absolute; top: 10px; right: 10px; background: #0d9488; color: white; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; z-index: 10; box-shadow: 0 2px 5px rgba(0,0,0,0.5); } .kemono-img-success::after { background: #10b981 !important; transform: scale(1.15); transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), background 0.3s; } `; document.head.appendChild(style); const getPostCard = (el) => el.closest('.post-card'); let isDragging = false; let dragMode = null; const mouseOver = (e) => { const card = getPostCard(e.target); if (card) { if (isDragging) { e.preventDefault(); e.stopPropagation(); const link = card.querySelector('a'); if (!link) return; const url = link.href; if (dragMode === 'select' && !selectedLinks.has(url)) { selectedLinks.add(url); card.classList.add('kemono-img-selector-selected'); card.classList.remove('kemono-img-selector-hover'); } else if (dragMode === 'deselect' && selectedLinks.has(url)) { selectedLinks.delete(url); card.classList.remove('kemono-img-selector-selected'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } else { if (!card.classList.contains('kemono-img-selector-selected')) { card.classList.add('kemono-img-selector-hover'); } } } }; const mouseOut = (e) => { const card = getPostCard(e.target); if (card) { card.classList.remove('kemono-img-selector-hover'); } }; const mouseDown = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); isDragging = true; const link = card.querySelector('a'); if (!link) return; const url = link.href; if (selectedLinks.has(url)) { dragMode = 'deselect'; selectedLinks.delete(url); card.classList.remove('kemono-img-selector-selected'); } else { dragMode = 'select'; selectedLinks.add(url); card.classList.add('kemono-img-selector-selected'); card.classList.remove('kemono-img-selector-hover'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } }; const mouseUp = (e) => { isDragging = false; dragMode = null; }; const dragStart = (e) => { const card = getPostCard(e.target); if (card) e.preventDefault(); }; const click = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); e.stopPropagation(); } }; document.addEventListener('mouseover', mouseOver, true); document.addEventListener('mouseout', mouseOut, true); document.addEventListener('mousedown', mouseDown, true); window.addEventListener('mouseup', mouseUp, true); document.addEventListener('dragstart', dragStart, true); document.addEventListener('click', click, true); selectAllBtn.onclick = () => { const cards = document.querySelectorAll('.post-card'); let allSelected = true; cards.forEach(card => { const link = card.querySelector('a'); if (link && !selectedLinks.has(link.href)) { allSelected = false; } }); if (allSelected && selectedLinks.size > 0) { cards.forEach(card => { card.classList.remove('kemono-img-selector-selected'); const link = card.querySelector('a'); if (link) selectedLinks.delete(link.href); }); selectAllBtn.textContent = 'Seleccionar Todos'; } else { cards.forEach(card => { const link = card.querySelector('a'); if (link && !selectedLinks.has(link.href)) { selectedLinks.add(link.href); card.classList.add('kemono-img-selector-selected'); card.classList.remove('kemono-img-selector-hover'); } }); selectAllBtn.textContent = 'Deseleccionar Todos'; } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; }; let wakeLockAudio = null; copyBtn.onclick = async () => { if (selectedLinks.size === 0) return; const ogText = copyBtn.textContent; try { if (!wakeLockAudio) { wakeLockAudio = document.createElement('audio'); wakeLockAudio.loop = true; wakeLockAudio.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA'; wakeLockAudio.volume = 0.01; wakeLockAudio.play().catch(()=>{}); } copyBtn.textContent = 'Analizando en Navegador... 0%'; copyBtn.style.background = '#0d9488'; copyBtn.style.color = '#fff'; copyBtn.disabled = true; finalCopyBtn.style.display = 'none'; const uniqueUrls = [...new Set([...selectedLinks].map(u => u.replace(/\/$/, '')))]; const total = uniqueUrls.length; let extractionPayload = []; let count = 0; const CONCURRENCY_LIMIT = 8; let queue = [...uniqueUrls]; const extractWorker = async (workerId) => { let iframe = document.createElement('iframe'); iframe.id = `kemono-extractor-frame-${workerId}`; iframe.style.width = '1px'; iframe.style.height = '1px'; iframe.style.opacity = '0'; iframe.style.pointerEvents = 'none'; iframe.style.position = 'fixed'; iframe.style.bottom = '0'; document.body.appendChild(iframe); while (queue.length > 0) { const url = queue.shift(); count++; copyBtn.textContent = `Analizando páginas... ${Math.round((count/total)*100)}%`; try { let loaded = false; iframe.onload = () => { loaded = true; }; iframe.src = url; let waitTimer = 0; while (!loaded && waitTimer < 15000) { await new Promise(r => setTimeout(r, 200)); waitTimer += 200; } await new Promise(r => setTimeout(r, 1200 + Math.random() * 500)); const doc = iframe.contentDocument; if (!doc) throw new Error("Página inaccesible"); let titleEl = doc.querySelector('.post__title span') || doc.querySelector('.post__title') || doc.querySelector('h1'); let title = titleEl ? titleEl.innerText.trim() : 'Desconocido'; let authorEl = doc.querySelector('.post__user-name') || doc.querySelector('.post__author'); let author = authorEl ? authorEl.innerText.trim() : 'Desconocido'; let imageLinks = []; const isImage = (str) => /\.(jpg|jpeg|png|webp|gif|avif)(\?|$|\w)/i.test(str || ''); // Attachments and Main Files doc.querySelectorAll('a.post__attachment-link, .post__attachment a, a.fileThumb, .post__thumbnail a, a[download]').forEach(a => { let href = a.getAttribute('href'); let name = a.getAttribute('download') || a.innerText.trim(); if (isImage(href) || isImage(name)) { if (!href.startsWith('http')) href = new URL(href, url).href; href = href.replace(/\/thumbnail\//g, '/'); imageLinks.push(href); } }); // Images inside content doc.querySelectorAll('.post__content img, .post__body img, .post__content a, .post__body a').forEach(el => { let src = el.getAttribute('src') || el.getAttribute('href'); if (isImage(src)) { if (!src.startsWith('http')) src = new URL(src, url).href; src = src.replace(/\/thumbnail\//g, '/'); imageLinks.push(src); } }); imageLinks = [...new Set(imageLinks)]; // Si la página usa Vue/Nuxt y no renderizó todo if (imageLinks.length === 0) { let scripts = Array.from(doc.querySelectorAll('script')); for(let s of scripts) { if (s.innerText.includes('postData') || s.innerText.includes('__NUXT__')) { let jsonMatch = s.innerText.match(/(https?:\/\/[^\s<"'\\]+)/g) || []; // También buscar URLs locales como /data/ let localMatch = s.innerText.match(/(\/data\/[^\s<"'\\]+)/g) || []; let allMatches = [...jsonMatch, ...localMatch]; allMatches.forEach(href => { try { let cleanHref = href.replace(/\\u0026/g, '&'); if (isImage(cleanHref)) { if (!cleanHref.startsWith('http')) cleanHref = new URL(cleanHref, url).href; cleanHref = cleanHref.replace(/\/thumbnail\//g, '/'); imageLinks.push(cleanHref); } } catch(e) {} }); } } imageLinks = [...new Set(imageLinks)]; } if (imageLinks.length > 0) { extractionPayload.push({ url: url, title: title, author: author, images: imageLinks, isDuplicate: false }); try { const urlPath = new URL(url).pathname; const cardAnchor = document.querySelector(`.post-card a[href="${urlPath}"]`) || document.querySelector(`.post-card a[href$="${urlPath}"]`); if (cardAnchor) { const card = cardAnchor.closest('.post-card'); if (card) { card.classList.add('kemono-img-success'); setTimeout(() => card.classList.remove('kemono-img-success'), 150); setTimeout(() => card.classList.add('kemono-img-success'), 300); } } } catch(e) {} } } catch (err) { console.error("Error cargando " + url, err); } } document.body.removeChild(iframe); }; const workers = []; for (let i = 0; i < CONCURRENCY_LIMIT; i++) { workers.push((async () => { await new Promise(r => setTimeout(r, i * 700)); await extractWorker(i); })()); } await Promise.all(workers); copyBtn.textContent = 'Enviando a Descargas...'; const port = chrome.runtime.connect({ name: "kemono-native-proxy" }); port.onMessage.addListener((msg) => { if (msg.status === "done") { copyBtn.textContent = '¡Enviado a Descargar Imágenes!'; copyBtn.style.background = '#10b981'; selectedLinks.clear(); countDisplay.textContent = '0 enlaces seleccionados'; document.querySelectorAll('.kemono-img-selector-selected').forEach(el => el.classList.remove('kemono-img-selector-selected')); setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#14b8a6'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 4000); if (wakeLockAudio) { wakeLockAudio.pause(); wakeLockAudio.remove(); wakeLockAudio = null; } port.disconnect(); } else if (msg.status === "progress") { if (msg.info) { copyBtn.textContent = msg.info; } else if (msg.current) { copyBtn.textContent = `Procesando ${msg.current}/${msg.total}...`; } } else if (msg.status === "error") { console.error("Native Error:", msg.message || msg.error); copyBtn.textContent = 'Error en Python'; copyBtn.style.background = '#ef4444'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#14b8a6'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 4000); if (wakeLockAudio) { wakeLockAudio.pause(); wakeLockAudio.remove(); wakeLockAudio = null; } port.disconnect(); } }); port.onDisconnect.addListener(() => { if (chrome.runtime.lastError) { console.error("Desconectado de Host: ", chrome.runtime.lastError.message); if (chrome.runtime.lastError.message.includes("host not found")) { alert("Error: No se encontró el Host de Python para Kemono.\nAsegúrate de ejecutar el archivo 'instalar_python_host.bat' con el ID correcto de esta extensión."); } copyBtn.textContent = 'Fallo de conexion'; copyBtn.style.background = '#ef4444'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#14b8a6'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 4000); } if (wakeLockAudio) { wakeLockAudio.pause(); wakeLockAudio.remove(); wakeLockAudio = null; } }); port.postMessage({ type: "DOWNLOAD_IMAGES_KEMONO", data: extractionPayload }); } catch (err) { copyBtn.textContent = 'Error inesperado'; copyBtn.style.background = '#ef4444'; copyBtn.style.color = '#fff'; console.error(err); setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#14b8a6'; copyBtn.style.color = '#000'; copyBtn.disabled = false; }, 3000); if (wakeLockAudio) { wakeLockAudio.pause(); wakeLockAudio.remove(); wakeLockAudio = null; } } }; finalCopyBtn.onclick = () => {}; closeBtn.onclick = () => { if (wakeLockAudio) { wakeLockAudio.pause(); wakeLockAudio.remove(); wakeLockAudio = null; } document.removeEventListener('mouseover', mouseOver, true); document.removeEventListener('mouseout', mouseOut, true); document.removeEventListener('mousedown', mouseDown, true); window.removeEventListener('mouseup', mouseUp, true); document.removeEventListener('dragstart', dragStart, true); document.removeEventListener('click', click, true); container.remove(); style.remove(); document.querySelectorAll('.kemono-img-selector-selected').forEach(el => el.classList.remove('kemono-img-selector-selected')); document.querySelectorAll('.kemono-img-selector-hover').forEach(el => el.classList.remove('kemono-img-selector-hover')); window.__kemonoImagesActive = false; }; } }, (results) => { if (chrome.runtime.lastError) { toggleKemonoImages.checked = false; showError("No se pudo inyectar el código. Estás en una web válida?"); } }); } else { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { const closeBtn = document.getElementById('kemono-img-close-btn'); if (closeBtn) closeBtn.click(); } }); } } catch (err) { console.error(err); toggleKemonoImages.checked = false; showError("Ocurrió un error."); } }); // Toggle Logic para Facebook toggleFacebook.addEventListener('change', async () => { try { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab || !tab.url || tab.url.startsWith('chrome://')) { toggleFacebook.checked = false; showError("No se puede inyectar en esta página."); return; } if (toggleFacebook.checked) { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { if (window.__fbSelectorActive) return; window.__fbSelectorActive = true; const selectedLinks = new Set(); const container = document.createElement('div'); container.id = 'fb-floating-ui'; container.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: #18181b; color: #fff; padding: 15px; border-radius: 10px; border: 1px solid #27272a; z-index: 999999; font-family: sans-serif; box-shadow: 0 4px 12px rgba(0,0,0,0.5); display: flex; flex-direction: column; gap: 10px; min-width: 200px; `; const countDisplay = document.createElement('div'); countDisplay.textContent = '0 enlaces seleccionados'; countDisplay.style.fontWeight = 'bold'; countDisplay.style.textAlign = 'center'; countDisplay.style.fontSize = '14px'; const autoScanBtn = document.createElement('button'); autoScanBtn.textContent = 'Buscar enlaces de videos'; autoScanBtn.style.cssText = ` background: #2563eb; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const copyBtn = document.createElement('button'); copyBtn.textContent = 'Copiar Enlaces'; copyBtn.style.cssText = ` background: #8b5cf6; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const selectAllBtn = document.createElement('button'); selectAllBtn.textContent = 'Seleccionar Todos'; selectAllBtn.style.cssText = ` background: #3f3f46; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; const closeBtn = document.createElement('button'); closeBtn.id = 'fb-close-btn'; closeBtn.textContent = 'Cerrar Selector'; closeBtn.style.cssText = ` background: #27272a; color: white; border: 1px solid #3f3f46; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 13px; `; container.appendChild(countDisplay); container.appendChild(autoScanBtn); container.appendChild(selectAllBtn); container.appendChild(copyBtn); container.appendChild(closeBtn); document.body.appendChild(container); const style = document.createElement('style'); style.id = 'fb-style'; style.textContent = ` .fb-selector-hover { outline: 3px solid #60a5fa !important; cursor: crosshair !important; transition: all 0.2s; } .fb-selector-selected { outline: 4px solid #10b981 !important; opacity: 0.8; position: relative; } .fb-selector-selected::after { content: '✓'; position: absolute; top: 10px; right: 10px; background: #10b981; color: white; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; z-index: 10; box-shadow: 0 2px 5px rgba(0,0,0,0.5); } `; document.head.appendChild(style); const getPostCard = (el) => el.closest('a[href*="/reel/"], a[href*="/videos/"], a[href*="/watch/"]'); let isDragging = false; let dragMode = null; const mouseOver = (e) => { const card = getPostCard(e.target); if (card) { if (isDragging) { e.preventDefault(); e.stopPropagation(); const url = card.href.split('?')[0]; if (dragMode === 'select' && !selectedLinks.has(url)) { selectedLinks.add(url); card.classList.add('fb-selector-selected'); card.classList.remove('fb-selector-hover'); } else if (dragMode === 'deselect' && selectedLinks.has(url)) { selectedLinks.delete(url); card.classList.remove('fb-selector-selected'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } else { if (!card.classList.contains('fb-selector-selected')) { card.classList.add('fb-selector-hover'); } } } }; const mouseOut = (e) => { const card = getPostCard(e.target); if (card) { card.classList.remove('fb-selector-hover'); } }; const mouseDown = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); isDragging = true; const url = card.href.split('?')[0]; if (selectedLinks.has(url)) { dragMode = 'deselect'; selectedLinks.delete(url); card.classList.remove('fb-selector-selected'); } else { dragMode = 'select'; selectedLinks.add(url); card.classList.add('fb-selector-selected'); card.classList.remove('fb-selector-hover'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } }; const mouseUp = (e) => { isDragging = false; dragMode = null; }; const dragStart = (e) => { const card = getPostCard(e.target); if (card) e.preventDefault(); }; const click = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); e.stopPropagation(); } }; document.addEventListener('mouseover', mouseOver, true); document.addEventListener('mouseout', mouseOut, true); document.addEventListener('mousedown', mouseDown, true); window.addEventListener('mouseup', mouseUp, true); document.addEventListener('dragstart', dragStart, true); document.addEventListener('click', click, true); let scanInterval = null; autoScanBtn.onclick = () => { if (window.__fbIsScanning) { // Stop it manually clearInterval(scanInterval); window.__fbIsScanning = false; autoScanBtn.textContent = 'Buscar enlaces de videos'; autoScanBtn.style.background = '#2563eb'; return; } window.__fbIsScanning = true; autoScanBtn.textContent = 'Buscando... (0)'; autoScanBtn.style.background = '#ef4444'; // Rojo para poder detener let lastHeight = 0; let retries = 0; const maxRetries = 5; // 5 comprobaciones sin cambios = detiene scanInterval = setInterval(() => { window.scrollTo(0, document.body.scrollHeight); const links = document.querySelectorAll('a[href*="/reel/"], a[href*="/videos/"], a[href*="/watch/"]'); let addedNew = false; links.forEach(a => { let cleanUrl = a.href.split('?')[0]; if (!selectedLinks.has(cleanUrl)) { selectedLinks.add(cleanUrl); a.classList.add('fb-selector-selected'); a.classList.remove('fb-selector-hover'); addedNew = true; } }); countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; autoScanBtn.textContent = 'Detener búsqueda (' + selectedLinks.size + ')'; if (document.body.scrollHeight === lastHeight && !addedNew) { retries++; if (retries >= maxRetries) { clearInterval(scanInterval); window.__fbIsScanning = false; autoScanBtn.textContent = 'Buscar enlaces de videos'; autoScanBtn.style.background = '#2563eb'; } } else { retries = 0; } lastHeight = document.body.scrollHeight; }, 1500); // Verifica cada 1.5 segundos }; selectAllBtn.onclick = () => { const cards = document.querySelectorAll('a[href*="/reel/"], a[href*="/videos/"], a[href*="/watch/"]'); let allSelected = true; cards.forEach(card => { const url = card.href.split('?')[0]; if (!selectedLinks.has(url)) { allSelected = false; } }); if (allSelected && selectedLinks.size > 0) { cards.forEach(card => { card.classList.remove('fb-selector-selected'); const url = card.href.split('?')[0]; selectedLinks.delete(url); }); selectAllBtn.textContent = 'Seleccionar Todos'; } else { cards.forEach(card => { const url = card.href.split('?')[0]; if (!selectedLinks.has(url)) { selectedLinks.add(url); card.classList.add('fb-selector-selected'); card.classList.remove('fb-selector-hover'); } }); selectAllBtn.textContent = 'Deseleccionar Todos'; } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; }; copyBtn.onclick = () => { if (selectedLinks.size === 0) return; const text = Array.from(selectedLinks).join('\n'); navigator.clipboard.writeText(text).then(() => { const ogText = copyBtn.textContent; copyBtn.textContent = '¡Copiados!'; copyBtn.style.background = '#10b981'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#8b5cf6'; }, 2000); }); }; closeBtn.onclick = () => { if (scanInterval) clearInterval(scanInterval); window.__fbIsScanning = false; document.removeEventListener('mouseover', mouseOver, true); document.removeEventListener('mouseout', mouseOut, true); document.removeEventListener('mousedown', mouseDown, true); window.removeEventListener('mouseup', mouseUp, true); document.removeEventListener('dragstart', dragStart, true); document.removeEventListener('click', click, true); container.remove(); style.remove(); document.querySelectorAll('.fb-selector-selected').forEach(el => el.classList.remove('fb-selector-selected')); document.querySelectorAll('.fb-selector-hover').forEach(el => el.classList.remove('fb-selector-hover')); window.__fbSelectorActive = false; window.dispatchEvent(new Event('FB_OFF')); }; } }, (results) => { if (chrome.runtime.lastError) { toggleFacebook.checked = false; showError("No se pudo inyectar el código. Estás en una web válida?"); } }); } else { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { const closeBtn = document.getElementById('fb-close-btn'); if (closeBtn) closeBtn.click(); } }); } } catch (err) { console.error(err); } }); // Toggle Logic para TikTok toggleTiktok.addEventListener('change', async () => { try { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab || !tab.url || tab.url.startsWith('chrome://')) { toggleTiktok.checked = false; showError("No se puede inyectar en esta página."); return; } if (toggleTiktok.checked) { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { if (window.__ttSelectorActive) return; window.__ttSelectorActive = true; const selectedLinks = new Set(); const container = document.createElement('div'); container.id = 'tt-floating-ui'; container.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: #18181b; color: #fff; padding: 15px; border-radius: 10px; border: 1px solid #27272a; z-index: 999999; font-family: sans-serif; box-shadow: 0 4px 12px rgba(0,0,0,0.5); display: flex; flex-direction: column; gap: 10px; min-width: 200px; `; const countDisplay = document.createElement('div'); countDisplay.textContent = '0 enlaces seleccionados'; countDisplay.style.fontWeight = 'bold'; countDisplay.style.textAlign = 'center'; countDisplay.style.fontSize = '14px'; const autoScanBtn = document.createElement('button'); autoScanBtn.textContent = 'Buscar enlaces de videos'; autoScanBtn.style.cssText = ` background: #ff0050; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const copyBtn = document.createElement('button'); copyBtn.textContent = 'Copiar Enlaces'; copyBtn.style.cssText = ` background: #8b5cf6; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: bold; `; const selectAllBtn = document.createElement('button'); selectAllBtn.textContent = 'Seleccionar Todos'; selectAllBtn.style.cssText = ` background: #3f3f46; color: white; border: none; padding: 8px; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; transition: background 0.2s; `; selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; const closeBtn = document.createElement('button'); closeBtn.id = 'tt-close-btn'; closeBtn.textContent = 'Cerrar Selector'; closeBtn.style.cssText = ` background: #27272a; color: white; border: 1px solid #3f3f46; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 13px; `; container.appendChild(countDisplay); container.appendChild(autoScanBtn); container.appendChild(selectAllBtn); container.appendChild(copyBtn); container.appendChild(closeBtn); document.body.appendChild(container); const style = document.createElement('style'); style.id = 'tt-style'; style.textContent = ` .tt-selector-hover { outline: 3px solid #ff0050 !important; cursor: crosshair !important; transition: all 0.2s; z-index: 10; } .tt-selector-selected { outline: 4px solid #10b981 !important; opacity: 0.8; position: relative; z-index: 5; } .tt-selector-selected::after { content: '✓'; position: absolute; top: 10px; right: 10px; background: #10b981; color: white; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; z-index: 20; box-shadow: 0 2px 5px rgba(0,0,0,0.5); } `; document.head.appendChild(style); const getPostCard = (el) => { return el.closest('a[href*="/video/"]') || el.closest('[data-e2e="user-post-item"]'); }; let isDragging = false; let dragMode = null; const mouseOver = (e) => { const card = getPostCard(e.target); if (card) { if (isDragging) { e.preventDefault(); e.stopPropagation(); const link = card.tagName === 'A' ? card : card.querySelector('a[href*="/video/"]'); if (!link) return; const url = link.href.split('?')[0]; if (dragMode === 'select' && !selectedLinks.has(url)) { selectedLinks.add(url); card.classList.add('tt-selector-selected'); card.classList.remove('tt-selector-hover'); } else if (dragMode === 'deselect' && selectedLinks.has(url)) { selectedLinks.delete(url); card.classList.remove('tt-selector-selected'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } else { if (!card.classList.contains('tt-selector-selected')) { card.classList.add('tt-selector-hover'); } } } }; const mouseOut = (e) => { const card = getPostCard(e.target); if (card) { card.classList.remove('tt-selector-hover'); } }; const mouseDown = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); isDragging = true; const link = card.tagName === 'A' ? card : card.querySelector('a[href*="/video/"]'); if (!link) return; const url = link.href.split('?')[0]; if (selectedLinks.has(url)) { dragMode = 'deselect'; selectedLinks.delete(url); card.classList.remove('tt-selector-selected'); } else { dragMode = 'select'; selectedLinks.add(url); card.classList.add('tt-selector-selected'); card.classList.remove('tt-selector-hover'); } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; } }; const mouseUp = (e) => { isDragging = false; dragMode = null; }; const dragStart = (e) => { const card = getPostCard(e.target); if (card) e.preventDefault(); }; const click = (e) => { const card = getPostCard(e.target); if (card) { e.preventDefault(); e.stopPropagation(); } }; document.addEventListener('mouseover', mouseOver, true); document.addEventListener('mouseout', mouseOut, true); document.addEventListener('mousedown', mouseDown, true); window.addEventListener('mouseup', mouseUp, true); document.addEventListener('dragstart', dragStart, true); document.addEventListener('click', click, true); let scanInterval = null; autoScanBtn.onclick = () => { if (window.__ttIsScanning) { clearInterval(scanInterval); window.__ttIsScanning = false; autoScanBtn.textContent = 'Buscar enlaces de videos'; autoScanBtn.style.background = '#ff0050'; return; } window.__ttIsScanning = true; autoScanBtn.textContent = 'Buscando... (0)'; autoScanBtn.style.background = '#27272a'; let lastHeight = 0; let retries = 0; const maxRetries = 10; scanInterval = setInterval(() => { window.scrollTo(0, document.body.scrollHeight); const links = document.querySelectorAll('a[href*="/video/"]'); let addedNew = false; links.forEach(a => { let cleanUrl = a.href.split('?')[0]; if (!selectedLinks.has(cleanUrl)) { selectedLinks.add(cleanUrl); const card = getPostCard(a) || a; card.classList.add('tt-selector-selected'); card.classList.remove('tt-selector-hover'); addedNew = true; } }); countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; autoScanBtn.textContent = 'Detener búsqueda (' + selectedLinks.size + ')'; if (document.body.scrollHeight === lastHeight && !addedNew) { retries++; if (retries >= maxRetries) { clearInterval(scanInterval); window.__ttIsScanning = false; autoScanBtn.textContent = 'Buscar enlaces de videos'; autoScanBtn.style.background = '#ff0050'; } } else { retries = 0; } lastHeight = document.body.scrollHeight; }, 2000); }; selectAllBtn.onclick = () => { const links = document.querySelectorAll('a[href*="/video/"]'); let allSelected = true; links.forEach(a => { const url = a.href.split('?')[0]; if (!selectedLinks.has(url)) { allSelected = false; } }); if (allSelected && selectedLinks.size > 0) { links.forEach(a => { const url = a.href.split('?')[0]; selectedLinks.delete(url); const card = getPostCard(a) || a; card.classList.remove('tt-selector-selected'); }); selectAllBtn.textContent = 'Seleccionar Todos'; } else { links.forEach(a => { const url = a.href.split('?')[0]; if (!selectedLinks.has(url)) { selectedLinks.add(url); const card = getPostCard(a) || a; card.classList.add('tt-selector-selected'); card.classList.remove('tt-selector-hover'); } }); selectAllBtn.textContent = 'Deseleccionar Todos'; } countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; }; copyBtn.onclick = () => { if (selectedLinks.size === 0) return; const text = Array.from(selectedLinks).join('\n'); navigator.clipboard.writeText(text).then(() => { const ogText = copyBtn.textContent; copyBtn.textContent = '¡Copiados!'; copyBtn.style.background = '#10b981'; setTimeout(() => { copyBtn.textContent = ogText; copyBtn.style.background = '#8b5cf6'; }, 2000); }); }; closeBtn.onclick = () => { if (scanInterval) clearInterval(scanInterval); window.__ttIsScanning = false; document.removeEventListener('mouseover', mouseOver, true); document.removeEventListener('mouseout', mouseOut, true); document.removeEventListener('mousedown', mouseDown, true); window.removeEventListener('mouseup', mouseUp, true); document.removeEventListener('dragstart', dragStart, true); document.removeEventListener('click', click, true); container.remove(); style.remove(); document.querySelectorAll('.tt-selector-selected').forEach(el => el.classList.remove('tt-selector-selected')); document.querySelectorAll('.tt-selector-hover').forEach(el => el.classList.remove('tt-selector-hover')); window.__ttSelectorActive = false; window.dispatchEvent(new Event('TT_OFF')); }; } }, (results) => { if (chrome.runtime.lastError) { toggleTiktok.checked = false; showError("No se pudo inyectar el código."); } }); } else { chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { const closeBtn = document.getElementById('tt-close-btn'); if (closeBtn) closeBtn.click(); } }); } } catch (err) { console.error(err); toggleTiktok.checked = false; showError("Ocurrió un error."); } }); // Listen for events from page to sync toggles chrome.runtime.onMessage.addListener((msg) => { if (msg.type === 'UI_CLOSED') { if (msg.tool === 'tiktok') toggleTiktok.checked = false; if (msg.tool === 'facebook') toggleFacebook.checked = false; if (msg.tool === 'kemono') toggleKemono.checked = false; } }); // Listen for background updates chrome.runtime.onMessage.addListener((message) => { if (message.type === 'SCAN_UPDATE') { renderState(message.payload); } }); try { // Fetch current state from background chrome.runtime.sendMessage({ type: 'GET_STATE' }, (state) => { if (chrome.runtime.lastError) { console.error("Background script not ready yet", chrome.runtime.lastError); return; } if (state && (state.isScanning || state.totalCount > 0)) { // If scanning or finished deep scan, inherently turn ON Video mode toggleVideo.checked = true; containerVideo.style.display = 'block'; renderState(state); } }); } catch (e) { showError("No se pudo conectar con la extensión de fondo."); } function renderState(state) { if (state.isScanning) { const percentage = Math.round((state.scannedCount / state.totalCount) * 100) || 0; deepScanBtn.style.display = 'flex'; deepScanBtn.disabled = true; deepScanBtn.style.position = 'relative'; deepScanBtn.innerHTML = `
Escaneando álbum ${state.scannedCount} de ${state.totalCount} (${percentage}%)
`; } else if (state.totalCount > 0) { deepScanBtn.style.display = 'flex'; deepScanBtn.disabled = false; deepScanBtn.innerHTML = `✨ Búsqueda Profunda Completada`; deepScanBtn.classList.add('success'); setTimeout(() => { deepScanBtn.style.display = 'none'; }, 4000); // Add a clean up button const resetBtn = document.createElement('button'); resetBtn.className = 'secondary'; resetBtn.innerHTML = 'Borrar Resultados (Escanear nueva página)'; resetBtn.onclick = () => { chrome.runtime.sendMessage({ type: 'RESET_SCAN' }, () => { window.location.reload(); }); }; if (!document.getElementById('reset-btn')) { resetBtn.id = 'reset-btn'; deepScanBtn.parentNode.insertBefore(resetBtn, deepScanBtn.nextSibling); } } renderList(state.foundUrls, state.albumUrls || []); } async function performQuickScan() { statusDiv.style.display = 'flex'; // show loading statusDiv.innerHTML = 'Escaneando página actual...'; try { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab || !tab.url || tab.url.startsWith('chrome://')) { showError("No se puede escanear esta página (ej. Configuración de Chrome). Ve a una pestaña web normal."); return; } chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { let urls = new Set(); let albumLinks = new Set(); try { document.querySelectorAll('video').forEach(v => { if (v.src && !v.src.startsWith('blob:')) urls.add(v.src); v.querySelectorAll('source').forEach(s => { if (s.src && !s.src.startsWith('blob:')) urls.add(s.src); }); }); document.querySelectorAll('a').forEach(a => { if (a.href && typeof a.href === 'string') { if (a.href.includes('.mp4')) { urls.add(a.href); } else if (a.href.includes('facebook.com/reel/') || a.href.match(/facebook\.com\/.*\/videos\//)) { urls.add(a.href.split('?')[0]); } else if (a.href.includes('facebook.com/watch')) { urls.add(a.href); } if (a.href.match(/erome\.com\/a\/[a-zA-Z0-9]+/)) { albumLinks.add(a.href); } } }); } catch(e) { return { error: e.message }; } return { videos: Array.from(urls), albums: Array.from(albumLinks) }; } }, (results) => { if (chrome.runtime.lastError || !results || !results[0]) { showError("No se pudo inyectar el código en la pestaña. Verifica que la página cargó por completo."); return; } const data = results[0].result; if (data.error) { showError("Error en la página: " + data.error); return; } const currentVideos = data.videos || []; const albumLinks = data.albums || []; renderList(currentVideos, albumLinks); if (albumLinks.length > 0) { deepScanBtn.style.display = 'flex'; deepScanBtn.innerHTML = `🔍 Explorar en fondo (${albumLinks.length} álbumes)`; deepScanBtn.classList.remove('success'); const resetBtn = document.getElementById('reset-btn'); if (resetBtn) resetBtn.remove(); deepScanBtn.onclick = () => { chrome.runtime.sendMessage({ type: 'START_SCAN', payload: { albumUrls: albumLinks, currentVideos: currentVideos } }, (state) => { renderState(state); }); }; } }); } catch (err) { showError("Ocurrió un error general."); console.error(err); } } function renderList(urlsArray, albumLinks) { list.innerHTML = ''; if (urlsArray && urlsArray.length > 0) { statusDiv.style.display = 'none'; copyAllBtn.style.display = 'flex'; countBadge.style.display = 'inline-block'; countBadge.textContent = `${urlsArray.length} video${urlsArray.length !== 1 ? 's' : ''}`; copyAllBtn.onclick = () => { const allLinks = urlsArray.join('\n'); navigator.clipboard.writeText(allLinks); copyAllBtn.innerHTML = ' ¡Todos copiados!'; copyAllBtn.classList.add('success'); setTimeout(() => { copyAllBtn.innerHTML = ' Copiar Todos a la Vez'; copyAllBtn.classList.remove('success'); }, 2000); }; urlsArray.forEach((url, i) => { const li = document.createElement('li'); const urlContainer = document.createElement('div'); urlContainer.className = 'url-container'; const urlStr = document.createElement('div'); urlStr.className = 'url'; urlStr.textContent = url; urlStr.title = url; urlContainer.appendChild(urlStr); const copyBtn = document.createElement('button'); copyBtn.innerHTML = ' Copiar'; copyBtn.onclick = () => { navigator.clipboard.writeText(url); copyBtn.innerHTML = ' Copiado'; copyBtn.classList.add('success'); setTimeout(() => { copyBtn.innerHTML = ' Copiar'; copyBtn.classList.remove('success'); }, 1000); }; li.appendChild(urlContainer); li.appendChild(copyBtn); list.appendChild(li); }); } else { statusDiv.style.display = 'flex'; if (albumLinks && albumLinks.length === 0) { statusDiv.innerHTML = 'No se encontró ningún video aquí ni álbumes asociados.'; } else if (albumLinks && albumLinks.length > 0) { statusDiv.innerHTML = 'Usa "Explorar en fondo" para obtener los videos.'; } } } function showError(msg) { statusDiv.style.display = 'flex'; statusDiv.innerHTML = `${msg}`; } });