Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions .github/workflows/android.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
name: Buddy Android app

# Builds Buddy-android.apk (android/: a full-screen window around the web app), signs it with the key in the
# repository's secrets, opens it on an emulator and puts it on the android release.
on:
workflow_dispatch:
push:
branches: [main]
paths:
- "android/**"
- ".github/workflows/android.yml"
pull_request:
paths:
- "android/**"
- ".github/workflows/android.yml"

permissions:
contents: write

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "17"

- name: "Build and sign the .apk (no Gradle: aapt2, javac, d8, zipalign, apksigner)"
env:
KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_B64 }}
KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
run: |
tools=$(ls -d "$ANDROID_HOME"/build-tools/34.* 2>/dev/null | sort -V | tail -n 1)
if [ -z "$tools" ]; then tools=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -n 1); fi
platform="$ANDROID_HOME/platforms/android-34"
if [ ! -f "$platform/android.jar" ]; then platform=$(ls -d "$ANDROID_HOME"/platforms/android-* | sort -V | tail -n 1); fi
export ANDROID_BUILD_TOOLS="$tools" ANDROID_JAR="$platform/android.jar"
echo "build-tools: $tools, platform: $platform"
if [ -n "$KEYSTORE_B64" ]; then
echo "$KEYSTORE_B64" | base64 -d > "$RUNNER_TEMP/release.p12"
printf '%s' "$KEYSTORE_PASSWORD" > "$RUNNER_TEMP/release-password.txt"
python3 android/build.py --keystore "$RUNNER_TEMP/release.p12" --password-file "$RUNNER_TEMP/release-password.txt" --alias shells
echo "SIGNED=release" >> "$GITHUB_ENV"
else
echo "::warning::No signing key secret here (a pull request from a fork): signed with a throwaway key."
python3 android/build.py
echo "SIGNED=throwaway" >> "$GITHUB_ENV"
fi
echo "APKSIGNER=$tools/apksigner" >> "$GITHUB_ENV"

- name: The certificate is the one app.json names
if: env.SIGNED == 'release'
run: |
expected=$(python3 -c "import json; print(json.load(open('android/app.json'))['certSha256'])")
found=$("$APKSIGNER" verify --print-certs android/dist/Buddy-android.apk | sed -n 's/^Signer #1 certificate SHA-256 digest: //p')
echo "expected $expected"
echo "found $found"
[ "$expected" = "$found" ]
(cd android/dist && sha256sum Buddy-android.apk > Buddy-android.apk.sha256 && cat Buddy-android.apk.sha256)

- uses: actions/upload-artifact@v4
with:
name: buddy-android
path: android/dist/
if-no-files-found: error

emulator:
needs: build
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: buddy-android
path: android/dist
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Open the app on an emulator and check it stays up
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 34
target: google_apis
arch: x86_64
profile: pixel_6
disable-animations: true
emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -camera-back none
script: python3 android/smoke.py android/dist/Buddy-android.apk
- uses: actions/upload-artifact@v4
if: always()
with:
name: buddy-android-emulator-check
path: |
android/dist/*.png
android/dist/android-logcat.txt
retention-days: 7

publish:
needs: [build, emulator]
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: buddy-android
path: dist
# The android release keeps one address for the download. The file there is replaced only when
# android/app.json names a new versionName, never by a rebuild of the same version.
- name: Put the .apk on the android release
env:
GH_TOKEN: ${{ github.token }}
run: |
version=$(python3 -c "import json; print(json.load(open('android/app.json'))['versionName'])")
echo "$version" > dist/Buddy-android.version.txt
if ! gh release view android --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then
printf '%s\n' "Buddy for Android: a full-screen window around the web app (https://juw12.github.io/buddy/)." "" \
"Download [Buddy-android.apk](https://github.com/$GITHUB_REPOSITORY/releases/download/android/Buddy-android.apk), open the file on the phone and allow \"install unknown apps\" for your browser once." \
"It is not from a store: Android asks before it installs." > notes.md
gh release create android dist/Buddy-android.apk dist/Buddy-android.apk.sha256 dist/Buddy-android.version.txt \
--title "Buddy for Android" --notes-file notes.md --latest=false --repo "$GITHUB_REPOSITORY"
echo "Made the android release with Buddy-android.apk $version"
exit 0
fi
published=$(gh release download android --repo "$GITHUB_REPOSITORY" --pattern Buddy-android.version.txt --output - 2>/dev/null || true)
if [ "$published" = "$version" ]; then
echo "the android release already has Buddy-android.apk $version"
exit 0
fi
gh release upload android dist/Buddy-android.apk dist/Buddy-android.apk.sha256 dist/Buddy-android.version.txt --clobber --repo "$GITHUB_REPOSITORY"
echo "Buddy-android.apk on the android release is now $version (was: ${published:-none})"
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ It has three features:

Click the orange Buddy icon by the clock to open the main window. Its tabs are Home, Focus, Keyboard sounds and AI helper.

## On an Android phone

- **Android:** [`Buddy-android.apk`](https://github.com/juw12/buddy/releases/download/android/Buddy-android.apk): open the file on the phone and allow your browser to install apps once.
- **iPhone:** open https://juw12.github.io/buddy/ in Safari, tap Share, then **Add to Home Screen**.

It opens Buddy's page (https://juw12.github.io/buddy/) in a full-screen window of its own ([`android/`](android/README.md)) and changes with it. Buddy itself, the helper that points at your screen, is the Windows and Mac program below; a phone gets its page. The build is opened on an Android emulator on GitHub before it is published: it installs, opens and stays up. No real phone has run it yet.

## Run
- **App:** unzip `Buddy-win64.zip` anywhere and run `Buddy.exe`. You don't need Python.
- **From source:** run `setup.bat` once (it creates `.venv`, installs the requirements, and runs the self-test).
Expand Down
2 changes: 2 additions & 0 deletions android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build/
dist/
23 changes: 23 additions & 0 deletions android/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.github.juw12.buddy">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="Buddy"
android:icon="@mipmap/ic_launcher"
android:theme="@style/App"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:usesCleartextTraffic="false">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|uiMode|density">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
34 changes: 34 additions & 0 deletions android/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Buddy for Android

One full-screen window (Android's own WebView) around the web app (https://juw12.github.io/buddy/): the same Buddy a phone
opens in its browser, with its own icon and no address bar. `MainActivity.java` adds what a plain WebView lacks:
Share, saving a file to Downloads, picking a file, and links to other sites opening in the browser. Because it
loads the live web app, every change to the site reaches the installed app on its next start; only a change to
this folder needs a new .apk.

Get it: [`Buddy-android.apk`](https://github.com/juw12/buddy/releases/download/android/Buddy-android.apk). Open the file on the phone and allow "install unknown apps" for your browser once.

| File | What it is |
| --- | --- |
| `app.json` | name, package id, version (raise `versionCode` and `versionName` when this folder changes), and the SHA-256 of the signing certificate |
| `AndroidManifest.xml`, `res/`, `assets/offline.html` | the app's manifest, icon and colours, the page shown when the first start has no connection |
| `src/.../MainActivity.java` | the whole program (the shell Jeda, Teduh, EarlyStar and Cairn use) |
| `build.py` | builds and signs the .apk without Gradle: aapt2, javac, d8, zipalign, apksigner |
| `smoke.py` | installs the .apk on an emulator, opens it and checks it stays up |

```
JAVA_HOME=<JDK 17> ANDROID_BUILD_TOOLS=<build-tools 34> ANDROID_JAR=<platform 34>/android.jar \
python android/build.py --keystore release.p12 --password-file release-password.txt --alias shells
```

`.github/workflows/android.yml` does this on GitHub: it signs with the key in the repository's secrets,
checks the certificate is the one named in `app.json`, opens the app on an Android 14 emulator, and puts
`Buddy-android.apk` on the `android` release. The file there is replaced only when `versionName` in `app.json` is a
new one.

The signing key is not in this repository (its backup is the private `juw12/web-shells-signing`). Without `--keystore`
the build signs with a throwaway key, which is enough to try the app on your own phone.

Not checked: a real phone, and anything in the page that needs the camera, the microphone or a sign-in window
of another site. The emulator check cannot read the page inside a release build; it checks that the app
installs, opens its own window, stays up and does not crash, and keeps a screenshot.
10 changes: 10 additions & 0 deletions android/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "Buddy",
"id": "io.github.juw12.buddy",
"url": "https://juw12.github.io/buddy/",
"versionName": "1.0.0",
"versionCode": 1,
"minSdk": 24,
"targetSdk": 34,
"certSha256": "1a1af114c92c3247d47843b42ee14440e9bed7ad87112648bef0264e4d06ba36"
}
25 changes: 25 additions & 0 deletions android/assets/offline.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Buddy</title>
<style>
:root { color-scheme: light dark; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #fff7ef; color: #f4f1ea; }
main { max-width: 420px; padding: 32px; text-align: center; }
.mark { width: 64px; height: 64px; margin: 0 auto 20px; border-radius: 18px; background: #d9481f; color: #ffffff; display: grid; place-items: center; font: 700 30px/1 Georgia, serif; }
h1 { font-size: 24px; margin: 0 0 8px; }
p { color: #c9c3b6; margin: 0 0 24px; }
a { display: inline-block; padding: 12px 28px; border-radius: 14px; background: #d9481f; color: #ffffff; font-weight: 700; text-decoration: none; }
</style>
</head>
<body>
<main>
<div class="mark" aria-hidden="true">B</div>
<h1>Buddy can't reach the internet</h1>
<p>Buddy needs a connection the first time it opens. After that it also opens offline. Check your connection and try again.</p>
<a href="https://juw12.github.io/buddy/">Try again</a>
</main>
</body>
</html>
98 changes: 98 additions & 0 deletions android/build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Build the Android app in this folder without Gradle: aapt2, javac, d8, zipalign, apksigner.

python android/build.py --keystore PATH.p12 --password-file PATH.txt [--alias NAME]

Needs three things, named by environment variables:
JAVA_HOME a JDK 17 (https://adoptium.net)
ANDROID_BUILD_TOOLS the folder of Android build-tools 34 (aapt2, d8, zipalign, apksigner)
ANDROID_JAR android.jar of platform 34
Without --keystore the app is signed with a throwaway key: fine to try on your own phone, useless as
an update of the published app. The result is android/dist/<Name>-android.apk.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))


def run(*command):
print("+", " ".join(os.path.basename(part) if index == 0 else part for index, part in enumerate(command)), flush=True)
subprocess.run(command, check=True)


def main():
parser = argparse.ArgumentParser()
parser.add_argument("--keystore")
parser.add_argument("--password-file")
parser.add_argument("--alias", default="release")
args = parser.parse_args()
for name in ("JAVA_HOME", "ANDROID_BUILD_TOOLS", "ANDROID_JAR"):
if not os.environ.get(name):
raise SystemExit("Set %s (see the top of this file)" % name)
java_bin = os.path.join(os.environ["JAVA_HOME"], "bin")
tools = os.environ["ANDROID_BUILD_TOOLS"]
android_jar = os.environ["ANDROID_JAR"]
os.environ["PATH"] = java_bin + os.pathsep + os.environ["PATH"]
with open(os.path.join(HERE, "app.json"), encoding="utf-8") as handle:
app = json.load(handle)

work = os.path.join(HERE, "build")
dist = os.path.join(HERE, "dist")
shutil.rmtree(work, ignore_errors=True)
for folder in ("gen", "classes", "dex"):
os.makedirs(os.path.join(work, folder))
os.makedirs(dist, exist_ok=True)

resources = os.path.join(work, "resources.zip")
run(os.path.join(tools, "aapt2"), "compile", "--dir", os.path.join(HERE, "res"), "-o", resources)
unsigned = os.path.join(work, "unsigned.apk")
run(os.path.join(tools, "aapt2"), "link", "-o", unsigned, "-I", android_jar,
"--manifest", os.path.join(HERE, "AndroidManifest.xml"), "--java", os.path.join(work, "gen"),
"-A", os.path.join(HERE, "assets"),
"--min-sdk-version", str(app["minSdk"]), "--target-sdk-version", str(app["targetSdk"]),
"--version-code", str(app["versionCode"]), "--version-name", app["versionName"], resources)

sources = []
for root in (os.path.join(HERE, "src"), os.path.join(work, "gen")):
for folder, _, files in os.walk(root):
sources += [os.path.join(folder, name) for name in files if name.endswith(".java")]
run(os.path.join(java_bin, "javac"), "-source", "8", "-target", "8", "-Xlint:-options", "-bootclasspath", android_jar,
"-d", os.path.join(work, "classes"), *sources)
classes = []
for folder, _, files in os.walk(os.path.join(work, "classes")):
classes += [os.path.join(folder, name) for name in files if name.endswith(".class")]
run(os.path.join(tools, "d8"), "--release", "--lib", android_jar, "--min-api", str(app["minSdk"]),
"--output", os.path.join(work, "dex"), *classes)
with zipfile.ZipFile(unsigned, "a", zipfile.ZIP_DEFLATED) as archive:
archive.write(os.path.join(work, "dex", "classes.dex"), "classes.dex")

aligned = os.path.join(work, "aligned.apk")
run(os.path.join(tools, "zipalign"), "-f", "-p", "4", unsigned, aligned)
keystore, password_file, alias = args.keystore, args.password_file, args.alias
if not keystore:
keystore = os.path.join(work, "throwaway.p12")
password_file = os.path.join(work, "throwaway.txt")
alias = "throwaway"
with open(password_file, "w", encoding="utf-8") as handle:
handle.write("throwaway-key")
run(os.path.join(java_bin, "keytool"), "-genkeypair", "-keystore", keystore, "-storetype", "PKCS12",
"-storepass:file", password_file, "-alias", alias, "-keyalg", "RSA", "-keysize", "2048",
"-validity", "30", "-dname", "CN=throwaway")
print("No --keystore: signed with a throwaway key.")
result = os.path.join(dist, "%s-android.apk" % app["name"])
run(os.path.join(tools, "apksigner"), "sign", "--ks", keystore, "--ks-type", "PKCS12", "--ks-key-alias", alias,
"--ks-pass", "file:" + password_file, "--out", result, aligned)
run(os.path.join(tools, "apksigner"), "verify", "--verbose", "--print-certs", result)
if os.path.exists(result + ".idsig"):
os.remove(result + ".idsig")
print("Built %s (%d bytes)" % (result, os.path.getsize(result)))


if __name__ == "__main__":
sys.exit(main())
Binary file added android/res/mipmap-xxxhdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions android/res/values/styles.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="background">#fff7ef</color>
<style name="App" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">@color/background</item>
<item name="android:statusBarColor">@color/background</item>
<item name="android:navigationBarColor">@color/background</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowLightNavigationBar">true</item>
</style>
</resources>
Loading
Loading