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) path = parsed.path # Intentar obtener datos de la API rotando mirrors si es necesario api_mirrors = [parsed.netloc, "kemono.su", "kemono.cr"] data = None last_api_err = "" for m in api_mirrors: if not m: continue api_url = f"https://{m}/api/v1{path}" try: if scraper: response = scraper.get(api_url, headers=headers, timeout=10) response.raise_for_status() data = response.json() else: req = urllib.request.Request(api_url, headers=headers) with urllib.request.urlopen(req, timeout=10) as response: data = json.loads(response.read().decode()) if data: break except Exception as e: last_api_err = str(e) continue if not data: raise Exception(f"No se pudo obtener datos de la API en ningun mirror. Ultimo error: {last_api_err}") 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 fpath = file_obj['path'] if not fpath.startswith('http') and not fpath.startswith('/data'): fpath = '/data' + ('' if fpath.startswith('/') else '/') + fpath # Usar kemono.su como base mas confiable para descargas si es relativo domain = parsed.netloc if 'kemono' in parsed.netloc else 'kemono.su' link = fpath if fpath.startswith('http') else f"https://{domain}{fpath}" 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: hrefs = re.findall(r'href=["\'](https?://[^"\']+)["\']', content) urls_in_text = re.findall(r'(https?://[^\s<"\'\)]+)', content) for u in set(hrefs + urls_in_text): # Limpiar y normalizar enlaces externos u_clean = u.split('?')[0] if 'kemono' in u else u if 'kemono' not in u_clean or '/downloads' in u_clean or '/data/' in u_clean: 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(0.5) 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: # Normalizar URL if not img_url.startswith('http'): parsed = urllib.parse.urlparse(post.get('url')) img_url = f"{parsed.scheme}://{parsed.netloc}{img_url}" # Limpiar URL (quitar parĂ¡metros innecesarios y asegurar esquema https) img_url = img_url.split('?')[0].replace('http://', 'https://') # Lista de dominios para reintentar si falla (Kemono rota mucho estos mirrors) mirrors = [ "img.kemono.su", "c1.kemono.su", "c2.kemono.su", "c3.kemono.su", "img.kemono.cr", "c1.kemono.cr" ] current_parsed = urllib.parse.urlparse(img_url) path = current_parsed.path extMatch = re.search(r'\.(jpg|jpeg|png|webp|gif|avif)', path, 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 os.path.exists(filepath): with lock: images_downloaded += 1 return success = False last_error = "" # Intentar con el dominio original y luego con los mirrors test_urls = [img_url] for m in mirrors: alt_url = f"https://{m}{path}" if alt_url not in test_urls: test_urls.append(alt_url) for try_url in test_urls: try: if scraper: response = scraper.get(try_url, headers=headers, stream=True, timeout=10) 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(try_url, headers=headers) with urllib.request.urlopen(req, timeout=10) as response, open(filepath, 'wb') as out_file: while True: chunk = response.read(65536) if not chunk: break out_file.write(chunk) success = True break except Exception as e: last_error = str(e) continue if not success: raise Exception(f"Todos los mirrors fallaron. Ultimo error: {last_error}") except Exception as e: try: with lock: log_path = os.path.join(base_dir, "errores_descarga.txt") with open(log_path, "a", encoding="utf-8") as log: log.write(f"[{time.strftime('%H:%M:%S')}] ERROR en {img_url}: {str(e)}\n") except: 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=10) 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