Download bot.py from saske560/contrutor: direct link, hf CLI and curl.
- Browser
- Download file 36.9 kB
-
https://huggingface.co/spaces/saske560/contrutor/resolve/main/bot.py
- Command line
-
hf download hf://spaces/saske560/contrutor/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/saske560/contrutor/resolve/main/bot.py
36.9 kB
| import asyncio | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import subprocess | |
| import threading | |
| import uuid | |
| import zipfile | |
| from pathlib import Path | |
| from typing import Optional | |
| from pyrogram import Client, filters | |
| from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup | |
| try: | |
| from pyrogram.enums import ParseMode as _ParseMode | |
| except Exception: | |
| _ParseMode = None | |
| # ============================= | |
| # Configuración base | |
| # ============================= | |
| API_ID = int(os.environ.get("API_ID", "0")) | |
| API_HASH = os.environ.get("API_HASH", "") | |
| BOT_TOKEN = os.environ.get("BOT_TOKEN", "") | |
| STORAGE_DIR = Path(os.environ.get("STORAGE_DIR", "/app/storage")) | |
| DEFAULT_GRADLE_VERSION = os.environ.get("DEFAULT_GRADLE_VERSION", "8.7") | |
| DEFAULT_ANDROID_PLUGIN_VERSION = os.environ.get("DEFAULT_ANDROID_PLUGIN_VERSION", "8.6.1") | |
| DEFAULT_COMPILE_SDK = int(os.environ.get("DEFAULT_COMPILE_SDK", "34")) | |
| if not API_ID or not API_HASH or not BOT_TOKEN: | |
| raise RuntimeError("Faltan variables de entorno: API_ID, API_HASH y BOT_TOKEN.") | |
| for folder in ("jobs", "builds", "logs", "temp", "pyrogram"): | |
| (STORAGE_DIR / folder).mkdir(parents=True, exist_ok=True) | |
| JOBS_DIR = STORAGE_DIR / "jobs" | |
| SETTINGS_FILE = STORAGE_DIR / "user_settings.json" | |
| SETTINGS_LOCK = threading.Lock() | |
| USER_SETTINGS: dict[str, dict[str, str]] = {} | |
| JOB_STATE: dict[str, dict] = {} | |
| app = Client( | |
| "apk_builder_bot", | |
| api_id=API_ID, | |
| api_hash=API_HASH, | |
| bot_token=BOT_TOKEN, | |
| workdir=str(STORAGE_DIR / "pyrogram"), | |
| ) | |
| # ============================= | |
| # Utilidades de mensajes | |
| # ============================= | |
| def _clean_plain(text: str) -> str: | |
| return text.replace("`", "") | |
| async def safe_reply(message, text: str, prefer: str = "md", **kwargs): | |
| if _ParseMode is not None: | |
| if prefer in ("md", "markdown"): | |
| try: | |
| return await message.reply_text(text, parse_mode=_ParseMode.MARKDOWN, **kwargs) | |
| except Exception: | |
| pass | |
| try: | |
| return await message.reply_text(text, parse_mode=_ParseMode.HTML, **kwargs) | |
| except Exception: | |
| pass | |
| return await message.reply_text(_clean_plain(text), **kwargs) | |
| async def safe_edit(message, text: str, prefer: str = "md", **kwargs): | |
| if _ParseMode is not None: | |
| if prefer in ("md", "markdown"): | |
| try: | |
| return await message.edit_text(text, parse_mode=_ParseMode.MARKDOWN, **kwargs) | |
| except Exception: | |
| pass | |
| try: | |
| return await message.edit_text(text, parse_mode=_ParseMode.HTML, **kwargs) | |
| except Exception: | |
| pass | |
| return await message.edit_text(_clean_plain(text), **kwargs) | |
| def kb_logs(job_id: str) -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup( | |
| [[InlineKeyboardButton("📄 Ver logs", callback_data=f"logs:{job_id}")]] | |
| ) | |
| def kb_confirm(job_id: str) -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup( | |
| [ | |
| [ | |
| InlineKeyboardButton("✅ Construir APK Android", callback_data=f"go:{job_id}"), | |
| InlineKeyboardButton("❌ Cancelar", callback_data=f"cancel:{job_id}"), | |
| ] | |
| ] | |
| ) | |
| # ============================= | |
| # Preferencias por usuario | |
| # ============================= | |
| def load_user_settings() -> None: | |
| global USER_SETTINGS | |
| try: | |
| if SETTINGS_FILE.exists(): | |
| USER_SETTINGS = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) | |
| else: | |
| USER_SETTINGS = {} | |
| except Exception: | |
| USER_SETTINGS = {} | |
| def save_user_settings() -> None: | |
| SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| SETTINGS_FILE.write_text( | |
| json.dumps(USER_SETTINGS, ensure_ascii=False, indent=2), | |
| encoding="utf-8", | |
| ) | |
| def normalize_gradle_version(value: str) -> Optional[str]: | |
| value = (value or "").strip().lower() | |
| if value == "auto": | |
| return "auto" | |
| if re.fullmatch(r"\d+(?:\.\d+)+", value): | |
| return value | |
| return None | |
| def get_user_gradle(user_id: int) -> str: | |
| with SETTINGS_LOCK: | |
| return USER_SETTINGS.get(str(user_id), {}).get("gradle", "auto") | |
| def set_user_gradle(user_id: int, version: str) -> None: | |
| with SETTINGS_LOCK: | |
| USER_SETTINGS.setdefault(str(user_id), {})["gradle"] = version | |
| save_user_settings() | |
| def pick_gradle_version(user_id: int, project_dir: Path) -> str: | |
| preferred = get_user_gradle(user_id) | |
| if preferred != "auto": | |
| return preferred | |
| wrapper_version = parse_gradle_version_from_wrapper(project_dir) | |
| return wrapper_version or DEFAULT_GRADLE_VERSION | |
| def get_user_jdk(user_id: int) -> str: | |
| with SETTINGS_LOCK: | |
| value = USER_SETTINGS.get(str(user_id), {}).get("jdk", "auto") | |
| value = (value or "auto").strip().lower() | |
| return value if value in ("auto", "8", "11", "17") else "auto" | |
| def set_user_jdk(user_id: int, version: str) -> None: | |
| with SETTINGS_LOCK: | |
| USER_SETTINGS.setdefault(str(user_id), {})["jdk"] = version | |
| save_user_settings() | |
| load_user_settings() | |
| # ============================= | |
| # Utilidades de archivos/proyecto | |
| # ============================= | |
| def safe_name(name: str) -> str: | |
| name = name.strip().replace("\x00", "") | |
| name = re.sub(r"[^A-Za-z0-9._-]+", "_", name) | |
| return name[:120] or "proyecto" | |
| def safe_extract_zip(zip_path: Path, target_dir: Path) -> None: | |
| target_dir.mkdir(parents=True, exist_ok=True) | |
| root = target_dir.resolve() | |
| with zipfile.ZipFile(zip_path) as z: | |
| bad = z.testzip() | |
| if bad: | |
| raise RuntimeError(f"Archivo corrupto dentro del ZIP: {bad}") | |
| for member in z.infolist(): | |
| dest = (target_dir / member.filename).resolve() | |
| if not str(dest).startswith(str(root) + os.sep) and dest != root: | |
| raise RuntimeError("El ZIP contiene rutas inseguras.") | |
| z.extractall(target_dir) | |
| def find_project_root(extract_dir: Path) -> Path: | |
| markers = [ | |
| "gradlew", | |
| "build.gradle", | |
| "build.gradle.kts", | |
| "settings.gradle", | |
| "settings.gradle.kts", | |
| "apktool.yml", | |
| "AndroidManifest.xml", | |
| "buildozer.spec", | |
| ] | |
| if any((extract_dir / marker).exists() for marker in markers): | |
| return extract_dir | |
| children = [p for p in extract_dir.iterdir() if p.is_dir()] | |
| files = [p for p in extract_dir.iterdir() if p.is_file()] | |
| if len(children) == 1 and not files: | |
| inner = children[0] | |
| if any((inner / marker).exists() for marker in markers): | |
| return inner | |
| candidates = [] | |
| for folder in extract_dir.rglob("*"): | |
| if not folder.is_dir(): | |
| continue | |
| score = 0 | |
| if (folder / "settings.gradle").exists() or (folder / "settings.gradle.kts").exists(): | |
| score += 4 | |
| if (folder / "build.gradle").exists() or (folder / "build.gradle.kts").exists(): | |
| score += 3 | |
| if (folder / "gradlew").exists(): | |
| score += 3 | |
| if (folder / "app" / "build.gradle").exists() or (folder / "app" / "build.gradle.kts").exists(): | |
| score += 5 | |
| if (folder / "apktool.yml").exists(): | |
| score += 5 | |
| if score: | |
| candidates.append((score, folder)) | |
| if candidates: | |
| candidates.sort(key=lambda item: item[0], reverse=True) | |
| return candidates[0][1] | |
| return extract_dir | |
| def detect_android_mode(project_dir: Path) -> str: | |
| if (project_dir / "buildozer.spec").exists(): | |
| return "buildozer" | |
| if ( | |
| (project_dir / "gradlew").exists() | |
| or (project_dir / "settings.gradle").exists() | |
| or (project_dir / "settings.gradle.kts").exists() | |
| or (project_dir / "build.gradle").exists() | |
| or (project_dir / "build.gradle.kts").exists() | |
| or (project_dir / "app" / "build.gradle").exists() | |
| or (project_dir / "app" / "build.gradle.kts").exists() | |
| ): | |
| return "gradle" | |
| if ( | |
| (project_dir / "apktool.yml").exists() | |
| or (project_dir / "smali").exists() | |
| or (project_dir / "smali_classes2").exists() | |
| ): | |
| return "apktool" | |
| return "unknown" | |
| def describe_project(project_dir: Path) -> str: | |
| mode = detect_android_mode(project_dir) | |
| mode_text = { | |
| "gradle": "Gradle / Android Studio", | |
| "apktool": "apktool / smali", | |
| "buildozer": "Buildozer / Python Android", | |
| "unknown": "no detectado", | |
| }.get(mode, mode) | |
| return f"📦 Proyecto: `{project_dir.name}`\n🤖 Android: `{mode_text}`" | |
| def run_cmd(cmd: list[str], cwd: Path, log_path: Path, env: Optional[dict] = None) -> int: | |
| with log_path.open("a", encoding="utf-8", errors="ignore") as log: | |
| log.write("\n$ " + " ".join(cmd) + "\n") | |
| log.flush() | |
| process = subprocess.Popen( | |
| cmd, | |
| cwd=str(cwd), | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.STDOUT, | |
| text=True, | |
| env=env or os.environ.copy(), | |
| ) | |
| assert process.stdout is not None | |
| for line in process.stdout: | |
| log.write(line) | |
| process.wait() | |
| log.write(f"\n[exit_code={process.returncode}]\n") | |
| log.flush() | |
| return int(process.returncode or 0) | |
| def write_log(log_path: Path, text: str) -> None: | |
| with log_path.open("a", encoding="utf-8", errors="ignore") as log: | |
| log.write(text) | |
| if not text.endswith("\n"): | |
| log.write("\n") | |
| # ============================= | |
| # Parcheo Gradle Android moderno | |
| # ============================= | |
| def parse_gradle_version_from_wrapper(project_dir: Path) -> Optional[str]: | |
| prop = project_dir / "gradle" / "wrapper" / "gradle-wrapper.properties" | |
| if not prop.exists(): | |
| return None | |
| text = prop.read_text(encoding="utf-8", errors="ignore") | |
| match = re.search(r"distributionUrl\s*=.*gradle-([0-9]+(?:\.[0-9]+){1,3})-", text) | |
| return match.group(1) if match else None | |
| def gradle_major(version: str) -> int: | |
| parts = re.findall(r"\d+", version or "") | |
| return int(parts[0]) if parts else 0 | |
| def gradle_to_required_java_major(version: str) -> int: | |
| major = gradle_major(version) | |
| if major <= 4: | |
| return 8 | |
| if major <= 6: | |
| return 11 | |
| return 17 | |
| def android_plugin_major(version: str) -> int: | |
| parts = re.findall(r"\d+", version or "") | |
| return int(parts[0]) if parts else 0 | |
| def get_android_plugin_version(project_dir: Path) -> Optional[str]: | |
| for gradle_file in [project_dir / "build.gradle", *project_dir.glob("*/build.gradle")]: | |
| if not gradle_file.exists(): | |
| continue | |
| text = gradle_file.read_text(encoding="utf-8", errors="ignore") | |
| match = re.search(r"com\.android\.tools\.build:gradle:([0-9][^'\"\s)]+)", text) | |
| if match: | |
| return match.group(1) | |
| match = re.search(r"id\s+['\"]com\.android\.application['\"]\s+version\s+['\"]([^'\"]+)", text) | |
| if match: | |
| return match.group(1) | |
| return None | |
| def extract_manifest_package(project_dir: Path) -> Optional[str]: | |
| for manifest in [project_dir / "app" / "src" / "main" / "AndroidManifest.xml", *project_dir.glob("**/AndroidManifest.xml")]: | |
| if not manifest.exists(): | |
| continue | |
| text = manifest.read_text(encoding="utf-8", errors="ignore") | |
| match = re.search(r"package\s*=\s*['\"]([^'\"]+)['\"]", text) | |
| if match: | |
| return match.group(1) | |
| return None | |
| def extract_application_id(gradle_text: str) -> Optional[str]: | |
| match = re.search(r"applicationId\s+['\"]([^'\"]+)['\"]", gradle_text) | |
| return match.group(1) if match else None | |
| def inject_google_repository(text: str) -> str: | |
| if "google()" in text: | |
| return text | |
| return re.sub(r"repositories\s*\{", "repositories {\n google()", text) | |
| def patch_root_gradle(root_gradle: Path, log_path: Path) -> bool: | |
| if not root_gradle.exists() or root_gradle.suffix == ".kts": | |
| return False | |
| original = root_gradle.read_text(encoding="utf-8", errors="ignore") | |
| text = original | |
| text = inject_google_repository(text) | |
| text = text.replace("jcenter()", "mavenCentral()") | |
| text = re.sub( | |
| r"com\.android\.tools\.build:gradle:[^'\"\s)]+", | |
| f"com.android.tools.build:gradle:{DEFAULT_ANDROID_PLUGIN_VERSION}", | |
| text, | |
| ) | |
| if text != original: | |
| root_gradle.write_text(text, encoding="utf-8") | |
| write_log(log_path, f"\n🛠️ build.gradle raíz actualizado para Android Gradle Plugin {DEFAULT_ANDROID_PLUGIN_VERSION}.\n") | |
| return True | |
| return False | |
| def patch_app_gradle(app_gradle: Path, project_dir: Path, log_path: Path) -> bool: | |
| if not app_gradle.exists() or app_gradle.suffix == ".kts": | |
| return False | |
| original = app_gradle.read_text(encoding="utf-8", errors="ignore") | |
| text = original | |
| text = re.sub(r"compileSdkVersion\s+\d+", f"compileSdkVersion {DEFAULT_COMPILE_SDK}", text) | |
| text = re.sub(r"compileSdk\s+\d+", f"compileSdk {DEFAULT_COMPILE_SDK}", text) | |
| text = re.sub(r"^\s*buildToolsVersion\s+['\"][^'\"]+['\"]\s*\n", "", text, flags=re.MULTILINE) | |
| text = re.sub(r"(?m)^\s*compile\s+", " implementation ", text) | |
| text = re.sub(r"(?m)^\s*testCompile\s+", " testImplementation ", text) | |
| text = re.sub(r"(?m)^\s*androidTestCompile\s+", " androidTestImplementation ", text) | |
| if "namespace " not in text: | |
| namespace = extract_application_id(text) or extract_manifest_package(project_dir) or "com.sasuke.app" | |
| text = re.sub(r"android\s*\{", f"android {{\n namespace '{namespace}'", text, count=1) | |
| uses_legacy_http = False | |
| for java_file in project_dir.glob("**/*.java"): | |
| try: | |
| if "org.apache.http" in java_file.read_text(encoding="utf-8", errors="ignore"): | |
| uses_legacy_http = True | |
| break | |
| except Exception: | |
| pass | |
| if uses_legacy_http and "org.apache.http.legacy" not in text: | |
| text = re.sub(r"android\s*\{", "android {\n useLibrary 'org.apache.http.legacy'", text, count=1) | |
| if text != original: | |
| app_gradle.write_text(text, encoding="utf-8") | |
| write_log(log_path, f"\n🛠️ {app_gradle.relative_to(project_dir)} actualizado para SDK {DEFAULT_COMPILE_SDK}.\n") | |
| return True | |
| return False | |
| def patch_settings_gradle(project_dir: Path, log_path: Path) -> None: | |
| settings = project_dir / "settings.gradle" | |
| if settings.exists(): | |
| text = settings.read_text(encoding="utf-8", errors="ignore") | |
| if "pluginManagement" not in text and "dependencyResolutionManagement" not in text: | |
| return | |
| updated = text.replace("jcenter()", "mavenCentral()") | |
| updated = inject_google_repository(updated) | |
| if updated != text: | |
| settings.write_text(updated, encoding="utf-8") | |
| write_log(log_path, "\n🛠️ settings.gradle actualizado con repositorios Android modernos.\n") | |
| def patch_legacy_android_project(project_dir: Path, log_path: Path) -> None: | |
| plugin_version = get_android_plugin_version(project_dir) | |
| needs_modern_patch = plugin_version is None or android_plugin_major(plugin_version) < 7 | |
| if not needs_modern_patch: | |
| write_log(log_path, f"\nℹ️ Android Gradle Plugin detectado: {plugin_version}. No hace falta parche legacy.\n") | |
| return | |
| write_log(log_path, "\n🔧 Proyecto Android legacy detectado. Aplicando compatibilidad moderna...\n") | |
| patch_root_gradle(project_dir / "build.gradle", log_path) | |
| for app_gradle in project_dir.glob("**/build.gradle"): | |
| if app_gradle == project_dir / "build.gradle": | |
| continue | |
| text = app_gradle.read_text(encoding="utf-8", errors="ignore") | |
| if "com.android.application" in text or "com.android.library" in text or "android {" in text: | |
| patch_app_gradle(app_gradle, project_dir, log_path) | |
| patch_settings_gradle(project_dir, log_path) | |
| def ensure_android_sdk(project_dir: Path, log_path: Path) -> None: | |
| sdk_dir = os.environ.get("ANDROID_SDK_ROOT") or os.environ.get("ANDROID_HOME") | |
| if not sdk_dir: | |
| write_log(log_path, "\n⚠️ ANDROID_SDK_ROOT/ANDROID_HOME no está definido en el hosting.\n") | |
| return | |
| local_props = project_dir / "local.properties" | |
| existing = local_props.read_text(encoding="utf-8", errors="ignore") if local_props.exists() else "" | |
| if "sdk.dir=" not in existing: | |
| local_props.write_text(f"sdk.dir={sdk_dir}\n", encoding="utf-8") | |
| write_log(log_path, "\n✅ local.properties creado con sdk.dir.\n") | |
| # ============================= | |
| # Gradle / JDK temporal | |
| # ============================= | |
| def ensure_temp_gradle(project_dir: Path, log_path: Path, version: str) -> tuple[Path, Path]: | |
| job_root = project_dir.parent | |
| temp_dir = job_root / ".tmp_gradle" | |
| gradle_home = temp_dir / f"gradle-{version}" | |
| gradle_bin = gradle_home / "bin" / "gradle" | |
| zip_path = temp_dir / f"gradle-{version}-bin.zip" | |
| temp_dir.mkdir(parents=True, exist_ok=True) | |
| if gradle_bin.exists(): | |
| return gradle_bin, temp_dir | |
| url = os.environ.get("GRADLE_DIST_URL", f"https://services.gradle.org/distributions/gradle-{version}-bin.zip") | |
| write_log(log_path, f"\n⬇️ Descargando Gradle {version} temporal...\n") | |
| rc = run_cmd(["bash", "-lc", f"curl -L --fail -o '{zip_path}' '{url}'"], cwd=temp_dir, log_path=log_path) | |
| if rc != 0: | |
| raise RuntimeError(f"No pude descargar Gradle {version}.") | |
| rc = run_cmd(["bash", "-lc", f"rm -rf '{gradle_home}' && unzip -q '{zip_path}' -d '{temp_dir}'"], cwd=temp_dir, log_path=log_path) | |
| if rc != 0 or not gradle_bin.exists(): | |
| raise RuntimeError("No pude descomprimir Gradle.") | |
| gradle_bin.chmod(0o755) | |
| return gradle_bin, temp_dir | |
| def cleanup_dir(path: Optional[Path], log_path: Optional[Path] = None, label: str = "temporal") -> None: | |
| if not path: | |
| return | |
| try: | |
| shutil.rmtree(path, ignore_errors=True) | |
| if log_path: | |
| write_log(log_path, f"\n🧹 Carpeta {label} borrada.\n") | |
| except Exception: | |
| pass | |
| def ensure_temp_jdk(job_dir: Path, log_path: Path, java_major: int) -> tuple[Path, Path]: | |
| tmp = job_dir / f".tmp_jdk{java_major}" | |
| java_home = tmp / "jdk" | |
| marker = tmp / ".ready" | |
| tmp.mkdir(parents=True, exist_ok=True) | |
| if marker.exists() and (java_home / "bin" / "java").exists(): | |
| return java_home, tmp | |
| url = f"https://api.adoptium.net/v3/binary/latest/{java_major}/ga/linux/x64/jdk/hotspot/normal/eclipse" | |
| tar_path = tmp / f"jdk{java_major}.tar.gz" | |
| write_log(log_path, f"\n⬇️ Descargando JDK {java_major} temporal...\n") | |
| run_cmd(["bash", "-lc", f"rm -rf '{java_home}' '{tar_path}'"], cwd=tmp, log_path=log_path) | |
| rc = run_cmd(["bash", "-lc", f"curl -L --fail -o '{tar_path}' '{url}'"], cwd=tmp, log_path=log_path) | |
| if rc != 0: | |
| raise RuntimeError(f"No pude descargar JDK {java_major}.") | |
| rc = run_cmd(["bash", "-lc", f"tar -xzf '{tar_path}' -C '{tmp}'"], cwd=tmp, log_path=log_path) | |
| if rc != 0: | |
| raise RuntimeError("No pude descomprimir el JDK.") | |
| rc = run_cmd(["bash", "-lc", f"set -e; d=$(find '{tmp}' -mindepth 1 -maxdepth 1 -type d ! -name jdk | head -n1); mv \"$d\" '{java_home}'"], cwd=tmp, log_path=log_path) | |
| if rc != 0: | |
| raise RuntimeError("No pude preparar JAVA_HOME.") | |
| marker.write_text("ok", encoding="utf-8") | |
| return java_home, tmp | |
| def build_env_for_gradle(user_id: int, project_dir: Path, job_dir: Path, log_path: Path) -> tuple[dict, Optional[Path]]: | |
| env = os.environ.copy() | |
| chosen_gradle = pick_gradle_version(user_id, project_dir) | |
| java_major = gradle_to_required_java_major(chosen_gradle) | |
| jdk_pref = get_user_jdk(user_id) | |
| if jdk_pref != "auto": | |
| java_major = int(jdk_pref) | |
| try: | |
| java_home, temp_jdk = ensure_temp_jdk(job_dir, log_path, java_major) | |
| env["JAVA_HOME"] = str(java_home) | |
| env["PATH"] = str(java_home / "bin") + os.pathsep + env.get("PATH", "") | |
| write_log(log_path, f"\n✅ Java usado para build: JDK {java_major}.\n") | |
| return env, temp_jdk | |
| except Exception as exc: | |
| write_log(log_path, f"\n⚠️ No pude preparar JDK automático: {exc}\nUso Java del sistema.\n") | |
| return env, None | |
| def gradle_command(project_dir: Path, user_id: int, log_path: Path, env: dict) -> tuple[list[str], Optional[Path]]: | |
| wrapper = project_dir / "gradlew" | |
| wrapper_version = parse_gradle_version_from_wrapper(project_dir) | |
| plugin_version = get_android_plugin_version(project_dir) | |
| # Si parcheamos un proyecto viejo a Android Gradle Plugin 8+, un wrapper Gradle 2/3/4/5/6/7 | |
| # ya no sirve. En ese caso usamos Gradle temporal moderno automáticamente. | |
| if wrapper.exists() and wrapper_version: | |
| plugin_major = android_plugin_major(plugin_version or "0") | |
| wrapper_major = gradle_major(wrapper_version) | |
| if not (plugin_major >= 8 and wrapper_major < 8): | |
| try: | |
| wrapper.chmod(0o755) | |
| except Exception: | |
| pass | |
| return ["./gradlew"], None | |
| write_log( | |
| log_path, | |
| f"\n⚠️ gradlew trae Gradle {wrapper_version}, incompatible con Android Gradle Plugin {plugin_version}. " | |
| "Usando Gradle temporal moderno.\n", | |
| ) | |
| elif wrapper.exists(): | |
| try: | |
| wrapper.chmod(0o755) | |
| except Exception: | |
| pass | |
| return ["./gradlew"], None | |
| version = pick_gradle_version(user_id, project_dir) | |
| if plugin_version and android_plugin_major(plugin_version) >= 8 and gradle_major(version) < 8: | |
| version = DEFAULT_GRADLE_VERSION | |
| gradle_bin, temp_dir = ensure_temp_gradle(project_dir, log_path, version) | |
| env["PATH"] = str(gradle_bin.parent) + os.pathsep + env.get("PATH", "") | |
| return ["gradle"], temp_dir | |
| def run_gradle_task(base_cmd: list[str], project_dir: Path, log_path: Path, env: dict, task: str) -> int: | |
| return run_cmd(base_cmd + ["--no-daemon", "--stacktrace", task], cwd=project_dir, log_path=log_path, env=env) | |
| def find_apk(project_dir: Path, prefer_debug: bool = True) -> Optional[Path]: | |
| candidates = [p for p in project_dir.glob("**/*.apk") if p.is_file()] | |
| if not candidates: | |
| return None | |
| def score(path: Path) -> tuple[int, float]: | |
| name = path.name.lower() | |
| value = 0 | |
| if "debug" in name: | |
| value += 50 if prefer_debug else 10 | |
| if "release" in name: | |
| value += 20 if not prefer_debug else 5 | |
| if "unsigned" in name: | |
| value -= 30 | |
| if "unaligned" in name: | |
| value -= 20 | |
| return value, path.stat().st_mtime | |
| candidates.sort(key=score, reverse=True) | |
| return candidates[0] | |
| def ensure_debug_keystore(job_dir: Path, log_path: Path, env: dict) -> Path: | |
| keystore = job_dir / "debug.keystore" | |
| if keystore.exists(): | |
| return keystore | |
| rc = run_cmd( | |
| [ | |
| "keytool", | |
| "-genkeypair", | |
| "-v", | |
| "-keystore", | |
| str(keystore), | |
| "-storepass", | |
| "android", | |
| "-alias", | |
| "androiddebugkey", | |
| "-keypass", | |
| "android", | |
| "-keyalg", | |
| "RSA", | |
| "-keysize", | |
| "2048", | |
| "-validity", | |
| "10000", | |
| "-dname", | |
| "CN=Android Debug,O=Android,C=US", | |
| ], | |
| cwd=job_dir, | |
| log_path=log_path, | |
| env=env, | |
| ) | |
| if rc != 0 or not keystore.exists(): | |
| raise RuntimeError("No pude crear keystore de firma debug.") | |
| return keystore | |
| def sign_apk_if_needed(apk: Path, job_dir: Path, log_path: Path, env: dict) -> Path: | |
| name = apk.name.lower() | |
| if "debug" in name and "unsigned" not in name: | |
| return apk | |
| zipalign = shutil.which("zipalign", path=env.get("PATH")) or "zipalign" | |
| apksigner = shutil.which("apksigner", path=env.get("PATH")) or "apksigner" | |
| aligned = job_dir / f"{apk.stem}-aligned.apk" | |
| signed = job_dir / f"{apk.stem}-signed.apk" | |
| keystore = ensure_debug_keystore(job_dir, log_path, env) | |
| rc = run_cmd([zipalign, "-f", "-p", "4", str(apk), str(aligned)], cwd=job_dir, log_path=log_path, env=env) | |
| if rc != 0: | |
| aligned = apk | |
| rc = run_cmd( | |
| [ | |
| apksigner, | |
| "sign", | |
| "--ks", | |
| str(keystore), | |
| "--ks-pass", | |
| "pass:android", | |
| "--key-pass", | |
| "pass:android", | |
| "--out", | |
| str(signed), | |
| str(aligned), | |
| ], | |
| cwd=job_dir, | |
| log_path=log_path, | |
| env=env, | |
| ) | |
| if rc == 0 and signed.exists(): | |
| write_log(log_path, "\n✅ APK firmado con keystore debug temporal.\n") | |
| return signed | |
| write_log(log_path, "\n⚠️ No pude firmar el APK; envío el artefacto generado por el build.\n") | |
| return apk | |
| # ============================= | |
| # Construcción Android | |
| # ============================= | |
| def build_gradle_android(job_id: str, st: dict) -> None: | |
| user_id = int(st.get("user_id", 0)) | |
| project_dir = Path(st["project_dir"]) | |
| job_dir = Path(st["job_dir"]) | |
| log_path = Path(st["log_path"]) | |
| ensure_android_sdk(project_dir, log_path) | |
| patch_legacy_android_project(project_dir, log_path) | |
| env, temp_jdk = build_env_for_gradle(user_id, project_dir, job_dir, log_path) | |
| temp_gradle: Optional[Path] = None | |
| try: | |
| base_cmd, temp_gradle = gradle_command(project_dir, user_id, log_path, env) | |
| run_gradle_task(base_cmd, project_dir, log_path, env, "clean") | |
| rc = run_gradle_task(base_cmd, project_dir, log_path, env, "assembleDebug") | |
| if rc != 0: | |
| write_log(log_path, "\n⚠️ assembleDebug falló. Intentando assembleRelease...\n") | |
| rc = run_gradle_task(base_cmd, project_dir, log_path, env, "assembleRelease") | |
| if rc != 0: | |
| raise RuntimeError("Gradle no pudo generar la APK. Revisa los logs para ver el error exacto.") | |
| apk = find_apk(project_dir, prefer_debug=True) | |
| if not apk: | |
| raise RuntimeError("El build terminó, pero no encontré ningún archivo .apk.") | |
| apk = sign_apk_if_needed(apk, job_dir, log_path, env) | |
| st["apk_path"] = str(apk) | |
| write_log(log_path, f"\n✅ APK lista: {apk}\n") | |
| finally: | |
| cleanup_dir(temp_gradle, log_path, "Gradle") | |
| cleanup_dir(temp_jdk, log_path, "JDK") | |
| def build_apktool_android(job_id: str, st: dict) -> None: | |
| project_dir = Path(st["project_dir"]) | |
| job_dir = Path(st["job_dir"]) | |
| log_path = Path(st["log_path"]) | |
| out_apk = job_dir / "rebuilt-unsigned.apk" | |
| env = os.environ.copy() | |
| rc = run_cmd(["apktool", "b", str(project_dir), "-o", str(out_apk)], cwd=project_dir, log_path=log_path, env=env) | |
| if rc != 0 or not out_apk.exists(): | |
| raise RuntimeError("apktool no pudo reconstruir la APK.") | |
| st["apk_path"] = str(sign_apk_if_needed(out_apk, job_dir, log_path, env)) | |
| def build_buildozer_android(job_id: str, st: dict) -> None: | |
| project_dir = Path(st["project_dir"]) | |
| log_path = Path(st["log_path"]) | |
| env = os.environ.copy() | |
| if (project_dir / "requirements.txt").exists(): | |
| run_cmd(["bash", "-lc", "python -m pip install --no-cache-dir -r requirements.txt"], cwd=project_dir, log_path=log_path, env=env) | |
| rc = run_cmd(["bash", "-lc", "buildozer -v android debug"], cwd=project_dir, log_path=log_path, env=env) | |
| if rc != 0: | |
| raise RuntimeError("Buildozer no pudo generar la APK.") | |
| apk = find_apk(project_dir, prefer_debug=True) | |
| if not apk: | |
| raise RuntimeError("Buildozer terminó, pero no encontré ningún .apk.") | |
| st["apk_path"] = str(apk) | |
| def build_android(job_id: str) -> None: | |
| st = JOB_STATE.get(job_id) | |
| if not st: | |
| return | |
| project_dir = Path(st["project_dir"]) | |
| log_path = Path(st["log_path"]) | |
| st["done"] = False | |
| st["error"] = None | |
| try: | |
| with log_path.open("w", encoding="utf-8", errors="ignore") as log: | |
| log.write("Sasuke APK Builder - Android\n") | |
| log.write(f"Job: {job_id}\n") | |
| log.write(f"Proyecto: {project_dir}\n") | |
| log.write("\nIniciando build Android...\n") | |
| mode = detect_android_mode(project_dir) | |
| st["android_mode"] = mode | |
| if mode == "gradle": | |
| build_gradle_android(job_id, st) | |
| elif mode == "apktool": | |
| build_apktool_android(job_id, st) | |
| elif mode == "buildozer": | |
| build_buildozer_android(job_id, st) | |
| else: | |
| raise RuntimeError("No pude detectar un proyecto Android válido dentro del ZIP.") | |
| except Exception as exc: | |
| st["error"] = str(exc) | |
| write_log(log_path, f"\n❌ ERROR: {exc}\n") | |
| finally: | |
| st["done"] = True | |
| # ============================= | |
| # Comandos Telegram | |
| # ============================= | |
| async def start(_, msg): | |
| await safe_reply( | |
| msg, | |
| "😈 **Sasuke APK Builder Android**\n\n" | |
| "Envíame un **.zip** con tu proyecto Android.\n\n" | |
| "Soporta proyectos **Gradle/Android Studio**, **apktool/smali** y **Buildozer**.\n" | |
| "Cuando detecte el proyecto, te pedirá confirmar y luego enviará la APK con logs.", | |
| ) | |
| async def cmd_gradle(_, message): | |
| user_id = message.from_user.id if message.from_user else 0 | |
| parts = (message.text or "").split(maxsplit=1) | |
| if len(parts) == 1: | |
| await safe_reply( | |
| message, | |
| "⚙️ **Gradle por usuario**\n\n" | |
| f"Actual: `{get_user_gradle(user_id)}`\n\n" | |
| "Usa `/gradle auto` o una versión como `/gradle 8.7`.", | |
| ) | |
| return | |
| version = normalize_gradle_version(parts[1]) | |
| if not version: | |
| await safe_reply(message, "❌ Versión inválida. Ejemplo: `/gradle 8.7` o `/gradle auto`.") | |
| return | |
| set_user_gradle(user_id, version) | |
| await safe_reply(message, f"✅ Gradle guardado: `{version}`") | |
| async def cmd_jdk(_, message): | |
| user_id = message.from_user.id if message.from_user else 0 | |
| parts = (message.text or "").split(maxsplit=1) | |
| if len(parts) == 1: | |
| await safe_reply( | |
| message, | |
| "☕️ **JDK para compilar**\n\n" | |
| f"Actual: `{get_user_jdk(user_id)}`\n\n" | |
| "Usa `/jdk auto`, `/jdk 8`, `/jdk 11` o `/jdk 17`.", | |
| ) | |
| return | |
| version = (parts[1] or "").strip().lower() | |
| if version not in ("auto", "8", "11", "17"): | |
| await safe_reply(message, "❌ Valor inválido. Usa `/jdk auto`, `/jdk 8`, `/jdk 11` o `/jdk 17`.") | |
| return | |
| set_user_jdk(user_id, version) | |
| await safe_reply(message, f"✅ JDK guardado: `{version}`") | |
| async def handle_zip(_, msg): | |
| doc = msg.document | |
| if not doc or not doc.file_name: | |
| return | |
| if not doc.file_name.lower().endswith(".zip"): | |
| await safe_reply(msg, "⚠️ Envíame un archivo **.zip** con el proyecto Android.") | |
| return | |
| job_id = uuid.uuid4().hex[:10] | |
| job_dir = JOBS_DIR / job_id | |
| job_dir.mkdir(parents=True, exist_ok=True) | |
| zip_path = job_dir / safe_name(doc.file_name) | |
| log_path = job_dir / "build.log" | |
| status = await safe_reply( | |
| msg, | |
| f"📥 ZIP recibido ✅\n\n🆔 Job: `{job_id}`\n\nAnalizando proyecto Android...", | |
| quote=True, | |
| ) | |
| JOB_STATE[job_id] = { | |
| "chat_id": msg.chat.id, | |
| "message_id": status.id, | |
| "user_id": msg.from_user.id if msg.from_user else 0, | |
| "job_dir": str(job_dir), | |
| "zip_path": str(zip_path), | |
| "log_path": str(log_path), | |
| "project_dir": None, | |
| "apk_path": None, | |
| "done": False, | |
| "error": None, | |
| "android_mode": None, | |
| } | |
| await msg.download(file_name=str(zip_path)) | |
| extract_dir = job_dir / "src" | |
| try: | |
| safe_extract_zip(zip_path, extract_dir) | |
| project_root = find_project_root(extract_dir) | |
| JOB_STATE[job_id]["project_dir"] = str(project_root) | |
| except Exception as exc: | |
| JOB_STATE[job_id]["error"] = str(exc) | |
| JOB_STATE[job_id]["done"] = True | |
| log_path.write_text(f"Error al extraer/analizar ZIP: {exc}\n", encoding="utf-8") | |
| await safe_edit( | |
| status, | |
| f"❌ No pude leer el ZIP: `{exc}`\n\nEnvíalo de nuevo revisando que no esté corrupto.", | |
| reply_markup=kb_logs(job_id), | |
| ) | |
| return | |
| await safe_edit( | |
| status, | |
| "✅ Proyecto detectado\n\n" | |
| + describe_project(Path(JOB_STATE[job_id]["project_dir"])) | |
| + "\n\n¿Quieres construir la APK Android ahora?", | |
| reply_markup=kb_confirm(job_id), | |
| ) | |
| async def start_build(_, cq): | |
| job_id = cq.matches[0].group(1) | |
| st = JOB_STATE.get(job_id) | |
| if not st: | |
| await cq.answer("Ese job ya no existe.", show_alert=True) | |
| return | |
| if not st.get("project_dir"): | |
| await cq.answer("No encuentro el proyecto.", show_alert=True) | |
| return | |
| thread = threading.Thread(target=build_android, args=(job_id,), daemon=True) | |
| thread.start() | |
| await safe_edit( | |
| cq.message, | |
| f"🚀 Construyendo APK Android...\n\n🆔 Job: `{job_id}`\n\nPuedes abrir los logs cuando quieras 👇", | |
| reply_markup=kb_logs(job_id), | |
| ) | |
| asyncio.create_task(watch_and_send(job_id, cq.message.chat.id, cq.message.id)) | |
| await cq.answer("Build iniciado ✅") | |
| async def cancel_build(_, cq): | |
| job_id = cq.matches[0].group(1) | |
| st = JOB_STATE.get(job_id) | |
| if not st: | |
| await cq.answer("Ese job ya no existe.", show_alert=True) | |
| return | |
| st["done"] = True | |
| await safe_edit(cq.message, f"❌ Cancelado.\n\n🆔 Job: `{job_id}`") | |
| await cq.answer("Cancelado") | |
| async def watch_and_send(job_id: str, chat_id: int, status_msg_id: int) -> None: | |
| while not JOB_STATE.get(job_id, {}).get("done"): | |
| await asyncio.sleep(2) | |
| st = JOB_STATE.get(job_id, {}) | |
| log_path = Path(st["log_path"]) if st.get("log_path") else None | |
| apk = Path(st["apk_path"]) if st.get("apk_path") else None | |
| ok = bool(apk and apk.exists()) | |
| try: | |
| status = "✅ **Build Android terminado**\n\n" if ok else "❌ **Build Android falló**\n\n" | |
| status += f"🆔 Job: `{job_id}`\n" | |
| if st.get("android_mode"): | |
| status += f"Modo: `{st['android_mode']}`\n" | |
| if st.get("error"): | |
| status += f"\nError: `{st['error']}`\n" | |
| status += "\nLogs disponibles abajo 👇" | |
| await app.edit_message_text( | |
| chat_id=chat_id, | |
| message_id=status_msg_id, | |
| text=status if _ParseMode is not None else _clean_plain(status), | |
| reply_markup=kb_logs(job_id), | |
| parse_mode=_ParseMode.MARKDOWN if _ParseMode is not None else None, | |
| ) | |
| except Exception: | |
| pass | |
| if ok: | |
| caption = f"✅ APK Android lista\n🆔 Job: `{job_id}`" | |
| await app.send_document( | |
| chat_id=chat_id, | |
| document=str(apk.resolve()), | |
| caption=caption if _ParseMode is not None else _clean_plain(caption), | |
| parse_mode=_ParseMode.MARKDOWN if _ParseMode is not None else None, | |
| ) | |
| elif log_path and log_path.exists(): | |
| await app.send_document(chat_id=chat_id, document=str(log_path.resolve()), caption=f"📄 Logs - Job {job_id}") | |
| async def send_logs(_, cq): | |
| job_id = cq.matches[0].group(1) | |
| st = JOB_STATE.get(job_id) | |
| if not st: | |
| await cq.answer("Ese job ya no existe.", show_alert=True) | |
| return | |
| log_path = Path(st["log_path"]) if st.get("log_path") else None | |
| if not log_path or not log_path.exists(): | |
| await cq.answer("Todavía no hay logs.", show_alert=True) | |
| return | |
| size = log_path.stat().st_size | |
| if size > 18 * 1024 * 1024: | |
| tail = "\n".join(log_path.read_text(encoding="utf-8", errors="ignore").splitlines()[-500:]) | |
| tail_file = log_path.parent / "build_tail.txt" | |
| tail_file.write_text(tail, encoding="utf-8", errors="ignore") | |
| await cq.message.reply_document(str(tail_file), caption=f"📄 Logs finales - Job `{job_id}`") | |
| else: | |
| txt_path = log_path.parent / "build_logs.txt" | |
| if txt_path != log_path: | |
| shutil.copyfile(log_path, txt_path) | |
| await cq.message.reply_document(str(txt_path), caption=f"📄 Logs - Job `{job_id}`") | |
| await cq.answer("Logs enviados ✅") | |
| if __name__ == "__main__": | |
| print("Iniciando Sasuke APK Builder Android...") | |
| app.run() | |