"""Helpers mínimos para construir proyectos Android desde otros módulos. El bot principal usa bot.py, pero este módulo queda limpio para integraciones externas. """ import os import subprocess from pathlib import Path from typing import Optional def run_cmd(cmd: list[str], cwd: str, log_path: str, env: Optional[dict] = None) -> int: Path(log_path).parent.mkdir(parents=True, exist_ok=True) with open(log_path, "a", encoding="utf-8", errors="ignore") as log: log.write("\n$ " + " ".join(cmd) + "\n") log.flush() process = subprocess.Popen( cmd, cwd=cwd, stdout=log, stderr=subprocess.STDOUT, env=env or os.environ.copy(), ) return int(process.wait() or 0) def detect_project(unpacked_dir: str) -> str: root = Path(unpacked_dir) if (root / "buildozer.spec").exists(): return "buildozer" if ( (root / "gradlew").exists() or any(root.rglob("build.gradle")) or any(root.rglob("build.gradle.kts")) or (root / "settings.gradle").exists() or (root / "settings.gradle.kts").exists() ): return "gradle" if (root / "apktool.yml").exists() or (root / "smali").exists() or any(root.glob("smali_classes*")): return "apktool" return "unknown" def find_any_apk(root: str) -> Optional[str]: candidates = [p for p in Path(root).rglob("*.apk") if p.is_file()] if not candidates: return None candidates.sort(key=lambda p: p.stat().st_mtime, reverse=True) return str(candidates[0]) def build_zip(unpacked_dir: str, log_path: str) -> tuple[bool, str, str]: kind = detect_project(unpacked_dir) if kind == "gradle": wrapper = Path(unpacked_dir) / "gradlew" if wrapper.exists(): wrapper.chmod(0o755) code = run_cmd(["./gradlew", "--no-daemon", "assembleDebug"], unpacked_dir, log_path) else: code = run_cmd(["gradle", "--no-daemon", "assembleDebug"], unpacked_dir, log_path) apk = find_any_apk(unpacked_dir) return (code == 0 and bool(apk), apk or "", "APK generado" if apk else "No encontré APK") if kind == "apktool": out_apk = str(Path(unpacked_dir).parent / "rebuilt.apk") code = run_cmd(["apktool", "b", unpacked_dir, "-o", out_apk], unpacked_dir, log_path) return (code == 0 and Path(out_apk).exists(), out_apk, "APK reconstruido" if Path(out_apk).exists() else "apktool falló") return False, "", "ZIP no reconocido como proyecto Android."