Files
bubble/android/build.py
T

169 lines
6.7 KiB
Python

#!/usr/bin/env python3
"""Build the bubble Android app (for the Rabbit R1) without Gradle.
Same approach as andTunes (~/Documents/lintunes/andtunes/build.py): the app
links no libraries, so the five SDK steps run directly -- aapt2 compile/link,
javac against android.jar, R8, zipalign, apksigner.
python3 android/build.py # -> android/build/VoipMessages.apk
python3 android/build.py --ship # ... + copy to resources/android/ for the desktop installer
python3 android/build.py --dev --install
# a separate "bubble (dev)" app (its own
# package, its own data) for testing on
# the device without touching the real one
The APK is debuggable on purpose: the desktop installer copies the logins and
history into the app's private storage with `run-as`, which needs it.
Stdlib only.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
VERSION_NAME = "0.7.2"
VERSION_CODE = 10
PACKAGE = "me.teafry.voipmessages"
DEV_PACKAGE = PACKAGE + ".dev"
MIN_SDK = 26
TARGET_SDK = 33
BUILD_TOOLS = "34.0.0"
HERE = Path(__file__).resolve().parent
SRC = HERE / "app" / "src" / "main"
OUT = HERE / "build"
APK_NAME = "VoipMessages.apk"
SHIP_TO = HERE.parent / "resources" / "android" / APK_NAME
# Committed on purpose, like andTunes': every build must be signed the same
# way or `adb install -r` refuses the update.
KEYSTORE = HERE / "voipmessages.keystore"
KEY_ALIAS = "voipmessages"
KEY_PASS = "voipmessages"
def _sdk() -> Path:
for env in ("ANDROID_HOME", "ANDROID_SDK_ROOT"):
if os.environ.get(env):
return Path(os.environ[env])
return Path.home() / "Android" / "Sdk"
def _java_home() -> Path:
if os.environ.get("JAVA_HOME"):
return Path(os.environ["JAVA_HOME"])
return Path("/usr/lib/jvm/java-21-openjdk")
def run(*cmd):
printable = " ".join(str(c) for c in cmd)
print(f" $ {printable[:160]}{'…' if len(printable) > 160 else ''}")
subprocess.run([str(c) for c in cmd], check=True)
def build(dev: bool) -> Path:
sdk = _sdk()
bt = sdk / "build-tools" / BUILD_TOOLS
android_jar = sdk / "platforms" / f"android-{TARGET_SDK}" / "android.jar"
jbin = _java_home() / "bin"
for need in (bt / "aapt2", android_jar, jbin / "javac"):
if not need.exists():
sys.exit(f"missing {need} -- see android/README.md")
out = OUT / ("dev" if dev else "release")
if out.exists():
shutil.rmtree(out)
gen, classes, dex = out / "gen", out / "classes", out / "dex"
for d in (gen, classes, dex):
d.mkdir(parents=True)
# aapt2 has no manifest placeholders: fill in ${applicationId} (the MMS
# file provider's authority must differ between the real and dev apps).
manifest = out / "AndroidManifest.xml"
manifest.write_text((SRC / "AndroidManifest.xml").read_text()
.replace("${applicationId}", DEV_PACKAGE if dev else PACKAGE))
print("resources")
run(bt / "aapt2", "compile", "--dir", SRC / "res", "-o", out / "res.zip")
link = [bt / "aapt2", "link", "-o", out / "base.apk",
"-I", android_jar, "--manifest", manifest,
"--java", gen, "--proguard", out / "aapt-rules.pro",
"--min-sdk-version", MIN_SDK, "--target-sdk-version", TARGET_SDK,
"--version-code", VERSION_CODE, "--version-name", VERSION_NAME,
"--debug-mode", "--auto-add-overlay"]
if dev:
# Same code, different app: its own package (so its own data) and label.
link += ["--rename-manifest-package", DEV_PACKAGE]
if dev:
# ...and its own name on the launcher (res-dev overrides app_name).
run(bt / "aapt2", "compile", "--dir", HERE / "res-dev", "-o", out / "res-dev.zip")
link += ["-R", out / "res-dev.zip"]
run(*link, out / "res.zip")
print("java")
sources = sorted(str(p) for p in (SRC / "java").rglob("*.java"))
sources += sorted(str(p) for p in gen.rglob("*.java"))
run(jbin / "javac", "--release", "11", "-Xlint:-options", "-nowarn",
"-encoding", "UTF-8", "-cp", android_jar, "-d", classes, *sources)
classes_jar = out / "classes.jar"
with zipfile.ZipFile(classes_jar, "w") as jar:
for f in classes.rglob("*.class"):
jar.write(f, f.relative_to(classes).as_posix())
print("r8")
run(jbin / "java", "-cp", bt / "lib" / "d8.jar", "com.android.tools.r8.R8",
"--release", "--min-api", MIN_SDK, "--lib", android_jar,
"--pg-conf", out / "aapt-rules.pro", "--pg-conf", HERE / "proguard.pro",
"--output", dex, classes_jar)
print("package")
unsigned = out / "unsigned.apk"
shutil.copyfile(out / "base.apk", unsigned)
with zipfile.ZipFile(unsigned, "a", zipfile.ZIP_DEFLATED) as apk:
apk.write(dex / "classes.dex", "classes.dex")
aligned = out / "aligned.apk"
run(bt / "zipalign", "-f", "-p", "4", unsigned, aligned)
final = out / (("Dev" if dev else "") + APK_NAME)
env_java = dict(os.environ, JAVA_HOME=str(_java_home()),
PATH=f"{jbin}:{os.environ.get('PATH', '')}")
print(f" $ apksigner sign … {final.name}")
subprocess.run([str(bt / "apksigner"), "sign", "--ks", str(KEYSTORE),
"--ks-key-alias", KEY_ALIAS,
"--ks-pass", f"pass:{KEY_PASS}",
"--key-pass", f"pass:{KEY_PASS}",
"--out", str(final), str(aligned)],
check=True, env=env_java)
print(f"built {final} ({final.stat().st_size // 1024} KiB, v{VERSION_NAME} / {VERSION_CODE})")
return final
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--dev", action="store_true", help="build the separate dev app (me.teafry.voipmessages.dev)")
ap.add_argument("--install", action="store_true", help="adb install -r the result and launch it")
ap.add_argument("--ship", action="store_true", help="copy the APK to resources/android/ for the desktop installer")
args = ap.parse_args()
if args.ship and args.dev:
sys.exit("--ship is for the real app, not --dev")
apk = build(args.dev)
if args.ship:
SHIP_TO.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(apk, SHIP_TO)
SHIP_TO.with_suffix(".json").write_text(json.dumps(
{"version_name": VERSION_NAME, "version_code": VERSION_CODE, "package": PACKAGE}) + "\n")
print(f"shipped to {SHIP_TO}")
if args.install:
pkg = DEV_PACKAGE if args.dev else PACKAGE
run("adb", "install", "-r", "-g", apk)
run("adb", "shell", "am", "start", "-n", f"{pkg}/{PACKAGE}.MainActivity")
if __name__ == "__main__":
main()