from flask import Flask, request, send_file, Response import os, zipfile, subprocess, shutil, uuid app = Flask(__name__) def generate_keystore(work_dir): keystore_path = os.path.join(work_dir, "debug.keystore") cmd = ["keytool", "-genkey", "-v", "-keystore", keystore_path, "-storepass", "android", "-alias", "androiddebugkey", "-keypass", "android", "-keyalg", "RSA", "-keysize", "2048", "-validity", "10000", "-dname", "CN=AndroidDebug,O=Android,C=US"] subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return keystore_path @app.route('/') def index(): return "Backend is running. Use the HTML interface to upload." @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return "No file", 400 file = request.files['file'] unique_id = str(uuid.uuid4())[:8] work_dir = f"build_{unique_id}" os.makedirs(work_dir, exist_ok=True) zip_path = os.path.join(work_dir, "project.zip") extract_path = os.path.join(work_dir, "extract") file.save(zip_path) try: with zipfile.ZipFile(zip_path, "r") as z: z.extractall(extract_path) # Find gradlew project_root = next((root for root, _, files in os.walk(extract_path) if "gradlew" in files), None) if not project_root: return "Gradlew not found", 400 gradlew = os.path.join(project_root, "gradlew") subprocess.run(["chmod", "+x", gradlew]) # Build build_res = subprocess.run(["./gradlew", "assembleRelease", "--no-daemon"], cwd=project_root, capture_output=True, text=True) if build_res.returncode == 0: unsigned_apk = next((os.path.join(r, f) for r, _, fs in os.walk(project_root) for f in fs if f.endswith(".apk") and "release" in f), None) if unsigned_apk: ks = generate_keystore(work_dir) out_apk = os.path.abspath(os.path.join(work_dir, f"App_{unique_id}.apk")) # Sign subprocess.run(["apksigner", "sign", "--ks", ks, "--ks-pass", "pass:android", "--out", out_apk, unsigned_apk]) return send_file(out_apk, as_attachment=True, download_name=f"Build_{unique_id}.apk") return f"Build Failed: {build_res.stderr[:500]}", 500 finally: # Optional: Cleanup folder after some time or immediately # shutil.rmtree(work_dir) pass if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)