detector-de-enlaces-copia / background.js
codebydante's picture
Subida inicial de detector de enlaces - copia en la raíz del repositorio
596aae4 verified
Raw History Blame Contribute Delete
19.3 kB
let videoScanState = {
isScanning: false,
scannedCount: 0,
totalCount: 0,
foundUrls: [],
albumUrls: [],
error: null
};
let imageScanState = {
isScanning: false,
scannedCount: 0,
totalCount: 0,
foundUrls: [],
groupedResults: [],
albumUrls: [],
error: null
};
function getMediaId(urlStr) {
if (!urlStr) return '';
try {
const cleanUrl = urlStr.split('?')[0].split('#')[0];
const filename = cleanUrl.substring(cleanUrl.lastIndexOf('/') + 1);
const nameWithoutExt = filename.replace(/\.[a-zA-Z0-9]+$/, '');
const baseId = nameWithoutExt.replace(/_(?:\d+p|hd|sd|v|thumb)$/i, '');
return baseId.toLowerCase();
} catch(e) {
return '';
}
}
function isAlbumImageUrl(url, videoIds = new Set(), videoPosters = new Set()) {
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 (videoPosters.has(lower)) {
return false;
}
const mediaId = getMediaId(url);
if (mediaId && videoIds.has(mediaId)) {
return false;
}
// Filter out explicit video poster and video thumbnail patterns
if (lower.includes('_v.jpg') || lower.includes('_v.jpeg') || lower.includes('_v.png') || lower.includes('_v.webp') ||
lower.includes('_v_thumb') || lower.includes('v_thumb') || lower.includes('poster=')) {
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;
videoScanState.isScanning = false;
}
if (res.imageScanState) {
imageScanState = res.imageScanState;
imageScanState.isScanning = false;
}
});
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') {
startImageScan(message.payload.albumUrls, message.payload.currentImages, message.payload.groupedResults);
sendResponse(imageScanState);
return true;
}
if (message.type === 'RESET_IMAGE_SCAN') {
imageScanState = {
isScanning: false,
scannedCount: 0,
totalCount: 0,
foundUrls: [],
groupedResults: [],
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, initialGroups) {
imageScanState.isScanning = true;
imageScanState.albumUrls = albumUrls;
imageScanState.totalCount = albumUrls.length;
imageScanState.scannedCount = 0;
imageScanState.foundUrls = Array.from(new Set(initialImages || []));
imageScanState.groupedResults = [];
imageScanState.error = null;
chrome.storage.local.set({ imageScanState });
chrome.runtime.sendMessage({ type: 'IMAGE_SCAN_UPDATE', payload: imageScanState }).catch(() => {});
const CONCURRENCY = 3;
const queue = [...albumUrls];
const processAlbum = async (url) => {
const albumMatch = url.match(/erome\.com\/a\/([a-zA-Z0-9]+)/);
const albumId = albumMatch ? albumMatch[1] : null;
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 8000);
let res = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
let text = await res.text();
let albumTitle = "Álbum " + (albumId || url);
let newUrls = new Set();
let videoIds = new Set();
let videoPosters = new Set();
let mp4Matches = text.matchAll(/https?:\/\/[^"'\s<>]+\.mp4(?:\?[^"'\s<>]*)?/gi);
for (const m of mp4Matches) {
const id = getMediaId(m[0]);
if (id) videoIds.add(id);
}
let posterMatches = text.matchAll(/poster=["']([^"']+)["']/gi);
for (const m of posterMatches) {
videoPosters.add(m[1].toLowerCase());
const id = getMediaId(m[1]);
if (id) videoIds.add(id);
}
try {
let doc = new DOMParser().parseFromString(text, 'text/html');
let titleEl = doc.querySelector('h1.album-title, h1.page-title, h1, title');
if (titleEl) {
albumTitle = titleEl.textContent.trim().replace(/\s*-\s*Erome$/i, '');
}
doc.querySelectorAll('video, source, a[href*=".mp4"], [data-src*=".mp4"]').forEach(v => {
let p = v.getAttribute('poster') || v.getAttribute('data-poster');
if (p) {
videoPosters.add(p.toLowerCase());
let pid = getMediaId(p);
if (pid) videoIds.add(pid);
}
let src = v.getAttribute('src') || v.getAttribute('data-src') || v.getAttribute('href');
if (src) {
let sid = getMediaId(src);
if (sid) videoIds.add(sid);
}
});
let mediaGroups = doc.querySelectorAll('.media-group, .media-item, .post-media, .video-group');
if (mediaGroups.length > 0) {
mediaGroups.forEach(group => {
// Skip media groups containing a video, source, mp4 link or play icons
if (group.querySelector('video, source, a[href*=".mp4"], [data-src*=".mp4"], .video-holder, .video-player, .video-icon, .fa-play, [class*="play"], [class*="video"]') ||
group.classList.contains('video-group') ||
group.innerHTML.includes('.mp4') ||
group.innerHTML.includes('fa-play') ||
group.innerHTML.includes('video-icon')) return;
group.querySelectorAll('img').forEach(img => {
let src = img.getAttribute('data-src') || img.getAttribute('src') || img.getAttribute('data-lazy');
if (src) {
if (!src.startsWith('http')) {
try { src = new URL(src, url).href; } catch(e) {}
}
if (isAlbumImageUrl(src, videoIds, videoPosters)) {
if (!albumId || src.toLowerCase().includes('/' + albumId.toLowerCase() + '/')) {
newUrls.add(src);
}
}
}
});
});
} else {
doc.querySelectorAll('img').forEach(img => {
if (img.closest('video, .video-group, .video-holder, [class*="video"]')) return;
let src = img.getAttribute('data-src') || img.getAttribute('src') || img.getAttribute('data-lazy');
if (src) {
if (!src.startsWith('http')) {
try { src = new URL(src, url).href; } catch(e) {}
}
if (isAlbumImageUrl(src, videoIds, videoPosters)) {
if (albumId && src.toLowerCase().includes('/' + albumId.toLowerCase() + '/')) {
newUrls.add(src);
}
}
}
});
}
} catch(e) {
// Fallback regex match if DOMParser fails
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, videoIds, videoPosters)) {
if (albumId && imgUrl.toLowerCase().includes('/' + albumId.toLowerCase() + '/')) {
newUrls.add(imgUrl);
}
}
}
}
const albumImages = Array.from(newUrls);
if (albumImages.length > 0) {
const groupObj = {
albumUrl: url,
albumTitle: albumTitle,
albumId: albumId,
images: albumImages
};
const existingIdx = imageScanState.groupedResults.findIndex(g => g.albumUrl === url || (albumId && g.albumId === albumId));
if (existingIdx !== -1) {
imageScanState.groupedResults[existingIdx] = groupObj;
} else {
imageScanState.groupedResults.push(groupObj);
}
for (const u of albumImages) {
if (!imageScanState.foundUrls.includes(u)) {
imageScanState.foundUrls.push(u);
}
}
}
} catch (e) {
console.error("Error fetching album", url, e);
} finally {
imageScanState.scannedCount++;
chrome.storage.local.set({ imageScanState });
chrome.runtime.sendMessage({ type: 'IMAGE_SCAN_UPDATE', payload: imageScanState }).catch(() => {});
}
};
const workers = Array(Math.min(CONCURRENCY, queue.length)).fill(null).map(async () => {
while (queue.length > 0) {
const url = queue.shift();
await processAlbum(url);
}
});
await Promise.all(workers);
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!
});
}
});