diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..409d85a --- /dev/null +++ b/.github/workflows/android.yml @@ -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})" diff --git a/README.md b/README.md index a4587e9..3f0df58 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..edd9d60 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,2 @@ +build/ +dist/ diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml new file mode 100644 index 0000000..420a68c --- /dev/null +++ b/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..bc044f7 --- /dev/null +++ b/android/README.md @@ -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= ANDROID_BUILD_TOOLS= ANDROID_JAR=/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. diff --git a/android/app.json b/android/app.json new file mode 100644 index 0000000..f9b65f7 --- /dev/null +++ b/android/app.json @@ -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" +} diff --git a/android/assets/offline.html b/android/assets/offline.html new file mode 100644 index 0000000..d201792 --- /dev/null +++ b/android/assets/offline.html @@ -0,0 +1,25 @@ + + + + + + Buddy + + + +
+ +

Buddy can't reach the internet

+

Buddy needs a connection the first time it opens. After that it also opens offline. Check your connection and try again.

+ Try again +
+ + diff --git a/android/build.py b/android/build.py new file mode 100644 index 0000000..ae5e3b1 --- /dev/null +++ b/android/build.py @@ -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/-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()) diff --git a/android/res/mipmap-xxxhdpi/ic_launcher.png b/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..f00ee0d Binary files /dev/null and b/android/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/res/values/styles.xml b/android/res/values/styles.xml new file mode 100644 index 0000000..eaf3843 --- /dev/null +++ b/android/res/values/styles.xml @@ -0,0 +1,11 @@ + + + #fff7ef + + diff --git a/android/smoke.py b/android/smoke.py new file mode 100644 index 0000000..3e8abfe --- /dev/null +++ b/android/smoke.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Install the Buddy APK on a running Android emulator, open it and check it stays up. + + python3 android/smoke.py android/dist/Buddy-android.apk + +The app is a release build, so the page inside cannot be read from outside. This checks what can be: +the package installs, the window is the app's, the process is still there after 25 s, the shell's own log +says the live page finished loading, and nothing crashed. +A screenshot (android-emulator.png) is saved next to the APK to look at. Needs adb on PATH. +""" + +import json +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def adb(*args, check=True): + try: + result = subprocess.run(["adb", *args], capture_output=True, text=True, timeout=180) + except subprocess.TimeoutExpired: + # A busy emulator can take minutes over the whole log. Where the answer is only read (check=False) + # an empty one is enough: the checks above decide, not the dump. + if check: + raise + return "" + if check and result.returncode != 0: + raise SystemExit("adb %s failed: %s" % (" ".join(args), result.stderr.strip())) + return result.stdout + + +def main(): + apk = os.path.abspath(sys.argv[1]) + out = os.path.dirname(apk) + with open(os.path.join(HERE, "app.json"), encoding="utf-8") as handle: + app = json.load(handle) + package, site, shell_tag = app["id"], app["url"], app["name"] + "Shell" + failures = [] + + def check(condition, label): + print((" ok " if condition else " FAIL ") + label, flush=True) + if not condition: + failures.append(label) + + adb("wait-for-device") + # A freshly started emulator answers adb before it can look up a name: wait until it can, so a slow + # emulator is not mistaken for an app that cannot reach its site. + host = site.split("/")[2] + for _ in range(30): + # An emulator answers no ping from outside; "PING name (address)" is enough: the name was looked up. + if adb("shell", "ping", "-c", "1", "-W", "2", host, check=False).startswith("PING "): + break + time.sleep(3) + adb("install", "-r", apk) + adb("logcat", "-c", check=False) + adb("shell", "am", "start", "-W", "-n", package + "/.MainActivity") + + first = "" + for _ in range(30): + first = adb("shell", "pidof", package, check=False).strip() + if first: + break + time.sleep(1) + check(bool(first), "the app started (pid %s)" % (first or "-")) + time.sleep(25) + later = adb("shell", "pidof", package, check=False).strip() + check(bool(later) and later == first, "the same process is still there after 25 s (pid %s)" % (later or "-")) + focus = adb("shell", "dumpsys", "window", check=False) + focused = [line.strip() for line in focus.splitlines() if "mCurrentFocus" in line or "mFocusedApp" in line] + check(any(package in line for line in focused), "its window is in front (%s)" % (focused[0] if focused else "no focus line")) + # The shell says in the log which page finished loading, and when one did not load. + said = [line for line in adb("logcat", "-d", "-v", "brief", "-s", shell_tag, check=False).splitlines() if shell_tag in line] + finished = [line.split("page finished: ", 1)[1].strip() for line in said if "page finished: " in line] + refused = [line.split("did not load: ", 1)[1].strip() for line in said if "did not load: " in line] + check(any(page.startswith(site) for page in finished), "the live page finished loading (%s)" % (finished[-1] if finished else "nothing finished")) + check(not refused, "no page failed to load (%s)" % (refused[-1] if refused else "none")) + with open(os.path.join(out, "android-emulator.png"), "wb") as handle: + handle.write(subprocess.run(["adb", "exec-out", "screencap", "-p"], capture_output=True, timeout=60).stdout) + crashes = [line for line in adb("logcat", "-d", "-b", "crash", check=False).splitlines() if package in line] + check(not crashes, "no crash in logcat") + + log = adb("logcat", "-d", "-v", "brief", check=False) + with open(os.path.join(out, "android-logcat.txt"), "w", encoding="utf-8") as handle: + handle.write(log) + if failures: + # What the phone said about the app, so a failed run can be understood from its log. + words = (package, "AndroidRuntime", "FATAL", "Killing", "has died", "WebViewFactory", "chromium", "ActivityTaskManager: Displayed") + told = [line for line in log.splitlines() if any(word in line for word in words)] + print("\nfrom logcat (%d lines about the app, the last 50):" % len(told)) + for line in told[-50:]: + print(" " + line[:220]) + print("\n%d check(s) failed" % len(failures)) + sys.exit(1) + print("\nBuddy for Android installs, opens and stays up") + + +def killed_with_play_services(folder): + """True when Android ended the app because Google Play services restarted under it. + + A freshly started emulator updates Play services in its first minutes. The WebView holds Play + services' font provider, so Android ends every app that does when Play services goes down. That + says nothing about the app, and the next start stays up. + """ + try: + with open(os.path.join(folder, "android-logcat.txt"), encoding="utf-8") as handle: + log = handle.read() + except OSError: + return False + with open(os.path.join(HERE, "app.json"), encoding="utf-8") as handle: + package = json.load(handle)["id"] + return any("Killing" in line and package in line and "com.google.android.gms" in line for line in log.splitlines()) + + +if __name__ == "__main__": + for attempt in (1, 2, 3): + try: + main() + break + except SystemExit as stopped: + folder = os.path.dirname(os.path.abspath(sys.argv[1])) + if not stopped.code or attempt == 3 or not killed_with_play_services(folder): + raise + print("\nAndroid ended the app because Google Play services restarted on this new emulator. " + "Trying again (%d of 3).\n" % (attempt + 1), flush=True) + time.sleep(20) diff --git a/android/src/io/github/juw12/buddy/MainActivity.java b/android/src/io/github/juw12/buddy/MainActivity.java new file mode 100644 index 0000000..120a92a --- /dev/null +++ b/android/src/io/github/juw12/buddy/MainActivity.java @@ -0,0 +1,283 @@ +package io.github.juw12.buddy; + +import android.Manifest; +import android.app.Activity; +import android.content.ContentValues; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.provider.MediaStore; +import android.util.Base64; +import android.webkit.GeolocationPermissions; +import android.webkit.JavascriptInterface; +import android.webkit.ValueCallback; +import android.webkit.WebChromeClient; +import android.webkit.WebResourceError; +import android.webkit.WebResourceRequest; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.Toast; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; + +/** + * Buddy for Android: one full-screen window around the live web app. The page keeps its own data + * (the WebView's storage), works offline after the first visit (its service worker), and gets what + * a plain WebView lacks from this class: sharing, saving files, picking files, location, and links + * to other sites opening in the browser. + */ +public class MainActivity extends Activity { + private static final String START_URL = "https://juw12.github.io/buddy/"; + private static final String SCOPE = "juw12.github.io/buddy"; + private static final String SHELL_VERSION = "1.0.0"; + private static final int REQUEST_LOCATION = 7; + private static final int REQUEST_FILE = 8; + + // Runs in the page: Android's WebView has no navigator.share and cannot save blob: downloads. + private static final String PAGE_SCRIPT = "(function(){" + + "if(window.__androidShell){return;}window.__androidShell=true;" + + "if(!navigator.share){" + + "navigator.share=function(d){d=d||{};" + + "if(d.files&&d.files.length){return Promise.reject(new DOMException('Files cannot be shared here','NotSupportedError'));}" + + "AndroidShell.share(String(d.title||''),String(d.text||''),String(d.url||''));return Promise.resolve();};" + + "navigator.canShare=function(d){return !(d&&d.files&&d.files.length);};}" + + "function save(a){var href=String(a.href||'');" + + "if(!a.hasAttribute('download')||(href.indexOf('blob:')!==0&&href.indexOf('data:')!==0)){return false;}" + + "var name=a.getAttribute('download')||'download';" + + "fetch(href).then(function(r){return r.blob();}).then(function(b){var reader=new FileReader();" + + "reader.onload=function(){var s=String(reader.result);" + + "AndroidShell.saveFile(name,b.type||'application/octet-stream',s.slice(s.indexOf(',')+1));};" + + "reader.readAsDataURL(b);}).catch(function(){});return true;}" + + "var click=HTMLAnchorElement.prototype.click;" + + "HTMLAnchorElement.prototype.click=function(){if(!save(this)){click.call(this);}};" + + "document.addEventListener('click',function(e){" + + "var a=e.target&&e.target.closest?e.target.closest('a[download]'):null;" + + "if(a&&e.isTrusted&&save(a)){e.preventDefault();}},true);" + + "})();"; + + private WebView web; + private ValueCallback fileCallback; + private GeolocationPermissions.Callback locationCallback; + private String locationOrigin; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + web = new WebView(this); + web.setBackgroundColor(getResources().getColor(R.color.background)); + setContentView(web); + + WebSettings settings = web.getSettings(); + settings.setJavaScriptEnabled(true); + settings.setDomStorageEnabled(true); + settings.setDatabaseEnabled(true); + settings.setGeolocationEnabled(true); + settings.setMediaPlaybackRequiresUserGesture(false); + settings.setSupportMultipleWindows(false); + settings.setUserAgentString(settings.getUserAgentString() + " BuddyAndroid/" + SHELL_VERSION); + web.addJavascriptInterface(new Bridge(), "AndroidShell"); + + web.setWebViewClient(new WebViewClient() { + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + Uri uri = request.getUrl(); + String scheme = uri.getScheme() == null ? "" : uri.getScheme(); + if (scheme.equals("file") || scheme.equals("about") || scheme.equals("blob") || scheme.equals("data")) { + return false; + } + String place = (uri.getHost() == null ? "" : uri.getHost()) + (uri.getPath() == null ? "" : uri.getPath()); + if (scheme.equals("https") && (place.equals(SCOPE) || place.startsWith(SCOPE + "/"))) { + return false; + } + openOutside(uri); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + android.util.Log.i("BuddyShell", "page finished: " + url); + view.evaluateJavascript(PAGE_SCRIPT, null); + } + + @Override + public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { + if (request.isForMainFrame()) { + // Said in the phone's log, so "no connection" can be told from a page that would not load. + android.util.Log.w("BuddyShell", "the page did not load: " + error.getErrorCode() + " " + error.getDescription() + " " + request.getUrl()); + view.loadUrl("file:///android_asset/offline.html"); + } + } + }); + + web.setWebChromeClient(new WebChromeClient() { + @Override + public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { + boolean allowed = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED + || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; + if (allowed) { + callback.invoke(origin, true, false); + return; + } + locationOrigin = origin; + locationCallback = callback; + requestPermissions(new String[] { + Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, + }, REQUEST_LOCATION); + } + + @Override + public boolean onShowFileChooser(WebView view, ValueCallback callback, FileChooserParams params) { + if (fileCallback != null) { + fileCallback.onReceiveValue(null); + } + fileCallback = callback; + try { + startActivityForResult(params.createIntent(), REQUEST_FILE); + } catch (Exception error) { + fileCallback = null; + callback.onReceiveValue(null); + } + return true; + } + }); + + if (savedInstanceState == null || web.restoreState(savedInstanceState) == null) { + web.loadUrl(START_URL); + } + } + + private void openOutside(Uri uri) { + try { + startActivity(new Intent(Intent.ACTION_VIEW, uri)); + } catch (Exception error) { + Toast.makeText(this, "No app can open this link", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) { + super.onRequestPermissionsResult(requestCode, permissions, results); + if (requestCode != REQUEST_LOCATION || locationCallback == null) { + return; + } + boolean granted = false; + for (int result : results) { + granted = granted || result == PackageManager.PERMISSION_GRANTED; + } + locationCallback.invoke(locationOrigin, granted, false); + locationCallback = null; + locationOrigin = null; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_FILE && fileCallback != null) { + fileCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data)); + fileCallback = null; + } + } + + @Override + public void onBackPressed() { + if (web.canGoBack()) { + web.goBack(); + } else { + super.onBackPressed(); + } + } + + @Override + protected void onSaveInstanceState(Bundle state) { + super.onSaveInstanceState(state); + web.saveState(state); + } + + @Override + protected void onPause() { + web.onPause(); + super.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + web.onResume(); + } + + @Override + protected void onDestroy() { + web.destroy(); + super.onDestroy(); + } + + /** Called from the page (PAGE_SCRIPT). Methods arrive on a background thread. */ + public class Bridge { + @JavascriptInterface + public String version() { + return SHELL_VERSION; + } + + @JavascriptInterface + public void share(final String title, final String text, final String url) { + runOnUiThread(new Runnable() { + @Override + public void run() { + String body = text.isEmpty() ? url : (url.isEmpty() ? text : text + "\n" + url); + Intent send = new Intent(Intent.ACTION_SEND); + send.setType("text/plain"); + send.putExtra(Intent.EXTRA_TEXT, body); + if (!title.isEmpty()) { + send.putExtra(Intent.EXTRA_SUBJECT, title); + } + try { + startActivity(Intent.createChooser(send, title.isEmpty() ? null : title)); + } catch (Exception error) { + Toast.makeText(MainActivity.this, "Nothing to share with", Toast.LENGTH_SHORT).show(); + } + } + }); + } + + @JavascriptInterface + public void saveFile(String name, String mime, String base64) { + String safeName = name.replaceAll("[\\\\/:*?\"<>|]", "_"); + String message; + try { + byte[] bytes = Base64.decode(base64, Base64.DEFAULT); + if (Build.VERSION.SDK_INT >= 29) { + ContentValues values = new ContentValues(); + values.put(MediaStore.MediaColumns.DISPLAY_NAME, safeName); + values.put(MediaStore.MediaColumns.MIME_TYPE, mime); + values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS); + Uri target = getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values); + OutputStream stream = getContentResolver().openOutputStream(target); + stream.write(bytes); + stream.close(); + message = "Saved to Downloads: " + safeName; + } else { + File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), safeName); + FileOutputStream stream = new FileOutputStream(file); + stream.write(bytes); + stream.close(); + message = "Saved: " + file.getAbsolutePath(); + } + } catch (Exception error) { + message = "Could not save " + safeName; + } + final String shown = message; + runOnUiThread(new Runnable() { + @Override + public void run() { + Toast.makeText(MainActivity.this, shown, Toast.LENGTH_LONG).show(); + } + }); + } + } +}