diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..915645d93f6d3ca7da5ad2a65c852dfbfffc9866 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +ImageNinja[[:space:]]HD/baa2d01c-243a-46ba-8e3e-26825045023b.txt filter=lfs diff=lfs merge=lfs -text +local-video-downloader[[:space:]]-[[:space:]]copia[[:space:]](2)[[:space:]]-[[:space:]]copia/host/bin/AtomicParsley.exe filter=lfs diff=lfs merge=lfs -text +local-video-downloader[[:space:]]-[[:space:]]copia[[:space:]](2)[[:space:]]-[[:space:]]copia/host/bin/ffmpeg.exe filter=lfs diff=lfs merge=lfs -text +local-video-downloader[[:space:]]-[[:space:]]copia[[:space:]](2)[[:space:]]-[[:space:]]copia/host/bin/ffprobe.exe filter=lfs diff=lfs merge=lfs -text +local-video-downloader[[:space:]]-[[:space:]]copia[[:space:]](2)[[:space:]]-[[:space:]]copia/host/bin/N_m3u8DL-RE.exe filter=lfs diff=lfs merge=lfs -text +local-video-downloader[[:space:]]-[[:space:]]copia[[:space:]](2)[[:space:]]-[[:space:]]copia/host/bin/yt-dlp.exe filter=lfs diff=lfs merge=lfs -text diff --git a/ImageNinja HD/_metadata/generated_indexed_rulesets/_ruleset1 b/ImageNinja HD/_metadata/generated_indexed_rulesets/_ruleset1 new file mode 100644 index 0000000000000000000000000000000000000000..0fdba2c8f1087a867cabe8ac1b754270ac3f2724 Binary files /dev/null and b/ImageNinja HD/_metadata/generated_indexed_rulesets/_ruleset1 differ diff --git a/ImageNinja HD/assets/icons/icon.svg b/ImageNinja HD/assets/icons/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..4b69297b48232d25ea3edf73f4eb8dc1e92ff60b --- /dev/null +++ b/ImageNinja HD/assets/icons/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/ImageNinja HD/baa2d01c-243a-46ba-8e3e-26825045023b.txt b/ImageNinja HD/baa2d01c-243a-46ba-8e3e-26825045023b.txt new file mode 100644 index 0000000000000000000000000000000000000000..618e526f1a4727bf1f99231173d8998bc9ec74e0 --- /dev/null +++ b/ImageNinja HD/baa2d01c-243a-46ba-8e3e-26825045023b.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35f993dd108bc169dca769c0d527f26c9f0dba70ae17566af81646811b237d83 +size 146940 diff --git a/ImageNinja HD/manifest.json b/ImageNinja HD/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..6e15044bafd0fb656efbed5220de637232d5585a --- /dev/null +++ b/ImageNinja HD/manifest.json @@ -0,0 +1,37 @@ +{ + "manifest_version": 3, + "name": "Descargador de Imágenes", + "version": "1.0", + "description": "Descarga todas las imágenes de la página web donde te encuentres.", + "icons": { + "128": "assets/icons/icon.svg" + }, + "permissions": [ + "activeTab", + "scripting", + "downloads", + "storage", + "declarativeNetRequest", + "declarativeNetRequestWithHostAccess" + ], + "background": { + "service_worker": "src/background/background.js" + }, + "host_permissions": [ + "" + ], + "declarative_net_request": { + "rule_resources": [ + { + "id": "ruleset_1", + "enabled": true, + "path": "rules.json" + } + ] + }, + "action": { + "default_popup": "src/popup/popup.html", + "default_title": "Descargar Imágenes", + "default_icon": "assets/icons/icon.svg" + } +} diff --git a/ImageNinja HD/rules.json b/ImageNinja HD/rules.json new file mode 100644 index 0000000000000000000000000000000000000000..746214a18a6637110041b5e2ff0300d3d2216489 --- /dev/null +++ b/ImageNinja HD/rules.json @@ -0,0 +1,36 @@ +[ + { + "id": 1, + "priority": 1, + "action": { + "type": "modifyHeaders", + "requestHeaders": [ + { + "header": "Referer", + "operation": "set", + "value": "https://www.poringa.net/" + }, + { + "header": "Origin", + "operation": "set", + "value": "https://www.poringa.net" + } + ], + "responseHeaders": [ + { + "header": "Cross-Origin-Resource-Policy", + "operation": "remove" + }, + { + "header": "Access-Control-Allow-Origin", + "operation": "set", + "value": "*" + } + ] + }, + "condition": { + "urlFilter": "poringa.net", + "resourceTypes": ["main_frame", "sub_frame", "stylesheet", "script", "image", "font", "object", "xmlhttprequest", "ping", "csp_report", "media", "websocket", "other"] + } + } +] diff --git a/ImageNinja HD/src/background/background.js b/ImageNinja HD/src/background/background.js new file mode 100644 index 0000000000000000000000000000000000000000..106f9ead2d8088a2c12a276129307f93376d7702 --- /dev/null +++ b/ImageNinja HD/src/background/background.js @@ -0,0 +1,178 @@ +const downloadMap = new Map(); +const activeSessions = new Map(); + +chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { + if (request.action === 'registerDownload') { + downloadMap.set(request.url, request.filename); + sendResponse({ success: true }); + return true; + } + + if (request.action === 'startBackgroundDownloads') { + startBackgroundQueue(request); + sendResponse({ success: true }); + return true; + } + + if (request.action === 'getDownloadProgress') { + const session = activeSessions.get(request.comicUrl); + if (session) { + sendResponse(session); + } else { + sendResponse({ downloading: false }); + } + return true; + } +}); + +chrome.downloads.onDeterminingFilename.addListener((item, suggest) => { + if (downloadMap.has(item.url)) { + suggest({ filename: downloadMap.get(item.url), conflictAction: 'uniquify' }); + } else { + suggest(); + } +}); + +function arrayBufferToBase64(buffer) { + let binary = ''; + const bytes = new Uint8Array(buffer); + const len = bytes.byteLength; + for (let i = 0; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} + +function getExtension(url) { + const cleanUrl = url.split(/[#?]/)[0]; + const parts = cleanUrl.split('.'); + if (parts.length > 1) { + const ext = parts.pop().toLowerCase(); + if (['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg', 'avif', 'bmp', 'tiff', 'tif', 'ico', 'heic', 'heif', 'jxl'].includes(ext)) { + return ext; + } + } + return 'jpg'; +} + +function getQualityFolder(width, height) { + const max = Math.max(width, height); + const min = Math.min(width, height); + if (min >= 2160 || max >= 3840) return '4K'; + if (min >= 1440 || max >= 2560) return '2K'; + if (min >= 1080 || max >= 1920) return '1080p'; + if (min >= 720 || max >= 1280) return '720p'; + return 'Normal'; +} + +async function startBackgroundQueue({ toDownload, baseSf, uniqueSf, is3Hentai, isForcePNG, separateQuality, renameSequential, comicUrl }) { + const finalComicUrl = comicUrl || (toDownload[0]?.src || toDownload[0] || 'default'); + const session = { + downloading: true, + completed: 0, + total: toDownload.length + }; + activeSessions.set(finalComicUrl, session); + + const total = toDownload.length; + let completed = 0; + + const limit = is3Hentai ? 3 : total; + let active = 0; + let i = 0; + + const broadcastProgress = () => { + chrome.runtime.sendMessage({ + action: 'downloadProgress', + comicUrl: finalComicUrl, + completed: completed, + total: total, + downloading: true + }).catch(() => { + // Ignore error when popup is closed + }); + session.completed = completed; + session.total = total; + }; + + const runNext = async () => { + if (i >= total) { + if (completed === total) { + activeSessions.delete(finalComicUrl); + chrome.runtime.sendMessage({ + action: 'downloadProgress', + comicUrl: finalComicUrl, + completed: completed, + total: total, + downloading: false + }).catch(() => {}); + } + return; + } + + const idx = i++; + const img = toDownload[idx]; + active++; + + try { + const url = img.src || img; + const width = img.width || 0; + const height = img.height || 0; + const ext = isForcePNG ? 'png' : getExtension(url); + + let sf = uniqueSf || baseSf || 'comics_completos'; + if (separateQuality && width > 0 && height > 0) { + const quality = getQualityFolder(width, height); + sf = `${sf}/${quality}`; + } + + let name = url.split('/').pop().split(/[#?]/)[0].slice(0, 50) || `img_${idx + 1}`; + if (renameSequential) { + const padLength = Math.max(2, String(total).length); + name = `pag_${String(idx + 1).padStart(padLength, '0')}`; + } + + const filename = `${sf}/${name}.${ext}`; + 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; + + if (requiresBlobFetch) { + try { + const resp = await fetch(url); + if (!resp.ok) throw new Error('Fetch failed'); + const blob = await resp.blob(); + + const buffer = await blob.arrayBuffer(); + const base64 = arrayBufferToBase64(buffer); + const dataUrl = `data:${blob.type};base64,${base64}`; + + await new Promise((resolve) => { + downloadMap.set(dataUrl, filename); + chrome.downloads.download({ url: dataUrl, filename: filename, saveAs: false }, () => resolve()); + }); + } catch (e) { + console.warn("Background fetch failed, falling back to direct download", e); + await new Promise((resolve) => { + downloadMap.set(url, filename); + chrome.downloads.download({ url: url, filename: filename, saveAs: false }, () => resolve()); + }); + } + } else { + await new Promise((resolve) => { + downloadMap.set(url, filename); + chrome.downloads.download({ url: url, filename: filename, saveAs: false }, () => resolve()); + }); + } + } catch (err) { + console.error("Background download error:", err); + } + + active--; + completed++; + broadcastProgress(); + runNext(); + }; + + for (let j = 0; j < Math.min(limit, total); j++) { + runNext(); + } +} diff --git a/ImageNinja HD/src/popup/modules/downloader.js b/ImageNinja HD/src/popup/modules/downloader.js new file mode 100644 index 0000000000000000000000000000000000000000..65b68921edfd0d92865cdc95fffec805c80ecac7 --- /dev/null +++ b/ImageNinja HD/src/popup/modules/downloader.js @@ -0,0 +1,110 @@ +import { DOM } from './state.js'; +import { getExtension } from './filters.js'; + +export function getQualityFolder(width, height) { + const max = Math.max(width, height); + const min = Math.min(width, height); + if (min >= 2160 || max >= 3840) return '4K'; + if (min >= 1440 || max >= 2560) return '2K'; + if (min >= 1080 || max >= 1920) return '1080p'; + if (min >= 720 || max >= 1280) return '720p'; + return 'Normal'; +} + +export function convertWebpToPng(blob) { + return new Promise((resolve, reject) => { + const img = new Image(); + const url = URL.createObjectURL(blob); + img.onload = () => { + URL.revokeObjectURL(url); + const canvas = document.createElement('canvas'); + canvas.width = img.naturalWidth; + canvas.height = img.naturalHeight; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + canvas.toBlob((pngBlob) => { + if (pngBlob) { + resolve(pngBlob); + } else { + reject(new Error('Canvas conversion to PNG failed')); + } + }, 'image/png'); + }; + img.onerror = (e) => { + URL.revokeObjectURL(url); + reject(e); + }; + img.src = url; + }); +} + +export async function getUniqueSubfolder(baseFolder) { + return baseFolder || 'comics_completos'; +} + +export async function downloadImage(img, idx = 0, totalItems = 1, uniqueSf = null) { + const url = img.src || img; // Fallback + const width = img.width || 0; + const height = img.height || 0; + + const isForcePNG = DOM.forcePNG && DOM.forcePNG.checked; + const ext = isForcePNG ? 'png' : (getExtension(url) === 'desconocido' ? 'jpg' : getExtension(url)); + + let sf = uniqueSf; + if (!sf) { + sf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || 'comics_completos'; + } + + if (DOM.separateQuality && DOM.separateQuality.checked && width > 0 && height > 0) { + const quality = getQualityFolder(width, height); + sf = `${sf}/${quality}`; + } + + let name = url.split('/').pop().split(/[#?]/)[0].slice(0, 50) || `img_${idx + 1}`; + + if (DOM.renameSequential && DOM.renameSequential.checked) { + const padLength = Math.max(2, String(totalItems).length); + name = `pag_${String(idx + 1).padStart(padLength, '0')}`; + } + + const filename = `${sf}/${name}.${ext}`; + + 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; + + if (requiresBlobFetch) { + return new Promise((resolve) => { + fetch(url) + .then(r => { if(!r.ok) throw new Error('Fetch failed'); return r.blob(); }) + .then(async (blob) => { + let finalBlob = blob; + if (isForcePNG && blob.type !== 'image/png') { + try { + finalBlob = await convertWebpToPng(blob); + } catch (e) { + console.warn("PNG conversion failed, falling back to original blob", e); + } + } + const reader = new FileReader(); + reader.onloadend = () => { + const dataUrl = reader.result; + chrome.runtime.sendMessage({ action: 'registerDownload', url: dataUrl, filename: filename }, () => { + chrome.downloads.download({ url: dataUrl, filename: filename, saveAs: false }, () => resolve()); + }); + }; + reader.readAsDataURL(finalBlob); + }) + .catch(e => { + console.warn("Blob fetch failed, falling back to direct download", e); + chrome.runtime.sendMessage({ action: 'registerDownload', url: url, filename: filename }, () => { + chrome.downloads.download({ url, filename: filename, saveAs: false }, () => resolve()); + }); + }); + }); + } + + return new Promise((resolve) => { + chrome.runtime.sendMessage({ action: 'registerDownload', url: url, filename: filename }, () => { + chrome.downloads.download({ url, filename: filename, saveAs: false }, () => resolve()); + }); + }); +} diff --git a/ImageNinja HD/src/popup/modules/filters.js b/ImageNinja HD/src/popup/modules/filters.js new file mode 100644 index 0000000000000000000000000000000000000000..887ece90c4eaa6cd1ec5ffc6e38b7f711225a75f --- /dev/null +++ b/ImageNinja HD/src/popup/modules/filters.js @@ -0,0 +1,82 @@ +import { state, DOM } from './state.js'; +import { render } from '../popup.js'; + +export function getExtension(url) { + let e = url.split('.').pop().split(/[#?]/)[0].toLowerCase(); + return ['jpg','jpeg','png','webp','gif','svg','avif','bmp','tiff','tif','ico','heic','heif','jxl'].includes(e) ? e : 'desconocido'; +} + +export function applyFilters() { + const w = parseInt(DOM.minWidth.value) || 0; + const h = parseInt(DOM.minHeight.value) || 0; + const text = DOM.filterUrl.value.toLowerCase(); + const ext = DOM.filterExt.value; + + state.filteredImages = state.allImages.filter(img => { + if (DOM.cleanBrokenToggle && DOM.cleanBrokenToggle.checked && img.isBroken) return false; + + // Exempt direct links, kemono thumbs, and actively searching HD images from size filtering initially + const isExempt = img.hdSearching || (!img.hdFound && (img.isDirectLink || img.isKemonoThumb)); + if (!isExempt && (img.width < w || img.height < h)) return false; + if (ext !== 'all' && getExtension(img.src) !== ext) return false; + if (text && !img.src.toLowerCase().includes(text)) return false; + return true; + }); + + if (DOM.smartComic && DOM.smartComic.checked && state.filteredImages.length > 0) { + const dirInfo = {}; + state.filteredImages.forEach(img => { + if (img.hdSearching || (!img.hdFound && (img.isDirectLink || img.isKemonoThumb))) return; + try { + const url = img.originalSrc || img.src; + if (!url.startsWith('http')) return; + const urlObj = new URL(url); + const pathStr = urlObj.pathname; + const dirPath = urlObj.origin + pathStr.substring(0, pathStr.lastIndexOf('/')); + + if (!dirInfo[dirPath]) dirInfo[dirPath] = 0; + if (img.width >= 300 && img.height >= 300) { + dirInfo[dirPath] += 2; + } else { + dirInfo[dirPath] += 1; + } + } catch(e) {} + }); + + let mainDir = ''; + let maxScore = 0; + for (const [dir, score] of Object.entries(dirInfo)) { + if (score > maxScore) { + maxScore = score; + mainDir = dir; + } + } + + state.filteredImages = state.filteredImages.filter(img => { + if (img.hdSearching || (!img.hdFound && (img.isDirectLink || img.isKemonoThumb))) return true; + + try { + const url = img.originalSrc || img.src; + const urlObj = new URL(url); + const pathStr = urlObj.pathname; + const dirPath = urlObj.origin + pathStr.substring(0, pathStr.lastIndexOf('/')); + + if (maxScore >= 4) { + return dirPath === mainDir && img.width >= 300 && img.height >= 300; + } else { + return img.width >= 300 && img.height >= 300; + } + } catch { + return true; + } + }); + } + + // Limpiar selección de lo que ya no es visible + const visibleSrcs = new Set(state.filteredImages.map(i => i.src)); + state.selectedImages.forEach(src => { + if (!visibleSrcs.has(src)) state.selectedImages.delete(src); + }); + + render(); +} diff --git a/ImageNinja HD/src/popup/modules/scrapers.js b/ImageNinja HD/src/popup/modules/scrapers.js new file mode 100644 index 0000000000000000000000000000000000000000..02c05276734837cee33184ba91c8ce40846e1fb0 --- /dev/null +++ b/ImageNinja HD/src/popup/modules/scrapers.js @@ -0,0 +1,881 @@ +export async function getImagesFromPageDOM() { + const isHentaiMode = window.location.hostname.includes('hentaimode.com'); + if (isHentaiMode) { + try { + if (typeof window.ts_reader !== 'undefined') { + let images = null; + if (window.ts_reader.sources && window.ts_reader.sources[0] && window.ts_reader.sources[0].images) { + images = window.ts_reader.sources[0].images; + } else if (window.ts_reader.params && window.ts_reader.params.sources && window.ts_reader.params.sources[0] && window.ts_reader.params.sources[0].images) { + images = window.ts_reader.params.sources[0].images; + } + + if (images && images.length > 0) { + return images.map(src => { + let finalSrc = src; + try { + finalSrc = new URL(finalSrc, window.location.href).href; + } catch (e) {} + return { + src: finalSrc, + width: 0, + height: 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }; + }); + } + } + + const isMangaDetailsPage = !window.location.pathname.includes('/leer/'); + + if (isMangaDetailsPage) { + const title = document.querySelector('h1, .post-title h1, .manga-title h1')?.textContent?.trim() || document.title; + const coverEl = document.querySelector('.summary_image img, .manga-cover img, .summary-image img, .manga-info img, img.cover'); + const cover = coverEl ? (coverEl.getAttribute('data-src') || coverEl.getAttribute('data-lazy-src') || coverEl.getAttribute('src') || '') : ''; + + const chapters = []; + const seenChapters = new Set(); + const chapterLinks = document.querySelectorAll('a[href*="/leer/"]'); + chapterLinks.forEach(a => { + let href = a.href; + if (href) { + try { + href = new URL(href, window.location.href).href; + } catch(e) {} + if (!seenChapters.has(href)) { + seenChapters.add(href); + chapters.push(href); + } + } + }); + + if (chapters.length > 0) { + chapters.reverse(); + const results = []; + const seenImages = new Set(); + + for (const url of chapters) { + try { + const resp = await fetch(url); + if (resp.ok) { + const html = await resp.text(); + + const match = html.match(/ts_reader\s*=\s*({[\s\S]*?});/); + if (match) { + try { + const data = JSON.parse(match[1]); + let images = null; + if (data.sources && data.sources[0] && data.sources[0].images) { + images = data.sources[0].images; + } else if (data.params && data.params.sources && data.params.sources[0] && data.params.sources[0].images) { + images = data.params.sources[0].images; + } + + if (images && images.length > 0) { + images.forEach(src => { + let finalSrc = src; + try { + finalSrc = new URL(finalSrc, url).href; + } catch (e) {} + if (finalSrc.startsWith('http') && !seenImages.has(finalSrc)) { + seenImages.add(finalSrc); + results.push({ + src: finalSrc, + width: 0, + height: 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + }); + continue; + } + } catch(e) {} + } + + const doc = new DOMParser().parseFromString(html, 'text/html'); + const selectors = [ + '.reading-content img', + '.wp-manga-chapter-img img', + '.wp-manga-chapter-img', + '.page-break img', + '.viewer-pages img', + '#viewer img', + '#viewer-container img', + '.chapter-images img', + '.reader-images img', + '#reader img', + '.reader img', + '#readerarea img' + ]; + + doc.querySelectorAll(selectors.join(', ')).forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src'); + if (src && !src.includes('readerarea.svg')) { + try { + src = new URL(src, url).href; + } catch(e) {} + if (src.startsWith('http') && !seenImages.has(src)) { + seenImages.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + } + } catch(err) {} + } + if (results.length > 0) { + return results; + } + } + } + + const results = []; + const seen = new Set(); + const selectors = [ + '.reading-content img', + '.wp-manga-chapter-img img', + '.wp-manga-chapter-img', + '.page-break img', + '.viewer-pages img', + '#viewer img', + '#viewer-container img', + '.chapter-images img', + '.reader-images img', + '#reader img', + '.reader img', + '#readerarea img' + ]; + + document.querySelectorAll(selectors.join(', ')).forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src'); + if (src && !src.includes('readerarea.svg')) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + + if (results.length < 3) { + try { + const resp = await fetch(window.location.href); + if (resp.ok) { + const html = await resp.text(); + const doc = new DOMParser().parseFromString(html, 'text/html'); + doc.querySelectorAll(selectors.join(', ')).forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src'); + if (src && !src.includes('readerarea.svg')) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + } + } catch(err) {} + } + + if (results.length === 0) { + document.querySelectorAll('img').forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('data-opt-src') || img.src; + if (src && !src.includes('readerarea.svg')) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !src.includes('logo') && !src.includes('banner') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + } + + if (results.length > 0) { + return results; + } + } catch (e) { + console.error("HentaiMode parser error:", e); + } + } + + const isLectorHentai = window.location.hostname.includes('lectorhentai.com'); + if (isLectorHentai) { + try { + if (typeof window.ts_reader !== 'undefined') { + let images = null; + if (window.ts_reader.sources && window.ts_reader.sources[0] && window.ts_reader.sources[0].images) { + images = window.ts_reader.sources[0].images; + } else if (window.ts_reader.params && window.ts_reader.params.sources && window.ts_reader.params.sources[0] && window.ts_reader.params.sources[0].images) { + images = window.ts_reader.params.sources[0].images; + } + + if (images && images.length > 0) { + return images.map(src => { + let finalSrc = src; + try { + finalSrc = new URL(finalSrc, window.location.href).href; + } catch (e) {} + return { + src: finalSrc, + width: 0, + height: 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }; + }); + } + } + + const isMangaDetailsPage = window.location.pathname.includes('/manga/') && + !window.location.pathname.includes('/capitulo') && + !window.location.pathname.includes('/chapter') && + !window.location.pathname.includes('/read/') && + !window.location.pathname.includes('/lector/'); + const hasReaderElement = document.querySelector('.reading-content, .wp-manga-chapter-img, .page-break, #viewer, .chapter-images, #readerarea'); + + if (isMangaDetailsPage && !hasReaderElement) { + const title = document.querySelector('h1, .post-title h1, .manga-title h1')?.textContent?.trim() || document.title; + const coverEl = document.querySelector('.summary_image img, .manga-cover img, .summary-image img, .manga-info img'); + const cover = coverEl ? (coverEl.getAttribute('data-src') || coverEl.getAttribute('data-lazy-src') || coverEl.getAttribute('src') || '') : ''; + + const chapters = []; + const seenChapters = new Set(); + const chapterLinks = document.querySelectorAll('.wp-manga-chapter a, .listing-chapters_wrap a, a[href*="/capitulo-"], a[href*="/chapter-"], a[href*="/read/"], a[href*="/lector/"]'); + chapterLinks.forEach(a => { + let href = a.href; + if (href) { + try { + href = new URL(href, window.location.href).href; + } catch(e) {} + if (!seenChapters.has(href)) { + seenChapters.add(href); + chapters.push(href); + } + } + }); + + if (chapters.length === 0) { + document.querySelectorAll('a').forEach(a => { + let href = a.href; + 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.'))) { + try { + href = new URL(href, window.location.href).href; + } catch(e) {} + if (!seenChapters.has(href)) { + seenChapters.add(href); + chapters.push(href); + } + } + }); + } + + if (chapters.length > 0) { + chapters.reverse(); + + const results = []; + const seenImages = new Set(); + const selectors = [ + '.reading-content img', + '.wp-manga-chapter-img img', + '.wp-manga-chapter-img', + '.page-break img', + '.viewer-pages img', + '#viewer img', + '.chapter-images img', + '#readerarea img' + ]; + + for (const url of chapters) { + try { + const resp = await fetch(url); + if (resp.ok) { + const html = await resp.text(); + + const match = html.match(/ts_reader\s*=\s*({[\s\S]*?});/); + if (match) { + try { + const data = JSON.parse(match[1]); + let images = null; + if (data.sources && data.sources[0] && data.sources[0].images) { + images = data.sources[0].images; + } else if (data.params && data.params.sources && data.params.sources[0] && data.params.sources[0].images) { + images = data.params.sources[0].images; + } + + if (images && images.length > 0) { + images.forEach(src => { + let finalSrc = src; + try { + finalSrc = new URL(finalSrc, url).href; + } catch (e) {} + if (finalSrc.startsWith('http') && !seenImages.has(finalSrc)) { + seenImages.add(finalSrc); + results.push({ + src: finalSrc, + width: 0, + height: 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + }); + continue; + } + } catch(e) {} + } + + const doc = new DOMParser().parseFromString(html, 'text/html'); + + doc.querySelectorAll(selectors.join(', ')).forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src'); + if (src && !src.includes('readerarea.svg')) { + try { + src = new URL(src, url).href; + } catch(e) {} + if (src.startsWith('http') && !seenImages.has(src)) { + seenImages.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + + if (results.length === 0) { + doc.querySelectorAll('img').forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('data-opt-src') || img.src; + if (src && !src.includes('readerarea.svg')) { + try { + src = new URL(src, url).href; + } catch(e) {} + if (src.startsWith('http') && !src.includes('logo') && !src.includes('banner') && !seenImages.has(src)) { + seenImages.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + } + } + } catch(err) {} + } + + if (results.length > 0) { + return results; + } + } + } + + const results = []; + const seen = new Set(); + const selectors = [ + '.reading-content img', + '.wp-manga-chapter-img img', + '.wp-manga-chapter-img', + '.page-break img', + '.viewer-pages img', + '#viewer img', + '.chapter-images img', + '#readerarea img' + ]; + + document.querySelectorAll(selectors.join(', ')).forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src'); + if (src) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + + if (results.length < 3) { + try { + const resp = await fetch(window.location.href); + if (resp.ok) { + const html = await resp.text(); + const doc = new DOMParser().parseFromString(html, 'text/html'); + doc.querySelectorAll(selectors.join(', ')).forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('src'); + if (src) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + } + } catch(err) {} + } + + if (results.length === 0) { + document.querySelectorAll('img').forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-original') || img.getAttribute('data-opt-src') || img.src; + if (src) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !src.includes('logo') && !src.includes('banner') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + } + + if (results.length > 0) { + return results; + } + } catch (e) { + console.error("LectorHentai parser error:", e); + } + } + + const isVerComicsPorno = window.location.hostname.includes('vercomicsporno.com'); + if (isVerComicsPorno) { + try { + const results = []; + const seen = new Set(); + document.querySelectorAll('.wp-content img, .posts img').forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('src'); + if (src) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if ( + src.startsWith('http') && + src.includes('/wp-content/uploads/') && + !src.includes('avatar.jpg') && + !src.includes('/avatar') && + !src.match(/-\d+x\d+\.(jpg|jpeg|png|webp|gif)$/i) && + !seen.has(src) + ) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + if (results.length > 0) { + return results; + } + } catch (e) { + console.error("vercomicsporno parser error:", e); + } + } + + const isSexkomix = window.location.hostname.includes('sexkomix'); + if (isSexkomix) { + try { + const results = []; + const seen = new Set(); + document.querySelectorAll('ul#comix_pages_ul > li img').forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('src'); + if (src) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + if (src.startsWith('http') && !seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + isDirectLink: true + }); + } + } + }); + if (results.length > 0) { + return results; + } + } catch (e) { + console.error("sexkomix parser error:", e); + } + } + + const isNHentai = window.location.hostname.includes('nhentai.xxx') || window.location.hostname.includes('nhentai.net') || window.location.hostname.includes('nhentai.to'); + if (isNHentai) { + try { + const g_th = window.g_th; + if (g_th) { + const g_th_fl = g_th.fl || g_th; + let baseUrl = ''; + const mediaServer = window.media_server; + const imageDir = document.getElementById('image_dir')?.value; + const galleryId = document.getElementById('gallery_id')?.value; + if (mediaServer && imageDir && galleryId) { + baseUrl = `https://${mediaServer}/${imageDir}/${galleryId}`; + } + if (!baseUrl) { + const mainImg = document.querySelector('.fw_img img'); + const mainSrc = mainImg ? (mainImg.getAttribute('data-src') || mainImg.getAttribute('src')) : null; + if (mainSrc && mainSrc.startsWith('http')) { + const lastSlash = mainSrc.lastIndexOf('/'); + baseUrl = mainSrc.substring(0, lastSlash); + } + } + if (!baseUrl) { + const thumbImg = document.querySelector('.gallery_thumbs img, .gt_th img, #thumbs_append img'); + const thumbSrc = thumbImg ? (thumbImg.getAttribute('data-src') || thumbImg.getAttribute('src')) : null; + if (thumbSrc && thumbSrc.startsWith('http')) { + const lastSlash = thumbSrc.lastIndexOf('/'); + baseUrl = thumbSrc.substring(0, lastSlash); + } + } + if (baseUrl) { + const totalPages = Object.keys(g_th_fl).length; + const results = []; + for (let i = 1; i <= totalPages; i++) { + const pageData = g_th_fl[String(i)]; + if (pageData) { + const parts = pageData.split(','); + const code = parts[0]; + const w = parseInt(parts[1]) || 0; + const h = parseInt(parts[2]) || 0; + let ext = 'jpg'; + if (code === 'w') ext = 'webp'; + else if (code === 'p') ext = 'png'; + else if (code === 'j') ext = 'jpg'; + + const src = `${baseUrl}/${i}.${ext}`; + results.push({ + src: src, + width: w, + height: h, + inLink: false, + linkHref: null, + isKemonoThumb: false + }); + } + } + if (results.length > 0) { + return results; + } + } + } + } catch (e) { + console.error("nhentai parser error:", e); + } + } + + const is3Hentai = window.location.hostname.includes('3hentai.net'); + if (is3Hentai) { + try { + const results = []; + const seen = new Set(); + + const readerPages = window.readerPages; + if (readerPages && readerPages.pages && readerPages.baseUriImg) { + const baseUriImg = readerPages.baseUriImg; + const totalPages = readerPages.lastPage || Object.keys(readerPages.pages).length; + + for (let i = 1; i <= totalPages; i++) { + const pageData = readerPages.pages[String(i)]; + if (pageData && pageData.f) { + const src = baseUriImg.replace('%s', pageData.f); + if (!seen.has(src)) { + seen.add(src); + results.push({ + src: src, + width: pageData.w || 0, + height: pageData.h || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false + }); + } + } + } + } + + if (results.length === 0) { + const thumbs = document.querySelectorAll('#thumbnail-gallery img, .single-thumb img, .single-thumb-col img'); + thumbs.forEach(img => { + let src = img.getAttribute('data-src') || img.getAttribute('src'); + if (src) { + try { + if (!src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + + const match = src.match(/^(.*\/)(\d+)t\.(jpg|png|webp|jpeg|gif)$/i); + if (match) { + const base = match[1]; + const pageNum = match[2]; + const ext = match[3]; + const fullSrc = `${base}${pageNum}.${ext}`; + + if (!seen.has(fullSrc)) { + seen.add(fullSrc); + results.push({ + src: fullSrc, + width: img.naturalWidth || img.width || 0, + height: img.naturalHeight || img.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false + }); + } + } + } + }); + } + + if (results.length > 0) { + return results; + } + } catch (e) { + console.error("3hentai parser error:", e); + } + } + + const isHentaiera = window.location.hostname.includes('hentaiera.com') && window.location.pathname.includes('/view/'); + if (isHentaiera) { + try { + const pagesInput = document.getElementById('pages'); + const gimg = document.getElementById('gimg'); + const g_th = window.g_th; + if (pagesInput && gimg && g_th) { + const totalPages = parseInt(pagesInput.value) || 0; + const firstImgSrc = gimg.src || gimg.getAttribute('data-src'); + if (firstImgSrc && totalPages > 0) { + const lastSlashIdx = firstImgSrc.lastIndexOf('/'); + const baseUrl = firstImgSrc.substring(0, lastSlashIdx); + const results = []; + for (let i = 1; i <= totalPages; i++) { + const pageData = g_th[String(i)]; + if (pageData) { + const parts = pageData.split(','); + const code = parts[0]; + const w = parseInt(parts[1]) || 0; + const h = parseInt(parts[2]) || 0; + let ext = 'jpg'; + if (code === 'w') ext = 'webp'; + else if (code === 'p') ext = 'png'; + else if (code === 'j') ext = 'jpg'; + + const src = `${baseUrl}/${i}.${ext}`; + results.push({ + src: src, + width: w, + height: h, + inLink: false, + linkHref: null, + isKemonoThumb: false + }); + } + } + if (results.length > 0) { + return results; + } + } + } + } catch (e) { + console.error("Hentaiera parser error:", e); + } + } + + const isHitomi = window.location.hostname.includes('hitomi.la'); + if (isHitomi) { + try { + const match = window.location.href.match(/([0-9]+)\.html/); + if (match) { + const galleryId = match[1]; + + const loadScript = (src) => { + return new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.src = src; + script.onload = resolve; + script.onerror = () => reject(new Error(`Failed to load ${src}`)); + (document.head || document.documentElement).appendChild(script); + }); + }; + + if (typeof window.galleryinfo === 'undefined' || !window.galleryinfo || !window.galleryinfo.files) { + await loadScript(`https://ltn.hitomi.la/galleries/${galleryId}.js`); + } + if (typeof window.url_from_url_from_hash === 'undefined') { + await loadScript('https://ltn.hitomi.la/common.js'); + } + if (typeof window.gg === 'undefined' || !window.gg || !window.gg.m || !window.gg.s || !window.gg.b) { + await loadScript('https://ltn.hitomi.la/gg.js'); + } + + if (window.galleryinfo && window.galleryinfo.files) { + const results = []; + window.galleryinfo.files.forEach((file) => { + let src = ''; + try { + src = window.url_from_url_from_hash(galleryId, file, 'webp', undefined, undefined); + } catch (e) { + console.error("url_from_url_from_hash failed", e); + } + if (src) { + results.push({ + src: src, + width: file.width || 0, + height: file.height || 0, + inLink: false, + linkHref: null, + isKemonoThumb: false + }); + } + }); + if (results.length > 0) { + return results; + } + } + } + } catch (e) { + console.error("Hitomi parser error:", e); + } + } + + const results = []; + document.querySelectorAll('img').forEach(img => { + let p = img.parentElement, inLink = false, linkHref = null; + while(p && p.tagName !== 'BODY') { + if (p.tagName === 'A') { inLink = true; linkHref = p.href; break; } + p = p.parentElement; + } + let src = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || img.getAttribute('data-opt-src') || img.src; + + try { + if (src && !src.startsWith('data:') && !src.startsWith('blob:')) { + src = new URL(src, window.location.href).href; + } + } catch(e) {} + + if (src?.startsWith('http')) { + const isKemonoThumb = src.includes('kemono.') && src.includes('/thumbnail/data/'); + results.push({ src, width: img.naturalWidth || 0, height: img.naturalHeight || 0, inLink, linkHref, isKemonoThumb }); + } + }); + + document.querySelectorAll('.post__files a, .post__file a, .fileThumb, a[href*="kemono."]').forEach(a => { + if (a.href.match(/\.(jpg|jpeg|png|webp|gif|svg|avif|bmp|tiff|tif|ico|heic|heif|jxl)$/i)) { + results.push({ src: a.href, width: 0, height: 0, inLink: true, linkHref: a.href, isDirectLink: true }); + } + }); + return results; +} diff --git a/ImageNinja HD/src/popup/modules/settings.js b/ImageNinja HD/src/popup/modules/settings.js new file mode 100644 index 0000000000000000000000000000000000000000..0f8b99595fb823e98e5535321c39c08e1eaebb3d --- /dev/null +++ b/ImageNinja HD/src/popup/modules/settings.js @@ -0,0 +1,55 @@ +import { DOM } from './state.js'; + +export function saveSettings() { + if (typeof chrome === 'undefined' || !chrome.storage) return; + const settings = { + filterUrl: DOM.filterUrl.value, + filterExt: DOM.filterExt.value, + minWidth: DOM.minWidth.value, + minHeight: DOM.minHeight.value, + forceHD: DOM.forceHD.checked, + separateQuality: DOM.separateQuality.checked, + renameSequential: DOM.renameSequential.checked, + smartComic: DOM.smartComic.checked, + forcePNG: DOM.forcePNG.checked, + subfolder: DOM.subfolderInput.value, + selectAll: DOM.selectAll.checked, + cleanBroken: DOM.cleanBrokenToggle ? DOM.cleanBrokenToggle.checked : false, + filtersCollapsed: DOM.collapsibleFilters ? DOM.collapsibleFilters.classList.contains('collapsed') : false + }; + chrome.storage.local.set({ extensionSettings: settings }); +} + +export async function loadSettings() { + return new Promise((resolve) => { + if (typeof chrome === 'undefined' || !chrome.storage) return resolve(); + chrome.storage.local.get(['extensionSettings'], (res) => { + const s = res.extensionSettings; + if (s) { + DOM.filterUrl.value = s.filterUrl || ''; + DOM.filterExt.value = s.filterExt || 'all'; + DOM.minWidth.value = s.minWidth ?? 0; + DOM.minWidthVal.value = s.minWidth ?? 0; + DOM.minHeight.value = s.minHeight ?? 0; + DOM.minHeightVal.value = s.minHeight ?? 0; + DOM.forceHD.checked = !!s.forceHD; + DOM.separateQuality.checked = !!s.separateQuality; + DOM.renameSequential.checked = s.renameSequential !== false; // Activo por defecto + DOM.smartComic.checked = s.smartComic !== false; + DOM.forcePNG.checked = !!s.forcePNG; + DOM.subfolderInput.value = s.subfolder || ''; + DOM.selectAll.checked = !!s.selectAll; + if (DOM.cleanBrokenToggle) { + DOM.cleanBrokenToggle.checked = !!s.cleanBroken; + } + if (DOM.collapsibleFilters && s.filtersCollapsed) { + DOM.collapsibleFilters.classList.add('collapsed'); + if (DOM.toggleFiltersBtn) { + DOM.toggleFiltersBtn.classList.add('collapsed'); + } + } + } + resolve(); + }); + }); +} diff --git a/ImageNinja HD/src/popup/modules/state.js b/ImageNinja HD/src/popup/modules/state.js new file mode 100644 index 0000000000000000000000000000000000000000..cebad01ac480147a5f03cf653a570e9f781165c9 --- /dev/null +++ b/ImageNinja HD/src/popup/modules/state.js @@ -0,0 +1,51 @@ +// --- ESTADO GLOBAL --- +export const state = { + allImages: [], + filteredImages: [], + selectedImages: new Set(), + lastSelectedIdx: -1, + isHDSearching: false, + downloadMap: new Map(), + isDragging: false, + dragMode: true, + dragStartIdx: -1, + dragSavedSelection: new Set() +}; + +// --- ELEMENTOS DEL DOM --- +export const DOM = { + grid: document.getElementById('imageGrid'), + filterUrl: document.getElementById('filterUrl'), + filterExt: document.getElementById('filterExt'), + minWidth: document.getElementById('minWidth'), + minWidthVal: document.getElementById('minWidthVal'), + minHeight: document.getElementById('minHeight'), + minHeightVal: document.getElementById('minHeightVal'), + forceHD: document.getElementById('forceHD'), + separateQuality: document.getElementById('separateQuality'), + renameSequential: document.getElementById('renameSequential'), + smartComic: document.getElementById('smartComic'), + forcePNG: document.getElementById('forcePNG'), + selectAll: document.getElementById('selectAll'), + selectedCount: document.getElementById('selectedCount'), + totalCount: document.getElementById('totalCount'), + downloadBtn: document.getElementById('downloadBtn'), + btnCounter: document.getElementById('btnCounter'), + fullscreenBtn: document.getElementById('fullscreenBtn'), + subfolderInput: document.getElementById('subfolder'), + cleanBrokenToggle: document.getElementById('cleanBrokenToggle'), + // Búsqueda Secuencial + toggleSeqBtn: document.getElementById('toggleSeqBtn'), + seqPanel: document.getElementById('seqPanel'), + seqUrlPattern: document.getElementById('seqUrlPattern'), + seqStart: document.getElementById('seqStart'), + seqEnd: document.getElementById('seqEnd'), + seqSelector: document.getElementById('seqSelector'), + seqStartBtn: document.getElementById('seqStartBtn'), + seqProgress: document.getElementById('seqProgress'), + seqProgressText: document.getElementById('seqProgressText'), + seqProgressStatus: document.getElementById('seqProgressStatus'), + seqProgressBar: document.getElementById('seqProgressBar'), + collapsibleFilters: document.getElementById('collapsibleFilters'), + toggleFiltersBtn: document.getElementById('toggleFiltersBtn') +}; diff --git a/ImageNinja HD/src/popup/popup.css b/ImageNinja HD/src/popup/popup.css new file mode 100644 index 0000000000000000000000000000000000000000..50db6517432f8b540e67559332c80c0f9eba0cce --- /dev/null +++ b/ImageNinja HD/src/popup/popup.css @@ -0,0 +1,634 @@ +:root { + --bg-color: #0b0c10; + --surface-color: #12141a; + --border-color: #272a33; + --text-color: #c9d1d9; + --text-muted: #8b949e; + --accent-color: #e11d48; /* Rojo Carmesí */ + --accent-hover: #be123c; /* Rojo Oscuro */ + --danger-color: #f85149; + } + + body { + min-width: 800px; + min-height: 560px; + width: 100vw; + height: 100vh; + margin: 0; + /* removed fixed sizes */ + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; + background-color: var(--bg-color); + color: var(--text-color); + display: flex; + flex-direction: column; + overflow: hidden; + } + + ::-webkit-scrollbar { width: 8px; height: 8px; } + ::-webkit-scrollbar-track { background: var(--bg-color); } + ::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 4px; } + ::-webkit-scrollbar-thumb:hover { background: #555; } + + .header-panel { + padding: 10px 14px; + background: linear-gradient(180deg, var(--surface-color) 0%, var(--bg-color) 100%); + border-bottom: 1px solid var(--border-color); + display: flex; + flex-direction: column; + gap: 10px; + flex-shrink: 0; + } + + .header-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 14px; + } + + .group-title { + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.5px; + color: var(--text-muted); + font-weight: 600; + margin-bottom: 4px; + display: flex; + align-items: center; + gap: 4px; + } + + .info-icon { + background: rgba(255,255,255,0.1); + color: #fff; + border-radius: 50%; + width: 12px; + height: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 9px; + font-family: monospace; + font-weight: bold; + cursor: help; + } + + input[type="text"], input[type="number"], select { + background-color: rgba(255, 255, 255, 0.02); + color: var(--text-color); + border: 1px solid var(--border-color); + border-radius: 6px; + padding: 6px 8px; + font-size: 12px; + outline: none; + transition: all 0.2s; + } + + input[type="text"]:focus, input[type="number"]:focus, select:focus { + border-color: var(--accent-color); + background-color: rgba(225, 29, 72, 0.05); /* Rojo transparente */ + } + + /* Solucionar el menú desplegable blanco en Windows */ + select option { + background-color: var(--surface-color); + color: var(--text-color); + } + + .flex-row { display: flex; gap: 6px; width: 100%; align-items: center; } + .flex-row input[type="text"] { flex-grow: 1; } + .flex-row select { width: 110px; } + + .sliders-container { + display: flex; + gap: 8px; + } + + .slider-box { + flex: 1; + display: flex; + align-items: center; + gap: 6px; + background: rgba(255,255,255,0.02); + padding: 4px 8px; + border-radius: 6px; + border: 1px solid var(--border-color); + } + + .slider-box span { font-size: 11px; color: var(--text-muted); font-weight: 500; } + .slider-box input[type="range"] { flex-grow: 1; height: 3px; accent-color: var(--accent-color); } + .slider-box input[type="number"] { width: 40px; padding: 2px; text-align: center; border: none; background: rgba(0,0,0,0.2); } + + .options-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + } + + .custom-checkbox { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 6px 8px; + background: rgba(255,255,255,0.02); + border: 1px solid var(--border-color); + border-radius: 6px; + cursor: pointer; + transition: all 0.2s; + } + + .custom-checkbox:hover { + background: rgba(255,255,255,0.05); + border-color: #444c56; + } + + .custom-checkbox input[type="checkbox"] { + margin-top: 2px; + accent-color: var(--accent-color); + width: 13px; + height: 13px; + cursor: pointer; + } + + .checkbox-text { + display: flex; + flex-direction: column; + gap: 1px; + } + + .checkbox-text b { font-size: 11.5px; font-weight: 500; color: #fff; } + .checkbox-text small { font-size: 9.5px; color: var(--text-muted); line-height: 1.2; } + + .select-bar { + margin-top: 0px; + padding-top: 8px; + border-top: 1px dashed var(--border-color); + display: flex; + align-items: center; + justify-content: space-between; + } + + .select-all-label { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + font-weight: 500; + cursor: pointer; + } + + .select-all-label input { + accent-color: var(--accent-color); + width: 16px; + height: 16px; + cursor: pointer; + } + + /* GRID DE IMÁGENES */ + .grid-container { + flex-grow: 1; + overflow-y: auto; + padding: 14px; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); + grid-auto-rows: max-content; + align-content: start; + gap: 16px; + background-color: var(--bg-color); + } + + .image-card { + position: relative; + background-color: var(--surface-color); + border: 1px solid var(--border-color); + border-radius: 8px; + overflow: hidden; + display: flex; + flex-direction: column; + transition: all 0.2s; + } + + .image-card.selected { + border-color: var(--accent-color); + box-shadow: 0 0 0 2px rgba(225, 29, 72, 0.3); /* Resplandor rojo */ + } + + .image-wrapper { + position: relative; + width: 100%; + aspect-ratio: 1 / 1.4; + background-color: rgba(0,0,0,0.5); + display: flex; + align-items: center; + justify-content: center; + } + + .image-wrapper img { + max-width: 100%; + max-height: 100%; + object-fit: contain; + } + + .card-checkbox { + position: absolute; + top: 8px; + left: 8px; + width: 20px; + height: 20px; + accent-color: var(--accent-color); + cursor: pointer; + z-index: 10; + background: rgba(0,0,0,0.6); + border-radius: 4px; + box-shadow: 0 2px 4px rgba(0,0,0,0.3); + } + + .card-actions { + position: absolute; + top: 8px; + right: 8px; + display: flex; + gap: 6px; + background: rgba(0, 0, 0, 0.7); + padding: 4px; + border-radius: 6px; + z-index: 10; + backdrop-filter: blur(4px); + } + + .icon-btn { + background: none; + border: none; + color: #fff; + cursor: pointer; + padding: 5px; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + transition: background 0.2s; + } + + .icon-btn:hover { background-color: rgba(255,255,255,0.2); } + .icon-btn svg { + width: 16px; + height: 16px; + fill: none; + stroke: currentColor; + stroke-width: 2; + stroke-linecap: round; + stroke-linejoin: round; + } + + .card-info { + padding: 8px; + font-size: 11px; + color: var(--text-color); + display: flex; + flex-direction: column; + gap: 6px; + background: var(--surface-color); + } + + .url-bar { + background: rgba(0,0,0,0.7); + padding: 5px; + position: absolute; + bottom: 0; + left: 0; + right: 0; + font-size: 10px; + color: #ddd; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + backdrop-filter: blur(2px); + } + + .footer { + padding: 14px 16px; + background-color: var(--surface-color); + border-top: 1px solid var(--border-color); + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + flex-shrink: 0; + } + + .footer-inputs { + display: flex; + gap: 5px; + flex-grow: 1; + } + + .btn-download { + background-color: var(--accent-color); + color: #fff; /* Que se lea bien sobre el rojo */ + border: none; + border-radius: 6px; + padding: 10px 16px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; + white-space: nowrap; + transition: all 0.2s; + box-shadow: 0 4px 14px 0 rgba(225, 29, 72, 0.2); /* Sombra roja */ + } + + .btn-download:hover { + background-color: var(--accent-hover); + transform: translateY(-1px); + } + .btn-download:disabled { + background-color: #30363d; + color: #8b949e; + cursor: not-allowed; + box-shadow: none; + transform: none; + } + + .btn-clean { + background-color: rgba(255, 255, 255, 0.05); + border: 1px solid var(--border-color); + color: var(--text-muted); + border-radius: 4px; + padding: 4px 8px; + font-size: 11px; + cursor: pointer; + display: flex; + align-items: center; + gap: 4px; + transition: all 0.2s; + } + .btn-clean:hover { + background-color: rgba(225, 29, 72, 0.1); + border-color: var(--accent-color); + color: #fff; + } + + .loader { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100%; + color: var(--text-muted); + grid-column: span 4; + } + + /* PANEL BÚSQUEDA SECUENCIAL */ + .sequential-search-panel { + margin-top: 5px; + padding: 0 4px; + animation: slideDown 0.2s ease-out; + } + + .seq-grid { + display: flex; + flex-direction: column; + gap: 8px; + background: rgba(255, 255, 255, 0.02); + border: 1px solid var(--border-color); + padding: 10px; + border-radius: 8px; + } + + .seq-row-url { + display: flex; + width: 100%; + } + + .seq-row-inputs { + display: flex; + gap: 8px; + align-items: center; + flex-wrap: wrap; + } + + .seq-input-box { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + color: var(--text-muted); + } + + .seq-input-box span { + white-space: nowrap; + } + + .progress-bar-bg { + background: rgba(255, 255, 255, 0.08); + height: 6px; + border-radius: 3px; + overflow: hidden; + margin-top: 4px; + border: 1px solid rgba(255,255,255,0.02); + } + + .progress-bar-fill { + background: linear-gradient(90deg, var(--accent-color) 0%, #ff527b 100%); + height: 100%; + width: 0%; + transition: width 0.25s ease-out; + box-shadow: 0 0 8px var(--accent-color); + } + + @keyframes slideDown { + from { opacity: 0; transform: translateY(-8px); } + to { opacity: 1; transform: translateY(0); } + } + + /* FILTROS COLAPSABLES */ + .collapsible-filters { + max-height: 500px; + opacity: 1; + overflow: hidden; + transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), + opacity 0.2s ease-in-out, + padding-bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1); + } + + .collapsible-filters.collapsed { + max-height: 0; + opacity: 0; + pointer-events: none; + } + + #toggleFiltersBtn svg { + transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); + } + + #toggleFiltersBtn.collapsed svg { + transform: rotate(180deg); + } + + /* MANGA DETAILS VIEW DESIGN */ + .manga-details-container { + display: flex; + flex-direction: column; + gap: 16px; + padding: 20px; + background: rgba(18, 20, 26, 0.6); + backdrop-filter: blur(10px); + border-radius: 12px; + border: 1px solid var(--border-color); + max-width: 740px; + margin: 10px auto; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + animation: slideDown 0.3s ease-out; + } + + .manga-details-header { + display: flex; + gap: 20px; + align-items: flex-start; + border-bottom: 1px solid var(--border-color); + padding-bottom: 16px; + } + + .manga-details-cover { + width: 90px; + height: 120px; + object-fit: cover; + border-radius: 8px; + border: 1px solid var(--border-color); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5); + background-color: var(--bg-color); + } + + .manga-details-info { + display: flex; + flex-direction: column; + gap: 6px; + justify-content: center; + } + + .manga-details-title { + font-size: 18px; + font-weight: 700; + color: #ffffff; + margin: 0; + line-height: 1.3; + } + + .manga-details-meta { + font-size: 13px; + color: var(--text-muted); + margin: 0; + } + + .manga-details-meta b { + color: var(--text-color); + } + + .badge-madara { + align-self: flex-start; + background: rgba(225, 29, 72, 0.15); + color: var(--accent-color); + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + padding: 3px 8px; + border-radius: 4px; + border: 1px solid rgba(225, 29, 72, 0.3); + margin-top: 4px; + } + + .manga-chapters-title { + font-size: 13px; + font-weight: 600; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.5px; + margin-bottom: 4px; + } + + .manga-chapters-list { + display: flex; + flex-direction: column; + gap: 8px; + max-height: 280px; + overflow-y: auto; + padding-right: 4px; + } + + .manga-chapter-item { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 14px; + background: rgba(255, 255, 255, 0.02); + border: 1px solid var(--border-color); + border-radius: 8px; + transition: all 0.2s ease; + } + + .manga-chapter-item:hover { + background: rgba(255, 255, 255, 0.04); + border-color: rgba(255, 255, 255, 0.1); + } + + .chapter-name { + font-size: 13px; + font-weight: 500; + color: var(--text-color); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 320px; + } + + .chapter-actions { + display: flex; + gap: 8px; + align-items: center; + } + + .btn-chapter-download { + background: var(--accent-color); + color: white; + border: none; + border-radius: 6px; + padding: 6px 12px; + font-size: 11px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s ease; + } + + .btn-chapter-download:hover { + background: var(--accent-hover); + box-shadow: 0 0 10px rgba(225, 29, 72, 0.4); + } + + .btn-chapter-download:disabled { + background: var(--border-color); + color: var(--text-muted); + cursor: not-allowed; + box-shadow: none; + } + + .chapter-download-progress { + display: flex; + align-items: center; + gap: 10px; + min-width: 160px; + } + + .chapter-download-progress .progress-bar-bg { + flex-grow: 1; + height: 4px; + margin-top: 0; + } + + .chapter-download-progress .progress-text { + font-size: 10px; + color: var(--text-muted); + white-space: nowrap; + min-width: 65px; + text-align: right; + } \ No newline at end of file diff --git a/ImageNinja HD/src/popup/popup.html b/ImageNinja HD/src/popup/popup.html new file mode 100644 index 0000000000000000000000000000000000000000..6674f2855f86cdc50f7a537a843b23873977da39 --- /dev/null +++ b/ImageNinja HD/src/popup/popup.html @@ -0,0 +1,197 @@ + + + + + + + + +
+ +
+
+ +
+
+ Filtros de Contenido + ? +
+
+ + +
+
+ + +
+
+ Tamaño Mínimo Requerido + ? +
+
+
+ Ancho + + +
+
+ Alto + + +
+
+
+
+ + +
+
+ + + + + + + + + +
+
+ + + +
+ + +
+ +
+ + + + + Imágenes listas para guardar + +
+
+ +
+ +
+
+

Analizando página...

+

Buscando imágenes disponibles

+
+
+ + + + + + diff --git a/ImageNinja HD/src/popup/popup.js b/ImageNinja HD/src/popup/popup.js new file mode 100644 index 0000000000000000000000000000000000000000..77605f5b4b81d4755287e81465f830aa8017f63c --- /dev/null +++ b/ImageNinja HD/src/popup/popup.js @@ -0,0 +1,813 @@ +import { state, DOM } from './modules/state.js'; +import { loadSettings, saveSettings } from './modules/settings.js'; +import { applyFilters, getExtension } from './modules/filters.js'; +import { getImagesFromPageDOM } from './modules/scrapers.js'; +import { downloadImage, getUniqueSubfolder } from './modules/downloader.js'; + +// --- INICIALIZACIÓN --- +document.addEventListener('DOMContentLoaded', async () => { + await loadSettings(); + initListeners(); + + const params = new URLSearchParams(window.location.search); + const targetTabId = params.get('tabId'); + let tab; + + if (targetTabId) { + try { + tab = await chrome.tabs.get(parseInt(targetTabId)); + DOM.fullscreenBtn.title = 'Minimizar a Ventana Flotante'; + DOM.fullscreenBtn.innerHTML = ''; + DOM.fullscreenBtn.onclick = () => window.close(); + } catch(e) { + console.error("No se pudo obtener el tab original", e); + } + } else { + const tabs = await chrome.tabs.query({ active: true, currentWindow: true }); + tab = tabs[0]; + } + + if (!tab) return; + window.currentContextTabId = tab.id; + window.currentContextTabUrl = tab.url; + window.currentContextTabTitle = tab.title; + + if (tab.url) { + let suggestedPattern = tab.url; + let suggestedStart = 1; + let suggestedEnd = 10; + + if (tab.url.includes('hentaiera.com/view/')) { + suggestedPattern = tab.url.replace(/\/view\/(\d+)\/(\d+)\/?/, '/view/$1/{page}/'); + suggestedStart = 1; + try { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + world: 'MAIN', + function: () => document.getElementById('pages')?.value || '15' + }, (res) => { + if (res?.[0]?.result) { + const pagesVal = parseInt(res[0].result); + if (pagesVal && DOM.seqEnd) DOM.seqEnd.value = pagesVal; + } + }); + } catch (e) {} + } else { + const numRegex = /(\/|-|_|=)(\d+)(\/|\.html|\.htm|$|\?|&)/i; + const match = tab.url.match(numRegex); + if (match) { + suggestedPattern = tab.url.replace(numRegex, `$1{page}$3`); + suggestedStart = 1; + suggestedEnd = Math.max(10, parseInt(match[2])); + } + } + + if (DOM.seqUrlPattern) { + DOM.seqUrlPattern.value = suggestedPattern; + DOM.seqStart.value = suggestedStart; + DOM.seqEnd.value = suggestedEnd; + } + } + + const isHitomi = tab.url && tab.url.includes('hitomi.la'); + const isHentaiera = tab.url && tab.url.includes('hentaiera.com') && tab.url.includes('/view/'); + const isNHentai = tab.url && (tab.url.includes('nhentai.xxx') || tab.url.includes('nhentai.net') || tab.url.includes('nhentai.to')); + const is3Hentai = tab.url && tab.url.includes('3hentai.net'); + const isVerComicsPorno = tab.url && tab.url.includes('vercomicsporno.com'); + const isLectorHentai = tab.url && tab.url.includes('lectorhentai.com'); + const isHentaiMode = tab.url && tab.url.includes('hentaimode.com'); + if (isHitomi || isHentaiera || isNHentai || is3Hentai || isVerComicsPorno || isLectorHentai || isHentaiMode) { + DOM.forceHD.checked = false; + DOM.forceHD.disabled = true; + } + + try { + if (chrome.declarativeNetRequest && tab.url) { + await chrome.declarativeNetRequest.updateDynamicRules({ + removeRuleIds: [999, 998, 997, 996, 995], + addRules: [ + { + id: 999, + priority: 2, + action: { + type: "modifyHeaders", + requestHeaders: [ + { header: "Referer", operation: "set", value: tab.url }, + { header: "Origin", operation: "set", value: new URL(tab.url).origin } + ], + responseHeaders: [ + { header: "Access-Control-Allow-Origin", operation: "set", value: "*" }, + { header: "Cross-Origin-Resource-Policy", operation: "remove" } + ] + }, + condition: { + urlFilter: new URL(tab.url).hostname.replace('www.', ''), + resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"] + } + }, + { + id: 998, + priority: 2, + action: { + type: "modifyHeaders", + requestHeaders: [ + { header: "Referer", operation: "set", value: "https://hitomi.la/" }, + { header: "Origin", operation: "set", value: "https://hitomi.la" } + ], + responseHeaders: [ + { header: "Access-Control-Allow-Origin", operation: "set", value: "*" }, + { header: "Cross-Origin-Resource-Policy", operation: "remove" } + ] + }, + condition: { + urlFilter: "gold-usergeneratedcontent.net", + resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"] + } + }, + { + id: 997, + priority: 2, + action: { + type: "modifyHeaders", + requestHeaders: [ + { header: "Referer", operation: "set", value: tab.url }, + { header: "Origin", operation: "set", value: new URL(tab.url).origin } + ], + responseHeaders: [ + { header: "Access-Control-Allow-Origin", operation: "set", value: "*" }, + { header: "Cross-Origin-Resource-Policy", operation: "remove" } + ] + }, + condition: { + urlFilter: "nhentaimg.com", + resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"] + } + }, + { + id: 996, + priority: 2, + action: { + type: "modifyHeaders", + requestHeaders: [ + { header: "Referer", operation: "set", value: tab.url.includes('3hentai.net') ? tab.url : "https://3hentai.net/" }, + { header: "Origin", operation: "set", value: tab.url.includes('3hentai.net') ? new URL(tab.url).origin : "https://3hentai.net" } + ], + responseHeaders: [ + { header: "Access-Control-Allow-Origin", operation: "set", value: "*" }, + { header: "Cross-Origin-Resource-Policy", operation: "remove" } + ] + }, + condition: { + urlFilter: "3hentai.xyz", + resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"] + } + }, + { + id: 995, + priority: 2, + action: { + type: "modifyHeaders", + requestHeaders: [ + { header: "Referer", operation: "set", value: "https://lectorhentai.com/" }, + { header: "Origin", operation: "set", value: "https://lectorhentai.com" } + ], + responseHeaders: [ + { header: "Access-Control-Allow-Origin", operation: "set", value: "*" }, + { header: "Cross-Origin-Resource-Policy", operation: "remove" } + ] + }, + condition: { + urlFilter: "giolandscaping.com", + resourceTypes: ["image", "xmlhttprequest", "other", "main_frame", "sub_frame"] + } + } + ] + }); + } + } catch (e) { + console.error("Dynamic DNR failed", e); + } + + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + world: (isHitomi || isHentaiera || isNHentai || is3Hentai || isLectorHentai || isHentaiMode) ? 'MAIN' : 'ISOLATED', + function: getImagesFromPageDOM, + }, (results) => { + if (chrome.runtime.lastError || !results?.[0]?.result) { + DOM.grid.innerHTML = '

Error al obtener imágenes.

'; + return; + } + + const res = results[0].result; + + const uniqueMap = new Map(); + res.forEach(img => { + if (!uniqueMap.has(img.src) && img.src.startsWith('http')) { + uniqueMap.set(img.src, img); + } + }); + + state.allImages = Array.from(uniqueMap.values()); + if (DOM.selectAll.checked) { + state.allImages.forEach(img => state.selectedImages.add(img.src)); + } + applyFilters(); + + if (DOM.forceHD.checked) { + updateHDUrls(); + } + }); + + // Check if background is currently downloading + if (window.currentContextTabUrl) { + chrome.runtime.sendMessage({ action: 'getDownloadProgress', comicUrl: window.currentContextTabUrl }, (resp) => { + if (resp && resp.downloading) { + showDownloadingState(resp.completed, resp.total); + } + }); + } +}); + +function initListeners() { + const handleSizeInput = (slider, valBox) => { + valBox.value = slider.value; + applyFilters(); + if (DOM.forceHD.checked) updateHDUrls(); + saveSettings(); + }; + + DOM.minWidth.addEventListener('input', () => handleSizeInput(DOM.minWidth, DOM.minWidthVal)); + DOM.minHeight.addEventListener('input', () => handleSizeInput(DOM.minHeight, DOM.minHeightVal)); + DOM.minWidthVal.addEventListener('input', () => { DOM.minWidth.value = DOM.minWidthVal.value; applyFilters(); saveSettings(); }); + DOM.minHeightVal.addEventListener('input', () => { DOM.minHeight.value = DOM.minHeightVal.value; applyFilters(); saveSettings(); }); + + DOM.minWidth.addEventListener('change', saveSettings); + DOM.minHeight.addEventListener('change', saveSettings); + + DOM.filterUrl.addEventListener('input', () => { applyFilters(); saveSettings(); }); + DOM.filterExt.addEventListener('change', () => { applyFilters(); saveSettings(); }); + DOM.forceHD.addEventListener('change', () => { updateHDUrls(); saveSettings(); }); + DOM.separateQuality.addEventListener('change', saveSettings); + DOM.renameSequential.addEventListener('change', saveSettings); + DOM.smartComic.addEventListener('change', () => { applyFilters(); saveSettings(); }); + DOM.forcePNG.addEventListener('change', saveSettings); + DOM.subfolderInput.addEventListener('input', saveSettings); + + DOM.selectAll.addEventListener('change', (e) => { + if (e.target.checked) { + state.filteredImages.forEach(img => state.selectedImages.add(img.src)); + } else { + state.selectedImages.clear(); + } + updateSelectionVisuals(); + saveSettings(); + }); + + DOM.downloadBtn.addEventListener('click', async () => { + const toDownload = state.filteredImages.filter(img => state.selectedImages.has(img.src)); + if (toDownload.length === 0) return; + + const baseSf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || (window.currentContextTabTitle ? window.currentContextTabTitle.replace(/[\\:*?"<>|]/g, "").trim().slice(0, 80) : 'comics_completos'); + const uniqueSf = await getUniqueSubfolder(baseSf); + + const is3Hentai = window.currentContextTabUrl && window.currentContextTabUrl.includes('3hentai.net'); + + if (is3Hentai) { + chrome.runtime.sendMessage({ + action: 'startBackgroundDownloads', + toDownload, + baseSf, + uniqueSf, + is3Hentai, + isForcePNG: DOM.forcePNG && DOM.forcePNG.checked, + separateQuality: DOM.separateQuality && DOM.separateQuality.checked, + renameSequential: DOM.renameSequential && DOM.renameSequential.checked, + comicUrl: window.currentContextTabUrl + }, () => { + showDownloadingState(0, toDownload.length); + }); + } else { + // Original parallel behavior + toDownload.forEach((img, idx) => downloadImage(img, idx, toDownload.length, uniqueSf)); + } + }); + + if (DOM.fullscreenBtn) { + DOM.fullscreenBtn.addEventListener('click', () => { + const params = new URLSearchParams(window.location.search); + if (!params.has('tabId') && window.currentContextTabId) { + chrome.tabs.create({ url: chrome.runtime.getURL('popup.html?tabId=' + window.currentContextTabId) }); + } + }); + } + + window.addEventListener('mouseup', () => state.isDragging = false); + window.addEventListener('mouseleave', () => state.isDragging = false); + + if (DOM.cleanBrokenToggle) { + DOM.cleanBrokenToggle.addEventListener('change', () => { + applyFilters(); + saveSettings(); + }); + } + + if (DOM.toggleFiltersBtn) { + if (DOM.toggleFiltersBtn.classList.contains('collapsed')) { + DOM.toggleFiltersBtn.title = "Expandir filtros"; + } else { + DOM.toggleFiltersBtn.title = "Contraer filtros"; + } + + DOM.toggleFiltersBtn.addEventListener('click', () => { + const isCollapsed = DOM.collapsibleFilters.classList.toggle('collapsed'); + DOM.toggleFiltersBtn.classList.toggle('collapsed', isCollapsed); + DOM.toggleFiltersBtn.title = isCollapsed ? "Expandir filtros" : "Contraer filtros"; + saveSettings(); + }); + } + + if (DOM.toggleSeqBtn) { + DOM.toggleSeqBtn.addEventListener('click', () => { + if (DOM.seqPanel.style.display === 'none') { + DOM.seqPanel.style.display = 'block'; + DOM.toggleSeqBtn.style.backgroundColor = 'rgba(225, 29, 72, 0.15)'; + DOM.toggleSeqBtn.style.borderColor = 'var(--accent-color)'; + DOM.toggleSeqBtn.style.color = '#fff'; + } else { + DOM.seqPanel.style.display = 'none'; + DOM.toggleSeqBtn.style.backgroundColor = ''; + DOM.toggleSeqBtn.style.borderColor = ''; + DOM.toggleSeqBtn.style.color = ''; + } + }); + } + + if (DOM.seqStartBtn) { + DOM.seqStartBtn.addEventListener('click', startSequentialSearch); + } +} + +async function updateHDUrls() { + const isHitomi = window.currentContextTabUrl && window.currentContextTabUrl.includes('hitomi.la'); + const isHentaiera = window.currentContextTabUrl && window.currentContextTabUrl.includes('hentaiera.com'); + const isNHentai = window.currentContextTabUrl && (window.currentContextTabUrl.includes('nhentai.xxx') || window.currentContextTabUrl.includes('nhentai.net') || window.currentContextTabUrl.includes('nhentai.to')); + const is3Hentai = window.currentContextTabUrl && window.currentContextTabUrl.includes('3hentai.net'); + const isVerComicsPorno = window.currentContextTabUrl && window.currentContextTabUrl.includes('vercomicsporno.com'); + if (isHitomi || isHentaiera || isNHentai || is3Hentai || isVerComicsPorno) { + DOM.forceHD.checked = false; + DOM.forceHD.disabled = true; + return; + } + + if (!DOM.forceHD.checked) { + state.allImages.forEach(img => { + if (img.originalSrc) { + img.src = img.originalSrc; + img.width = img.origWidth; + img.height = img.origHeight; + } + img.hdSearching = false; + img.hdFound = false; + }); + applyFilters(); + return; + } + + state.allImages.forEach(img => { + if (!img.originalSrc) { + img.originalSrc = img.src; + img.origWidth = img.width; + img.origHeight = img.height; + } + }); + + state.filteredImages.forEach(img => { + if (img.inLink && img.linkHref && !img.hdFound && !img.hdSearching) { + img.hdSearching = true; + } + if (!img.hdFound && img.src.includes('kemono.') && img.src.includes('/thumbnail/data/')) { + img.src = img.src.replace('/thumbnail/data/', '/data/'); + img.linkHref = img.src; + img.hdSearching = true; + } + }); + + render(); + + let queue = state.filteredImages.map((img, idx) => ({img, idx})).filter(x => x.img.hdSearching); + const limit = 5; + let active = 0; + + await new Promise(resolve => { + if (queue.length === 0) return resolve(); + + const processNext = async () => { + if (queue.length === 0 && active === 0) return resolve(); + + while (active < limit && queue.length > 0) { + active++; + const {img, idx} = queue.shift(); + + try { + const resp = await fetch(img.linkHref); + const html = await resp.text(); + const doc = new DOMParser().parseFromString(html, 'text/html'); + + let foundSrc = doc.querySelector('#image-container img, .fit-horizontal img, #gimg, .gallery-image img, figure img, .post__content img')?.getAttribute('src'); + + if (!foundSrc && img.linkHref.match(/\.(jpg|jpeg|png|webp|gif|svg|avif|bmp|tiff|tif|ico|heic|heif|jxl)$/i)) foundSrc = img.linkHref; + + if (!foundSrc) { + const folder = (new URL(img.originalSrc)).pathname.split('/').slice(0,-1).join('/'); + foundSrc = Array.from(doc.querySelectorAll('img')) + .map(i => i.getAttribute('src')) + .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')); + } + + if (foundSrc) { + const fullUrl = foundSrc.startsWith('http') ? foundSrc : new URL(foundSrc, img.linkHref).href; + img.src = fullUrl; + await new Promise(r => { + const t = new Image(); + t.onload = () => { img.width = t.naturalWidth; img.height = t.naturalHeight; img.hdFound = true; r(); }; + t.onerror = r; + t.src = fullUrl; + }); + } + } catch {} + + img.hdSearching = false; + updateCardForHD(idx); + active--; + processNext(); + } + }; + processNext(); + }); +} + +function updateCardForHD(idx) { + const cards = DOM.grid.querySelectorAll('.image-card'); + const card = cards[idx]; + if (!card) return; + const img = state.filteredImages[idx]; + + let info = `${img.width} × ${img.height}`; + let style = ''; + if (DOM.forceHD.checked) { + if (img.hdSearching) { info = '🔎 Buscando...'; style = 'color: #f39c12; font-size: 11px;'; } + else if (img.hdFound) { info = `🌟 HD: ${img.width}×${img.height}`; style = 'color: #2ecc71; font-weight: bold;'; } + else { info = '❌ Normal'; style = 'color: #e74c3c; font-size: 11px;'; } + } + + const span = card.querySelector('.card-info span'); + if (span) { + span.innerHTML = info; + span.setAttribute('style', style); + } + + if (img.hdFound) { + const imgEl = card.querySelector('.image-wrapper img'); + if (imgEl && imgEl.src !== img.src) imgEl.src = img.src; + const urlBar = card.querySelector('.url-bar'); + if (urlBar && urlBar.textContent !== img.src) urlBar.textContent = img.src; + } +} + +export function render() { + const scroll = DOM.grid.scrollTop; + DOM.grid.innerHTML = ''; + + if (state.filteredImages.length === 0) { + DOM.grid.innerHTML = '

No se encontraron imágenes.

'; + } else { + state.filteredImages.forEach((img, idx) => { + const isSelected = state.selectedImages.has(img.src); + const card = document.createElement('div'); + card.className = `image-card ${isSelected ? 'selected' : ''}`; + + let info = `${img.width} × ${img.height}`; + let style = ''; + if (DOM.forceHD.checked) { + if (img.hdSearching) { info = '🔎 Buscando...'; style = 'color: #f39c12; font-size: 11px;'; } + else if (img.hdFound) { info = `🌟 HD: ${img.width}×${img.height}`; style = 'color: #2ecc71; font-weight: bold;'; } + else { info = '❌ Normal'; style = 'color: #e74c3c; font-size: 11px;'; } + } + + card.innerHTML = ` + +
+ + +
+
${img.src}
+
${info}
+ `; + + card.querySelector('.btn-ext').onclick = (e) => { e.stopPropagation(); chrome.tabs.create({ url: img.src }); }; + card.querySelector('.btn-dl').onclick = async (e) => { + e.stopPropagation(); + const baseSf = DOM.subfolderInput.value.trim().replace(/[\\:*?"<>|]/g, "") || (window.currentContextTabTitle ? window.currentContextTabTitle.replace(/[\\:*?"<>|]/g, "").trim().slice(0, 80) : 'comics_completos'); + const uniqueSf = await getUniqueSubfolder(baseSf); + downloadImage(img, idx, state.filteredImages.length, uniqueSf); + }; + + const imgEl = card.querySelector('img'); + imgEl.addEventListener('dragstart', (e) => e.preventDefault()); + imgEl.addEventListener('error', () => { + img.isBroken = true; + if (DOM.cleanBrokenToggle && DOM.cleanBrokenToggle.checked) { + card.style.display = 'none'; + state.selectedImages.delete(img.src); + updateSelectionVisuals(); + } + }); + + card.addEventListener('mousedown', (e) => { + if (e.target.closest('.card-actions')) return; + e.preventDefault(); + if (e.shiftKey) { + toggleSelection(idx, true); + } else { + state.isDragging = true; + state.dragStartIdx = idx; + state.dragMode = !state.selectedImages.has(img.src); + state.dragSavedSelection = new Set(state.selectedImages); + updateDragSelection(idx); + } + }); + + card.addEventListener('mouseenter', (e) => { + if (state.isDragging) { + updateDragSelection(idx); + } + }); + + DOM.grid.appendChild(card); + }); + } + + updateSelectionVisuals(); + DOM.grid.scrollTop = scroll; +} + +function updateSelectionVisuals() { + const cards = DOM.grid.querySelectorAll('.image-card'); + state.filteredImages.forEach((img, idx) => { + const isSelected = state.selectedImages.has(img.src); + const card = cards[idx]; + if (card) { + if (isSelected) card.classList.add('selected'); + else card.classList.remove('selected'); + + const checkbox = card.querySelector('.card-checkbox'); + if (checkbox) checkbox.checked = isSelected; + } + }); + + DOM.selectedCount.textContent = state.selectedImages.size; + DOM.btnCounter.textContent = state.selectedImages.size; + DOM.selectAll.checked = state.filteredImages.length > 0 && state.selectedImages.size === state.filteredImages.length; + DOM.downloadBtn.disabled = state.selectedImages.size === 0; + DOM.totalCount.textContent = state.filteredImages.length; +} + +function updateDragSelection(currentIdx) { + state.selectedImages = new Set(state.dragSavedSelection); + const start = Math.min(state.dragStartIdx, currentIdx); + const end = Math.max(state.dragStartIdx, currentIdx); + + for (let i = start; i <= end; i++) { + const src = state.filteredImages[i].src; + if (state.dragMode) state.selectedImages.add(src); + else state.selectedImages.delete(src); + } + + state.lastSelectedIdx = currentIdx; + updateSelectionVisuals(); +} + +function toggleSelection(idx, shift, forceState = null) { + const img = state.filteredImages[idx]; + const isCurrentlySelected = state.selectedImages.has(img.src); + + if (shift && state.lastSelectedIdx !== -1) { + const start = Math.min(state.lastSelectedIdx, idx); + const end = Math.max(state.lastSelectedIdx, idx); + const shouldSelect = !state.selectedImages.has(state.filteredImages[state.lastSelectedIdx].src); + + for (let i = start; i <= end; i++) { + const src = state.filteredImages[i].src; + if (shouldSelect) state.selectedImages.add(src); + else state.selectedImages.delete(src); + } + } else { + if (forceState !== null) { + if (forceState) state.selectedImages.add(img.src); + else state.selectedImages.delete(img.src); + } else { + if (isCurrentlySelected) state.selectedImages.delete(img.src); + else state.selectedImages.add(img.src); + } + state.lastSelectedIdx = idx; + } + updateSelectionVisuals(); +} + +async function startSequentialSearch() { + const urlPattern = DOM.seqUrlPattern.value.trim(); + const startPage = parseInt(DOM.seqStart.value) || 1; + const endPage = parseInt(DOM.seqEnd.value) || 1; + const customSelector = DOM.seqSelector.value.trim(); + + if (!urlPattern.includes('{page}')) { + alert('Por favor, introduce una URL con el marcador {page} para poder paginar.'); + return; + } + + if (startPage > endPage) { + alert('La página de inicio ("Desde") no puede ser mayor que la página final ("Hasta").'); + return; + } + + DOM.seqStartBtn.disabled = true; + DOM.seqStartBtn.textContent = 'Buscando...'; + DOM.seqUrlPattern.disabled = true; + DOM.seqStart.disabled = true; + DOM.seqEnd.disabled = true; + DOM.seqSelector.disabled = true; + DOM.seqProgress.style.display = 'block'; + + state.allImages = []; + state.selectedImages.clear(); + applyFilters(); + + const totalPages = endPage - startPage + 1; + let loadedCount = 0; + + DOM.seqProgressText.textContent = `0 / ${totalPages}`; + DOM.seqProgressStatus.textContent = 'Iniciando búsqueda...'; + DOM.seqProgressBar.style.width = '0%'; + + const queue = []; + for (let p = startPage; p <= endPage; p++) { + queue.push(p); + } + + const limit = 3; + let activeCount = 0; + + const processNext = async () => { + if (queue.length === 0 && activeCount === 0) { + DOM.seqStartBtn.disabled = false; + DOM.seqStartBtn.textContent = 'Buscar'; + DOM.seqUrlPattern.disabled = false; + DOM.seqStart.disabled = false; + DOM.seqEnd.disabled = false; + DOM.seqSelector.disabled = false; + DOM.seqProgressStatus.textContent = '¡Búsqueda completa!'; + + state.allImages.forEach(img => state.selectedImages.add(img.src)); + updateSelectionVisuals(); + return; + } + + while (activeCount < limit && queue.length > 0) { + activeCount++; + const pageNum = queue.shift(); + const pageUrl = urlPattern.replace('{page}', pageNum); + + DOM.seqProgressStatus.textContent = `Cargando página ${pageNum}...`; + + try { + const resp = await fetch(pageUrl); + if (!resp.ok) throw new Error(`HTTP error ${resp.status}`); + + const html = await resp.text(); + const doc = new DOMParser().parseFromString(html, 'text/html'); + + let foundSrc = ''; + if (customSelector) { + foundSrc = doc.querySelector(customSelector)?.getAttribute('src') || doc.querySelector(customSelector)?.getAttribute('data-src'); + } + + if (!foundSrc) { + const standardSelectors = '#gimg, #image-container img, .fit-horizontal img, .gallery-image img, figure img, .post__content img'; + foundSrc = doc.querySelector(standardSelectors)?.getAttribute('src') || doc.querySelector(standardSelectors)?.getAttribute('data-src'); + } + + if (!foundSrc) { + const imgs = Array.from(doc.querySelectorAll('img')); + let bestImg = null; + let bestScore = 0; + + imgs.forEach(img => { + const src = img.getAttribute('src') || img.getAttribute('data-src') || img.getAttribute('data-lazy-src'); + if (!src || src.startsWith('data:') || src.startsWith('blob:')) return; + if (src.includes('logo') || src.includes('banner') || src.includes('avatar') || src.includes('icon')) return; + + let score = 10; + const filename = src.split('/').pop(); + if (filename.match(/\d+/)) score += 20; + if (img.width >= 300 || img.height >= 300) score += 50; + + if (score > bestScore) { + bestScore = score; + bestImg = src; + } + }); + + if (bestImg) { + foundSrc = bestImg; + } + } + + if (foundSrc) { + const fullUrl = foundSrc.startsWith('http') ? foundSrc : new URL(foundSrc, pageUrl).href; + + const imgObj = { + src: fullUrl, + width: 0, + height: 0, + inLink: false, + linkHref: null, + isKemonoThumb: false, + originalSrc: fullUrl, + origWidth: 0, + origHeight: 0 + }; + + await new Promise(resolve => { + const t = new Image(); + t.onload = () => { + imgObj.width = t.naturalWidth; + imgObj.height = t.naturalHeight; + imgObj.origWidth = t.naturalWidth; + imgObj.origHeight = t.naturalHeight; + resolve(); + }; + t.onerror = () => { resolve(); }; + t.src = fullUrl; + }); + + if (!state.allImages.some(img => img.src === imgObj.src)) { + state.allImages.push(imgObj); + state.selectedImages.add(imgObj.src); + applyFilters(); + } + } + } catch (err) { + console.error(`Error al cargar página ${pageNum}:`, err); + } + + loadedCount++; + activeCount--; + + const progressPercent = (loadedCount / totalPages) * 100; + DOM.seqProgressText.textContent = `${loadedCount} / ${totalPages}`; + DOM.seqProgressBar.style.width = `${progressPercent}%`; + + processNext(); + } + }; + + processNext(); +} + +let originalHTML = ''; + +function showDownloadingState(completed, total) { + if (!originalHTML) { + originalHTML = DOM.downloadBtn.innerHTML; + } + DOM.downloadBtn.disabled = true; + const percentage = Math.round((completed / total) * 100); + DOM.downloadBtn.innerHTML = ` + + + + + + Descargando... ${percentage}% (${completed}/${total}) + `; +} + +function restoreDownloadButton() { + if (originalHTML) { + DOM.downloadBtn.disabled = false; + DOM.downloadBtn.innerHTML = originalHTML; + originalHTML = ''; + } + updateSelectionVisuals(); +} + +chrome.runtime.onMessage.addListener((request) => { + if (request.action === 'downloadProgress' && request.comicUrl === window.currentContextTabUrl) { + if (request.downloading) { + showDownloadingState(request.completed, request.total); + } else { + restoreDownloadButton(); + } + } +}); + diff --git a/buscador hls/manifest.json b/buscador hls/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..e0cfccaaf72e6e6db78c8d6f16c9e01d7042f22c --- /dev/null +++ b/buscador hls/manifest.json @@ -0,0 +1,23 @@ +{ + "manifest_version": 3, + "name": "Buscador HLS", + "version": "1.0", + "description": "Busca y extrae enlaces de video HLS (.m3u8) en su máxima calidad de forma masiva.", + "permissions": [ + "activeTab", + "scripting", + "tabs" + ], + "host_permissions": [ + "*://*.xvideos.com/*", + "*://*.xvideos.es/*", + "*://*.xvideos2.com/*", + "*://*.xvideos-cdn.com/*", + "*://*.pornhub.com/*", + "*://*.phncdn.com/*", + "" + ], + "action": { + "default_popup": "popup.html" + } +} diff --git a/buscador hls/popup.css b/buscador hls/popup.css new file mode 100644 index 0000000000000000000000000000000000000000..d0328871c886a39639460978a3c933966599ff45 --- /dev/null +++ b/buscador hls/popup.css @@ -0,0 +1,643 @@ +/* Buscador HLS Max - Custom Stylesheet */ +:root { + --bg-main: #09090b; + --bg-card: #18181b; + --bg-input: #09090b; + --border: #27272a; + --border-focus: #4f46e5; + --text-main: #f4f4f5; + --text-muted: #a1a1aa; + + --primary: #6366f1; + --primary-hover: #4f46e5; + --primary-shadow: rgba(99, 102, 241, 0.35); + + --accent: #8b5cf6; + --accent-hover: #7c3aed; + + --success: #10b981; + --success-bg: rgba(16, 185, 129, 0.15); + --success-border: rgba(16, 185, 129, 0.3); + + --info: #3b82f6; + --info-bg: rgba(59, 130, 246, 0.15); + + --warning: #f59e0b; + --warning-bg: rgba(245, 158, 11, 0.15); + + --danger: #ef4444; + --danger-bg: rgba(239, 68, 68, 0.15); + + --font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); + --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); + --shadow-glow: 0 0 15px rgba(99, 102, 241, 0.15); +} + +/* Reset */ +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + background-color: var(--bg-main); + color: var(--text-main); + font-family: var(--font-family); + font-size: 14px; + line-height: 1.5; + width: 680px; /* Default popup width */ + min-height: 520px; + overflow-x: hidden; + position: relative; +} + +/* Full Tab / Page Mode Detection */ +@media (min-width: 768px) { + body { + width: 100vw; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: flex-start; + padding: 30px 15px; + } + .app-container { + width: 100%; + max-width: 900px; + margin: 0 auto; + border-radius: 16px; + border: 1px solid var(--border); + box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 10px 10px -5px rgba(0,0,0,0.4); + background: linear-gradient(180deg, #18181b 0%, #09090b 100%); + } + .results-container { + max-height: 480px; + } +} + +.app-container { + display: flex; + flex-direction: column; + background-color: var(--bg-main); + padding: 20px; + min-height: inherit; +} + +/* Header */ +.header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; + padding-bottom: 15px; + border-bottom: 1px solid var(--border); +} + +.brand { + display: flex; + align-items: center; + gap: 12px; +} + +.logo-icon { + background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%); + color: #fff; + width: 38px; + height: 38px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + box-shadow: 0 4px 10px rgba(99, 102, 241, 0.3); +} + +.brand-text h1 { + font-size: 18px; + font-weight: 800; + letter-spacing: -0.025em; + color: #ffffff; +} + +.brand-text h1 span { + background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; +} + +.brand-text p { + font-size: 11px; + color: var(--text-muted); + font-weight: 500; +} + +.btn-icon { + background: var(--bg-card); + border: 1px solid var(--border); + color: var(--text-muted); + width: 36px; + height: 36px; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: all 0.2s ease; +} + +.btn-icon:hover { + background: var(--border); + color: #fff; + border-color: var(--text-muted); +} + +/* Panels styling */ +.panel { + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: 12px; + padding: 16px; + margin-bottom: 16px; + box-shadow: var(--shadow-sm); + transition: box-shadow 0.2s ease, border-color 0.2s ease; +} + +.panel:hover { + box-shadow: var(--shadow-md), var(--shadow-glow); + border-color: rgba(99, 102, 241, 0.15); +} + +.panel-header { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 14px; +} + +.step-num { + background: rgba(99, 102, 241, 0.1); + color: var(--primary); + font-size: 12px; + font-weight: 700; + width: 22px; + height: 22px; + border-radius: 6px; + display: flex; + align-items: center; + justify-content: center; + border: 1px solid rgba(99, 102, 241, 0.2); +} + +.panel-header h2 { + font-size: 15px; + font-weight: 700; + color: #fff; +} + +/* Inputs & Textareas */ +.textarea-wrapper { + position: relative; + margin-bottom: 12px; +} + +textarea { + width: 100%; + height: 120px; + background-color: var(--bg-input); + border: 1px solid var(--border); + border-radius: 8px; + color: var(--text-main); + padding: 12px; + font-family: monospace; + font-size: 12.5px; + resize: vertical; + outline: none; + transition: border-color 0.2s ease, box-shadow 0.2s ease; +} + +textarea:focus { + border-color: var(--border-focus); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15); +} + +textarea::placeholder { + color: #52525b; +} + +.btn-clear { + position: absolute; + right: 12px; + bottom: 12px; + background: rgba(39, 39, 42, 0.8); + border: 1px solid var(--border); + color: var(--text-muted); + font-size: 11px; + font-weight: 600; + padding: 4px 8px; + border-radius: 6px; + display: flex; + align-items: center; + gap: 4px; + cursor: pointer; + backdrop-filter: blur(4px); + transition: all 0.2s ease; +} + +.btn-clear:hover { + background: var(--danger-bg); + color: #ef4444; + border-color: rgba(239, 68, 68, 0.3); +} + +/* Control Rows */ +.control-row { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; +} + +.concurrency-selector { + display: flex; + align-items: center; + gap: 8px; + color: var(--text-muted); + font-size: 13px; +} + +.concurrency-selector select { + background-color: var(--bg-input); + border: 1px solid var(--border); + color: var(--text-main); + padding: 6px 10px; + border-radius: 6px; + outline: none; + cursor: pointer; + font-weight: 500; +} + +.concurrency-selector select:focus { + border-color: var(--border-focus); +} + +/* Buttons */ +.btn-primary { + background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%); + color: #fff; + border: none; + font-weight: 700; + font-size: 13px; + padding: 10px 18px; + border-radius: 8px; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; + box-shadow: 0 4px 12px rgba(139, 92, 246, 0.2); + transition: all 0.2s ease; +} + +.btn-primary:hover { + transform: translateY(-1px); + box-shadow: 0 6px 16px rgba(139, 92, 246, 0.35); + opacity: 0.95; +} + +.btn-primary:active { + transform: translateY(0); +} + +.btn-secondary { + background-color: #27272a; + border: 1px solid #3f3f46; + color: var(--text-main); + font-weight: 600; + font-size: 12.5px; + padding: 8px 14px; + border-radius: 8px; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; + transition: all 0.2s ease; +} + +.btn-secondary:hover { + background-color: #3f3f46; + border-color: #52525b; +} + +.btn-small { + padding: 4px 8px; + font-size: 11px; + border-radius: 6px; +} + +.btn-accent { + background: linear-gradient(135deg, var(--accent) 0%, #a855f7 100%); +} + +/* Progress bar section */ +.progress-section { + background: rgba(39, 39, 42, 0.3); + border: 1px dashed var(--border); + border-radius: 10px; + padding: 12px 16px; + margin-bottom: 16px; +} + +.progress-info { + display: flex; + justify-content: space-between; + font-size: 12.5px; + font-weight: 600; + margin-bottom: 6px; +} + +#progress-status { + color: var(--text-main); +} + +#progress-percentage { + color: var(--primary); +} + +.progress-bar-container { + width: 100%; + height: 8px; + background-color: #27272a; + border-radius: 9999px; + overflow: hidden; +} + +.progress-bar { + height: 100%; + width: 0; + background: linear-gradient(90deg, var(--primary) 0%, var(--accent) 100%); + border-radius: 9999px; + transition: width 0.2s ease; +} + +/* Results Placeholder */ +.results-placeholder { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 40px 20px; + text-align: center; + color: var(--text-muted); +} + +.placeholder-icon { + color: #3f3f46; + margin-bottom: 12px; +} + +.results-placeholder p { + font-weight: 600; + color: #e4e4e7; + font-size: 13.5px; + margin-bottom: 4px; +} + +.results-placeholder .hint { + font-size: 11px; + color: #71717a; +} + +/* Results Table */ +.results-container { + overflow-y: auto; + max-height: 220px; + border: 1px solid var(--border); + border-radius: 8px; + background-color: var(--bg-input); +} + +/* Custom scrollbars */ +.results-container::-webkit-scrollbar { + width: 6px; +} +.results-container::-webkit-scrollbar-track { + background: transparent; +} +.results-container::-webkit-scrollbar-thumb { + background: #27272a; + border-radius: 999px; +} +.results-container::-webkit-scrollbar-thumb:hover { + background: #3f3f46; +} + +.title-with-badge { + display: flex; + align-items: center; + gap: 8px; +} + +.badge { + background-color: #27272a; + border: 1px solid var(--border); + color: #fff; + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: 12px; +} + +.results-table { + width: 100%; + border-collapse: collapse; + text-align: left; +} + +.results-table th { + background-color: #18181b; + color: var(--text-muted); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.05em; + padding: 10px 12px; + border-bottom: 1px solid var(--border); + position: sticky; + top: 0; + z-index: 10; +} + +.results-table td { + padding: 12px; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} + +.results-table tbody tr:hover { + background-color: rgba(39, 39, 42, 0.4); +} + +.results-table tbody tr.error-row { + opacity: 0.7; +} + +/* Custom Checkbox */ +input[type="checkbox"] { + accent-color: var(--primary); + width: 15px; + height: 15px; + cursor: pointer; +} + +/* Video Column Info */ +.video-cell { + display: flex; + flex-direction: column; + gap: 4px; + max-width: 320px; +} + +.video-title { + font-weight: 600; + color: #fff; + font-size: 13px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.video-url { + font-family: monospace; + font-size: 11px; + color: var(--text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.video-url a { + color: inherit; + text-decoration: none; +} + +.video-url a:hover { + color: var(--primary); + text-decoration: underline; +} + +/* Quality Tag colors */ +.quality-tag { + font-size: 11px; + font-weight: 800; + padding: 3px 8px; + border-radius: 6px; + text-transform: uppercase; + display: inline-block; + text-align: center; +} + +.quality-1080p { + background-color: var(--success-bg); + color: var(--success); + border: 1px solid var(--success-border); +} + +.quality-720p { + background-color: var(--info-bg); + color: var(--info); + border: 1px solid rgba(59, 130, 246, 0.3); +} + +.quality-480p, .quality-360p { + background-color: var(--warning-bg); + color: var(--warning); + border: 1px solid rgba(245, 158, 11, 0.3); +} + +.quality-error { + background-color: var(--danger-bg); + color: var(--danger); + border: 1px solid rgba(239, 68, 68, 0.3); +} + +/* Action items inside cell */ +.actions-cell { + display: flex; + gap: 6px; +} + +.btn-actions-row { + background: var(--bg-card); + border: 1px solid var(--border); + color: var(--text-main); + padding: 6px; + border-radius: 6px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.btn-actions-row:hover { + background-color: var(--border); + color: #fff; +} + +.btn-actions-row.success-toast { + color: var(--success); + border-color: var(--success); + background-color: var(--success-bg); +} + +/* Bulk actions footer panel */ +.bulk-actions { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 14px; + padding-top: 14px; + border-top: 1px solid var(--border); +} + +.select-info { + font-size: 12.5px; + color: var(--text-muted); + font-weight: 600; +} + +.bulk-buttons { + display: flex; + gap: 8px; +} + +/* Toast Message popup */ +.toast { + position: fixed; + bottom: 20px; + left: 50%; + transform: translateX(-50%) translateY(100px); + background-color: #27272a; + border: 1px solid var(--border); + color: #fff; + padding: 10px 20px; + border-radius: 8px; + font-weight: 600; + font-size: 13px; + box-shadow: var(--shadow-lg), 0 0 20px rgba(0,0,0,0.5); + pointer-events: none; + z-index: 2000; + transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), opacity 0.3s ease; + opacity: 0; +} + +.toast.show { + transform: translateX(-50%) translateY(0); + opacity: 1; +} + +/* Utility Helpers */ +.hidden { + display: none !important; +} diff --git a/buscador hls/popup.html b/buscador hls/popup.html new file mode 100644 index 0000000000000000000000000000000000000000..39e164677cb0bc8b82c369dcdd481d0ab92462c9 --- /dev/null +++ b/buscador hls/popup.html @@ -0,0 +1,184 @@ + + + + + + Buscador HLS Max + + + + + + + +
+ +
+
+
+ + + + +
+
+

Buscador HLS Max

+

Extractor de enlaces m3u8 en alta fidelidad

+
+
+ +
+ + +
+ +
+
+ 1 +

Ingresar enlaces de video

+
+
+ + +
+ +
+
+ + +
+ +
+
+ + + + + +
+
+
+ 2 +

Enlaces HLS Encontrados

+ 0 +
+
+ + +
+
+ +
+
+
+ + + + + + + + + + +
+

Los enlaces resueltos en su máxima calidad aparecerán aquí.

+ Pega los enlaces arriba y presiona "Extraer Enlaces HLS". +
+ + + + + + + + + + + + + + +
+ + + +
+
+
+ + + + + + + diff --git a/buscador hls/popup.js b/buscador hls/popup.js new file mode 100644 index 0000000000000000000000000000000000000000..41d903701593616faafa6dae5eaf21f4699e89fb --- /dev/null +++ b/buscador hls/popup.js @@ -0,0 +1,709 @@ +document.addEventListener('DOMContentLoaded', () => { + // Elements + const urlsInput = document.getElementById('urls-input'); + const btnClearInput = document.getElementById('btn-clear-input'); + const concurrencySelect = document.getElementById('concurrency-select'); + const btnExtract = document.getElementById('btn-extract'); + const btnExpand = document.getElementById('btn-expand'); + + const progressSection = document.getElementById('progress-section'); + const progressStatus = document.getElementById('progress-status'); + const progressPercentage = document.getElementById('progress-percentage'); + const progressBar = document.getElementById('progress-bar'); + + const resultsCount = document.getElementById('results-count'); + const resultsPlaceholder = document.getElementById('results-placeholder'); + const resultsTable = document.getElementById('results-table'); + const resultsList = document.getElementById('results-list'); + const selectAllCheckbox = document.getElementById('select-all-checkbox'); + const btnCopyAllTop = document.getElementById('btn-copy-all-top'); + + const bulkActions = document.getElementById('bulk-actions'); + const selectedCount = document.getElementById('selected-count'); + const btnBulkCopy = document.getElementById('btn-bulk-copy'); + const btnBulkOpen = document.getElementById('btn-bulk-open'); + const btnBulkDownload = document.getElementById('btn-bulk-download'); + const toast = document.getElementById('toast'); + + let activeQueue = null; + let parsedResults = []; + + // Check if we are running in full tab mode + const urlParams = new URLSearchParams(window.location.search); + const isTab = urlParams.get('mode') === 'tab' || window.innerWidth > 700; + if (isTab) { + btnExpand.classList.add('hidden'); + // Adapt layout width for tab + document.body.style.width = '100%'; + } + + // Expand to tab event + btnExpand.addEventListener('click', () => { + chrome.tabs.create({ url: chrome.runtime.getURL('popup.html?mode=tab') }); + }); + + // Clear Input + btnClearInput.addEventListener('click', () => { + urlsInput.value = ''; + urlsInput.focus(); + }); + + // Extract HLS Event + btnExtract.addEventListener('click', () => { + if (activeQueue) { + activeQueue.cancel(); + activeQueue = null; + } + startExtraction(); + }); + + // Select All Results + selectAllCheckbox.addEventListener('change', () => { + const checkboxes = resultsList.querySelectorAll('input[type="checkbox"]:not(:disabled)'); + checkboxes.forEach(cb => { + cb.checked = selectAllCheckbox.checked; + }); + updateSelectedCount(); + }); + + // Copy All Successful URLs (Top Button) + btnCopyAllTop.addEventListener('click', () => { + const urls = parsedResults + .filter(item => item.success) + .map(item => item.hlsUrl); + if (urls.length === 0) return; + + navigator.clipboard.writeText(urls.join('\n')).then(() => { + showToast(`¡Copiados ${urls.length} enlaces!`); + }); + }); + + // Bulk Actions + btnBulkCopy.addEventListener('click', () => { + const urls = getSelectedUrls(); + if (urls.length === 0) return; + + navigator.clipboard.writeText(urls.join('\n')).then(() => { + showToast(`¡Copiados ${urls.length} enlaces!`); + }); + }); + + btnBulkOpen.addEventListener('click', () => { + const urls = getSelectedUrls(); + if (urls.length === 0) return; + + if (confirm(`¿Deseas abrir ${urls.length} enlaces en una nueva ventana?`)) { + chrome.windows.create({ url: urls[0] }, (win) => { + for (let i = 1; i < urls.length; i++) { + chrome.tabs.create({ windowId: win.id, url: urls[i] }); + } + }); + } + }); + + btnBulkDownload.addEventListener('click', () => { + const selected = getSelectedItems(); + if (selected.length === 0) return; + + let m3uText = '#EXTM3U\n'; + selected.forEach(item => { + m3uText += `#EXTINF:-1,${item.title} [${item.quality}]\n${item.hlsUrl}\n`; + }); + + const blob = new Blob([m3uText], { type: 'text/plain;charset=utf-8' }); + const downloadUrl = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = downloadUrl; + a.download = `buscador_hls_lista_${Date.now()}.m3u`; + a.click(); + URL.revokeObjectURL(downloadUrl); + showToast('Lista exportada como M3U'); + }); + + // Main Extraction Flow + async function startExtraction() { + const rawInput = urlsInput.value.trim(); + if (!rawInput) { + showToast('Por favor, ingresa al menos una URL.'); + return; + } + + // Split and clean URLs + const urls = rawInput.split('\n') + .map(url => url.trim()) + .filter(url => url.length > 0); + + if (urls.length === 0) { + showToast('No se encontraron URLs válidas.'); + return; + } + + // Reset UI state + parsedResults = []; + resultsList.innerHTML = ''; + resultsPlaceholder.classList.add('hidden'); + resultsTable.classList.remove('hidden'); + bulkActions.classList.add('hidden'); + btnCopyAllTop.classList.add('hidden'); + resultsCount.textContent = '0'; + selectAllCheckbox.checked = true; + + // Show Progress + progressSection.classList.remove('hidden'); + updateProgress(0, urls.length, 'Iniciando escaneo...'); + + const concurrency = parseInt(concurrencySelect.value, 10); + const tasks = urls.map(url => { + const taskFn = () => processVideoUrl(url); + taskFn.url = url; // attach metadata + return taskFn; + }); + + activeQueue = new Queue( + tasks, + concurrency, + // Progress Callback + (completed, total) => { + const percent = Math.round((completed / total) * 100); + updateProgress(percent, total, `Procesando: ${completed} de ${total}`); + }, + // Completion Callback + (results) => { + activeQueue = null; + progressSection.classList.add('hidden'); + parsedResults = results; + renderResults(); + } + ); + + activeQueue.start(); + } + + // Helper to extract HLS master URL from Pornhub HTML page + function extractPornhubHls(html) { + if (!html) return null; + + // Unescape JSON escaped slashes in HTML (e.g. https:\/\/... -> https://...) + const unescapedHtml = html.replace(/\\\/javascript/g, '').replace(/\\\//g, '/'); + + // 1. Robust bracket-matching parser for mediaDefinitions array in JS + let mediaDefs = []; + const mediaDefIndex = unescapedHtml.indexOf('mediaDefinitions'); + if (mediaDefIndex !== -1) { + const startArr = unescapedHtml.indexOf('[', mediaDefIndex); + if (startArr !== -1) { + let depth = 0; + let endArr = -1; + for (let i = startArr; i < unescapedHtml.length; i++) { + if (unescapedHtml[i] === '[') depth++; + else if (unescapedHtml[i] === ']') { + depth--; + if (depth === 0) { + endArr = i; + break; + } + } + } + if (endArr !== -1) { + const jsonStr = unescapedHtml.substring(startArr, endArr + 1); + try { + mediaDefs = JSON.parse(jsonStr); + } catch (e) { + console.log('Failed parsing mediaDefinitions JSON block', e); + } + } + } + } + + if (Array.isArray(mediaDefs) && mediaDefs.length > 0) { + // Filter valid HLS videoUrls + const hlsDefs = mediaDefs.filter(item => item.videoUrl && typeof item.videoUrl === 'string' && item.videoUrl.trim() !== '' && (item.format === 'hls' || item.videoUrl.includes('.m3u8'))); + + if (hlsDefs.length > 0) { + // Sort by quality height descending (1080 > 720 > 480 > 240) + hlsDefs.sort((a, b) => { + const qA = parseInt(a.quality, 10) || a.height || 0; + const qB = parseInt(b.quality, 10) || b.height || 0; + return qB - qA; + }); + + // Prioritize path-tokenized URLs (/TOKEN,TIMESTAMP/hls/) if provided by Pornhub + const pathTokenized = hlsDefs.find(item => /\/[^\/]+,\d+\/hls\//i.test(item.videoUrl)); + if (pathTokenized) return pathTokenized.videoUrl; + + // Return highest quality HLS videoUrl directly from mediaDefinitions + return hlsDefs[0].videoUrl; + } + } + + // 2. Direct regex search for master.m3u8 URLs in unescaped HTML + const masterRegex = /(https?:\/\/[^"'\s\<\>]+\/hls\/[^"'\s\<\>]+\.m3u8[^"'\s\<\>]*)/i; + const masterMatch = unescapedHtml.match(masterRegex); + if (masterMatch && masterMatch[1]) { + return masterMatch[1]; + } + + return null; + } + + + + + + // Individual URL processing + async function processVideoUrl(url) { + try { + // Validate schema/domain + let cleanUrl = url; + if (!url.startsWith('http://') && !url.startsWith('https://')) { + cleanUrl = 'https://' + url; + } + + const parsedUrl = new URL(cleanUrl); + const isXVideos = parsedUrl.hostname.includes('xvideos'); + const isPornhub = parsedUrl.hostname.includes('pornhub.com'); + + if (!isXVideos && !isPornhub) { + throw new Error('Solo se admiten enlaces de XVideos y Pornhub'); + } + + // 1. Fetch Video Page + const response = await fetch(cleanUrl); + if (!response.ok) { + throw new Error(`Petición fallida (${response.status})`); + } + const html = await response.text(); + + // 2. Extract Title + const title = extractTitle(html, parsedUrl.pathname); + + let masterHlsUrl = null; + + if (isXVideos) { + // Extract XVideos Master HLS Url + const hlsRegex = /html5player\.setVideoHLS\s*\(\s*['"]([^'"]+)['"]/i; + const hlsMatch = html.match(hlsRegex); + + if (hlsMatch && hlsMatch[1]) { + masterHlsUrl = hlsMatch[1]; + } else { + // Fallback: Check direct high-quality MP4 + const mp4HighRegex = /html5player\.setVideoUrlHigh\s*\(\s*['"]([^'"]+)['"]/i; + const mp4HighMatch = html.match(mp4HighRegex); + if (mp4HighMatch && mp4HighMatch[1]) { + return { + originalUrl: cleanUrl, + title: title, + hlsUrl: mp4HighMatch[1], + quality: 'HD (MP4)', + success: true + }; + } + } + } else if (isPornhub) { + // Extract Pornhub Master HLS Url + masterHlsUrl = extractPornhubHls(html); + if (masterHlsUrl) { + masterHlsUrl = convertToPathTokenPornhubUrl(masterHlsUrl); + } + } + + if (masterHlsUrl) { + // 3. Resolve Maximum Quality m3u8 + const resolved = await resolveMaxQualityHLS(masterHlsUrl); + let finalHlsUrl = resolved.url; + if (isPornhub) { + finalHlsUrl = convertToPathTokenPornhubUrl(finalHlsUrl); + } + return { + originalUrl: cleanUrl, + title: title, + hlsUrl: finalHlsUrl, + quality: resolved.quality, + success: true + }; + } + + throw new Error('No se detectó flujo HLS ni descarga MP4'); + } catch (e) { + console.error(`Error processing URL: ${url}`, e); + return { + originalUrl: url, + title: url, + error: e.message, + success: false + }; + } + } + + // Resolve sub-playlists from Master Playlist to get the absolute maximum quality stream + async function resolveMaxQualityHLS(masterUrl) { + try { + const response = await fetch(masterUrl); + if (!response.ok) { + if (masterUrl.includes('phncdn.com') && masterUrl.includes('/master.m3u8')) { + const directStreamUrl = masterUrl.replace(/\/master\.m3u8/i, '/index-v1-a1.m3u8'); + return { url: directStreamUrl, quality: '1080p (HLS)' }; + } + return { url: masterUrl, quality: 'HLS' }; + } + const text = await response.text(); + + const lines = text.split(/\r?\n/); + const streams = []; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line.startsWith('#EXT-X-STREAM-INF:')) { + // Resolution parsing (e.g. RESOLUTION=1920x1080) + const resMatch = line.match(/RESOLUTION=(\d+)x(\d+)/i); + const nameMatch = line.match(/NAME="?([^",]+)"?/i); + + let height = 0; + let qualityName = ''; + + if (resMatch) { + height = parseInt(resMatch[2], 10); + qualityName = `${height}p`; + } else if (nameMatch) { + qualityName = nameMatch[1]; + height = parseInt(qualityName, 10) || 0; + } + + if (i + 1 < lines.length) { + const streamUrl = lines[i + 1].trim(); + if (streamUrl && !streamUrl.startsWith('#')) { + // Build absolute URL relative to the master playlist URL + const absoluteUrl = new URL(streamUrl, masterUrl).href; + streams.push({ + url: absoluteUrl, + height: height, + name: qualityName || `${height}p` + }); + } + } + } + } + + if (streams.length > 0) { + // Sort by resolution height descending (highest quality first) + streams.sort((a, b) => b.height - a.height); + return { + url: streams[0].url, + quality: streams[0].name + }; + } + + // Check if there are relative m3u8 playlists listed in raw text + const rawM3u8Regex = /[^\s#]+\.m3u8[^\s]*/g; + const matches = text.match(rawM3u8Regex); + if (matches && matches.length > 0) { + let bestUrl = matches[0]; + // Prefer one containing 1080, 720, or v1 + for (const matchUrl of matches) { + if (matchUrl.includes('1080') || matchUrl.includes('v1')) { + bestUrl = matchUrl; + break; + } + } + return { + url: new URL(bestUrl, masterUrl).href, + quality: bestUrl.includes('1080') ? '1080p' : 'HLS' + }; + } + + if (masterUrl.includes('phncdn.com') && masterUrl.includes('/master.m3u8')) { + const directStreamUrl = masterUrl.replace(/\/master\.m3u8/i, '/index-v1-a1.m3u8'); + return { url: directStreamUrl, quality: '1080p (HLS)' }; + } + + return { url: masterUrl, quality: 'HLS' }; + } catch (e) { + console.error('resolveMaxQualityHLS failed:', e); + if (masterUrl.includes('phncdn.com') && masterUrl.includes('/master.m3u8')) { + const directStreamUrl = masterUrl.replace(/\/master\.m3u8/i, '/index-v1-a1.m3u8'); + return { url: directStreamUrl, quality: '1080p (HLS)' }; + } + return { url: masterUrl, quality: 'HLS (Default)' }; + } + } + + // Scrape Page Title helper + function extractTitle(html, fallback) { + const ogTitleMatch = html.match(/(.*?)<\/title>/i); + if (titleMatch && titleMatch[1]) { + let t = titleMatch[1].trim(); + t = t.replace(/\s*-\s*XVideos\.com\s*/i, ''); + t = t.replace(/\s*-\s*XVIDEOS\.ES\s*/i, ''); + t = t.replace(/\s*-\s*XVideos2\.com\s*/i, ''); + t = t.replace(/\s*-\s*Pornhub\.com\s*/i, ''); + t = t.replace(/\s*-\s*Pornhub\s*/i, ''); + return decodeHtmlEntities(t); + } + + return fallback; + } + + function decodeHtmlEntities(str) { + return str.replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/ /g, ' '); + } + + // Render Results List in UI + function renderResults() { + resultsList.innerHTML = ''; + let successCount = 0; + + parsedResults.forEach((res, index) => { + const tr = document.createElement('tr'); + + if (!res.success) { + tr.className = 'error-row'; + tr.innerHTML = ` + + +
+ Error al procesar + ${res.error || 'Error desconocido'} +
+ + Fallo + +
+ +
+ + `; + } else { + successCount++; + const qClass = `quality-${res.quality.toLowerCase().replace(/[^a-z0-9]/g, '')}`; + tr.innerHTML = ` + + +
+ ${res.title} + ${res.hlsUrl} +
+ + ${res.quality} + +
+ + +
+ + `; + } + resultsList.appendChild(tr); + }); + + resultsCount.textContent = successCount; + + if (successCount > 0) { + btnCopyAllTop.classList.remove('hidden'); + bulkActions.classList.remove('hidden'); + setupRowEventListeners(); + updateSelectedCount(); + } else { + btnCopyAllTop.classList.add('hidden'); + if (parsedResults.length > 0) { + // All failed + setupRowEventListeners(); + } else { + // Empty + resultsPlaceholder.classList.remove('hidden'); + resultsTable.classList.add('hidden'); + } + } + } + + // Row operations listeners + function setupRowEventListeners() { + // Checkboxes change + const checkboxes = resultsList.querySelectorAll('.result-item-checkbox'); + checkboxes.forEach(cb => { + cb.addEventListener('change', () => { + updateSelectedCount(); + // Sync master select checkbox + const allChecked = Array.from(checkboxes).every(c => c.checked); + selectAllCheckbox.checked = allChecked; + }); + }); + + // Copy row button + resultsList.querySelectorAll('.btn-copy-row').forEach(btn => { + btn.addEventListener('click', (e) => { + const index = parseInt(btn.dataset.index, 10); + const item = parsedResults[index]; + navigator.clipboard.writeText(item.hlsUrl).then(() => { + showToast('¡Enlace HLS copiado!'); + btn.classList.add('success-toast'); + setTimeout(() => btn.classList.remove('success-toast'), 1500); + }); + }); + }); + + // Copy error raw link + resultsList.querySelectorAll('.btn-copy-page').forEach(btn => { + btn.addEventListener('click', () => { + const url = btn.dataset.url; + navigator.clipboard.writeText(url).then(() => { + showToast('URL original copiada'); + }); + }); + }); + + // Open row button + resultsList.querySelectorAll('.btn-open-row').forEach(btn => { + btn.addEventListener('click', () => { + const url = btn.dataset.url; + chrome.tabs.create({ url: url }); + }); + }); + } + + // Update selected badge + function updateSelectedCount() { + const count = getSelectedUrls().length; + selectedCount.textContent = `${count} seleccionado${count !== 1 ? 's' : ''}`; + + // Disable/Enable bulk buttons + btnBulkCopy.disabled = count === 0; + btnBulkOpen.disabled = count === 0; + btnBulkDownload.disabled = count === 0; + } + + // Retrieve selections + function getSelectedUrls() { + const selectedUrls = []; + const checkboxes = resultsList.querySelectorAll('.result-item-checkbox:checked'); + checkboxes.forEach(cb => { + const index = parseInt(cb.dataset.index, 10); + selectedUrls.push(parsedResults[index].hlsUrl); + }); + return selectedUrls; + } + + function getSelectedItems() { + const selected = []; + const checkboxes = resultsList.querySelectorAll('.result-item-checkbox:checked'); + checkboxes.forEach(cb => { + const index = parseInt(cb.dataset.index, 10); + selected.push(parsedResults[index]); + }); + return selected; + } + + // UI Helpers + function updateProgress(percentage, total, text) { + progressBar.style.width = `${percentage}%`; + progressStatus.textContent = text; + progressPercentage.textContent = `${percentage}%`; + } + + function showToast(message) { + toast.textContent = message; + toast.classList.remove('hidden'); + toast.classList.add('show'); + + setTimeout(() => { + toast.classList.remove('show'); + setTimeout(() => toast.classList.add('hidden'), 300); + }, 2500); + } +}); + +// Simple Queue worker framework to run requests in parallel with concurrency limit +class Queue { + constructor(tasks, concurrency, progressCallback, completionCallback) { + this.tasks = tasks; + this.concurrency = concurrency; + this.progressCallback = progressCallback; + this.completionCallback = completionCallback; + + this.activeCount = 0; + this.completedCount = 0; + this.currentIndex = 0; + this.results = []; + this.isCancelled = false; + } + + start() { + if (this.tasks.length === 0) { + this.completionCallback([]); + return; + } + const limit = Math.min(this.concurrency, this.tasks.length); + for (let i = 0; i < limit; i++) { + this.next(); + } + } + + cancel() { + this.isCancelled = true; + } + + next() { + if (this.isCancelled || this.currentIndex >= this.tasks.length) { + if (this.activeCount === 0) { + this.completionCallback(this.results); + } + return; + } + + const index = this.currentIndex++; + const task = this.tasks[index]; + this.activeCount++; + + task().then(result => { + if (!this.isCancelled) { + this.results[index] = result; + } + }).catch(err => { + if (!this.isCancelled) { + this.results[index] = { + originalUrl: task.url || '', + title: task.url || 'Error', + error: err.message, + success: false + }; + } + }).finally(() => { + this.activeCount--; + this.completedCount++; + + if (!this.isCancelled) { + this.progressCallback(this.completedCount, this.tasks.length); + this.next(); + } + }); + } +} diff --git a/detector de enlaces - copia/background.js b/detector de enlaces - copia/background.js new file mode 100644 index 0000000000000000000000000000000000000000..b7f82881fa814fa85cd72898f59b1987c7aca90d --- /dev/null +++ b/detector de enlaces - copia/background.js @@ -0,0 +1,351 @@ +let videoScanState = { + isScanning: false, + scannedCount: 0, + totalCount: 0, + foundUrls: [], + albumUrls: [], + error: null +}; + +let imageScanState = { + isScanning: false, + scannedCount: 0, + totalCount: 0, + foundUrls: [], + albumUrls: [], + error: null +}; + +function isAlbumImageUrl(url) { + if (!url) return false; + const lower = url.toLowerCase(); + if (lower.includes('/avatar/') || lower.includes('/icon/') || lower.includes('/logo/') || lower.includes('logo') || lower.includes('/thumbs/') || lower.includes('/img/')) { + return false; + } + return true; +} + +let activeNativePort = null; +let activeTaskState = { + isProcessing: false, + type: null, + status: 'idle', + info: '', + current: 0, + total: 0, + file: null, + error: null +}; + +// Initialize task state from storage if present +chrome.storage.local.get(['activeTask', 'videoScanState', 'imageScanState'], (res) => { + if (res.activeTask) activeTaskState = res.activeTask; + if (res.videoScanState) videoScanState = res.videoScanState; + if (res.imageScanState) imageScanState = res.imageScanState; +}); + +function updateTaskState(newState) { + activeTaskState = { ...activeTaskState, ...newState }; + chrome.storage.local.set({ activeTask: activeTaskState }).catch(() => {}); + chrome.runtime.sendMessage({ type: 'TASK_UPDATE', payload: activeTaskState }).catch(() => {}); +} + +function runNativeTask(msg, sendResponse) { + if (activeTaskState.isProcessing) { + if (sendResponse) sendResponse({ success: false, message: 'Un proceso ya está en ejecución' }); + return; + } + + updateTaskState({ + isProcessing: true, + type: msg.type, + status: 'started', + info: 'Iniciando conexión con Python...', + current: 0, + total: 0, + file: null, + error: null + }); + + try { + if (activeNativePort) { + try { activeNativePort.disconnect(); } catch (e) {} + activeNativePort = null; + } + + activeNativePort = chrome.runtime.connectNative("com.linkdetector.kemono"); + + activeNativePort.onMessage.addListener((nativeMsg) => { + if (nativeMsg.status === "progress") { + let infoStr = nativeMsg.info; + if (!infoStr && nativeMsg.current) { + infoStr = `Procesando ${nativeMsg.current}/${nativeMsg.total || '?'}`; + } + updateTaskState({ + status: "progress", + current: nativeMsg.current || 0, + total: nativeMsg.total || 0, + info: infoStr || "Procesando en segundo plano..." + }); + } else if (nativeMsg.status === "done") { + updateTaskState({ + isProcessing: false, + status: "done", + info: nativeMsg.file ? `¡Guardado en ${nativeMsg.file}!` : "¡Completado exitosamente!", + file: nativeMsg.file + }); + try { activeNativePort.disconnect(); } catch (e) {} + activeNativePort = null; + } else if (nativeMsg.status === "error") { + updateTaskState({ + isProcessing: false, + status: "error", + error: nativeMsg.message || "Error en proceso Python", + info: "Error: " + (nativeMsg.message || "Error en Python") + }); + try { activeNativePort.disconnect(); } catch (e) {} + activeNativePort = null; + } + }); + + activeNativePort.onDisconnect.addListener(() => { + let errMsg = chrome.runtime.lastError ? chrome.runtime.lastError.message : "Desconectado de Host"; + if (activeTaskState.isProcessing) { + updateTaskState({ + isProcessing: false, + status: "error", + error: errMsg, + info: errMsg.includes("host not found") ? "No se encontró el Host de Python. Ejecuta instalar_python_host.bat" : ("Conexión cerrada: " + errMsg) + }); + } + activeNativePort = null; + }); + + // Obtener cookies de kemono.cr, kemono.su y pawchive.st para pasarlas a Python + chrome.cookies.getAll({ domain: "kemono.cr" }, (cookiesCR) => { + chrome.cookies.getAll({ domain: "kemono.su" }, (cookiesSU) => { + chrome.cookies.getAll({ domain: "pawchive.st" }, (cookiesPawchive) => { + let allCookies = [...cookiesCR, ...cookiesSU, ...cookiesPawchive]; + let cookieStr = allCookies.map(c => c.name + "=" + c.value).join("; "); + let ua = navigator.userAgent; + + msg.cookies = cookieStr; + msg.userAgent = ua; + + if (activeNativePort) { + activeNativePort.postMessage(msg); + if (sendResponse) sendResponse({ success: true, state: activeTaskState }); + } + }); + }); + }); + } catch (e) { + updateTaskState({ + isProcessing: false, + status: "error", + error: e.message, + info: "Error: " + e.message + }); + if (sendResponse) sendResponse({ success: false, error: e.message }); + } +} + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.type === 'GET_STATE') { + sendResponse({ video: videoScanState, image: imageScanState, activeTask: activeTaskState }); + return true; + } + + if (message.type === 'START_NATIVE_TASK') { + runNativeTask(message.payload, sendResponse); + return true; + } + + if (message.type === 'GET_TASK_STATE') { + sendResponse(activeTaskState); + return true; + } + + if (message.type === 'FETCH_SURRIT') { + fetch(message.url, { + headers: { + 'Referer': message.referer || 'https://surrit.store/', + 'Origin': 'https://surrit.store' + } + }) + .then(res => { + if (!res.ok) throw new Error('HTTP status ' + res.status); + return res.json(); + }) + .then(data => sendResponse({ success: true, data })) + .catch(err => sendResponse({ success: false, error: err.message })); + return true; + } + + if (message.type === 'START_SCAN') { + if (!videoScanState.isScanning) { + startScan(message.payload.albumUrls, message.payload.currentVideos); + } + sendResponse(videoScanState); + return true; + } + + if (message.type === 'RESET_SCAN') { + if (!videoScanState.isScanning) { + videoScanState = { + isScanning: false, + scannedCount: 0, + totalCount: 0, + foundUrls: [], + albumUrls: [], + error: null + }; + chrome.storage.local.set({ videoScanState }); + } + sendResponse(videoScanState); + return true; + } + + if (message.type === 'START_IMAGE_SCAN') { + if (!imageScanState.isScanning) { + startImageScan(message.payload.albumUrls, message.payload.currentImages); + } + sendResponse(imageScanState); + return true; + } + + if (message.type === 'RESET_IMAGE_SCAN') { + if (!imageScanState.isScanning) { + imageScanState = { + isScanning: false, + scannedCount: 0, + totalCount: 0, + foundUrls: [], + albumUrls: [], + error: null + }; + chrome.storage.local.set({ imageScanState }); + } + sendResponse(imageScanState); + return true; + } +}); + +async function startScan(albumUrls, initialVideos) { + videoScanState.isScanning = true; + videoScanState.albumUrls = albumUrls; + videoScanState.totalCount = albumUrls.length; + videoScanState.scannedCount = 0; + videoScanState.foundUrls = Array.from(new Set(initialVideos || [])); + videoScanState.error = null; + + chrome.storage.local.set({ videoScanState }); + chrome.runtime.sendMessage({ type: 'SCAN_UPDATE', payload: videoScanState }).catch(() => {}); + + for (const url of albumUrls) { + videoScanState.scannedCount++; + try { + let res = await fetch(url); + let text = await res.text(); + + let newUrls = new Set(); + let srcMatches = text.matchAll(/src=["'](https?:\/\/[^"'\s]+\.mp4)['"]/gi); + for (const match of srcMatches) { + newUrls.add(match[1]); + } + + let hrefMatches = text.matchAll(/href=["'](https?:\/\/[^"'\s]+\.mp4)['"]/gi); + for (const match of hrefMatches) { + newUrls.add(match[1]); + } + + for (const u of newUrls) { + if (!videoScanState.foundUrls.includes(u)) { + videoScanState.foundUrls.push(u); + } + } + } catch (e) { + console.error("Error fetching album", url, e); + } + + chrome.storage.local.set({ videoScanState }); + chrome.runtime.sendMessage({ type: 'SCAN_UPDATE', payload: videoScanState }).catch(() => {}); + } + + videoScanState.isScanning = false; + chrome.storage.local.set({ videoScanState }); + chrome.runtime.sendMessage({ type: 'SCAN_UPDATE', payload: videoScanState }).catch(() => {}); +} + +async function startImageScan(albumUrls, initialImages) { + imageScanState.isScanning = true; + imageScanState.albumUrls = albumUrls; + imageScanState.totalCount = albumUrls.length; + imageScanState.scannedCount = 0; + imageScanState.foundUrls = Array.from(new Set(initialImages || [])); + imageScanState.error = null; + + chrome.storage.local.set({ imageScanState }); + chrome.runtime.sendMessage({ type: 'IMAGE_SCAN_UPDATE', payload: imageScanState }).catch(() => {}); + + for (const url of albumUrls) { + imageScanState.scannedCount++; + const albumMatch = url.match(/erome\.com\/a\/([a-zA-Z0-9]+)/); + const albumId = albumMatch ? albumMatch[1] : null; + + try { + let res = await fetch(url); + let text = await res.text(); + + let newUrls = new Set(); + let imgMatches = text.matchAll(/https?:\/\/[a-z0-9\.]*erome\.com\/[^"'\s\)]+\.(?:jpg|jpeg|png|webp)(?:\?[^"'\s\)]+)?/gi); + for (const match of imgMatches) { + const imgUrl = match[0]; + if (isAlbumImageUrl(imgUrl)) { + if (albumId && imgUrl.toLowerCase().includes('/' + albumId.toLowerCase() + '/')) { + newUrls.add(imgUrl); + } + } + } + + for (const u of newUrls) { + if (!imageScanState.foundUrls.includes(u)) { + imageScanState.foundUrls.push(u); + } + } + } catch (e) { + console.error("Error fetching album", url, e); + } + + chrome.storage.local.set({ imageScanState }); + chrome.runtime.sendMessage({ type: 'IMAGE_SCAN_UPDATE', payload: imageScanState }).catch(() => {}); + } + + imageScanState.isScanning = false; + chrome.storage.local.set({ imageScanState }); + chrome.runtime.sendMessage({ type: 'IMAGE_SCAN_UPDATE', payload: imageScanState }).catch(() => {}); +} + +// Proxy for Native Messaging (content scripts -> native host) +chrome.runtime.onConnect.addListener((port) => { + if (port.name === "kemono-native-proxy") { + const messageListener = (msg) => { + if (msg.type === "EXTRACT_KEMONO" || msg.type === "SAVE_KEMONO" || msg.type === "DOWNLOAD_IMAGES_KEMONO") { + runNativeTask(msg); + } + }; + port.onMessage.addListener(messageListener); + + const updateListener = (msg) => { + if (msg.type === "TASK_UPDATE") { + try { port.postMessage(msg.payload); } catch (e) {} + } + }; + chrome.runtime.onMessage.addListener(updateListener); + + port.onDisconnect.addListener(() => { + chrome.runtime.onMessage.removeListener(updateListener); + // DO NOT DISCONNECT activeNativePort HERE! Let native task complete in background! + }); + } +}); diff --git a/detector de enlaces - copia/host/__pycache__/kemono_host.cpython-311.pyc b/detector de enlaces - copia/host/__pycache__/kemono_host.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5797657fd0c9f4c46915906ad8dc772307e3873c Binary files /dev/null and b/detector de enlaces - copia/host/__pycache__/kemono_host.cpython-311.pyc differ diff --git a/detector de enlaces - copia/host/com.linkdetector.kemono.json b/detector de enlaces - copia/host/com.linkdetector.kemono.json new file mode 100644 index 0000000000000000000000000000000000000000..534c7a854716deb7962d35fae4d9ef1a3c7bb0d6 --- /dev/null +++ b/detector de enlaces - copia/host/com.linkdetector.kemono.json @@ -0,0 +1,9 @@ +{ + "name": "com.linkdetector.kemono", + "description": "Extractor de enlaces de Kemono", + "path": "C:\\Users\\Gonzalo\\Desktop\\extesione sherrameitnas\\detector de enlaces - copia\\host\\kemono_host.bat", + "type": "stdio", + "allowed_origins": [ + "chrome-extension://nonloheakmkaplfdedilgmlkdhohfnbc/" + ] +} diff --git a/detector de enlaces - copia/host/kemono_host.bat b/detector de enlaces - copia/host/kemono_host.bat new file mode 100644 index 0000000000000000000000000000000000000000..f4962e53ff60b59b126388cd2cbb8fa706275f56 --- /dev/null +++ b/detector de enlaces - copia/host/kemono_host.bat @@ -0,0 +1,6 @@ +@echo off +pip show cloudscraper >nul 2>&1 +if errorlevel 1 ( + pip install cloudscraper +) +python "%~dp0kemono_host.py" %* diff --git a/detector de enlaces - copia/host/kemono_host.py b/detector de enlaces - copia/host/kemono_host.py new file mode 100644 index 0000000000000000000000000000000000000000..4534d8fa7b55d9a567f14e3469807e6907f90f4b --- /dev/null +++ b/detector de enlaces - copia/host/kemono_host.py @@ -0,0 +1,285 @@ +import sys +import json +import struct +import os +import time +import urllib.parse +import urllib.request +import re +try: + import cloudscraper +except ImportError: + cloudscraper = None +import concurrent.futures +import threading + +def get_message(): + raw_length = sys.stdin.buffer.read(4) + if len(raw_length) == 0: + return None + message_length = struct.unpack('@I', raw_length)[0] + message = sys.stdin.buffer.read(message_length).decode('utf-8') + return json.loads(message) + +def encode_message(message_content): + encoded_content = json.dumps(message_content).encode('utf-8') + encoded_length = struct.pack('@I', len(encoded_content)) + return {'length': encoded_length, 'content': encoded_content} + +def send_message(message_content): + encoded = encode_message(message_content) + sys.stdout.buffer.write(encoded['length']) + sys.stdout.buffer.write(encoded['content']) + sys.stdout.buffer.flush() + +def extract_links(urls, cookie_str, user_agent): + desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') + output_file = os.path.join(desktop, 'kemono_downloads_extraidos.txt') + + send_message({"status": "started", "total": len(urls)}) + + unique_urls = list(set([u.rstrip('/') for u in urls])) + + count = 0 + scraper = cloudscraper.create_scraper(browser={'browser': 'chrome', 'platform': 'windows', 'desktop': True}) if cloudscraper else None + + with open(output_file, 'a', encoding='utf-8') as f: + f.write("\n=========================================\n") + f.write(f"NUEVA EXTRACCION - {time.strftime('%Y-%m-%d %H:%M:%S')}\n") + f.write("=========================================\n\n") + + # Configurar headers exactos del navegador Chrome del usuario + headers = { + 'User-Agent': user_agent or 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + 'Cookie': cookie_str or '', + 'Accept': 'application/json, text/plain, */*' + } + + for url in unique_urls: + count += 1 + try: + parsed = urllib.parse.urlparse(url) + api_path = '/api/v1' + parsed.path + api_url = f"{parsed.scheme}://{parsed.netloc}{api_path}" + + if scraper: + response = scraper.get(api_url, headers=headers) + response.raise_for_status() + data = response.json() + else: + req = urllib.request.Request(api_url, headers=headers) + with urllib.request.urlopen(req) as response: + data = json.loads(response.read().decode()) + + post_data = data.get('post', data) + title = post_data.get('title', 'Desconocido').strip() + author = post_data.get('user', 'Desconocido') + + download_links = [] + + def is_image(name): + return bool(re.search(r'\.(jpg|jpeg|png|webp|gif|avif)$', name or '', re.I)) + + def construct_link(file_obj): + if not file_obj or not file_obj.get('path'): return None + path = file_obj['path'] + if not path.startswith('http') and not path.startswith('/data'): + path = '/data' + ('' if path.startswith('/') else '/') + path + link = path if path.startswith('http') else f"{parsed.scheme}://{parsed.netloc}{path}" + if file_obj.get('name'): + link += f"?f={urllib.parse.quote(file_obj['name'])}" + return link + + # Main file + if post_data.get('file') and post_data['file'].get('path'): + if not is_image(post_data['file'].get('name')): + lk = construct_link(post_data['file']) + if lk: download_links.append(lk) + + # Attachments + attachs = post_data.get('attachments', []) or data.get('attachments', []) + for att in attachs: + if not is_image(att.get('name')): + lk = construct_link(att) + if lk: download_links.append(lk) + + # Content links + content = post_data.get('content', '') + if content: + # Find all links in href="..." or basic urls + hrefs = re.findall(r'href=["\'](https?://[^"\']+)["\']', content) + urls_in_text = re.findall(r'(https?://[^\s<"\'\)]+)', content) + for u in set(hrefs + urls_in_text): + if ('kemono.cr' not in u and 'kemono.su' not in u and 'pawchive.st' not in u) or '/downloads' in u or '/data/' in u: + download_links.append(u) + + download_links = list(set(download_links)) + + post_text = f"Titulo: {title}\nEnlace original: {url}\nAutor: {author}\nEnlaces de descarga:\n" + if download_links: + for idx, link in enumerate(download_links, 1): + post_text += f"({idx}) {link}\n" + else: + post_text += "No hay enlaces\n" + post_text += "\n" + + f.write(post_text) + send_message({"status": "progress", "current": count, "total": len(unique_urls)}) + + time.sleep(1) # Be nice to the API + + except Exception as e: + f.write(f"ERROR: {url} -> {str(e)}\n\n") + send_message({"status": "progress", "current": count, "total": len(unique_urls), "error": str(e)}) + + send_message({"status": "done", "file": output_file}) + +def clean_filename(name): + """Remove invalid characters for Windows paths""" + return re.sub(r'[\\/:*?"<>|]', '', str(name)).strip() + +def download_kemono_images(posts, cookie_str, user_agent): + downloads_dir = os.path.join(os.environ['USERPROFILE'], 'Downloads') + base_dir = os.path.join(downloads_dir, 'Kemono Images') + os.makedirs(base_dir, exist_ok=True) + + send_message({"status": "started", "total": len(posts)}) + + scraper = cloudscraper.create_scraper(browser={'browser': 'chrome', 'platform': 'windows', 'desktop': True}) if cloudscraper else None + + headers = { + 'User-Agent': user_agent or 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + 'Cookie': cookie_str or '', + 'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8' + } + + total_images_all = sum(len(post.get('images', [])) for post in posts) + images_downloaded = 0 + lock = threading.Lock() + + def download_image(img_info): + nonlocal images_downloaded + + post = img_info['post'] + idx = img_info['idx'] + img_url = img_info['url'] + post_dir = img_info['dir'] + title_clean = img_info['title'] + + try: + if not img_url.startswith('http'): + parsed = urllib.parse.urlparse(post.get('url')) + img_url = f"{parsed.scheme}://{parsed.netloc}{img_url}" + + extMatch = re.search(r'\.(jpg|jpeg|png|webp|gif|avif)', img_url, re.I) + ext = extMatch.group(0).lower() if extMatch else '.jpg' + + filename = f"img_{idx:03d}{ext}" + filepath = os.path.join(post_dir, filename) + + if not os.path.exists(filepath): + if scraper: + response = scraper.get(img_url, headers=headers, stream=True) + response.raise_for_status() + with open(filepath, 'wb') as f: + for chunk in response.iter_content(chunk_size=8192): + if chunk: f.write(chunk) + else: + req = urllib.request.Request(img_url, headers=headers) + with urllib.request.urlopen(req) as response, open(filepath, 'wb') as out_file: + while True: + chunk = response.read(65536) + if not chunk: break + out_file.write(chunk) + except Exception: + pass + + with lock: + images_downloaded += 1 + if images_downloaded % 2 == 0 or images_downloaded == total_images_all: + send_message({"status": "progress", "current": images_downloaded, "total": total_images_all, "info": f"Descargando {images_downloaded}/{total_images_all}..."}) + + tasks = [] + for post in posts: + author_clean = clean_filename(post.get('author', 'Unknown Author')) + title_clean = clean_filename(post.get('title', 'Unknown Title')) + + url = post.get('url', '') + post_id = url.rstrip('/').split('/')[-1] if '/' in url else '' + if post_id and post_id.isdigit(): + title_clean = f"{title_clean} [{post_id}]" + + is_duplicate = post.get('isDuplicate', False) + base_target_dir = os.path.join(base_dir, 'Duplicados') if is_duplicate else base_dir + + dup_idx = post.get('dupIndex') + if dup_idx: + title_clean = f"{title_clean} (Repetido {dup_idx})" + + post_dir = os.path.join(base_target_dir, author_clean, title_clean) + os.makedirs(post_dir, exist_ok=True) + + images = post.get('images', []) + for idx, img_url in enumerate(images, 1): + tasks.append({ + 'post': post, + 'idx': idx, + 'url': img_url, + 'dir': post_dir, + 'title': title_clean + }) + + with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor: + executor.map(download_image, tasks) + + send_message({"status": "done", "file": base_dir}) + +def get_unique_filename(filepath): + if not os.path.exists(filepath): + return filepath + dir_name, file_name = os.path.split(filepath) + name, ext = os.path.splitext(file_name) + counter = 1 + while True: + new_name = f"{name} ({counter}){ext}" + new_path = os.path.join(dir_name, new_name) + if not os.path.exists(new_path): + return new_path + counter += 1 + +if __name__ == '__main__': + while True: + try: + msg = get_message() + if msg and msg.get('type') == 'EXTRACT_KEMONO': + extract_links(msg.get('urls', []), msg.get('cookies'), msg.get('userAgent')) + elif msg and msg.get('type') == 'SAVE_KEMONO': + text_links = msg.get('textLinks', '') + text_no_links = msg.get('textNoLinks', '') + + downloads_dir = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Downloads') + base_links = os.path.join(downloads_dir, 'kemono_con_descargas.txt') + base_no_links = os.path.join(downloads_dir, 'kemono_sin_descargas.txt') + + try: + if text_links: + final_links = get_unique_filename(base_links) + with open(final_links, 'w', encoding='utf-8') as f: + f.write(text_links) + if text_no_links: + final_no_links = get_unique_filename(base_no_links) + with open(final_no_links, 'w', encoding='utf-8') as f: + f.write(text_no_links) + + send_message({"status": "done", "file": "Descargas"}) + except Exception as e: + send_message({"status": "error", "message": str(e)}) + elif msg and msg.get('type') == 'DOWNLOAD_IMAGES_KEMONO': + download_kemono_images(msg.get('data', []), msg.get('cookies'), msg.get('userAgent')) + elif msg: + send_message({"status": "error", "message": "Unknown command"}) + else: + break + except Exception as e: + send_message({"status": "error", "message": str(e)}) + break diff --git a/detector de enlaces - copia/inject.py b/detector de enlaces - copia/inject.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac826ee87f441f3c537ceea5d73d092b64d9f73 --- /dev/null +++ b/detector de enlaces - copia/inject.py @@ -0,0 +1,135 @@ +import json +import re + +with open('popup.js', 'r', encoding='utf-8') as f: + content = f.read() + +start_idx = content.find(' // Toggle Logic para Kemono Descargas') +end_idx = content.find(' // Toggle Logic para Facebook') + +if start_idx != -1 and end_idx != -1: + downloads_block = content[start_idx:end_idx] + + images_block = downloads_block.replace('toggleKemonoDownloads', 'toggleKemonoImages') + images_block = images_block.replace('__kemonoDownloadsActive', '__kemonoImagesActive') + images_block = images_block.replace('kemono-dl-', 'kemono-img-') + images_block = images_block.replace('#fbbf24', '#14b8a6') + images_block = images_block.replace('#f59e0b', '#0d9488') + images_block = images_block.replace('¡Guardado en Descargas!', '¡Enviado a Descargar Imágenes!') + + extraction_start = images_block.find('let outputWithLinks =') + extraction_end = images_block.find('document.body.removeChild(iframe);') + + new_extraction = '''let extractionPayload = []; + + 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)}%`; + + 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 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 + 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 (isImage(href) || isImage(name)) { + if (!href.startsWith('http')) href = new URL(href, url).href; + 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; + imageLinks.push(src); + } + }); + + imageLinks = [...new Set(imageLinks)]; + + if (imageLinks.length > 0) { + extractionPayload.push({ + url: url, + title: title, + author: author, + images: imageLinks + }); + + 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); + };''' + + images_block = images_block[:extraction_start] + new_extraction + images_block[extraction_end + len('document.body.removeChild(iframe);'):] + + images_block = images_block.replace('type: "SAVE_KEMONO"', 'type: "DOWNLOAD_IMAGES_KEMONO"') + images_block = re.sub(r'textLinks:.*,', 'data: extractionPayload', images_block) + images_block = re.sub(r'textNoLinks:.*', '', images_block) + + images_block = images_block.replace('// Toggle Logic para Kemono Descargas', '// Toggle Logic para Kemono Imagenes') + images_block = images_block.replace('Procesar Enlaces', 'Procesar Imágenes') + + new_content = content[:end_idx] + images_block + '\n' + content[end_idx:] + + with open('popup.js', 'w', encoding='utf-8') as f: + f.write(new_content) + + print("Injection successful.") +else: + print("Could not find blocks") diff --git a/detector de enlaces - copia/instalar_python_host.bat b/detector de enlaces - copia/instalar_python_host.bat new file mode 100644 index 0000000000000000000000000000000000000000..5bddcbc9a21f8245a7036aabd64226bc8406261d --- /dev/null +++ b/detector de enlaces - copia/instalar_python_host.bat @@ -0,0 +1,46 @@ +@echo off +setlocal +echo ======================================================== +echo INSTALADOR DEL HOST DE DESCARGAS DE KEMONO (PYTHON) +echo ======================================================== +echo. +echo Para que Chrome pueda conectar con el script de Python, +echo necesitamos el "ID" de tu extension. +echo. +echo 1. Abre Chrome y ve a chrome://extensions/ +echo 2. Busca "Detector de Enlaces Erome" +echo 3. Copia el ID (ejemplo: aabbccddeeffgghhiijjkkllmmnnoopp) +echo. +set /p EXT_ID="Pega el ID de la extension y presiona ENTER: " + +echo. +echo Creando manifest JSON para el host... + +set MANIFEST_PATH=%~dp0host\com.linkdetector.kemono.json +set BAT_PATH=%~dp0host\kemono_host.bat +set BAT_PATH=%BAT_PATH:\=\\% + +> "%MANIFEST_PATH%" echo { +>> "%MANIFEST_PATH%" echo "name": "com.linkdetector.kemono", +>> "%MANIFEST_PATH%" echo "description": "Extractor de enlaces de Kemono", +>> "%MANIFEST_PATH%" echo "path": "%BAT_PATH%", +>> "%MANIFEST_PATH%" echo "type": "stdio", +>> "%MANIFEST_PATH%" echo "allowed_origins": [ +>> "%MANIFEST_PATH%" echo "chrome-extension://%EXT_ID%/" +>> "%MANIFEST_PATH%" echo ] +>> "%MANIFEST_PATH%" echo } + +echo Archivo JSON creado en: %MANIFEST_PATH% +echo. +echo Registrando en Windows Registry... +REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.linkdetector.kemono" /ve /t REG_SZ /d "%MANIFEST_PATH%" /f + +echo. +echo ======================================================== +echo INSTALACION COMPLETADA +echo ======================================================== +echo Ya puedes usar la opcion de Extraer Descargas Kemono. +echo Los enlaces se guardaran automaticamente en tu Escritorio +echo en un archivo llamado "kemono_downloads_extraidos.txt". +echo. +pause diff --git a/detector de enlaces - copia/manifest.json b/detector de enlaces - copia/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7f3a473c1f71ec3f6cc9109e08f32bf797a7233e --- /dev/null +++ b/detector de enlaces - copia/manifest.json @@ -0,0 +1,41 @@ +{ + "manifest_version": 3, + "name": "Detector de Enlaces Erome", + "version": "1.3", + "description": "Extrae enlaces directos de video (.mp4) de la página actual y escanea álbumes a fondo en segundo plano.", + "permissions": ["activeTab", "scripting", "nativeMessaging", "cookies", "storage"], + "host_permissions": [ + "*://*.erome.com/*", + "*://*.facebook.com/*", + "*://*.tiktok.com/*", + "*://*.kemono.cr/*", + "*://*.kemono.su/*", + "*://*.pawchive.st/*", + "*://*.eporner.com/*", + "*://*.xhamster.com/*", + "*://*.ixxx.com/*", + "*://*.xhand.net/*", + "*://*.123av.com/*", + "*://*.123av.org/*", + "*://*.123av.me/*", + "*://*.missav.com/*", + "*://*.missav.ws/*", + "*://*.surrit.store/*", + "*://*.surrit.com/*", + "*://*.ladys.one/*", + "*://*.twpornstars.com/*", + "*://*.leakgallery.com/*", + "*://*.x.com/*", + "*://*.twitter.com/*", + "*://*.xvideos.com/*", + "*://*.xvideos.es/*", + "*://*.instagram.com/*", + "*://*.pornhub.com/*" + ], + "background": { + "service_worker": "background.js" + }, + "action": { + "default_popup": "popup.html" + } +} diff --git a/detector de enlaces - copia/popup.html b/detector de enlaces - copia/popup.html new file mode 100644 index 0000000000000000000000000000000000000000..27c474ce5e6ae9e9690a83c9a91434500532e8da --- /dev/null +++ b/detector de enlaces - copia/popup.html @@ -0,0 +1,866 @@ + + + + + + + + +
+
+

+ + + + + + + + + + + + LinkDetector +

+ +
+ +
+ + + +
+ + + + +
+
+
+
+ +
+
+
Modo Extractor Erome (Videos)
+
Extrae todos los videos de álbumes en Erome.
+
+
+ +
+ +
+ + +
+
+
+
+ +
+
+
Modo Extractor Erome (Imágenes)
+
Extrae todas las imágenes de álbumes en Erome.
+
+
+ +
+ +
+ + +
+
+
+
+ +
+
+
Modo Selector Kemono
+
Elige portadas interactivamente para copiar.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Extraer Descargas Kemono
+
Selecciona posts para extraer sus archivos (Zips, Mega, Drive).
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Extraer Imágenes Kemono
+
Extrae y descarga las imágenes en carpetas automáticamente.
+
+
+ +
+
+ + + +
+
+
+
+ +
+
+
Modo Selector Facebook
+
Selecciona o extrae reels y videos en lote.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Modo Selector TikTok
+
Selecciona videos interactivamente o escanea perfiles.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Modo Selector Eporner
+
Selecciona videos interactivamente y copia sus enlaces.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Modo Selector XHamster
+
Selecciona videos interactivamente y copia sus enlaces.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Modo Selector iXXX
+
Selecciona videos interactivamente y copia sus enlaces.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Modo Selector XHand
+
Selecciona videos interactivamente y copia sus enlaces.
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
Modo Selector JAV
+
Extrae enlaces HLS (.m3u8) de reproductores Surrit en 123AV y MissAV.
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + +
+ + + + diff --git a/detector de enlaces - copia/popup.js b/detector de enlaces - copia/popup.js new file mode 100644 index 0000000000000000000000000000000000000000..23e70815658a646e0a3e240ee699935991dbca2b --- /dev/null +++ b/detector de enlaces - copia/popup.js @@ -0,0 +1,2156 @@ +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 toggleEromeImages = document.getElementById('toggle-erome-images'); + 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 toggleEporner = document.getElementById('toggle-eporner'); + const toggleXhamster = document.getElementById('toggle-xhamster'); + const toggleIxxx = document.getElementById('toggle-ixxx'); + const toggleXhand = document.getElementById('toggle-xhand'); + const toggleJav = document.getElementById('toggle-jav'); + const containerVideo = document.getElementById('container-video'); + const containerEromeImages = document.getElementById('container-erome-images'); + const containerJav = document.getElementById('container-jav'); + + const cardVideo = document.getElementById('card-video'); + const cardEromeImages = document.getElementById('card-erome-images'); + 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 cardEporner = document.getElementById('card-eporner'); + const cardXhamster = document.getElementById('card-xhamster'); + const cardIxxx = document.getElementById('card-ixxx'); + const cardXhand = document.getElementById('card-xhand'); + const cardJav = document.getElementById('card-jav'); + const noToolsMsg = document.getElementById('no-tools-msg'); + + const statusEromeImages = document.getElementById('status-erome-images'); + const imageList = document.getElementById('image-list'); + const copyAllEromeImagesBtn = document.getElementById('copy-all-erome-images'); + const deepScanEromeImagesBtn = document.getElementById('deep-scan-erome-images'); + + const statusJav = document.getElementById('status-jav'); + const scanJavBtn = document.getElementById('scan-jav'); + const copyAllJavBtn = document.getElementById('copy-all-jav'); + const javList = document.getElementById('jav-list'); + + const toggleLadys = document.getElementById('toggle-ladys'); + const containerLadys = document.getElementById('container-ladys'); + const cardLadys = document.getElementById('card-ladys'); + const statusLadys = document.getElementById('status-ladys'); + const scanLadysBtn = document.getElementById('scan-ladys'); + const copyAllLadysBtn = document.getElementById('copy-all-ladys'); + const ladysList = document.getElementById('ladys-list'); + + const toggleTWPornstars = document.getElementById('toggle-twpornstars'); + const containerTWPornstars = document.getElementById('container-twpornstars'); + const cardTWPornstars = document.getElementById('card-twpornstars'); + const statusTWPornstars = document.getElementById('status-twpornstars'); + const scanTWPornstarsBtn = document.getElementById('scan-twpornstars'); + const copyAllTWPornstarsBtn = document.getElementById('copy-all-twpornstars'); + const twpornstarsList = document.getElementById('twpornstars-list'); + const deepScanTWPornstarsBtn = document.getElementById('deep-scan-twpornstars'); + + const toggleLeakGallery = document.getElementById('toggle-leakgallery'); + const containerLeakGallery = document.getElementById('container-leakgallery'); + const cardLeakGallery = document.getElementById('card-leakgallery'); + const statusLeakGallery = document.getElementById('status-leakgallery'); + const scanLeakGalleryBtn = document.getElementById('scan-leakgallery'); + const copyAllLeakGalleryBtn = document.getElementById('copy-all-leakgallery'); + const leakgalleryList = document.getElementById('leakgallery-list'); + + const toggleXvideos = document.getElementById('toggle-xvideos'); + const cardXvideos = document.getElementById('card-xvideos'); + + const togglePornhub = document.getElementById('toggle-pornhub'); + const cardPornhub = document.getElementById('card-pornhub'); + + const toggleInstagram = document.getElementById('toggle-instagram'); + const cardInstagram = document.getElementById('card-instagram'); + + const toggleX = document.getElementById('toggle-x'); + const cardX = document.getElementById('card-x'); + + function saveSiteState() { + const lists = { + videoListHTML: list ? list.innerHTML : '', + imageListHTML: imageList ? imageList.innerHTML : '', + javListHTML: javList ? javList.innerHTML : '', + ladysListHTML: ladysList ? ladysList.innerHTML : '', + twpornstarsListHTML: twpornstarsList ? twpornstarsList.innerHTML : '', + leakgalleryListHTML: leakgalleryList ? leakgalleryList.innerHTML : '' + }; + + const countBadgeText = countBadge ? countBadge.textContent : ''; + const countBadgeVisible = countBadge ? countBadge.style.display : 'none'; + + chrome.storage.local.set({ + popupLists: lists, + countBadgeText: countBadgeText, + countBadgeVisible: countBadgeVisible + }).catch(() => {}); + } + + function rebindCopyButtons(container) { + if (!container) return; + container.querySelectorAll('li').forEach(li => { + const urlEl = li.querySelector('.url'); + const link = urlEl ? urlEl.textContent : ''; + const btns = li.querySelectorAll('button'); + btns.forEach(btn => { + if (!btn.dataset.bound) { + btn.dataset.bound = "true"; + const originalHTML = btn.innerHTML; + btn.addEventListener('click', (e) => { + e.preventDefault(); + e.stopPropagation(); + if (link) { + navigator.clipboard.writeText(link); + btn.innerHTML = ' Copiado'; + btn.classList.add('success'); + setTimeout(() => { + btn.innerHTML = originalHTML; + btn.classList.remove('success'); + }, 1500); + } + }); + } + }); + }); + } + + function restoreSiteStates() { + chrome.storage.local.get(['popupLists', 'countBadgeText', 'countBadgeVisible'], (res) => { + + if (res.popupLists) { + if (res.popupLists.videoListHTML && list && res.popupLists.videoListHTML.trim()) { + list.innerHTML = res.popupLists.videoListHTML; + if (copyAllBtn) copyAllBtn.style.display = list.children.length > 0 ? 'flex' : 'none'; + if (deepScanBtn) deepScanBtn.style.display = list.children.length > 0 ? 'flex' : 'none'; + rebindCopyButtons(list); + } + if (res.popupLists.imageListHTML && imageList && res.popupLists.imageListHTML.trim()) { + imageList.innerHTML = res.popupLists.imageListHTML; + if (copyAllEromeImagesBtn) copyAllEromeImagesBtn.style.display = imageList.children.length > 0 ? 'flex' : 'none'; + if (deepScanEromeImagesBtn) deepScanEromeImagesBtn.style.display = imageList.children.length > 0 ? 'flex' : 'none'; + rebindCopyButtons(imageList); + } + if (res.popupLists.javListHTML && javList && res.popupLists.javListHTML.trim()) { + javList.innerHTML = res.popupLists.javListHTML; + if (copyAllJavBtn) copyAllJavBtn.style.display = javList.children.length > 0 ? 'flex' : 'none'; + rebindCopyButtons(javList); + } + if (res.popupLists.ladysListHTML && ladysList && res.popupLists.ladysListHTML.trim()) { + ladysList.innerHTML = res.popupLists.ladysListHTML; + if (copyAllLadysBtn) copyAllLadysBtn.style.display = ladysList.children.length > 0 ? 'flex' : 'none'; + rebindCopyButtons(ladysList); + } + if (res.popupLists.twpornstarsListHTML && twpornstarsList && res.popupLists.twpornstarsListHTML.trim()) { + twpornstarsList.innerHTML = res.popupLists.twpornstarsListHTML; + if (copyAllTWPornstarsBtn) copyAllTWPornstarsBtn.style.display = twpornstarsList.children.length > 0 ? 'flex' : 'none'; + rebindCopyButtons(twpornstarsList); + } + if (res.popupLists.leakgalleryListHTML && leakgalleryList && res.popupLists.leakgalleryListHTML.trim()) { + leakgalleryList.innerHTML = res.popupLists.leakgalleryListHTML; + if (copyAllLeakGalleryBtn) copyAllLeakGalleryBtn.style.display = leakgalleryList.children.length > 0 ? 'flex' : 'none'; + rebindCopyButtons(leakgalleryList); + } + } + + if (countBadge) { + if (res.countBadgeText) countBadge.textContent = res.countBadgeText; + if (res.countBadgeVisible) countBadge.style.display = res.countBadgeVisible; + } + }); + } + + document.querySelectorAll('input[type="checkbox"]').forEach(chk => { + chk.addEventListener('change', saveSiteState); + }); + + // 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.') || urlStr.includes('pawchive.st'); + let showFacebook = urlStr.includes('facebook.com'); + let showTiktok = urlStr.includes('tiktok.com'); + let showEporner = urlStr.includes('eporner.com'); + let showPornhub = urlStr.includes('pornhub.com'); + let showXhamster = urlStr.includes('xhamster.com'); + let showIxxx = urlStr.includes('ixxx.com'); + let showXhand = urlStr.includes('xhand.net'); + let showJav = urlStr.includes('123av.') || urlStr.includes('missav.'); + let showLadys = urlStr.includes('ladys.one'); + let showTWPornstars = urlStr.includes('twpornstars.com'); + let showLeakGallery = urlStr.includes('leakgallery.com'); + let showX = urlStr.includes('x.com') || urlStr.includes('twitter.com'); + let showXvideos = urlStr.includes('xvideos.com') || urlStr.includes('xvideos.es'); + let showInstagram = urlStr.includes('instagram.com'); + + cardVideo.style.display = showVideo ? 'block' : 'none'; + cardEromeImages.style.display = showVideo ? 'block' : 'none'; + cardKemono.style.display = showKemono ? 'block' : 'none'; + cardKemonoDownloads.style.display = showKemono ? 'block' : 'none'; + cardKemonoImages.style.display = showKemono ? 'block' : 'none'; + + if (showKemono) { + const siteName = urlStr.includes('pawchive.st') ? 'Pawchive' : 'Kemono'; + const titleSelector = cardKemono.querySelector('.tool-title'); + const titleDownloads = cardKemonoDownloads.querySelector('.tool-title'); + const titleImages = cardKemonoImages.querySelector('.tool-title'); + + if (titleSelector) titleSelector.textContent = `Modo Selector ${siteName}`; + if (titleDownloads) titleDownloads.textContent = `Extraer Descargas ${siteName}`; + if (titleImages) titleImages.textContent = `Extraer Imágenes ${siteName}`; + } + cardFacebook.style.display = showFacebook ? 'block' : 'none'; + cardTiktok.style.display = showTiktok ? 'block' : 'none'; + cardEporner.style.display = showEporner ? 'block' : 'none'; + cardPornhub.style.display = showPornhub ? 'block' : 'none'; + cardXhamster.style.display = showXhamster ? 'block' : 'none'; + cardIxxx.style.display = showIxxx ? 'block' : 'none'; + cardXhand.style.display = showXhand ? 'block' : 'none'; + cardJav.style.display = showJav ? 'block' : 'none'; + cardLadys.style.display = showLadys ? 'block' : 'none'; + cardTWPornstars.style.display = showTWPornstars ? 'block' : 'none'; + cardLeakGallery.style.display = showLeakGallery ? 'block' : 'none'; + cardX.style.display = showX ? 'block' : 'none'; + cardXvideos.style.display = showXvideos ? 'block' : 'none'; + cardInstagram.style.display = showInstagram ? 'block' : 'none'; + + if (!showVideo && !showKemono && !showFacebook && !showTiktok && !showEporner && !showPornhub && !showXhamster && !showIxxx && !showXhand && !showJav && !showLadys && !showTWPornstars && !showLeakGallery && !showX && !showXvideos && !showInstagram) { + noToolsMsg.style.display = 'flex'; + } + + if (showLadys) { + toggleLadys.checked = true; + containerLadys.style.display = 'block'; + performLadysScan(); + } + + if (showTWPornstars) { + toggleTWPornstars.checked = true; + containerTWPornstars.style.display = 'block'; + performTWPornstarsScan(); + } + + if (showLeakGallery) { + toggleLeakGallery.checked = true; + containerLeakGallery.style.display = 'block'; + performLeakGalleryScan(); + } + + // Sync XVideos toggle state if already active + if (showXvideos) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!(window.__xvideosSelectorActive && document.getElementById('xvideos-floating-ui')) + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleXvideos.checked = true; + } + }); + } + + // Sync Pornhub toggle state if already active + if (showPornhub) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('pornhub-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + togglePornhub.checked = true; + } else { + togglePornhub.checked = false; + } + }); + } + + // Sync Instagram toggle state if already active + if (showInstagram) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('instagram-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleInstagram.checked = true; + } else { + toggleInstagram.checked = false; + } + }); + } + + if (showX) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('x-extractor-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleX.checked = true; + } else { + toggleX.checked = false; + } + }); + } + + // Sync Kemono toggle state if already active + if (showKemono) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('kemono-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleKemono.checked = true; + } else { + toggleKemono.checked = false; + } + }); + + 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: () => !!document.getElementById('fb-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleFacebook.checked = true; + } else { + toggleFacebook.checked = false; + } + }); + } + // Sync TikTok toggle state if already active + if (showTiktok) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('tiktok-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleTiktok.checked = true; + } else { + toggleTiktok.checked = false; + } + }); + } + // Sync Eporner toggle state if already active + if (showEporner) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('eporner-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleEporner.checked = true; + } else { + toggleEporner.checked = false; + } + }); + } + // Sync XHamster toggle state if already active + if (showXhamster) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('xhamster-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleXhamster.checked = true; + } else { + toggleXhamster.checked = false; + } + }); + } + // Sync iXXX toggle state if already active + if (showIxxx) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('ixxx-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleIxxx.checked = true; + } else { + toggleIxxx.checked = false; + } + }); + } + // Sync XHand toggle state if already active + if (showXhand) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!document.getElementById('xhand-floating-ui') + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleXhand.checked = true; + } else { + toggleXhand.checked = false; + } + }); + } + // Sync JAV toggle state if already active + if (showJav) { + chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => !!window.__javSelectorActive + }, (results) => { + if (!chrome.runtime.lastError && results && results[0] && results[0].result === true) { + toggleJav.checked = true; + containerJav.style.display = 'block'; + performJavScan(); + } + }); + } + } + } catch (e) { + console.error("No se pudo filtrar por dominio", e); + } + + restoreSiteStates(); + + // 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 Erome/Imágenes + toggleEromeImages.addEventListener('change', () => { + if (toggleEromeImages.checked) { + containerEromeImages.style.display = 'block'; + if (imageList.children.length === 0 && (!statusEromeImages.innerHTML.includes('Escaneando álbum') && !statusEromeImages.innerHTML.includes('Completada'))) { + performQuickScanForImages(); + } + } else { + containerEromeImages.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 }, + files: ['src/kemono/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleKemono.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-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 }, + files: ['src/kemono/downloads.js'] + }, (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 }, + files: ['src/kemono/images.js'] + }, (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 }, + files: ['src/facebook/selector.js'] + }, (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 }, + files: ['src/tiktok/selector.js'] + }, (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."); + } + }); + + // Toggle Logic para Eporner + toggleEporner.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleEporner.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleEporner.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/eporner/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleEporner.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('eporner-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + toggleEporner.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para XHamster + toggleXhamster.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleXhamster.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleXhamster.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/xhamster/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleXhamster.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('xh-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + toggleXhamster.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para iXXX + toggleIxxx.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleIxxx.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleIxxx.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/ixxx/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleIxxx.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('ixxx-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + toggleIxxx.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para XHand + toggleXhand.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleXhand.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleXhand.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/xhand/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleXhand.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('xhand-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + toggleXhand.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para JAV + toggleJav.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleJav.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleJav.checked) { + containerJav.style.display = 'block'; + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/jav/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + console.error("No se pudo inyectar el selector flotante:", chrome.runtime.lastError); + } + }); + + if (javList.children.length === 0 && !statusJav.innerHTML.includes('Escaneando')) { + performJavScan(); + } + } else { + containerJav.style.display = 'none'; + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('jav-close-btn'); + if (closeBtn) closeBtn.click(); + } + }).catch(() => {}); + } + } catch (err) { + console.error(err); + toggleJav.checked = false; + showError("Ocurrió un error."); + } + }); + + if (scanJavBtn) { + scanJavBtn.addEventListener('click', () => { + performJavScan(); + }); + } + + // Toggle Logic para Ladys.one + toggleLadys.addEventListener('change', () => { + if (toggleLadys.checked) { + containerLadys.style.display = 'block'; + if (ladysList.children.length === 0 && !statusLadys.innerHTML.includes('Escaneando')) { + performLadysScan(); + } + } else { + containerLadys.style.display = 'none'; + } + }); + + if (scanLadysBtn) { + scanLadysBtn.addEventListener('click', () => { + performLadysScan(); + }); + } + + // Toggle Logic para TWPornstars + toggleTWPornstars.addEventListener('change', () => { + if (toggleTWPornstars.checked) { + containerTWPornstars.style.display = 'block'; + if (twpornstarsList.children.length === 0 && !statusTWPornstars.innerHTML.includes('Escaneando')) { + performTWPornstarsScan(); + } + } else { + containerTWPornstars.style.display = 'none'; + } + }); + + if (scanTWPornstarsBtn) { + scanTWPornstarsBtn.addEventListener('click', () => { + performTWPornstarsScan(); + }); + } + + if (deepScanTWPornstarsBtn) { + deepScanTWPornstarsBtn.addEventListener('click', () => { + const baseUrl = deepScanTWPornstarsBtn.dataset.baseUrl; + const maxPage = parseInt(deepScanTWPornstarsBtn.dataset.maxPage, 10); + if (baseUrl && maxPage > 1) { + performTWPornstarsDeepScan(baseUrl, maxPage); + } + }); + } + + // Toggle Logic para LeakGallery + toggleLeakGallery.addEventListener('change', () => { + if (toggleLeakGallery.checked) { + containerLeakGallery.style.display = 'block'; + if (leakgalleryList.children.length === 0 && !statusLeakGallery.innerHTML.includes('Escaneando')) { + performLeakGalleryScan(); + } + } else { + containerLeakGallery.style.display = 'none'; + } + }); + + if (scanLeakGalleryBtn) { + scanLeakGalleryBtn.addEventListener('click', () => { + performLeakGalleryScan(); + }); + } + + // Toggle Logic para XVideos + toggleXvideos.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleXvideos.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleXvideos.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/xvideos/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleXvideos.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('xvideos-close-btn'); + if (closeBtn) closeBtn.click(); + } + }).catch(() => {}); + } + saveSiteState(); + } catch (err) { + console.error(err); + toggleXvideos.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para Pornhub + togglePornhub.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + togglePornhub.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (togglePornhub.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/pornhub/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + togglePornhub.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('pornhub-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + togglePornhub.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para Instagram + toggleInstagram.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleInstagram.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleInstagram.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/instagram/selector.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleInstagram.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('instagram-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + toggleInstagram.checked = false; + showError("Ocurrió un error."); + } + }); + + // Toggle Logic para X (Twitter) + toggleX.addEventListener('change', async () => { + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + toggleX.checked = false; + showError("No se puede inyectar en esta página."); + return; + } + + if (toggleX.checked) { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/x/auto_extractor.js'] + }, (results) => { + if (chrome.runtime.lastError) { + toggleX.checked = false; + showError("No se pudo inyectar el código."); + } + }); + } else { + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + const closeBtn = document.getElementById('x-close-btn'); + if (closeBtn) closeBtn.click(); + } + }); + } + } catch (err) { + console.error(err); + toggleX.checked = false; + showError("Ocurrió un error."); + } + }); + + async function performJavScan() { + statusJav.style.display = 'flex'; + statusJav.innerHTML = 'Buscando reproductor JAV...'; + + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + showJavError("No se puede escanear esta página."); + return; + } + + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + func: () => { + try { + const html = document.documentElement.outerHTML; + const url = window.location.href; + const title = document.title.replace(/\s*-\s*MissAV\.ws/gi, '') + .replace(/\s*-\s*MissAV/gi, '') + .replace(/\s*—\s*123AV/gi, '') + .replace(/\s*-\s*123AV/gi, '') + .trim(); + + // 1. Intentar player(JSON.parse(...)) para 123AV + const match123 = html.match(/player\(JSON\.parse\('([^']+)'\)/); + if (match123) { + let rawJson = match123[1]; + let jsonStr = rawJson.replace(/\\"/g, '"').replace(/\\\//g, '/'); + jsonStr = jsonStr.replace(/\\u([0-9a-fA-F]{4})/g, (m, grp) => String.fromCharCode(parseInt(grp, 16))); + const playerData = JSON.parse(jsonStr); + for (const item of playerData) { + if (item.url && item.url.includes('surrit.')) { + return { type: '123av', surritUrl: item.url, title, originUrl: url }; + } + } + } + + // 2. Intentar packer de MissAV + const splitMatch = html.match(/'([^']+)'\.split\('\|'\)/); + if (splitMatch) { + const words = splitMatch[1].split('|'); + const pMatch = html.match(/\}\('(.*?)', *\d+, *\d+,/); + if (pMatch) { + let p = pMatch[1]; + function base36(i) { return i.toString(36); } + for (let i = words.length - 1; i >= 0; i--) { + const word = words[i]; + if (word) { + const idx = base36(i); + const regex = new RegExp('\\b' + idx + '\\b', 'g'); + p = p.replace(regex, word); + } + } + const m3u8Links = p.match(/https?:\/\/surrit\.com[^\s'"]+\.m3u8/); + if (m3u8Links) { + return { type: 'missav', m3u8Url: m3u8Links[0], title, originUrl: url }; + } + } + } + + // 3. Regex simple para surrit.com + const m3u8Matches = html.match(/https?:\/\/surrit\.com\/[a-zA-Z0-9-]+\/[^\s'"]+\.m3u8/); + if (m3u8Matches) { + return { type: 'missav', m3u8Url: m3u8Matches[0], title, originUrl: url }; + } + + // 4. Buscar en DOM + const sources = Array.from(document.querySelectorAll('video, source, iframe')); + for (const srcEl of sources) { + const src = srcEl.src || srcEl.getAttribute('src'); + if (src && (src.includes('surrit.com') || src.includes('surrit.store')) && src.includes('.m3u8')) { + return { type: 'missav', m3u8Url: src, title, originUrl: url }; + } + } + } catch (e) { + console.error(e); + } + return null; + } + }, async (results) => { + if (chrome.runtime.lastError || !results || !results[0] || !results[0].result) { + showJavError("No se detectó ningún reproductor JAV de Surrit en la página."); + return; + } + + const res = results[0].result; + let m3u8Url = null; + + if (res.type === '123av' && res.surritUrl) { + statusJav.innerHTML = 'Obteniendo stream de Surrit API...'; + try { + const urlObj = new URL(res.surritUrl); + const videoId = urlObj.pathname.split('/').pop(); + const poster = urlObj.searchParams.get('poster') || ''; + const streamApiUrl = `https://surrit.store/stream?id=${videoId}&poster=${encodeURIComponent(poster)}`; + + const apiResponse = await new Promise((resolve) => { + chrome.runtime.sendMessage({ + type: 'FETCH_SURRIT', + url: streamApiUrl, + referer: res.surritUrl + }, (resp) => { + resolve(resp); + }); + }); + + if (apiResponse && apiResponse.success && apiResponse.data) { + m3u8Url = apiResponse.data.media?.stream; + } + } catch (err) { + console.error("Error fetching surrit stream info:", err); + } + } else if (res.type === 'missav' && res.m3u8Url) { + m3u8Url = res.m3u8Url; + } + + if (m3u8Url) { + statusJav.style.display = 'none'; + renderJavList([{ + title: res.title, + m3u8Url: m3u8Url, + originUrl: res.originUrl + }]); + } else { + showJavError("No se pudo resolver el stream de Surrit."); + } + }); + } catch (err) { + console.error(err); + showJavError("Error al escanear."); + } + } + + function showJavError(msg) { + statusJav.style.display = 'flex'; + statusJav.innerHTML = `${msg}`; + } + + function renderJavList(videos) { + javList.innerHTML = ''; + if (videos && videos.length > 0) { + copyAllJavBtn.style.display = 'flex'; + copyAllJavBtn.onclick = () => { + const allLinks = videos.map(v => v.m3u8Url).join('\n'); + navigator.clipboard.writeText(allLinks); + copyAllJavBtn.innerHTML = ' ¡Todos copiados!'; + copyAllJavBtn.classList.add('success'); + setTimeout(() => { + copyAllJavBtn.innerHTML = ' Copiar Todos'; + copyAllJavBtn.classList.remove('success'); + }, 2000); + }; + + videos.forEach((video) => { + const li = document.createElement('li'); + + const titleEl = document.createElement('div'); + titleEl.style.cssText = 'font-weight: 600; font-size: 13px; color: #fff; margin-bottom: 5px;'; + titleEl.textContent = video.title; + li.appendChild(titleEl); + + const urlContainer = document.createElement('div'); + urlContainer.className = 'url-container'; + urlContainer.style.marginBottom = '8px'; + + const urlStr = document.createElement('div'); + urlStr.className = 'url'; + urlStr.textContent = video.m3u8Url; + urlStr.title = video.m3u8Url; + + urlContainer.appendChild(urlStr); + li.appendChild(urlContainer); + + const btnGroup = document.createElement('div'); + btnGroup.style.cssText = 'display: flex; gap: 8px; width: 100%;'; + + const copyBtn = document.createElement('button'); + copyBtn.innerHTML = ' Enlace .m3u8'; + copyBtn.style.flex = '1'; + copyBtn.onclick = () => { + navigator.clipboard.writeText(video.m3u8Url); + copyBtn.innerHTML = ' Copiado'; + copyBtn.classList.add('success'); + setTimeout(() => { + copyBtn.innerHTML = ' Enlace .m3u8'; + copyBtn.classList.remove('success'); + }, 1500); + }; + btnGroup.appendChild(copyBtn); + + const copyCmdBtn = document.createElement('button'); + copyCmdBtn.innerHTML = ' Comando RE'; + copyCmdBtn.style.flex = '1'; + copyCmdBtn.onclick = () => { + const cleanTitle = video.title.replace(/["'\\]/g, ''); + let cmd = ''; + if (video.originUrl.includes('123av.')) { + cmd = `N_m3u8DL-RE "${video.m3u8Url}" -H "Referer: https://surrit.store/" --save-name "${cleanTitle}"`; + } else { + const referer = new URL(video.originUrl).origin + '/'; + cmd = `N_m3u8DL-RE "${video.m3u8Url}" -H "Referer: ${referer}" --save-name "${cleanTitle}"`; + } + navigator.clipboard.writeText(cmd); + copyCmdBtn.innerHTML = ' Copiado'; + copyCmdBtn.classList.add('success'); + setTimeout(() => { + copyCmdBtn.innerHTML = ' Comando RE'; + copyCmdBtn.classList.remove('success'); + }, 1500); + }; + btnGroup.appendChild(copyCmdBtn); + + li.appendChild(btnGroup); + javList.appendChild(li); + }); + } else { + copyAllJavBtn.style.display = 'none'; + } + saveSiteState(); + } + + async function performLadysScan() { + statusLadys.style.display = 'flex'; + statusLadys.innerHTML = 'Escaneando videos de Ladys.one...'; + + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + showLadysError("No se puede escanear esta página."); + return; + } + + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/ladys/quick_scan.js'] + }, (results) => { + if (chrome.runtime.lastError || !results || !results[0]) { + showLadysError("No se pudo inyectar el scanner. Verifica que la página cargó."); + return; + } + + const data = results[0].result; + if (data.error) { + showLadysError("Error: " + data.error); + return; + } + + renderLadysList(data.videos); + }); + } catch (err) { + console.error(err); + showLadysError("Error al escanear."); + } + } + + function showLadysError(msg) { + statusLadys.style.display = 'flex'; + statusLadys.innerHTML = `${msg}`; + } + + function renderLadysList(videos) { + ladysList.innerHTML = ''; + + if (videos && videos.length > 0) { + statusLadys.style.display = 'none'; + copyAllLadysBtn.style.display = 'flex'; + + copyAllLadysBtn.onclick = () => { + const allLinks = videos.map(v => v.videoUrl).join('\n'); + navigator.clipboard.writeText(allLinks); + copyAllLadysBtn.innerHTML = ' ¡Todos copiados!'; + copyAllLadysBtn.classList.add('success'); + setTimeout(() => { + copyAllLadysBtn.innerHTML = ' Copiar Todos'; + copyAllLadysBtn.classList.remove('success'); + }, 2000); + }; + + videos.forEach((video) => { + const li = document.createElement('li'); + + if (video.thumbnailUrl) { + const thumbImg = document.createElement('img'); + thumbImg.src = video.thumbnailUrl; + thumbImg.style.cssText = 'width: 100%; max-height: 180px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border); margin-bottom: 5px;'; + li.appendChild(thumbImg); + } + + const titleEl = document.createElement('div'); + titleEl.style.cssText = 'font-weight: 600; font-size: 13px; color: #fff; margin-bottom: 5px;'; + titleEl.textContent = video.title; + li.appendChild(titleEl); + + const urlContainer = document.createElement('div'); + urlContainer.className = 'url-container'; + urlContainer.style.marginBottom = '8px'; + + const urlStr = document.createElement('div'); + urlStr.className = 'url'; + urlStr.textContent = video.videoUrl; + urlStr.title = video.videoUrl; + + urlContainer.appendChild(urlStr); + li.appendChild(urlContainer); + + const copyBtn = document.createElement('button'); + copyBtn.innerHTML = ' Copiar Enlace Video'; + copyBtn.onclick = () => { + navigator.clipboard.writeText(video.videoUrl); + copyBtn.innerHTML = ' Copiado'; + copyBtn.classList.add('success'); + setTimeout(() => { + copyBtn.innerHTML = ' Copiar Enlace Video'; + copyBtn.classList.remove('success'); + }, 1500); + }; + li.appendChild(copyBtn); + ladysList.appendChild(li); + }); + } else { + statusLadys.style.display = 'flex'; + statusLadys.innerHTML = 'No se encontró ningún video en esta página. Si cargaste más videos, vuelve a activar el scanner.'; + } + saveSiteState(); + } + + async function performTWPornstarsScan() { + statusTWPornstars.style.display = 'flex'; + statusTWPornstars.innerHTML = 'Buscando posts de videos...'; + + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + showTWPornstarsError("No se puede escanear esta página."); + return; + } + + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/twpornstars/quick_scan.js'] + }, async (results) => { + if (chrome.runtime.lastError || !results || !results[0]) { + showTWPornstarsError("No se pudo inyectar el scanner. Verifica que la página cargó."); + return; + } + + const data = results[0].result; + if (data.error) { + showTWPornstarsError("Error: " + data.error); + return; + } + + const posts = data.videos || []; + if (posts.length === 0) { + showTWPornstarsError("No se encontraron posts de video en la página."); + return; + } + + statusTWPornstars.innerHTML = `Obteniendo enlaces directos (0/${posts.length})...`; + + const finalVideos = []; + let completed = 0; + + const fetchPromises = posts.map(async (post) => { + try { + const response = await fetch(post.postUrl); + const text = await response.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(text, 'text/html'); + const source = doc.querySelector('video source[type="video/mp4"]') || doc.querySelector('video source'); + + if (source && source.src) { + finalVideos.push({ + title: post.title, + videoUrl: source.src, + thumbnailUrl: post.thumbnailUrl, + postUrl: post.postUrl + }); + } + } catch (e) { + console.error("Error fetching detail for post", post.postUrl, e); + } finally { + completed++; + statusTWPornstars.innerHTML = `Obteniendo enlaces directos (${completed}/${posts.length})...`; + } + }); + + await Promise.all(fetchPromises); + renderTWPornstarsList(finalVideos); + + if (data.maxPage && data.maxPage > 1) { + deepScanTWPornstarsBtn.style.display = 'flex'; + deepScanTWPornstarsBtn.innerHTML = `🔍 Escanear todas las páginas (1-${data.maxPage})`; + deepScanTWPornstarsBtn.dataset.baseUrl = data.baseUrl; + deepScanTWPornstarsBtn.dataset.maxPage = data.maxPage; + } else { + deepScanTWPornstarsBtn.style.display = 'none'; + } + }); + } catch (err) { + console.error(err); + showTWPornstarsError("Error al escanear."); + } + } + + async function performTWPornstarsDeepScan(baseUrl, maxPage) { + deepScanTWPornstarsBtn.style.display = 'none'; + statusTWPornstars.style.display = 'flex'; + statusTWPornstars.innerHTML = `Escaneando páginas de posts (1/${maxPage})...`; + + try { + const allPosts = []; + const seenPostUrls = new Set(); + const pageUrls = []; + for (let i = 1; i <= maxPage; i++) { + pageUrls.push({ pageNum: i, url: `${baseUrl}?page=${i}` }); + } + + let pagesCompleted = 0; + const pageScanPromises = pageUrls.map(async (pageObj) => { + try { + const response = await fetch(pageObj.url); + const htmlText = await response.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(htmlText, 'text/html'); + + const thumbs = doc.querySelectorAll('.thumb[data-isvideo="1"], .thumb'); + thumbs.forEach(thumb => { + const isVideo = thumb.getAttribute('data-isvideo') === '1' || !!thumb.querySelector('.thumb__video_icon'); + if (!isVideo) return; + + const linkEl = thumb.querySelector('.thumb__link'); + const imgEl = thumb.querySelector('.thumb__img'); + const infoTextEl = thumb.querySelector('.thumb__info_text') || thumb.querySelector('.thumb__title'); + + if (linkEl && linkEl.href) { + let title = infoTextEl ? infoTextEl.textContent.trim() : ''; + if (!title && imgEl && imgEl.alt) { + title = imgEl.alt.trim(); + } + if (!title) { + title = "Video " + linkEl.href.split('/').pop(); + } + + let postUrl = linkEl.href; + if (postUrl.startsWith('/')) { + postUrl = window.location.origin + postUrl; + } + + if (!seenPostUrls.has(postUrl)) { + seenPostUrls.add(postUrl); + allPosts.push({ + title: title, + postUrl: postUrl, + thumbnailUrl: imgEl ? imgEl.src : '' + }); + } + } + }); + } catch (e) { + console.error("Error scanning page", pageObj.pageNum, e); + } finally { + pagesCompleted++; + statusTWPornstars.innerHTML = `Escaneando páginas de posts (${pagesCompleted}/${maxPage})...`; + } + }); + + await Promise.all(pageScanPromises); + + if (allPosts.length === 0) { + showTWPornstarsError("No se encontraron videos en ninguna página."); + return; + } + + statusTWPornstars.innerHTML = `Obteniendo enlaces directos (0/${allPosts.length})...`; + + const finalVideos = []; + let completed = 0; + const batchSize = 15; + + for (let i = 0; i < allPosts.length; i += batchSize) { + const batch = allPosts.slice(i, i + batchSize); + await Promise.all(batch.map(async (post) => { + try { + const response = await fetch(post.postUrl); + const text = await response.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(text, 'text/html'); + const source = doc.querySelector('video source[type="video/mp4"]') || doc.querySelector('video source'); + + if (source && source.src) { + finalVideos.push({ + title: post.title, + videoUrl: source.src, + thumbnailUrl: post.thumbnailUrl, + postUrl: post.postUrl + }); + } + } catch (e) { + console.error("Error fetching detail for post", post.postUrl, e); + } finally { + completed++; + statusTWPornstars.innerHTML = `Obteniendo enlaces directos (${completed}/${allPosts.length})...`; + } + })); + } + + renderTWPornstarsList(finalVideos); + } catch (err) { + console.error(err); + showTWPornstarsError("Error al escanear todas las páginas."); + } + } + + function showTWPornstarsError(msg) { + statusTWPornstars.style.display = 'flex'; + statusTWPornstars.innerHTML = `${msg}`; + } + + function renderTWPornstarsList(videos) { + twpornstarsList.innerHTML = ''; + + if (videos && videos.length > 0) { + statusTWPornstars.style.display = 'none'; + copyAllTWPornstarsBtn.style.display = 'flex'; + + copyAllTWPornstarsBtn.onclick = () => { + const allLinks = videos.map(v => v.videoUrl).join('\n'); + navigator.clipboard.writeText(allLinks); + copyAllTWPornstarsBtn.innerHTML = ' ¡Todos copiados!'; + copyAllTWPornstarsBtn.classList.add('success'); + setTimeout(() => { + copyAllTWPornstarsBtn.innerHTML = ' Copiar Todos'; + copyAllTWPornstarsBtn.classList.remove('success'); + }, 2000); + }; + + videos.forEach((video) => { + const li = document.createElement('li'); + + if (video.thumbnailUrl) { + const thumbImg = document.createElement('img'); + thumbImg.src = video.thumbnailUrl; + thumbImg.style.cssText = 'width: 100%; max-height: 180px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border); margin-bottom: 5px;'; + li.appendChild(thumbImg); + } + + const titleEl = document.createElement('div'); + titleEl.style.cssText = 'font-weight: 600; font-size: 13px; color: #fff; margin-bottom: 5px;'; + titleEl.textContent = video.title; + li.appendChild(titleEl); + + const urlContainer = document.createElement('div'); + urlContainer.className = 'url-container'; + urlContainer.style.marginBottom = '8px'; + + const urlStr = document.createElement('div'); + urlStr.className = 'url'; + urlStr.textContent = video.videoUrl; + urlStr.title = video.videoUrl; + + urlContainer.appendChild(urlStr); + li.appendChild(urlContainer); + + const copyBtn = document.createElement('button'); + copyBtn.innerHTML = ' Copiar Enlace Video'; + copyBtn.onclick = () => { + navigator.clipboard.writeText(video.videoUrl); + copyBtn.innerHTML = ' Copiado'; + copyBtn.classList.add('success'); + setTimeout(() => { + copyBtn.innerHTML = ' Copiar Enlace Video'; + copyBtn.classList.remove('success'); + }, 1500); + }; + li.appendChild(copyBtn); + twpornstarsList.appendChild(li); + }); + } else { + statusTWPornstars.style.display = 'flex'; + statusTWPornstars.innerHTML = 'No se encontró ningún video en esta página.'; + } + saveSiteState(); + } + + async function performLeakGalleryScan() { + statusLeakGallery.style.display = 'flex'; + statusLeakGallery.innerHTML = 'Buscando posts de videos...'; + + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + showLeakGalleryError("No se puede escanear esta página."); + return; + } + + chrome.scripting.executeScript({ + target: { tabId: tab.id }, + files: ['src/leakgallery/quick_scan.js'] + }, async (results) => { + if (chrome.runtime.lastError || !results || !results[0]) { + showLeakGalleryError("No se pudo inyectar el scanner. Verifica que la página cargó."); + return; + } + + const data = results[0].result; + if (data.error) { + showLeakGalleryError("Error: " + data.error); + return; + } + + const posts = data.videos || []; + if (posts.length === 0) { + showLeakGalleryError("No se encontraron posts de video en la página."); + return; + } + + statusLeakGallery.innerHTML = `Obteniendo enlaces directos (0/${posts.length})...`; + + const finalVideos = []; + let completed = 0; + + const fetchPromises = posts.map(async (post) => { + try { + const response = await fetch(post.postUrl); + const text = await response.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(text, 'text/html'); + const source = doc.querySelector('video source[type="video/mp4"]') || doc.querySelector('video source') || doc.querySelector('#video-element_html5_api source'); + + if (source && source.src) { + finalVideos.push({ + title: post.title, + videoUrl: source.src, + thumbnailUrl: post.thumbnailUrl, + postUrl: post.postUrl + }); + } + } catch (e) { + console.error("Error fetching detail for post", post.postUrl, e); + } finally { + completed++; + statusLeakGallery.innerHTML = `Obteniendo enlaces directos (${completed}/${posts.length})...`; + } + }); + + await Promise.all(fetchPromises); + renderLeakGalleryList(finalVideos); + }); + } catch (err) { + console.error(err); + showLeakGalleryError("Error al escanear."); + } + } + + function showLeakGalleryError(msg) { + statusLeakGallery.style.display = 'flex'; + statusLeakGallery.innerHTML = `${msg}`; + } + + function renderLeakGalleryList(videos) { + leakgalleryList.innerHTML = ''; + + if (videos && videos.length > 0) { + statusLeakGallery.style.display = 'none'; + copyAllLeakGalleryBtn.style.display = 'flex'; + + copyAllLeakGalleryBtn.onclick = () => { + const allLinks = videos.map(v => v.videoUrl).join('\n'); + navigator.clipboard.writeText(allLinks); + copyAllLeakGalleryBtn.innerHTML = ' ¡Todos copiados!'; + copyAllLeakGalleryBtn.classList.add('success'); + setTimeout(() => { + copyAllLeakGalleryBtn.innerHTML = ' Copiar Todos'; + copyAllLeakGalleryBtn.classList.remove('success'); + }, 2000); + }; + + videos.forEach((video) => { + const li = document.createElement('li'); + + if (video.thumbnailUrl) { + const thumbImg = document.createElement('img'); + thumbImg.src = video.thumbnailUrl; + thumbImg.style.cssText = 'width: 100%; max-height: 180px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border); margin-bottom: 5px;'; + li.appendChild(thumbImg); + } + + const titleEl = document.createElement('div'); + titleEl.style.cssText = 'font-weight: 600; font-size: 13px; color: #fff; margin-bottom: 5px;'; + titleEl.textContent = video.title; + li.appendChild(titleEl); + + const urlContainer = document.createElement('div'); + urlContainer.className = 'url-container'; + urlContainer.style.marginBottom = '8px'; + + const urlStr = document.createElement('div'); + urlStr.className = 'url'; + urlStr.textContent = video.videoUrl; + urlStr.title = video.videoUrl; + + urlContainer.appendChild(urlStr); + li.appendChild(urlContainer); + + const copyBtn = document.createElement('button'); + copyBtn.innerHTML = ' Copiar Enlace Video'; + copyBtn.onclick = () => { + navigator.clipboard.writeText(video.videoUrl); + copyBtn.innerHTML = ' Copiado'; + copyBtn.classList.add('success'); + setTimeout(() => { + copyBtn.innerHTML = ' Copiar Enlace Video'; + copyBtn.classList.remove('success'); + }, 1500); + }; + li.appendChild(copyBtn); + leakgalleryList.appendChild(li); + }); + } else { + statusLeakGallery.style.display = 'flex'; + statusLeakGallery.innerHTML = 'No se encontró ningún video en esta página.'; + } + saveSiteState(); + } + + + + // 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; + if (msg.tool === 'eporner') toggleEporner.checked = false; + if (msg.tool === 'xhamster') toggleXhamster.checked = false; + if (msg.tool === 'ixxx') toggleIxxx.checked = false; + if (msg.tool === 'xhand') toggleXhand.checked = false; + if (msg.tool === 'xvideos') toggleXvideos.checked = false; + if (msg.tool === 'pornhub') togglePornhub.checked = false; + if (msg.tool === 'instagram') toggleInstagram.checked = false; + if (msg.tool === 'x') toggleX.checked = false; + if (msg.tool === 'jav') { + toggleJav.checked = false; + containerJav.style.display = 'none'; + } + } + }); + + // Listen for background updates + chrome.runtime.onMessage.addListener((message) => { + if (message.type === 'SCAN_UPDATE') { + renderState(message.payload); + } else if (message.type === 'IMAGE_SCAN_UPDATE') { + renderImageState(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) { + if (state.video && (state.video.isScanning || state.video.foundUrls.length > 0 || state.video.totalCount > 0)) { + toggleVideo.checked = true; + containerVideo.style.display = 'block'; + renderState(state.video); + } + if (state.image && (state.image.isScanning || state.image.foundUrls.length > 0 || state.image.totalCount > 0)) { + toggleEromeImages.checked = true; + containerEromeImages.style.display = 'block'; + renderImageState(state.image); + } + } + }); + } 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 }, + files: ['src/erome/quick_scan.js'] + }, (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.'; + } + } + saveSiteState(); + } + + function showError(msg) { + statusDiv.style.display = 'flex'; + statusDiv.innerHTML = `${msg}`; + } + + function renderImageState(state) { + if (state.isScanning) { + const percentage = Math.round((state.scannedCount / state.totalCount) * 100) || 0; + deepScanEromeImagesBtn.style.display = 'flex'; + deepScanEromeImagesBtn.disabled = true; + deepScanEromeImagesBtn.style.position = 'relative'; + deepScanEromeImagesBtn.innerHTML = ` +
+
+ + Escaneando álbum ${state.scannedCount} de ${state.totalCount} (${percentage}%) +
+ `; + } else if (state.totalCount > 0) { + deepScanEromeImagesBtn.style.display = 'flex'; + deepScanEromeImagesBtn.disabled = false; + deepScanEromeImagesBtn.innerHTML = `✨ Búsqueda Profunda Completada`; + deepScanEromeImagesBtn.classList.add('success'); + setTimeout(() => { deepScanEromeImagesBtn.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_IMAGE_SCAN' }, () => { + window.location.reload(); + }); + }; + if (!document.getElementById('reset-img-btn')) { + resetBtn.id = 'reset-img-btn'; + deepScanEromeImagesBtn.parentNode.insertBefore(resetBtn, deepScanEromeImagesBtn.nextSibling); + } + } + + renderImageList(state.foundUrls, state.albumUrls || []); + } + + async function performQuickScanForImages() { + statusEromeImages.style.display = 'flex'; + statusEromeImages.innerHTML = 'Escaneando página actual...'; + + try { + let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + + if (!tab || !tab.url || tab.url.startsWith('chrome://')) { + showImageError("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 }, + files: ['src/erome/quick_scan_images.js'] + }, (results) => { + if (chrome.runtime.lastError || !results || !results[0]) { + showImageError("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) { + showImageError("Error en la página: " + data.error); + return; + } + + const currentImages = data.images || []; + const albumLinks = data.albums || []; + + renderImageList(currentImages, albumLinks); + + if (albumLinks.length > 0) { + deepScanEromeImagesBtn.style.display = 'flex'; + deepScanEromeImagesBtn.innerHTML = `🔍 Explorar en fondo (${albumLinks.length} álbumes)`; + deepScanEromeImagesBtn.classList.remove('success'); + + const resetBtn = document.getElementById('reset-img-btn'); + if (resetBtn) resetBtn.remove(); + + deepScanEromeImagesBtn.onclick = () => { + chrome.runtime.sendMessage({ + type: 'START_IMAGE_SCAN', + payload: { albumUrls: albumLinks, currentImages: currentImages } + }, (state) => { + renderImageState(state); + }); + }; + } + }); + } catch (err) { + showImageError("Ocurrió un error general."); + console.error(err); + } + } + + function renderImageList(urlsArray, albumLinks) { + imageList.innerHTML = ''; + + if (urlsArray && urlsArray.length > 0) { + statusEromeImages.style.display = 'none'; + copyAllEromeImagesBtn.style.display = 'flex'; + + copyAllEromeImagesBtn.onclick = () => { + const allLinks = urlsArray.join('\n'); + navigator.clipboard.writeText(allLinks); + copyAllEromeImagesBtn.innerHTML = ' ¡Todos copiados!'; + copyAllEromeImagesBtn.classList.add('success'); + setTimeout(() => { + copyAllEromeImagesBtn.innerHTML = ' Copiar Todos a la Vez'; + copyAllEromeImagesBtn.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); + imageList.appendChild(li); + }); + } else { + statusEromeImages.style.display = 'flex'; + if (albumLinks && albumLinks.length === 0) { + statusEromeImages.innerHTML = 'No se encontró ninguna imagen aquí ni álbumes asociados.'; + } else if (albumLinks && albumLinks.length > 0) { + statusEromeImages.innerHTML = 'Usa "Explorar en fondo" para obtener las imágenes.'; + } + } + saveSiteState(); + } + + function showImageError(msg) { + statusEromeImages.style.display = 'flex'; + statusEromeImages.innerHTML = `${msg}`; + } +}); diff --git a/detector de enlaces - copia/src/eporner/selector.js b/detector de enlaces - copia/src/eporner/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..e9bc0be20b9a2d9cd07c909ddf714b7acf94eb99 --- /dev/null +++ b/detector de enlaces - copia/src/eporner/selector.js @@ -0,0 +1,276 @@ +(() => { + if (window.__epornerSelectorActive) return; + window.__epornerSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'eporner-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 = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #ff5500; + color: white; + border: none; + padding: 10px; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + `; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'eporner-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 = 'eporner-style'; + style.textContent = ` + .eporner-selector-selected { + position: relative !important; + outline: 4px solid #10b981 !important; + outline-offset: -4px !important; + } + .eporner-selector-selected::after { + content: '✓' !important; + position: absolute !important; + top: 10px !important; + left: 10px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 5px rgba(0,0,0,0.5) !important; + pointer-events: none !important; + } + `; + document.head.appendChild(style); + + // Helper to get normalized URLs for matching + const getCleanUrl = (href) => { + if (!href) return ''; + let url = href.split('?')[0].split('#')[0].trim(); + if (url.endsWith('/')) { + url = url.slice(0, -1); + } + return url; + }; + + // Helper to check if an anchor is a thumbnail cover rather than text title (robust and crash-proof) + const isThumbnailAnchor = (a) => { + if (!a) return false; + if (a.__isThumbnail) return true; + + // 1. If it contains an image, video, canvas, or thumbnail class-like elements + if (a.querySelector('img, picture, canvas, video, [class*="thumb"], [class*="img"], [class*="preview"], [class*="cover"]')) return true; + + // 2. Safe class name parsing (prevent crashes on animated SVG string wrappers) + let className = ''; + if (typeof a.className === 'string') { + className = a.className.toLowerCase(); + } else if (a.className && typeof a.className.baseVal === 'string') { + className = a.className.baseVal.toLowerCase(); + } + if (className.includes('thumb') || className.includes('img') || className.includes('preview') || className.includes('cover') || className.includes('vimg')) return true; + + // 3. Fallback: if it has short text content and wraps some tag, it is likely a thumbnail (like Eporner lazy loaders) + const textLen = a.textContent.trim().length; + if (textLen < 15 && a.querySelector('*')) return true; + + return false; + }; + + // Capture and save initial attributes before they are mutated by site scripts + const initAnchors = () => { + document.querySelectorAll('a[href*="/video-"]').forEach(a => { + if (isThumbnailAnchor(a)) { + a.__isThumbnail = true; + if (!a.__originalVideoUrl) { + const url = getCleanUrl(a.href); + if (url && !url.startsWith('javascript') && url !== '#' && !url.includes('void(0)')) { + a.__originalVideoUrl = url; + } + } + } + }); + }; + + // Run initial scan + initAnchors(); + + // Scan periodically to catch new elements (scroll/pagination) + const initInterval = setInterval(initAnchors, 800); + + const toggleCardSelection = (url, select) => { + initAnchors(); + document.querySelectorAll('a[href*="/video-"]').forEach(a => { + if (a.__originalVideoUrl === url && a.__isThumbnail) { + if (select) { + a.classList.add('eporner-selector-selected'); + } else { + a.classList.remove('eporner-selector-selected'); + } + } + }); + }; + + const clickHandler = (e) => { + const card = e.target.closest('a[href*="/video-"]'); + if (card) { + initAnchors(); + if (card.__isThumbnail) { + let url = card.__originalVideoUrl; + if (!url && card.href && !card.href.startsWith('javascript') && card.href !== '#') { + url = getCleanUrl(card.href); + card.__originalVideoUrl = url; + } + if (!url) return; + + e.preventDefault(); + e.stopPropagation(); + + if (selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } + } + }; + + document.addEventListener('click', clickHandler, true); + + selectAllBtn.onclick = () => { + initAnchors(); + const links = []; + document.querySelectorAll('a[href*="/video-"]').forEach(a => { + if (a.__isThumbnail && a.__originalVideoUrl) { + links.push(a); + } + }); + + let allSelected = true; + links.forEach(a => { + const url = a.__originalVideoUrl; + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + links.forEach(a => { + const url = a.__originalVideoUrl; + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + links.forEach(a => { + const url = a.__originalVideoUrl; + if (!selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + }); + 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 = '#ff5500'; + }, 2000); + }); + }; + + closeBtn.onclick = () => { + clearInterval(initInterval); + document.removeEventListener('click', clickHandler, true); + container.remove(); + style.remove(); + + document.querySelectorAll('.eporner-selector-selected').forEach(el => el.classList.remove('eporner-selector-selected')); + + window.__epornerSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'eporner' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('EPORNER_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/erome/quick_scan.js b/detector de enlaces - copia/src/erome/quick_scan.js new file mode 100644 index 0000000000000000000000000000000000000000..b0a58a15552ec1f882e0573b834ae8cb8b8cb80f --- /dev/null +++ b/detector de enlaces - copia/src/erome/quick_scan.js @@ -0,0 +1,36 @@ +(() => { + 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) + }; +})(); diff --git a/detector de enlaces - copia/src/erome/quick_scan_images.js b/detector de enlaces - copia/src/erome/quick_scan_images.js new file mode 100644 index 0000000000000000000000000000000000000000..15ce5b07965d7fb6a6a0183c60cfc75655761564 --- /dev/null +++ b/detector de enlaces - copia/src/erome/quick_scan_images.js @@ -0,0 +1,60 @@ +(() => { + let urls = new Set(); + let albumLinks = new Set(); + // Extract album ID from current page URL + const pageUrl = window.location.href; + const albumMatch = pageUrl.match(/erome\.com\/a\/([a-zA-Z0-9]+)/); + const currentAlbumId = albumMatch ? albumMatch[1] : null; + + const isAlbumImageUrl = (url) => { + if (!url) return false; + const lower = url.toLowerCase(); + if (lower.includes('/avatar/') || lower.includes('/icon/') || lower.includes('/logo/') || lower.includes('logo') || lower.includes('/thumbs/') || lower.includes('/img/')) { + return false; + } + + // If we are on an album page, only include images that belong to the current album ID + if (currentAlbumId) { + if (!lower.includes('/' + currentAlbumId.toLowerCase() + '/')) { + return false; + } + } else { + // On non-album pages (e.g. search/home), we don't want to collect cover thumbnails of albums as images. + return false; + } + + return lower.includes('erome.com') && (lower.endsWith('.jpg') || lower.endsWith('.jpeg') || lower.endsWith('.png') || lower.endsWith('.webp') || lower.includes('.jpg?') || lower.includes('.jpeg?') || lower.includes('.png?') || lower.includes('.webp?')); + }; + + try { + document.querySelectorAll('img').forEach(img => { + const src = img.src || img.getAttribute('data-src') || img.getAttribute('data-lazy'); + if (src && isAlbumImageUrl(src)) { + urls.add(src); + } + }); + + document.querySelectorAll('[style*="background-image"]').forEach(el => { + const style = el.getAttribute('style'); + const match = style.match(/url\(['"]?([^'"]+)['"]?\)/); + if (match && isAlbumImageUrl(match[1])) { + urls.add(match[1]); + } + }); + + document.querySelectorAll('a').forEach(a => { + if (a.href && typeof a.href === 'string') { + if (a.href.match(/erome\.com\/a\/[a-zA-Z0-9]+/)) { + albumLinks.add(a.href); + } + } + }); + } catch(e) { + return { error: e.message }; + } + + return { + images: Array.from(urls), + albums: Array.from(albumLinks) + }; +})(); diff --git a/detector de enlaces - copia/src/facebook/selector.js b/detector de enlaces - copia/src/facebook/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..f88ae1ad364c1622a89704cba3394675ee99f3a8 --- /dev/null +++ b/detector de enlaces - copia/src/facebook/selector.js @@ -0,0 +1,328 @@ +(() => { + if (document.getElementById('fb-floating-ui')) 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: 2147483647; + 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 || document.documentElement).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 || document.documentElement).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) { + 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'; + + let lastHeight = 0; + let retries = 0; + const maxRetries = 5; + + 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); + }; + + 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')); + }; +})(); diff --git a/detector de enlaces - copia/src/instagram/selector.js b/detector de enlaces - copia/src/instagram/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..ef7d5a2835350068996f01dbd2fbee3b963e3188 --- /dev/null +++ b/detector de enlaces - copia/src/instagram/selector.js @@ -0,0 +1,520 @@ +(() => { + if (document.getElementById('instagram-floating-ui')) return; + window.__instagramSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'instagram-floating-ui'; + container.style.cssText = ` + position: fixed; + bottom: 20px; + right: 20px; + background: #18181b; + color: #fff; + padding: 16px; + border-radius: 12px; + border: 1px solid #27272a; + z-index: 2147483647; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.6); + display: flex; + flex-direction: column; + gap: 10px; + min-width: 220px; + user-select: none; + `; + + const countDisplay = document.createElement('div'); + countDisplay.textContent = '0 enlaces seleccionados'; + countDisplay.style.cssText = ` + font-weight: 700; + text-align: center; + font-size: 15px; + color: #ffffff; + margin-bottom: 2px; + `; + + const autoScanBtn = document.createElement('button'); + autoScanBtn.textContent = 'Buscar videos y fotos'; + autoScanBtn.style.cssText = ` + background: #e1306c; + color: #ffffff; + border: none; + padding: 10px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 700; + font-size: 14px; + transition: background 0.2s ease; + `; + autoScanBtn.onmouseover = () => { + if (!window.__instagramIsScanning) autoScanBtn.style.background = '#c13584'; + }; + autoScanBtn.onmouseout = () => { + if (!window.__instagramIsScanning) autoScanBtn.style.background = '#e1306c'; + }; + + const selectAllBtn = document.createElement('button'); + selectAllBtn.textContent = 'Seleccionar Todos'; + selectAllBtn.style.cssText = ` + background: #3f3f46; + color: #ffffff; + border: none; + padding: 9px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 600; + font-size: 13.5px; + transition: background 0.2s ease; + `; + selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; + selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; + + const copyBtn = document.createElement('button'); + copyBtn.textContent = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #8b5cf6; + color: #ffffff; + border: none; + padding: 11px 16px; + border-radius: 8px; + cursor: pointer; + font-weight: 700; + font-size: 15px; + transition: background 0.2s ease, transform 0.1s ease; + `; + copyBtn.onmouseover = () => copyBtn.style.background = '#7c3aed'; + copyBtn.onmouseout = () => copyBtn.style.background = '#8b5cf6'; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'instagram-close-btn'; + closeBtn.textContent = 'Cerrar Selector'; + closeBtn.style.cssText = ` + background: #27272a; + color: #e4e4e7; + border: 1px solid #3f3f46; + padding: 8px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 500; + font-size: 13px; + transition: background 0.2s ease; + `; + closeBtn.onmouseover = () => closeBtn.style.background = '#3f3f46'; + closeBtn.onmouseout = () => closeBtn.style.background = '#27272a'; + + container.appendChild(countDisplay); + container.appendChild(autoScanBtn); + container.appendChild(selectAllBtn); + container.appendChild(copyBtn); + container.appendChild(closeBtn); + (document.body || document.documentElement).appendChild(container); + + const style = document.createElement('style'); + style.id = 'instagram-selector-style'; + style.textContent = ` + .instagram-selector-hover { + box-shadow: 0 0 12px rgba(225, 48, 108, 0.6) !important; + outline: 4px solid #e1306c !important; + outline-offset: -4px !important; + cursor: crosshair !important; + transition: all 0.15s ease; + position: relative !important; + z-index: 9999 !important; + } + .instagram-selector-selected { + box-shadow: 0 0 15px rgba(16, 185, 129, 0.7) !important; + outline: 4px solid #10b981 !important; + outline-offset: -4px !important; + position: relative !important; + z-index: 9998 !important; + } + .instagram-selector-selected::after, + .instagram-selector-selected:hover::after { + content: '✓' !important; + position: absolute !important; + top: 8px !important; + left: 8px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 6px rgba(0,0,0,0.6) !important; + pointer-events: none !important; + } + `; + (document.head || document.documentElement).appendChild(style); + + const getCleanUrl = (hrefOrAnchor) => { + if (!hrefOrAnchor) return ''; + let raw = typeof hrefOrAnchor === 'string' ? hrefOrAnchor : (hrefOrAnchor.href || hrefOrAnchor.getAttribute('href') || ''); + if (!raw) return ''; + try { + let full = new URL(raw, window.location.origin).href; + let clean = full.split('?')[0].split('#')[0].trim(); + if (clean.endsWith('/')) clean = clean.slice(0, -1); + return clean; + } catch(e) { + return ''; + } + }; + + const isInstagramPostUrl = (url) => { + if (!url) return false; + try { + const parsed = new URL(url); + const path = parsed.pathname; + const parts = path.split('/').filter(Boolean); + const idx = parts.findIndex(p => { + const lower = p.toLowerCase(); + return lower === 'p' || lower === 'reel' || lower === 'reels'; + }); + if (idx !== -1 && parts[idx + 1] && parts[idx + 1].length > 0) { + return true; + } + } catch (e) { + const lower = url.toLowerCase(); + if (lower.endsWith('/reels') || lower.endsWith('/reels/') || lower.endsWith('/p') || lower.endsWith('/p/')) { + return false; + } + return lower.includes('/p/') || lower.includes('/reel/') || lower.includes('/reels/'); + } + return false; + }; + + const getPostCard = (el) => { + if (!el || el.closest('#instagram-floating-ui')) return null; + + const anchor = el.closest('a'); + if (!anchor) return null; + + const url = getCleanUrl(anchor); + if (!isInstagramPostUrl(url)) return null; + + return { card: anchor, anchor, url }; + }; + + const getVisualTarget = (cardObj) => { + if (!cardObj) return null; + return cardObj.anchor; + }; + + const toggleCardSelection = (url, select) => { + document.querySelectorAll('a').forEach(el => { + const cardObj = getPostCard(el); + if (cardObj && cardObj.url === url) { + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + if (select) { + visualTarget.classList.add('instagram-selector-selected'); + visualTarget.classList.remove('instagram-selector-hover'); + } else { + visualTarget.classList.remove('instagram-selector-selected'); + } + } + } + }); + }; + + let isDragging = false; + let dragMode = null; + + const mouseOver = (e) => { + if (e.target.closest('#instagram-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + const { url } = cardObj; + const visualTarget = getVisualTarget(cardObj); + if (!visualTarget) return; + + if (isDragging) { + e.preventDefault(); + e.stopPropagation(); + + if (dragMode === 'select' && !selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!visualTarget.classList.contains('instagram-selector-selected')) { + visualTarget.classList.add('instagram-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + if (e.target.closest('#instagram-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + visualTarget.classList.remove('instagram-selector-hover'); + } + } + }; + + const mouseDown = (e) => { + if (e.target.closest('#instagram-floating-ui')) return; + + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); + isDragging = true; + + const { url } = cardObj; + + if (selectedLinks.has(url)) { + dragMode = 'deselect'; + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + dragMode = 'select'; + selectedLinks.add(url); + toggleCardSelection(url, true); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } + }; + + const mouseUp = () => { + isDragging = false; + dragMode = null; + }; + + const dragStart = (e) => { + if (e.target.closest('#instagram-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + } + }; + + const click = (e) => { + if (e.target.closest('#instagram-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); + } + }; + + 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; + let observer = null; + + const updateDOMHighlights = () => { + let countChanged = false; + document.querySelectorAll('a').forEach(el => { + const cardObj = getPostCard(el); + if (cardObj) { + const { url } = cardObj; + + // If scanning is active, automatically select any new post/reel URLs found + if (window.__instagramIsScanning && !selectedLinks.has(url)) { + selectedLinks.add(url); + countChanged = true; + } + + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + if (selectedLinks.has(url)) { + visualTarget.classList.add('instagram-selector-selected'); + visualTarget.classList.remove('instagram-selector-hover'); + } else { + visualTarget.classList.remove('instagram-selector-selected'); + } + } + } + }); + + if (countChanged) { + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + if (window.__instagramIsScanning) { + autoScanBtn.textContent = 'Detener búsqueda (' + selectedLinks.size + ')'; + } + } + }; + + let updateTimeout = null; + const scheduleUpdateHighlights = () => { + if (updateTimeout) return; + updateTimeout = setTimeout(() => { + updateDOMHighlights(); + updateTimeout = null; + }, 150); + }; + + observer = new MutationObserver((mutations) => { + let hasChanges = false; + for (let i = 0; i < mutations.length; i++) { + if (mutations[i].addedNodes.length > 0) { + hasChanges = true; + break; + } + } + if (hasChanges) { + scheduleUpdateHighlights(); + } + }); + observer.observe(document.body, { childList: true, subtree: true }); + + // Initial highlight of already existing links + updateDOMHighlights(); + + autoScanBtn.onclick = () => { + if (window.__instagramIsScanning) { + clearInterval(scanInterval); + window.__instagramIsScanning = false; + autoScanBtn.textContent = 'Buscar videos y fotos'; + autoScanBtn.style.background = '#e1306c'; + return; + } + + window.__instagramIsScanning = true; + autoScanBtn.textContent = 'Buscando... (' + selectedLinks.size + ')'; + autoScanBtn.style.background = '#27272a'; + + let lastScrollY = -1; + let lastCount = selectedLinks.size; + let retries = 0; + const maxRetries = 20; // 20 * 600ms = 12 seconds of wait time at bottom + + scanInterval = setInterval(() => { + // Scroll window + window.scrollBy(0, 600); + + // Scroll any scrollable div containers on the page + document.querySelectorAll('div').forEach(el => { + const style = window.getComputedStyle(el); + if ((style.overflowY === 'auto' || style.overflowY === 'scroll') && el.scrollHeight > el.clientHeight) { + el.scrollBy(0, 600); + } + }); + + // Scan and highlight + updateDOMHighlights(); + + const currentScrollY = window.scrollY || document.documentElement.scrollTop; + const currentCount = selectedLinks.size; + + // If scroll position didn't change and we didn't find new links, we might be at the end + if (currentScrollY === lastScrollY && currentCount === lastCount) { + retries++; + if (retries >= maxRetries) { + clearInterval(scanInterval); + window.__instagramIsScanning = false; + autoScanBtn.textContent = 'Buscar videos y fotos'; + autoScanBtn.style.background = '#e1306c'; + } + } else { + retries = 0; + } + + lastScrollY = currentScrollY; + lastCount = currentCount; + + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + autoScanBtn.textContent = 'Detener búsqueda (' + selectedLinks.size + ')'; + }, 600); + }; + + selectAllBtn.onclick = () => { + const postUrls = new Set(); + document.querySelectorAll('a').forEach(a => { + const url = getCleanUrl(a); + if (isInstagramPostUrl(url)) { + postUrls.add(url); + } + }); + + let allSelected = true; + postUrls.forEach(url => { + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + postUrls.forEach(url => { + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + postUrls.forEach(url => { + selectedLinks.add(url); + toggleCardSelection(url, true); + }); + 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; + const ogBg = copyBtn.style.background; + copyBtn.textContent = '¡Copiados!'; + copyBtn.style.background = '#10b981'; + setTimeout(() => { + copyBtn.textContent = ogText; + copyBtn.style.background = ogBg || '#8b5cf6'; + }, 2000); + }); + }; + + closeBtn.onclick = () => { + if (scanInterval) clearInterval(scanInterval); + window.__instagramIsScanning = false; + + if (observer) { + observer.disconnect(); + observer = 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('.instagram-selector-selected').forEach(el => el.classList.remove('instagram-selector-selected')); + document.querySelectorAll('.instagram-selector-hover').forEach(el => el.classList.remove('instagram-selector-hover')); + window.__instagramSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'instagram' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('INSTAGRAM_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/ixxx/selector.js b/detector de enlaces - copia/src/ixxx/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..be08a05599c26089e6484f0095a67d2cd3c60623 --- /dev/null +++ b/detector de enlaces - copia/src/ixxx/selector.js @@ -0,0 +1,370 @@ +(() => { + if (window.__ixxxSelectorActive) return; + window.__ixxxSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'ixxx-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 = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #ec4899; + color: white; + border: none; + padding: 10px; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + `; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'ixxx-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 = 'ixxx-style'; + style.textContent = ` + .ixxx-selector-hover { + box-shadow: inset 0 0 0 4px #ec4899 !important, 0 0 10px rgba(236, 72, 153, 0.5) !important; + cursor: crosshair !important; + transition: all 0.2s; + position: relative !important; + z-index: 9999 !important; + } + .ixxx-selector-selected { + box-shadow: inset 0 0 0 4px #10b981 !important, 0 0 15px rgba(16, 185, 129, 0.6) !important; + position: relative !important; + z-index: 9998 !important; + } + .ixxx-selector-selected::after, + .ixxx-selector-selected:hover::after { + content: '✓' !important; + position: absolute !important; + top: 8px !important; + left: 8px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 5px rgba(0,0,0,0.5) !important; + pointer-events: none !important; + } + `; + document.head.appendChild(style); + + // Helper to decode Base64 URL from ixxx outbound link + const decodeIxxxUrl = (urlStr) => { + try { + const urlObj = new URL(urlStr, window.location.origin); + const lParam = urlObj.searchParams.get('l'); + if (!lParam) return urlStr; + + let b64Index = lParam.indexOf('aHR0cHM6Ly'); // https:// + if (b64Index === -1) { + b64Index = lParam.indexOf('aHR0cDov'); // http:// + } + + if (b64Index !== -1) { + let encodedPart = lParam.substring(b64Index).split('&')[0]; + let cleanB64 = encodedPart.replace(/[^A-Za-z0-9+/]/g, ''); + while (cleanB64.length % 4 !== 0) { + cleanB64 += '='; + } + const decoded = atob(cleanB64); + const match = decoded.match(/^(https?:\/\/[^\s"'<>\\\{\}\[\]\^\`\x00-\x1f\x7f-\xff]+)/); + if (match) { + return match[1]; + } + } + } catch (e) { + console.error("Error decoding ixxx URL", e); + } + return urlStr; + }; + + // Helper to get normalized URLs for matching + const getCleanUrl = (href) => { + if (!href) return ''; + let url = href.trim(); + if (url.includes('/out/?l=')) { + url = decodeIxxxUrl(url); + } + let clean = url.split('?')[0].split('#')[0].trim(); + if (clean.endsWith('/')) { + clean = clean.slice(0, -1); + } + return clean; + }; + + // Helper to check if an anchor is a thumbnail cover rather than text title + const isThumbnailAnchor = (a) => { + if (!a) return false; + if (a.classList.contains('item-title')) return false; + if (a.querySelector('img, picture, canvas, video, [class*="thumb"], [class*="img"], [class*="preview"], [class*="cover"]')) return true; + return false; + }; + + const getPostCard = (el) => { + const card = el.closest('a[href*="/out/?l="]'); + if (!card) return null; + return card; + }; + + const getThumbnailAnchorForUrl = (url) => { + let thumb = null; + document.querySelectorAll('a[href*="/out/?l="]').forEach(a => { + if (getCleanUrl(a.href) === url) { + if (isThumbnailAnchor(a)) { + thumb = a; + } + } + }); + return thumb; + }; + + const getVisualTarget = (card) => { + // Target closest card wrapper container to render outline cleanly around the whole block + return card.closest('.card') || card.parentElement || card; + }; + + const toggleCardSelection = (url, select) => { + document.querySelectorAll('a[href*="/out/?l="]').forEach(a => { + if (getCleanUrl(a.href) === url) { + if (isThumbnailAnchor(a)) { + const visualTarget = getVisualTarget(a); + if (select) { + visualTarget.classList.add('ixxx-selector-selected'); + visualTarget.classList.remove('ixxx-selector-hover'); + } else { + visualTarget.classList.remove('ixxx-selector-selected'); + } + } + } + }); + }; + + let isDragging = false; + let dragMode = null; + + const mouseOver = (e) => { + const card = getPostCard(e.target); + if (card) { + const url = getCleanUrl(card.href); + const thumb = getThumbnailAnchorForUrl(url) || card; + const visualTarget = getVisualTarget(thumb); + + if (isDragging) { + e.preventDefault(); + e.stopPropagation(); + + if (dragMode === 'select' && !selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!visualTarget.classList.contains('ixxx-selector-selected')) { + visualTarget.classList.add('ixxx-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + const card = getPostCard(e.target); + if (card) { + const url = getCleanUrl(card.href); + const thumb = getThumbnailAnchorForUrl(url) || card; + const visualTarget = getVisualTarget(thumb); + visualTarget.classList.remove('ixxx-selector-hover'); + } + }; + + const mouseDown = (e) => { + const card = getPostCard(e.target); + if (card) { + e.preventDefault(); + e.stopPropagation(); + isDragging = true; + + const url = getCleanUrl(card.href); + + if (selectedLinks.has(url)) { + dragMode = 'deselect'; + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + dragMode = 'select'; + selectedLinks.add(url); + toggleCardSelection(url, true); + } + 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(); + e.stopPropagation(); + } + }; + + 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 links = []; + document.querySelectorAll('a[href*="/out/?l="]').forEach(a => { + if (isThumbnailAnchor(a)) { + links.push(a); + } + }); + + let allSelected = true; + links.forEach(a => { + const url = getCleanUrl(a.href); + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + links.forEach(a => { + const url = getCleanUrl(a.href); + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + links.forEach(a => { + const url = getCleanUrl(a.href); + if (!selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + }); + 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 = '#ec4899'; + }, 2000); + }); + }; + + 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('.ixxx-selector-selected').forEach(el => el.classList.remove('ixxx-selector-selected')); + document.querySelectorAll('.ixxx-selector-hover').forEach(el => el.classList.remove('ixxx-selector-hover')); + window.__ixxxSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'ixxx' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('IXXX_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/jav/selector.js b/detector de enlaces - copia/src/jav/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..a9112be3f2f8db7e850a913633c53113f40a5ee8 --- /dev/null +++ b/detector de enlaces - copia/src/jav/selector.js @@ -0,0 +1,526 @@ +(() => { + if (window.__javSelectorActive) return; + window.__javSelectorActive = true; + + const isPlayPage = () => { + const url = window.location.href.toLowerCase(); + if (url.includes('/v/')) { + return true; + } + const hasJavCode = /\/[a-z0-9]+-\d+/i.test(url); + const isListPage = url.includes('/genres/') || url.includes('/search/') || url.includes('/makers/') || url.includes('/actresses/') || url.includes('/tags/'); + if ((url.includes('missav.com') || url.includes('missav.ws')) && hasJavCode && !isListPage) { + return true; + } + return false; + }; + + const getTitle = () => { + let title = document.title; + title = title.replace(/\s*-\s*MissAV\.ws/gi, '') + .replace(/\s*-\s*MissAV/gi, '') + .replace(/\s*—\s*123AV/gi, '') + .replace(/\s*-\s*123AV/gi, '') + .trim(); + return title; + }; + + const makeDownloadCommand = (m3u8Url) => { + const title = getTitle().replace(/["'\\]/g, ''); + const referer = window.location.origin + '/'; + if (window.location.hostname.includes('123av.')) { + return `N_m3u8DL-RE "${m3u8Url}" -H "Referer: https://surrit.store/" --save-name "${title}"`; + } else { + return `N_m3u8DL-RE "${m3u8Url}" -H "Referer: ${referer}" --save-name "${title}"`; + } + }; + + // UI creation + const container = document.createElement('div'); + container.id = 'jav-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: 250px; + max-width: 380px; + `; + + const titleDisplay = document.createElement('div'); + titleDisplay.style.cssText = ` + font-weight: bold; + font-size: 13px; + color: #f43f5e; + margin-bottom: 2px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; + titleDisplay.textContent = isPlayPage() ? getTitle() : 'Modo Selección JAV'; + + const statusDisplay = document.createElement('div'); + statusDisplay.textContent = 'Inicializando...'; + statusDisplay.style.cssText = ` + font-size: 13px; + text-align: center; + color: #a1a1aa; + `; + + container.appendChild(titleDisplay); + container.appendChild(statusDisplay); + document.body.appendChild(container); + + const style = document.createElement('style'); + style.id = 'jav-selector-style'; + style.textContent = ` + .jav-selector-selected { + position: relative !important; + outline: 4px solid #f43f5e !important; + outline-offset: -4px !important; + } + .jav-selector-selected::after { + content: '✓' !important; + position: absolute !important; + top: 10px !important; + left: 10px !important; + background: #f43f5e !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 5px rgba(0,0,0,0.5) !important; + pointer-events: none !important; + } + `; + document.head.appendChild(style); + + const closeBtn = document.createElement('button'); + closeBtn.id = 'jav-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; + margin-top: 5px; + `; + + const cleanUp = () => { + document.querySelectorAll('.jav-selector-selected').forEach(el => el.classList.remove('jav-selector-selected')); + container.remove(); + style.remove(); + window.__javSelectorActive = false; + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'jav' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + }; + + closeBtn.onclick = cleanUp; + + // PLAY PAGE MODE + if (isPlayPage()) { + const extract123AV = async () => { + const html = document.documentElement.outerHTML; + const match = html.match(/player\(JSON\.parse\('([^']+)'\)/); + if (!match) { + throw new Error("No se encontró el objeto de reproducción 123AV."); + } + + let rawJson = match[1]; + let jsonStr = rawJson.replace(/\\"/g, '"').replace(/\\\//g, '/'); + jsonStr = jsonStr.replace(/\\u([0-9a-fA-F]{4})/g, (m, grp) => String.fromCharCode(parseInt(grp, 16))); + + const playerData = JSON.parse(jsonStr); + let surritUrl = null; + for (const item of playerData) { + if (item.url && item.url.includes('surrit.')) { + surritUrl = item.url; + break; + } + } + + if (!surritUrl) { + throw new Error("No se encontró el reproductor Surrit."); + } + + const urlObj = new URL(surritUrl); + const videoId = urlObj.pathname.split('/').pop(); + const poster = urlObj.searchParams.get('poster') || ''; + const streamApiUrl = `https://surrit.store/stream?id=${videoId}&poster=${encodeURIComponent(poster)}`; + + return new Promise((resolve, reject) => { + chrome.runtime.sendMessage({ + type: 'FETCH_SURRIT', + url: streamApiUrl, + referer: surritUrl + }, (response) => { + if (chrome.runtime.lastError) { + reject(new Error(chrome.runtime.lastError.message)); + return; + } + if (response && response.success && response.data) { + const streamUrl = response.data.media?.stream; + if (streamUrl) { + resolve(streamUrl); + } else { + reject(new Error("La API de Surrit no devolvió un stream válido.")); + } + } else { + reject(new Error(response?.error || "Error al consultar la API de Surrit.")); + } + }); + }); + }; + + const extractMissAV = async () => { + const html = document.documentElement.outerHTML; + + const splitMatch = html.match(/'([^']+)'\.split\('\|'\)/); + if (splitMatch) { + const words = splitMatch[1].split('|'); + const pMatch = html.match(/\}\('(.*?)', *\d+, *\d+,/); + if (pMatch) { + let p = pMatch[1]; + function base36(i) { + return i.toString(36); + } + for (let i = words.length - 1; i >= 0; i--) { + const word = words[i]; + if (word) { + const idx = base36(i); + const regex = new RegExp('\\b' + idx + '\\b', 'g'); + p = p.replace(regex, word); + } + } + const m3u8Links = p.match(/https?:\/\/surrit\.com[^\s'"]+\.m3u8/); + if (m3u8Links) { + return m3u8Links[0]; + } + } + } + + const m3u8Matches = html.match(/https?:\/\/surrit\.com\/[a-zA-Z0-9-]+\/[^\s'"]+\.m3u8/); + if (m3u8Matches) { + return m3u8Matches[0]; + } + + const sources = Array.from(document.querySelectorAll('video, source, iframe')); + for (const srcEl of sources) { + const src = srcEl.src || srcEl.getAttribute('src'); + if (src && (src.includes('surrit.com') || src.includes('surrit.store')) && src.includes('.m3u8')) { + return src; + } + } + + throw new Error("No se pudo desencriptar ni localizar la URL HLS (.m3u8)."); + }; + + const runExtraction = async () => { + statusDisplay.textContent = 'Extrayendo enlace de video...'; + try { + let m3u8Url = null; + if (window.location.hostname.includes('123av.')) { + m3u8Url = await extract123AV(); + } else { + m3u8Url = await extractMissAV(); + } + + statusDisplay.style.display = 'none'; + + const urlInput = document.createElement('input'); + urlInput.type = 'text'; + urlInput.readOnly = true; + urlInput.value = m3u8Url; + urlInput.style.cssText = ` + background: #27272a; + border: 1px solid #3f3f46; + color: #fff; + padding: 8px; + border-radius: 6px; + font-size: 12px; + outline: none; + width: calc(100% - 18px); + `; + urlInput.onclick = () => { + urlInput.select(); + }; + + const copyM3u8Btn = document.createElement('button'); + copyM3u8Btn.textContent = 'Copiar Enlace .m3u8'; + copyM3u8Btn.style.cssText = ` + background: #f43f5e; + color: white; + border: none; + padding: 10px; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + font-size: 13px; + `; + copyM3u8Btn.onclick = () => { + navigator.clipboard.writeText(m3u8Url).then(() => { + const originalText = copyM3u8Btn.textContent; + copyM3u8Btn.textContent = '¡Copiado!'; + copyM3u8Btn.style.background = '#10b981'; + setTimeout(() => { + copyM3u8Btn.textContent = originalText; + copyM3u8Btn.style.background = '#f43f5e'; + }, 2000); + }); + }; + + const copyCmdBtn = document.createElement('button'); + copyCmdBtn.textContent = 'Copiar Comando de Descarga'; + copyCmdBtn.style.cssText = ` + background: #3f3f46; + color: white; + border: none; + padding: 8px; + border-radius: 6px; + cursor: pointer; + font-weight: 600; + font-size: 12px; + `; + copyCmdBtn.onclick = () => { + const cmd = makeDownloadCommand(m3u8Url); + navigator.clipboard.writeText(cmd).then(() => { + const originalText = copyCmdBtn.textContent; + copyCmdBtn.textContent = '¡Comando Copiado!'; + copyCmdBtn.style.background = '#10b981'; + setTimeout(() => { + copyCmdBtn.textContent = originalText; + copyCmdBtn.style.background = '#3f3f46'; + }, 2000); + }); + }; + + container.appendChild(urlInput); + container.appendChild(copyM3u8Btn); + container.appendChild(copyCmdBtn); + container.appendChild(closeBtn); + + } catch (err) { + statusDisplay.textContent = 'Error: ' + err.message; + statusDisplay.style.color = '#ef4444'; + container.appendChild(closeBtn); + } + }; + + runExtraction(); + + } else { + // LISTINGS INTERACTIVE MODE + statusDisplay.textContent = '0 enlaces seleccionados'; + + const selectedLinks = new Set(); + + const getCleanUrl = (href) => { + if (!href) return ''; + let url = href.split('?')[0].split('#')[0].trim(); + if (url.endsWith('/')) { + url = url.slice(0, -1); + } + return url; + }; + + const isVideoLink = (a) => { + if (!a || !a.href) return false; + const href = a.href.toLowerCase(); + if (href.includes('javascript') || href === '#' || href.includes('void(0)')) return false; + + if (href.includes('123av.com') || href.includes('123av.org') || href.includes('123av.me')) { + return href.includes('/v/'); + } + if (href.includes('missav.com') || href.includes('missav.ws')) { + return /\/[a-z0-9]+-\d+/i.test(href); + } + // Fallback for relative paths + const pathname = a.pathname; + return pathname.includes('/v/') || /\/[a-z0-9]+-\d+/i.test(pathname); + }; + + const isThumbnailAnchor = (a) => { + if (!a) return false; + if (a.querySelector('img, picture, canvas, video, [class*="thumb"], [class*="img"], [class*="preview"], [class*="cover"]')) return true; + + let className = ''; + if (typeof a.className === 'string') { + className = a.className.toLowerCase(); + } else if (a.className && typeof a.className.baseVal === 'string') { + className = a.className.baseVal.toLowerCase(); + } + if (className.includes('thumb') || className.includes('img') || className.includes('preview') || className.includes('cover')) return true; + + const textLen = a.textContent.trim().length; + if (textLen < 20 && a.querySelector('*')) return true; + + return false; + }; + + const initAnchors = () => { + document.querySelectorAll('a').forEach(a => { + if (isVideoLink(a) && isThumbnailAnchor(a)) { + a.__isThumbnail = true; + if (!a.__originalVideoUrl) { + a.__originalVideoUrl = getCleanUrl(a.href); + } + } + }); + }; + + initAnchors(); + const initInterval = setInterval(initAnchors, 800); + + const toggleCardSelection = (url, select) => { + initAnchors(); + document.querySelectorAll('a').forEach(a => { + if (a.__originalVideoUrl === url && a.__isThumbnail) { + if (select) { + a.classList.add('jav-selector-selected'); + } else { + a.classList.remove('jav-selector-selected'); + } + } + }); + }; + + const clickHandler = (e) => { + const card = e.target.closest('a'); + if (card && isVideoLink(card) && isThumbnailAnchor(card)) { + initAnchors(); + let url = card.__originalVideoUrl; + if (!url) { + url = getCleanUrl(card.href); + card.__originalVideoUrl = url; + } + if (!url) return; + + e.preventDefault(); + e.stopPropagation(); + + if (selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + statusDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } + }; + + document.addEventListener('click', clickHandler, true); + + 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'; + + selectAllBtn.onclick = () => { + initAnchors(); + const links = []; + document.querySelectorAll('a').forEach(a => { + if (a.__isThumbnail && a.__originalVideoUrl) { + links.push(a); + } + }); + + let allSelected = true; + links.forEach(a => { + const url = a.__originalVideoUrl; + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + links.forEach(a => { + const url = a.__originalVideoUrl; + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + links.forEach(a => { + const url = a.__originalVideoUrl; + if (!selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + }); + selectAllBtn.textContent = 'Deseleccionar Todos'; + } + statusDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + }; + + const copyBtn = document.createElement('button'); + copyBtn.textContent = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #f43f5e; + color: white; + border: none; + padding: 10px; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + `; + 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 = '#f43f5e'; + }, 2000); + }); + }; + + container.appendChild(selectAllBtn); + container.appendChild(copyBtn); + container.appendChild(closeBtn); + + // Override cleanup to clear interval and listener + const originalCleanUp = closeBtn.onclick; + closeBtn.onclick = () => { + clearInterval(initInterval); + document.removeEventListener('click', clickHandler, true); + originalCleanUp(); + }; + } +})(); diff --git a/detector de enlaces - copia/src/kemono/downloads.js b/detector de enlaces - copia/src/kemono/downloads.js new file mode 100644 index 0000000000000000000000000000000000000000..c21e883a590ea510298a268d4cbcf0d809eeebb7 --- /dev/null +++ b/detector de enlaces - copia/src/kemono/downloads.js @@ -0,0 +1,544 @@ +(() => { + 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|pawchive\.st)\/[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; + + const isExternal = !h.includes('kemono.cr') && !h.includes('kemono.su') && !h.includes('pawchive.st') && 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)]; + + 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) {} + }); + } + } + 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...'; + + chrome.runtime.sendMessage({ + type: "START_NATIVE_TASK", + payload: { + type: "SAVE_KEMONO", + textLinks: hasLinksElements ? outputWithLinks : "", + textNoLinks: hasNoLinksElements ? outputNoLinks : "" + } + }); + + const onTaskUpdate = (msg) => { + const payload = msg.payload || msg; + if (payload && payload.type === "SAVE_KEMONO") { + if (payload.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); + } else if (payload.status === "progress") { + if (payload.info) copyBtn.textContent = payload.info; + } else if (payload.status === "error") { + console.error("Native Error:", payload.error || payload.info); + copyBtn.textContent = payload.info || 'Error en Python'; + copyBtn.style.background = '#ef4444'; + setTimeout(() => { + copyBtn.textContent = ogText; + copyBtn.style.background = '#fbbf24'; + copyBtn.style.color = '#000'; + copyBtn.disabled = false; + }, 4000); + } + } + }; + + chrome.runtime.onMessage.addListener((msg) => { + if (msg.type === "TASK_UPDATE") { + onTaskUpdate(msg.payload); + } + }); + + } 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; + }; +})(); diff --git a/detector de enlaces - copia/src/kemono/images.js b/detector de enlaces - copia/src/kemono/images.js new file mode 100644 index 0000000000000000000000000000000000000000..fdbb8b57613945f56fc2df8e0bb338fb968b643f --- /dev/null +++ b/detector de enlaces - copia/src/kemono/images.js @@ -0,0 +1,546 @@ +(() => { + 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|pawchive\.st)\/[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 = 16; + 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 || ''); + + 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); + } + }); + + 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)]; + + 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) || []; + 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...'; + + chrome.runtime.sendMessage({ + type: "START_NATIVE_TASK", + payload: { + type: "DOWNLOAD_IMAGES_KEMONO", + data: extractionPayload + } + }); + + const onTaskUpdate = (msg) => { + const payload = msg.payload || msg; + if (payload && payload.type === "DOWNLOAD_IMAGES_KEMONO") { + if (payload.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; } + } else if (payload.status === "progress") { + if (payload.info) { + copyBtn.textContent = payload.info; + } else if (payload.current) { + copyBtn.textContent = `Procesando ${payload.current}/${payload.total}...`; + } + } else if (payload.status === "error") { + console.error("Native Error:", payload.error || payload.info); + copyBtn.textContent = payload.info || '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; } + } + } + }; + + chrome.runtime.onMessage.addListener((msg) => { + if (msg.type === "TASK_UPDATE") { + onTaskUpdate(msg.payload); + } + }); + + } 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; + }; +})(); diff --git a/detector de enlaces - copia/src/kemono/selector.js b/detector de enlaces - copia/src/kemono/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..d1283a29ef49fba234cae402e6696c1948d53b7e --- /dev/null +++ b/detector de enlaces - copia/src/kemono/selector.js @@ -0,0 +1,267 @@ +(() => { + if (document.getElementById('kemono-floating-ui')) 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) { + 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 { + 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); + }); + }; + + 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; + + window.dispatchEvent(new Event('KEMONO_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/ladys/quick_scan.js b/detector de enlaces - copia/src/ladys/quick_scan.js new file mode 100644 index 0000000000000000000000000000000000000000..c000ec43cc009804034a9937879e0e398ab7831f --- /dev/null +++ b/detector de enlaces - copia/src/ladys/quick_scan.js @@ -0,0 +1,82 @@ +(() => { + try { + const videoCards = document.querySelectorAll('#profile-public-tabs-tabpane-videos .c-b_cq, .c-b_cq'); + const results = []; + const seenUrls = new Set(); + + videoCards.forEach(card => { + const titleLink = card.querySelector('a.c-b_ct'); + const video = card.querySelector('video'); + + let videoUrl = ''; + let thumbnailUrl = ''; + let videoTitle = titleLink ? titleLink.innerText.trim() : ''; + + if (video) { + const contentMeta = video.querySelector('meta[itemprop="contentUrl"]'); + const thumbMeta = video.querySelector('meta[itemprop="thumbnailUrl"]'); + const nameMeta = video.querySelector('meta[itemprop="name"]'); + + if (contentMeta) videoUrl = contentMeta.getAttribute('content'); + if (thumbMeta) thumbnailUrl = thumbMeta.getAttribute('content'); + if (nameMeta && !videoTitle) videoTitle = nameMeta.getAttribute('content'); + } + + // If no video tag with microdata, look for any video source or direct mp4 links in card + if (!videoUrl && video) { + if (video.src && !video.src.startsWith('blob:')) videoUrl = video.src; + video.querySelectorAll('source').forEach(s => { + if (s.src && !s.src.startsWith('blob:')) videoUrl = s.src; + }); + } + + // Fallback for title if still empty + if (!videoTitle && card.innerText) { + videoTitle = card.innerText.split('\n')[0].trim(); + } + + if (videoUrl && !seenUrls.has(videoUrl)) { + seenUrls.add(videoUrl); + results.push({ + title: videoTitle || "Video de Ladys.one", + videoUrl: videoUrl, + thumbnailUrl: thumbnailUrl, + postUrl: titleLink ? titleLink.href : window.location.href + }); + } + }); + + // General fallback search for page if no cards found + if (results.length === 0) { + document.querySelectorAll('meta[itemprop="contentUrl"]').forEach(meta => { + const videoUrl = meta.getAttribute('content'); + if (videoUrl && videoUrl.includes('.mp4') && !seenUrls.has(videoUrl)) { + seenUrls.add(videoUrl); + + // Try to find parent/nearby title + let videoTitle = "Video de Ladys.one"; + const parentCard = meta.closest('.c-b_cq') || meta.parentElement; + if (parentCard) { + const titleLink = parentCard.querySelector('a.c-b_ct'); + if (titleLink) videoTitle = titleLink.innerText.trim(); + else { + const nameMeta = parentCard.querySelector('meta[itemprop="name"]'); + if (nameMeta) videoTitle = nameMeta.getAttribute('content'); + } + } + + results.push({ + title: videoTitle, + videoUrl: videoUrl, + thumbnailUrl: '', + postUrl: window.location.href + }); + } + }); + } + + return { videos: results }; + } catch(e) { + return { error: e.message }; + } +})(); diff --git a/detector de enlaces - copia/src/leakgallery/quick_scan.js b/detector de enlaces - copia/src/leakgallery/quick_scan.js new file mode 100644 index 0000000000000000000000000000000000000000..b20f2b70e62108472b686be1556fbed41883042f --- /dev/null +++ b/detector de enlaces - copia/src/leakgallery/quick_scan.js @@ -0,0 +1,30 @@ +(() => { + try { + const mediaElements = document.querySelectorAll('#scroller .media-content, .media-content'); + const results = []; + mediaElements.forEach(el => { + // Only include videos: must have play icon + const hasPlayIcon = !!el.querySelector('#play') || el.innerHTML.includes('icon-play.svg') || el.innerHTML.includes('logo/icon-play'); + if (!hasPlayIcon) return; + + const detailPath = el.getAttribute('href'); + if (!detailPath) return; + + const postUrl = detailPath.startsWith('http') ? detailPath : (window.location.origin + detailPath); + const thumbImg = el.querySelector('.thumbnail-container img') || el.querySelector('img'); + + // Generate a placeholder title since cards may not have text titles on profile view + const postId = detailPath.split('/').pop() || ''; + const title = "Video #" + postId; + + results.push({ + title: title, + postUrl: postUrl, + thumbnailUrl: thumbImg ? thumbImg.src : '' + }); + }); + return { videos: results }; + } catch(e) { + return { error: e.message }; + } +})(); diff --git a/detector de enlaces - copia/src/pornhub/selector.js b/detector de enlaces - copia/src/pornhub/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..fd20fa246d430c99c62593909bb7b33ea06563ac --- /dev/null +++ b/detector de enlaces - copia/src/pornhub/selector.js @@ -0,0 +1,372 @@ +(() => { + if (document.getElementById('pornhub-floating-ui')) return; + window.__pornhubSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'pornhub-floating-ui'; + container.style.cssText = ` + position: fixed; + bottom: 20px; + right: 20px; + background: #18181b; + color: #fff; + padding: 16px; + border-radius: 12px; + border: 1px solid #27272a; + z-index: 2147483647; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.6); + display: flex; + flex-direction: column; + gap: 10px; + min-width: 220px; + user-select: none; + `; + + const countDisplay = document.createElement('div'); + countDisplay.textContent = '0 enlaces seleccionados'; + countDisplay.style.cssText = ` + font-weight: 700; + text-align: center; + font-size: 15px; + color: #ffffff; + margin-bottom: 2px; + `; + + const selectAllBtn = document.createElement('button'); + selectAllBtn.textContent = 'Seleccionar Todos'; + selectAllBtn.style.cssText = ` + background: #3f3f46; + color: #ffffff; + border: none; + padding: 9px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 600; + font-size: 13.5px; + transition: background 0.2s ease; + `; + selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; + selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; + + const copyBtn = document.createElement('button'); + copyBtn.textContent = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #ff9000; + color: #ffffff; + border: none; + padding: 11px 16px; + border-radius: 8px; + cursor: pointer; + font-weight: 700; + font-size: 15px; + transition: background 0.2s ease, transform 0.1s ease; + `; + copyBtn.onmouseover = () => copyBtn.style.background = '#e68200'; + copyBtn.onmouseout = () => copyBtn.style.background = '#ff9000'; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'pornhub-close-btn'; + closeBtn.textContent = 'Cerrar Selector'; + closeBtn.style.cssText = ` + background: #27272a; + color: #e4e4e7; + border: 1px solid #3f3f46; + padding: 8px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 500; + font-size: 13px; + transition: background 0.2s ease; + `; + closeBtn.onmouseover = () => closeBtn.style.background = '#3f3f46'; + closeBtn.onmouseout = () => closeBtn.style.background = '#27272a'; + + container.appendChild(countDisplay); + container.appendChild(selectAllBtn); + container.appendChild(copyBtn); + container.appendChild(closeBtn); + (document.body || document.documentElement).appendChild(container); + + const style = document.createElement('style'); + style.id = 'pornhub-selector-style'; + style.textContent = ` + .pornhub-selector-hover { + box-shadow: inset 0 0 0 4px #ff9000 !important, 0 0 12px rgba(255, 144, 0, 0.6) !important; + cursor: crosshair !important; + transition: all 0.15s ease; + position: relative !important; + z-index: 9999 !important; + } + .pornhub-selector-selected { + box-shadow: inset 0 0 0 4px #10b981 !important, 0 0 15px rgba(16, 185, 129, 0.7) !important; + outline: 4px solid #10b981 !important; + outline-offset: -4px !important; + position: relative !important; + z-index: 9998 !important; + } + .pornhub-selector-selected::after, + .pornhub-selector-selected:hover::after { + content: '✓' !important; + position: absolute !important; + top: 8px !important; + left: 8px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 6px rgba(0,0,0,0.6) !important; + pointer-events: none !important; + } + `; + (document.head || document.documentElement).appendChild(style); + + // Helper to extract clean video URL from Pornhub anchor or string + const getCleanUrl = (hrefOrAnchor) => { + if (!hrefOrAnchor) return ''; + let raw = typeof hrefOrAnchor === 'string' ? hrefOrAnchor : (hrefOrAnchor.href || hrefOrAnchor.getAttribute('href') || ''); + if (!raw) return ''; + try { + const match = raw.match(/view_video\.php\?viewkey=([a-zA-Z0-9]+)/i); + if (match && match[1]) { + const origin = window.location.origin && window.location.origin.includes('pornhub.com') + ? window.location.origin + : 'https://es.pornhub.com'; + return `${origin}/view_video.php?viewkey=${match[1]}`; + } + return ''; + } catch(e) { + return ''; + } + }; + + const isVideoUrl = (url) => { + return !!url && url.includes('view_video.php?viewkey='); + }; + + // Find the enclosing video card container or anchor on Pornhub + const getPostCard = (el) => { + if (!el || el.closest('#pornhub-floating-ui')) return null; + + // Check if el or ancestor is inside a video card element + const card = el.closest('li.videoblock, .pcVideoListItem, .videoBox, .phimage, li[data-video-vkey], div[data-video-vkey], .b-model-videos__item, .video-card, [data-vkey], .wrapper'); + + let anchor = el.closest('a'); + if (!anchor && card) { + anchor = card.querySelector('a[href*="view_video.php"]'); + } + + if (!anchor) return null; + + const url = getCleanUrl(anchor); + if (!isVideoUrl(url)) return null; + + const finalCard = card || anchor.closest('li, .phimage, .videoBox') || anchor; + + return { card: finalCard, anchor, url }; + }; + + // Get visual element to highlight + const getVisualTarget = (cardObj) => { + if (!cardObj) return null; + const { card, anchor } = cardObj; + let target = card.querySelector('.phimage, .thumbnail-info-wrapper, .videoBox, .img, p.title') || anchor || card; + if (target && target.tagName === 'IMG') { + target = target.parentElement || target; + } + return target; + }; + + const toggleCardSelection = (url, select) => { + document.querySelectorAll('li.videoblock, .pcVideoListItem, .videoBox, .phimage, li[data-video-vkey], div[data-video-vkey], .b-model-videos__item, .video-card, a[href*="view_video.php"]').forEach(el => { + const cardObj = getPostCard(el); + if (cardObj && cardObj.url === url) { + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + if (select) { + visualTarget.classList.add('pornhub-selector-selected'); + visualTarget.classList.remove('pornhub-selector-hover'); + } else { + visualTarget.classList.remove('pornhub-selector-selected'); + } + } + } + }); + }; + + let isDragging = false; + let dragMode = null; + + const mouseOver = (e) => { + if (e.target.closest('#pornhub-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + const { url } = cardObj; + const visualTarget = getVisualTarget(cardObj); + if (!visualTarget) return; + + if (isDragging) { + e.preventDefault(); + e.stopPropagation(); + + if (dragMode === 'select' && !selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!visualTarget.classList.contains('pornhub-selector-selected')) { + visualTarget.classList.add('pornhub-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + if (e.target.closest('#pornhub-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + visualTarget.classList.remove('pornhub-selector-hover'); + } + } + }; + + const mouseDown = (e) => { + if (e.target.closest('#pornhub-floating-ui')) return; + + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); + isDragging = true; + + const { url } = cardObj; + + if (selectedLinks.has(url)) { + dragMode = 'deselect'; + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + dragMode = 'select'; + selectedLinks.add(url); + toggleCardSelection(url, true); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } + }; + + const mouseUp = () => { + isDragging = false; + dragMode = null; + }; + + const dragStart = (e) => { + if (e.target.closest('#pornhub-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + } + }; + + const click = (e) => { + if (e.target.closest('#pornhub-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); + } + }; + + 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 videoUrls = new Set(); + document.querySelectorAll('a[href*="view_video.php"]').forEach(a => { + const url = getCleanUrl(a); + if (isVideoUrl(url)) { + videoUrls.add(url); + } + }); + + let allSelected = true; + videoUrls.forEach(url => { + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + videoUrls.forEach(url => { + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + videoUrls.forEach(url => { + selectedLinks.add(url); + toggleCardSelection(url, true); + }); + 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; + const ogBg = copyBtn.style.background; + copyBtn.textContent = '¡Copiados!'; + copyBtn.style.background = '#10b981'; + setTimeout(() => { + copyBtn.textContent = ogText; + copyBtn.style.background = ogBg || '#ff9000'; + }, 2000); + }); + }; + + 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('.pornhub-selector-selected').forEach(el => el.classList.remove('pornhub-selector-selected')); + document.querySelectorAll('.pornhub-selector-hover').forEach(el => el.classList.remove('pornhub-selector-hover')); + window.__pornhubSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'pornhub' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('PORNHUB_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/tiktok/selector.js b/detector de enlaces - copia/src/tiktok/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..8dccf8cfcde87a5665c3e61e2f83b011b4d76fe2 --- /dev/null +++ b/detector de enlaces - copia/src/tiktok/selector.js @@ -0,0 +1,358 @@ +(() => { + if (document.getElementById('tiktok-floating-ui')) 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 videos y fotos'; + 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('a[href*="/photo/"]') || 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/"]') || card.querySelector('a[href*="/photo/"]')); + 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/"]') || card.querySelector('a[href*="/photo/"]')); + 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 videos y fotos'; + 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/"], a[href*="/photo/"]'); + 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 videos y fotos'; + autoScanBtn.style.background = '#ff0050'; + } + } else { + retries = 0; + } + lastHeight = document.body.scrollHeight; + }, 2000); + }; + + selectAllBtn.onclick = () => { + const links = document.querySelectorAll('a[href*="/video/"], a[href*="/photo/"]'); + 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 videos = []; + const photos = []; + + selectedLinks.forEach(url => { + if (url.includes('/photo/')) { + photos.push(url); + } else { + videos.push(url); + } + }); + + let text = ''; + if (videos.length > 0 && photos.length > 0) { + text = `=== VIDEOS ===\n${videos.join('\n')}\n\n=== IMAGENES ===\n${photos.join('\n')}`; + } else if (photos.length > 0) { + text = photos.join('\n'); + } else { + text = videos.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')); + }; +})(); diff --git a/detector de enlaces - copia/src/twpornstars/quick_scan.js b/detector de enlaces - copia/src/twpornstars/quick_scan.js new file mode 100644 index 0000000000000000000000000000000000000000..9b3bfa3032178eab9adf0787db9b55c1f5f43c96 --- /dev/null +++ b/detector de enlaces - copia/src/twpornstars/quick_scan.js @@ -0,0 +1,50 @@ +(() => { + try { + const thumbs = document.querySelectorAll('.thumb[data-isvideo="1"], .thumb'); + const results = []; + thumbs.forEach(thumb => { + // Check if it's a video: either data-isvideo="1" or contains thumb__video_icon + const isVideo = thumb.getAttribute('data-isvideo') === '1' || !!thumb.querySelector('.thumb__video_icon'); + if (!isVideo) return; + + const linkEl = thumb.querySelector('.thumb__link'); + const imgEl = thumb.querySelector('.thumb__img'); + const infoTextEl = thumb.querySelector('.thumb__info_text') || thumb.querySelector('.thumb__title'); + + if (linkEl && linkEl.href) { + let title = infoTextEl ? infoTextEl.textContent.trim() : ''; + if (!title && imgEl && imgEl.alt) { + title = imgEl.alt.trim(); + } + if (!title) { + title = "Video " + linkEl.href.split('/').pop(); + } + results.push({ + title: title, + postUrl: linkEl.href, + thumbnailUrl: imgEl ? imgEl.src : '' + }); + } + }); + const pagination = document.querySelector('.pagination'); + let maxPage = 1; + if (pagination) { + pagination.querySelectorAll('li').forEach(li => { + const num = parseInt(li.textContent.trim(), 10); + if (!isNaN(num) && num > maxPage) { + maxPage = num; + } + }); + } + + const baseUrl = window.location.origin + window.location.pathname; + + return { + videos: results, + maxPage: maxPage, + baseUrl: baseUrl + }; + } catch(e) { + return { error: e.message }; + } +})(); diff --git a/detector de enlaces - copia/src/x/auto_extractor.js b/detector de enlaces - copia/src/x/auto_extractor.js new file mode 100644 index 0000000000000000000000000000000000000000..caedfbaa2c81f2fb844347d66d2c374fe245cd9e --- /dev/null +++ b/detector de enlaces - copia/src/x/auto_extractor.js @@ -0,0 +1,198 @@ +(() => { + if (window.__xExtractorActive) return; + window.__xExtractorActive = true; + + const collectedVideos = new Map(); // url -> { url, title, thumb } + + const container = document.createElement('div'); + container.id = 'x-extractor-ui'; + container.style.cssText = ` + position: fixed; + bottom: 20px; + right: 20px; + background: #000; + color: #fff; + padding: 15px; + border-radius: 10px; + border: 1px solid #333; + z-index: 999999; + font-family: sans-serif; + box-shadow: 0 4px 12px rgba(255,255,255,0.2); + display: flex; + flex-direction: column; + gap: 10px; + min-width: 250px; + `; + + const titleDisplay = document.createElement('div'); + titleDisplay.innerHTML = 'Extractor de Videos X'; + titleDisplay.style.textAlign = 'center'; + titleDisplay.style.fontSize = '15px'; + + const countDisplay = document.createElement('div'); + countDisplay.textContent = '0 videos encontrados'; + countDisplay.style.fontWeight = 'bold'; + countDisplay.style.textAlign = 'center'; + countDisplay.style.fontSize = '18px'; + countDisplay.style.color = '#1da1f2'; + + const statusDisplay = document.createElement('div'); + statusDisplay.textContent = 'Listo para escanear.'; + statusDisplay.style.textAlign = 'center'; + statusDisplay.style.fontSize = '12px'; + statusDisplay.style.color = '#888'; + + const autoScanBtn = document.createElement('button'); + autoScanBtn.textContent = 'Iniciar Búsqueda Automática (Scroll)'; + autoScanBtn.style.cssText = ` + background: #1da1f2; + 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 closeBtn = document.createElement('button'); + closeBtn.id = 'x-close-btn'; + closeBtn.textContent = 'Cerrar Extractor'; + closeBtn.style.cssText = ` + background: #27272a; + color: white; + border: 1px solid #3f3f46; + padding: 8px; + border-radius: 6px; + cursor: pointer; + font-size: 13px; + `; + + container.appendChild(titleDisplay); + container.appendChild(countDisplay); + container.appendChild(statusDisplay); + container.appendChild(autoScanBtn); + container.appendChild(copyBtn); + container.appendChild(closeBtn); + document.body.appendChild(container); + + let scanInterval = null; + let isScanning = false; + let maxRetries = 10; // Aumentar reintentos antes de rendirse + + autoScanBtn.onclick = () => { + if (isScanning) { + clearInterval(scanInterval); + isScanning = false; + autoScanBtn.textContent = 'Continuar Búsqueda'; + autoScanBtn.style.background = '#1da1f2'; + statusDisplay.textContent = 'Búsqueda pausada.'; + return; + } + + isScanning = true; + autoScanBtn.textContent = 'Detener Búsqueda'; + autoScanBtn.style.background = '#e0245e'; + statusDisplay.textContent = 'Haciendo scroll y buscando videos...'; + + let lastHeight = 0; + let retries = 0; + + scanInterval = setInterval(() => { + // Scroll progresivo en lugar de ir directo al fondo para no atascar React + window.scrollBy(0, 1000); + + // Buscar enlaces a videos o tweets que parezcan videos + const links = document.querySelectorAll('a[href*="/status/"]'); + + links.forEach(a => { + let cleanUrl = a.href.split('?')[0]; + + // Es un video si tiene /video/ en la URL, o si tiene un div indicando duración (ej. "4:13") + let isVideo = cleanUrl.includes('/video/'); + if (!isVideo && a.innerText && /^\d+:\d+$/.test(a.innerText.trim())) { + isVideo = true; + } + // Si el link de la cuadricula no termina en /video/1, se lo agregamos si estamos seguros que es video + if (isVideo && !cleanUrl.includes('/video/')) { + if (!cleanUrl.endsWith('/')) cleanUrl += '/'; + cleanUrl += 'video/1'; + } + + if (isVideo && !collectedVideos.has(cleanUrl)) { + collectedVideos.set(cleanUrl, true); + + // Feedback visual (borde verde y opacidad) + a.style.outline = '4px solid #10b981'; + a.style.opacity = '0.8'; + a.style.position = 'relative'; + + // Agregar marca de verificación visual si no la tiene + if (!a.querySelector('.x-check-mark')) { + const check = document.createElement('div'); + check.className = 'x-check-mark'; + check.innerHTML = '✓'; + check.style.cssText = '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);'; + a.appendChild(check); + } + } + }); + + countDisplay.textContent = collectedVideos.size + ' videos encontrados'; + + let currentScroll = window.scrollY || document.documentElement.scrollTop; + if (currentScroll === lastHeight) { + retries++; + // Darle un pequeño empujón hacia arriba y abajo por si se atascó + if (retries === 3) window.scrollBy(0, -500); + if (retries === 4) window.scrollBy(0, 800); + + if (retries >= maxRetries) { + clearInterval(scanInterval); + isScanning = false; + autoScanBtn.textContent = 'Búsqueda finalizada'; + autoScanBtn.style.background = '#1da1f2'; + autoScanBtn.disabled = true; + statusDisplay.textContent = 'Llegaste al final de la página.'; + } + } else { + retries = 0; + } + lastHeight = currentScroll; + }, 1000); + }; + + copyBtn.onclick = () => { + if (collectedVideos.size === 0) return; + const urls = Array.from(collectedVideos.keys()); + const text = urls.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); + isScanning = false; + container.remove(); + window.__xExtractorActive = false; + }; +})(); diff --git a/detector de enlaces - copia/src/x/quick_scan.js b/detector de enlaces - copia/src/x/quick_scan.js new file mode 100644 index 0000000000000000000000000000000000000000..bf479a73e88e527b570281fc3c670fe630a031f5 --- /dev/null +++ b/detector de enlaces - copia/src/x/quick_scan.js @@ -0,0 +1,55 @@ +(() => { + try { + const results = []; + const seenUrls = new Set(); + + // Buscar imágenes + const images = document.querySelectorAll('img[src*="twimg.com/media"]'); + images.forEach(img => { + let url = img.src; + // Convertir a calidad original (orig) + if (url.includes('name=')) { + url = url.replace(/name=[^&]+/, 'name=orig'); + } else { + url = url + '&name=orig'; + } + + if (!seenUrls.has(url)) { + seenUrls.add(url); + results.push({ + title: 'X Media Image', + mediaUrl: url, + thumbnailUrl: img.src, + type: 'image' + }); + } + }); + + // Intentar buscar videos (usualmente son blobs o m3u8, X usa m3u8 en el DOM a veces si no es blob) + const videos = document.querySelectorAll('video'); + videos.forEach(video => { + let url = video.src; + if (!url || url.startsWith('blob:')) { + // Intentar buscar source + const source = video.querySelector('source'); + if (source && source.src && !source.src.startsWith('blob:')) { + url = source.src; + } + } + + if (url && !url.startsWith('blob:') && !seenUrls.has(url)) { + seenUrls.add(url); + results.push({ + title: 'X Media Video', + mediaUrl: url, + thumbnailUrl: video.getAttribute('poster') || '', + type: 'video' + }); + } + }); + + return { media: results }; + } catch(e) { + return { error: e.message }; + } +})(); diff --git a/detector de enlaces - copia/src/x/selector.js b/detector de enlaces - copia/src/x/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..35167642ae15173dcd322d878cca059f767c3e62 --- /dev/null +++ b/detector de enlaces - copia/src/x/selector.js @@ -0,0 +1,330 @@ +(() => { + if (window.__xSelectorActive) return; + window.__xSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'x-floating-ui'; + container.style.cssText = ` + position: fixed; + bottom: 20px; + right: 20px; + background: #000; + color: #fff; + padding: 15px; + border-radius: 10px; + border: 1px solid #333; + z-index: 999999; + font-family: sans-serif; + box-shadow: 0 4px 12px rgba(255,255,255,0.1); + 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 en pantalla'; + autoScanBtn.style.cssText = ` + background: #1da1f2; + 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: #333; + 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 = '#444'; + selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#333'; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'x-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 = 'x-style'; + style.textContent = ` + .x-selector-hover { + outline: 3px solid #1da1f2 !important; + cursor: crosshair !important; + transition: all 0.2s; + z-index: 10; + } + .x-selector-selected { + outline: 4px solid #10b981 !important; + opacity: 0.8; + position: relative; + z-index: 5; + } + .x-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*="/status/"]'); + }; + + 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('x-selector-selected'); + card.classList.remove('x-selector-hover'); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + card.classList.remove('x-selector-selected'); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!card.classList.contains('x-selector-selected')) { + card.classList.add('x-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + const card = getPostCard(e.target); + if (card) { + card.classList.remove('x-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('x-selector-selected'); + } else { + dragMode = 'select'; + selectedLinks.add(url); + card.classList.add('x-selector-selected'); + card.classList.remove('x-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.__xIsScanning) { + clearInterval(scanInterval); + window.__xIsScanning = false; + autoScanBtn.textContent = 'Buscar enlaces en pantalla'; + autoScanBtn.style.background = '#1da1f2'; + return; + } + + window.__xIsScanning = true; + autoScanBtn.textContent = 'Buscando... (0)'; + autoScanBtn.style.background = '#333'; + + let lastHeight = 0; + let retries = 0; + const maxRetries = 10; + + scanInterval = setInterval(() => { + window.scrollTo(0, document.body.scrollHeight); + + const links = document.querySelectorAll('a[href*="/status/"]'); + let addedNew = false; + links.forEach(a => { + let cleanUrl = a.href.split('?')[0]; + if (!selectedLinks.has(cleanUrl)) { + selectedLinks.add(cleanUrl); + a.classList.add('x-selector-selected'); + a.classList.remove('x-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.__xIsScanning = false; + autoScanBtn.textContent = 'Buscar enlaces en pantalla'; + autoScanBtn.style.background = '#1da1f2'; + } + } else { + retries = 0; + } + lastHeight = document.body.scrollHeight; + }, 2000); + }; + + selectAllBtn.onclick = () => { + const links = document.querySelectorAll('a[href*="/status/"]'); + 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); + a.classList.remove('x-selector-selected'); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + links.forEach(a => { + const url = a.href.split('?')[0]; + if (!selectedLinks.has(url)) { + selectedLinks.add(url); + a.classList.add('x-selector-selected'); + a.classList.remove('x-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.__xIsScanning = 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('.x-selector-selected').forEach(el => el.classList.remove('x-selector-selected')); + document.querySelectorAll('.x-selector-hover').forEach(el => el.classList.remove('x-selector-hover')); + window.__xSelectorActive = false; + }; +})(); diff --git a/detector de enlaces - copia/src/xhamster/selector.js b/detector de enlaces - copia/src/xhamster/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..e42d1b4bc3c408cb8e5c7fb98c6182f7dcf00b8e --- /dev/null +++ b/detector de enlaces - copia/src/xhamster/selector.js @@ -0,0 +1,361 @@ +(() => { + if (window.__xhamsterSelectorActive) return; + window.__xhamsterSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'xh-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 = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #ef4444; + color: white; + border: none; + padding: 10px; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + `; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'xh-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 = 'xh-style'; + style.textContent = ` + .xh-selector-hover { + box-shadow: inset 0 0 0 4px #ef4444 !important, 0 0 10px rgba(239, 68, 68, 0.5) !important; + cursor: crosshair !important; + transition: all 0.2s; + position: relative !important; + z-index: 9999 !important; + } + .xh-selector-selected { + box-shadow: inset 0 0 0 4px #10b981 !important, 0 0 15px rgba(16, 185, 129, 0.6) !important; + position: relative !important; + z-index: 9998 !important; + } + .xh-selector-selected::after, + .xh-selector-selected:hover::after { + content: '✓' !important; + position: absolute !important; + top: 8px !important; + left: 8px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 5px rgba(0,0,0,0.5) !important; + pointer-events: none !important; + } + `; + document.head.appendChild(style); + + // Helper to get normalized URLs for matching + const getCleanUrl = (href) => { + if (!href) return ''; + let url = href.split('?')[0].split('#')[0].trim(); + if (url.endsWith('/')) { + url = url.slice(0, -1); + } + return url; + }; + + // Helper to check if an anchor is a thumbnail cover rather than text title (robust and crash-proof) + const isThumbnailAnchor = (a) => { + if (!a) return false; + + // 1. If it contains an image, video, canvas, or thumbnail class-like elements + if (a.querySelector('img, picture, canvas, video, [class*="thumb"], [class*="img"], [class*="preview"], [class*="cover"]')) return true; + + // 2. Safe class name parsing (prevent crashes on animated SVG string wrappers) + let className = ''; + if (typeof a.className === 'string') { + className = a.className.toLowerCase(); + } else if (a.className && typeof a.className.baseVal === 'string') { + className = a.className.baseVal.toLowerCase(); + } + if (className.includes('thumb') || className.includes('img') || className.includes('preview') || className.includes('cover') || className.includes('vimg')) return true; + + // 3. Fallback: if it has short text content and wraps some tag, it is likely a thumbnail (like XHamster lazy loaders) + const textLen = a.textContent.trim().length; + if (textLen < 15 && a.querySelector('*')) return true; + + return false; + }; + + const getPostCard = (el) => { + const card = el.closest('a[href*="/videos/"], a[href*="/shorts/"]'); + if (!card) return null; + + const url = card.href.toLowerCase(); + // Ignore creator pages, main page directories and creator pagination pages (e.g. /creators/.../shorts/2) + if (url.includes('/creators/')) return null; + if (url.endsWith('/shorts') || url.endsWith('/shorts/') || url.endsWith('/videos') || url.endsWith('/videos/')) return null; + + return card; + }; + + const getThumbnailAnchorForUrl = (url) => { + let thumb = null; + document.querySelectorAll('a[href*="/videos/"], a[href*="/shorts/"]').forEach(a => { + if (getCleanUrl(a.href) === url) { + if (isThumbnailAnchor(a)) { + thumb = a; + } + } + }); + return thumb; + }; + + const getVisualTarget = (card) => { + // Target the parent container of the thumbnail (e.g. .thumb div) instead of the anchor itself + // so the selection outline and checkmark remain visible even if the anchor is set to display: none on hover. + return card.closest('.thumb, .vimg, .video-thumb, .image-wrap') || card.parentElement || card; + }; + + const toggleCardSelection = (url, select) => { + document.querySelectorAll('a[href*="/videos/"], a[href*="/shorts/"]').forEach(a => { + if (getCleanUrl(a.href) === url) { + if (isThumbnailAnchor(a)) { + const visualTarget = getVisualTarget(a); + if (select) { + visualTarget.classList.add('xh-selector-selected'); + visualTarget.classList.remove('xh-selector-hover'); + } else { + visualTarget.classList.remove('xh-selector-selected'); + } + } + } + }); + }; + + let isDragging = false; + let dragMode = null; + + const mouseOver = (e) => { + const card = getPostCard(e.target); + if (card) { + const url = getCleanUrl(card.href); + const thumb = getThumbnailAnchorForUrl(url) || card; + const visualTarget = getVisualTarget(thumb); + + if (isDragging) { + e.preventDefault(); + e.stopPropagation(); + + if (dragMode === 'select' && !selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!visualTarget.classList.contains('xh-selector-selected')) { + visualTarget.classList.add('xh-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + const card = getPostCard(e.target); + if (card) { + const url = getCleanUrl(card.href); + const thumb = getThumbnailAnchorForUrl(url) || card; + const visualTarget = getVisualTarget(thumb); + visualTarget.classList.remove('xh-selector-hover'); + } + }; + + const mouseDown = (e) => { + const card = getPostCard(e.target); + if (card) { + e.preventDefault(); + e.stopPropagation(); + isDragging = true; + + const url = getCleanUrl(card.href); + + if (selectedLinks.has(url)) { + dragMode = 'deselect'; + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + dragMode = 'select'; + selectedLinks.add(url); + toggleCardSelection(url, true); + } + 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(); + e.stopPropagation(); + } + }; + + 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 links = []; + document.querySelectorAll('a[href*="/videos/"], a[href*="/shorts/"]').forEach(a => { + const url = a.href.toLowerCase(); + if (!url.includes('/creators/') && !url.endsWith('/shorts') && !url.endsWith('/shorts/') && !url.endsWith('/videos') && !url.endsWith('/videos/')) { + if (isThumbnailAnchor(a)) { + links.push(a); + } + } + }); + + let allSelected = true; + links.forEach(a => { + const url = getCleanUrl(a.href); + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + links.forEach(a => { + const url = getCleanUrl(a.href); + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + links.forEach(a => { + const url = getCleanUrl(a.href); + if (!selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + }); + 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 = '#ef4444'; + }, 2000); + }); + }; + + 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('.xh-selector-selected').forEach(el => el.classList.remove('xh-selector-selected')); + document.querySelectorAll('.xh-selector-hover').forEach(el => el.classList.remove('xh-selector-hover')); + window.__xhamsterSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'xhamster' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('XH_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/xhand/selector.js b/detector de enlaces - copia/src/xhand/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..c1a9955cafa2ba69cc71ab16e57c363a0ebad334 --- /dev/null +++ b/detector de enlaces - copia/src/xhand/selector.js @@ -0,0 +1,358 @@ +(() => { + if (window.__xhandSelectorActive) return; + window.__xhandSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'xhand-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 = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #a78bfa; + color: white; + border: none; + padding: 10px; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + `; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'xhand-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 = 'xhand-style'; + style.textContent = ` + .xhand-selector-hover { + box-shadow: inset 0 0 0 4px #a78bfa !important, 0 0 10px rgba(167, 139, 250, 0.5) !important; + cursor: crosshair !important; + transition: all 0.2s; + position: relative !important; + z-index: 9999 !important; + } + .xhand-selector-selected { + box-shadow: inset 0 0 0 4px #10b981 !important, 0 0 15px rgba(16, 185, 129, 0.6) !important; + position: relative !important; + z-index: 9998 !important; + } + .xhand-selector-selected::after, + .xhand-selector-selected:hover::after { + content: '✓' !important; + position: absolute !important; + top: 8px !important; + left: 8px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 5px rgba(0,0,0,0.5) !important; + pointer-events: none !important; + } + `; + document.head.appendChild(style); + + // Helper to get normalized URLs for matching + const getCleanUrl = (href) => { + if (!href) return ''; + let url = href.trim(); + let clean = url.split('?')[0].split('#')[0].trim(); + if (!clean.endsWith('/')) { + clean = clean + '/'; + } + return clean; + }; + + // Helper to check if an anchor is a thumbnail cover rather than text title (robust and crash-proof) + const isThumbnailAnchor = (a) => { + if (!a) return false; + + // 1. If it contains an image, video, canvas, or thumbnail class-like elements + if (a.querySelector('img, picture, canvas, video, [class*="thumb"], [class*="img"], [class*="preview"], [class*="cover"]')) return true; + + // 2. Safe class name parsing (prevent crashes on animated SVG string wrappers) + let className = ''; + if (typeof a.className === 'string') { + className = a.className.toLowerCase(); + } else if (a.className && typeof a.className.baseVal === 'string') { + className = a.className.baseVal.toLowerCase(); + } + if (className.includes('thumb') || className.includes('img') || className.includes('preview') || className.includes('cover') || className.includes('vimg')) return true; + + // 3. Fallback: if it has short text content and wraps some tag, it is likely a thumbnail + const textLen = a.textContent.trim().length; + if (textLen < 15 && a.querySelector('*')) return true; + + return false; + }; + + const getPostCard = (el) => { + const card = el.closest('a[href*="/videos/"]'); + if (!card) return null; + + const url = card.href.toLowerCase(); + if (url.endsWith('/videos') || url.endsWith('/videos/')) return null; + + return card; + }; + + const getThumbnailAnchorForUrl = (url) => { + let thumb = null; + document.querySelectorAll('a[href*="/videos/"]').forEach(a => { + if (getCleanUrl(a.href) === url) { + if (isThumbnailAnchor(a)) { + thumb = a; + } + } + }); + return thumb; + }; + + const getVisualTarget = (card) => { + return card.closest('.thumb, .vimg, .video-thumb, .image-wrap, .card') || card.parentElement || card; + }; + + const toggleCardSelection = (url, select) => { + document.querySelectorAll('a[href*="/videos/"]').forEach(a => { + if (getCleanUrl(a.href) === url) { + if (isThumbnailAnchor(a)) { + const visualTarget = getVisualTarget(a); + if (select) { + visualTarget.classList.add('xhand-selector-selected'); + visualTarget.classList.remove('xhand-selector-hover'); + } else { + visualTarget.classList.remove('xhand-selector-selected'); + } + } + } + }); + }; + + let isDragging = false; + let dragMode = null; + + const mouseOver = (e) => { + const card = getPostCard(e.target); + if (card) { + const url = getCleanUrl(card.href); + const thumb = getThumbnailAnchorForUrl(url) || card; + const visualTarget = getVisualTarget(thumb); + + if (isDragging) { + e.preventDefault(); + e.stopPropagation(); + + if (dragMode === 'select' && !selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!visualTarget.classList.contains('xhand-selector-selected')) { + visualTarget.classList.add('xhand-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + const card = getPostCard(e.target); + if (card) { + const url = getCleanUrl(card.href); + const thumb = getThumbnailAnchorForUrl(url) || card; + const visualTarget = getVisualTarget(thumb); + visualTarget.classList.remove('xhand-selector-hover'); + } + }; + + const mouseDown = (e) => { + const card = getPostCard(e.target); + if (card) { + e.preventDefault(); + e.stopPropagation(); + isDragging = true; + + const url = getCleanUrl(card.href); + + if (selectedLinks.has(url)) { + dragMode = 'deselect'; + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + dragMode = 'select'; + selectedLinks.add(url); + toggleCardSelection(url, true); + } + 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(); + e.stopPropagation(); + } + }; + + 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 links = []; + document.querySelectorAll('a[href*="/videos/"]').forEach(a => { + const url = a.href.toLowerCase(); + if (!url.endsWith('/videos') && !url.endsWith('/videos/')) { + if (isThumbnailAnchor(a)) { + links.push(a); + } + } + }); + + let allSelected = true; + links.forEach(a => { + const url = getCleanUrl(a.href); + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + links.forEach(a => { + const url = getCleanUrl(a.href); + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + links.forEach(a => { + const url = getCleanUrl(a.href); + if (!selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } + }); + 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 = '#a78bfa'; + }, 2000); + }); + }; + + 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('.xhand-selector-selected').forEach(el => el.classList.remove('xhand-selector-selected')); + document.querySelectorAll('.xhand-selector-hover').forEach(el => el.classList.remove('xhand-selector-hover')); + window.__xhandSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'xhand' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('XHAND_OFF')); + }; +})(); diff --git a/detector de enlaces - copia/src/xvideos/quick_scan.js b/detector de enlaces - copia/src/xvideos/quick_scan.js new file mode 100644 index 0000000000000000000000000000000000000000..824aa4631025249289aeebd51b97d25884a7f36c --- /dev/null +++ b/detector de enlaces - copia/src/xvideos/quick_scan.js @@ -0,0 +1,78 @@ +(() => { + try { + const thumbs = document.querySelectorAll('.thumb-block, div[id^="video_"]'); + const results = []; + const seenUrls = new Set(); + + thumbs.forEach(thumb => { + const linkEl = thumb.querySelector('a'); + if (!linkEl) return; + + let href = linkEl.getAttribute('href'); + if (!href) return; + + // Skip actual image/gallery links if any (though on video tab they should be videos) + if (href.includes('/gallery') || href.includes('.jpg') || href.includes('.png')) { + return; + } + + const postUrl = new URL(href, window.location.origin).href; + + if (seenUrls.has(postUrl)) return; + + // Extract title + const titleEl = thumb.querySelector('p.title a') || thumb.querySelector('.title a') || thumb.querySelector('p a') || thumb.querySelector('img'); + let title = ''; + if (titleEl) { + if (titleEl.tagName === 'IMG') { + title = titleEl.getAttribute('alt') || titleEl.getAttribute('title') || ''; + } else { + title = titleEl.textContent.trim(); + } + } + if (!title) { + title = "Video XVideos"; + } + + // Extract thumbnail + const imgEl = thumb.querySelector('img'); + let thumbnailUrl = ''; + if (imgEl) { + thumbnailUrl = imgEl.getAttribute('data-src') || imgEl.getAttribute('src') || ''; + } + + seenUrls.add(postUrl); + results.push({ + title: title, + postUrl: postUrl, + thumbnailUrl: thumbnailUrl + }); + }); + + // Find max page + let maxPage = 1; + const paginationLinks = document.querySelectorAll('.pagination a, .pagination li a, .pagination span'); + paginationLinks.forEach(link => { + const num = parseInt(link.textContent.trim(), 10); + if (!isNaN(num) && num > maxPage) { + maxPage = num; + } + }); + + // Construct AJAX Base URL + const pathParts = window.location.pathname.split('/').filter(Boolean); + let username = ''; + if (pathParts.length > 0) { + username = pathParts[0] === 'profiles' ? pathParts[1] : pathParts[0]; + } + const ajaxBaseUrl = username ? (window.location.origin + '/profiles/' + username + '/videos/uploads/') : ''; + + return { + videos: results, + maxPage: maxPage, + ajaxBaseUrl: ajaxBaseUrl + }; + } catch(e) { + return { error: e.message }; + } +})(); diff --git a/detector de enlaces - copia/src/xvideos/selector.js b/detector de enlaces - copia/src/xvideos/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..870d3370082a0ba63ec3563a1399dc4d0e74e2dd --- /dev/null +++ b/detector de enlaces - copia/src/xvideos/selector.js @@ -0,0 +1,403 @@ +(() => { + if (document.getElementById('xvideos-floating-ui')) return; + window.__xvideosSelectorActive = true; + + const selectedLinks = new Set(); + + const container = document.createElement('div'); + container.id = 'xvideos-floating-ui'; + container.style.cssText = ` + position: fixed; + bottom: 20px; + right: 20px; + background: #18181b; + color: #fff; + padding: 16px; + border-radius: 12px; + border: 1px solid #27272a; + z-index: 2147483647; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.6); + display: flex; + flex-direction: column; + gap: 10px; + min-width: 220px; + user-select: none; + `; + + const countDisplay = document.createElement('div'); + countDisplay.textContent = '0 enlaces seleccionados'; + countDisplay.style.cssText = ` + font-weight: 700; + text-align: center; + font-size: 15px; + color: #ffffff; + margin-bottom: 2px; + `; + + const selectAllBtn = document.createElement('button'); + selectAllBtn.textContent = 'Seleccionar Todos'; + selectAllBtn.style.cssText = ` + background: #3f3f46; + color: #ffffff; + border: none; + padding: 9px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 600; + font-size: 13.5px; + transition: background 0.2s ease; + `; + selectAllBtn.onmouseover = () => selectAllBtn.style.background = '#52525b'; + selectAllBtn.onmouseout = () => selectAllBtn.style.background = '#3f3f46'; + + const copyBtn = document.createElement('button'); + copyBtn.textContent = 'Copiar Enlaces'; + copyBtn.style.cssText = ` + background: #8b5cf6; + color: #ffffff; + border: none; + padding: 11px 16px; + border-radius: 8px; + cursor: pointer; + font-weight: 700; + font-size: 15px; + transition: background 0.2s ease, transform 0.1s ease; + `; + copyBtn.onmouseover = () => copyBtn.style.background = '#7c3aed'; + copyBtn.onmouseout = () => copyBtn.style.background = '#8b5cf6'; + + const closeBtn = document.createElement('button'); + closeBtn.id = 'xvideos-close-btn'; + closeBtn.textContent = 'Cerrar Selector'; + closeBtn.style.cssText = ` + background: #27272a; + color: #e4e4e7; + border: 1px solid #3f3f46; + padding: 8px 12px; + border-radius: 8px; + cursor: pointer; + font-weight: 500; + font-size: 13px; + transition: background 0.2s ease; + `; + closeBtn.onmouseover = () => closeBtn.style.background = '#3f3f46'; + closeBtn.onmouseout = () => closeBtn.style.background = '#27272a'; + + container.appendChild(countDisplay); + container.appendChild(selectAllBtn); + container.appendChild(copyBtn); + container.appendChild(closeBtn); + (document.body || document.documentElement).appendChild(container); + + const style = document.createElement('style'); + style.id = 'xvideos-selector-style'; + style.textContent = ` + .xvideos-selector-hover { + box-shadow: inset 0 0 0 4px #8b5cf6 !important, 0 0 12px rgba(139, 92, 246, 0.6) !important; + cursor: crosshair !important; + transition: all 0.15s ease; + position: relative !important; + z-index: 9999 !important; + } + .xvideos-selector-selected { + box-shadow: inset 0 0 0 4px #10b981 !important, 0 0 15px rgba(16, 185, 129, 0.7) !important; + outline: 4px solid #10b981 !important; + outline-offset: -4px !important; + position: relative !important; + z-index: 9998 !important; + } + .xvideos-selector-selected::after, + .xvideos-selector-selected:hover::after { + content: '✓' !important; + position: absolute !important; + top: 8px !important; + left: 8px !important; + background: #10b981 !important; + color: white !important; + border-radius: 50% !important; + width: 28px !important; + height: 28px !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + font-weight: bold !important; + font-size: 16px !important; + z-index: 2147483647 !important; + box-shadow: 0 2px 6px rgba(0,0,0,0.6) !important; + pointer-events: none !important; + } + `; + (document.head || document.documentElement).appendChild(style); + + // Helper to get normalized URLs for matching + const getCleanUrl = (hrefOrAnchor) => { + if (!hrefOrAnchor) return ''; + let raw = typeof hrefOrAnchor === 'string' ? hrefOrAnchor : (hrefOrAnchor.href || hrefOrAnchor.getAttribute('href') || ''); + if (!raw) return ''; + try { + let full = new URL(raw, window.location.origin).href; + let clean = full.split('?')[0].split('#')[0].trim(); + if (clean.endsWith('/')) clean = clean.slice(0, -1); + return clean; + } catch(e) { + return ''; + } + }; + + // Strict helper to check if a URL is strictly a video link on XVideos + const isVideoUrl = (url) => { + if (!url) return false; + const lower = url.toLowerCase(); + + // Exclude non-video links: photos, galleries, headers, tabs, navigation bars + if (lower.includes('/photos/') || + lower.includes('/photo/') || + lower.includes('/pictures/') || + lower.includes('/picture/') || + lower.includes('/gallery/') || + lower.includes('/videos-i-like') || + lower.includes('/red/videos') || + lower.includes('/tags/') || + (lower.includes('/channels/') && !lower.includes('/prof-video-click/')) || + (lower.includes('/profiles/') && !lower.includes('/prof-video-click/')) || + lower.includes('/models/') || + lower.includes('/pornstar/') || + lower.includes('/amateur/') || + lower.endsWith('.jpg') || + lower.endsWith('.png') || + lower.endsWith('.gif') || + lower.endsWith('.css') || + lower.endsWith('.js') || + lower.startsWith('javascript') || + lower === '#' || + lower.includes('void(0)')) { + return false; + } + + // Strictly match XVideos video URL formats + if (lower.includes('/prof-video-click/')) return true; + if (lower.includes('/video.') || lower.includes('/video_') || lower.includes('/video-')) return true; + if (/\/video[\/\.\_-]?\d+/.test(lower) || /\/video\.[a-z0-9]+/.test(lower)) return true; + + return false; + }; + + // Find the enclosing video card container or anchor + const getPostCard = (el) => { + if (!el || el.closest('#xvideos-floating-ui')) return null; + + // 1. Check if el or ancestor is inside a video container + const card = el.closest('.thumb-block, div[id^="video_"], div[id^="video"], .frame-block, .thumb-inside, .thumb, .mozaique > div, div[class*="thumb"]'); + + // 2. Find anchor element + let anchor = el.closest('a'); + if (!anchor && card) { + anchor = card.querySelector('a'); + } + + if (!anchor) return null; + + const url = getCleanUrl(anchor); + if (!isVideoUrl(url)) return null; + + const finalCard = card || anchor.closest('.thumb-block, div[id^="video_"], div[id^="video"], .frame-block, .thumb-inside, .thumb, .mozaique > div, div[class*="thumb"]') || anchor; + + return { card: finalCard, anchor, url }; + }; + + // Get the visual element to apply border/checkmark highlights (never IMG tag directly) + const getVisualTarget = (cardObj) => { + if (!cardObj) return null; + const { card, anchor } = cardObj; + let target = card.querySelector('.thumb, .thumb-inside, .img, .video-pic, .frame, p.thumb') || anchor || card; + if (target && target.tagName === 'IMG') { + target = target.parentElement || target; + } + return target; + }; + + const toggleCardSelection = (url, select) => { + document.querySelectorAll('.thumb-block, div[id^="video_"], div[id^="video"], .frame-block, .mozaique > div, a').forEach(el => { + const cardObj = getPostCard(el); + if (cardObj && cardObj.url === url) { + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + if (select) { + visualTarget.classList.add('xvideos-selector-selected'); + visualTarget.classList.remove('xvideos-selector-hover'); + } else { + visualTarget.classList.remove('xvideos-selector-selected'); + } + } + } + }); + }; + + let isDragging = false; + let dragMode = null; + + const mouseOver = (e) => { + if (e.target.closest('#xvideos-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + const { url } = cardObj; + const visualTarget = getVisualTarget(cardObj); + if (!visualTarget) return; + + if (isDragging) { + e.preventDefault(); + e.stopPropagation(); + + if (dragMode === 'select' && !selectedLinks.has(url)) { + selectedLinks.add(url); + toggleCardSelection(url, true); + } else if (dragMode === 'deselect' && selectedLinks.has(url)) { + selectedLinks.delete(url); + toggleCardSelection(url, false); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } else { + if (!visualTarget.classList.contains('xvideos-selector-selected')) { + visualTarget.classList.add('xvideos-selector-hover'); + } + } + } + }; + + const mouseOut = (e) => { + if (e.target.closest('#xvideos-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + const visualTarget = getVisualTarget(cardObj); + if (visualTarget) { + visualTarget.classList.remove('xvideos-selector-hover'); + } + } + }; + + const mouseDown = (e) => { + if (e.target.closest('#xvideos-floating-ui')) return; + + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); + isDragging = true; + + const { url } = cardObj; + + if (selectedLinks.has(url)) { + dragMode = 'deselect'; + selectedLinks.delete(url); + toggleCardSelection(url, false); + } else { + dragMode = 'select'; + selectedLinks.add(url); + toggleCardSelection(url, true); + } + countDisplay.textContent = selectedLinks.size + ' enlaces seleccionados'; + } + }; + + const mouseUp = () => { + isDragging = false; + dragMode = null; + }; + + const dragStart = (e) => { + if (e.target.closest('#xvideos-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + } + }; + + const click = (e) => { + if (e.target.closest('#xvideos-floating-ui')) return; + const cardObj = getPostCard(e.target); + if (cardObj) { + e.preventDefault(); + e.stopPropagation(); + if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); + } + }; + + 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 videoUrls = new Set(); + document.querySelectorAll('a').forEach(a => { + const url = getCleanUrl(a); + if (isVideoUrl(url)) { + videoUrls.add(url); + } + }); + + let allSelected = true; + videoUrls.forEach(url => { + if (!selectedLinks.has(url)) { + allSelected = false; + } + }); + + if (allSelected && selectedLinks.size > 0) { + videoUrls.forEach(url => { + selectedLinks.delete(url); + toggleCardSelection(url, false); + }); + selectAllBtn.textContent = 'Seleccionar Todos'; + } else { + videoUrls.forEach(url => { + selectedLinks.add(url); + toggleCardSelection(url, true); + }); + 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; + const ogBg = copyBtn.style.background; + copyBtn.textContent = '¡Copiados!'; + copyBtn.style.background = '#10b981'; + setTimeout(() => { + copyBtn.textContent = ogText; + copyBtn.style.background = ogBg || '#8b5cf6'; + }, 2000); + }); + }; + + 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('.xvideos-selector-selected').forEach(el => el.classList.remove('xvideos-selector-selected')); + document.querySelectorAll('.xvideos-selector-hover').forEach(el => el.classList.remove('xvideos-selector-hover')); + window.__xvideosSelectorActive = false; + + try { + chrome.runtime.sendMessage({ type: 'UI_CLOSED', tool: 'xvideos' }); + } catch (e) { + console.log("Could not notify popup, it is probably closed"); + } + + window.dispatchEvent(new Event('XVIDEOS_OFF')); + }; +})(); diff --git a/local-video-downloader - copia (2) - copia/.gitattributes b/local-video-downloader - copia (2) - copia/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..30ee0fe4bc94724debfa834f397994fe63a12843 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/.gitattributes @@ -0,0 +1,66 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.avro filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.lz4 filter=lfs diff=lfs merge=lfs -text +*.mds filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +# Audio files - uncompressed +*.pcm filter=lfs diff=lfs merge=lfs -text +*.sam filter=lfs diff=lfs merge=lfs -text +*.raw filter=lfs diff=lfs merge=lfs -text +# Audio files - compressed +*.aac filter=lfs diff=lfs merge=lfs -text +*.flac filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.ogg filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +# Image files - uncompressed +*.bmp filter=lfs diff=lfs merge=lfs -text +*.gif filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.tiff filter=lfs diff=lfs merge=lfs -text +# Image files - compressed +*.jpg filter=lfs diff=lfs merge=lfs -text +*.jpeg filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text +# Video files - compressed +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.webm filter=lfs diff=lfs merge=lfs -text +host/bin/aria2c.exe filter=lfs diff=lfs merge=lfs -text +host/bin/AtomicParsley.exe filter=lfs diff=lfs merge=lfs -text +host/bin/ffmpeg.exe filter=lfs diff=lfs merge=lfs -text +host/bin/ffprobe.exe filter=lfs diff=lfs merge=lfs -text +host/bin/N_m3u8DL-RE.exe filter=lfs diff=lfs merge=lfs -text +host/bin/yt-dlp.exe filter=lfs diff=lfs merge=lfs -text diff --git a/local-video-downloader - copia (2) - copia/.gitignore b/local-video-downloader - copia (2) - copia/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..fdb84c1703a46d9f5572c9f316ec59a94de8a6e8 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/.gitignore @@ -0,0 +1,29 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class + +# Binaries (mejor descargarlos con los scripts de instalación) +host/bin/*.exe +host/bin/ffmpeg +host/bin/ffprobe +host/bin/aria2c +host/bin/AtomicParsley +host/bin/N_m3u8DL-RE +host/bin/yt-dlp + +# Archivos de configuración locales y temporales +host/youtube_cookies.txt +host/last_update.txt +host/*.part +host/*.ytdl + +# Videos de prueba y descargas +host/*.mp4 +host/*.mkv +host/*.mp3 +host/*.webm + +# OS +.DS_Store +Thumbs.db diff --git a/local-video-downloader - copia (2) - copia/README.md b/local-video-downloader - copia (2) - copia/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e0a7ff58d70079c79b3b6fa48b0ece0a18e06b0d --- /dev/null +++ b/local-video-downloader - copia (2) - copia/README.md @@ -0,0 +1,71 @@ +# Local Video Downloader + +Sistema de descarga de contenido multimedia basado en una extensión de navegador y un host nativo en Python. Permite la extracción de video y audio en alta resolución mediante la integración de herramientas profesionales de procesamiento. + +## Descripción + +Esta solución utiliza el protocolo de mensajería nativa de los navegadores basados en Chromium para superar las limitaciones de las extensiones convencionales. El procesamiento y la descarga se delegan a un host local, permitiendo el uso de motores como yt-dlp, aria2 y N_m3u8DL-RE para una eficiencia máxima y soporte para protocolos complejos (HLS, DASH). + +## Características Principales + +* **Descarga de Alta Resolución:** Soporte hasta 4K/8K dependiendo de la disponibilidad del origen. +* **Conversión de Audio:** Extracción y conversión a formatos como MP3, M4A u OPUS. +* **Motores de Descarga:** Integración con yt-dlp, N_m3u8DL-RE y aceleración mediante aria2. +* **Gestión de Metadatos:** Incrustación automática de miniaturas, subtítulos y metadatos descriptivos. +* **Interfaz de Usuario:** Panel de control integrado con detector de streams y selector de calidad. + +## Estructura del Proyecto + +```text +. +├── extension/ # Código fuente de la extensión de navegador +│ ├── manifest.json # Manifiesto de la extensión (v3) +│ ├── background.js # Service worker para gestión de tareas y sniffer +│ ├── popup.html # Interfaz de usuario principal +│ ├── popup.js # Lógica de la interfaz y comunicación +│ ├── popup.css # Estilos de la UI +│ ├── lib/ # Librerías externas (hls.js) +│ └── icons/ # Activos visuales +│ +├── host/ # Backend local (Native Messaging Host) +│ ├── download_host.py # Lógica principal de gestión de procesos +│ ├── download_host.bat # Lanzador de entrada para el navegador +│ ├── bin/ # Binarios ejecutables (Excluidos de Git) +│ ├── setup/ # Scripts de instalación de dependencias +│ │ └── install_*.py # Descargadores de dependencias +│ └── tests/ # Entorno de pruebas y muestras +│ +├── tools/ # Utilidades de desarrollo +│ └── resize.py # Script de procesamiento de iconos +│ +├── .gitignore # Reglas de exclusión para control de versiones +├── instalar_requisitos.bat # Comprueba e instala Python (Paso 1) +├── actualizar_motores.bat # Descarga los motores de descarga (Paso 2) +├── install_host.bat # Registra el sistema en el navegador (Paso 3) +└── README.md # Documentación técnica del proyecto +``` + +## Instalación + +### Requisitos del Sistema +* Python 3.8 o superior. +* Navegador basado en Chromium (Chrome, Edge, Brave, etc.). + +### Configuración del Host +1. Ejecutar `instalar_requisitos.bat`. Este script verificará si Python está instalado y, en caso contrario, intentará instalarlo automáticamente mediante `winget`. +2. Ejecutar `actualizar_motores.bat`. Esto descargará y configurará automáticamente todos los binarios necesarios (`yt-dlp`, `ffmpeg`, etc.) en la carpeta `host/bin`. +3. Ejecutar `install_host.bat` con privilegios de administrador. Siga las instrucciones en pantalla para registrar la extensión mediante su ID. + +### Instalación de la Extensión +1. Acceder a la sección de extensiones del navegador (`chrome://extensions`). +2. Habilitar el "Modo de desarrollador". +3. Seleccionar "Cargar descomprimida" y elegir la carpeta `extension` de este repositorio. + +## Uso +1. Acceder al sitio web del cual se desea extraer el contenido. +2. Abrir la extensión desde la barra de herramientas. +3. Seleccionar los parámetros de calidad y formato deseados. +4. Iniciar el proceso de descarga. El progreso se mostrará en tiempo real en el panel de la extensión. + +## Nota Legal +Este software se proporciona exclusivamente para fines educativos y de respaldo personal. El usuario es responsable de cumplir con los términos de servicio de las plataformas de terceros y las leyes de propiedad intelectual vigentes. diff --git a/local-video-downloader - copia (2) - copia/actualizar_motores.bat b/local-video-downloader - copia (2) - copia/actualizar_motores.bat new file mode 100644 index 0000000000000000000000000000000000000000..1c6fd4640698f8b8818f5c252df2d93d09fddddf --- /dev/null +++ b/local-video-downloader - copia (2) - copia/actualizar_motores.bat @@ -0,0 +1,34 @@ +@echo off +setlocal +echo ======================================================= +echo Actualizador de Motores - Local Video Downloader +echo ======================================================= +echo. + +:: Asegurar que la carpeta bin existe +if not exist "%~dp0host\bin" mkdir "%~dp0host\bin" + +:: Actualizar yt-dlp (El más importante) +echo [*] Actualizando yt-dlp... +if exist "%~dp0host\bin\yt-dlp.exe" ( + "%~dp0host\bin\yt-dlp.exe" --update-to master +) else ( + echo [!] yt-dlp no encontrado, descargando version inicial... + powershell -Command "Invoke-WebRequest -Uri 'https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe' -OutFile '%~dp0host\bin\yt-dlp.exe'" +) + +:: Ejecutar los scripts de instalación para el resto de motores +echo [*] Actualizando FFmpeg... +python "%~dp0host\setup\install_ffmpeg.py" + +echo [*] Actualizando N_m3u8DL-RE... +python "%~dp0host\setup\install_nm3u8dlre.py" + +echo [*] Actualizando AtomicParsley... +python "%~dp0host\setup\install_atomicparsley.py" + +echo. +echo ======================================================= +echo Actualizacion completada. Todos los motores estan al dia. +echo ======================================================= +pause diff --git a/local-video-downloader - copia (2) - copia/apagado_emergencia.bat b/local-video-downloader - copia (2) - copia/apagado_emergencia.bat new file mode 100644 index 0000000000000000000000000000000000000000..b800f9f17624f8d96651b83b02433cd0701c95af --- /dev/null +++ b/local-video-downloader - copia (2) - copia/apagado_emergencia.bat @@ -0,0 +1,14 @@ +@echo off +echo ============================================== +echo APAGADO DE EMERGENCIA - MOTORES DE DESCARGA +echo ============================================== +echo. +echo Cancelando procesos en segundo plano... +taskkill /F /IM yt-dlp.exe /T 2>NUL +taskkill /F /IM N_m3u8DL-RE.exe /T 2>NUL +taskkill /F /IM aria2c.exe /T 2>NUL +taskkill /F /IM ffmpeg.exe /T 2>NUL +echo. +echo [OK] Todos los motores de descarga han sido detenidos exitosamente. +echo. +pause diff --git a/local-video-downloader - copia (2) - copia/extension/background.js b/local-video-downloader - copia (2) - copia/extension/background.js new file mode 100644 index 0000000000000000000000000000000000000000..3e40bacfc62594f7a2128d9d77ea5583a2c41497 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/background.js @@ -0,0 +1,553 @@ +let activeTasks = {}; +let activePorts = {}; +let snifferEnabled = true; +let maxConcurrentDownloadsLimit = 1; + +chrome.runtime.onInstalled.addListener(() => { + chrome.contextMenus.create({ + id: "download_video_link", + title: "Descargar con Local Downloader", + contexts: ["video", "link", "page"] + }); +}); + +chrome.contextMenus.onClicked.addListener((info, tab) => { + if (info.menuItemId === "download_video_link") { + let targetUrl = info.srcUrl || info.linkUrl || info.pageUrl || (tab ? tab.url : ""); + if (!targetUrl) return; + + let title = (tab && tab.title) ? tab.title.replace(/^\(\d+\)\s*/, '').replace(/ - YouTube$/, '').trim() : "Video Descargado (Menú)"; + + chrome.storage.local.get(['customSavePath', 'formatSetting', 'qualitySetting', 'engineSetting', 'threadCount', 'audioFormat', 'audioQuality', 'audioConvert', 'videoFormatPref', 'ytAudioLang', 'ytSubs'], (result) => { + let request = { + action: "download", + url: targetUrl, + title: title, + savePath: result.customSavePath || "", + formatSetting: result.formatSetting || "mp4", + qualitySetting: result.qualitySetting || "max", + engineSetting: result.engineSetting || "ytdlp", + threadCount: result.threadCount || 4, + audioFormat: result.audioFormat || "best", + audioQuality: result.audioQuality || "0", + audioConvert: result.audioConvert || "mp3", + videoFormatPref: result.videoFormatPref || "legado", + ytAudioLang: result.ytAudioLang || "es", + ytSubs: result.ytSubs || "off", + isAutoTitle: false + }; + + let downloadId = "dl_" + Date.now() + "_" + Math.floor(Math.random() * 1000); + + activeTasks[downloadId] = { + id: downloadId, + title: title, + url: targetUrl, + percent: "0", + status: "queued" + }; + + downloadQueue.push({ + downloadId: downloadId, + request: request + }); + + try { chrome.runtime.sendMessage({ action: "download_update", task: activeTasks[downloadId] }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + + processDownloadQueue(); + }); + } +}); + +chrome.storage.local.get(['snifferEnabled', 'maxConcurrentDownloads'], (res) => { + if (res.snifferEnabled === false) snifferEnabled = false; + if (res.maxConcurrentDownloads) { + maxConcurrentDownloadsLimit = parseInt(res.maxConcurrentDownloads); + } +}); + +chrome.storage.onChanged.addListener((changes, namespace) => { + if (changes.snifferEnabled) { + snifferEnabled = changes.snifferEnabled.newValue; + } + if (changes.maxConcurrentDownloads) { + maxConcurrentDownloadsLimit = parseInt(changes.maxConcurrentDownloads.newValue || 1); + processDownloadQueue(); + } +}); + +function prefetchQuality(videoUrl) { + let cacheKey = videoUrl; + if (videoUrl.includes('youtube.com/watch')) { + let match = videoUrl.match(/([?&]v=[^&]+)/); + if (match) cacheKey = "yt_" + match[1]; + } + + chrome.storage.local.get(['qualitySetting', 'prefetchedQualities'], function(result) { + if (result.qualitySetting === 'detect') { + let cache = result.prefetchedQualities || {}; + if (cache[cacheKey] && (Date.now() - cache[cacheKey].timestamp < 300000)) return; + + try { + let port = chrome.runtime.connectNative("com.gonzalo.videodownloader"); + port.onMessage.addListener((message) => { + if (message.status === "info") { + chrome.storage.local.get(['prefetchedQualities'], (r2) => { + let freshCache = r2.prefetchedQualities || {}; + freshCache[cacheKey] = { timestamp: Date.now(), formats: message.info.formats }; + chrome.storage.local.set({ prefetchedQualities: freshCache }); + }); + } + port.disconnect(); + }); + port.postMessage({ command: "get_info", url: videoUrl }); + } catch(e) {} + } + }); +} + +chrome.webRequest.onBeforeRequest.addListener( + function(details) { + if (!snifferEnabled) return; + if (details.tabId >= 0) { + const url = details.url; + const isMedia = details.type === "media"; + const isDirectVideo = url.includes(".m3u8") || url.includes("/m3u8/") || url.includes(".mp4"); + + if (isDirectVideo || isMedia) { + if (url.includes('tiktok') || url.includes('tiktokcdn') || url.includes('facebook') || url.includes('fbcdn')) return; + + chrome.storage.local.get(['sniffedUrls'], function(result) { + let urls = result.sniffedUrls || {}; + if (!urls[details.tabId]) urls[details.tabId] = []; + + if (!urls[details.tabId].includes(url)) { + urls[details.tabId].push(url); + chrome.storage.local.set({ sniffedUrls: urls }); + + // Disparar precarga automáticamente apenas un nuevo video sea detectado (M3U8, MP4, etc) + prefetchQuality(url); + } + }); + } + } + }, + { urls: [""] } +); + +chrome.tabs.onUpdated.addListener((tabId, changeInfo) => { + if (changeInfo.url) { + chrome.storage.local.get(['sniffedUrls'], function(result) { + let urls = result.sniffedUrls || {}; + delete urls[tabId]; + chrome.storage.local.set({ sniffedUrls: urls }); + + // Disparar precarga para YouTube (ya que YouTube oculta sus streams directos) + if (changeInfo.url.includes('youtube.com/watch') || changeInfo.url.includes('youtu.be/')) { + prefetchQuality(changeInfo.url); + } + }); + } +}); + +chrome.tabs.onRemoved.addListener((tabId) => { + chrome.storage.local.get(['sniffedUrls'], function(result) { + let urls = result.sniffedUrls || {}; + delete urls[tabId]; + chrome.storage.local.set({ sniffedUrls: urls }); + }); +}); + +chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { + // Manejador del Método 1 (eliminado) + + if (request.action === "emergency_stop") { + // 1. Cancel all queued downloads in downloadQueue + downloadQueue.forEach(item => { + let taskId = item.downloadId; + if (activeTasks[taskId]) { + activeTasks[taskId].status = "cancelled"; + try { chrome.runtime.sendMessage({ action: "download_update", task: activeTasks[taskId] }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + setTimeout(() => { + delete activeTasks[taskId]; + try { chrome.runtime.sendMessage({ action: "download_remove", id: taskId }, () => { let _ = chrome.runtime.lastError; }); } catch(e) {} + }, 3000); + } + }); + downloadQueue = []; + + // 2. Cancel all active downloads + Object.keys(activePorts).forEach(taskId => { + let task = activeTasks[taskId]; + if (task) { + task.status = "cancelled"; + try { chrome.runtime.sendMessage({ action: "download_update", task: task }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + } + let port = activePorts[taskId]; + if (port) { + try { port.disconnect(); } catch(e) {} + } + delete activePorts[taskId]; + + setTimeout(() => { + if (activeTasks[taskId]) { + delete activeTasks[taskId]; + try { chrome.runtime.sendMessage({ action: "download_remove", id: taskId }, () => { let _ = chrome.runtime.lastError; }); } catch(e) {} + } + }, 3000); + }); + + // Reset active count + activeDownloadsCount = 0; + + // Broadcast emergency log + try { + chrome.runtime.sendMessage({ + action: "download_log", + log: "[EMERGENCIA] Parada de emergencia activada. Se han cancelado y eliminado todas las descargas activas y en cola." + }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + + sendResponse({ success: true }); + return true; + } + + if (request.action === "get_active_downloads") { + sendResponse({ success: true, tasks: activeTasks }); + return true; + } + + if (request.action === "clear_task") { + if (activeTasks[request.id]) { + delete activeTasks[request.id]; + delete activePorts[request.id]; + } + return true; + } + + if (request.action === "cancel_download") { + let task = activeTasks[request.id]; + if (task) { + task.status = "cancelled"; + try { chrome.runtime.sendMessage({ action: "download_update", task: task }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + + let port = activePorts[request.id]; + if (port) { + port.disconnect(); // Terminate native host instantly + activeDownloadsCount--; // Free slot + setTimeout(processDownloadQueue, 500); // Process next + } else { + // It's queued, not started natively yet + // Remove it from the queue immediately so it won't be processed + downloadQueue = downloadQueue.filter(q => q.downloadId !== request.id); + } + + setTimeout(() => { + if (activeTasks[request.id]) { + delete activeTasks[request.id]; + if (activePorts[request.id]) delete activePorts[request.id]; + try { chrome.runtime.sendMessage({ action: "download_remove", id: request.id }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + } + }, 2000); + } + return true; + } + + if (request.action === "download" || request.action === "open_folder" || request.action === "get_info" || request.action === "get_playlist_info" || request.action === "select_folder") { + + if (request.action === "open_folder" || request.action === "get_info" || request.action === "get_playlist_info" || request.action === "select_folder") { + const hostName = "com.gonzalo.videodownloader"; + let port; + try { + port = chrome.runtime.connectNative(hostName); + let responded = false; + port.onMessage.addListener((message) => { + if (!responded) { + sendResponse({ success: true, ...message }); + responded = true; + try { port.disconnect(); } catch(e) {} + } + }); + port.onDisconnect.addListener(() => { + if (!responded) { + sendResponse({ success: false, error: chrome.runtime.lastError ? chrome.runtime.lastError.message : "Desconectado" }); + responded = true; + } + }); + port.postMessage({ command: request.action, url: request.url }); + } catch(e) { + sendResponse({ success: false, error: e.message }); + } + return true; + } + + // Action === "download" + let downloadId = "dl_" + Date.now() + "_" + Math.floor(Math.random() * 1000); + + activeTasks[downloadId] = { + id: downloadId, + title: request.title || "Video", + url: request.url, + percent: "0", + status: "queued" + }; + + downloadQueue.push({ + downloadId: downloadId, + request: request + }); + + sendResponse({ success: true, queued: true, id: downloadId }); + try { chrome.runtime.sendMessage({ action: "download_update", task: activeTasks[downloadId] }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + + processDownloadQueue(); + return true; // Asynchronous response + } +}); + +let downloadQueue = []; +let activeDownloadsCount = 0; + +function getCookiesForDomain(targetUrl, downloadId, callback) { + function logMsg(msg) { + console.log(msg); + try { + chrome.runtime.sendMessage({ + action: "download_log", + id: downloadId, + log: msg + }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + } + + if (!chrome.cookies) { + logMsg("[-] ERROR CRÍTICO: chrome.cookies no está disponible. DEBES recargar la extensión desde chrome://extensions."); + return callback(''); + } + + let query = { url: targetUrl }; + try { + let domain = new URL(targetUrl).hostname; + if (domain.startsWith("www.")) { + domain = domain.substring(4); + } + if (domain.includes("instagram.com") || domain.includes("youtube.com") || domain.includes("tiktok.com")) { + query = { domain: domain }; + } + } catch(e) {} + + chrome.cookies.getAll(query, (cookies) => { + if (chrome.runtime.lastError) { + logMsg("[-] Error al extraer cookies: " + chrome.runtime.lastError.message); + return callback(''); + } + let cookieString = "# Netscape HTTP Cookie File\n"; + if (cookies && cookies.length > 0) { + logMsg(`[*] Extraídas ${cookies.length} cookies nativas para ${targetUrl} con éxito.`); + cookies.forEach(c => { + let domain = c.domain; + let includesSub = domain.startsWith('.') ? "TRUE" : "FALSE"; + let path = c.path; + let secure = c.secure ? "TRUE" : "FALSE"; + let expiration = c.expirationDate ? Math.floor(c.expirationDate) : Math.floor(Date.now() / 1000) + 3600; + cookieString += `${domain}\t${includesSub}\t${path}\t${secure}\t${expiration}\t${c.name}\t${c.value}\n`; + }); + callback(cookieString); + } else { + logMsg(`[-] ADVERTENCIA: 0 cookies encontradas en Chrome para ${targetUrl}.`); + callback(''); + } + }); +} + +function processDownloadQueue() { + if (activeDownloadsCount >= maxConcurrentDownloadsLimit) return; + if (downloadQueue.length === 0) return; + + let queuedItem = downloadQueue.shift(); + let downloadId = queuedItem.downloadId; + let request = queuedItem.request; + + if (!activeTasks[downloadId] || activeTasks[downloadId].status !== "queued") { + // Was cleared or cancelled before it started + processDownloadQueue(); + return; + } + + activeDownloadsCount++; + activeTasks[downloadId].status = "started"; + try { + chrome.runtime.sendMessage({ + action: "download_log", + id: downloadId, + log: `[COLA] Iniciando descarga de "${activeTasks[downloadId].title}". (Simultáneas activas: ${activeDownloadsCount}/${maxConcurrentDownloadsLimit})` + }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + + // Extraer cookies de forma centralizada en background.js antes de conectar con el host nativo + chrome.storage.local.get(['cookiesSetting'], (storageRes) => { + let cookiesSetting = storageRes.cookiesSetting || 'none'; + let url = request.url || ''; + let shouldGetCookies = false; + let targetDomain = url; + + if (url.includes("youtube.com") || url.includes("youtu.be")) { + shouldGetCookies = true; + targetDomain = "https://www.youtube.com"; + } else if (url.includes("instagram.com")) { + shouldGetCookies = true; + targetDomain = "https://www.instagram.com"; + } else if (url.includes("tiktok.com")) { + shouldGetCookies = true; + targetDomain = "https://www.tiktok.com"; + } else if (cookiesSetting === "chrome") { + shouldGetCookies = true; + try { + let parsed = new URL(url); + targetDomain = parsed.protocol + "//" + parsed.hostname; + } catch(e) {} + } + + if (shouldGetCookies) { + getCookiesForDomain(targetDomain, downloadId, (cookiesStr) => { + request.netscapeCookies = cookiesStr; + launchNativeDownload(downloadId, request); + }); + } else { + request.netscapeCookies = ''; + launchNativeDownload(downloadId, request); + } + }); +} + +function launchNativeDownload(downloadId, request) { + if (!activeTasks[downloadId] || activeTasks[downloadId].status !== "started") { + // Cancelado o removido durante la obtención de cookies + activeDownloadsCount--; + setTimeout(processDownloadQueue, 500); + return; + } + + const hostName = "com.gonzalo.videodownloader"; + let port; + try { + port = chrome.runtime.connectNative(hostName); + activePorts[downloadId] = port; + } catch (e) { + activeTasks[downloadId].status = "error"; + activeTasks[downloadId].error = e.message; + try { chrome.runtime.sendMessage({ action: "download_update", task: activeTasks[downloadId] }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + + activeDownloadsCount--; + try { + chrome.runtime.sendMessage({ + action: "download_log", + id: downloadId, + log: `[COLA] Error al conectar con el host para "${activeTasks[downloadId].title}". (Simultáneas activas restantes: ${activeDownloadsCount}/${maxConcurrentDownloadsLimit})` + }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + setTimeout(processDownloadQueue, 500); + return; + } + + port.onMessage.addListener((message) => { + if (message.status === "log") { + try { + let title = activeTasks[downloadId] ? activeTasks[downloadId].title : "Descarga"; + chrome.runtime.sendMessage({ action: "download_log", id: downloadId, title: title, log: message.log }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + } + else if (message.status === "progress" || message.status === "completed" || message.status === "error" || message.status === "cancelled" || message.status === "started") { + + if (activeTasks[downloadId]) { + activeTasks[downloadId].status = message.status; + if (message.percent) activeTasks[downloadId].percent = message.percent; + if (message.error) activeTasks[downloadId].error = message.error; + } + try { chrome.runtime.sendMessage({ action: "download_update", task: activeTasks[downloadId] }, () => { let _ = chrome.runtime.lastError; }); } catch(err) {} + + if (message.status === "completed" || message.status === "cancelled" || message.status === "error") { + if (message.status === "completed" && activeTasks[downloadId]) { + let final_file = message.final_file || ""; + let title = activeTasks[downloadId].title; + let url = activeTasks[downloadId].url; + chrome.storage.local.get(['downloadHistory'], (res) => { + let history = res.downloadHistory || []; + history.push({ title: title, url: url, final_file: final_file, date: new Date().toISOString() }); + chrome.storage.local.set({ downloadHistory: history }); + }); + } + activeDownloadsCount--; + + // Disconnect the native port immediately to close the Python process + let port = activePorts[downloadId]; + if (port) { + delete activePorts[downloadId]; + try { port.disconnect(); } catch(e) {} + } + + try { + let taskName = activeTasks[downloadId] ? activeTasks[downloadId].title : "Descarga"; + chrome.runtime.sendMessage({ + action: "download_log", + id: downloadId, + log: `[COLA] Finalizó "${taskName}" con estado: ${message.status}. (Simultáneas activas restantes: ${activeDownloadsCount}/${maxConcurrentDownloadsLimit})` + }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + setTimeout(processDownloadQueue, 1500); // 1.5s delay to cool down between sequential downloads + + if (message.status !== "error") { + setTimeout(() => { + if (activeTasks[downloadId]) { + delete activeTasks[downloadId]; + try { chrome.runtime.sendMessage({ action: "download_remove", id: downloadId }, () => { let _ = chrome.runtime.lastError; }); } catch(e) {} + } + }, 4000); + } + } + } + }); + + port.onDisconnect.addListener(() => { + if (activePorts[downloadId]) { + delete activePorts[downloadId]; + + if (activeTasks[downloadId] && (activeTasks[downloadId].status === "queued" || activeTasks[downloadId].status === "started" || activeTasks[downloadId].status === "progress")) { + let err = chrome.runtime.lastError ? chrome.runtime.lastError.message : "Desconectado inesperadamente"; + activeTasks[downloadId].status = "error"; + activeTasks[downloadId].error = err; + try { chrome.runtime.sendMessage({ action: "download_update", task: activeTasks[downloadId] }, () => {}); } catch(e) {} + + activeDownloadsCount--; + try { + let taskName = activeTasks[downloadId] ? activeTasks[downloadId].title : "Descarga"; + chrome.runtime.sendMessage({ + action: "download_log", + id: downloadId, + log: `[COLA] Error en "${taskName}": Desconectado inesperadamente. (Simultáneas activas restantes: ${activeDownloadsCount}/${maxConcurrentDownloadsLimit})` + }, () => { let _ = chrome.runtime.lastError; }); + } catch(err) {} + setTimeout(processDownloadQueue, 1000); + } + } + }); + + port.postMessage({ + command: "download", + title: request.title, + url: request.url, + pageUrl: request.pageUrl, + savePath: request.savePath, + formatSetting: request.formatSetting, + qualitySetting: request.qualitySetting, + engineSetting: request.engineSetting, + threadCount: request.threadCount, + audioFormat: request.audioFormat, + audioQuality: request.audioQuality, + audioConvert: request.audioConvert, + videoFormatPref: request.videoFormatPref, + customFormatId: request.customFormatId, + netscapeCookies: request.netscapeCookies, + isAutoTitle: request.isAutoTitle + }); +} diff --git a/local-video-downloader - copia (2) - copia/extension/content.js b/local-video-downloader - copia (2) - copia/extension/content.js new file mode 100644 index 0000000000000000000000000000000000000000..3957a8280350e6ec8d35cc17289043c82508f24c --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/content.js @@ -0,0 +1 @@ +// Archivo limpiado temporalmente por solicitud del usuario. diff --git a/local-video-downloader - copia (2) - copia/extension/icons/icon.png b/local-video-downloader - copia (2) - copia/extension/icons/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..85762b2a520a1bc1e3fcfaf1f3bd53d30fab516f --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/icons/icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f593cd7c23e9ae9a9a45e27a908ef60e42636582a4ac18b39dda923758b7133 +size 13111 diff --git a/local-video-downloader - copia (2) - copia/extension/lib/hls.light.min.js b/local-video-downloader - copia (2) - copia/extension/lib/hls.light.min.js new file mode 100644 index 0000000000000000000000000000000000000000..e30908ff95d1ef3ac31c255463b0c0886e2f9deb --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/lib/hls.light.min.js @@ -0,0 +1,2 @@ +!function e(t){var r,i;r=this,i=function(){"use strict";function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function i(e){for(var t=1;t1?t-1:0),i=1;i"):L}(t)}))}function D(e,t){if("object"==typeof console&&!0===e||"object"==typeof e){b(e,"debug","log","info","warn","error");try{A.log('Debug logs enabled for "'+t+'" in hls.js version 1.5.7')}catch(e){A=R}}else A=R}var k=A,_=/^(\d+)x(\d+)$/,x=/(.+?)=(".*?"|.*?)(?:,|$)/g,w=function(){function e(t){"string"==typeof t&&(t=e.parseAttrList(t)),o(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=_.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(x.lastIndex=0;null!==(t=x.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1].trim()]=i}return r},s(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}]),e}();function C(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}var I=function(){function e(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){var r=t.attr;for(var i in r)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==r[i]){k.warn('DATERANGE tag attribute: "'+i+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=i;break}e=o(new w({}),r,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){var a=new Date(this.attr["END-DATE"]);m(a.getTime())&&(this._endDate=a)}}return s(e,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(m(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&m(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),e}(),P=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}},F="audio",O="video",M="audiovideo",N=function(){function e(e){var t;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((t={})[F]=null,t[O]=null,t[M]=null,t),this.baseurl=e}return e.prototype.setByteRange=function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]},s(e,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=g.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}]),e}(),B=function(e){function t(t,r){var i;return(i=e.call(this,r)||this)._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new P,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=t,i}l(t,e);var r=t.prototype;return r.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},r.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},r.setElementaryStreamInfo=function(e,t,r,i,a,n){void 0===n&&(n=!1);var s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,a)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:a,partial:n}},r.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[F]=null,e[O]=null,e[M]=null},s(t,[{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!m(this.programDateTime))return null;var e=m(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&this.levelkeys[t[0]].encrypted)return!0}return!1}}]),t}(N),U=function(e){function t(t,r,i,a,n){var s;(s=e.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new P,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=a;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,n),n&&(s.fragOffset=n.fragOffset+n.duration),s}return l(t,e),s(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}]),t}(N),G=function(){function e(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}return e.prototype.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay},s(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&m(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),e}(),H=c(void 0);function V(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}var K,j=function(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},W=function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},Y=function(e,t){for(var r=t,i=0;j(e,t);)i+=10,i+=q(e,t+6),W(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)},q=function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]},z=function(e,t){return j(e,t)&&q(e,t+6)+10<=e.length-t},X=function(e){for(var t=$(e),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:s=e[d++],u+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=e[d++],o=e[d++],u+=String.fromCharCode((15&n)<<12|(63&s)<<6|(63&o)<<0)}}return u};function ne(){if(!navigator.userAgent.includes("PlayStation 4"))return K||void 0===self.TextDecoder||(K=new self.TextDecoder("utf-8")),K}var se=function(e){for(var t="",r=0;r>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function me(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,a=0;a1?a+n:i;if(de(e.subarray(a+4,a+8))===t[0])if(1===t.length)r.push(e.subarray(a+8,s));else{var o=me(e.subarray(a+8,s),t.slice(1));o.length&&le.apply(r,o)}a=s}return r}function pe(e){var t=[],r=e[0],i=8,a=fe(e,i);i+=4;var n=0,s=0;0===r?(n=fe(e,i),s=fe(e,i+4),i+=8):(n=ce(e,i),s=ce(e,i+8),i+=16),i+=2;var o=e.length+s,l=he(e,i);i+=2;for(var u=0;u>>31)return k.warn("SIDX has hierarchical references (not supported)"),null;var c=fe(e,d);d+=4,t.push({referenceSize:f,subsegmentDuration:c,info:{duration:c/a,start:o,end:o+f-1}}),o+=f,i=d+=4}return{earliestPresentationTime:n,timescale:a,version:r,referencesCount:l,references:t}}function ye(e){for(var t=[],r=me(e,["moov","trak"]),a=0;a12){var d=4;if(3!==u[d++])break;d=Te(u,d),d+=2;var h=u[d++];if(128&h&&(d+=2),64&h&&(d+=u[d++]),4!==u[d++])break;d=Te(u,d);var f=u[d++];if(64!==f)break;if(a+="."+Se(f),d+=12,5!==u[d++])break;d=Te(u,d);var c=u[d++],v=(248&c)>>3;31===v&&(v+=1+((7&c)<<3)+((224&u[d])>>5)),a+="."+v}break;case"hvc1":case"hev1":var g=me(r,["hvcC"])[0],m=g[1],p=["","A","B","C"][m>>6],y=31&m,E=fe(g,2),T=(32&m)>>5?"H":"L",S=g[12],L=g.subarray(6,12);a+="."+p+y,a+="."+E.toString(16).toUpperCase(),a+="."+T+S;for(var R="",A=L.length;A--;){var b=L[A];(b||R)&&(R="."+b.toString(16).toUpperCase()+R)}a+=R;break;case"dvh1":case"dvhe":var D=me(r,["dvcC"])[0],k=D[2]>>1&127,_=D[2]<<5&32|D[3]>>3&31;a+="."+Le(k)+"."+Le(_);break;case"vp09":var x=me(r,["vpcC"])[0],w=x[4],C=x[5],I=x[6]>>4&15;a+="."+Le(w)+"."+Le(C)+"."+Le(I);break;case"av01":var P=me(r,["av1C"])[0],F=P[1]>>>5,O=31&P[1],M=P[2]>>>7?"H":"M",N=(64&P[2])>>6,B=(32&P[2])>>5,U=2===F&&N?B?12:10:N?10:8,G=(16&P[2])>>4,H=(8&P[2])>>3,V=(4&P[2])>>2,K=3&P[2];a+="."+F+"."+Le(O)+M+"."+Le(U)+"."+G+"."+H+V+K+"."+Le(1)+"."+Le(1)+"."+Le(1)+".0"}return{codec:a,encrypted:n}}function Te(e,t){for(var r=t+5;128&e[t++]&&t0;a||(i=me(t,["encv"])),i.forEach((function(e){me(a?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=function(e){var t=me(e,["schm"])[0];if(t){var r=de(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return me(e,["schi","tenc"])[0]}return k.error("[eme] missing 'schm' box"),null}(e);if(t){var i=t.subarray(8,24);i.some((function(e){return 0!==e}))||(k.log("[eme] Patching keyId in 'enc"+(a?"a":"v")+">sinf>>tenc' box: "+se(i)+" -> "+se(r)),t.set(r,8))}}))}))})),e}function Ae(e){var t=fe(e,0),r=8;1&t&&(r+=4),4&t&&(r+=4);for(var i=0,a=fe(e,4),n=0;n>1&63;return 39===r||40===r}return 6==(31&t)}function _e(e,t,r,i){var a=xe(e),n=0;n+=t;for(var s=0,o=0,l=0;n=a.length)break;s+=l=a[n++]}while(255===l);o=0;do{if(n>=a.length)break;o+=l=a[n++]}while(255===l);var u=a.length-n,d=n;if(ou){k.error("Malformed SEI payload. "+o+" is too small, only "+u+" bytes left to parse.");break}if(4===s){if(181===a[d++]){var h=he(a,d);if(d+=2,49===h){var f=fe(a,d);if(d+=4,1195456820===f){var c=a[d++];if(3===c){var v=a[d++],g=64&v,m=g?2+3*(31&v):0,p=new Uint8Array(m);if(g){p[0]=v;for(var y=1;y16){for(var E=[],T=0;T<16;T++){var S=a[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var L=o-16,R=new Uint8Array(L),A=0;A>8*(15-r)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,r)}return this},e}();function Ce(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}var Ie={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Pe(e,t,r){return void 0===r&&(r=!0),!e.split(",").some((function(e){return!Fe(e,t,r)}))}function Fe(e,t,r){var i;void 0===r&&(r=!0);var a=Ce(r);return null!=(i=null==a?void 0:a.isTypeSupported(Oe(e,t)))&&i}function Oe(e,t){return t+'/mp4;codecs="'+e+'"'}function Me(e){if(e){var t=e.substring(0,4);return Ie.video[t]}return 2}function Ne(e){return e.split(",").reduce((function(e,t){var r=Ie.video[t];return r?(2*r+e)/(e?3:2):(Ie.audio[t]+e)/(e?2:1)}),0)}var Be={},Ue=/flac|opus/i;function Ge(e,t){return void 0===t&&(t=!0),e.replace(Ue,(function(e){return function(e,t){if(void 0===t&&(t=!0),Be[e])return Be[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[e],i=0;i0&&n.length0&&q.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=q.optionalFloat("PART-HOLD-BACK",0),d.holdBack=q.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var z=new w(x);d.partTarget=z.decimalFloatingPoint("PART-TARGET");break;case"PART":var X=d.partList;X||(X=d.partList=[]);var Q=v>0?X[X.length-1]:void 0,J=v++,$=new w(x),Z=new U($,E,t,J,Q);X.push(Z),E.duration+=Z.duration;break;case"PRELOAD-HINT":var ee=new w(x);d.preloadHint=ee;break;case"RENDITION-REPORT":var te=new w(x);d.renditionReports=d.renditionReports||[],d.renditionReports.push(te);break;default:k.warn("line parsed but not handled: "+s)}}}y&&!y.relurl?(h.pop(),g-=y.duration,d.partList&&(d.fragmentHint=y)):d.partList&&($e(E,y),E.cc=p,d.fragmentHint=E,u&&et(E,u,d));var re=h.length,ie=h[0],ae=h[re-1];if((g+=d.skippedSegments*d.targetduration)>0&&re&&ae){d.averagetargetduration=g/re;var ne=ae.sn;d.endSN="initSegment"!==ne?ne:0,d.live||(ae.endList=!0),ie&&(d.startCC=ie.cc)}else d.endSN=0,d.startCC=0;return d.fragmentHint&&(g+=d.fragmentHint.duration),d.totalduration=g,d.endCC=p,T>0&&function(e,t){for(var r=e[t],i=t;i--;){var a=e[i];if(!a)return;a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(h,T),d},e}();function ze(e,t,r){var i,a,n=new w(e),s=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),u=n.KEYFORMATVERSIONS,d=null!=(a=n.KEYFORMAT)?a:"identity";o&&n.IV&&!l&&k.error("Invalid IV: "+n.IV);var h=o?qe.resolve(o,t):"",f=(u||"1").split("/").map(Number).filter(Number.isFinite);return new we(s,h,d,f,l)}function Xe(e){var t=new w(e).decimalFloatingPoint("TIME-OFFSET");return m(t)?t:null}function Qe(e,t){var r=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var i=r.filter((function(t){return function(e,t){var r=Ie[t];return!!r&&!!r[e.slice(0,4)]}(t,e)}));i.length&&(t[e+"Codec"]=i.join(","),r=r.filter((function(e){return-1===i.indexOf(e)})))})),t.unknownCodecs=r}function Je(e,t,r){var i=t[r];i&&(e[r]=i)}function $e(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),m(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function Ze(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function et(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||i.push(e)}var tt="manifest",rt="level",it="audioTrack",at="subtitleTrack",nt="main",st="audio",ot="subtitle";function lt(e){switch(e.type){case it:return st;case at:return ot;default:return nt}}function ut(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var dt=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.unregisterListeners=function(){var e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,a=new(r||i)(t);return this.loaders[e.type]=a,a},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:tt,url:r,deliveryDirectives:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,a=t.pathwayId,n=t.url,s=t.deliveryDirectives;this.load({id:r,level:i,pathwayId:a,responseType:"text",type:rt,url:n,deliveryDirectives:s})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,a=t.url,n=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:it,url:a,deliveryDirectives:n})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,a=t.url,n=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:at,url:a,deliveryDirectives:n})},t.load=function(e){var t,r,i,a=this,n=this.hls.config,s=this.getInternalLoader(e);if(s){var l=s.context;if(l&&l.url===e.url&&l.level===e.level)return void k.trace("[playlist-loader]: playlist request ongoing");k.log("[playlist-loader]: aborting previous loader for type: "+e.type),s.abort()}if(r=e.type===tt?n.manifestLoadPolicy.default:o({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),m(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===rt&&null!==e.level?i=this.hls.levels[e.level].details:e.type===it&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===at&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,d=i.targetduration;if(u&&d){var h=1e3*Math.max(3*u,.8*d);r=o({},r,{maxTimeToFirstByteMs:Math.min(h,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,r.maxTimeToFirstByteMs)})}}var f=r.errorRetry||r.timeoutRetry||{},c={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var n=a.getInternalLoader(r);a.resetInternalLoader(r.type);var s=e.data;0===s.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),qe.isMediaPlaylist(s)?a.handleTrackOrLevelPlaylist(e,t,r,i||null,n):a.handleMasterPlaylist(e,t,r,i)):a.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),i||null,t)},onError:function(e,t,r,i){a.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){a.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,c,v)},t.handleMasterPlaylist=function(e,t,r,i){var a=this.hls,n=e.data,s=ut(e,r),o=qe.parseMasterPlaylist(n,s);if(o.playlistParsingError)this.handleManifestParsingError(e,r,o.playlistParsingError,i,t);else{var l=o.contentSteering,u=o.levels,d=o.sessionData,h=o.sessionKeys,f=o.startTimeOffset,c=o.variableList;this.variableList=c;var v=qe.parseMasterPlaylistMedia(n,s,o),g=v.AUDIO,m=void 0===g?[]:g,p=v.SUBTITLES,y=v["CLOSED-CAPTIONS"];m.length&&(m.some((function(e){return!e.url}))||!u[0].audioCodec||u[0].attrs.AUDIO||(k.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new w({}),bitrate:0,url:""}))),a.trigger(E.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:p,captions:y,contentSteering:l,url:s,stats:t,networkDetails:i,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:c})}},t.handleTrackOrLevelPlaylist=function(e,t,r,i,a){var n=this.hls,s=r.id,o=r.level,l=r.type,u=ut(e,r),d=m(o)?o:m(s)?s:0,h=lt(r),f=qe.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(l===tt){var c={attrs:new w({}),bitrate:0,details:f,name:"",url:u};n.trigger(E.MANIFEST_LOADED,{levels:[c],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,i,a)},t.handleManifestParsingError=function(e,t,r,i,a){this.hls.trigger(E.ERROR,{type:T.NETWORK_ERROR,details:S.MANIFEST_PARSING_ERROR,fatal:t.type===tt,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:a})},t.handleNetworkError=function(e,t,r,a,n){void 0===r&&(r=!1);var s="A network "+(r?"timeout":"error"+(a?" (status "+a.code+")":""))+" occurred while loading "+e.type;e.type===rt?s+=": "+e.level+" id: "+e.id:e.type!==it&&e.type!==at||(s+=" id: "+e.id+' group-id: "'+e.groupId+'"');var o=new Error(s);k.warn("[playlist-loader]: "+s);var l=S.UNKNOWN,u=!1,d=this.getInternalLoader(e);switch(e.type){case tt:l=r?S.MANIFEST_LOAD_TIMEOUT:S.MANIFEST_LOAD_ERROR,u=!0;break;case rt:l=r?S.LEVEL_LOAD_TIMEOUT:S.LEVEL_LOAD_ERROR,u=!1;break;case it:l=r?S.AUDIO_TRACK_LOAD_TIMEOUT:S.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case at:l=r?S.SUBTITLE_TRACK_LOAD_TIMEOUT:S.SUBTITLE_LOAD_ERROR,u=!1}d&&this.resetInternalLoader(e.type);var h={type:T.NETWORK_ERROR,details:l,fatal:u,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(a){var f=(null==t?void 0:t.url)||e.url;h.response=i({url:f,data:void 0},a)}this.hls.trigger(E.ERROR,h)},t.handlePlaylistLoaded=function(e,t,r,i,a,n){var s=this.hls,o=i.type,l=i.level,u=i.id,d=i.groupId,h=i.deliveryDirectives,f=ut(t,i),c=lt(i),v="number"==typeof i.level&&c===nt?l:void 0;if(e.fragments.length){e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));var g=e.playlistParsingError;if(g)s.trigger(E.ERROR,{type:T.NETWORK_ERROR,details:S.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:g,reason:g.message,response:t,context:i,level:v,parent:c,networkDetails:a,stats:r});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case tt:case rt:s.trigger(E.LEVEL_LOADED,{details:e,level:v||0,id:u||0,stats:r,networkDetails:a,deliveryDirectives:h});break;case it:s.trigger(E.AUDIO_TRACK_LOADED,{details:e,id:u||0,groupId:d||"",stats:r,networkDetails:a,deliveryDirectives:h});break;case at:s.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,id:u||0,groupId:d||"",stats:r,networkDetails:a,deliveryDirectives:h})}}else{var m=new Error("No Segments found in Playlist");s.trigger(E.ERROR,{type:T.NETWORK_ERROR,details:S.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:i,level:v,parent:c,networkDetails:a,stats:r})}},e}();function ht(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function ft(e,t,r,i){var a=e.mode;if("disabled"===a&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=function(e,t,r){var i=[],a=function(e,t){if(te[r].endTime)return-1;for(var i=0,a=r;i<=a;){var n=Math.floor((a+i)/2);if(te[n].startTime&&i-1)for(var n=a,s=e.length;n=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;syt&&(h=yt),h-d<=0&&(h=d+.25);for(var f=0;ft.startDate&&(!e||t.startDate.05&&this.forwardBufferLength>1){var l=Math.min(2,Math.max(1,n)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(l,Math.max(1,u))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}}}}},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},s(e,[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config,t=this.levelDetails;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,a=this.config,n=a.liveSyncDuration,s=a.liveSyncDurationCount,o=a.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==n?n:s*i);var d=i;return u+Math.min(1*this.stallCount,d)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;var i=r.edge,a=e-t-this.edgeStalled,n=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,a),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}]),e}(),Lt=["NONE","TYPE-0","TYPE-1",null],Rt=["SDR","PQ","HLG"],At="",bt="YES",Dt="v2",kt=function(){function e(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},e}(),_t=function(){function e(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}var t=e.prototype;return t.hasAudioGroup=function(e){return xt(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return xt(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}},t.addFallback=function(){},s(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}]),e}();function xt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function wt(e,t){var r=t.startPTS;if(m(r)){var i,a=0;t.sn>e.sn?(a=r-e.start,i=e):(a=e.start-r,i=t),i.duration!==a&&(i.duration=a)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration:t.start=Math.max(e.start-t.duration,0)}function Ct(e,t,r,i,a,n){i-r<=0&&(k.warn("Fragment should have a positive duration",t),i=r+t.duration,n=a+t.duration);var s=r,o=i,l=t.startPTS,u=t.endPTS;if(m(l)){var d=Math.abs(l-r);m(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,s=Math.max(r,l),r=Math.min(r,l),a=Math.min(a,t.startDTS),o=Math.min(i,u),i=Math.max(i,u),n=Math.max(n,t.endDTS)}var h=r-t.start;0!==t.start&&(t.start=r),t.duration=i-t.start,t.startPTS=r,t.maxStartPTS=s,t.startDTS=a,t.endPTS=i,t.minEndPTS=o,t.endDTS=n;var f,c=t.sn;if(!e||ce.endSN)return 0;var v=c-e.startSN,g=e.fragments;for(g[v]=t,f=v;f>0;f--)wt(g[f],g[f-1]);for(f=v;f=0;a--){var n=i[a].initSegment;if(n){r=n;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;var s,l,u,d,h,f=0;if(function(e,t,r){for(var i=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=a;u<=n;u++){var d=l[s+u],h=o[u];i&&!h&&u=i.length||function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i499)}(a)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}var Vt=function(e,t){for(var r=0,i=e.length-1,a=null,n=null;r<=i;){var s=t(n=e[a=(r+i)/2|0]);if(s>0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null};function Kt(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var a=null;if(e){a=t[e.sn-t[0].sn+1]||null;var n=e.endDTS-r;n>0&&n<15e-7&&(r+=15e-7)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&(!e||e.level===a.level)&&0===jt(r,i,a))return a;var s=Vt(t,jt.bind(null,r,i));return!s||s===e&&a?a:s}function jt(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Wt(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}var Yt=0,qt=2,zt=3,Xt=5,Qt=0,Jt=1,$t=2,Zt=function(){function e(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=k.log.bind(k,"[info]:"),this.warn=k.warn.bind(k,"[warning]:"),this.error=k.error.bind(k,"[error]:"),this.registerListeners()}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))},t.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},t.startLoad=function(e){},t.stopLoad=function(){this.playlistError=0},t.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===nt?e.level:this.hls.loadLevel},t.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},t.onLevelUpdated=function(){this.playlistError=0},t.onError=function(e,t){var r,i;if(!t.fatal){var a=this.hls,n=t.context;switch(t.details){case S.FRAG_LOAD_ERROR:case S.FRAG_LOAD_TIMEOUT:case S.KEY_LOAD_ERROR:case S.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case S.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:Yt,flags:Qt});case S.FRAG_GAP:case S.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=qt);case S.LEVEL_EMPTY_ERROR:case S.LEVEL_PARSING_ERROR:var s,o,l=t.parent===nt?t.level:a.loadLevel;return void(t.details===S.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(o=s.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l)));case S.LEVEL_LOAD_ERROR:case S.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case S.AUDIO_TRACK_LOAD_ERROR:case S.AUDIO_TRACK_LOAD_TIMEOUT:case S.SUBTITLE_LOAD_ERROR:case S.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var u=a.levels[a.loadLevel];if(u&&(n.type===it&&u.hasAudioGroup(n.groupId)||n.type===at&&u.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.loadLevel),t.errorAction.action=qt,void(t.errorAction.flags=Jt)}return;case S.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var d=a.levels[a.loadLevel],h=null==d?void 0:d.attrs["HDCP-LEVEL"];return void(h?t.errorAction={action:qt,flags:$t,hdcpLevel:h}:this.keySystemError(t));case S.BUFFER_ADD_CODEC_ERROR:case S.REMUX_ALLOC_ERROR:case S.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(i=t.level)?i:a.loadLevel));case S.INTERNAL_EXCEPTION:case S.BUFFER_APPENDING_ERROR:case S.BUFFER_FULL_ERROR:case S.LEVEL_SWITCH_ERROR:case S.BUFFER_STALLED_ERROR:case S.BUFFER_SEEK_OVER_HOLE:case S.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:Yt,flags:Qt})}t.type===T.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},t.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},t.getPlaylistRetryOrSwitchAction=function(e,t){var r=Bt(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Ht(r,i,Nt(e),e.response))return{action:Xt,flags:Qt,retryConfig:r,retryCount:i};var a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=i),a},t.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],a=t.config,n=a.fragLoadPolicy,s=a.keyLoadPolicy,o=Bt(e.details.startsWith("key")?s:n,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==S.FRAG_GAP&&i.fragmentError++,Ht(o,l,Nt(e),e.response)))return{action:Xt,flags:Qt,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u},t.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var a,n,s=e.details;i.loadError++,s===S.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,d=r.minAutoLevel,h=r.maxAutoLevel;r.autoLevelEnabled||(r.loadLevel=-1);for(var f,c=null==(a=e.frag)?void 0:a.type,v=(c===st&&s===S.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(s===S.BUFFER_ADD_CODEC_ERROR||s===S.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return i.audioCodec!==t})),g="video"===e.sourceBufferName&&(s===S.BUFFER_ADD_CODEC_ERROR||s===S.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(n=e.context)?n:{},p=m.type,y=m.groupId,E=function(){var t=(T+u)%l.length;if(t!==u&&t>=d&&t<=h&&0===l[t].loadError){var r,a,n=l[t];if(s===S.FRAG_GAP&&e.frag){var f=l[t].details;if(f){var m=Kt(e.frag,f.fragments,e.frag.start);if(null!=m&&m.gap)return 0}}else{if(p===it&&n.hasAudioGroup(y)||p===at&&n.hasSubtitleGroup(y))return 0;if(c===st&&null!=(r=i.audioGroups)&&r.some((function(e){return n.hasAudioGroup(e)}))||c===ot&&null!=(a=i.subtitleGroups)&&a.some((function(e){return n.hasSubtitleGroup(e)}))||v&&i.audioCodec===n.audioCodec||!v&&i.audioCodec!==n.audioCodec||g&&i.codecSet===n.codecSet)return 0}return o=t,1}},T=l.length;T--&&(0===(f=E())||1!==f););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:qt,flags:Qt,nextAutoLevel:o}}return{action:qt,flags:Jt}},t.onErrorOut=function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case Yt:break;case qt:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===S.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'+t.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},t.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,a=r.hdcpLevel,n=r.nextAutoLevel;switch(i){case Qt:this.switchLevel(e,n);break;case $t:a&&(t.maxHdcpLevel=Lt[Lt.indexOf(a)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}r.resolved||this.switchLevel(e,n)}},t.switchLevel=function(e,t){void 0!==t&&e.errorAction&&(this.warn("switching to level "+t+" after "+e.details),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},e}(),er=function(){function e(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=k.log.bind(k,t+":"),this.warn=k.warn.bind(k,t+":"),this.hls=e}var t=e.prototype;return t.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},t.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},t.startLoad=function(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()},t.stopLoad=function(){this.canLoad=!1,this.clearTimer()},t.switchParams=function(e,t){var r=null==t?void 0:t.renditionReports;if(r){for(var i=-1,a=0;a=0&&d>t.partTarget&&(u+=1)}return new kt(l,u>=0?u:void 0,At)}}},t.loadPlaylist=function(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())},t.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},t.shouldReloadPlaylist=function(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)},t.playlistLoaded=function(e,t,r){var i=this,a=t.details,n=t.stats,s=self.performance.now(),o=n.loading.first?Math.max(0,s-n.loading.first):0;if(a.advancedDateTime=Date.now()-o,a.live||null!=r&&r.live){if(a.reloaded(r),r&&this.log("live playlist "+e+" "+(a.advanced?"REFRESHED "+a.lastPartSn+"-"+a.lastPartIndex:a.updated?"UPDATED":"MISSED")),r&&a.fragments.length>0&&It(r,a),!this.canLoad||!a.live)return;var l,u=void 0,d=void 0;if(a.canBlockReload&&a.endSN&&a.advanced){var h=this.hls.config.lowLatencyMode,f=a.lastPartSn,c=a.endSN,v=a.lastPartIndex,g=f===c;-1!==v?(u=g?c+1:f,d=g?h?0:v:v+1):u=c+1;var m=a.age,p=m+a.ageHeader,y=Math.min(p-a.partTarget,1.5*a.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+a.age),y=0;else{var E=Math.floor(y/a.targetduration);u+=E,void 0!==d&&(d+=Math.round(y%a.targetduration/a.partTarget)),this.log("CDN Tune-in age: "+a.ageHeader+"s last advanced "+m.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+d)}a.tuneInGoal=y}if(l=this.getDeliveryDirectives(a,t.deliveryDirectives,u,d),h||!g)return void this.loadPlaylist(l)}else(a.canBlockReload||a.canSkipUntil)&&(l=this.getDeliveryDirectives(a,t.deliveryDirectives,u,d));var T=this.hls.mainForwardBufferInfo,S=T?T.end-T.len:0,L=function(e,t){void 0===t&&(t=1/0);var r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var a=1e3*i[i.length-1].duration;athis.requestScheduled+L&&(this.requestScheduled=n.loading.start),void 0!==u&&a.canBlockReload?this.requestScheduled=n.loading.first+L-(1e3*a.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+L=u.maxNumRetry)return!1;if(i&&null!=(h=e.context)&&h.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var f=Ut(u,l);this.timer=self.setTimeout((function(){return t.loadPlaylist()}),f),this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" in '+f+"ms")}e.levelRetry=!0,a.resolved=!0}return d},e}(),tr=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),rr=function(){function e(e,t,r,i){void 0===i&&(i=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new tr(e),this.fast_=new tr(t),this.defaultTTFB_=i,this.ttfb_=new tr(e)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_,a=this.ttfb_;r.halfLife!==e&&(this.slow_=new tr(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new tr(t,i.getEstimate(),i.getTotalWeight())),a.halfLife!==e&&(this.ttfb_=new tr(e,a.getEstimate(),a.getTotalWeight()))},t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},e}();function ir(e,t){var r=!1,i=[];return e&&(r="SDR"!==e,i=[e]),t&&(i=t.allowedVideoRanges||Rt.slice(0),i=(r=void 0!==t.preferHDR?t.preferHDR:function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())?i.filter((function(e){return"SDR"!==e})):["SDR"]),{preferHDR:r,allowedVideoRanges:i}}function ar(e,t){k.log('[abr] start candidates with "'+e+'" ignored because '+t)}var nr=function(){function e(e){var t=this;this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=function(){var e=t.fragCurrent,r=t.partCurrent,i=t.hls,a=i.autoLevelEnabled,n=i.media;if(e&&n){var s=performance.now(),o=r?r.stats:e.stats,l=r?r.duration:e.duration,u=s-o.loading.start,d=i.minAutoLevel;if(o.aborted||o.loaded&&o.loaded===o.total||e.level<=d)return t.clearTimer(),void(t._nextAutoLevel=-1);if(a&&!n.paused&&n.playbackRate&&n.readyState){var h=i.mainForwardBufferInfo;if(null!==h){var f=t.bwEstimator.getEstimateTTFB(),c=Math.abs(n.playbackRate);if(!(u<=Math.max(f,l/(2*c)*1e3))){var v=h.len/c,g=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&g>-1,y=t.getBwEstimate(),T=i.levels,S=T[e.level],L=o.total||Math.max(o.loaded,Math.round(l*S.averageBitrate/8)),R=p?u-g:u;R<1&&p&&(R=Math.min(u,8*o.loaded/y));var A=p?1e3*o.loaded/R:0,b=A?(L-o.loaded)/A:8*L/y+f/1e3;if(!(b<=v)){var D,_=A?8*A:y,x=Number.POSITIVE_INFINITY;for(D=e.level-1;D>d;D--){var w=T[D].maxBitrate;if((x=t.getTimeToLoadFrag(f/1e3,_,l*w,!T[D].details))=b||x>10*l)){i.nextLoadLevel=i.nextAutoLevel=D,p?t.bwEstimator.sample(u-Math.min(f,g),o.loaded):t.bwEstimator.sampleTTFB(u);var C=T[D].maxBitrate;t.getBwEstimate()*t.hls.config.abrBandWidthUpFactor>C&&t.resetEstimator(C),t.clearTimer(),k.warn("[abr] Fragment "+e.sn+(r?" part "+r.index:"")+" of level "+e.level+" is loading too slowly;\n Time to underbuffer: "+v.toFixed(3)+" s\n Estimated load time for current fragment: "+b.toFixed(3)+" s\n Estimated load time for down switch fragment: "+x.toFixed(3)+" s\n TTFB estimate: "+(0|g)+" ms\n Current BW estimate: "+(m(y)?0|y:"Unknown")+" bps\n New BW estimate: "+(0|t.getBwEstimate())+" bps\n Switching to level "+D+" @ "+(0|C)+" bps"),i.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:r,stats:o})}}}}}}},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}var t=e.prototype;return t.resetEstimator=function(e){e&&(k.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},t.initEstimator=function(){var e=this.hls.config;return new rr(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},t.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))},t.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},t.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},t.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},t.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},t.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},t.onLevelSwitching=function(e,t){this.clearTimer()},t.onError=function(e,t){if(!t.fatal)switch(t.details){case S.BUFFER_ADD_CODEC_ERROR:case S.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case S.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,a=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var n=performance.now(),s=a?a.stats:r.stats,o=n-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}},t.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?this.lastLevelLoadSec:0)},t.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,a=i.end-i.start;m(a)&&(this.lastLevelLoadSec=a/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},t.onFragLoaded=function(e,t){var r=t.frag,i=t.part,a=i?i.stats:r.stats;if(r.type===nt&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+a.loaded,l=(s.loaded?s.loaded.duration:0)+n;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:a,frag:r,part:i,id:r.type};this.onFragBuffered(E.FRAG_BUFFERED,u),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},t.onFragBuffered=function(e,t){var r=t.frag,i=t.part,a=null!=i&&i.stats.loaded?i.stats:r.stats;if(!a.aborted&&!this.ignoreFragment(r)){var n=a.parsing.end-a.loading.start-Math.min(a.loading.first-a.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,a.loaded),a.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},t.ignoreFragment=function(e){return e.type!==nt||"initSegment"===e.sn},t.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},t.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},t.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,i=r.maxAutoLevel,a=r.config,n=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=a.abrBandWidthFactor,d=a.abrBandWidthUpFactor;if(l){var h=this.findBestLevel(o,n,i,l,0,u,d);if(h>=0)return h}var f=s?Math.min(s,a.maxStarvationDelay):a.maxStarvationDelay;if(!l){var c=this.bitrateTestDelay;c&&(f=(s?Math.min(s,a.maxLoadingDelay):a.maxLoadingDelay)-c,k.info("[abr] bitrate test took "+Math.round(1e3*c)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*f)+" ms"),u=d=1)}var v=this.findBestLevel(o,n,i,l,f,u,d);if(k.info("[abr] "+(l?"rebuffering expected":"buffer is empty")+", optimal quality level "+v),v>-1)return v;var g=r.levels[n],m=r.levels[r.loadLevel];return(null==g?void 0:g.bitrate)<(null==m?void 0:m.bitrate)?n:r.loadLevel},t.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r},t.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},t.findBestLevel=function(e,t,r,i,a,n,s){var o,l=this,u=i+a,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,f=this.fragCurrent,c=this.partCurrent,v=this.hls,g=v.levels,p=v.allAudioTracks,y=v.loadLevel,E=v.config;if(1===g.length)return 0;var T,S=g[h],L=!(null==S||null==(o=S.details)||!o.live),R=-1===y||-1===d,A="SDR",b=(null==S?void 0:S.frameRate)||0,D=E.audioPreference,_=E.videoPreference,x=this.audioTracksByGroup||(this.audioTracksByGroup=function(e){return e.reduce((function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(p));if(R){if(-1!==this.firstSelection)return this.firstSelection;var w=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce((function(e,r){if(!r.codecSet)return e;var i=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var n=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,n),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,i&&i.forEach((function(e){if(e){var r=t.groups[e];a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach((function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}})),e}),{})}(g,x,t,r)),C=function(e,t,r,i,a){for(var n=Object.keys(e),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=s&&2===parseInt(s),u=!0,d=!1,h=1/0,f=1/0,c=1/0,v=0,g=[],p=ir(t,a),y=p.preferHDR,E=p.allowedVideoRanges,T=function(){var t=e[n[S]];u=t.channels[2]>0,h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),c=Math.min(c,t.minBitrate);var r=E.filter((function(e){return t.videoRanges[e]>0}));r.length>0&&(d=!0,g=r)},S=n.length;S--;)T();h=m(h)?h:0,f=m(f)?f:0;var L=Math.max(1080,h),R=Math.max(30,f);return c=m(c)?c:r,r=Math.max(c,r),d||(t=void 0,g=[]),{codecSet:n.reduce((function(t,i){var a=e[i];if(i===t)return t;if(a.minBitrate>r)return ar(i,"min bitrate of "+a.minBitrate+" > current estimate of "+r),t;if(!a.hasDefaultAudio)return ar(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return ar(i,'audio codec preference "'+o+'" not found'),t;if(s&&!l){if(!a.channels[s])return ar(i,"no renditions with "+s+" channel sound found (channels options: "+Object.keys(a.channels)+")"),t}else if((!o||l)&&u&&0===a.channels[2])return ar(i,"no renditions with stereo sound found"),t;return a.minHeight>L?(ar(i,"min resolution of "+a.minHeight+" > maximum of "+L),t):a.minFramerate>R?(ar(i,"min framerate of "+a.minFramerate+" > maximum of "+R),t):g.some((function(e){return a.videoRanges[e]>0}))?a.maxScore=Ne(t)||a.fragmentError>e[t].fragmentError)?t:(v=a.maxScore,i):(ar(i,"no variants with VIDEO-RANGE of "+JSON.stringify(g)+" found"),t)}),void 0),videoRanges:g,preferHDR:y,minFramerate:f,minBitrate:c}}(w,A,e,D,_),I=C.codecSet,P=C.videoRanges,F=C.minFramerate,O=C.minBitrate,M=C.preferHDR;T=I,A=M?P[P.length-1]:P[0],b=F,e=Math.max(e,O),k.log("[abr] picked start tier "+JSON.stringify(C))}else T=null==S?void 0:S.codecSet,A=null==S?void 0:S.videoRange;for(var N,B=c?c.duration:f?f.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t,o=g[V],f=V>h;if(!o)return 0;if(T&&o.codecSet!==T||A&&o.videoRange!==A||f&&b>o.frameRate||!f&&b>0&&b=2*B&&0===a?g[V].averageBitrate:g[V].maxBitrate,_=l.getTimeToLoadFrag(U,v,D*E,void 0===p);if(v>=D&&(V===d||0===o.loadError&&0===o.fragmentError)&&(_<=U||!m(_)||L&&!l.bitrateTestDelay||_"+V+" adjustedbw("+Math.round(v)+")-bitrate="+Math.round(v-D)+" ttfb:"+U.toFixed(1)+" avgDuration:"+E.toFixed(1)+" maxFetchDuration:"+u.toFixed(1)+" fetchDuration:"+_.toFixed(1)+" firstSelection:"+R+" codecSet:"+T+" videoRange:"+A+" hls.loadLevel:"+y)),R&&(l.firstSelection=V),{v:V}}},V=r;V>=t;V--)if(0!==(N=H())&&N)return N.v;return-1},s(e,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,r,t,0,a,1,1);if(n>-1)return n;var s=this.hls.firstLevel,o=Math.min(Math.max(s,r),t);return k.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist "+s+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var a=this.hls.levels;if(a.length>Math.max(e,i)&&a[e].loadError<=a[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel,a=Math.min(Math.max(e,i),r);this._nextAutoLevel!==a&&(this.nextAutoLevelKey="",this._nextAutoLevel=a)}}]),e}(),sr={length:0,start:function(){return 0},end:function(){return 0}},or=function(){function e(){}return e.isBuffered=function(t,r){try{if(t)for(var i=e.getBuffered(t),a=0;a=i.start(a)&&r<=i.end(a))return!0}catch(e){}return!1},e.bufferInfo=function(t,r,i){try{if(t){var a,n=e.getBuffered(t),s=[];for(a=0;as&&(i[n-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;for(var o,l=0,u=t,d=t,h=0;h=f&&t "+e+")")},this.hls=e;var r="[buffer-controller]";this.appendSource=e.config.preferManagedMediaSource&&"undefined"!=typeof self&&self.ManagedMediaSource,this.log=k.log.bind(k,r),this.warn=k.warn.bind(k,r),this.error=k.error.bind(k,r),this._initSourceBuffer(),this.registerListeners()}var t=e.prototype;return t.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},t.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null},t.registerListeners=function(){var e=this.hls;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this)},t.unregisterListeners=function(){var e=this.hls;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this)},t._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new lr(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null},t.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},t.onManifestParsed=function(e,t){var r=2;t.audio&&!t.video||t.altAudio,r=1,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},t.onMediaAttaching=function(e,t){var r=this.media=t.media,i=Ce(this.appendSource);if(r&&i){var a,n=this.mediaSource=new i;this.log("created media source: "+(null==(a=n.constructor)?void 0:a.name)),n.addEventListener("sourceopen",this._onMediaSourceOpen),n.addEventListener("sourceended",this._onMediaSourceEnded),n.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.addEventListener("startstreaming",this._onStartStreaming),n.addEventListener("endstreaming",this._onEndStreaming));var s=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&n instanceof o,hr(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s;r.addEventListener("emptied",this._onMediaEmptied)}},t.onMediaDetaching=function(){var e=this.media,t=this.mediaSource,r=this._objectUrl;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(e.removeAttribute("src"),this.appendSource&&hr(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(E.MEDIA_DETACHED,void 0)},t.onBufferReset=function(){var e=this;this.getSourceBufferTypes().forEach((function(t){e.resetBuffer(t)})),this._initSourceBuffer()},t.resetBuffer=function(e){var t=this.sourceBuffer[e];try{var r;t&&(this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t))}catch(t){this.warn("onBufferReset "+e,t)}},t.onBufferCodecs=function(e,t){var r=this,i=this.getSourceBufferTypes().length,a=Object.keys(t);if(a.forEach((function(e){if(i){var a=r.tracks[e];if(a&&"function"==typeof a.buffer.changeType){var n,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,d=s.container,h=s.metadata,f=He(a.codec,a.levelCodec),c=null==f?void 0:f.replace(ur,"$1"),v=He(l,u),g=null==(n=v)?void 0:n.replace(ur,"$1");if(v&&c!==g){"audio"===e.slice(0,5)&&(v=Ge(v,r.appendSource));var m=d+";codecs="+v;r.appendChangeType(e,m),r.log("switching codec "+f+" to "+v),r.tracks[e]={buffer:a.buffer,codec:l,container:d,levelCodec:u,metadata:h,id:o}}}}else r.pendingTracks[e]=t[e]})),!i){var n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(n+" bufferCodec event(s) expected "+a.join(",")),this.bufferCodecEventsExpected=n),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}},t.appendChangeType=function(e,t){var r=this,i=this.operationQueue,a={execute:function(){var a=r.sourceBuffer[e];a&&(r.log("changing "+e+" sourceBuffer type to "+t),a.changeType(t)),i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};i.append(a,e,!!this.pendingTracks[e])},t.onBufferAppending=function(e,t){var r=this,i=this.hls,a=this.operationQueue,n=this.tracks,s=t.data,o=t.type,l=t.frag,u=t.part,d=t.chunkMeta,h=d.buffering[o],f=self.performance.now();h.start=f;var c=l.stats.buffering,v=u?u.stats.buffering:null;0===c.start&&(c.start=f),v&&0===v.start&&(v.start=f);var g=n.audio,m=!1;"audio"===o&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===d.id||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);var p=l.start,y={execute:function(){if(h.executeStart=self.performance.now(),m){var e=r.sourceBuffer[o];if(e){var t=p-e.timestampOffset;Math.abs(t)>=.1&&(r.log("Updating audio SourceBuffer timestampOffset to "+p+" (delta: "+t+") sn: "+l.sn+")"),e.timestampOffset=p)}}r.appendExecutor(s,o)},onStart:function(){},onComplete:function(){var e=self.performance.now();h.executeEnd=h.end=e,0===c.first&&(c.first=e),v&&0===v.first&&(v.first=e);var t=r.sourceBuffer,i={};for(var a in t)i[a]=or.getBuffered(t[a]);r.appendErrors[o]=0,"audio"===o||"video"===o?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(E.BUFFER_APPENDED,{type:o,frag:l,part:u,chunkMeta:d,parent:l.type,timeRanges:i})},onError:function(e){var t={type:T.MEDIA_ERROR,parent:l.type,details:S.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:u,chunkMeta:d,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=S.BUFFER_FULL_ERROR;else{var a=++r.appendErrors[o];t.details=S.BUFFER_APPEND_ERROR,r.warn("Failed "+a+"/"+i.config.appendErrorMaxRetry+' times to append segment in "'+o+'" sourceBuffer'),a>=i.config.appendErrorMaxRetry&&(t.fatal=!0)}i.trigger(E.ERROR,t)}};a.append(y,o,!!this.pendingTracks[o])},t.onBufferFlushing=function(e,t){var r=this,i=this.operationQueue,a=function(e){return{execute:r.removeExecutor.bind(r,e,t.startOffset,t.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:function(t){r.warn("Failed to remove from "+e+" SourceBuffer",t)}}};t.type?i.append(a(t.type),t.type):this.getSourceBufferTypes().forEach((function(e){i.append(a(e),e)}))},t.onFragParsed=function(e,t){var r=this,i=t.frag,a=t.part,n=[],s=a?a.elementaryStreams:i.elementaryStreams;s[M]?n.push("audiovideo"):(s[F]&&n.push("audio"),s[O]&&n.push("video")),0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,a&&(a.stats.buffering.end=e);var t=a?a.stats:i.stats;r.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:a,stats:t,id:i.type})}),n)},t.onFragChanged=function(e,t){this.trimBuffers()},t.onBufferEos=function(e,t){var r=this;this.getSourceBufferTypes().reduce((function(e,i){var a=r.sourceBuffer[i];return!a||t.type&&t.type!==i||(a.ending=!0,a.ended||(a.ended=!0,r.log(i+" sourceBuffer now EOS"))),e&&!(a&&!a.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((function(){r.getSourceBufferTypes().forEach((function(e){var t=r.sourceBuffer[e];t&&(t.ending=!1)}));var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)})))},t.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},t.trimBuffers=function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.getSourceBufferTypes().length){var i=e.config,a=r.currentTime,n=t.levelTargetDuration,s=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(m(s)&&s>0){var o=Math.max(s,n),l=Math.floor(a/n)*n-o;this.flushBackBuffer(a,n,l)}if(m(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){var u=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),d=Math.max(u,n),h=Math.floor(a/n)*n+d;this.flushFrontBuffer(a,n,h)}}},t.flushBackBuffer=function(e,t,r){var i=this,a=this.details,n=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(s){var o=n[s];if(o){var l=or.getBuffered(o);if(l.length>0&&r>l.start(0)){if(i.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:r}),null!=a&&a.live)i.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(o.ended&&l.end(l.length-1)-e<2*t)return void i.log("Cannot flush "+s+" back buffer while SourceBuffer is in ended state");i.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:s})}}}))},t.flushFrontBuffer=function(e,t,r){var i=this,a=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(n){var s=a[n];if(s){var o=or.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),d=o.end(l-1);if(r>u||e>=u&&e<=d)return;if(s.ended&&e-d<2*t)return void i.log("Cannot flush "+n+" front buffer while SourceBuffer is in ended state");i.hls.trigger(E.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:n})}}))},t.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var e=this.details,t=this.hls,r=this.media,i=this.mediaSource,a=e.fragments[0].start+e.totalduration,n=r.duration,s=m(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(a>s&&a>n||!m(n))&&(this.log("Updating Media Source duration to "+a.toFixed(3)),i.duration=a)}},t.updateSeekableRange=function(e){var t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){var i=Math.max(0,r[0].start),a=Math.max(i,i+e.totalduration);this.log("Media Source duration is set to "+t.duration+". Setting seekable range to "+i+"-"+a+"."),t.setLiveSeekableRange(i,a)}},t.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&(!e||2===i||"audiovideo"in r)){this.createSourceBuffers(r),this.pendingTracks={};var a=this.getSourceBufferTypes();if(a.length)this.hls.trigger(E.BUFFER_CREATED,{tracks:this.tracks}),a.forEach((function(e){t.executeNext(e)}));else{var n=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:n,reason:n.message})}}},t.createSourceBuffers=function(e){var t=this,r=this.sourceBuffer,i=this.mediaSource;if(!i)throw Error("createSourceBuffers called when mediaSource was null");var a=function(a){if(!r[a]){var n=e[a];if(!n)throw Error("source buffer exists for track "+a+", however track does not");var s=n.levelCodec||n.codec;s&&"audio"===a.slice(0,5)&&(s=Ge(s,t.appendSource));var o=n.container+";codecs="+s;t.log("creating sourceBuffer("+o+")");try{var l=r[a]=i.addSourceBuffer(o),u=a;t.addBufferListener(u,"updatestart",t._onSBUpdateStart),t.addBufferListener(u,"updateend",t._onSBUpdateEnd),t.addBufferListener(u,"error",t._onSBUpdateError),t.appendSource&&t.addBufferListener(u,"bufferedchange",(function(e,r){var i=r.removedRanges;null!=i&&i.length&&t.hls.trigger(E.BUFFER_FLUSHED,{type:a})})),t.tracks[a]={buffer:l,codec:s,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(e){t.error("error while trying to add sourceBuffer: "+e.message),t.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:a,mimeType:o})}}};for(var n in e)a(n)},t._onSBUpdateStart=function(e){this.operationQueue.current(e).onStart()},t._onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.operationQueue;r.current(e).onComplete(),r.shiftAndExecuteNext(e)}else this.resetBuffer(e)},t._onSBUpdateError=function(e,t){var r,i=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(r=this.mediaSource)?void 0:r.readyState));this.error(""+i,t),this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var a=this.operationQueue.current(e);a&&a.onError(i)},t.removeExecutor=function(e,t,r){var i=this.media,a=this.mediaSource,n=this.operationQueue,s=this.sourceBuffer[e];if(!i||!a||!s)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void n.shiftAndExecuteNext(e);var o=m(i.duration)?i.duration:1/0,l=m(a.duration)?a.duration:1/0,u=Math.max(0,t),d=Math.min(r,o,l);d>u&&(!s.ending||s.ended)?(s.ended=!1,this.log("Removing ["+u+","+d+"] from the "+e+" SourceBuffer"),s.remove(u,d)):n.shiftAndExecuteNext(e)},t.appendExecutor=function(e,t){var r=this.sourceBuffer[t];if(r)r.ended=!1,r.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error("Attempting to append to the "+t+" SourceBuffer, but it does not exist")},t.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.getSourceBufferTypes()),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);var i=this.operationQueue,a=t.map((function(e){return i.appendBlocker(e)}));Promise.all(a).then((function(){e(),t.forEach((function(e){var t=r.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)}))}))},t.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},t.addBufferListener=function(e,t,r){var i=this.sourceBuffer[e];if(i){var a=r.bind(this,e);this.listeners[e].push({event:t,listener:a}),i.addEventListener(t,a)}},t.removeBufferListeners=function(e){var t=this.sourceBuffer[e];t&&this.listeners[e].forEach((function(e){t.removeEventListener(e.event,e.listener)}))},s(e,[{key:"mediaSrc",get:function(){var e,t=(null==(e=this.media)?void 0:e.firstChild)||this.media;return null==t?void 0:t.src}}]),e}();function hr(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}var fr=function(){function e(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},t.registerListeners=function(){var e=this.hls;e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&m(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping()},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&k.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var a=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(a,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,r){if(null==e||!e.length)return-1;for(var i,a,n=e.length-1,s=Math.max(t,r),o=0;o=s||l.height>=s)&&(i=l,!(a=e[o+1])||i.width!==a.width||i.height!==a.height)){n=o;break}}return n},s(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}}]),e}(),cr=function(){function e(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this)},t.unregisterListeners=function(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var a=i-this.lastTime,n=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*n/a,l=this.hls;if(l.trigger(E.FPS_DROP,{currentDropped:n,currentDecoded:s,totalDroppedFrames:r}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;k.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}(),vr=function(){function e(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=k.log.bind(k,"[content-steering]:"),this.registerListeners()}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))},t.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},t.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},t.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},t.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},t.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},t.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},t.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},t.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},t.onError=function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===qt&&r.flags===Jt){var i=this.levels,a=this.pathwayPriority,n=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?n=this.getPathwayForGroupId(o,u,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!a&&i&&(a=i.reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])),a&&a.length>1&&(this.updatePathwayPriority(a),r.resolved=this.pathwayId!==n),r.resolved||k.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+n+" levels: "+(i?i.length:i)+" priorities: "+JSON.stringify(a)+" penalized: "+JSON.stringify(this.penalizedPathways))}},t.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length?(this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t):e},t.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},t.updatePathwayPriority=function(e){var t;this.pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var a=0;a0){this.log('Setting Pathway to "'+n+'"'),this.pathwayId=n,Mt(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=s);break}}}},t.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),a=0;a=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),a.timeout!==a.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),a.timeout=a.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var n=t.status,s="text"!==t.responseType;if(n>=200&&n<300&&(s&&t.response||null!==t.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);var o=s?t.response:t.responseText,l="arraybuffer"===t.responseType?o.byteLength:o.length;if(r.loaded=r.total=l,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,e,o,t),!this.callbacks)return;var d={url:t.responseURL,data:o,code:n};this.callbacks.onSuccess(d,r,e,t)}else{var h=a.loadPolicy.errorRetry;Ht(h,r.retry,!1,{url:e.url,data:void 0,code:n})?this.retry(h):(k.error(n+" while loading "+e.url),this.callbacks.onError({code:n,text:t.statusText},e,t,r))}}}},t.loadtimeout=function(){var e,t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(Ht(t,this.stats.retry,!0))this.retry(t);else{var r;k.warn("timeout while loading "+(null==(r=this.context)?void 0:r.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}},t.retry=function(e){var t=this.context,r=this.stats;this.retryDelay=Ut(e,r.retry),r.retry++,k.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+r.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&pr.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},e}(),Er=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,a=0;a=i&&a(t,r,n.flush(),e)):a(t,r,l,e),o()})).catch((function(){return Promise.reject()}))}()},e}();function Lr(e,t){return new self.Request(e.url,t)}var Rr,Ar=function(e){function t(t,r,i){var a;return(a=e.call(this,t)||this).code=void 0,a.details=void 0,a.code=r,a.details=i,a}return l(t,e),t}(f(Error)),br=i(i({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:yr,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:nr,bufferController:dr,capLevelController:fr,errorController:Zt,fpsController:cr,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:H,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:vr});function Dr(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Dr):Object.keys(e).reduce((function(t,r){return t[r]=Dr(e[r]),t}),{}):e}function kr(e){var t=e.loader;t!==Sr&&t!==yr?(k.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=Sr,e.progressive=!0,e.enableSoftwareAES=!0,k.log("[config]: Progressive streaming enabled, using FetchLoader"))}var _r=function(e){function t(t,r){var i;return(i=e.call(this,t,"[level-controller]")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}l(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this.hls.config.preferManagedMediaSource,i=[],a={},n={},s=!1,o=!1,l=!1;t.levels.forEach((function(e){var t,u,d=e.attrs,h=e.audioCodec,f=e.videoCodec;-1!==(null==(t=h)?void 0:t.indexOf("mp4a.40.34"))&&(Rr||(Rr=/chrome|firefox/i.test(navigator.userAgent)),Rr&&(e.audioCodec=h=void 0)),h&&(e.audioCodec=h=Ge(h,r)),0===(null==(u=f)?void 0:u.indexOf("avc1"))&&(f=e.videoCodec=function(e){var t=e.split(".");if(t.length>2){var r=t.shift()+".";return(r+=parseInt(t.shift()).toString(16))+("000"+parseInt(t.shift()).toString(16)).slice(-4)}return e}(f));var c=e.width,v=e.height,g=e.unknownCodecs;if(s||(s=!(!c||!v)),o||(o=!!f),l||(l=!!h),!(null!=g&&g.length||h&&!Pe(h,"audio",r)||f&&!Pe(f,"video",r))){var m=d.CODECS,p=d["FRAME-RATE"],y=d["HDCP-LEVEL"],E=d["PATHWAY-ID"],T=d.RESOLUTION,S=d["VIDEO-RANGE"],L=(E||".")+"-"+e.bitrate+"-"+T+"-"+p+"-"+m+"-"+S+"-"+y;if(a[L])if(a[L].uri===e.url||e.attrs["PATHWAY-ID"])a[L].addGroupId("audio",d.AUDIO),a[L].addGroupId("text",d.SUBTITLES);else{var R=n[L]+=1;e.attrs["PATHWAY-ID"]=new Array(R+1).join(".");var A=new _t(e);a[L]=A,i.push(A)}else{var b=new _t(e);a[L]=b,n[L]=1,i.push(b)}}})),this.filterAndSortMediaOptions(i,t,s,o,l)},r.filterAndSortMediaOptions=function(e,t,r,i,a){var n=this,s=[],o=[],l=e;if((r||i)&&a&&(l=l.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,a=e.width,n=e.height;return(!!r||!(!a||!n))&&!!(t=i)&&Rt.indexOf(t)>-1}))),0!==l.length){if(t.audioTracks){var u=this.hls.config.preferManagedMediaSource;xr(s=t.audioTracks.filter((function(e){return!e.audioCodec||Pe(e.audioCodec,"audio",u)})))}t.subtitles&&xr(o=t.subtitles);var d=l.slice(0);l.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Rt.indexOf(e.videoRange)-Rt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=Me(e.videoCodec),a=Me(t.videoCodec);if(i!==a)return a-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var n=Ne(e.codecSet),s=Ne(t.codecSet);if(n!==s)return s-n}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var h=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==d.length)for(var f=0;fm&&m===br.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=p)}break}var y=a&&!i,L={levels:l,audioTracks:s,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:i,altAudio:!y&&s.some((function(e){return!!e.url}))};this.hls.trigger(E.MANIFEST_PARSED,L),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else Promise.resolve().then((function(){if(n.hls){t.levels.length&&n.warn("One or more CODECS in variant not supported: "+JSON.stringify(t.levels[0].attrs));var e=new Error("no level with compatible codecs found in manifest");n.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}))},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===rt&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(void 0!==r&&r.type===nt){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var a=this._levels[r.level];null!=a&&a.loadError&&(this.log("Resetting level error count of "+a.loadError+" on frag buffered"),a.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,a=t.level,n=t.details,s=this._levels[a];if(!s)return this.warn("Invalid level index "+a),void(null!=(i=t.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0));a===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0),this.playlistLoaded(a,t,s.details)):null!=(r=t.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var r=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){var a=i.uri;if(t)try{a=t.addDirectives(a)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}var n=i.attrs["PATHWAY-ID"];this.log("Loading level index "+r+(void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:"")+" with"+(n?" Pathway "+n:"")+" "+a),this.clearTimer(),this.hls.trigger(E.LEVEL_LOADING,{url:a,level:r,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}},r.removeLevel=function(e){var t,r=this,i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));Mt(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(E.LEVELS_UPDATED,{levels:i})},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},s(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var a=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,a!==e||!o.details||!n||s!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+a+(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,u);var d=o.details;if(!d||d.live){var h=this.switchParams(o.uri,null==n?void 0:n.details);this.loadPlaylist(h)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}]),t}(er);function xr(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var wr="NOT_LOADED",Cr="APPENDING",Ir="PARTIAL",Pr="OK",Fr=function(){function e(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var a=r[i];if(!a)break;var n=a.end;if(a.start<=e&&null!==n&&e<=n)return a}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){for(var r=this.fragments,i=Object.keys(r),a=i.length;a--;){var n=r[i[a]];if((null==n?void 0:n.body.type)===t&&n.buffered){var s=n.body;if(s.start<=e&&e<=s.end)return s}}return null},t.detectEvictedFragments=function(e,t,r,i){var a=this;this.timeRanges&&(this.timeRanges[e]=t);var n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(i){var s=a.fragments[i];if(s&&!(n>=s.body.sn))if(s.buffered||s.loaded){var o=s.range[e];o&&o.time.some((function(e){var r=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&a.removeFragment(s.body),r}))}else s.body.type===r&&a.removeFragment(s.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges,i=e.frag,a=e.part;if(r&&"initSegment"!==i.sn){var n=Mr(i),s=this.fragments[n];if(!(!s||s.buffered&&i.gap)){var o=!i.relurl;Object.keys(r).forEach((function(e){var n=i.elementaryStreams[e];if(n){var l=r[e],u=o||!0===n.partial;s.range[e]=t.getBufferedTimes(i,a,u,l)}})),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Or(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}}},t.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=r.filter((function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var r=Mr(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var a={time:[],partial:r},n=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||n,u=0;u=d&&o<=h){a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(nd){var f=Math.max(n,i.start(u)),c=Math.min(s,i.end(u));c>f&&(a.partial=!0,a.time.push({startPTS:f,endPTS:c}))}else if(s<=d)break}return a},t.getPartialFragment=function(e){var t,r,i,a=null,n=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&Or(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),n<=t&&(a=u.body,n=t)))})),a},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Or(t))},t.getState=function(e){var t=Mr(e),r=this.fragments[t];return r?r.buffered?Or(r)?Ir:Pr:Cr:wr},t.isTimeBuffered=function(e,t,r){for(var i,a,n=0;n=i&&t<=a)return!0;if(t<=i)return!1}return!1},t.onFragLoaded=function(e,t){var r=t.frag,i=t.part;if("initSegment"!==r.sn&&!r.bitrateTest){var a=i?null:t,n=Mr(r);this.fragments[n]={body:r,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=this,i=t.frag,a=t.part,n=t.timeRanges;if("initSegment"!==i.sn){var s=i.type;if(a){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(a)}this.timeRanges=n,Object.keys(n).forEach((function(e){var t=n[e];r.detectEvictedFragments(e,t,s,a)}))}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Mr(e);return!!this.fragments[t]},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,r,i,a){var n=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(s){var o=n.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.starte&&(o.buffered||a)&&n.removeFragment(l)}}))},t.removeFragment=function(e){var t=Mr(e);e.stats.loaded=0,e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=r.filter((function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},e}();function Or(e){var t,r,i;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(i=e.range.audiovideo)?void 0:i.partial))}function Mr(e){return e.type+"_"+e.level+"_"+e.sn}var Nr=Math.pow(2,17),Br=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var r=this,a=e.url;if(!a)return Promise.reject(new Hr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(a?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,s=n.fLoader,o=n.loader;return new Promise((function(l,u){if(r.loader&&r.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void u(Gr(e));e.gap=!1}var d=r.loader=e.loader=s?new s(n):new o(n),h=Ur(e),f=Gt(n.fragLoadPolicy.default),c={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Nr};e.stats=d.stats,d.load(h,c,{onSuccess:function(t,i,a,n){r.resetLoader(e,d);var s=t.data;a.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),l({frag:e,part:null,payload:s,networkDetails:n})},onError:function(t,n,s,o){r.resetLoader(e,d),u(new Hr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:i({url:a,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:s,stats:o}))},onAbort:function(t,i,a){r.resetLoader(e,d),u(new Hr({type:T.NETWORK_ERROR,details:S.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:a,stats:t}))},onTimeout:function(t,i,a){r.resetLoader(e,d),u(new Hr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+c.timeout+"ms"),networkDetails:a,stats:t}))},onProgress:function(r,i,a,n){t&&t({frag:e,part:null,payload:a,networkDetails:n})}})}))},t.loadPart=function(e,t,r){var a=this;this.abort();var n=this.config,s=n.fLoader,o=n.loader;return new Promise((function(l,u){if(a.loader&&a.loader.destroy(),e.gap||t.gap)u(Gr(e,t));else{var d=a.loader=e.loader=s?new s(n):new o(n),h=Ur(e,t),f=Gt(n.fragLoadPolicy.default),c={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Nr};t.stats=d.stats,d.load(h,c,{onSuccess:function(i,n,s,o){a.resetLoader(e,d),a.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:i.data,networkDetails:o};r(u),l(u)},onError:function(r,n,s,o){a.resetLoader(e,d),u(new Hr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:i({url:h.url,data:void 0},r),error:new Error("HTTP Error "+r.code+" "+r.text),networkDetails:s,stats:o}))},onAbort:function(r,i,n){e.stats.aborted=t.stats.aborted,a.resetLoader(e,d),u(new Hr({type:T.NETWORK_ERROR,details:S.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:r}))},onTimeout:function(r,i,n){a.resetLoader(e,d),u(new Hr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+c.timeout+"ms"),networkDetails:n,stats:r}))}})}}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,a=i.total;if(r.loaded+=i.loaded,a){var n=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/a),n),o=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Ur(e,t){void 0===t&&(t=null);var r=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,n=r.byteRangeEndOffset;if(m(a)&&m(n)){var s,o=a,l=n;if("initSegment"===e.sn&&"AES-128"===(null==(s=e.decryptdata)?void 0:s.method)){var u=n-a;u%16&&(l=n+(16-u%16)),0!==a&&(i.resetIV=!0,o=a-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Gr(e,t){var r=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),i={type:T.MEDIA_ERROR,details:S.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Hr(i)}var Hr=function(e){function t(t){var r;return(r=e.call(this,t.error.message)||this).data=void 0,r.data=t,r}return l(t,e),t}(f(Error)),Vr=function(){function e(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}var t=e.prototype;return t.abort=function(e){for(var t in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},t.detach=function(){for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}},t.destroy=function(){for(var e in this.detach(),this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}},t.createKeyLoadError=function(e,t,r,i,a){return void 0===t&&(t=S.KEY_LOAD_ERROR),new Hr({type:T.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:a,error:r,networkDetails:i})},t.loadClear=function(e,t){var r=this;if(this.emeController&&this.config.emeEnabled)for(var i=e.sn,a=e.cc,n=function(){var e=t[s];if(a<=e.cc&&("initSegment"===i||"initSegment"===e.sn||i1&&this.tickImmediate(),this._tickCallCount=0)},t.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},t.doTick=function(){},e}(),jr=function(e,t,r,i,a,n){void 0===i&&(i=0),void 0===a&&(a=-1),void 0===n&&(n=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=a,this.partial=n};function Wr(e,t){for(var r=0,i=e.length;rr.startCC||e&&e.cc>>8^255&m^99,e[c]=m,t[m]=c;var p=f[c],y=f[p],E=f[y],T=257*f[m]^16843008*m;i[c]=T<<24|T>>>8,a[c]=T<<16|T>>>16,n[c]=T<<8|T>>>24,s[c]=T,T=16843009*E^65537*y^257*p^16843008*c,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,d[m]=T<<8|T>>>24,h[m]=T,c?(c=p^f[f[f[E^p]]],v^=f[f[v]]):c=v=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;is.end){var d=n>u;(n0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(a),n.key.buffer,n.iv.buffer).catch((function(t){throw i.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((function(a){var n=self.performance.now();return i.trigger(E.FRAG_DECRYPTED,{frag:e,payload:a,stats:{tstart:s,tdecrypt:n}}),t.payload=a,r.completeInitSegmentLoad(t)}))}return r.completeInitSegmentLoad(t)})).catch((function(t){r.state!==ei&&r.state!==li&&(r.warn(t),r.resetFragmentLoading(e))}))},r.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state=ti,e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},r.fragBufferedComplete=function(e,t){var r,i,a,n,s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+(this.playlistType===nt?"level":"track")+" "+e.level+" (frag:["+(null!=(r=e.startPTS)?r:NaN).toFixed(3)+"-"+(null!=(i=e.endPTS)?i:NaN).toFixed(3)+"] > buffer:"+(s?Zr(or.getBuffered(s)):"(detached)")+")"),"initSegment"!==e.sn){var o;if(e.type!==ot){var l=e.elementaryStreams;if(!Object.keys(l).some((function(e){return!!l[e]})))return void(this.state=ti)}var u=null==(o=this.levels)?void 0:o[e.level];null!=u&&u.fragmentError&&(this.log("Resetting level fragment error count of "+u.fragmentError+" on frag buffered"),u.fragmentError=0)}this.state=ti,s&&(!this.loadedmetadata&&e.type==nt&&s.buffered.length&&(null==(a=this.fragCurrent)?void 0:a.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},r.seekToStartPos=function(){},r._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,a=e.partsLoaded,n=!a||0===a.length||a.some((function(e){return!e})),s=new jr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(s)}},r._handleFragmentLoadProgress=function(e){},r._doFragLoad=function(e,t,r,i){var a,n=this;void 0===r&&(r=null);var s=null==t?void 0:t.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level"+(s?"":" detail")+"s");var o=null;if(!e.encrypted||null!=(a=e.decryptdata)&&a.key?!e.encrypted&&s.encryptedFragments.length&&this.keyLoader.loadClear(e,s.encryptedFragments):(this.log("Loading key for "+e.sn+" of ["+s.startSN+"-"+s.endSN+"], "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+e.level),this.state=ri,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(E.KEY_LOADED,e),n.state===ri&&(n.state=ti),e})),this.hls.trigger(E.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(e.start,r||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){var l=s.partList;if(l&&i){r>e.end&&s.fragmentHint&&(e=s.fragmentHint);var u=this.getNextPart(l,e,r);if(u>-1){var d,h=l[u];return this.log("Loading part sn: "+e.sn+" p: "+h.index+" cc: "+e.cc+" of playlist ["+s.startSN+"-"+s.endSN+"] parts [0-"+u+"-"+(l.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=h.start+h.duration,this.state=ii,d=o?o.then((function(r){return!r||n.fragContextChanged(r.frag)?null:n.doFragPartsLoad(e,h,t,i)})).catch((function(e){return n.handleFragLoadError(e)})):this.doFragPartsLoad(e,h,t,i).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:h,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(l,r))return Promise.resolve(null)}}this.log("Loading fragment "+e.sn+" cc: "+e.cc+" "+(s?"of ["+s.startSN+"-"+s.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),m(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=ii;var f,c=this.config.progressive;return f=c&&o?o.then((function(t){return!t||n.fragContextChanged(null==t?void 0:t.frag)?null:n.fragmentLoader.load(e,i)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,c?i:void 0),o]).then((function(e){var t=e[0];return!c&&t&&i&&i(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):f},r.doFragPartsLoad=function(e,t,r,i){var a=this;return new Promise((function(n,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList;!function t(o){a.fragmentLoader.loadPart(e,o,i).then((function(i){l[o.index]=i;var s=i.part;a.hls.trigger(E.FRAG_LOADED,i);var d=Ft(r,e.sn,o.index+1)||Ot(u,e.sn,o.index+1);if(!d)return n({frag:e,part:s,partsLoaded:l});t(d)})).catch(s)}(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===S.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===ni){var r=t.frag,i=t.part,a=t.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,a,e.partial)}else this.fragCurrent||this.state===ei||this.state===li||(this.state=ti)},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,a=e.sn,n=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+a+" of level "+i+". The current chunk will not be buffered."),null;var s=t[i],o=n>-1?Ft(s,a,n):null,l=o?o.fragment:function(e,t,r){if(null==e||!e.details)return null;var i=e.details,a=i.fragments[t-i.startSN];return a||((a=i.fragmentHint)&&a.sn===t?a:tn&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r=this.getLoadPosition();return m(r)?this.getFwdBufferInfoAtPos(e,r,t):null},r.getFwdBufferInfoAtPos=function(e,t,r){var i=this.config.maxBufferHole,a=or.bufferInfo(e,t,i);if(0===a.len&&void 0!==a.nextStart){var n=this.fragmentTracker.getBufferedFrag(t,r);if(n&&a.nextStart=r&&(t.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},r.getAppendedFrag=function(e,t){var r=this.fragmentTracker.getAppendedFrag(e,nt);return r&&"fragment"in r?r.fragment:r},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var a,n=this.config,s=r[0].start;if(t.live){var o=n.initialLiveManifestSize;if(it},r.getNextFragmentLoopLoading=function(e,t,r,i,a){var n=e.gap,s=this.getNextFragment(this.nextLoadPosition,t);if(null===s)return s;if(e=s,n&&e&&!e.gap&&r.nextStart){var o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i);if(null!==o&&r.len+o.len>=a)return this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+e.sn),null}return e},r.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},r.getNextPart=function(e,t,r){for(var i=-1,a=!1,n=!0,s=0,o=e.length;s-1&&rr.start&&r.loaded},r.getInitialLiveFragment=function(e,t){var r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!m(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=e.startSN&&a<=e.endSN){var n=t[a-e.startSN];r.cc===n.cc&&(i=n,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(e,t){return Vt(e,(function(e){return e.cct?-1:0}))}(t,r.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,a=this.config,n=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=a.maxFragLookUpTolerance,d=r.partList,h=!!(a.lowLatencyMode&&null!=d&&d.length&&l);if(h&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),i=et-u?0:u):s[s.length-1]){var f=i.sn-r.startSN,c=this.fragmentTracker.getState(i);if((c===Pr||c===Ir&&i.gap)&&(n=i),n&&i.sn===n.sn&&(!h||d[0].fragment.sn>i.sn)&&n&&i.level===n.level){var v=s[f+1];i=i.sn=n-t.maxFragLookUpTolerance&&a<=s;if(null!==i&&r.duration>i&&(a"+e.startSN+" prev-sn: "+(o?o.sn:"na")+" fragments: "+i),l}return a},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;if(r "+(null==(a=this.fragCurrent)?void 0:a.url))}else{var n=t.details===S.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);var s=t.errorAction,o=s||{},l=o.action,u=o.retryCount,d=void 0===u?0:u,h=o.retryConfig;if(s&&l===Xt&&h){this.resetStartWhenNotLoaded(this.levelLastLoaded);var f=Ut(h,d);this.warn("Fragment "+i.sn+" of "+e+" "+i.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+h.maxNumRetry+" in "+f+"ms"),s.resolved=!0,this.retryDate=self.performance.now()+f,this.state=ai}else if(h&&s){if(this.resetFragmentErrors(e),!(d.5;i&&this.reduceMaxBufferLength(r.len);var a=!i;return a&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+t+" buffer"),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),a}return!1},r.resetFragmentErrors=function(e){e===st&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ei&&(this.state=ti)},r.afterBufferFlushed=function(e,t,r){if(e){var i=or.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===oi&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=ti},r.resetStartWhenNotLoaded=function(e){if(!this.loadedmetadata){this.startFragRequested=!1;var t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(e){this.warn("The loading context changed while buffering fragment "+e.sn+" of level "+e.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var a,n=this,s=r.details;if(s){if(!Object.keys(e.elementaryStreams).reduce((function(t,a){var o=e.elementaryStreams[a];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment "+e.sn+" "+a+" duration reliably ("+l+")"),t||!1;var u=i?0:Ct(s,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return n.hls.trigger(E.LEVEL_PTS_UPDATED,{details:s,level:r,drift:u,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&null===(null==(a=this.transmuxer)?void 0:a.error)){var o=new Error("Found no media in fragment "+e.sn+" of level "+e.level+" resetting transmuxer to fallback to playlist timing");if(0===r.fragmentError&&(r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(o.message),this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+' of level "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=si,this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},r.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},s(t,[{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}]),t}(Kr);function hi(){return self.SourceBuffer||self.WebKitSourceBuffer}function fi(){if(!Ce())return!1;var e=hi();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function ci(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var vi=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,r){},t.demux=function(e,t){this.cachedData&&(e=be(this.cachedData,e),this.cachedData=null);var r,i=Y(e,0),a=i?i.length:0,n=this._audioTrack,s=this._id3Track,o=i?X(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&m(o))&&(this.basePTS=gi(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ct,duration:Number.POSITIVE_INFINITY});a>>5}function Ei(e,t){return t+1=e.length)return!1;var i=yi(e,t);if(i<=r)return!1;var a=t+i;return a===e.length||Ei(e,a)}return!1}function Si(e,t,r,i,a){if(!e.samplerate){var n=function(e,t,r,i){var a,n,s,o,l=navigator.userAgent.toLowerCase(),u=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];a=1+((192&t[r+2])>>>6);var h=(60&t[r+2])>>>2;if(!(h>d.length-1))return s=(1&t[r+2])<<2,s|=(192&t[r+3])>>>6,k.log("manifest codec:"+i+", ADTS type:"+a+", samplingIndex:"+h),/firefox/i.test(l)?h>=6?(a=5,o=new Array(4),n=h-3):(a=2,o=new Array(2),n=h):-1!==l.indexOf("android")?(a=2,o=new Array(2),n=h):(a=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&h>=6?n=h-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(h>=6&&1===s||/vivaldi/i.test(l))||!i&&1===s)&&(a=2,o=new Array(2)),n=h)),o[0]=a<<3,o[0]|=(14&h)>>1,o[1]|=(1&h)<<7,o[1]|=s<<3,5===a&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[h],channelCount:s,codec:"mp4a.40."+a,manifestCodec:u};var f=new Error("invalid ADTS sampling index:"+h);e.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message})}(t,r,i,a);if(!n)return;e.config=n.config,e.samplerate=n.samplerate,e.channelCount=n.channelCount,e.codec=n.codec,e.manifestCodec=n.manifestCodec,k.log("parsed codec:"+e.codec+", rate:"+n.samplerate+", channels:"+n.channelCount)}}function Li(e){return 9216e4/e}function Ri(e,t,r,i,a){var n,s=i+a*Li(e.samplerate),o=function(e,t){var r=pi(e,t);if(t+r<=e.length){var i=yi(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,d=u+l,h=Math.max(0,r+d-t.length);h?(n=new Uint8Array(d-u)).set(t.subarray(r+u,t.length),0):n=t.subarray(r+u,r+d);var f={unit:n,pts:s};return h||e.samples.push(f),{sample:f,length:d,missing:h}}var c=t.length-r;return(n=new Uint8Array(c)).set(t.subarray(r,t.length),0),{sample:{unit:n,pts:s},length:c,missing:-1}}var Ai=null,bi=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Di=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ki=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],_i=[0,1,1,4];function xi(e,t,r,i,a){if(!(r+24>t.length)){var n=wi(t,r);if(n&&r+n.frameLength<=t.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+n.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function wi(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,a=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==r&&0!==a&&15!==a&&3!==n){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*bi[14*(3===r?3-i:3===i?3:4)+a-1],u=Di[3*(3===r?0:2===r?1:2)+n],d=3===o?1:2,h=ki[r][i],f=_i[i],c=8*h*f,v=Math.floor(h*l/u+s)*f;if(null===Ai){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ai=g?parseInt(g[1]):0}return!!Ai&&Ai<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:d,frameLength:v,samplesPerFrame:c}}}function Ci(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function Ii(e,t){return t+18&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=be(this.remainderData,e));var n=function(e){var t={valid:null,remainder:null},r=me(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=V(e,0,i.byteOffset-8),t.remainder=V(e,i.byteOffset-8),t}(r);this.remainderData=n.remainder,i.samples=n.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,t);return a.samples=De(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=De(e,t),{videoTrack:t,audioTrack:ci(),id3Track:i,textTrack:ci()}},t.extractID3Track=function(e,t){var r=this.id3Track;if(e.samples.length){var i=me(e.samples,["emsg"]);i&&i.forEach((function(e){var i=function(e){var t=e[0],r="",i="",a=0,n=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==de(e.subarray(u,u+1));)r+=de(e.subarray(u,u+1)),u+=1;for(r+=de(e.subarray(u,u+1)),u+=1;"\0"!==de(e.subarray(u,u+1));)i+=de(e.subarray(u,u+1)),u+=1;i+=de(e.subarray(u,u+1)),u+=1,a=fe(e,12),n=fe(e,16),o=fe(e,20),l=fe(e,24),u=28}else if(1===t){a=fe(e,u+=4);var d=fe(e,u+=4),h=fe(e,u+=4);for(u+=4,s=Math.pow(2,32)*d+h,p(s)||(s=Number.MAX_SAFE_INTEGER,k.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=fe(e,u),l=fe(e,u+=4),u+=4;"\0"!==de(e.subarray(u,u+1));)r+=de(e.subarray(u,u+1)),u+=1;for(r+=de(e.subarray(u,u+1)),u+=1;"\0"!==de(e.subarray(u,u+1));)i+=de(e.subarray(u,u+1)),u+=1;i+=de(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:a,presentationTime:s,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(Oi.test(i.schemeIdUri)){var a=m(i.presentationTime)?i.presentationTime/i.timeScale:t+i.presentationTimeDelta/i.timeScale,n=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;n<=.001&&(n=Number.POSITIVE_INFINITY);var s=i.payload;r.samples.push({data:s,len:s.byteLength,dts:a,pts:a,type:gt,duration:n})}}))}return r},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){},e}(),Ni=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,r,i){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:i,length:0}},t.getLastNalUnit=function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var a=i.units;r=a[a.length-1]}return r},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var a=r[i-1];e.pts=a.pts,e.dts=a.dts}t.samples.push(e)}e.debug.length&&k.log(e.pts+"/"+e.dts+":"+e.debug)},e}(),Bi=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),a=Math.min(4,t);if(0===a)throw new Error("no bytes available");i.set(e.subarray(r,r+a)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*a,this.bytesAvailable-=a},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&k.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){for(var t=8,r=8,i=0;i4){var c=new Bi(f).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(d=!0)}d&&null!=(h=l)&&h.frame&&!l.key&&(s.pushAccessUnit(l,e),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts,"")),l.frame=!0,l.key=d;break;case 5:n=!0,null!=(o=l)&&o.frame&&!l.key&&(s.pushAccessUnit(l,e),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts,"")),l.key=!0,l.frame=!0;break;case 6:n=!0,_e(i.data,1,r.pts,t.samples);break;case 7:var v,g;n=!0,u=!0;var m=i.data,p=new Bi(m).readSPS();if(!e.sps||e.width!==p.width||e.height!==p.height||(null==(v=e.pixelRatio)?void 0:v[0])!==p.pixelRatio[0]||(null==(g=e.pixelRatio)?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[m],e.duration=a;for(var y=m.subarray(1,4),E="avc1.",T=0;T<3;T++){var S=y[T].toString(16);S.length<2&&(S="0"+S),E+=S}e.codec=E}break;case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,l&&s.pushAccessUnit(l,e),l=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts,"");break;case 12:n=!0;break;default:n=!1,l&&(l.debug+="unknown NAL "+i.type+" ")}l&&n&&l.units.push(i)})),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)},r.parseAVCNALu=function(e,t){var r,i,a=t.byteLength,n=e.naluState||0,s=n,o=[],l=0,u=-1,d=0;for(-1===n&&(u=0,d=31&t[0],n=0,l=1);l=0){var h={data:t.subarray(u,i),type:d};o.push(h)}else{var f=this.getLastNalUnit(e.samples);f&&(s&&l<=4-s&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-s)),i>0&&(f.data=be(f.data,t.subarray(0,i)),f.state=0))}l=0&&n>=0){var c={data:t.subarray(u,a),type:d,state:n};o.push(c)}if(0===o.length){var v=this.getLastNalUnit(e.samples);v&&(v.data=be(v.data,t))}return e.naluState=n,o},t}(Ni),Gi=function(){function e(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new $r(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)},t.decryptAacSample=function(e,t,r){var i=this,a=e[t].unit;if(!(a.length<=16)){var n=a.subarray(16,a.length-a.length%16),s=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(s).then((function(n){var s=new Uint8Array(n);a.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}))}},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,a=32;a=e.length)return void i();for(var a=e[t].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,r,i,n),this.decrypter.isSync())))return}}},e}(),Hi=188,Vi=function(){function e(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.videoParser=new Ui}e.probe=function(t){var r=e.syncOffset(t);return r>0&&k.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-Hi)+1,i=0;i1&&(0===n&&s>2||o+Hi>r))return n}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ue[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,r,i,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._audioTrack=e.createTrack("audio",a),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,this._duration=a},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,a){var n;void 0===i&&(i=!1),void 0===a&&(a=!1),i||(this.sampleAes=null);var s=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,d=s.pid,h=s.pesData,f=o.pid,c=l.pid,v=o.pesData,g=l.pesData,m=null,p=this.pmtParsed,y=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=be(this.remainderData,t)).length,this.remainderData=null),L>4>1){if((x=b+5+t[b+4])===b+Hi)continue}else x=b+4;switch(_){case d:D&&(h&&(n=qi(h))&&this.videoParser.parseAVCPES(s,u,n,!1,this._duration),h={data:[],size:0}),h&&(h.data.push(t.subarray(x,b+Hi)),h.size+=b+Hi-x);break;case f:if(D){if(v&&(n=qi(v)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n)}v={data:[],size:0}}v&&(v.data.push(t.subarray(x,b+Hi)),v.size+=b+Hi-x);break;case c:D&&(g&&(n=qi(g))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(x,b+Hi)),g.size+=b+Hi-x);break;case 0:D&&(x+=t[x]+1),y=this._pmtId=ji(t,x);break;case y:D&&(x+=t[x]+1);var w=Wi(t,x,this.typeSupported,i);(d=w.videoPid)>0&&(s.pid=d,s.segmentCodec=w.segmentVideoCodec),(f=w.audioPid)>0&&(o.pid=f,o.segmentCodec=w.segmentAudioCodec),(c=w.id3Pid)>0&&(l.pid=c),null===m||p||(k.warn("MPEG-TS PMT found at "+b+" after unknown PID '"+m+"'. Backtracking to sync byte @"+R+" to parse all TS packets."),m=null,b=R-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=_}}else A++;if(A>0){var C=new Error("Found "+A+" TS packet/s that do not start with 0x47");this.observer.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message})}s.pesData=h,o.pesData=v,l.pesData=g;var I={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return a&&this.extractRemainingSamples(I),I},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,r=e.audioTrack,i=e.videoTrack,a=e.id3Track,n=e.textTrack,s=i.pesData,o=r.pesData,l=a.pesData;if(s&&(t=qi(s))?(this.videoParser.parseAVCPES(i,n,t,!0,this._duration),i.pesData=null):i.pesData=s,o&&(t=qi(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t)}r.pesData=null}else null!=o&&o.size&&k.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=qi(l))?(this.parseID3PES(a,t),a.pesData=null):a.pesData=l},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),a=this.sampleAes=new Gi(this.observer,this.config,t);return this.decrypt(i,a)},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,a=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){a.samples?t.decryptAvcSamples(a.samples,0,0,(function(){r(e)})):r(e)})):a.samples&&t.decryptAvcSamples(a.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){this._duration=0},t.parseAACPES=function(e,t){var r,i,a,n=0,s=this.aacOverFlow,o=t.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l)o=be(s.sample.unit,o);else{var d=u-l;s.sample.unit.set(o.subarray(0,l),d),e.samples.push(s.sample),n=s.missing}}for(r=n,i=o.length;r0)for(var l=t+5,u=o;u>2;){106===e[l]&&k.warn("AC-3 in M2TS support not included in build");var d=e[l+1]+2;l+=d,u-=d}break;case 194:case 135:k.warn("Unsupported EC-3 in M2TS found");break;case 36:k.warn("Unsupported HEVC in M2TS found")}t+=o+5}return a}function Yi(e){k.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function qi(e){var t,r,i,a,n,s=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=be(o[0],o[1]),o.splice(1,1);if(1===((t=o[0])[0]<<16)+(t[1]<<8)+t[2]){if((r=(t[4]<<8)+t[5])&&r>e.size-6)return null;var l=t[7];192&l&&(a=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?a-(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(k.warn(Math.round((a-n)/9e4)+"s delta between PTS and DTS, align them"),a=n):n=a);var u=(i=t[8])+9;if(e.size<=u)return null;e.size-=u;for(var d=new Uint8Array(e.size),h=0,f=o.length;hc){u-=c;continue}t=t.subarray(u),c-=u,u=0}d.set(t,s),s+=c}return r&&(r-=i+3),{data:d,pts:a,dts:n,len:r}}return null}var zi=function(e){function t(){return e.apply(this,arguments)||this}l(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,a){e.prototype.resetInitSegment.call(this,t,r,i,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:a,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=Y(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==X(t)&&function(e,t){var r=0,i=5;t+=i;for(var a=new Uint32Array(1),n=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<>l,r=r?r<1?r-1:0),a=1;a>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),n=0,t=8;n>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(Qi+1)),a=Math.floor(r%(Qi+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,n)},e.sdtp=function(t){var r,i,a=t.samples||[],n=new Uint8Array(4+a.length);for(r=0;r>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},e.esds=function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))},e.audioStsd=function(e){var t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?e.box(e.types.stsd,e.STSD,e.mp3(t)):"ac3"===t.segmentCodec?e.box(e.types.stsd,e.STSD,e.ac3(t)):e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,i=t.duration*t.timescale,a=t.width,n=t.height,s=Math.floor(i/(Qi+1)),o=Math.floor(i%(Qi+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,n>>8&255,255&n,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),a=t.id,n=Math.floor(r/(Qi+1)),s=Math.floor(r%(Qi+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,a,n,s,o,l,u=t.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,f)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t);return be(e.FTYP,r)},e}();function $i(e,t){return void 0===t&&(t=!1),function(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=e*t*r;return i?Math.round(a):a}(e,1e3,1/9e4,t)}Ji.types=void 0,Ji.HDLR_TYPES=void 0,Ji.STTS=void 0,Ji.STSC=void 0,Ji.STCO=void 0,Ji.STSZ=void 0,Ji.VMHD=void 0,Ji.SMHD=void 0,Ji.STSD=void 0,Ji.FTYP=void 0,Ji.DINF=void 0;var Zi=null,ea=null,ta=function(){function e(e,t,r,i){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===Zi){var a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Zi=a?parseInt(a[1]):0}if(null===ea){var n=navigator.userAgent.match(/Safari\/(\d+)/i);ea=n?parseInt(n[1]):0}}var t=e.prototype;return t.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},t.resetTimeStamp=function(e){k.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},t.resetNextTimestamp=function(){k.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},t.resetInitSegment=function(){k.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},t.getVideoStartPts=function(e){var t=!1,r=e.reduce((function(e,r){var i=r.pts-e;return i<-4294967296?(t=!0,ra(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&k.debug("PTS rollover detected"),r},t.remux=function(e,t,r,i,a,n,s,o){var l,u,d,h,f,c,v=a,g=a,m=e.pid>-1,p=t.pid>-1,y=t.samples.length,E=e.samples.length>0,T=s&&y>0||y>1;if((!m||E)&&(!p||T)||this.ISGenerated||s){if(this.ISGenerated){var S,L,R,A,b=this.videoTrackConfig;!b||t.width===b.width&&t.height===b.height&&(null==(S=t.pixelRatio)?void 0:S[0])===(null==(L=b.pixelRatio)?void 0:L[0])&&(null==(R=t.pixelRatio)?void 0:R[1])===(null==(A=b.pixelRatio)?void 0:A[1])||this.resetInitSegment()}else d=this.generateIS(e,t,a,n);var D,_=this.isVideoContiguous,x=-1;if(T&&(x=function(e){for(var t=0;t0){k.warn("[mp4-remuxer]: Dropped "+x+" out of "+y+" video samples due to a missing keyframe");var w=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(x),t.dropped+=x,D=g+=(t.samples[0].pts-w)/t.inputTimeScale}else-1===x&&(k.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),c=!1);if(this.ISGenerated){if(E&&T){var C=this.getVideoStartPts(t.samples),I=(ra(e.samples[0].pts,C)-C)/t.inputTimeScale;v+=Math.max(0,I),g+=Math.max(0,-I)}if(E){if(e.samplerate||(k.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,a,n)),u=this.remuxAudio(e,v,this.isAudioContiguous,n,p||T||o===st?g:void 0),T){var P=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(k.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,a,n)),l=this.remuxVideo(t,g,_,P)}}else T&&(l=this.remuxVideo(t,g,_,0));l&&(l.firstKeyFrame=x,l.independent=-1!==x,l.firstKeyFramePTS=D)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=ia(r,a,this._initPTS,this._initDTS)),i.samples.length&&(h=aa(i,a,this._initPTS))),{audio:u,video:l,initSegment:d,independent:c,text:h,id3:f}},t.generateIS=function(e,t,r,i){var a,n,s,o=e.samples,l=t.samples,u=this.typeSupported,d={},h=this._initPTS,f=!h||i,c="audio/mp4";if(f&&(a=n=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(c="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}d.audio={id:"audio",container:c,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Ji.initSegment([e]),metadata:{channelCount:e.channelCount}},f&&(s=e.inputTimeScale,h&&s===h.timescale?f=!1:a=n=o[0].pts-Math.round(s*r))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ji.initSegment([t]),metadata:{width:t.width,height:t.height}},f)if(s=t.inputTimeScale,h&&s===h.timescale)f=!1;else{var v=this.getVideoStartPts(l),g=Math.round(s*r);n=Math.min(n,ra(l[0].dts,v)-g),a=Math.min(a,v-g)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,f?(this._initPTS={baseTime:a,timescale:s},this._initDTS={baseTime:n,timescale:s}):a=s=void 0,{tracks:d,initPTS:a,timescale:s}},t.remuxVideo=function(e,t,r,i){var a,n,s=e.inputTimeScale,l=e.samples,u=[],d=l.length,h=this._initPTS,f=this.nextAvcDts,c=8,v=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!r||null===f){var y=t*s,L=l[0].pts-ra(l[0].dts,l[0].pts);Zi&&null!==f&&Math.abs(y-L-f)<15e3?r=!0:f=y-L}for(var R=h.baseTime*s/h.timescale,A=0;A0?A-1:A].dts&&(p=!0)}p&&l.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),a=l[0].dts;var D=(n=l[l.length-1].dts)-a,_=D?Math.round(D/(d-1)):v||e.inputTimeScale/30;if(r){var x=a-f,w=x>_,C=x<-1;if((w||C)&&(w?k.warn("AVC: "+$i(x,!0)+" ms ("+x+"dts) hole between fragments detected at "+t.toFixed(3)):k.warn("AVC: "+$i(-x,!0)+" ms ("+x+"dts) overlapping between fragments detected at "+t.toFixed(3)),!C||f>=l[0].pts||Zi)){a=f;var I=l[0].pts-x;if(w)l[0].dts=a,l[0].pts=I;else for(var P=0;PI);P++)l[P].dts-=x,l[P].pts-=x;k.log("Video: Initial PTS/DTS adjusted: "+$i(I,!0)+"/"+$i(a,!0)+", delta: "+$i(x,!0)+" ms")}}for(var F=0,O=0,M=a=Math.max(0,a),N=0;N0?$.dts-l[J-1].dts:_;if(se=J>0?$.pts-l[J-1].pts:_,oe.stretchShortVideoTrack&&null!==this.nextAudioPts){var ue=Math.floor(oe.maxBufferHole*s),de=(i?g+i*s:this.nextAudioPts)-$.pts;de>ue?((v=de-le)<0?v=le:Y=!0,k.log("[mp4-remuxer]: It is approximately "+de/90+" ms to the next segment; using duration "+v/90+" ms for the last video frame.")):v=le}else v=le}var he=Math.round($.pts-$.dts);q=Math.min(q,v),X=Math.max(X,v),z=Math.min(z,se),Q=Math.max(Q,se),u.push(new na($.key,v,ee,he))}if(u.length)if(Zi){if(Zi<70){var fe=u[0].flags;fe.dependsOn=2,fe.isNonSync=0}}else if(ea&&Q-z0&&(i&&Math.abs(p-m)<9e3||Math.abs(ra(v[0].pts-y,p)-m)<20*u),v.forEach((function(e){e.pts=ra(e.pts-y,p)})),!r||m<0){if(v=v.filter((function(e){return e.pts>=0})),!v.length)return;m=0===a?0:i&&!c?Math.max(0,p):v[0].pts}if("aac"===e.segmentCodec)for(var L=this.config.maxAudioFramesDrift,R=0,A=m;R=L*u&&x<1e4&&c){var w=Math.round(_/u);(A=D-w*u)<0&&(w--,A+=u),0===R&&(this.nextAudioPts=m=A),k.warn("[mp4-remuxer]: Injecting "+w+" audio frame @ "+(A/n).toFixed(3)+"s due to "+Math.round(1e3*_/n)+" ms gap.");for(var C=0;C0))return;N+=g;try{F=new Uint8Array(N)}catch(e){return void this.observer.emit(E.ERROR,E.ERROR,{type:T.MUX_ERROR,details:S.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:N,reason:"fail allocating audio mdat "+N})}h||(new DataView(F.buffer).setUint32(0,N),F.set(Ji.types.mdat,4))}F.set(V,g);var j=V.byteLength;g+=j,f.push(new na(!0,l,j,0)),M=K}var W=f.length;if(W){var Y=f[f.length-1];this.nextAudioPts=m=M+s*Y.duration;var q=h?new Uint8Array(0):Ji.moof(e.sequenceNumber++,O/s,o({},e,{samples:f}));e.samples=[];var z=O/n,X=m/n,Q={data1:q,data2:F,startPTS:z,endPTS:X,startDTS:z,endDTS:X,type:"audio",hasAudio:!0,hasVideo:!1,nb:W};return this.isAudioContiguous=!0,Q}},t.remuxEmptyAudio=function(e,t,r,i){var a=e.inputTimeScale,n=a/(e.samplerate?e.samplerate:a),s=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,u=(null!==s?s:i.startDTS*a)+l,d=i.endDTS*a+l,h=1024*n,f=Math.ceil((d-u)/h),c=Xi.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(k.warn("[mp4-remuxer]: remux empty Audio"),c){for(var v=[],g=0;g4294967296;)e+=r;return e}function ia(e,t,r,i){var a=e.samples.length;if(a){for(var n=e.inputTimeScale,s=0;sa}(l,p,a,v)||f.timescale!==l.timescale&&n)&&(f.initPTS=p-a,l&&1===l.timescale&&k.warn("Adjusting initPTS by "+(f.initPTS-l.baseTime)),this.initPTS=l={baseTime:f.initPTS,timescale:1});var y=e?p-l.baseTime/l.timescale:u,E=y+v;!function(e,t,r){me(t,["moof","traf"]).forEach((function(t){me(t,["tfhd"]).forEach((function(i){var a=fe(i,4),n=e[a];if(n){var s=n.timescale||9e4;me(t,["tfdt"]).forEach((function(e){var t=e[0],i=r*s;if(i){var a=fe(e,4);if(0===t)a-=i,ge(e,4,a=Math.max(a,0));else{a*=Math.pow(2,32),a+=fe(e,8),a-=i,a=Math.max(a,0);var n=Math.floor(a/(oe+1)),o=Math.floor(a%(oe+1));ge(e,4,n),ge(e,8,o)}}}))}}))}))}(c,h,l.baseTime/l.timescale),v>0?this.lastEndTime=E:(k.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var T=!!c.audio,S=!!c.video,L="";T&&(L+="audio"),S&&(L+="video");var R={data1:h,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return d.audio="audio"===R.type?R:void 0,d.video="audio"!==R.type?R:void 0,d.initSegment=f,d.id3=ia(r,a,l,l),i.samples.length&&(d.text=aa(i,a,l)),d},e}();function oa(e,t){var r=null==e?void 0:e.codec;if(r&&r.length>4)return r;if(t===F){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r)return Ge(r,!1);var i="mp4a.40.5";return k.info('Parsed audio codec "'+r+'" or audio object type not handled. Using "'+i+'"'),i}return k.warn('Unhandled video codec "'+r+'"'),"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1.42e01e"}var la,ua="undefined"!=typeof self?self:void 0;try{la=self.performance.now.bind(self.performance)}catch(e){k.debug("Unable to use Performance API on this environment"),la=null==ua?void 0:ua.Date.now}var da=[{demux:Mi,remux:sa},{demux:Vi,remux:ta},{demux:Fi,remux:ta},{demux:zi,remux:ta}],ha=function(){function e(e,t,r,i,a){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i,this.id=a}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,i){var a=this,n=r.transmuxing;n.executeStart=la();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,d=u.contiguous,h=u.discontinuity,f=u.trackSwitch,c=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,L=l.duration,R=l.initSegmentData,A=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(s,t);if(A&&"AES-128"===A.method){var b=this.getDecrypter();if(!b.isSync())return this.decryptionPromise=b.webCryptoDecrypt(s,A.key.buffer,A.iv.buffer).then((function(e){var t=a.push(e,null,r);return a.decryptionPromise=null,t})),this.decryptionPromise;var D=b.softwareDecrypt(s,A.key.buffer,A.iv.buffer);if(r.part>-1&&(D=b.flush()),!D)return n.executeEnd=la(),fa(r);s=new Uint8Array(D)}var _=this.needsProbing(h,f);if(_){var x=this.configureTransmuxer(s);if(x)return k.warn("[transmuxer] "+x.message),this.observer.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),n.executeEnd=la(),fa(r)}(h||f||g||_)&&this.resetInitSegment(R,m,p,L,t),(h||g||_)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var w=this.transmux(s,A,v,c,r),C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,n.executeEnd=la(),w},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=la();var i=this.decrypter,a=this.currentTransmuxState,n=this.decryptionPromise;if(n)return n.then((function(){return t.flush(e)}));var s=[],o=a.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l,null,e))}var u=this.demuxer,d=this.remuxer;if(!u||!d)return r.executeEnd=la(),[fa(e)];var h=u.flush(o);return ca(h)?h.then((function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),s)},t.flushRemux=function(e,t,r){var i=t.audioTrack,a=t.videoTrack,n=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;k.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var d=this.remuxer.remux(i,a,n,s,u,l,!0,this.id);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=la()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,a){var n=this.demuxer,s=this.remuxer;n&&s&&(n.resetInitSegment(e,t,r,i),s.resetInitSegment(e,t,r,a))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,r,i,a){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,a):this.transmuxUnencrypted(e,r,i,a)},t.transmuxUnencrypted=function(e,t,r,i){var a=this.demuxer.demux(e,t,!1,!this.config.progressive),n=a.audioTrack,s=a.videoTrack,o=a.id3Track,l=a.textTrack;return{remuxResult:this.remuxer.remux(n,s,o,l,t,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,a){var n=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,n.id),chunkMeta:a}}))},t.configureTransmuxer=function(e){for(var t,r=this.config,i=this.observer,a=this.typeSupported,n=this.vendor,s=0,o=da.length;s1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!y&&(1===E||0===E&&(1===T||S&&T<=0)),R=self.performance.now();(y||E||0===a.stats.parsing.start)&&(a.stats.parsing.start=R),!n||!T&&L||(n.stats.parsing.start=R);var A=!(m&&(null==(d=a.initSegment)?void 0:d.url)===(null==(h=m.initSegment)?void 0:h.url)),b=new ga(p,L,o,y,v,A);if(!L||p||A){k.log("[transmuxer-interface, "+a.type+"]: Starting new transmux session for sn: "+l.sn+" p: "+l.part+" level: "+l.level+" id: "+l.id+"\n discontinuity: "+p+"\n trackSwitch: "+y+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+v+"\n initSegmentChange: "+A);var D=new va(r,i,t,s,u);this.configureTransmuxer(D)}if(this.frag=a,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:b},e instanceof ArrayBuffer?[e]:[]);else if(c){var _=c.push(e,g,l,b);ca(_)?(c.async=!0,_.then((function(e){f.handleTransmuxComplete(e)})).catch((function(e){f.transmuxerError(e,l,"transmuxer-interface push error")}))):(c.async=!1,this.handleTransmuxComplete(_))}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(r){var i=r.flush(e);ca(i)||r.async?(ca(i)||(i=Promise.resolve(i)),i.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}))):this.handleFlushResult(i,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":var i,a=null==(i=this.workerContext)?void 0:i.objectURL;a&&self.URL.revokeObjectURL(a);break;case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":k[t.data.logType]&&k[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}},r.configureTransmuxer=function(e){var t=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},t}(),La=function(){function e(e,t,r,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i}var t=e.prototype;return t.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},t.poll=function(e,t){var r=this.config,i=this.media,a=this.stalled;if(null!==i){var n=i.currentTime,s=i.seeking,o=this.seeking&&!s,l=!this.seeking&&s;if(this.seeking=s,n===e)if(l||o)this.stalled=null;else if(i.paused&&!s||i.ended||0===i.playbackRate||!or.getBuffered(i).length)this.nudgeRetry=0;else{var u=or.bufferInfo(i,n,0),d=u.nextStart||0;if(s){var h=u.len>2,f=!d||t&&t.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(h||f)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(u.len>0||d))return;var v=Math.max(d,u.start||0)-n,g=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==g||null==(c=g.details)?void 0:c.live)?2*g.details.targetduration:2,p=this.fragmentTracker.getPartialFragment(n);if(v>0&&(v<=m||p))return void(i.paused||this._trySkipBufferHole(p))}var y=self.performance.now();if(null!==a){var E=y-a;if(s||!(E>=250)||(this._reportStall(u),this.media)){var T=or.bufferInfo(i,n,r.maxBufferHole);this._tryFixBufferStall(T,E)}}else this.stalled=y}else if(this.moved=!0,s||(this.nudgeRetry=0),null!==a){if(this.stallReported){var S=self.performance.now()-a;k.warn("playback not stuck anymore @"+n+", after "+Math.round(S)+"ms"),this.stallReported=!1}this.stalled=null}}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,a=this.media;if(null!==a){var n=a.currentTime,s=i.getPartialFragment(n);if(s&&(this._trySkipBufferHole(s)||!this.media))return;(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-n1e3*r.highBufferWatchdogPeriod&&(k.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},t._reportStall=function(e){var t=this.hls,r=this.media;if(!this.stallReported&&r){this.stallReported=!0;var i=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(e)+")");k.warn(i.message),t.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len})}},t._trySkipBufferHole=function(e){var t=this.config,r=this.hls,i=this.media;if(null===i)return 0;var a=i.currentTime,n=or.bufferInfo(i,a,0),s=a0&&n.len<1&&i.readyState<3,u=s-a;if(u>0&&(o||l)){if(u>t.maxBufferHole){var d=this.fragmentTracker,h=!1;if(0===a){var f=d.getAppendedFrag(0,nt);f&&s1?(i=0,this.bitrateTest=!0):i=r.firstAutoLevel),r.nextLoadLevel=i,this.level=r.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=ti,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=ei},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case ui:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(i))break;this.state=ti;break}if(this.hls.nextLoadLevel!==this.level){this.state=ti;break}break;case ai:var a,n=self.performance.now(),s=this.retryDate;if(!s||n>=s||null!=(a=this.media)&&a.seeking){var o=this.levels,l=this.level,u=null==o?void 0:o[l];this.resetStartWhenNotLoaded(u||null),this.state=ti}}this.state===ti&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){e.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var a=e.nextLoadLevel;if(null!=r&&r[a]){var n=r[a],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={};return this.altAudio&&(l.type="video"),this.hls.trigger(E.BUFFER_EOS,l),void(this.state=oi)}e.loadLevel!==a&&-1===e.manualLevel&&this.log("Adapting to level "+a+" from level "+this.level),this.level=e.nextLoadLevel=a;var u=n.details;if(!u||this.state===ui||u.live&&this.levelLastLoaded!==n)return this.level=a,void(this.state=ui);var d=s.len,h=this.getMaxBufferLength(n.maxBitrate);if(!(d>=h)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);var f=this.backtrackFragment?this.backtrackFragment.start:s.end,c=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&c&&"initSegment"!==c.sn&&this.fragmentTracker.getState(c)!==Pr){var v,g=(null!=(v=this.backtrackFragment)?v:c).sn-u.startSN,m=u.fragments[g-1];m&&c.cc===m.cc&&(c=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,f)){if(!c.gap){var p=this.audioOnly&&!this.altAudio?F:O,y=(p===O?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,nt)}c=this.getNextFragmentLoopLoading(c,u,s,nt,h)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,f))}}}}},r.loadFragment=function(t,r,i){var a=this.fragmentTracker.getState(t);this.fragCurrent=t,a===wr||a===Ir?"initSegment"===t.sn?this._loadInitSegment(t,r):this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,r)):(this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,i)):this.clearTrackerIfNeeded(t)},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,nt)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var a=this.getLevelDetails();if(null!=a&&a.live){var n=this.getMainFwdBufferInfo();if(!n||n.len<2*a.targetduration)return}if(!t.paused&&e){var s=e[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var d=u.maxStartPTS?u.maxStartPTS:u.start,h=u.duration,f=Math.max(l.end,d+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(f,Number.POSITIVE_INFINITY)}}}},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ri:case ii:case ai:case ni:case si:this.state=ti}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.altAudio?"video":null)},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new La(this.config,i,this.fragmentTracker,this.hls)},r.onMediaDetaching=function(){var t=this.media;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),e.prototype.onMediaDetaching.call(this)},r.onMediaPlaying=function(){this.tick()},r.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:null;m(t)&&this.log("Media seeked to "+t.toFixed(3));var r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn('Main forward buffer length on "seeked" event '+(r?r.len:"empty")+")")},r.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1},r.onManifestParsed=function(e,t){var r,i,a=!1,n=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(a=a||-1!==t.indexOf("mp4a.40.2"),n=n||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=a&&n&&!("function"==typeof(null==(i=hi())||null==(r=i.prototype)?void 0:r.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},r.onLevelLoading=function(e,t){var r=this.levels;if(r&&this.state===ti){var i=r[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=ui)}},r.onLevelLoaded=function(e,t){var r,i=this.levels,a=t.level,n=t.details,s=n.totalduration;if(i){this.log("Level "+a+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+", cc ["+n.startCC+", "+n.endCC+"] duration:"+s);var o=i[a],l=this.fragCurrent;!l||this.state!==ii&&this.state!==ai||l.level!==t.level&&l.loader&&this.abortCurrentFrag();var u=0;if(n.live||null!=(r=o.details)&&r.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;u=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(E.LEVEL_UPDATED,{details:n,level:a}),this.state===ui){if(this.waitForCdnTuneIn(n))return;this.state=ti}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,u),this.tick()}else this.warn("Levels were reset while loading level "+a)},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,a=e.payload,n=this.levels;if(n){var s=n[r.level],o=s.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,d=null==(t=r.initSegment)?void 0:t.data,h=this._getAudioCodec(s),f=this.transmuxer=this.transmuxer||new Sa(this.hls,nt,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=i?i.index:-1,v=-1!==c,g=new jr(r.level,r.sn,r.stats.chunkCount,a.byteLength,c,v),m=this.initPTS[r.cc];f.push(a,d,h,l,r,i,o.totalduration,u,g,m)}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(e,t){var r=this.altAudio;if(!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i&&(this.log("Switching to main audio track, cancel main fragment load"),i.abortRequests(),this.fragmentTracker.removeFragment(i)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var a=this.hls;r&&(a.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),a.trigger(E.AUDIO_TRACK_SWITCHED,t)}},r.onAudioTrackSwitched=function(e,t){var r=t.id,i=!!this.hls.audioTracks[r].url;if(i){var a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()},r.onBufferCreated=function(e,t){var r,i,a=t.tracks,n=!1;for(var s in a){var o=a[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=a[s];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(!r||r.type===nt){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===si&&(this.state=ti));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},r.onError=function(e,t){var r;if(t.fatal)this.state=li;else switch(t.details){case S.FRAG_GAP:case S.FRAG_PARSING_ERROR:case S.FRAG_DECRYPT_ERROR:case S.FRAG_LOAD_ERROR:case S.FRAG_LOAD_TIMEOUT:case S.KEY_LOAD_ERROR:case S.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(nt,t);break;case S.LEVEL_LOAD_ERROR:case S.LEVEL_LOAD_TIMEOUT:case S.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==ui||(null==(r=t.context)?void 0:r.type)!==rt||(this.state=ti);break;case S.BUFFER_APPEND_ERROR:case S.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===S.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case S.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},r.checkBuffer=function(){var e=this.media,t=this.gapController;if(e&&t&&e.readyState){if(this.loadedmetadata||!or.getBuffered(e).length){var r=this.state!==ti?this.fragCurrent:null;t.poll(this.lastCurrentTime,r)}this.lastCurrentTime=e.currentTime}},r.onFragLoadEmergencyAborted=function(){this.state=ti,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==F||this.audioOnly&&!this.altAudio){var i=(r===O?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,nt),this.tick()}},r.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t0&&(aS.cc;if(!1!==a.independent){var A=d.startPTS,b=d.endPTS,D=d.startDTS,k=d.endDTS;if(l)l.elementaryStreams[d.type]={startPTS:A,endPTS:b,startDTS:D,endDTS:k};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!R&&(this.couldBacktrack=!0),d.dropped&&d.independent){var _=this.getMainFwdBufferInfo(),x=(_?_.end:this.getLoadPosition())+this.config.maxBufferHole,w=d.firstKeyFramePTS?d.firstKeyFramePTS:A;if(!L&&x2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,A,b,D,k),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,L||R)}else{if(!L&&!R)return void this.backtrack(o);o.gap=!0}}if(g){var C=g.startPTS,I=g.endPTS,P=g.startDTS,O=g.endDTS;l&&(l.elementaryStreams[F]={startPTS:C,endPTS:I,startDTS:P,endDTS:O}),o.setElementaryStreamInfo(F,C,I,P,O),this.bufferFragmentData(g,o,l,n)}if(v&&null!=f&&null!=(t=f.samples)&&t.length){var M={id:r,frag:o,details:v,samples:f.samples};i.trigger(E.FRAG_PARSING_METADATA,M)}if(v&&h){var N={id:r,frag:o,details:v,samples:h.samples};i.trigger(E.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(n)},r._bufferInitSegment=function(e,t,r,i){var a=this;if(this.state===ni){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;var n=t.audio,s=t.video,o=t.audiovideo;if(n){var l=e.audioCodec,u=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==n.metadata.channelCount&&-1===u.indexOf("firefox")&&(l="mp4a.40.5")),l&&-1!==l.indexOf("mp4a.40.5")&&-1!==u.indexOf("android")&&"audio/mpeg"!==n.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),e.audioCodec&&e.audioCodec!==l&&this.log('Swapping manifest audio codec "'+e.audioCodec+'" for "'+l+'"'),n.levelCodec=l,n.id="main",this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+n.codec+"]")}s&&(s.levelCodec=e.videoCodec,s.id="main",this.log("Init video buffer, container:"+s.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+s.codec+"]")),o&&this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),this.hls.trigger(E.BUFFER_CODECS,t),Object.keys(t).forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&a.hls.trigger(E.BUFFER_APPENDING,{type:e,data:n,frag:r,part:null,chunkMeta:i,parent:r.type})})),this.tickImmediate()}},r.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,nt)},r.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=ti},r.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(or.isBuffered(e,r)?t=this.getAppendedFrag(r):or.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,a=t.level;i&&t.sn===i.sn&&i.level===a||(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),i&&i.level===a||this.hls.trigger(E.LEVEL_SWITCHED,{level:a}))}}},s(t,[{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}},{key:"currentProgramDateTime",get:function(){var e=this.media;if(e){var t=e.currentTime,r=this.currentFrag;if(r&&m(t)&&m(r.programDateTime)){var i=r.programDateTime+1e3*(t-r.start);return new Date(i)}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}]),t}(di),Aa=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new pa,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,D(t.debug||!1,"Hls instance");var r=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=Dr(e),a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var i=("level"===e?"playlist":e)+"LoadPolicy",n=void 0===t[i],s=[];a.forEach((function(a){var o=e+"Loading"+a,l=t[o];if(void 0!==l&&n){s.push(o);var u=r[i].default;switch(t[i]={default:u},a){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}})),s.length&&k.warn('hls.js config: "'+s.join('", "')+'" setting(s) are deprecated, use "'+i+'": '+JSON.stringify(t[i]))})),i(i({},r),t)}(e.DefaultConfig,t);this.userConfig=t,r.progressive&&kr(r);var a=r.abrController,n=r.bufferController,s=r.capLevelController,o=r.errorController,l=r.fpsController,u=new o(this),d=this.abrController=new a(this),h=this.bufferController=new n(this),f=this.capLevelController=new s(this),c=new l(this),v=new dt(this),g=new Tt(this),m=r.contentSteeringController,p=m?new m(this):null,y=this.levelController=new _r(this,p),T=new Fr(this),S=new Vr(this.config),L=this.streamController=new Ra(this,T,S);f.setStreamController(L),c.setStreamController(L);var R=[v,y,L];p&&R.splice(1,0,p),this.networkControllers=R;var A=[d,h,f,c,g,T];this.audioTrackController=this.createController(r.audioTrackController,R);var b=r.audioStreamController;b&&R.push(new b(this,T,S)),this.subtitleTrackController=this.createController(r.subtitleTrackController,R);var _=r.subtitleStreamController;_&&R.push(new _(this,T,S)),this.createController(r.timelineController,A),S.emeController=this.emeController=this.createController(r.emeController,A),this.cmcdController=this.createController(r.cmcdController,A),this.latencyController=this.createController(St,A),this.coreComponents=A,R.push(u);var x=u.onErrorOut;"function"==typeof x&&this.on(E.ERROR,x,u)}e.isMSESupported=function(){return fi()},e.isSupported=function(){return function(){if(!fi())return!1;var e=Ce();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Oe(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Oe(t,"audio"))})))}()},e.getMediaSource=function(){return Ce()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(k.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===E.ERROR;this.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){k.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){k.log("attachMedia"),this._media=e,this.trigger(E.MEDIA_ATTACHING,{media:e})},t.detachMedia=function(){k.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,void 0),this._media=null},t.loadSource=function(e){this.stopLoad();var t=this.media,r=this.url,i=this.url=g.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,k.log("loadSource:"+i),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})},t.startLoad=function(e){void 0===e&&(e=-1),k.log("startLoad("+e+")"),this.started=!0,this.networkControllers.forEach((function(t){t.startLoad(e)}))},t.stopLoad=function(){k.log("stopLoad"),this.started=!1,this.networkControllers.forEach((function(e){e.stopLoad()}))},t.resumeBuffering=function(){this.started&&this.networkControllers.forEach((function(e){"fragmentLoader"in e&&e.startLoad(-1)}))},t.pauseBuffering=function(){this.networkControllers.forEach((function(e){"fragmentLoader"in e&&e.stopLoad()}))},t.swapAudioCodec=function(){k.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){k.log("recoverMediaError");var e=this._media;this.detachMedia(),e&&this.attachMedia(e)},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)},t.setSubtitleOption=function(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null},s(e,[{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){k.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){k.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){k.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){k.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){k.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(k.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return Lt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var a=e;a--;){var n=t[a].attrs["HDCP-LEVEL"];if(n&&n<=i)return a}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}],[{key:"version",get:function(){return"1.5.7"}},{key:"Events",get:function(){return E}},{key:"ErrorTypes",get:function(){return T}},{key:"ErrorDetails",get:function(){return S}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:br},set:function(t){e.defaultConfig=t}}]),e}();return Aa.defaultConfig=void 0,Aa},"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(r="undefined"!=typeof globalThis?globalThis:r||self).Hls=i()}(!1); +//# sourceMappingURL=hls.light.min.js.map diff --git a/local-video-downloader - copia (2) - copia/extension/manifest.json b/local-video-downloader - copia (2) - copia/extension/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..39d6aa24bf7570b86f99b1b6999e01e76219d5c0 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/manifest.json @@ -0,0 +1,35 @@ +{ + "manifest_version": 3, + "name": "Local Video Downloader", + "version": "1.0", + "description": "Descarga videos directamente a tu PC usando Native Messaging.", + "permissions": [ + "nativeMessaging", + "activeTab", + "storage", + "cookies", + "webRequest", + "scripting", + "clipboardRead", + "contextMenus" + ], + "host_permissions": [ + "*://*/*" + ], + "icons": { + "16": "icons/icon.png", + "48": "icons/icon.png", + "128": "icons/icon.png" + }, + "action": { + "default_popup": "popup.html", + "default_icon": { + "16": "icons/icon.png", + "48": "icons/icon.png", + "128": "icons/icon.png" + } + }, + "background": { + "service_worker": "background.js" + } +} diff --git a/local-video-downloader - copia (2) - copia/extension/popup.css b/local-video-downloader - copia (2) - copia/extension/popup.css new file mode 100644 index 0000000000000000000000000000000000000000..0ee76a7e9daff7a5052e991746353ae3cf1d8403 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/popup.css @@ -0,0 +1,508 @@ +body { + width: 500px; + min-height: 550px; + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + margin: 0; + background-color: #1a1b1e; + color: #eeeeee; +} + +.tabs-container { + display: flex; + background-color: #1a1b1e; + border-bottom: 1px solid #2f3036; + padding: 10px 10px 0 10px; + user-select: none; +} + +.tab { + padding: 8px 12px; + font-size: 14px; + font-weight: 500; + color: #8c8d91; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; + border-radius: 6px 6px 0 0; + margin-bottom: -1px; +} + +.tab.active { + color: #ffffff; + background-color: #25262a; + border: 1px solid #2f3036; + border-bottom: 1px solid #25262a; +} + +.icon { + width: 18px; + height: 18px; +} + +.main-content { + padding: 20px; + background-color: #1a1b1e; +} + +.panel { + display: none; +} +.panel.active { + display: block; +} + +.section-title { + font-size: 16px; + font-weight: 600; + margin: 0 0 15px 0; + color: #ffffff; +} + +.flex-title { + display: flex; + justify-content: space-between; + align-items: center; +} + +.detected-video-card { + background-color: #1f2023; + border: 1px solid #2f3036; + border-radius: 8px; + padding: 15px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 15px; + margin-bottom: 20px; + box-shadow: 0 4px 6px rgba(0,0,0,0.1); +} + +.hidden { + display: none !important; +} + +.video-info { + display: flex; + flex-direction: column; + gap: 6px; + overflow: hidden; + flex: 1; +} + +.preview-title { + font-size: 14px; + font-weight: 600; + color: #ffffff; + display: -webkit-box; + -webkit-line-clamp: 2; + line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + line-height: 1.3; +} + +.preview-url { + font-size: 12px; + color: #8c8d91; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.action-btn { + background-color: #26272b; + color: #b0b1b5; + border: 1px solid #2f3036; + border-radius: 6px; + padding: 8px 16px; + font-size: 13px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; +} + +.action-btn.primary { + grid-column: 2; + grid-row: 1; + min-width: 95px; +} + +.action-btn:hover:not(:disabled) { + background-color: #313338; + color: #ffffff; +} + +.action-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + margin-top: 50px; +} + +.empty-icon { + width: 42px; + height: 42px; + color: #e5e5e5; + margin-bottom: 20px; +} + +.state-title { + font-size: 18px; + font-weight: 600; + margin: 0 0 10px 0; + color: #ffffff; +} + +.state-desc { + font-size: 14px; + color: #8c8d91; + margin: 0; + text-align: center; + line-height: 1.5; +} + +/* History List Styles */ +.downloads-list { + display: flex; + flex-direction: column; + gap: 10px; + max-height: 420px; + overflow-y: auto; + padding-right: 5px; +} + +/* Scrollbar Global Estético */ +::-webkit-scrollbar { width: 6px; height: 6px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { background: #3f4147; border-radius: 4px; } +::-webkit-scrollbar-thumb:hover { background: #55575e; } +::-webkit-scrollbar-corner { background: transparent; } + +.history-item { + background-color: #1f2023; + border: 1px solid #2f3036; + border-radius: 6px; + padding: 12px; + display: flex; + flex-direction: column; + gap: 6px; +} + +.history-title { + font-size: 13px; + color: #e5e5e5; + font-weight: 500; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.history-date { + font-size: 11px; + color: #6a6b70; + margin-bottom: 4px; +} + +.history-actions { + display: flex; + gap: 8px; +} + +.btn-small { + padding: 6px 10px; + font-size: 11px; + flex: 1; +} + +.history-url { + color: #4da6ff; + text-decoration: none; +} +.history-url:hover { text-decoration: underline; } + +.settings-card, .about-card { + background-color: #1f2023; + border: 1px solid #2f3036; + border-radius: 6px; + padding: 15px; +} +.about-card h3 { margin: 0 0 5px 0; color: #fff; } +.about-card p { margin: 0 0 10px 0; color: #8c8d91; font-size: 13px; line-height: 1.5; } +.setting-item { margin-bottom: 15px; } +.setting-item label { font-size: 13px; color: #e5e5e5; font-weight: 500; } + +.radio-switch input[type="radio"] { display: none; } +.radio-switch .radio-btn { + display: flex; + background-color: #1a1b1e; + border: 1px solid #2f3036; + border-radius: 6px; + padding: 10px 12px; + font-size: 13px; + color: #8c8d91; + cursor: pointer; + transition: all 0.2s; + flex: 1; + justify-content: center; + align-items: center; +} +.radio-switch input[type="radio"]:checked + .radio-btn { + background-color: #313338; + color: #ffffff; + border-color: #4da6ff; +} + +.quality-item { + background-color: #26272b; + border: 1px solid #2f3036; + border-radius: 4px; + padding: 10px; + color: #eeeeee; + cursor: pointer; + font-size: 12px; + text-align: left; +} +.quality-item:hover { background-color: #313338; } +#qualityModal.hidden { display: none !important; } + +/* Custom Radio Cards */ +.hidden-radio { position: absolute; opacity: 0; width: 0; height: 0; } +.radio-card { display: flex; align-items: flex-start; gap: 12px; padding: 14px; background: #16171a; border: 1px solid #2f3036; border-radius: 8px; transition: border-color 0.2s, background-color 0.2s; margin-bottom: 2px; } +.radio-card:hover { border-color: #444; background: #1c1d21; } +.hidden-radio:checked + .radio-card { border-color: #4da6ff; background: rgba(77, 166, 255, 0.05); } +.card-radio-circle { width: 16px; height: 16px; border-radius: 50%; border: 2px solid #6a6b70; transition: all 0.2s; flex-shrink: 0; margin-top: 1px; position: relative; } +.hidden-radio:checked + .radio-card .card-radio-circle { border-color: #4da6ff; } +.hidden-radio:checked + .radio-card .card-radio-circle::after { content: ""; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 8px; height: 8px; border-radius: 50%; background: #4da6ff; } +.card-title-text { font-size: 14px; color: #eeeeee; margin-bottom: 4px; font-weight: 500; } +.card-desc-text { font-size: 11px; color: #8c8d91; line-height: 1.4; } + +/* Custom Select Dropdowns */ +.custom-select-wrapper { position: relative; width: 100%; display: block; } +.custom-select { + width: 100%; + padding: 10px 36px 10px 14px; + background: #16171a; + color: #eeeeee; + border: 1px solid #2f3036; + border-radius: 8px; + cursor: pointer; + appearance: none; + -moz-appearance: none; + -webkit-appearance: none; + font-size: 13px; + font-family: inherit; + transition: all 0.2s; + box-sizing: border-box; +} +.custom-select:hover { border-color: #444; background: #1c1d21; } +.custom-select:focus { border-color: #4da6ff; outline: none; background: #1c1d21; box-shadow: 0 0 0 2px rgba(77, 166, 255, 0.1); } +.select-arrow { + position: absolute; + right: 14px; + top: 50%; + transform: translateY(-50%); + width: 16px; + height: 16px; + color: #6a6b70; + pointer-events: none; +} + +/* Custom Dark Slider (No Bright Colors) */ +.custom-slider { + -webkit-appearance: none; + width: 65%; + height: 6px; + background: transparent; /* track handles it */ + outline: none; + cursor: pointer; + margin: 0; +} + +.custom-slider::-webkit-slider-runnable-track { + width: 100%; + height: 6px; + background: #2a2b30; + border-radius: 3px; + border: 1px solid #1f2023; +} + +.custom-slider::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 16px; + height: 16px; + border-radius: 50%; + background: #55575e; + cursor: pointer; + margin-top: -6px; + box-shadow: 0 1px 3px rgba(0,0,0,0.5); + border: 2px solid #2f3036; + transition: background 0.2s, transform 0.1s; +} + +.custom-slider:hover::-webkit-slider-thumb { + background: #6a6b70; +} + +.custom-slider:active::-webkit-slider-thumb { + transform: scale(1.1); + background: #8c8d91; +} + +.custom-slider::-moz-range-track { + width: 100%; + height: 6px; + background: #2a2b30; + border-radius: 3px; + border: 1px solid #1f2023; +} + +.custom-slider::-moz-range-thumb { + width: 12px; + height: 12px; + border-radius: 50%; + background: #55575e; + cursor: pointer; + box-shadow: 0 1px 3px rgba(0,0,0,0.5); + border: 2px solid #2f3036; + transition: background 0.2s, transform 0.1s; +} + +.custom-slider:hover::-moz-range-thumb { + background: #6a6b70; +} + +.custom-slider:active::-moz-range-thumb { + transform: scale(1.1); + background: #8c8d91; +} + +/* Sniffer Footer Styles */ +.sniffer-footer { + position: fixed; + bottom: 0; + left: 0; + right: 0; + background-color: rgba(17, 18, 20, 0.85); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + border-top: 1px solid rgba(255, 255, 255, 0.08); + padding: 8px 12px; + display: flex; + justify-content: space-between; + align-items: center; + z-index: 1000; + box-shadow: 0 -8px 24px rgba(0,0,0,0.6); + transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); +} + +.footer-left { + display: flex; + align-items: center; + gap: 6px; +} + +.status-dot { + width: 6px; + height: 6px; + background-color: #00ff88; + border-radius: 50%; + box-shadow: 0 0 10px rgba(0, 255, 136, 0.6), 0 0 20px rgba(0, 255, 136, 0.4); + animation: pulse-dot 2s infinite; +} + +@keyframes pulse-dot { + 0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(0, 255, 136, 0.7); } + 70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(0, 255, 136, 0); } + 100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(0, 255, 136, 0); } +} + +.footer-text { + font-size: 11px; + font-weight: 700; + letter-spacing: 0; + text-transform: uppercase; + background: linear-gradient(90deg, #ffffff, #a1a1a5); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + white-space: nowrap; +} + +.count-badge { + background: linear-gradient(135deg, rgba(77, 166, 255, 0.15), rgba(77, 166, 255, 0.05)); + color: #4da6ff; + padding: 0 8px; + border-radius: 12px; + font-size: 9px; + font-weight: 600; + border: 1px solid rgba(77, 166, 255, 0.3); + box-shadow: inset 0 0 8px rgba(77, 166, 255, 0.1); + white-space: nowrap; + display: flex; + align-items: center; + height: 20px; + box-sizing: border-box; + text-transform: uppercase; +} + +.footer-btn { + padding: 0 8px; + font-size: 9px; + font-weight: 600; + border-radius: 12px; + height: 20px; + white-space: nowrap; + display: flex; + align-items: center; + justify-content: center; + margin: 0; + box-sizing: border-box; + text-transform: uppercase; + transition: all 0.2s ease; + cursor: pointer; +} + +.footer-btn-primary { + background: rgba(156, 39, 176, 0.15); + color: #e1bee7; + border: 1px solid rgba(156, 39, 176, 0.4); +} +.footer-btn-primary:hover { + background: rgba(156, 39, 176, 0.25); + border-color: rgba(156, 39, 176, 0.6); + box-shadow: 0 0 10px rgba(156, 39, 176, 0.2); +} + +.footer-btn-secondary { + background: rgba(255, 255, 255, 0.05); + color: #b0b1b5; + border: 1px solid rgba(255, 255, 255, 0.1); +} +.footer-btn-secondary:hover { + background: rgba(255, 255, 255, 0.1); + color: #ffffff; + border-color: rgba(255, 255, 255, 0.2); +} + +.footer-btn-jav { + background: rgba(244, 63, 94, 0.15); + color: #fecdd3; + border: 1px solid rgba(244, 63, 94, 0.4); +} +.footer-btn-jav:hover:not(:disabled) { + background: rgba(244, 63, 94, 0.25); + border-color: rgba(244, 63, 94, 0.6); + box-shadow: 0 0 10px rgba(244, 63, 94, 0.2); +} + +/* Adjust main content padding to not be hidden by footer when active */ +body { + padding-bottom: 55px; +} \ No newline at end of file diff --git a/local-video-downloader - copia (2) - copia/extension/popup.html b/local-video-downloader - copia (2) - copia/extension/popup.html new file mode 100644 index 0000000000000000000000000000000000000000..cd0c3a392e1f9b0eef003ae9673075ebfab315a5 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/popup.html @@ -0,0 +1,434 @@ + + + + + + + +
+
+ + Detector +
+
+ + Descargas +
+
+ + Configuración +
+
+ + Acerca de +
+
+ +
+ + +
+

+ Detector +
+ + +
+

+ + + +
+
+ + + +
+ +

Analizando la web...

+

Por favor, espera un segundo.

+
+
+ + +
+

+ Historial de Descargas + +

+
+ +
+
+ + +
+

Configuración

+ +
+
+ +
+ + +
+
+ +
+ +
+ + + + +
+

Al dar en "Preguntar" podrás elegir la calidad manual. Con "Detector", la app interrogará al servidor para extraer la lista real (Requiere configuración del Host).

+
+ +
+ +
+ + +
+
+ +
+ + +
+
+ +
+ + +
+
+ +
+ +
+ + +
+
+ +
+ +
+ + +
+
+
+
+
+ +
+
+ +
+ + + +
+ +
+
+ +
+
+ Hilos: 4 + +
+
+

+
+
+ +
+
+ Descargas a la vez: 1 + +
+
+

Controla cuántos videos se pueden descargar al mismo tiempo (de 1 a 50). Los videos adicionales se quedarán en la cola de espera.

+
+
+ +
+
+ +
+ +
Ninguna seleccionada (Descargas)
+
+

Si no seleccionas nada, se guardará en Descargas por defecto.

+
+
+ +
+
+ +
+ + +
+

Utiliza tu sesión del navegador de forma segura para permitirte bajar videos privados, de pago o con limitación de edad. Aviso: En el caso de YouTube, las cookies ya se extraen de forma silenciosa e invisible en segundo plano porque es necesario. Sin embargo, marcar deliberadamente esta opción para otros sitios a veces puede generar errores si detectan comportamiento automático. Úsalo si un video falla.

+
+
+ +
+

Exclusivo de YouTube

+ +
+ +
+ + +
+

Si eliges Español y el video no lo tiene, bajará el idioma original automáticamente.

+
+ +
+ +
+ + +
+

Incrusta los subtítulos dentro del video para encenderlos o apagarlos en tu reproductor.

+
+
+ +
+
+ +
+ + +
+

Muestra una tarjeta fija en el Detector para pegar cualquier enlace manualmente.

+
+
+ +
+
+ +
+ + +
+

Detecta automáticamente segmentos de video directos ocultos en el tráfico de red de las páginas que visitas.

+
+
+ +
+
+ +
Native Messaging API [Conectado]
+
+
+
+ + +
+

Acerca de

+
+

Descargador de Videos

+

Versión 1.0.0

+

Permite la extracción híbrida de videos mediante múltiples motores (yt-dlp, N_m3u8DL-RE, Aria2) con Native Messaging directamente al ordenador del usuario.

+
+ +

Consola de Procesos (Multi-Motor)

+
Esperando logs de descarga...
+
+ +
+ + + + + + + diff --git a/local-video-downloader - copia (2) - copia/extension/popup.js b/local-video-downloader - copia (2) - copia/extension/popup.js new file mode 100644 index 0000000000000000000000000000000000000000..278fa6b3d7eb221fea52540ba78ab692245016c1 --- /dev/null +++ b/local-video-downloader - copia (2) - copia/extension/popup.js @@ -0,0 +1,1519 @@ +document.addEventListener('DOMContentLoaded', () => { + // Navigation Tabs logic + const tabs = document.querySelectorAll('.tab'); + const panels = document.querySelectorAll('.panel'); + + tabs.forEach(tab => { + tab.addEventListener('click', () => { + tabs.forEach(t => t.classList.remove('active')); + panels.forEach(p => p.classList.remove('active')); + + tab.classList.add('active'); + const targetId = 'panel-' + tab.getAttribute('data-tab'); + document.getElementById(targetId).classList.add('active'); + }); + }); + + // Local Storage Cache + const downloadsList = document.getElementById('downloadsList'); + const clearHistoryBtn = document.getElementById('clearHistoryBtn'); + + function loadHistory() { + chrome.storage.local.get(['downloadHistory'], (result) => { + const history = result.downloadHistory || []; + downloadsList.innerHTML = ''; + if (history.length === 0) { + downloadsList.innerHTML = '
No hay historial en caché
'; + return; + } + history.slice().reverse().forEach(item => { + const div = document.createElement('div'); + div.className = 'history-item'; + div.innerHTML = ` +
${item.title}
+
${new Date(item.date).toLocaleString()}
+
+ + +
+ `; + div.querySelector('.open-url-btn').addEventListener('click', (e) => { + window.open(e.target.getAttribute('data-url'), '_blank'); + }); + div.querySelector('.open-folder-btn').addEventListener('click', (e) => { + let file = e.target.getAttribute('data-file'); + if (file) { + chrome.runtime.sendMessage({ action: "open_folder", file: file }, () => { }); + } else { + chrome.runtime.sendMessage({ action: "open_folder" }, () => { }); + } + }); + downloadsList.appendChild(div); + }); + }); + } + + clearHistoryBtn.addEventListener('click', () => { + chrome.storage.local.set({ downloadHistory: [] }, () => { + loadHistory(); + }); + }); + + loadHistory(); + + // Settings Logic + const openFolderBtn = document.getElementById('openFolderBtn'); + const sniffedVideosCard = document.getElementById('sniffedVideosCard'); + const sniffedLinksList = document.getElementById('sniffedLinksList'); + let customPathObj = null; + let sniffedUrlOverride = null; + + const selectFolderBtn = document.getElementById('selectFolderBtn'); + const savePathDisplay = document.getElementById('savePathDisplay'); + const savePathStatus = document.getElementById('savePathStatus'); + + const formatRadios = document.querySelectorAll('input[name="formatSetting"]'); + const qualityRadios = document.querySelectorAll('input[name="qualitySetting"]'); + const engineRadios = document.querySelectorAll('input[name="engineSetting"]'); + const qualitySettingContainer = document.getElementById('qualitySettingContainer'); + const videoPreferenceContainer = document.getElementById('videoPreferenceContainer'); + const audioSettingsContainer = document.getElementById('audioSettingsContainer'); + const audioSettingsLabel = document.getElementById('audioSettingsLabel'); + const audioFormatSelect = document.getElementById('audioFormatSelect'); + const audioQualitySelect = document.getElementById('audioQualitySelect'); + const audioConvertSelect = document.getElementById('audioConvertSelect'); + const threadSlider = document.getElementById('threadSlider'); + const threadCountLabel = document.getElementById('threadCountLabel'); + const threadSettingContainer = document.getElementById('threadSettingContainer'); + const concurrencySlider = document.getElementById('concurrencySlider'); + const concurrencyCountLabel = document.getElementById('concurrencyCountLabel'); + const videoFormatPrefRadios = document.querySelectorAll('input[name="videoFormatPref"]'); + + const customModeToggle = document.getElementById('customModeToggle'); + const snifferToggle = document.getElementById('snifferToggle'); + const manualCardContainer = document.getElementById('manualCardContainer'); + const manualUrlInput = document.getElementById('manualUrlInput'); + const manualQualityDrop = document.getElementById('manualQualityDrop'); + const manualDownloadBtn = document.getElementById('manualDownloadBtn'); + const pasteUrlBtn = document.getElementById('pasteUrlBtn'); + const clearErrorsBtn = document.getElementById('clearErrorsBtn'); + const snifferStatusFooter = document.getElementById('snifferStatusFooter'); + const snifferCountBadge = document.getElementById('snifferCountBadge'); + const forceDetectBtn = document.getElementById('forceDetectBtn'); + const forceDetectHtmlBtn = document.getElementById('forceDetectHtmlBtn'); + const forceDetectJavBtn = document.getElementById('forceDetectJavBtn'); + const openToolsBtn = document.getElementById('openToolsBtn'); + + if (openToolsBtn) { + openToolsBtn.addEventListener('click', () => { + chrome.tabs.create({ url: chrome.runtime.getURL('tools.html') }); + }); + } + + if (forceDetectBtn) { + forceDetectBtn.addEventListener('click', () => { + forceDetectBtn.innerText = "Recargando..."; + forceDetectBtn.disabled = true; + chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { + if (tabs.length > 0) { + chrome.tabs.reload(tabs[0].id, () => { + window.close(); // Cierra el popup para permitir que la página recargue y capture libremente + }); + } + }); + }); + } + + if (forceDetectHtmlBtn) { + forceDetectHtmlBtn.addEventListener('click', () => { + forceDetectHtmlBtn.innerText = "Buscando..."; + forceDetectHtmlBtn.disabled = true; + chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { + if (tabs.length > 0) { + chrome.scripting.executeScript({ + target: { tabId: tabs[0].id, allFrames: true }, + func: () => { + let urls = []; + + // 1. Detección Inteligente del Video en Pantalla (Monitor de Red) + try { + let entries = performance.getEntriesByType('resource'); + entries.sort((a, b) => b.startTime - a.startTime); // Ordenar de más reciente a más antiguo + let activeFound = 0; + for (let entry of entries) { + let n = entry.name; + let low_n = n.toLowerCase(); + if (low_n.includes('.mp4') || low_n.includes('.webm') || low_n.includes('.mkv') || low_n.includes('.m3u8') || low_n.includes('.mpd')) { + let cleanUrl = n; + // Remover fragmentos de byte para obtener la URL original + if (cleanUrl.includes('&bytestart=')) cleanUrl = cleanUrl.split('&bytestart=')[0]; + if (cleanUrl.includes('?bytestart=')) cleanUrl = cleanUrl.split('?bytestart=')[0]; + + if (!urls.includes(cleanUrl + "#ACTUAL")) { + urls.push(cleanUrl + "#ACTUAL"); + activeFound++; + } + if (activeFound >= 3) break; // Tomar los 3 videos descargados más recientemente + } + } + } catch (e) {} + + // 2. Buscar en etiquetas