diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a63c8830..77d834eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,7 @@ jobs: sh scripts/get_test.sh sh scripts/release_test.sh sh scripts/apk_test.sh + sh scripts/apk-release_test.sh changelog: if: github.event_name == 'pull_request' diff --git a/CHANGELOG.md b/CHANGELOG.md index 15198468..308f83e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,9 +14,18 @@ renames `## Unreleased` to the next patch of the newest release, such as `## v0.2.1` after `v0.2.0`, or to the version you pass, and opens a `Release v0.2.N` pull request. Once that merges, `git pull --ff-only` and run `sh scripts/release.sh --tag`. It tags the release commit on `main` and -pushes the tag once, which starts the release build. Either step takes -`--dry-run`. +pushes the tag once, which starts the release build. It then waits for the +GitHub release, builds the arm64 APK from the tag and attaches +`pitwall-phone.apk`. The signing key stays in the main checkout's +`dist/android/debug.keystore`, or at `PITWALL_APK_KEY`; it never goes to CI. +Without that key or the Android SDK/NDK, tagging still succeeds and prints +the retry command, `sh scripts/apk-release.sh vX.Y.Z`. Either release step +takes `--dry-run`. +## Unreleased + + +- Attach the Android APK to releases from the maintainer's computer. The Android app checks on launch, daily while open, or through Check for updates in Settings. Install downloads the APK with progress and a size check, then uses Android's installer and its required confirmation. Dismissing a version hides it until a newer one ships. ## v0.2.9 - Keep messages sent during a Claude Code turn in the phone chat at their transcript position after reopening it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 091259ba..75bf00c4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,6 +44,7 @@ mise exec -- go -C third_party/x-vt test -race -timeout 5m ./... sh scripts/get_test.sh sh scripts/release_test.sh sh scripts/apk_test.sh +sh scripts/apk-release_test.sh ``` ### macOS diff --git a/docs/maintainers.md b/docs/maintainers.md index d8fbe7bf..6901ff59 100644 --- a/docs/maintainers.md +++ b/docs/maintainers.md @@ -94,9 +94,18 @@ does, and what to check around it. 3. Tag that commit on `main` with `v0.2.N` and push the tag on its own. The release workflow verifies that the tagged commit belongs to `main` before building and publishes the release as the latest one. -4. Review the six platform archives, `checksums.txt`, notices and release notes +4. `scripts/release.sh --tag` waits for the release and builds the arm64 APK + in a clean temporary worktree at the tag. It uploads `pitwall-phone.apk` + with the signing key from the main checkout's `dist/android/debug.keystore`, + or `PITWALL_APK_KEY`. Keep this key on the maintainer's computer, outside CI. + Without the key or Android SDK/NDK, the script skips the APK after pushing + the tag. Run `sh scripts/apk-release.sh vX.Y.Z` once those are available. + This command also retries a failed build or upload without moving the tag. + The APK must declare its installation permission and result receiver before + upload. Prerelease tags skip the APK step because phone updates use stable releases. +5. Review `pitwall-phone.apk`, the six platform archives, `checksums.txt`, notices and release notes on the GitHub release before announcing it. -5. Push the AUR package by hand, as below. The workflow updates Homebrew and +6. Push the AUR package by hand, as below. The workflow updates Homebrew and Scoop itself. The **release tags: immutable** ruleset blocks updates and deletion of `v*` diff --git a/docs/phone.md b/docs/phone.md index 6a9f486a..e74c45d4 100644 --- a/docs/phone.md +++ b/docs/phone.md @@ -182,8 +182,24 @@ copy of the chat drops the request. The same tabs and chats also come as an Android app: pitwall's own sidebar as the home screen, and each agent tab's chat with model, effort and send on the message box. It talks to the phone page's API, so turn the -page on and reach it as above first. There is no store listing; you build -the APK and install it yourself. +page on and reach it as above first. Download +[`pitwall-phone.apk`](https://github.com/quanticstudios/pitwall/releases/latest/download/pitwall-phone.apk) +from the latest GitHub release, or build the APK yourself. There is no store listing. + +The app checks GitHub on launch and every 24 hours while open. Check daily +in Settings turns those automatic checks on or off. Check for updates runs +a check immediately, even when daily checks are off. Its status says Checking, +Up to date with the installed version, a failure reason, or which version is out. +Dismiss on the session list hides that version across launches. + +When a newer release has its APK attached, the session list and Settings offer +Install. The app downloads the APK into its cache with a progress bar, checks +the byte count against the release asset, then asks Android to install it. +Downloads and redirects must use HTTPS on GitHub's download hosts. On the first +install, allow pitwall to install unknown apps in the settings screen it opens, +then return. Android still requires a tap on its installation confirmation. +The app reports cancellation or Android's failure message and removes the +cached APK after the installation result. Android checks the signing key. ### Pictures @@ -225,12 +241,13 @@ build-tools, a platform and the NDK, and runs Java 17 through mise (`java@temurin-17`). The APK is for arm64 phones; `ARCH=amd64` builds one for the x86_64 emulator, and `ARCH=arm64,amd64` one for both. It is signed with a debug key the script makes on first use, `dist/android/debug.keystore`, -which git ignores. Keep that file: Android installs an update only over an -APK signed with the same key. +which git ignores. `PITWALL_APK_KEY` selects an existing key instead. Keep +that file: Android installs an update only over an APK signed with the same +key. A self-built APK with another key cannot take the release APK as an update. The script stamps the APK with pitwall's version: the highest stable release tag the commit contains, and the commits since. A build 3 commits -after tag v0.2.6 gets versionName `0.2.6.206003` and versionCode 206003: +after tag v0.2.6 gets versionName `v0.2.6` and versionCode 206003: the tag's three numbers as two digits each after the first, then the commit count as three. Each release and each commit after it raises the code, so Android takes every newer build over the last. A maintenance tag @@ -238,7 +255,10 @@ merged in later, such as v0.2.10 into v0.3.x, does not lower it. The script refuses a shallow clone (`git fetch --unshallow --tags` first), since it would count too few commits, a tag whose minor or patch is 100 or more, and a build more than 999 commits after its tag. `sh scripts/apk.sh --version` prints the -name, the code and the version the app shows without building. +three-part number, the code and the version the app shows without building. +The app shows the exact tag on a release build, or the tag plus commit count +and hash on a build after it. A build after a tag never offers that same tag +as an update. ### Install diff --git a/internal/ui/kit/switch.go b/internal/ui/kit/switch.go new file mode 100644 index 00000000..b9f810db --- /dev/null +++ b/internal/ui/kit/switch.go @@ -0,0 +1,50 @@ +package kit + +import ( + "image" + "image/color" + + "gioui.org/io/pointer" + "gioui.org/io/semantic" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/op/paint" + "gioui.org/widget" + + "github.com/quanticstudios/pitwall/internal/ui/theme" +) + +// Switch draws an on/off control with the theme's track and knob. +func Switch(gtx layout.Context, th *theme.Theme, c *widget.Clickable, on bool) layout.Dimensions { + return c.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + sz := image.Pt(gtx.Dp(32), gtx.Dp(18)) + hit := image.Pt(sz.X, max(sz.Y, gtx.Constraints.Min.Y)) + semantic.Switch.Add(gtx.Ops) + semantic.SelectedOp(on).Add(gtx.Ops) + semantic.EnabledOp(gtx.Enabled()).Add(gtx.Ops) + defer op.Offset(image.Pt(0, (hit.Y-sz.Y)/2)).Push(gtx.Ops).Pop() + knob, in := gtx.Dp(14), gtx.Dp(2) + track := theme.Mix(th.SurfaceElevated, th.Fg, 0.12) + ring, x := track, in + if on { + track, ring, x = th.Primary, th.Primary, sz.X-in-knob + } + if c.Hovered() { + track = theme.Mix(track, th.Fg, 0.08) + } + paint.FillShape(gtx.Ops, ring, clip.UniformRRect(image.Rectangle{Max: sz}, sz.Y/2).Op(gtx.Ops)) + paint.FillShape(gtx.Ops, track, clip.UniformRRect(image.Rect(1, 1, sz.X-1, sz.Y-1), sz.Y/2-1).Op(gtx.Ops)) + fg := th.Muted + if on { + fg = color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff} + } + paint.FillShape(gtx.Ops, fg, clip.UniformRRect(image.Rect(x, in, x+knob, in+knob), knob/2).Op(gtx.Ops)) + if gtx.Focused(c) { + FocusRing(gtx, th, image.Rectangle{Max: sz}, sz.Y/2) + } + defer clip.Rect{Max: sz}.Push(gtx.Ops).Pop() + pointer.CursorPointer.Add(gtx.Ops) + return layout.Dimensions{Size: hit} + }) +} diff --git a/internal/ui/kit/switch_test.go b/internal/ui/kit/switch_test.go new file mode 100644 index 00000000..b062d7e1 --- /dev/null +++ b/internal/ui/kit/switch_test.go @@ -0,0 +1,41 @@ +package kit + +import ( + "image" + "testing" + + "gioui.org/io/input" + "gioui.org/io/semantic" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + "gioui.org/widget" + + "github.com/quanticstudios/pitwall/internal/ui/theme" +) + +func TestSwitchTouchAreaAndSemantics(t *testing.T) { + for _, on := range []bool{false, true} { + var c widget.Clickable + var r input.Router + var ops op.Ops + gtx := layout.Context{Ops: &ops, Source: r.Source(), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Constraints{Min: image.Pt(0, 32), Max: image.Pt(100, 100)}} + d := Switch(gtx, theme.Dark(), &c, on) + if d.Size != image.Pt(32, 32) { + t.Fatalf("touch area: %v", d.Size) + } + r.Frame(&ops) + found := false + for _, n := range r.AppendSemantics(nil) { + if n.Desc.Class == semantic.Switch { + found = true + if n.Desc.Selected != on { + t.Fatal("switch misreports its state") + } + } + } + if !found { + t.Fatal("switch has no Switch semantic role") + } + } +} diff --git a/internal/ui/mobile/ApkInstall.java b/internal/ui/mobile/ApkInstall.java new file mode 100644 index 00000000..755df5c0 --- /dev/null +++ b/internal/ui/mobile/ApkInstall.java @@ -0,0 +1,214 @@ +package com.quanticstudios.pitwall; + +import android.app.Activity; +import android.app.Fragment; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageInstaller; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.provider.Settings; +import android.view.View; +import android.widget.Toast; +import java.io.File; +import java.io.FileInputStream; +import java.io.OutputStream; +import java.lang.ref.WeakReference; + +@SuppressWarnings("deprecation") +public final class ApkInstall { + private static WeakReference current = new WeakReference<>(null); + private static boolean active; + private static Intent pendingConfirm; + private static SharedPreferences prefs(Context c) { return c.getSharedPreferences("pitwall-update", Context.MODE_PRIVATE); } + + private static void report(Context c) { + if (current.get() != null) { + SharedPreferences p = prefs(c); + PhotoPick.onInstall(c.getCacheDir().getAbsolutePath(), p.getString("message", ""), p.contains("path")); + if (!p.contains("path")) p.edit().remove("message").commit(); + } + } + + private static void finish(Context c, String message, boolean abandon) { + active = false; + pendingConfirm = null; + Activity a = current.get(); + if (a != null) { + Fragment status = a.getFragmentManager().findFragmentByTag("pitwall-install-status"); + if (status != null) a.getFragmentManager().beginTransaction().remove(status).commitAllowingStateLoss(); + } + SharedPreferences p = prefs(c); + int session = p.getInt("session", -1); + if (abandon && session != -1) { + try { c.getPackageManager().getPackageInstaller().abandonSession(session); } catch (RuntimeException ignored) {} + } + String path = p.getString("path", ""); + if (!path.isEmpty()) new File(path).delete(); + p.edit().remove("path").remove("session").remove("target").putString("message", message).commit(); + report(c); + } + + private static boolean recover(Activity a) { + SharedPreferences p = prefs(a); + String path = p.getString("path", ""); + if (path.isEmpty()) return false; + long target = p.getLong("target", 0); + try { + if (target != 0 && a.getPackageManager().getPackageInfo(a.getPackageName(), 0).getLongVersionCode() >= target) { + finish(a, "Update installed.", false); + return true; + } + } catch (Exception ignored) {} + int id = p.getInt("session", -1); + PackageInstaller.SessionInfo session = id < 0 ? null : a.getPackageManager().getPackageInstaller().getSessionInfo(id); + if (!active || !new File(path).isFile() || (id >= 0 && session == null)) { + finish(a, "", true); + return true; + } + return false; + } + + public static void start(final View view, final String path) { + view.post(new Runnable() { public void run() { + Activity a = (Activity) view.getContext(); + current = new WeakReference<>(a); + boolean recovered = recover(a); + if (path.isEmpty()) { + if (!recovered) report(a); + return; + } + File apk = new File(path); + try { + if (!apk.getCanonicalFile().getParentFile().equals(a.getCacheDir().getCanonicalFile())) throw new Exception("APK is outside the app cache"); + if (prefs(a).contains("path")) { + if (!path.equals(prefs(a).getString("path", ""))) apk.delete(); + report(a); + return; + } + PackageInfo candidate = a.getPackageManager().getPackageArchiveInfo(path, 0); + PackageInfo installed = a.getPackageManager().getPackageInfo(a.getPackageName(), 0); + if (candidate == null || !a.getPackageName().equals(candidate.packageName)) throw new Exception("APK is not a pitwall update"); + if (candidate.getLongVersionCode() <= installed.getLongVersionCode()) throw new Exception("APK is not newer than this build"); + prefs(a).edit().putString("path", path).putLong("target", candidate.getLongVersionCode()).putString("message", "Preparing installation…").commit(); + active = true; + if (a.getFragmentManager().findFragmentByTag("pitwall-install-status") == null) { + a.getFragmentManager().beginTransaction().add(new Status(), "pitwall-install-status").commitAllowingStateLoss(); + } + if (!a.getPackageManager().canRequestPackageInstalls()) { + String explanation = "Allow pitwall to install updates, then return."; + prefs(a).edit().putString("message", explanation).commit(); + report(a); + Toast.makeText(a, explanation, Toast.LENGTH_LONG).show(); + a.getFragmentManager().beginTransaction().add(new Permission(), "pitwall-install").commitAllowingStateLoss(); + } else begin(a); + } catch (Exception e) { + apk.delete(); + finish(a, "Installation failed: " + e.getMessage(), true); + } + }}); + } + + public static final class Permission extends Fragment { + private boolean started; + @Override public void onCreate(Bundle state) { + super.onCreate(state); + started = state != null && state.getBoolean("started"); + } + @Override public void onSaveInstanceState(Bundle state) { + super.onSaveInstanceState(state); + state.putBoolean("started", started); + } + @Override public void onResume() { + super.onResume(); + if (!prefs(getActivity()).contains("path")) { + getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss(); + return; + } + if (started) return; + started = true; + try { startActivityForResult(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getActivity().getPackageName())), 1); } + catch (RuntimeException e) { finish(getActivity(), "Could not open install settings: " + e.getMessage(), true); } + } + @Override public void onActivityResult(int request, int result, Intent data) { + Activity a = getActivity(); + if (a.getPackageManager().canRequestPackageInstalls()) begin(a); + else finish(a, "Installation cancelled. Allow pitwall to install updates to continue.", true); + getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss(); + } + } + + public static final class Status extends Fragment { + @Override public void onResume() { + super.onResume(); + showConfirmation(getActivity()); + } + } + + private static void showConfirmation(Activity a) { + Fragment status = a.getFragmentManager().findFragmentByTag("pitwall-install-status"); + if (pendingConfirm == null || status == null || !status.isResumed()) return; + Intent confirm = pendingConfirm; + pendingConfirm = null; + // A dialog left open across a process restart still holds its old session. + try { a.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); } + catch (RuntimeException e) { finish(a, "Could not show installation confirmation: " + e.getMessage(), true); } + } + + private static void begin(final Activity a) { + prefs(a).edit().putString("message", "Preparing installation…").commit(); + report(a); + new Thread(new Runnable() { public void run() { + PackageInstaller installer = a.getPackageManager().getPackageInstaller(); + try { + File apk = new File(prefs(a).getString("path", "")); + PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL); + params.setAppPackageName(a.getPackageName()); + params.setSize(apk.length()); + if (Build.VERSION.SDK_INT >= 31) params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_REQUIRED); + int id = installer.createSession(params); + prefs(a).edit().putInt("session", id).commit(); + try (PackageInstaller.Session session = installer.openSession(id)) { + try (FileInputStream in = new FileInputStream(apk); OutputStream out = session.openWrite("pitwall-phone.apk", 0, apk.length())) { + byte[] buffer = new byte[65536]; + int n; + while ((n = in.read(buffer)) != -1) out.write(buffer, 0, n); + session.fsync(out); + } + Intent result = new Intent(a, Result.class).setAction(a.getPackageName() + ".INSTALL_RESULT"); + int flags = PendingIntent.FLAG_UPDATE_CURRENT; + if (Build.VERSION.SDK_INT >= 31) flags |= PendingIntent.FLAG_MUTABLE; + session.commit(PendingIntent.getBroadcast(a, id, result, flags).getIntentSender()); + } + } catch (final Exception e) { + a.runOnUiThread(new Runnable() { public void run() { finish(a, "Installation failed: " + e.getMessage(), true); }}); + } + }}, "pitwall-install").start(); + } + + public static final class Result extends BroadcastReceiver { + @Override public void onReceive(Context c, Intent intent) { + if (!(c.getPackageName() + ".INSTALL_RESULT").equals(intent.getAction())) return; + if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1) != prefs(c).getInt("session", -2)) return; + int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); + if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) { + prefs(c).edit().putString("message", "Confirm installation in Android.").commit(); + report(c); + pendingConfirm = intent.getParcelableExtra(Intent.EXTRA_INTENT); + Activity a = current.get(); + if (a == null) finish(c, "Return to pitwall and tap Install again.", true); + else showConfirmation(a); + return; + } + String message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE); + if (status == PackageInstaller.STATUS_SUCCESS) finish(c, "Update installed.", false); + else if (status == PackageInstaller.STATUS_FAILURE_ABORTED) finish(c, "Installation cancelled.", true); + else finish(c, "Installation failed: " + (message == null ? "Android status " + status : message), true); + } + } +} diff --git a/internal/ui/mobile/PhotoPick.java b/internal/ui/mobile/PhotoPick.java index 9878dd64..24e56a71 100644 --- a/internal/ui/mobile/PhotoPick.java +++ b/internal/ui/mobile/PhotoPick.java @@ -21,6 +21,9 @@ // A Fragment receives the picker result without changing GioActivity. @SuppressWarnings("deprecation") public final class PhotoPick { + static native void onInstall(String cache, String message, boolean busy); + public static void install(final View view, final String path) { ApkInstall.start(view, path); } + static native void onImage(byte[] data, String type, int error); // onInsertStart tells Go a keyboard image is on its way; onInsert brings its bytes or error. static native void onInsertStart(int id); diff --git a/internal/ui/mobile/app.go b/internal/ui/mobile/app.go index 4b6b1793..616b9238 100644 --- a/internal/ui/mobile/app.go +++ b/internal/ui/mobile/app.go @@ -7,6 +7,7 @@ package mobile import ( "context" "errors" + "log" "runtime" "slices" "time" @@ -52,10 +53,12 @@ func Theme() *theme.Theme { // App is the app's state; Run owns it, on the window's goroutine. Other // goroutines hand it work through post. type App struct { - w *app.Window - th *theme.Theme - dir string - ui chan func() + w *app.Window + th *theme.Theme + dir string + ui chan func() + closed chan struct{} + updates phoneUpdates fleet *phone.Fleet // nil while no machine is paired links map[string]*link @@ -98,7 +101,12 @@ type link struct { // Run runs the app in w, with its machines kept in dir, until w closes. func Run(w *app.Window, th *theme.Theme, dir string) error { - a := &App{w: w, th: th, dir: dir, ui: make(chan func(), 256)} + a := &App{w: w, th: th, dir: dir, ui: make(chan func(), 256), closed: make(chan struct{})} + var err error + a.updates.settings, err = loadPhoneSettings(dir) + if err != nil { + log.Printf("mobile: update settings: %v", err) + } a.sb.TreeOnly, a.sb.Fill, a.sb.Touch, a.sb.ExpandAll, a.sb.Answers = true, true, true, true, true // why: no machine is the phone's own; a worker's state shows on its parent's strip, a tap opens its row. a.sb.AllHosts, a.sb.SeparateWorkers, a.sb.Rev = true, true, 1 @@ -113,6 +121,13 @@ func Run(w *app.Window, th *theme.Theme, dir string) error { for { switch e := w.Event().(type) { case app.DestroyEvent: + close(a.closed) + if a.updates.cancel != nil { + a.updates.cancel() + } + if a.updates.downloadCancel != nil { + a.updates.downloadCancel() + } stopCamera() a.stop() return e.Err @@ -120,6 +135,7 @@ func Run(w *app.Window, th *theme.Theme, dir string) error { setCameraView(e) setImageView(e, func(id int) { a.post(func() { a.insertStart(id) }) }, func(id int, b []byte, err error) { a.post(func() { a.insertImage(id, b, err) }) }) + setInstallListener(a.w.Invalidate) case app.ConfigEvent: // why: back in the foreground, a stream from before the phone slept may be dead without an error. if e.Config.Focused && !a.focused { @@ -130,11 +146,15 @@ func Run(w *app.Window, th *theme.Theme, dir string) error { a.focused = e.Config.Focused case app.FrameEvent: a.drain() + if state, ok := takeInstallState(); ok { + a.applyInstallState(state) + } var gtx C // why: a tap that changes the screen lands mid-layout; the frame must show the new // screen, or it shows the old one, with its hit areas, until the next input. for range 3 { gtx = app.NewContext(&ops, e) + a.pollUpdates(gtx) paint.Fill(gtx.Ops, th.Bg) gtx.Metric.PxPerDp *= zoom gtx.Metric.PxPerSp *= zoom diff --git a/internal/ui/mobile/download.go b/internal/ui/mobile/download.go new file mode 100644 index 00000000..3b0129a8 --- /dev/null +++ b/internal/ui/mobile/download.go @@ -0,0 +1,120 @@ +package mobile + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "strings" + "time" +) + +const maxAPKSize = 512 << 20 + +// apkTestURL permits the compiled emulator fixture's loopback origin. +var apkTestURL string + +func validAPKURL(raw, local string) bool { + u, err := url.Parse(raw) + if err != nil || u.User != nil || u.Host == "" || u.Fragment != "" { + return false + } + if local != "" { + fixture, err := url.Parse(local) + if err == nil && fixture.Host == u.Host && fixture.Scheme == u.Scheme { + ip := net.ParseIP(u.Hostname()) + if ip != nil && ip.IsLoopback() { + return true + } + } + } + if u.Scheme != "https" || u.Port() != "" { + return false + } + switch u.Hostname() { + case "github.com": + return strings.HasPrefix(u.Path, "/quanticstudios/pitwall/releases/download/") + case "release-assets.githubusercontent.com", "objects.githubusercontent.com": + return true + } + return false +} + +func downloadAPK(ctx context.Context, c *http.Client, source string, size int64, cache, local string, progress func(int64)) (path string, err error) { + if !validAPKURL(source, local) { + return "", errors.New("APK URL must use HTTPS on a GitHub download host") + } + if size <= 0 || size > maxAPKSize { + return "", errors.New("invalid APK asset size") + } + client := *c + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("too many APK redirects") + } + if !validAPKURL(req.URL.String(), local) { + return errors.New("APK redirect is outside GitHub download hosts") + } + return nil + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, source, nil) + if err != nil { + return "", err + } + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("APK download: HTTP %d", resp.StatusCode) + } + if resp.ContentLength >= 0 && resp.ContentLength != size { + return "", errors.New("APK size does not match the release asset") + } + f, err := os.CreateTemp(cache, "pitwall-update-*.apk") + if err != nil { + return "", err + } + name := f.Name() + defer func() { + if err != nil { + f.Close() + os.Remove(name) + } + }() + w := &apkProgress{Writer: f, total: size, report: progress} + n, err := io.Copy(w, io.LimitReader(resp.Body, size+1)) + if err != nil { + return "", err + } + if n != size { + return "", fmt.Errorf("APK size mismatch: got %d bytes, expected %d", n, size) + } + err = errors.Join(f.Sync(), f.Close()) + if err != nil { + return "", err + } + return name, nil +} + +type apkProgress struct { + io.Writer + written, total int64 + last time.Time + report func(int64) +} + +func (w *apkProgress) Write(b []byte) (int, error) { + n, err := w.Writer.Write(b) + w.written += int64(n) + if w.report != nil && (time.Since(w.last) >= 100*time.Millisecond || w.written >= w.total) { + w.last = time.Now() + w.report(min(w.written, w.total)) + } + return n, err +} diff --git a/internal/ui/mobile/download_test.go b/internal/ui/mobile/download_test.go new file mode 100644 index 00000000..f9940287 --- /dev/null +++ b/internal/ui/mobile/download_test.go @@ -0,0 +1,102 @@ +package mobile + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "os" + "testing" +) + +func TestAPKDownloadHosts(t *testing.T) { + for _, c := range []struct { + url string + want bool + }{ + {"https://github.com/quanticstudios/pitwall/releases/download/v0.3.0/pitwall-phone.apk", true}, + {"https://github.com/other/repo/releases/download/v0.3.0/pitwall-phone.apk", false}, + {"https://github.com/quanticstudios/pitwall/releases/downloads/v0.3.0/pitwall-phone.apk", false}, + {"https://release-assets.githubusercontent.com/file", true}, + {"https://objects.githubusercontent.com/file", true}, + {"http://github.com/file", false}, + {"https://github.com.example.com/file", false}, + {"https://example.com/file", false}, + {"https://user@github.com/file", false}, + {"https://github.com:8443/file", false}, + {"https://github.com/file#fragment", false}, + {"file:///app.apk", false}, + {"http://127.0.0.1:8089/apk", false}, + } { + if got := validAPKURL(c.url, ""); got != c.want { + t.Errorf("validAPKURL(%q)=%v", c.url, got) + } + } + if !validAPKURL("http://127.0.0.1:8089/apk", "http://127.0.0.1:8089") { + t.Fatal("compiled loopback fixture refused") + } + if validAPKURL("http://example.com/apk", "http://example.com") { + t.Fatal("non-loopback fixture accepted") + } +} + +func TestDownloadAPK(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/redirect": + http.Redirect(w, r, "/apk", http.StatusFound) + case "/outside": + http.Redirect(w, r, "https://example.com/app.apk", http.StatusFound) + case "/apk": + fmt.Fprint(w, "bytes") + case "/short": + w.(http.Flusher).Flush() + fmt.Fprint(w, "four") + case "/long": + w.(http.Flusher).Flush() + fmt.Fprint(w, "sixsix") + case "/forbidden": + w.WriteHeader(http.StatusForbidden) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + for _, c := range []struct { + endpoint string + size int64 + want bool + }{ + {"/apk", 5, true}, {"/redirect", 5, true}, {"/apk", 4, false}, + {"/short", 5, false}, {"/long", 5, false}, {"/outside", 5, false}, + {"/forbidden", 5, false}, {"/apk", 0, false}, {"/apk", maxAPKSize + 1, false}, + } { + t.Run(c.endpoint+fmt.Sprint(c.size), func(t *testing.T) { + dir := t.TempDir() + var progress int64 + path, err := downloadAPK(context.Background(), srv.Client(), srv.URL+c.endpoint, c.size, dir, srv.URL, func(n int64) { progress = n }) + if (err == nil) != c.want { + t.Fatalf("download=%q,%v", path, err) + } + if c.want { + b, err := os.ReadFile(path) + if err != nil || string(b) != "bytes" || progress != c.size { + t.Fatalf("file=%q,progress=%d,error=%v", b, progress, err) + } + os.Remove(path) + } + files, err := os.ReadDir(dir) + if err != nil || len(files) != 0 { + t.Fatalf("cache has files: %v, %v", files, err) + } + }) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := downloadAPK(ctx, srv.Client(), srv.URL+"/apk", 5, t.TempDir(), srv.URL, nil); err == nil { + t.Fatal("cancelled download succeeded") + } + if _, err := downloadAPK(context.Background(), srv.Client(), srv.URL+"/apk", 5, t.TempDir(), "", nil); err == nil { + t.Fatal("accepted a non-GitHub download without fixture override") + } +} diff --git a/internal/ui/mobile/image_android.c b/internal/ui/mobile/image_android.c index 45bbfb78..72188c90 100644 --- a/internal/ui/mobile/image_android.c +++ b/internal/ui/mobile/image_android.c @@ -56,6 +56,29 @@ void pitwallPhotoBytes(JNIEnv *env, jbyteArray a, void *dst, jsize n) { (*env)->GetByteArrayRegion(env, a, 0, n, (jbyte *)dst); } +int pitwallInstall(JavaVM *vm, jobject view, const char *path) { + JNIEnv *env; + int attached = 0, rc = 0; + if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) { + if ((*vm)->AttachCurrentThread(vm, &env, NULL) != JNI_OK) return -1; + attached = 1; + } + if (photoClass == NULL) { + rc = -1; + } else { + jmethodID method = (*env)->GetStaticMethodID(env, photoClass, "install", "(Landroid/view/View;Ljava/lang/String;)V"); + jstring link = (*env)->NewStringUTF(env, path); + if (method != NULL && link != NULL) (*env)->CallStaticVoidMethod(env, photoClass, method, view, link); + if (link != NULL) (*env)->DeleteLocalRef(env, link); + } + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + rc = -1; + } + if (attached) (*vm)->DetachCurrentThread(vm); + return rc; +} + jsize pitwallPhotoLen(JNIEnv *jni, jbyteArray data) { return (*jni)->GetArrayLength(jni,data); } // pitwallChars and pitwallRelease wrap a Java string's modified UTF-8, which diff --git a/internal/ui/mobile/image_android.go b/internal/ui/mobile/image_android.go index 1dce34c9..6f855368 100644 --- a/internal/ui/mobile/image_android.go +++ b/internal/ui/mobile/image_android.go @@ -4,6 +4,7 @@ package mobile #include #include int pitwallPhoto(JavaVM *vm, jobject view, int mode); +int pitwallInstall(JavaVM *vm, jobject view, const char *path); void pitwallPhotoBytes(JNIEnv *env,jbyteArray data,void *dst,jsize n); jsize pitwallPhotoLen(JNIEnv *env,jbyteArray data); const char *pitwallChars(JNIEnv *env, jstring s); @@ -25,12 +26,63 @@ import ( const canPickImage = true +func installAPK(path string) error { + photo.Lock() + view := photo.view + photo.Unlock() + if view == 0 { + return errors.New("no Android view") + } + runtime.LockOSThread() + defer runtime.UnlockOSThread() + c := C.CString(path) + defer C.free(unsafe.Pointer(c)) + if C.pitwallInstall((*C.JavaVM)(unsafe.Pointer(app.JavaVM())), C.jobject(unsafe.Pointer(view)), c) != 0 { + return errors.New("Android could not start the installer") + } + return nil +} + var photo struct { sync.Mutex - view uintptr - done func([]byte, error) - insertStart func(id int) - insert func(id int, b []byte, err error) + view uintptr + done func([]byte, error) + insertStart func(id int) + insert func(id int, b []byte, err error) + install func() + installState *installState +} + +func setInstallListener(on func()) { + photo.Lock() + photo.install = on + photo.Unlock() + if err := installAPK(""); err != nil { + log.Printf("mobile: installer: %v", err) + } +} + +func takeInstallState() (installState, bool) { + photo.Lock() + defer photo.Unlock() + if photo.installState == nil { + return installState{}, false + } + s := *photo.installState + photo.installState = nil + return s, true +} + +//export Java_com_quanticstudios_pitwall_PhotoPick_onInstall +func Java_com_quanticstudios_pitwall_PhotoPick_onInstall(env *C.JNIEnv, cls C.jclass, cache, message C.jstring, busy C.jboolean) { + s := &installState{cache: goString(env, cache), message: goString(env, message), busy: busy != C.JNI_FALSE} + photo.Lock() + photo.installState = s + on := photo.install + photo.Unlock() + if on != nil { + on() + } } // setImageView keeps the view for the picker and the clipboard, and has it diff --git a/internal/ui/mobile/image_other.go b/internal/ui/mobile/image_other.go index 3742fed2..6fc00bb9 100644 --- a/internal/ui/mobile/image_other.go +++ b/internal/ui/mobile/image_other.go @@ -14,3 +14,7 @@ func setImageView(app.ViewEvent, func(int), func(int, []byte, error)) {} func pickImage(clipboard bool, done func([]byte, error)) { done(nil, errors.New("photo picking requires Android")) } + +func installAPK(string) error { return errors.New("installing an APK requires Android") } +func setInstallListener(func()) {} +func takeInstallState() (installState, bool) { return installState{}, false } diff --git a/internal/ui/mobile/list.go b/internal/ui/mobile/list.go index 53c477b8..6e58904f 100644 --- a/internal/ui/mobile/list.go +++ b/internal/ui/mobile/list.go @@ -100,6 +100,8 @@ func (a *App) listLayout(gtx C) { } layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(a.listHeader), + layout.Rigid(a.updateLine), + layout.Rigid(a.updateProgress), layout.Rigid(a.offlineLine), layout.Rigid(a.waiting), layout.Flexed(1, func(gtx C) D { diff --git a/internal/ui/mobile/machines.go b/internal/ui/mobile/machines.go index f0aa7c1c..0377d81f 100644 --- a/internal/ui/mobile/machines.go +++ b/internal/ui/mobile/machines.go @@ -100,6 +100,7 @@ func (a *App) machinesLayout(gtx C) { ws = append(ws, func(gtx C) D { return small(gtx, th, th.Readable(th.Red, th.Sidebar), v.note) }, gap(10)) } ws = append(ws, func(gtx C) D { return kit.WideButton(gtx, th, &v.add, kit.Secondary, kit.Large, "Add machine") }, + gap(16), func(gtx C) D { return small(gtx, th, th.Muted, "Updates") }, gap(6), a.updateToggle, gap(12), a.updateSettings, gap(16), func(gtx C) D { return layout.Center.Layout(gtx, func(gtx C) D { return label(gtx, th, th.UIFont, th.Sp(theme.Caption), th.Muted, 1, "pitwall for Android "+Version) @@ -108,7 +109,7 @@ func (a *App) machinesLayout(gtx C) { layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { return a.bar(gtx, func(gtx C) D { return iconButton(gtx, th, &v.back, icon("chevron-left")) }, func(gtx C) D { - return label(gtx, th, weight(th.UIFont, 600), th.Sp(theme.Large), th.Fg, 1, "Machines") + return label(gtx, th, weight(th.UIFont, 600), th.Sp(theme.Large), th.Fg, 1, "Settings") }, nil) }), layout.Flexed(1, func(gtx C) D { diff --git a/internal/ui/mobile/update.go b/internal/ui/mobile/update.go new file mode 100644 index 00000000..222eff14 --- /dev/null +++ b/internal/ui/mobile/update.go @@ -0,0 +1,452 @@ +package mobile + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "image" + "io" + "log" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "sync/atomic" + "time" + + "gioui.org/io/semantic" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/op/paint" + "gioui.org/widget" + + "github.com/quanticstudios/pitwall/internal/ui/kit" + "github.com/quanticstudios/pitwall/internal/ui/theme" + "github.com/quanticstudios/pitwall/internal/update" +) + +var releaseURL = "https://api.github.com/repos/quanticstudios/pitwall/releases/latest" + +var errUpdateRateLimit = errors.New("GitHub's rate limit was reached. Try again in an hour.") + +type phoneSettings struct { + CheckUpdates bool `json:"check_updates"` + Dismissed string `json:"dismissed,omitempty"` +} + +func loadPhoneSettings(dir string) (phoneSettings, error) { + s := phoneSettings{CheckUpdates: true} + b, err := os.ReadFile(filepath.Join(dir, "settings.json")) + if errors.Is(err, os.ErrNotExist) { + return s, nil + } + if err != nil { + return s, err + } + err = json.Unmarshal(b, &s) + return s, err +} + +func savePhoneSettings(dir string, s phoneSettings) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + b, err := json.Marshal(s) + if err != nil { + return err + } + f, err := os.CreateTemp(dir, ".settings-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + _, err = f.Write(b) + err = errors.Join(err, f.Sync(), f.Close()) + if err != nil { + return err + } + return os.Rename(f.Name(), filepath.Join(dir, "settings.json")) +} + +type phoneRelease struct { + Tag string `json:"tag_name"` + Assets []struct { + Name string `json:"name"` + URL string `json:"browser_download_url"` + Size int64 `json:"size"` + } `json:"assets"` +} + +func (r phoneRelease) apkURL() string { + for _, a := range r.Assets { + if a.Name == "pitwall-phone.apk" && validAPKURL(a.URL, apkTestURL) && a.Size > 0 && a.Size <= maxAPKSize { + return a.URL + } + } + return "" +} + +func (r phoneRelease) apkSize() int64 { + for _, a := range r.Assets { + if a.Name == "pitwall-phone.apk" { + return a.Size + } + } + return 0 +} + +func (r phoneRelease) available(current string) bool { + return r.apkURL() != "" && update.Newer(r.Tag, phoneVersion(current)) +} + +var phoneDescribe = regexp.MustCompile(`^(v\d+\.\d+\.\d+(?:-[A-Za-z]+\.\d+)?)(?:-\d+-g[0-9a-f]+(?:-dirty)?)?$`) + +func phoneVersion(version string) string { + v := "v" + strings.TrimPrefix(version, "v") + if m := phoneDescribe.FindStringSubmatch(v); m != nil { + return m[1] + } + return "" +} + +func (r phoneRelease) offered(current string, s phoneSettings) bool { + return s.CheckUpdates && r.available(current) && + (s.Dismissed == "" || update.Newer(r.Tag, s.Dismissed)) +} + +func fetchPhoneRelease(ctx context.Context, c *http.Client, endpoint, etag string, cached phoneRelease) (phoneRelease, string, error) { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return cached, etag, err + } + if etag != "" { + req.Header.Set("If-None-Match", etag) + } + resp, err := c.Do(req) + if err != nil { + return cached, etag, err + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusNotModified && etag != "" { + return cached, etag, nil + } + if resp.StatusCode != http.StatusOK { + if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests { + return cached, etag, errUpdateRateLimit + } + return cached, etag, fmt.Errorf("GitHub release: HTTP %d", resp.StatusCode) + } + b, err := io.ReadAll(io.LimitReader(resp.Body, (1<<20)+1)) + if err != nil { + return cached, etag, err + } + if len(b) > 1<<20 { + return cached, etag, errors.New("GitHub release exceeds 1 MiB") + } + var r phoneRelease + if err := json.Unmarshal(b, &r); err != nil { + return cached, etag, errors.New("invalid GitHub release JSON") + } + return r, resp.Header.Get("ETag"), nil +} + +type phoneUpdates struct { + settings phoneSettings + release phoneRelease + etag string + next time.Time + cancel context.CancelFunc + request int + install, dismiss, toggle, check widget.Clickable + checked bool + checkError string + cache, installNote string + installing bool + progress atomic.Int64 + downloadSize int64 + sweptCache string + downloadCancel context.CancelFunc +} + +type installState struct { + cache, message string + busy bool +} + +func (a *App) applyInstallState(s installState) { + u := &a.updates + u.cache = s.cache + if u.downloadCancel == nil || s.busy || s.message != "" { + u.installNote, u.installing = s.message, s.busy + } + if s.message == "Update installed." && u.checked { + u.installNote = "" + } + if !s.busy && u.downloadCancel == nil && s.cache != "" && u.sweptCache != s.cache { + if err := sweepAPKs(s.cache); err != nil { + log.Printf("mobile: APK cache: %v", err) + } + u.sweptCache = s.cache + } +} + +func sweepAPKs(cache string) error { + files, err := filepath.Glob(filepath.Join(cache, "pitwall-update-*.apk")) + for _, f := range files { + err = errors.Join(err, os.Remove(f)) + } + return err +} + +func (a *App) reportDownloadProgress(n int64) { + a.updates.progress.Store(n) + a.w.Invalidate() +} + +func (u *phoneUpdates) canInstall() bool { return !u.installing && u.release.available(Version) } + +func (u *phoneUpdates) lineText() string { + if u.installNote != "" { + return u.installNote + } + return "pitwall " + u.release.Tag + " is out" +} + +func (u *phoneUpdates) checkText() string { + switch { + case u.installNote != "": + return u.installNote + case u.cancel != nil: + return "Checking…" + case u.checkError != "": + return u.checkError + case u.release.available(Version): + return u.release.Tag + " is out" + case update.Newer(u.release.Tag, phoneVersion(Version)): + return u.release.Tag + " is out; its APK is not attached yet" + case u.checked: + return "Up to date (" + Version + ")" + } + return "Installed " + Version +} + +func (a *App) pollUpdates(gtx C) { + u := &a.updates + if !a.focused || !u.settings.CheckUpdates || phoneVersion(Version) == "" { + return + } + if !gtx.Now.Before(u.next) && u.cancel == nil { + a.startUpdateCheck(gtx.Now, false) + } + gtx.Execute(op.InvalidateCmd{At: u.next}) +} + +func (a *App) postUpdate(f func()) { + select { + case a.ui <- f: + a.w.Invalidate() + case <-a.closed: + } +} + +func (a *App) startUpdateCheck(now time.Time, manual bool) { + u := &a.updates + if u.cancel != nil { + return + } + u.next = now.Add(24 * time.Hour) + u.checkError = "" + if manual && !u.installing { + u.installNote = "" + } + ctx, cancel := context.WithCancel(context.Background()) + u.cancel = cancel + u.request++ + request, etag, cached := u.request, u.etag, u.release + go func() { + r, etag, err := fetchPhoneRelease(ctx, &http.Client{Timeout: 10 * time.Second}, releaseURL, etag, cached) + cancel() + if err != nil && !errors.Is(err, context.Canceled) { + log.Printf("mobile: update check: %v", err) + } + done := func() { + if u.request != request { + return + } + u.cancel = nil + if err == nil && (manual || u.settings.CheckUpdates) { + u.release, u.etag = r, etag + u.checked = true + if !u.installing { + u.installNote = "" + } + } else if err != nil { + u.checkError = "Could not check for updates: " + err.Error() + if errors.Is(err, errUpdateRateLimit) { + u.checkError = err.Error() + } + } + } + a.postUpdate(done) + }() +} + +func (a *App) startInstall() { + u := &a.updates + if !u.canInstall() { + return + } + if u.cache == "" { + u.installNote = "Could not reach Android's installer. Close and reopen pitwall." + return + } + u.installing, u.installNote = true, "Downloading update…" + u.progress.Store(0) + ctx, cancel := context.WithCancel(context.Background()) + u.downloadCancel = cancel + url, size, cache := u.release.apkURL(), u.release.apkSize(), u.cache + u.downloadSize = size + go func() { + path, err := downloadAPK(ctx, &http.Client{Timeout: 10 * time.Minute}, url, size, cache, apkTestURL, a.reportDownloadProgress) + cancel() + if err == nil { + err = installAPK(path) + } + if err != nil && path != "" { + os.Remove(path) + } + a.postUpdate(func() { + u.downloadCancel = nil + if err != nil { + u.installing, u.installNote = false, "Update failed: "+err.Error() + } + }) + }() +} + +func (a *App) saveUpdates(s phoneSettings) bool { + if err := savePhoneSettings(a.dir, s); err != nil { + a.mach.note = "Could not save update settings." + log.Printf("mobile: update settings: %v", err) + return false + } + a.updates.settings = s + return true +} + +func (a *App) updateLine(gtx C) D { + u, th := &a.updates, a.th + if !u.installing && u.installNote == "" && !u.release.offered(Version, u.settings) { + return D{} + } + if u.dismiss.Clicked(gtx) && !u.installing { + if u.installNote != "" { + u.installNote = "" + return D{} + } + s := u.settings + s.Dismissed = u.release.Tag + if a.saveUpdates(s) { + return D{} + } + } + if u.install.Clicked(gtx) { + a.startInstall() + } + note := u.lineText() + return layout.Inset{Left: pad, Right: 2}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { return label(gtx, th, th.UIFont, th.Sp(theme.Small), th.Fg, 1, note) }), + layout.Rigid(func(gtx C) D { + if !u.canInstall() { + return D{} + } + return textButton(gtx, th, &u.install, "Install") + }), + layout.Rigid(func(gtx C) D { + if u.installing { + return D{} + } + description := "Dismiss this version" + if u.installNote != "" { + description = "Clear update status" + } + semantic.DescriptionOp(description).Add(gtx.Ops) + return iconButton(gtx, th, &u.dismiss, icon("x")) + }), + ) + }) +} + +func (a *App) updateSettings(gtx C) D { + u, th := &a.updates, a.th + if u.check.Clicked(gtx) { + a.startUpdateCheck(gtx.Now, true) + } + if u.install.Clicked(gtx) { + a.startInstall() + } + note := u.checkText() + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { + return kit.WideButton(gtx, th, &u.check, kit.Secondary.When(u.cancel == nil && !u.installing), kit.Large, "Check for updates") + }), + layout.Rigid(gap(8)), + layout.Rigid(func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { return small(gtx, th, th.Fg, note) }), + layout.Rigid(func(gtx C) D { + if !u.canInstall() { + return D{} + } + return textButton(gtx, th, &u.install, "Install") + }), + ) + }), + layout.Rigid(a.updateProgress), + ) +} + +func (a *App) updateProgress(gtx C) D { + u := &a.updates + if u.downloadCancel == nil { + return D{} + } + size := image.Pt(gtx.Constraints.Max.X, gtx.Dp(4)) + defer clip.Rect{Max: size}.Push(gtx.Ops).Pop() + semantic.LabelOp("Update download").Add(gtx.Ops) + progress := float32(u.progress.Load()) / float32(u.downloadSize) + semantic.DescriptionOp(fmt.Sprintf("%d percent", int(progress*100))).Add(gtx.Ops) + paint.FillShape(gtx.Ops, a.th.Border, clip.Rect{Max: size}.Op()) + paint.FillShape(gtx.Ops, a.th.Primary, clip.Rect{Max: image.Pt(int(float32(size.X)*progress), size.Y)}.Op()) + return D{Size: size} +} + +func (a *App) updateToggle(gtx C) D { + u, th := &a.updates, a.th + if u.toggle.Clicked(gtx) { + s := u.settings + s.CheckUpdates = !s.CheckUpdates + if a.saveUpdates(s) { + if u.cancel != nil { + u.cancel() + u.cancel = nil + u.request++ + } + u.next = time.Time{} + gtx.Execute(op.InvalidateCmd{}) + } + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { return body(gtx, th, th.Fg, "Check daily") }), + layout.Rigid(func(gtx C) D { + gtx.Constraints.Min.Y = gtx.Dp(touch) + return kit.Switch(gtx, th, &u.toggle, u.settings.CheckUpdates) + }), + ) +} diff --git a/internal/ui/mobile/update_recovery_test.go b/internal/ui/mobile/update_recovery_test.go new file mode 100644 index 00000000..6ba6d6b0 --- /dev/null +++ b/internal/ui/mobile/update_recovery_test.go @@ -0,0 +1,169 @@ +package mobile + +import ( + "encoding/json" + "fmt" + "image" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "gioui.org/app" + "gioui.org/io/input" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + + "github.com/quanticstudios/pitwall/internal/ui/theme" +) + +func recoveryApp(t *testing.T) *App { + t.Helper() + old := Version + Version = "v0.2.9" + t.Cleanup(func() { Version = old }) + a := &App{w: new(app.Window), th: theme.Dark(), dir: t.TempDir(), ui: make(chan func(), 1), closed: make(chan struct{})} + a.updates.settings.CheckUpdates = true + if err := json.Unmarshal([]byte(apkReleaseJSON), &a.updates.release); err != nil { + t.Fatal(err) + } + return a +} + +func TestInstallMessageYieldsToNewRelease(t *testing.T) { + a := recoveryApp(t) + a.applyInstallState(installState{cache: t.TempDir(), message: "Update installed."}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, apkReleaseJSON) })) + defer srv.Close() + oldURL := releaseURL + releaseURL = srv.URL + t.Cleanup(func() { releaseURL = oldURL }) + a.startUpdateCheck(time.Now(), false) + select { + case done := <-a.ui: + done() + case <-time.After(5 * time.Second): + t.Fatal("no check result") + } + if got := a.updates.lineText(); got != "pitwall v0.3.0 is out" { + t.Fatalf("stale install result masks release: %q", got) + } + a.applyInstallState(installState{cache: a.updates.cache, message: "Update installed."}) + if got := a.updates.lineText(); got != "pitwall v0.3.0 is out" { + t.Fatalf("late success masks release: %q", got) + } +} + +func TestStaleInstallerUnlocksInstall(t *testing.T) { + a := recoveryApp(t) + cache := t.TempDir() + a.applyInstallState(installState{cache: cache, message: "Confirm installation in Android.", busy: true}) + if a.updates.canInstall() { + t.Fatal("offered a second active install") + } + a.applyInstallState(installState{cache: cache}) + if !a.updates.canInstall() || a.updates.installNote != "" { + t.Fatal("stale busy state still locks Install") + } +} + +func TestClearInstallNoteDoesNotDismissRelease(t *testing.T) { + a := recoveryApp(t) + a.updates.installNote = "Update failed: x" + a.updates.dismiss.Click() + gtx := layout.Context{Ops: new(op.Ops), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Constraints{Max: image.Pt(300, 100)}} + a.updateLine(gtx) + if a.updates.installNote != "" || a.updates.settings.Dismissed != "" { + t.Fatal("clearing a note dismissed the release") + } + a.updates.installing = true + a.updates.installNote = "Downloading update…" + var router input.Router + gtx.Ops.Reset() + gtx.Source = router.Source() + a.updateLine(gtx) + router.Frame(gtx.Ops) + for _, n := range router.AppendSemantics(nil) { + if strings.Contains(n.Desc.Description, "Dismiss") || strings.Contains(n.Desc.Description, "Clear update") { + t.Fatal("installing row exposes a dismiss control") + } + } +} + +func TestProgressDoesNotWaitForFrames(t *testing.T) { + a := recoveryApp(t) + a.ui <- func() {} + done := make(chan struct{}) + go func() { + for n := int64(1); n <= 10000; n++ { + a.reportDownloadProgress(n) + } + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("progress blocked on a full UI queue") + } + if a.updates.progress.Load() != 10000 || len(a.ui) != 1 { + t.Fatal("progress did not retain the latest byte count") + } +} + +func TestSweepPartialAPKsWhenIdle(t *testing.T) { + a := recoveryApp(t) + cache := t.TempDir() + for _, name := range []string{"pitwall-update-first.apk", "pitwall-update-second.apk", "keep.png"} { + if err := os.WriteFile(filepath.Join(cache, name), []byte("partial"), 0o600); err != nil { + t.Fatal(err) + } + } + a.updates.downloadCancel = func() {} + a.updates.installing = true + a.applyInstallState(installState{cache: cache}) + files, _ := os.ReadDir(cache) + if len(files) != 3 || !a.updates.installing { + t.Fatal("startup report disturbed an active download") + } + a.updates.downloadCancel = nil + a.applyInstallState(installState{cache: cache}) + files, err := os.ReadDir(cache) + if err != nil || len(files) != 1 || files[0].Name() != "keep.png" { + t.Fatalf("partial APK sweep: %v, %v", files, err) + } +} + +func TestUpdateStatusCopy(t *testing.T) { + a := recoveryApp(t) + u := &a.updates + u.release = phoneRelease{Tag: "v0.2.10"} + u.checked = true + if got := u.checkText(); got != "v0.2.10 is out; its APK is not attached yet" { + t.Fatalf("missing APK: %q", got) + } + u.cancel = func() {} + if got := u.checkText(); got != "Checking…" { + t.Fatalf("checking: %q", got) + } + u.cancel = nil + u.release.Tag = "v0.2.9" + if got := u.checkText(); got != "Up to date (v0.2.9)" { + t.Fatalf("current release: %q", got) + } + if err := json.Unmarshal([]byte(apkReleaseJSON), &u.release); err != nil { + t.Fatal(err) + } + u.release.Tag = "v0.2.10" + if !u.release.offered("v0.2.9", u.settings) { + t.Fatal("v0.2.10 not offered over v0.2.9") + } + u.cache = "" + a.startInstall() + if !strings.Contains(u.installNote, "Close and reopen pitwall") { + t.Fatalf("no recovery action: %q", u.installNote) + } +} diff --git a/internal/ui/mobile/update_test.go b/internal/ui/mobile/update_test.go new file mode 100644 index 00000000..1b25c541 --- /dev/null +++ b/internal/ui/mobile/update_test.go @@ -0,0 +1,242 @@ +package mobile + +import ( + "context" + "encoding/json" + "fmt" + "image" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "gioui.org/app" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + + "github.com/quanticstudios/pitwall/internal/ui/theme" +) + +const apkReleaseJSON = `{"tag_name":"v0.3.0","assets":[{"name":"pitwall_linux_arm64.tar.gz","browser_download_url":"https://example.com/desktop"},{"name":"pitwall-phone.apk","browser_download_url":"https://github.com/quanticstudios/pitwall/releases/download/v0.3.0/pitwall-phone.apk","size":5}]}` + +func TestPhoneReleaseOffer(t *testing.T) { + var r phoneRelease + if err := json.Unmarshal([]byte(apkReleaseJSON), &r); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + current, dismissed string + want bool + }{ + {"v0.2.9", "", true}, + {"0.2.9", "", true}, + {"v0.2.9-5-gabc123", "", true}, + {"0.2.9-5-gabc123", "", true}, + {"v0.3.0-5-gabc123", "", false}, + {"v0.3.0", "", false}, + {"v0.4.0", "", false}, + {"dev", "", false}, + {"dev-abc123", "", false}, + {"", "", false}, + {"v0.2.9", "v0.3.0", false}, + {"v0.2.9", "v0.4.0", false}, + {"v0.2.9", "v0.2.10", true}, + } { + if got := r.offered(c.current, phoneSettings{CheckUpdates: true, Dismissed: c.dismissed}); got != c.want { + t.Errorf("offer %s, dismissed %s = %v, want %v", c.current, c.dismissed, got, c.want) + } + } + if r.offered("v0.2.9", phoneSettings{}) { + t.Fatal("offered with updates disabled") + } + for _, body := range []string{ + `{"tag_name":"v0.3.0"}`, + `{"tag_name":"v0.3.0","assets":[{"name":"other.apk","browser_download_url":"https://example.com/app.apk"}]}`, + strings.ReplaceAll(apkReleaseJSON, "https://github.com/quanticstudios/pitwall/releases/download/v0.3.0/pitwall-phone.apk", "file:///app.apk"), + strings.ReplaceAll(apkReleaseJSON, "https://github.com/quanticstudios/pitwall/releases/download/v0.3.0/pitwall-phone.apk", ""), + strings.ReplaceAll(apkReleaseJSON, `"size":5`, `"size":0`), + strings.ReplaceAll(apkReleaseJSON, `"size":5`, `"size":-1`), + strings.ReplaceAll(apkReleaseJSON, `"size":5`, `"size":9999999999`), + } { + r = phoneRelease{} + if err := json.Unmarshal([]byte(body), &r); err != nil { + t.Fatal(err) + } + if r.offered("v0.2.9", phoneSettings{CheckUpdates: true}) { + t.Fatalf("offered without a usable APK: %s", body) + } + } +} + +func TestFetchPhoneRelease(t *testing.T) { + status, body, requests := http.StatusOK, apkReleaseJSON, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + if r.Method != http.MethodGet || r.Header.Get("Authorization") != "" { + t.Error("unexpected method or auth") + } + if requests > 1 && r.Header.Get("If-None-Match") != `"release-1"` { + t.Error("missing ETag") + } + w.Header().Set("ETag", `"release-1"`) + w.WriteHeader(status) + fmt.Fprint(w, body) + })) + defer srv.Close() + r, etag, err := fetchPhoneRelease(context.Background(), srv.Client(), srv.URL, "", phoneRelease{}) + if err != nil || r.Tag != "v0.3.0" || etag != `"release-1"` || r.apkURL() == "" { + t.Fatalf("200: %+v, %q, %v", r, etag, err) + } + status = http.StatusNotModified + cached, e, err := fetchPhoneRelease(context.Background(), srv.Client(), srv.URL, etag, r) + if err != nil || cached.Tag != r.Tag || cached.apkURL() != r.apkURL() || e != etag { + t.Fatalf("304: %+v, %q, %v", cached, e, err) + } + for _, c := range []struct { + status int + body string + }{ + {http.StatusForbidden, "rate limited"}, + {http.StatusOK, "{"}, + {http.StatusOK, apkReleaseJSON + "{}"}, + {http.StatusOK, strings.Repeat(" ", (1<<20)+1)}, + } { + status, body = c.status, c.body + got, e, err := fetchPhoneRelease(context.Background(), srv.Client(), srv.URL, etag, r) + if err == nil || got.Tag != r.Tag || e != etag { + t.Fatalf("failure %d: %+v, %q, %v", status, got, e, err) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := fetchPhoneRelease(ctx, srv.Client(), srv.URL, etag, r); err == nil { + t.Fatal("ignored cancellation") + } +} + +func TestManualPhoneUpdateCheck(t *testing.T) { + oldVersion, oldURL := Version, releaseURL + t.Cleanup(func() { Version, releaseURL = oldVersion, oldURL }) + for _, status := range []int{http.StatusOK, http.StatusForbidden, http.StatusTooManyRequests} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status); fmt.Fprint(w, apkReleaseJSON) })) + defer srv.Close() + Version, releaseURL = "v0.2.9", srv.URL + a := &App{w: new(app.Window), ui: make(chan func(), 10), closed: make(chan struct{})} + a.startUpdateCheck(time.Now(), true) + if a.updates.cancel == nil { + t.Fatal("manual check did not start while daily checks were off") + } + select { + case done := <-a.ui: + done() + case <-time.After(time.Second): + t.Fatal("manual check did not finish") + } + if status == http.StatusOK { + if !a.updates.checked || !a.updates.release.available(Version) { + t.Fatal("manual check dropped its result") + } + } else if a.updates.checkError != errUpdateRateLimit.Error() { + t.Fatalf("missing failure reason: %q", a.updates.checkError) + } + }) + } +} + +func TestPhoneSettings(t *testing.T) { + dir := t.TempDir() + s, err := loadPhoneSettings(dir) + if err != nil || !s.CheckUpdates || s.Dismissed != "" { + t.Fatalf("default: %+v, %v", s, err) + } + s = phoneSettings{CheckUpdates: false, Dismissed: "v0.3.0"} + if err := savePhoneSettings(dir, s); err != nil { + t.Fatal(err) + } + got, err := loadPhoneSettings(dir) + if err != nil || got != s { + t.Fatalf("reload: %+v, %v", got, err) + } + if err := os.WriteFile(filepath.Join(dir, "settings.json"), []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := loadPhoneSettings(dir); err == nil { + t.Fatal("invalid settings accepted") + } +} + +func TestPhoneUpdateSchedule(t *testing.T) { + oldVersion, oldURL := Version, releaseURL + t.Cleanup(func() { Version, releaseURL = oldVersion, oldURL }) + requests := make(chan struct{}, 10) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests <- struct{}{} + fmt.Fprint(w, apkReleaseJSON) + })) + defer srv.Close() + Version, releaseURL = "v0.2.9", srv.URL + a := &App{w: new(app.Window), ui: make(chan func(), 10), closed: make(chan struct{})} + a.updates.settings.CheckUpdates = true + gtx := layout.Context{Ops: new(op.Ops), Now: time.Now()} + a.pollUpdates(gtx) + if a.updates.cancel != nil { + t.Fatal("background app started a request") + } + a.focused = true + a.updates.settings.CheckUpdates = false + a.pollUpdates(gtx) + if a.updates.cancel != nil { + t.Fatal("disabled app started a request") + } + a.updates.settings.CheckUpdates = true + Version = "dev" + a.pollUpdates(gtx) + if a.updates.cancel != nil { + t.Fatal("dev build started a request") + } + Version = "v0.2.9" + finish := func() { + t.Helper() + select { + case <-requests: + case <-time.After(time.Second): + t.Fatal("no request") + } + select { + case f := <-a.ui: + f() + case <-time.After(time.Second): + t.Fatal("no result") + } + } + a.pollUpdates(gtx) + finish() + gtx.Now = gtx.Now.Add(24*time.Hour - time.Second) + a.pollUpdates(gtx) + if a.updates.cancel != nil { + t.Fatal("checked before 24 hours") + } + gtx.Now = gtx.Now.Add(time.Second) + a.pollUpdates(gtx) + finish() +} + +func TestPhoneUpdateLineFits(t *testing.T) { + a := &App{th: theme.Dark()} + a.updates.settings.CheckUpdates = true + if err := json.Unmarshal([]byte(apkReleaseJSON), &a.updates.release); err != nil { + t.Fatal(err) + } + old := Version + Version = "v0.2.9" + defer func() { Version = old }() + gtx := layout.Context{Ops: new(op.Ops), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Constraints{Max: image.Pt(280, 100)}} + if d := a.updateLine(gtx); d.Size.X > 280 || d.Size.Y > 44 || d.Size.Y == 0 { + t.Fatalf("update row dimensions: %v", d.Size) + } +} diff --git a/internal/ui/settings/page.go b/internal/ui/settings/page.go index d31d9736..d58f6fd1 100644 --- a/internal/ui/settings/page.go +++ b/internal/ui/settings/page.go @@ -906,31 +906,7 @@ func (p *Page) switchOf(id string, on bool, flip func()) gl.Widget { for c.Clicked(gtx) { flip() } - return c.Layout(gtx, func(gtx gl.Context) gl.Dimensions { - sz := image.Pt(gtx.Dp(32), gtx.Dp(18)) - knob, in := gtx.Dp(14), gtx.Dp(2) - track := theme.Mix(th.SurfaceElevated, th.Fg, 0.12) - ring, x := track, in - if on { - track, ring, x = th.Primary, th.Primary, sz.X-in-knob - } - if c.Hovered() { - track = theme.Mix(track, th.Fg, 0.08) - } - rrect(gtx, ring, image.Rectangle{Max: sz}, sz.Y/2) - rrect(gtx, track, image.Rect(1, 1, sz.X-1, sz.Y-1), sz.Y/2-1) - fg := th.Muted - if on { - fg = color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff} - } - rrect(gtx, fg, image.Rect(x, in, x+knob, in+knob), knob/2) - if gtx.Focused(c) { - kit.FocusRing(gtx, th, image.Rectangle{Max: sz}, sz.Y/2) - } - defer clip.Rect{Max: sz}.Push(gtx.Ops).Pop() - pointer.CursorPointer.Add(gtx.Ops) - return gl.Dimensions{Size: sz} - }) + return kit.Switch(gtx, th, c, on) } } diff --git a/internal/update/update_test.go b/internal/update/update_test.go index 22617b18..2853bff6 100644 --- a/internal/update/update_test.go +++ b/internal/update/update_test.go @@ -104,7 +104,9 @@ func release(t *testing.T, goos string, bin []byte, sums func(name, sum string) // TestInstall installs a release's tar.gz the Unix way, and its zip the // Windows way: the old binary set aside, then removed on the next start. func TestInstall(t *testing.T) { - ok := func(name, sum string) string { return "abc pitwall_other.zip\n" + sum + " " + name + "\n" } + ok := func(name, sum string) string { + return "abc pitwall-phone.apk\nabc pitwall_other.zip\n" + sum + " " + name + "\n" + } for _, goos := range []string{"linux", "windows"} { for _, c := range []struct { name string diff --git a/scripts/apk-gogio.sh b/scripts/apk-gogio.sh new file mode 100644 index 00000000..342911aa --- /dev/null +++ b/scripts/apk-gogio.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +file=${1:?usage: apk-gogio.sh androidbuild.go} +tmp=$file.tmp +trap 'rm -f "$tmp"' EXIT +grep -qF 'android:versionName="{{.Version}}"' "$file" || + { echo 'apk.sh: gogio versionName template changed' >&2; exit 1; } +sed -e 's/android:versionName="{{.Version}}"/android:versionName="v{{.Version.StringCompact}}"/' \ + -e 's###' \ + "$file" >"$tmp" +for entry in 'android:versionName="v{{.Version.StringCompact}}"' \ + 'android:name="android.permission.REQUEST_INSTALL_PACKAGES"' \ + 'android:name="com.quanticstudios.pitwall.ApkInstall$Result"'; do + [ "$(grep -cF "$entry" "$tmp" || true)" -eq 1 ] || + { echo "apk.sh: gogio manifest patch must insert exactly one $entry" >&2; exit 1; } +done +mv "$tmp" "$file" diff --git a/scripts/apk-release.sh b/scripts/apk-release.sh new file mode 100644 index 00000000..d13e9aec --- /dev/null +++ b/scripts/apk-release.sh @@ -0,0 +1,64 @@ +#!/bin/sh +set -eu + +optional= +if [ "${1:-}" = --if-available ]; then optional=1; shift; fi +[ "$#" = 1 ] || { echo 'usage: scripts/apk-release.sh [--if-available] vX.Y.Z' >&2; exit 2; } +tag=$1 +if ! printf '%s\n' "$tag" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then + echo "APK step skipped for $tag; phone updates use stable vX.Y.Z releases." + exit 0 +fi +root=$(git rev-parse --show-toplevel) +tmp= +cleanup() { + result=$? + if [ -n "$tmp" ]; then + git -C "$root" worktree remove --force "$tmp/build" 2>/dev/null || true + rm -rf "$tmp" + fi + if [ "$result" -ne 0 ]; then echo "apk-release: retry: sh scripts/apk-release.sh $tag" >&2; fi +} +trap cleanup EXIT +trap 'exit 1' HUP INT TERM +common=$(git rev-parse --path-format=absolute --git-common-dir) +key=${PITWALL_APK_KEY:-$(dirname "$common")/dist/android/debug.keystore} +sdk=${ANDROID_SDK_ROOT:-$HOME/Android/Sdk} +ndk=${ANDROID_NDK_ROOT:-$(ls -d "$sdk"/ndk/* 2>/dev/null | sort -V | tail -n 1)} +if [ ! -f "$key" ] || [ ! -d "$sdk/build-tools" ] || [ ! -d "$sdk/platforms" ] || [ ! -d "$ndk" ]; then + if [ -n "$optional" ]; then + echo "APK step skipped (signing key or Android SDK/NDK missing); run later: sh scripts/apk-release.sh $tag" + exit 0 + fi + echo 'apk-release: provide the signing key (PITWALL_APK_KEY) and Android SDK/NDK' >&2 + exit 1 +fi +key=$(CDPATH='' cd -- "$(dirname "$key")" && pwd)/$(basename "$key") + +tmp=$(mktemp -d) +git worktree add --quiet --detach "$tmp/build" "refs/tags/$tag" +cd "$tmp/build" +set -- $(sh scripts/apk.sh --version) +[ "$#" = 3 ] && [ "v$1" = "$tag" ] && [ "$3" = "$tag" ] || + { echo "apk-release: version does not match $tag: $*" >&2; exit 1; } + +attempt=0 +echo "Waiting for GitHub release $tag before building the APK" +until gh release view "$tag" >/dev/null 2>&1; do + attempt=$((attempt + 1)) + [ "$attempt" -lt 90 ] || { echo "apk-release: timed out waiting for $tag; run this command again later" >&2; exit 1; } + sleep 20 +done +PITWALL_APK_KEY=$key APK_LDFLAGS= ARCH=arm64 sh scripts/apk.sh +aapt=$(ls "$sdk"/build-tools/*/aapt 2>/dev/null | sort -V | tail -n 1) +[ -x "$aapt" ] || { echo 'apk-release: no aapt in Android build-tools' >&2; exit 1; } +permissions=$("$aapt" dump permissions dist/pitwall-phone.apk) +printf '%s\n' "$permissions" | grep -qF 'android.permission.REQUEST_INSTALL_PACKAGES' || + { echo 'apk-release: APK lacks REQUEST_INSTALL_PACKAGES' >&2; exit 1; } +manifest=$("$aapt" dump xmltree dist/pitwall-phone.apk AndroidManifest.xml) +printf '%s\n' "$manifest" | grep -qF 'com.quanticstudios.pitwall.ApkInstall$Result' || + { echo 'apk-release: APK lacks the installation result receiver' >&2; exit 1; } +set -- $(sh scripts/apk.sh --version) +[ "$#" = 3 ] && [ "v$1" = "$tag" ] && [ "$3" = "$tag" ] || + { echo "apk-release: built version does not match $tag: $*" >&2; exit 1; } +gh release upload "$tag" dist/pitwall-phone.apk --clobber diff --git a/scripts/apk-release_test.sh b/scripts/apk-release_test.sh new file mode 100644 index 00000000..373164c1 --- /dev/null +++ b/scripts/apk-release_test.sh @@ -0,0 +1,146 @@ +#!/bin/sh +set -eu + +src=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)/apk-release.sh +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +export GIT_CONFIG_GLOBAL="$tmp/gitconfig" GIT_CONFIG_NOSYSTEM=1 +export GIT_AUTHOR_NAME=dev GIT_AUTHOR_EMAIL=dev@example.com +export GIT_COMMITTER_NAME=dev GIT_COMMITTER_EMAIL=dev@example.com +: >"$GIT_CONFIG_GLOBAL" +mkdir -p "$tmp/repo/scripts" "$tmp/repo/dist/android" "$tmp/bin" "$tmp/sdk/build-tools/1" "$tmp/sdk/platforms" "$tmp/sdk/ndk/1" +export ANDROID_SDK_ROOT="$tmp/sdk" ANDROID_NDK_ROOT="$tmp/sdk/ndk/1" +unset PITWALL_APK_KEY APK_LDFLAGS +export APK_RELEASE_TEST="$tmp" +cat >"$tmp/sdk/build-tools/1/aapt" <<'SH' +#!/bin/sh +case "$2" in +permissions) [ -f "$APK_RELEASE_TEST/no-permission" ] || echo "uses-permission: name='android.permission.REQUEST_INSTALL_PACKAGES'" ;; +xmltree) [ -f "$APK_RELEASE_TEST/no-receiver" ] || echo 'com.quanticstudios.pitwall.ApkInstall$Result' ;; +esac +exit 0 +SH +chmod +x "$tmp/sdk/build-tools/1/aapt" +cat >"$tmp/bin/gh" <<'SH' +#!/bin/sh +printf '%s\n' "$*" >>"$APK_RELEASE_TEST/gh.log" +if [ "$2" = view ] && [ ! -f "$APK_RELEASE_TEST/waited" ]; then + touch "$APK_RELEASE_TEST/waited" + exit 1 +fi +if [ "$2" = upload ]; then + [ "$3 $4 $5" = 'v0.3.0 dist/pitwall-phone.apk --clobber' ] + [ "$(cat "$4")" = apk ] +fi +SH +cat >"$tmp/bin/sleep" <<'SH' +#!/bin/sh +echo waited >>"$APK_RELEASE_TEST/sleep.log" +SH +chmod +x "$tmp/bin/gh" "$tmp/bin/sleep" +export PATH="$tmp/bin:$PATH" +git init --quiet -b main "$tmp/repo" +cd "$tmp/repo" +printf 'dist/\n' >.gitignore +cp "$src" scripts/apk-release.sh +cat >scripts/apk.sh <<'SH' +#!/bin/sh +set -eu +if [ "${1:-}" = --version ]; then + echo '0.3.0 300000 v0.3.0' + exit +fi +[ "$(git status --porcelain)" = '' ] +[ "$(cat "$PITWALL_APK_KEY")" = key ] +[ "$ARCH" = arm64 ] +[ -z "$APK_LDFLAGS" ] +mkdir -p dist +echo apk >dist/pitwall-phone.apk +SH +git add . +git commit --quiet -m init +git tag v0.3.0 +echo key >dist/android/debug.keystore +out=$(sh scripts/apk-release.sh v0.3.0-beta.1) +printf '%s' "$out" | grep -qF 'APK step skipped' +[ ! -f "$tmp/gh.log" ] +sh scripts/apk-release.sh v0.3.0 >"$tmp/output" +grep -qF 'release upload v0.3.0 dist/pitwall-phone.apk --clobber' "$tmp/gh.log" +[ "$(wc -l <"$tmp/sleep.log")" -eq 1 ] +[ "$(git worktree list --porcelain | grep -c '^worktree ')" -eq 1 ] + +for missing in permission receiver; do + before=$(grep -c 'release upload' "$tmp/gh.log") + touch "$tmp/no-$missing" + if sh scripts/apk-release.sh v0.3.0 >"$tmp/output" 2>&1; then + echo "FAIL: uploaded without $missing" >&2 + exit 1 + fi + [ "$(grep -c 'release upload' "$tmp/gh.log")" -eq "$before" ] + grep -qF 'retry: sh scripts/apk-release.sh v0.3.0' "$tmp/output" + rm "$tmp/no-$missing" +done + +git worktree add --quiet -b other "$tmp/other" +(cd "$tmp/other" && sh scripts/apk-release.sh v0.3.0 >"$tmp/output") +git worktree remove "$tmp/other" + +mv dist/android/debug.keystore "$tmp/override.key" +out=$(sh scripts/apk-release.sh --if-available v0.3.0) +printf '%s' "$out" | grep -qF 'APK step skipped' +PITWALL_APK_KEY="$tmp/override.key" sh scripts/apk-release.sh v0.3.0 >"$tmp/output" +out=$(PITWALL_APK_KEY="$tmp/override.key" ANDROID_SDK_ROOT="$tmp/missing-sdk" sh scripts/apk-release.sh --if-available v0.3.0) +printf '%s' "$out" | grep -qF 'APK step skipped' + +cat >"$tmp/bin/gh" <<'SH' +#!/bin/sh +if [ "$2" = view ]; then exit 0; fi +echo 'upload-failure' >&2 +exit 1 +SH +if PITWALL_APK_KEY="$tmp/override.key" sh scripts/apk-release.sh v0.3.0 >"$tmp/output" 2>&1; then + echo 'FAIL: succeeded after an upload failure' >&2 + exit 1 +fi +grep -qF 'upload-failure' "$tmp/output" +grep -qF 'retry: sh scripts/apk-release.sh v0.3.0' "$tmp/output" +[ "$(git worktree list --porcelain | grep -c '^worktree ')" -eq 1 ] + +sed 's/v0.3.0/v0.3.0-1-gabc123/' scripts/apk.sh >scripts/apk.sh.tmp +mv scripts/apk.sh.tmp scripts/apk.sh +git add scripts/apk.sh +git commit --quiet -m mismatch +git tag v0.3.1 +cp "$tmp/gh.log" "$tmp/before" +if PITWALL_APK_KEY="$tmp/override.key" sh scripts/apk-release.sh v0.3.1 >"$tmp/output" 2>&1; then + echo 'FAIL: uploaded a mismatched version' >&2 + exit 1 +fi +cmp "$tmp/before" "$tmp/gh.log" +[ "$(git worktree list --porcelain | grep -c '^worktree ')" -eq 1 ] + +sed 's/0.3.0 300000 v0.3.0-1-gabc123/0.3.2 302000 v0.3.2/' scripts/apk.sh >scripts/apk.sh.tmp +mv scripts/apk.sh.tmp scripts/apk.sh +printf '\necho build-failure >&2\nexit 1\n' >>scripts/apk.sh +git add scripts/apk.sh +git commit --quiet -m 'build failure' +git tag v0.3.2 +if PITWALL_APK_KEY="$tmp/override.key" sh scripts/apk-release.sh v0.3.2 >"$tmp/output" 2>&1; then + echo 'FAIL: succeeded after a build failure' >&2 + exit 1 +fi +grep -qF 'build-failure' "$tmp/output" +grep -qF 'retry: sh scripts/apk-release.sh v0.3.2' "$tmp/output" +[ "$(git worktree list --porcelain | grep -c '^worktree ')" -eq 1 ] + +cat >"$tmp/bin/gh" <<'SH' +#!/bin/sh +exit 1 +SH +if PITWALL_APK_KEY="$tmp/override.key" sh scripts/apk-release.sh v0.3.0 >"$tmp/output" 2>&1; then + echo 'FAIL: succeeded without a release' >&2 + exit 1 +fi +grep -qF 'timed out' "$tmp/output" +[ "$(git worktree list --porcelain | grep -c '^worktree ')" -eq 1 ] +echo 'apk-release_test: ok' diff --git a/scripts/apk.sh b/scripts/apk.sh index e1f5b792..4ff7c8d6 100755 --- a/scripts/apk.sh +++ b/scripts/apk.sh @@ -14,7 +14,8 @@ tag=$(git tag --merged HEAD --list 'v[0-9]*' --sort=-v:refname | grep -E '^v[0-9 [ -n "$tag" ] || { echo "apk.sh: no vX.Y.Z tag in reach; run git fetch --tags" >&2; exit 1; } # warn: git describe --match miscounts across merges; rev-list counts exactly. n=$(git rev-list --count "refs/tags/$tag..HEAD") -describe=$tag-$n-g$(git rev-parse --short HEAD) +describe=$tag +[ "$n" = 0 ] || describe=$tag-$n-g$(git rev-parse --short HEAD) git diff --quiet HEAD -- || describe=$describe-dirty v=${tag#v} major=${v%%.*} @@ -28,7 +29,7 @@ esac { echo "apk.sh: $describe does not fit a versionCode: minor and patch under 100, at most 999 commits after the tag" >&2; exit 1; } name=$major.$minor.$patch code=$((((major * 100 + minor) * 100 + patch) * 1000 + n)) -shown=${describe#v} +shown=$describe if [ "${1:-}" = --version ]; then echo "$name $code $shown" exit 0 @@ -41,17 +42,30 @@ ndk=${ANDROID_NDK_ROOT:-$(ls -d "$sdk"/ndk/* 2>/dev/null | sort -V | tail -n 1)} java=${JAVA:-java@temurin-17} out=dist/pitwall-phone.apk # why: dist/ is ignored by git, so the debug keystore never gets committed. -key=dist/android/debug.keystore +key=${PITWALL_APK_KEY:-dist/android/debug.keystore} gogio_version=$(mise exec -- go list -m -f '{{.Version}}' gioui.org) [ -d "$sdk/build-tools" ] || { echo "apk.sh: no Android SDK at $sdk" >&2; exit 1; } [ -d "$ndk" ] || { echo "apk.sh: no NDK under $sdk/ndk" >&2; exit 1; } mkdir -p dist/android -gogio=$root/dist/android/gogio-$gogio_version/gogio -[ -x "$gogio" ] || GOFLAGS= GOBIN=$(dirname "$gogio") mise exec -- go install "gioui.org/cmd/gogio@$gogio_version" +patch_hash=$(git hash-object scripts/apk-gogio.sh | cut -c1-12) +gogio=$root/dist/android/gogio-$gogio_version-$patch_hash/gogio +if [ ! -x "$gogio" ]; then + GOFLAGS= mise exec -- go mod download "gioui.org/cmd@$gogio_version" + src=$(mise exec -- go env GOMODCACHE)/gioui.org/cmd@$gogio_version + build=$(mktemp -d) + trap 'rm -rf "$build"' EXIT + cp -R "$src/." "$build/" + chmod -R u+w "$build" + sh scripts/apk-gogio.sh "$build/gogio/androidbuild.go" + GOFLAGS= mise exec -- go -C "$build" build -o "$gogio" ./gogio + rm -rf "$build" + trap - EXIT +fi if [ ! -f "$key" ]; then + [ -z "${PITWALL_APK_KEY:-}" ] || { echo "apk.sh: no signing key at $key" >&2; exit 1; } mise exec "$java" -- keytool -genkeypair -keystore "$key" -storepass android -keypass android \ -alias androiddebugkey -dname "CN=Android Debug,O=Android,C=US" -keyalg RSA -keysize 2048 \ -validity 10000 >/dev/null 2>&1 @@ -66,11 +80,11 @@ mise exec "$java" -- javac -source 1.8 -target 1.8 -Xlint:-options -bootclasspat -d "$classes" internal/ui/mobile/*.java mise exec "$java" -- jar cf "$jar" -C "$classes" . -# warn: gogio puts all four parts of -version in Android's versionName. +# APK_LDFLAGS can override Version, releaseURL and apkTestURL for local emulator checks. ANDROID_HOME=$sdk ANDROID_SDK_ROOT=$sdk ANDROID_NDK_ROOT=$ndk GOFLAGS=-tags=novulkan \ mise exec "$java" -- "$gogio" -target android -arch "$arch" -minsdk 28 -targetsdk 35 \ -appid com.quanticstudios.pitwall -name pitwall -version "$name.$code" \ - -ldflags "-X github.com/quanticstudios/pitwall/internal/ui/mobile.Version=$shown" \ + -ldflags "-X github.com/quanticstudios/pitwall/internal/ui/mobile.Version=$shown ${APK_LDFLAGS:-}" \ -icon internal/remote/web/icon-512.png -signkey "$key" -signpass android \ -o "$out" ./cmd/pitwall-phone echo "$root/$out" diff --git a/scripts/apk_test.sh b/scripts/apk_test.sh index 72d63d2b..1bfb8d1d 100644 --- a/scripts/apk_test.sh +++ b/scripts/apk_test.sh @@ -3,6 +3,7 @@ set -eu src=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)/apk.sh +patcher=$(dirname "$src")/apk-gogio.sh tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT @@ -18,6 +19,23 @@ bad() { fail=1 } +for missing in none application receiver; do + cat >"$tmp/template" <<'TEMPLATE' +android:versionName="{{.Version}}" + + +TEMPLATE + case "$missing" in + application) sed '/"$tmp/changed"; mv "$tmp/changed" "$tmp/template" ;; + receiver) sed '\##d' "$tmp/template" >"$tmp/changed"; mv "$tmp/changed" "$tmp/template" ;; + esac + if sh "$patcher" "$tmp/template" >"$tmp/patch-output" 2>&1; then + [ "$missing" = none ] || bad "manifest patch accepted a missing $missing template" + else + [ "$missing" != none ] || bad "manifest patch rejected a valid template" + fi +done + git init --quiet -b main "$tmp/repo" cd "$tmp/repo" mkdir scripts @@ -34,7 +52,7 @@ if out=$(ver 2>&1); then fi git tag -a v0.2.9 -m v0.2.9 -[ "$(ver)" = "0.2.9 209000 0.2.9-0-g$(git rev-parse --short HEAD)" ] || bad "on v0.2.9: $(ver)" +[ "$(ver)" = "0.2.9 209000 v0.2.9" ] || bad "on v0.2.9: $(ver)" last=209000 commit a diff --git a/scripts/release.sh b/scripts/release.sh index 55db0faf..455aa400 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -78,6 +78,7 @@ if [ -n "$tag" ]; then run git tag -a "$version" -m "pitwall $version" "$commit" run git push origin "refs/tags/$version" step "Done. Watch the release build: gh run list --workflow release.yml" + run sh "$root/scripts/apk-release.sh" --if-available "$version" exit 0 fi diff --git a/scripts/release_test.sh b/scripts/release_test.sh index 4a389e81..99e7af8e 100755 --- a/scripts/release_test.sh +++ b/scripts/release_test.sh @@ -3,6 +3,7 @@ set -eu script=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)/release.sh +apk_release=$(dirname "$script")/apk-release.sh tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT @@ -33,9 +34,11 @@ setup() { git init --quiet --bare -b main "$tmp/origin.git" git init --quiet -b main "$tmp/repo" cd "$tmp/repo" + mkdir scripts + cp "$apk_release" scripts/apk-release.sh git remote add origin "$tmp/origin.git" printf '# Changelog\n\n%s\n## v0.1.10\n\n- Old.\n' "$1" >CHANGELOG.md - git add CHANGELOG.md + git add CHANGELOG.md scripts git commit --quiet -m init for t in ${2:-v0.0.10 v0.1.0-beta.17 v0.1.0-beta.18 v0.1.2 v0.1.9 v0.1.10}; do git tag -a "$t" -m "$t" @@ -90,7 +93,9 @@ git commit --quiet -m 'A later feature' git push --quiet origin main sh "$script" --tag --dry-run >/dev/null [ -z "$(git ls-remote --tags origin v0.1.11)" ] || bad '--tag --dry-run pushed a tag' -sh "$script" --tag >/dev/null 2>&1 +out=$(PITWALL_APK_KEY="$tmp/missing.key" sh "$script" --tag 2>&1) +printf '%s' "$out" | grep -qF 'APK step skipped' || bad "missing key did not skip the APK: $out" +printf '%s' "$out" | grep -qF 'sh scripts/apk-release.sh v0.1.11' || bad 'skip did not name the retry command' got=$(git ls-remote origin 'refs/tags/v0.1.11^{}' | cut -f 1) [ "$got" = "$merged" ] || bad "tag points at $got, want the release commit $merged" refuses 'already exists' --tag v0.1.11