Scan to open on your phone
Point a camera at the QR code - it opens this exact paste, no app needed.
https://codepastes.com/zzgs3qxzvdkq11fauntitledPlain Text
import base64
import re
import os
import sys
import hashlib
import uuid
import json
import time
import requests
import winsound # ✅ Importar para sonidos del sistema
from datetime import datetime, timezone
import tkinter as tk
from tkinter import filedialog, messagebox
import tkinter.simpledialog as sd
import tkinter.messagebox as mb
from tkinter import messagebox
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox
from splash import mostrar_splash
def hay_internet():
try:
requests.get("https://www.google.com", timeout=3)
return True
except:
return False
URL_SHEETS = "https://docs.google.com/spreadsheets/d/1UOAl6tkwEcP_pSi9iIo5wkzMRUfZ5KJqsyKxl1jHp04/export?format=csv"
def ahora_utc():
return datetime.now(timezone.utc)
def obtener_datos_servidor(hwid):
try:
import requests
import time
import csv
from io import StringIO
hwid = hwid.strip().upper()
r = requests.get(URL_SHEETS + f"&t={time.time()}", timeout=5)
texto = r.text
reader = csv.reader(StringIO(texto), delimiter=';')
for i, columnas in enumerate(reader):
if i == 0:
continue
if len(columnas) == 1:
columnas = columnas[0].split(",")
if len(columnas) < 5:
continue
hwid_excel = columnas[0].replace('"', '').strip().upper()
fecha_vencimiento = columnas[3].replace('"', '').strip()
estado = columnas[4].replace('"', '').strip().lower()
if hwid_excel == hwid:
return {
"fecha": fecha_vencimiento,
"estado": estado
}
# 🔴 NO existe en el servidor
return None
except Exception as e:
print("Error consultando Sheets:", e)
return "error" # 🔥 diferencia clave
def mostrar_dialogo_personalizado(titulo, mensaje, tipo="info", parent=None):
if parent is None:
parent = app
"""
Diálogo modal personalizado (ttkbootstrap) con sonidos e íconos diferentes según el tipo:
- tipo = "info" → sonido de información e ícono verde
- tipo = "warning" → sonido de advertencia e ícono amarillo
- tipo = "error" → sonido de error e ícono rojo
- tipo = "confirm" → sonido de pregunta e ícono azul
"""
dlg = tb.Toplevel(parent)
dlg.withdraw() # 🚫 No mostrar aún (evita parpadeo)
dlg.transient(parent)
dlg.grab_set()
dlg.resizable(False, False)
dlg.title(titulo)
# Icono de ventana (barra de título)
try:
dlg.iconbitmap(obtener_ruta_recurso("icono.ico"))
except Exception:
pass
# === 📐 Tamaño base según tipo ===
if tipo == "warning":
ancho, alto = 360, 170
else:
lineas = mensaje.count("\n") + 1
alto = 160 + (lineas * 15)
ancho = 430 if len(mensaje) < 150 else 390
# === ✨ Fade-in con centrado y sin parpadeo ===
dlg.attributes("-alpha", 0.0)
def centrar_y_fade_in(op=0.0):
"""Centra el cuadro y aplica el efecto de aparición."""
try:
parent.update_idletasks()
x = parent.winfo_rootx() + (parent.winfo_width() // 2) - (ancho // 2)
y = parent.winfo_rooty() + (parent.winfo_height() // 2) - (alto // 2)
dlg.geometry(f"{ancho}x{alto}+{x}+{y}")
except Exception:
dlg.geometry(f"{ancho}x{alto}+200+200") # posición de respaldo
# Mostrar solo cuando ya tiene posición definida
dlg.deiconify()
# Incrementar opacidad progresivamente
if op < 1.0:
dlg.attributes("-alpha", op)
dlg.after(25, centrar_y_fade_in, op + 0.08)
else:
dlg.attributes("-alpha", 1.0)
# Espera breve para asegurar que el parent esté renderizado
dlg.after(100, centrar_y_fade_in)
# === 🌙 Efecto Fade-out (al cerrar) ===
def fade_out(callback):
"""Desvanece suavemente el cuadro antes de cerrarlo."""
op = dlg.attributes("-alpha")
if op > 0:
dlg.attributes("-alpha", op - 0.08)
dlg.after(25, fade_out, callback)
else:
callback()
# Marco interior
frame = tb.Frame(dlg, padding=(15, 15, 15, 10))
frame.pack(fill="both", expand=True)
# Determinar ícono visual, color y sonido
iconos = {
"info": ("✅", "success", winsound.MB_ICONASTERISK),
"warning": ("⚠️", "warning", winsound.MB_ICONEXCLAMATION),
"error": ("❌", "danger", winsound.MB_ICONHAND),
"confirm": ("❓", "info", winsound.MB_ICONQUESTION)
}
simbolo, estilo, sonido = iconos.get(tipo, ("ℹ️", "info", winsound.MB_OK))
# 🔊 Reproducir sonido del sistema
try:
winsound.MessageBeep(sonido)
except Exception:
pass
# === 🖼️ Ícono gráfico personalizado según el tipo ===
from PIL import Image, ImageTk
try:
if tipo == "warning":
icon_path = obtener_ruta_recurso("icon_warning.png")
elif tipo == "error":
icon_path = obtener_ruta_recurso("icon_error.png")
else:
icon_path = obtener_ruta_recurso("icon_success.png")
# Cargar la imagen
img = Image.open(icon_path)
img = img.resize((48, 48), Image.LANCZOS)
icon_img = ImageTk.PhotoImage(img)
# Mostrar imagen a la izquierda
lbl_icon = tb.Label(frame, image=icon_img)
lbl_icon.image = icon_img # evitar que se elimine de memoria
lbl_icon.grid(row=0, column=0, rowspan=2, padx=(0, 15), pady=5, sticky="n")
except Exception as e:
# Si falla (no se encontró la imagen), mostrar emoji como respaldo
simbolo = "✅" if tipo == "info" else "⚠️" if tipo == "warning" else "❌"
tb.Label(
frame,
text=simbolo,
font=("Segoe UI Emoji", 32)
).grid(row=0, column=0, rowspan=2, padx=(0, 15), pady=5, sticky="n")
# === Contenido del mensaje ===
tb.Label(
frame,
text=titulo,
font=("Segoe UI", 11, "bold")
).grid(row=0, column=1, sticky="w", pady=(5, 0))
tb.Label(
frame,
text=mensaje,
wraplength=320,
justify="left",
font=("Segoe UI", 10)
).grid(row=1, column=1, sticky="w", pady=(6, 8))
# === Botones ===
botones_frame = tb.Frame(frame)
botones_frame.grid(row=2, column=0, columnspan=2, sticky="e")
resultado = {"value": False}
def fade_out(callback):
"""Animación de desvanecido al cerrar el cuadro."""
op = dlg.attributes("-alpha")
if op > 0:
dlg.attributes("-alpha", op - 0.08)
dlg.after(25, fade_out, callback)
else:
callback()
def aceptar():
resultado["value"] = True
fade_out(dlg.destroy)
def cancelar():
resultado["value"] = False
fade_out(dlg.destroy)
if tipo == "confirm":
tb.Button(botones_frame, text="Cancelar", bootstyle="secondary-outline", command=cancelar).pack(side="right", padx=(6, 0))
tb.Button(botones_frame, text="Aceptar", bootstyle=f"{estilo}-outline", command=aceptar).pack(side="right")
else:
tb.Button(botones_frame, text="Aceptar", bootstyle=f"{estilo}-outline", command=aceptar).pack(side="right")
dlg.protocol("WM_DELETE_WINDOW", lambda: fade_out(dlg.destroy))
parent.wait_window(dlg)
return resultado["value"]
URL_BLOQUEADAS = "https://docs.google.com/spreadsheets/d/e/2PACX-1vTZSRYra0tC_F_PiQMgs5sjH3h13xCk1aJR-1WBpqC0VkH55-RsCo9IkP3Jq7v0ROlH9wu8QFVOyN5z/pub?output=csv"
def licencia_bloqueada(serial):
try:
import requests
import time
import csv
from io import StringIO
serial = serial.strip().upper()
r = requests.get(URL_BLOQUEADAS + f"&t={time.time()}", timeout=5)
texto = r.text
reader = csv.reader(StringIO(texto), delimiter=';')
for i, columnas in enumerate(reader):
if i == 0:
continue
print("BLOQUEADAS:", columnas)
if len(columnas) == 1:
columnas = columnas[0].split(",")
if len(columnas) < 1:
continue
serial_excel = columnas[0].replace('"', '').strip().upper()
if serial_excel == serial:
print("LICENCIA BLOQUEADA")
return True
except Exception as e:
print("Error leyendo lista bloqueada:", e)
return False
def obtener_hwid():
mac = uuid.getnode()
return hashlib.sha256(str(mac).encode()).hexdigest().upper()
def ruta_licencia():
base = os.getenv("LOCALAPPDATA")
carpeta = os.path.join(base, "PdfSvgEncryptor")
if not os.path.exists(carpeta):
os.makedirs(carpeta)
return os.path.join(carpeta, "license.dat")
SECRET_KEY = base64.b64decode("WDlrTDJwQThzUQ==").decode()
parpadeo_activo = False
parpadeo_job = None
def cifrar(texto):
key = hashlib.sha256(SECRET_KEY.encode()).digest()
data = texto.encode()
resultado = bytearray()
for i in range(len(data)):
resultado.append(data[i] ^ key[i % len(key)])
return base64.b64encode(resultado).decode()
def descifrar(texto):
key = hashlib.sha256(SECRET_KEY.encode()).digest()
data = base64.b64decode(texto)
resultado = bytearray()
for i in range(len(data)):
resultado.append(data[i] ^ key[i % len(key)])
return resultado.decode()
def cargar_licencia():
try:
if not os.path.exists(ruta_licencia()):
return None
with open(ruta_licencia(), "r") as f:
contenido = f.read()
descifrado = descifrar(contenido)
licencia = json.loads(descifrado)
return licencia["data"] # 👈 IMPORTANTE
except Exception as e:
print("Error cargando licencia:", e)
return None
def formato_serial_valido(serial):
patron = r'^[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[0-9]{8}-[A-Z0-9]{5}$'
return bool(re.match(patron, serial.upper()))
def verificar_serial_guardado():
try:
if not os.path.exists(ruta_licencia()):
return False
with open(ruta_licencia(), "r") as f:
contenido = f.read()
descifrado = descifrar(contenido)
licencia = json.loads(descifrado)
datos = licencia["data"]
firma = licencia["sign"]
# 🔐 Validar integridad
texto = json.dumps(datos)
firma_calculada = hashlib.sha256((texto + SECRET_KEY).encode()).hexdigest()
if firma != firma_calculada:
return False
# 🔐 Validar HWID
if datos["hwid"] != obtener_hwid():
return False
ahora = ahora_utc()
fecha_exp = datetime.strptime(
datos["fecha_exp"], "%Y-%m-%d %H:%M:%S"
).replace(tzinfo=timezone.utc)
ultima_validacion = datetime.strptime(
datos.get("ultima_validacion", "2000-01-01 00:00:00"),
"%Y-%m-%d %H:%M:%S"
).replace(tzinfo=timezone.utc)
# 💀 Anti rollback
if ahora < ultima_validacion:
return False
dias_sin_validar = int((ahora - ultima_validacion).total_seconds() / 86400)
# =========================
# 🌐 VALIDACIÓN ONLINE
# =========================
if hay_internet():
datos_servidor = obtener_datos_servidor(datos["hwid"])
# ⚠️ ERROR DE SERVIDOR (NO RESPONDE)
if datos_servidor == "error":
if dias_sin_validar > 3:
mostrar_dialogo_personalizado(
"Sin conexión",
"Debes conectarte a internet para validar la licencia.",
"warning"
)
return False
else:
return True
# 💀 LICENCIA ELIMINADA (MODO ESTRICTO)
elif datos_servidor is None:
mostrar_dialogo_personalizado(
"Licencia inválida",
"Esta licencia fue eliminada del servidor.",
"error"
)
return False
# 🚫 LICENCIA BLOQUEADA
elif datos_servidor["estado"] == "bloqueada":
mostrar_dialogo_personalizado(
"Licencia bloqueada",
"Esta licencia fue bloqueada remotamente.",
"error"
)
return False
# 🔄 ACTUALIZAR DATOS
datos["fecha_exp"] = datos_servidor["fecha"]
datos["ultima_validacion"] = ahora.strftime("%Y-%m-%d %H:%M:%S")
fecha_exp = datetime.strptime(
datos["fecha_exp"], "%Y-%m-%d %H:%M:%S"
).replace(tzinfo=timezone.utc)
texto = json.dumps(datos)
firma_nueva = hashlib.sha256((texto + SECRET_KEY).encode()).hexdigest()
nueva_licencia = {
"data": datos,
"sign": firma_nueva
}
with open(ruta_licencia(), "w") as f:
f.write(cifrar(json.dumps(nueva_licencia)))
# =========================
# 🔌 MODO OFFLINE
# =========================
else:
if dias_sin_validar > 3:
mostrar_dialogo_personalizado(
"Sin conexión",
"Debes conectarte a internet para validar la licencia.",
"warning"
)
return False
# =========================
# ⏰ EXPIRACIÓN
# =========================
if ahora > fecha_exp:
mostrar_dialogo_personalizado(
"Licencia vencida",
"Tu licencia ha expirado.",
"error"
)
return False
return True
except Exception as e:
print("Error verificando licencia:", e)
return False
def obtener_dias_restantes():
try:
with open(ruta_licencia(), "r") as f:
contenido = f.read()
licencia = json.loads(descifrar(contenido))
datos = licencia["data"]
fecha_exp = datetime.strptime(datos["fecha_exp"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
ahora = ahora_utc()
dias_restantes = (fecha_exp - ahora).days
if dias_restantes < 0:
return 0
return dias_restantes
except:
return 0
def guardar_licencia(serial):
hwid = obtener_hwid()
datos_servidor = obtener_datos_servidor(hwid)
if not datos_servidor:
raise Exception("No se pudo validar con el servidor")
ahora = ahora_utc()
datos = {
"serial": serial,
"hwid": hwid,
"fecha_exp": datos_servidor["fecha"],
"last_use": ahora.strftime("%Y%m%d"),
"ultima_validacion": ahora.strftime("%Y-%m-%d %H:%M:%S")
}
texto = json.dumps(datos)
firma = hashlib.sha256((texto + SECRET_KEY).encode()).hexdigest()
licencia = {
"data": datos,
"sign": firma
}
cifrado = cifrar(json.dumps(licencia))
with open(ruta_licencia(),"w") as f:
f.write(cifrado)
def ventana_activacion(parent):
"""
Ventana de activación de licencia.
parent: ventana principal (app)
"""
# 🔹 Crear ventana secundaria
win = tb.Toplevel(parent)
win.title("Activación de licencia")
win.geometry("420x420")
win.resizable(False, False)
win.focus_force()
try:
win.iconbitmap(obtener_ruta_recurso("icono.ico"))
except:
pass
hwid = obtener_hwid()
cont = tb.Frame(win, padding=25)
cont.pack(fill="both", expand=True)
# ===== LOGO =====
try:
logo = tk.PhotoImage(file="logo.png")
lbl_logo = tb.Label(cont, image=logo)
lbl_logo.image = logo
lbl_logo.pack(pady=(0,10))
except:
pass
# ===== TITULO =====
tb.Label(
cont,
text="Incrustador (SVG / HTML)",
font=("Segoe UI", 18, "bold")
).pack()
tb.Label(
cont,
text="Activación de licencia",
font=("Segoe UI", 10)
).pack(pady=(0,20))
# ===== HWID =====
tb.Label(
cont,
text="HWID de este equipo",
font=("Segoe UI", 9)
).pack(anchor="w")
frame_hwid = tb.Frame(cont)
frame_hwid.pack(fill="x", pady=5)
entry_hwid = tb.Entry(frame_hwid)
entry_hwid.insert(0, hwid)
entry_hwid.config(state="readonly")
entry_hwid.pack(side="left", fill="x", expand=True)
def copiar():
win.clipboard_clear()
win.clipboard_append(hwid)
win.update() # ← muy importante
mostrar_dialogo_personalizado(
"Éxito","El HWID fue copiado correctamente al portapapeles.","info",
parent=win
)
tb.Button(
frame_hwid,
text="Copiar",
bootstyle="info",
command=copiar,
width=8
).pack(side="right", padx=5)
# ===== SERIAL =====
tb.Label(
cont,
text="Introduce tu serial",
font=("Segoe UI", 9)
).pack(anchor="w", pady=(20,5))
entry_serial = tb.Entry(cont)
entry_serial.pack(fill="x")
# ===== ACTIVAR =====
resultado = {"ok": False} # flag para verificar activación
def activar():
if not hay_internet():
mostrar_dialogo_personalizado(
"Sin conexión",
"Se requiere internet para activar la licencia.",
"error",
parent=win
)
return
serial = entry_serial.get().strip().upper()
if not serial:
mostrar_dialogo_personalizado(
"Advertencia",
"Debes ingresar un serial",
"warning",
parent=win
)
return
if not formato_serial_valido(serial):
mostrar_dialogo_personalizado(
"Error",
"Formato de licencia inválido.\n\nEjemplo válido:\nABCDE-ABCDE-ABCDE-20260101-ABCDE",
"error",
parent=win
)
return
if licencia_bloqueada(serial):
mostrar_dialogo_personalizado(
"Error",
"Esta licencia ha sido desactivada.",
"error",
parent=win
)
return
try:
if verificar_serial(serial):
guardar_licencia(serial)
mostrar_dialogo_personalizado(
"Licencia",
"Licencia activada correctamente",
"info",
parent=win
)
resultado["ok"] = True
win.destroy()
else:
mostrar_dialogo_personalizado(
"Licencia",
"El serial no es válido o está expirado",
"error",
parent=win
)
except Exception as e:
print("ERROR REAL:", e)
mostrar_dialogo_personalizado(
"Error",
f"Error al validar la licencia:\n{e}",
"error",
parent=win
)
tb.Button(
cont,
text="Activar licencia",
bootstyle="success",
command=activar,
width=25
).pack(pady=30)
# Manejar cierre de ventana sin activar
def cerrar():
resultado["ok"] = False
win.destroy()
win.protocol("WM_DELETE_WINDOW", cerrar)
parent.wait_window(win)
# Esperar a que el usuario termine
return resultado["ok"]
def verificar_serial(serial):
try:
partes = serial.split("-")
if len(partes) != 5:
return False
fecha = partes[3]
base = obtener_hwid() + SECRET_KEY + fecha
hash_val = hashlib.sha256(base.encode()).hexdigest()[:5].upper()
if hash_val != partes[0]:
return False
return True
except:
return False
# === Funciones de selección ===
def seleccionar_svg():
ruta = filedialog.askopenfilename(title="Seleccionar archivo SVG", filetypes=[("Archivos SVG", "*.svg")])
if ruta: entrada_svg.set(ruta)
def seleccionar_html_svg():
ruta = filedialog.askopenfilename(
title="Seleccionar archivo a incrustar en SVG",
filetypes=[
("HTML / ZIP / Todos", "*.html;*.htm;*.zip;*.lnk;*.*"),
("HTML", "*.html;*.htm"),
("ZIP", "*.zip"),
("Todos", "*.*")
]
)
if ruta:
entrada_html_svg.set(ruta)
def seleccionar_html_zip():
ruta = filedialog.askopenfilename(title="Seleccionar archivo HTML (para ZIP)", filetypes=[("Archivos HTML", "*.html;*.htm")])
if ruta: entrada_html_zip.set(ruta)
def seleccionar_zip():
ruta = filedialog.askopenfilename(
title="Seleccionar archivo",
filetypes=[
("Archivos comprimidos", "*.zip *.rar *.tar *.7z"),
("Archivos comunes", "*.zip *.rar *.tar *.7z *.pdf *.exe *.doc *.docx"),
("Todos los archivos", "*.*")
]
)
if ruta:
entrada_zip.set(ruta)
def elegir_formato_salida(parent=None):
if parent is None:
parent = app
dlg = tb.Toplevel(parent)
dlg.title("Formato de salida")
dlg.geometry("360x160")
dlg.resizable(False, False)
dlg.transient(parent)
dlg.grab_set()
try:
dlg.iconbitmap(obtener_ruta_recurso("icono.ico"))
except:
pass
resultado = {"formato": None}
frame = tb.Frame(dlg, padding=20)
frame.pack(fill="both", expand=True)
tb.Label(
frame,
text="¿Con qué formato deseas guardar?",
font=("Segoe UI", 11, "bold")
).pack(pady=(0, 10))
tb.Label(
frame,
text="Selecciona una opción:",
font=("Segoe UI", 9)
).pack(pady=(0, 15))
def seleccionar_svg():
resultado["formato"] = "svg"
dlg.destroy()
def seleccionar_xhtml():
resultado["formato"] = "xhtml"
dlg.destroy()
botones = tb.Frame(frame)
botones.pack()
# 🔵 SVG → azul bonito estilo bootstrap
tb.Button(
botones,
text="🧩 SVG",
bootstyle="info, outline", # 🔥 AQUÍ EL CAMBIO
command=seleccionar_svg,
width=18
).pack(side="left", padx=5)
# 🟢 XHTML → verde como ya lo tenías
tb.Button(
botones,
text="🌐 XHTML",
bootstyle="success-outline",
command=seleccionar_xhtml,
width=18
).pack(side="left", padx=5)
parent.wait_window(dlg)
return resultado["formato"]
# === Función 1: HTML → SVG ===
import re
def limpiar_svg(svg: str) -> str:
import re
# 1. eliminar comentarios (seguro)
svg = re.sub(r'<!--[\s\S]*?-->', '', svg)
# 2. eliminar scripts (seguro)
svg = re.sub(r'<script[\s\S]*?</script>', '', svg, flags=re.IGNORECASE)
# 3. eliminar eventos inline (seguro)
svg = re.sub(r'\son\w+="[^"]*"', '', svg, flags=re.IGNORECASE)
svg = re.sub(r"\son\w+='[^']*'", '', svg, flags=re.IGNORECASE)
# 4. eliminar metadata (seguro)
svg = re.sub(r'<metadata[\s\S]*?</metadata>', '', svg, flags=re.IGNORECASE)
# ❌ NO TOCAR:
# - xmlns
# - viewBox
# - width/height
# - image href
# - preserveAspectRatio
return svg
def incrustar_html_en_svg():
import random
import string
ruta_svg = entrada_svg.get()
ruta_html = entrada_html_svg.get()
if not ruta_svg or not ruta_html:
mostrar_dialogo_personalizado(
"Advertencia",
"Selecciona ambos archivos primero.",
"warning"
)
return
try:
# ===============================
# 📥 LEER HTML
# ===============================
with open(ruta_html, "r", encoding="utf-8", errors="ignore") as f:
contenido_html = f.read()
# ===============================
# 🔐 XOR SEGURO (BYTES)
# ===============================
key = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
data_bytes = contenido_html.encode("utf-8")
key_bytes = key.encode("utf-8")
cifrado_bytes = bytearray()
key2 = ''.join(random.choices(string.ascii_letters, k=8))
key2_bytes = key2.encode("utf-8")
cifrado_bytes = bytearray()
for i in range(len(data_bytes)):
k = key_bytes[i % len(key_bytes)] ^ key2_bytes[i % len(key2_bytes)]
cifrado_bytes.append(data_bytes[i] ^ k)
b64_html = base64.b64encode(cifrado_bytes).decode("utf-8")
# ===============================
# 🧩 FRAGMENTAR + MEZCLAR
# ===============================
chunk_size = random.randint(60, 120)
frags = [b64_html[i:i+chunk_size] for i in range(0, len(b64_html), chunk_size)]
indices = list(range(len(frags)))
random.shuffle(indices)
frags_mix = [frags[i] for i in indices]
orden = indices
# ===============================
# 🎭 VARIABLES RANDOM
# ===============================
def rnd(n=10):
return ''.join(random.choices(string.ascii_letters, k=n))
# Variables con nombres menos sospechosos
v_f = "data_" + rnd()
v_m = "idx_" + rnd()
v_k = "key_" + rnd()
# ===============================
# 🧠 SCRIPT OFUSCADO AVANZADO
# ===============================
def rn(n=8):
import random, string
return "fn_" + ''.join(random.choices(string.ascii_letters, k=n))
# Nombres de funciones ofuscados
f_r = rn()
f_b = rn()
f_x = rn()
f_d = rn()
f_o = rn()
f_i = rn()
f_k = rn()
flag = "init_" + rnd()
l = len(frags)
# Codificación adicional de claves
key_encoded = key.encode('utf-8').hex()
key2_encoded = key2.encode('utf-8').hex()
script = f"""
(function(){{
(function(){{
// Variables con nombres aleatorios
var _0x1a2b = {frags_mix};
var _0x3c4d = {orden};
// Claves codificadas en hexadecimal
var _0x5e6f = ["{key[:4]}", "{key[4:8]}", "{key[8:]}"];
var _0x7g8h = ["{key2[:4]}", "{key2[4:]}"];
// Función de unión
var {f_k} = Function('p', 'return p.join("")');
var _0x9i0j = {f_k}(_0x5e6f);
var _0x1k2l = {f_k}(_0x7g8h);
// Función de reconstrucción
var {f_r} = function(){{
var t = new Array({l});
for (var i = 0; i < {l}; i++) {{
t[_0x3c4d[i]] = _0x1a2b[i];
}}
return t.join('');
}};
// Decodificación base64
var {f_b} = function(b64){{
try {{
var bin = atob(b64);
var len = bin.length;
var out = new Uint8Array(len);
for (var i = 0; i < len; i++) {{
out[i] = bin.charCodeAt(i) & 255;
}}
return out;
}} catch(e) {{
console.error("Error en base64:", e);
return null;
}}
}};
// Decodificación XOR
var {f_x} = function(d,k1,k2){{
try {{
var o = new Uint8Array(d.length);
for (var i = 0; i < d.length; i++) {{
var k = k1.charCodeAt(i % k1.length) ^ k2.charCodeAt(i % k2.length);
o[i] = d[i] ^ k;
}}
return o;
}} catch(e) {{
console.error("Error en XOR:", e);
return null;
}}
}};
// Función principal de descifrado
var {f_d} = function(){{
try {{
var b = {f_r}();
var by = {f_b}(b);
if (!by) return null;
var de = {f_x}(by,_0x9i0j,_0x1k2l);
if (!de) return null;
var h = new TextDecoder("utf-8").decode(de);
if (!h || h.length < 20 || h.charCodeAt(0) !== 60) {{
console.error("HTML inválido");
return null;
}}
return h;
}} catch(e) {{
console.error("Error en descifrado:", e);
return null;
}}
}};
// Función de apertura de contenido mejorada
var {f_o} = function(h){{
try {{
// Método 1: Usar iframe
var iframe = document.createElement('iframe');
iframe.style.width = '100%';
iframe.style.height = '100vh';
iframe.style.border = 'none';
iframe.style.position = 'fixed';
iframe.style.top = '0';
iframe.style.left = '0';
iframe.style.zIndex = '9999';
iframe.style.backgroundColor = 'white';
document.body.appendChild(iframe);
iframe.contentDocument.open();
iframe.contentDocument.write(h);
iframe.contentDocument.close();
// Botón para cerrar
var closeBtn = document.createElement('button');
closeBtn.textContent = '✕ Cerrar';
closeBtn.style.position = 'fixed';
closeBtn.style.top = '10px';
closeBtn.style.right = '10px';
closeBtn.style.zIndex = '10000';
closeBtn.style.padding = '5px 10px';
closeBtn.style.backgroundColor = '#ff4444';
closeBtn.style.color = 'white';
closeBtn.style.border = 'none';
closeBtn.style.borderRadius = '5px';
closeBtn.style.cursor = 'pointer';
closeBtn.onclick = function() {{
document.body.removeChild(iframe);
document.body.removeChild(closeBtn);
}};
document.body.appendChild(closeBtn);
}} catch(e) {{
console.error("Error al mostrar contenido:", e);
// Método 2: Fallback a nueva ventana
try {{
var bl = new Blob([h],{{type:"text/html"}});
var u = URL.createObjectURL(bl);
window.open(u,"_blank");
setTimeout(function(){{URL.revokeObjectURL(u)}},4000);
}} catch(e2) {{
console.error("Error en fallback:", e2);
}}
}}
}};
// Inicialización con anti-debugging
var {f_i} = function(){{
// Anti-análisis de tiempo
var t0 = performance.now();
debugger;
var t1 = performance.now();
if (t1 - t0 > 120) return;
var html = {f_d}();
if (!html) {{
console.error("No se pudo descifrar el HTML");
return;
}}
document.documentElement.style.cursor = "pointer";
var used = false;
document.addEventListener("click",function(e){{
if (used) return;
used = true;
e.stopPropagation();
{f_o}(html);
}});
}};
// Ejecución retardada con aleatoriedad
setTimeout({f_i}, Math.random()*1000+300);
}})();
// Marca de ejecución para evitar duplicados
window.{flag} = true;
}})();
"""
# ===============================
# 📥 LEER SVG
# ===============================
with open(ruta_svg, "r", encoding="utf-8", errors="ignore") as f:
svg = f.read()
svg = limpiar_svg(svg)
# ===============================
# 🧹 LIMPIEZAS CRÍTICAS
# ===============================
# quitar comentarios
svg = re.sub(r'<!--[\s\S]*?-->', '', svg)
# 🔥 quitar onclick problemáticos
svg = re.sub(r'onclick="[^"]*"', '', svg, flags=re.IGNORECASE)
# ===============================
# 🔁 INSERTAR SCRIPT
# ===============================
if "<script" in svg.lower():
svg_modificado = re.sub(
r"<script[\s\S]*?</script>",
"<script><![CDATA[\n" + script + "\n]]></script>",
svg,
count=1,
flags=re.IGNORECASE
)
else:
svg_modificado = svg.replace(
"</svg>",
"<script><![CDATA[\n" + script + "\n]]></script>\n</svg>"
)
# ===============================
# 💾 GUARDAR
# ===============================
# ===============================
# ❓ ELEGIR FORMATO DE SALIDA
# ===============================
# ===============================
# ❓ ELEGIR FORMATO
# ===============================
formato = elegir_formato_salida(app)
if not formato:
return # si el usuario cierra
base_nombre = os.path.splitext(ruta_svg)[0]
if formato == "xhtml":
ruta_salida = base_nombre + "_indetectable.xhtml"
contenido_final = f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>Documento</title>
<style>
html, body {{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #fff;
}}
svg {{
width: 100vw;
height: 100vh;
display: block;
}}
</style>
</head>
<body>
{svg_modificado}
</body>
</html>
'''
else:
ruta_salida = base_nombre + "_indetectable.svg"
contenido_final = svg_modificado
# ===============================
# 💾 GUARDAR
# ===============================
with open(ruta_salida, "w", encoding="utf-8") as f:
f.write(contenido_final)
mostrar_dialogo_personalizado(
"Éxito",
f"Archivo guardado correctamente:\n\n{ruta_salida}",
"info"
)
except Exception as e:
mostrar_dialogo_personalizado(
"Error",
f"Ocurrió un error:\n{e}",
"error"
)
# === Función 2: ZIP → HTML + reemplazo de texto opcional ===
def incrustar_zip_en_html():
ruta_html = entrada_html_zip.get()
ruta_archivo = entrada_zip.get()
# Detectar nombre y extensión del archivo seleccionado
nombre_archivo = os.path.basename(ruta_archivo)
nombre_base, extension = os.path.splitext(nombre_archivo)
extension = extension.lower().replace(".", "")
texto_nuevo = entrada_texto.get()
reemplazar_texto = var_reemplazo.get()
nombre_archivo_nuevo = entrada_nombre_zip.get()
reemplazar_nombre = var_nombre_zip.get()
if not ruta_html or not ruta_archivo:
mostrar_dialogo_personalizado(
"Advertencia",
"Selecciona el HTML y el archivo primero.",
"warning"
)
return
try:
# ==============================
# Leer archivo y convertir a Base64
# ==============================
with open(ruta_archivo, "rb") as f:
b64 = base64.b64encode(f.read()).decode("utf-8")
# ==============================
# Leer HTML original
# ==============================
with open(ruta_html, "r", encoding="utf-8", errors="ignore") as f:
contenido = f.read()
# ==============================
# Buscar variable frags dinámica
# ==============================
match = re.search(
r"(var|let|const)\s+(frags_[a-zA-Z0-9_]+)\s*=\s*\[[\s\S]*?\]\s*;",
contenido,
re.DOTALL
)
if not match:
mostrar_dialogo_personalizado(
"Error",
"No se encontró variable frags_ en el HTML.",
"error"
)
return
tipo_variable = match.group(1)
nombre_variable = match.group(2)
# ==============================
# Crear nuevo array con el Base64
# ==============================
nuevo_array = f"{tipo_variable} {nombre_variable} = ['{b64}'];"
nuevo_contenido = (
contenido[:match.start()] +
nuevo_array +
contenido[match.end():]
)
# ==============================
# Ajustar extensión automática
# ==============================
nuevo_contenido = re.sub(
r'var\s+EXTENSION_ARCHIVO\s*=\s*"(.*?)";',
f'var EXTENSION_ARCHIVO = "{extension}";',
nuevo_contenido,
count=1
)
# ==============================
# Reemplazar texto del DIV (opcional)
# ==============================
if reemplazar_texto and texto_nuevo.strip():
script_fijar_div = f"""
<script>
document.getElementById("key_1ead473ebedb590d").innerText = "{texto_nuevo}";
</script>
"""
if "</body>" in nuevo_contenido:
nuevo_contenido = nuevo_contenido.replace(
"</body>",
script_fijar_div + "\n</body>"
)
else:
nuevo_contenido += script_fijar_div
# ==============================
# Cambiar nombre del archivo descargado
# ==============================
if reemplazar_nombre and nombre_archivo_nuevo.strip():
nuevo_contenido = re.sub(
r"(const|let|var)\s+D\s*=\s*['\"][^'\"]+['\"]",
f"const D='{nombre_archivo_nuevo}'",
nuevo_contenido,
count=1
)
# ==============================
# Guardar HTML final
# ==============================
nuevo_html = os.path.splitext(ruta_html)[0] + "_modificado.html"
with open(nuevo_html, "w", encoding="utf-8") as f:
f.write(nuevo_contenido)
# ==============================
# Mensaje de éxito
# ==============================
exito_msg = f"Archivo incrustado correctamente en:\n{nuevo_html}"
if reemplazar_texto:
exito_msg += f"\n\nTexto reemplazado por: {texto_nuevo}"
if reemplazar_nombre:
exito_msg += f"\n\nNombre del archivo cambiado por: {nombre_archivo_nuevo}"
mostrar_dialogo_personalizado("Éxito", exito_msg, "info")
except Exception as e:
mostrar_dialogo_personalizado("Error", str(e), "error")
def obtener_ruta_recurso(nombre):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, nombre)
return os.path.join(os.path.abspath("."), nombre)
ruta_icono = obtener_ruta_recurso("icono.ico")
app = tb.Window(themename="darkly")
app.withdraw()
if not verificar_serial_guardado():
activado = ventana_activacion(app)
if not activado:
mostrar_dialogo_personalizado("Advertencia", "Licencia no activada", "warning", parent=app)
sys.exit()
if not verificar_serial_guardado():
# 🔥 SOLO si no hay licencia local válida
if not os.path.exists(ruta_licencia()):
mostrar_dialogo_personalizado("Advertencia", "Licencia inválida", "error", parent=app)
sys.exit()
# volver a ocultar antes del splash
app.title("🧩 Incrustador (SVG / HTML) — Versión 2")
app.geometry("720x520")
app.minsize(650, 480) # mínimo para que no se rompa
app.resizable(True, True)
app.iconbitmap(obtener_ruta_recurso("icono.ico"))
def iniciar_app():
app.deiconify()
# Mostrar splash primero
mostrar_splash(app)
# Esperar (ej: 2.5 segundos) y luego mostrar app
app.after(2500, iniciar_app)
entrada_svg = tb.StringVar()
entrada_html_svg = tb.StringVar()
entrada_html_zip = tb.StringVar()
entrada_zip = tb.StringVar()
entrada_texto = tb.StringVar()
var_reemplazo = tb.BooleanVar(value=False)
# ==========================
# SISTEMA DE LICENCIA
# ==========================
# === SISTEMA DE LICENCIA ===
# ===== VERIFICAR LICENCIA =====
def obtener_info_licencia():
archivo = ruta_licencia()
if not os.path.exists(archivo):
return None
try:
with open(archivo,"r") as f:
cifrado = f.read()
texto = descifrar(cifrado)
licencia = json.loads(texto)
serial = licencia["data"]["serial"]
partes = serial.split("-")
fecha = partes[3]
fecha_exp = datetime.strptime(
licencia["data"]["fecha_exp"], "%Y-%m-%d %H:%M:%S"
).replace(tzinfo=timezone.utc)
dias_restantes = (fecha_exp - ahora_utc()).days
return fecha_exp, dias_restantes
except:
return None
def parpadear_alerta(widget):
global parpadeo_job
colores = ["#ff3b3b", "#ffc0c0"]
def alternar(i=0):
global parpadeo_job
widget.configure(foreground=colores[i % 2])
parpadeo_job = widget.after(600, alternar, i + 1)
alternar()
def detener_parpadeo(widget):
global parpadeo_job, parpadeo_activo
if parpadeo_job is not None:
widget.after_cancel(parpadeo_job)
parpadeo_job = None
parpadeo_activo = False
widget.configure(foreground="") # vuelve a color normal
def actualizar_label_licencia():
global parpadeo_activo
info = obtener_info_licencia()
if info:
fecha_exp, dias = info
delta = fecha_exp - ahora_utc()
dias_restantes = delta.days
# 🚫 LICENCIA VENCIDA (POR HORA REAL)
if delta.total_seconds() <= 0:
texto_lic = "❌ Licencia vencida"
color = "danger"
label_licencia.config(text=texto_lic, bootstyle=color)
mostrar_dialogo_personalizado(
"❌ Licencia vencida",
"Tu licencia ha expirado.",
"error"
)
app.after(500, app.destroy)
return
# ⏳ EXPIRA HOY (CON CONTADOR)
elif dias_restantes == 0:
segundos_restantes = int(delta.total_seconds())
horas = segundos_restantes // 3600
minutos = (segundos_restantes % 3600) // 60
segundos = segundos_restantes % 60
contador = f"{horas:02}:{minutos:02}:{segundos:02}"
texto_lic = f"❗ Expira hoy | ⏳ {contador}"
color = "danger"
elif dias_restantes <= 2:
texto_lic = f"❗ Licencia expira en {dias_restantes} día(s)"
color = "danger"
elif dias_restantes <= 5:
texto_lic = f"⚠ Licencia expira en {dias_restantes} días"
color = "warning"
else:
texto_lic = f"Licencia activa | Expira: {fecha_exp.strftime('%d/%m/%Y')} | Días restantes: {dias_restantes}"
color = "success"
# 🔄 ACTUALIZAR LABEL
label_licencia.config(text=texto_lic, bootstyle=color)
# 🧹 SIEMPRE DETENER PARPADEO ANTES DE DECIDIR
detener_parpadeo(label_licencia)
if color == "danger":
parpadear_alerta(label_licencia)
app.after(1000, actualizar_label_licencia)
def sincronizar_licencia_tiempo_real():
try:
print("⏳ Verificando licencia...")
datos = cargar_licencia()
if not datos:
print("❌ No hay licencia local")
return
datos_servidor = obtener_datos_servidor(datos["hwid"])
# =========================
# ⚠️ ERROR DE CONEXIÓN (modo offline)
# =========================
if datos_servidor == "error":
print("⚠️ Error de conexión con el servidor (modo offline)")
return
# =========================
# 💀 LICENCIA ELIMINADA
# =========================
elif datos_servidor is None:
print("💀 Licencia eliminada del servidor")
mostrar_dialogo_personalizado(
"Acceso revocado",
"Tu licencia fue eliminada remotamente.",
"error"
)
app.after(0, app.destroy)
return
# =========================
# 🚫 LICENCIA BLOQUEADA
# =========================
elif datos_servidor.get("estado") == "bloqueada":
print("🚫 Licencia bloqueada")
mostrar_dialogo_personalizado(
"Acceso revocado",
"Tu licencia fue bloqueada remotamente por el servidor.",
"error"
)
app.after(0, app.destroy)
return
# =========================
# 🔄 SINCRONIZACIÓN NORMAL
# =========================
else:
print("Local:", datos.get("fecha_exp"))
print("Servidor:", datos_servidor["fecha"])
# 🔄 Si cambió la fecha en el servidor
if datos_servidor["fecha"] != datos.get("fecha_exp"):
print("🔄 Licencia actualizada")
datos["fecha_exp"] = datos_servidor["fecha"]
datos["ultima_validacion"] = ahora_utc().strftime("%Y-%m-%d %H:%M:%S")
texto = json.dumps(datos)
firma_nueva = hashlib.sha256((texto + SECRET_KEY).encode()).hexdigest()
licencia_actualizada = {
"data": datos,
"sign": firma_nueva
}
with open(ruta_licencia(), "w") as f:
f.write(cifrar(json.dumps(licencia_actualizada)))
actualizar_label_licencia()
except Exception as e:
print("💥 Error sincronizando:", e)
# ⏱️ repetir cada 10 segundos
app.after(10000, sincronizar_licencia_tiempo_real)
# === 📘 Ventana "Acerca de..." ===
def mostrar_creditos():
ventana = tb.Toplevel(app)
ventana.title("Acerca de Incrustador")
ventana.geometry("420x310")
ventana.resizable(False, False)
ventana.iconbitmap(obtener_ruta_recurso("icono.ico"))
ventana.grab_set() # bloquea la ventana principal mientras esté abierta
tb.Label(
ventana,
text="🧩 Incrustador (SVG / HTML) — Versión 2",
font=("Segoe UI", 13, "bold")
).pack(pady=(20, 5))
tb.Label(
ventana,
text="Desarrollado por: Josema Higor",
font=("Segoe UI", 10)
).pack(pady=(0, 5))
tb.Label(
ventana,
text="© 2025 — Todos los derechos reservados",
font=("Segoe UI", 9),
foreground="#888"
).pack(pady=(0, 15))
tb.Separator(ventana, bootstyle="secondary").pack(fill="x", padx=25, pady=10)
tb.Label(
ventana,
text="Herramienta avanzada para incrustar HTML y archivos ZIP en SVG,\n"
"con compatibilidad total y preservación del formato Base64.",
wraplength=360,
justify="center",
font=("Segoe UI", 9)
).pack(pady=10)
tb.Label(
ventana,
text="⚠️ Aviso:\n"
"Esta herramienta está destinada únicamente para fines educativos y de prueba.\n"
"El uso de la misma es responsabilidad del usuario.\n"
"El desarrollador no se hace responsable por el uso indebido, ilegal o no autorizado\n"
"de la misma.",
wraplength=360,
justify="center",
font=("Segoe UI", 8),
foreground="#aa4444"
).pack(pady=(5, 10))
tb.Button(
ventana,
text="Cerrar",
bootstyle="secondary-outline",
command=ventana.destroy
).pack(pady=15)
notebook = tb.Notebook(app, bootstyle="dark")
notebook.pack(fill="both", expand=True, padx=15, pady=(15, 0))
tab1 = tb.Frame(notebook)
tab2 = tb.Frame(notebook)
for tab in (tab1, tab2):
tab.columnconfigure(0, weight=1)
tab.columnconfigure(1, weight=0)
for i in range(20):
tab.rowconfigure(i, weight=0)
tab.rowconfigure(99, weight=1) # espacio flexible abajo
notebook.add(tab1, text="🧩 Incrustar HTML en SVG")
notebook.add(tab2, text="📦 Incrustar ZIP en HTML")
notebook.select(tab2)
# === Variables ===
# === TAB 1 ===
tb.Label(tab1, text="Archivo SVG original:", font=("Segoe UI", 11, "bold")).grid(row=0, column=0, sticky="w", padx=10, pady=(15,5))
tb.Entry(tab1, textvariable=entrada_svg, bootstyle="dark").grid(row=1, column=0, columnspan=2, padx=10, sticky="ew")
tb.Button(tab1, text="Buscar SVG", bootstyle="secondary-outline", command=seleccionar_svg).grid(row=1, column=1, padx=10, sticky="e")
tb.Label(tab1, text="Archivo HTML a incrustar:", font=("Segoe UI", 11, "bold")).grid(row=2, column=0, sticky="w", padx=10, pady=(20,5))
tb.Entry(tab1, textvariable=entrada_html_svg, bootstyle="dark").grid(row=3, column=0, columnspan=2, padx=10, sticky="ew")
tb.Button(tab1, text="Buscar HTML", bootstyle="secondary-outline", command=seleccionar_html_svg).grid(row=3, column=1, padx=10, sticky="e")
tb.Button(tab1, text="🚀 Incrustar HTML en SVG", bootstyle="success, outline", command=incrustar_html_en_svg).grid(row=4, column=0, columnspan=2, pady=30, sticky="ew", padx=20)
# === TAB 2 ===
tb.Label(tab2, text="Archivo HTML donde incrustar el ZIP:", font=("Segoe UI", 11, "bold")).grid(row=0, column=0, sticky="w", padx=10, pady=(15,5))
tb.Entry(tab2, textvariable=entrada_html_zip, bootstyle="dark").grid(row=1, column=0, columnspan=2, padx=10, sticky="ew")
tb.Button(tab2, text="Buscar HTML", bootstyle="secondary-outline", command=seleccionar_html_zip).grid(row=1, column=1, padx=10, sticky="e")
tb.Label(tab2, text="Archivo ZIP a convertir:", font=("Segoe UI", 11, "bold")).grid(row=2, column=0, sticky="w", padx=10, pady=(20,5))
tb.Entry(tab2, textvariable=entrada_zip, bootstyle="dark").grid(row=3, column=0, columnspan=2, padx=10, sticky="ew")
tb.Button(tab2, text="Buscar ZIP", bootstyle="secondary-outline", command=seleccionar_zip).grid(row=3, column=1, padx=10, sticky="e")
# 🔤 Opción de reemplazo de texto dinámica con efecto visual
# === 🔤 Opción de reemplazo de texto dinámica con animación ===
# Colores para los dos estados
# === 🎨 Colores y funciones de animación ===
COLOR_FONDO_OFF = (43, 43, 43) # gris oscuro (#2b2b2b)
COLOR_FONDO_ON = (26, 26, 26) # gris más claro (#1a1a1a)
COLOR_TEXTO_OFF = (136, 136, 136) # gris claro (#888)
COLOR_TEXTO_ON = (255, 255, 255) # blanco
def rgb_to_hex(rgb):
"""Convierte un color RGB (tuple) a formato HEX (#rrggbb)"""
return f"#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}"
def animar_transicion(inicio, fin, pasos=15, delay=15, tipo="fondo", campo=None):
"""Animación de color suave para cualquier campo"""
r1, g1, b1 = inicio
r2, g2, b2 = fin
for i in range(pasos + 1):
r = int(r1 + (r2 - r1) * i / pasos)
g = int(g1 + (g2 - g1) * i / pasos)
b = int(b1 + (b2 - b1) * i / pasos)
color = rgb_to_hex((r, g, b))
if campo:
app.after(i * delay, lambda c=color, t=tipo, e=campo: (
e.configure(background=c) if t == "fondo" else e.configure(foreground=c)
))
# === 🗝️ Campo 1: Contraseña Archivo ===
def alternar_campo_texto():
"""Activa o desactiva el campo de texto con animación de color."""
if var_reemplazo.get():
entry_texto.configure(state="normal", bootstyle="info")
animar_transicion(COLOR_FONDO_OFF, COLOR_FONDO_ON, tipo="fondo", campo=entry_texto)
animar_transicion(COLOR_TEXTO_OFF, COLOR_TEXTO_ON, tipo="texto", campo=entry_texto)
else:
animar_transicion(COLOR_FONDO_ON, COLOR_FONDO_OFF, tipo="fondo", campo=entry_texto)
animar_transicion(COLOR_TEXTO_ON, COLOR_TEXTO_OFF, tipo="texto", campo=entry_texto)
app.after(300, lambda: entry_texto.configure(state="disabled", bootstyle="secondary"))
tb.Checkbutton(
tab2,
text="Contraseña Archivo",
variable=var_reemplazo,
bootstyle="round-toggle",
command=alternar_campo_texto
).grid(row=4, column=0, sticky="w", padx=10, pady=(25,5))
entry_texto = tb.Entry(
tab2,
textvariable=entrada_texto,
bootstyle="secondary",
state="disabled"
)
entry_texto.grid(row=5, column=0, columnspan=2, padx=10, sticky="ew")
tb.Label(
tab2,
font=("Segoe UI", 9),
foreground="#aaa"
).grid(row=5, column=0, sticky="e", padx=(0,70))
# === 💾 Campo 2: Nombre del archivo ZIP con animación ===
var_nombre_zip = tb.BooleanVar(value=False)
entrada_nombre_zip = tb.StringVar()
def alternar_campo_zip():
"""Activa/desactiva el campo del nombre de archivo ZIP con animación."""
if var_nombre_zip.get():
entry_nombre_zip.configure(state="normal", bootstyle="info")
animar_transicion(COLOR_FONDO_OFF, COLOR_FONDO_ON, tipo="fondo", campo=entry_nombre_zip)
animar_transicion(COLOR_TEXTO_OFF, COLOR_TEXTO_ON, tipo="texto", campo=entry_nombre_zip)
else:
animar_transicion(COLOR_FONDO_ON, COLOR_FONDO_OFF, tipo="fondo", campo=entry_nombre_zip)
animar_transicion(COLOR_TEXTO_ON, COLOR_TEXTO_OFF, tipo="texto", campo=entry_nombre_zip)
app.after(300, lambda: entry_nombre_zip.configure(state="disabled", bootstyle="secondary"))
tb.Checkbutton(
tab2,
text="Nombre del archivo a descargar",
variable=var_nombre_zip,
bootstyle="round-toggle",
command=alternar_campo_zip
).grid(row=7, column=0, sticky="w", padx=10, pady=(25,5))
entry_nombre_zip = tb.Entry(
tab2,
textvariable=entrada_nombre_zip,
bootstyle="secondary",
state="disabled"
)
entry_nombre_zip.grid(row=8, column=0, columnspan=2, padx=10, sticky="ew")
tb.Label(
tab2,
font=("Segoe UI", 9),
foreground="#aaa"
).grid(row=8, column=0, sticky="e", padx=(0,70))
# === ⚙️ Botón final de acción ===
tb.Button(
tab2,
text="⚡ Incrustar ZIP en HTML",
bootstyle="info, outline",
command=incrustar_zip_en_html
).grid(row=9, column=0, columnspan=2, pady=30, sticky="ew", padx=20)
# === 📜 Pie de la aplicación ===
pie = tb.Frame(app)
frame_info = tb.Frame(pie)
frame_info.pack(fill="x", expand=True)
frame_info.columnconfigure(0, weight=1)
# 🔥 LABEL FIJO (SE CREA UNA SOLA VEZ)
label_licencia = tb.Label(
pie,
text="Validando licencia...",
bootstyle="secondary",
font=("Segoe UI", 9)
)
label_licencia.pack(side="right", padx=10, anchor="e")
pie.pack(fill="x", side="bottom", padx=10, pady=5)
# Etiquetas dentro del pie
tb.Label(
frame_info,
text="© Herramienta avanzada de incrustación HTML en SVG — V2",
foreground="#888",
font=("Segoe UI", 9)
).pack(side="left", padx=10)
tb.Label(
frame_info,
text="© Desarrollado por: Josema Higor",
foreground="#888",
font=("Segoe UI", 9, "italic")
).pack(side="left", padx=10)
# Botón "Acerca de"
tb.Button(
frame_info,
text="ℹ️ Acerca de ",
bootstyle="secondary-outline",
command=mostrar_creditos
).pack(side="right", padx=2)
actualizar_label_licencia()
app.after(1000, sincronizar_licencia_tiempo_real)
app.mainloop()
55,660 chars · codepastes.com