Files
IPSExtractor/bots/bot_descarga/bot_descarga/ui/windows_autostart.py
T

75 lines
2.1 KiB
Python

"""Autoarranque con Windows (carpeta Startup del usuario)."""
from __future__ import annotations
import os
import sys
from pathlib import Path
TASK_BASENAME = "IPSExtractor-BotDescarga"
def bot_root() -> Path:
"""Raíz del paquete bots/bot_descarga (donde está run_gui.py)."""
return Path(__file__).resolve().parents[2]
def startup_dir() -> Path:
appdata = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
return Path(appdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"
def startup_script_path() -> Path:
return startup_dir() / f"{TASK_BASENAME}.bat"
def resolve_python(root: Path | None = None) -> Path:
root = root or bot_root()
for candidate in (
root / ".venv" / "Scripts" / "pythonw.exe",
root / ".venv" / "Scripts" / "python.exe",
root / ".venv" / "bin" / "python",
):
if candidate.exists():
return candidate
return Path(sys.executable)
def is_autostart_enabled() -> bool:
if sys.platform != "win32":
return False
return startup_script_path().exists()
def enable_autostart(root: Path | None = None) -> Path:
"""Crea un .bat en Startup que abre la GUI del bot tras el login."""
if sys.platform != "win32":
raise RuntimeError("El autoarranque solo está disponible en Windows.")
root = (root or bot_root()).resolve()
gui = root / "run_gui.py"
if not gui.exists():
raise FileNotFoundError(f"No se encontró run_gui.py en {root}")
py = resolve_python(root)
dest = startup_script_path()
dest.parent.mkdir(parents=True, exist_ok=True)
# start "" deja que el .bat termine; la GUI queda como proceso independiente.
content = (
"@echo off\r\n"
f'cd /d "{root}"\r\n'
f'start "" "{py}" "{gui}"\r\n'
)
dest.write_text(content, encoding="utf-8")
return dest
def disable_autostart() -> bool:
"""Elimina el .bat de Startup. True si había algo que borrar."""
path = startup_script_path()
if path.exists():
path.unlink()
return True
return False