feat(app): Check for updates downloads the server's newest APK and opens the installer

This commit is contained in:
2026-10-23 19:59:03 +01:00
parent 72e01471ab
commit 6152292aff
11 changed files with 523 additions and 0 deletions
@@ -1,5 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<!-- Check for updates hands a downloaded build to the system installer. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<!-- The client reaches the Pipelines server over the shared socket. -->
<uses-permission android:name="android.permission.INTERNET"/>
<application
@@ -14,6 +14,8 @@ import 'settings_notifications_section.dart';
import 'settings_schedules_section.dart';
import 'settings_sections.dart';
import 'settings_sign_in_section.dart';
import 'settings_updates_section.dart';
import '../updates/app_updates.dart';
import 'settings_store.dart';
import 'settings_templates_section.dart';
@@ -159,6 +161,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
),
],
// A phone installs newer builds from the server.
if (widget.showSignIn && appUpdatesSupported) ...<Widget>[
const SizedBox(height: settingsSectionGap),
_SettingsSection(
title: 'App updates',
child: SettingsUpdatesSection(
endpoint: _controller.serverUrl,
),
),
],
const SizedBox(height: settingsSectionGap),
_SettingsSection(
title: 'Workspace',
@@ -0,0 +1,165 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../ui/adaptive/host.dart';
import '../updates/app_updates.dart';
/// Check for updates: compares this build with the newest one the server
/// offers and installs it on request.
class SettingsUpdatesSection extends StatefulWidget {
const SettingsUpdatesSection({super.key, required this.endpoint});
/// The server's websocket address; its builds sit beside it.
final String endpoint;
@override
State<SettingsUpdatesSection> createState() => _SettingsUpdatesSectionState();
}
class _SettingsUpdatesSectionState extends State<SettingsUpdatesSection> {
int? _installed;
AppUpdate? _available;
bool _busy = false;
double? _progress;
String? _message;
@override
void initState() {
super.initState();
installedVersionCode().then((code) {
if (mounted) setState(() => _installed = code);
});
}
Future<void> _check() async {
final endpoint = Uri.tryParse(widget.endpoint.trim());
final base = endpoint == null ? null : updatesBaseFor(endpoint);
if (base == null) {
setState(() => _message = 'Set the server address first.');
return;
}
setState(() {
_busy = true;
_message = null;
_available = null;
});
try {
final latest = await fetchLatestUpdate(base);
if (!mounted) return;
final installed = _installed ?? 0;
setState(() {
if (latest.versionCode > installed) {
_available = latest;
_message = 'Build ${latest.versionCode} is available.';
} else {
_message = 'Up to date.';
}
});
} catch (error) {
if (mounted) setState(() => _message = '$error');
} finally {
if (mounted) setState(() => _busy = false);
}
}
Future<void> _install() async {
final update = _available;
if (update == null) return;
setState(() {
_busy = true;
_progress = 0;
_message = 'Downloading…';
});
try {
await downloadAndInstall(
update,
onProgress: (value) {
if (mounted) setState(() => _progress = value);
},
);
if (mounted) setState(() => _message = 'Opened the installer.');
} catch (error) {
if (mounted) setState(() => _message = '$error');
} finally {
if (mounted) {
setState(() {
_busy = false;
_progress = null;
});
}
}
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
Widget button(
Key key,
String label,
VoidCallback? onPressed,
bool primary,
) => cupertino
? (primary
? CupertinoButton.filled(
key: key,
onPressed: onPressed,
child: Text(label),
)
: CupertinoButton(
key: key,
onPressed: onPressed,
child: Text(label),
))
: (primary
? FilledButton(key: key, onPressed: onPressed, child: Text(label))
: OutlinedButton(
key: key,
onPressed: onPressed,
child: Text(label),
));
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
_installed == null
? 'Installed build unknown.'
: 'Installed build $_installed.',
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
button(
const Key('settings-check-updates'),
'Check for updates',
_busy ? null : _check,
_available == null,
),
if (_available != null)
button(
const Key('settings-install-update'),
'Download and install',
_busy ? null : _install,
true,
),
],
),
if (_progress != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: cupertino
? CupertinoActivityIndicator.partiallyRevealed(
progress: _progress!,
)
: LinearProgressIndicator(value: _progress),
),
if (_message != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Semantics(liveRegion: true, child: Text(_message!)),
),
],
);
}
}
+68
View File
@@ -0,0 +1,68 @@
import 'dart:convert';
import 'app_updates_stub.dart'
if (dart.library.io) 'app_updates_io.dart'
as impl;
/// The latest app build the server offers, from its `updates/version.json`.
class AppUpdate {
const AppUpdate({
required this.versionCode,
required this.versionName,
required this.apk,
this.notes = '',
});
final int versionCode;
final String versionName;
final Uri apk;
final String notes;
/// Reads `version.json`; the APK path is relative to [base].
static AppUpdate? parse(String body, Uri base) {
try {
final json = jsonDecode(body);
if (json is! Map) return null;
final code = json['versionCode'];
final file = '${json['apk'] ?? ''}'.trim();
if (code is! num || file.isEmpty) return null;
return AppUpdate(
versionCode: code.toInt(),
versionName: '${json['versionName'] ?? ''}',
apk: base.resolve(file),
notes: '${json['notes'] ?? ''}',
);
} on FormatException {
return null;
}
}
}
/// Where a server's app builds live: the preview origin beside it (same host,
/// port 8096) under `/updates/`.
Uri? updatesBaseFor(Uri endpoint) {
if (endpoint.host.isEmpty) return null;
final secure = endpoint.scheme == 'wss' || endpoint.scheme == 'https';
return Uri(
scheme: secure ? 'https' : 'http',
host: endpoint.host,
port: 8096,
path: '/updates/',
);
}
/// Whether this build can update itself (an Android phone).
bool get appUpdatesSupported => impl.supported;
/// The installed build number, or null where there is none to compare.
Future<int?> installedVersionCode() => impl.installedVersionCode();
/// Fetches the latest offered build, or throws what went wrong in words.
Future<AppUpdate> fetchLatestUpdate(Uri base) => impl.fetchLatest(base);
/// Downloads [update] (reporting 0..1 progress) and hands it to the system
/// installer.
Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) => impl.downloadAndInstall(update, onProgress: onProgress);
@@ -0,0 +1,76 @@
import 'dart:io';
import 'package:open_filex/open_filex.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import '../../core/session/server_session.dart';
import 'app_updates.dart';
bool get supported => Platform.isAndroid;
Future<int?> installedVersionCode() async {
final info = await PackageInfo.fromPlatform();
return int.tryParse(info.buildNumber);
}
Future<HttpClientResponse> _get(HttpClient client, Uri uri) async {
final request = await client.getUrl(uri);
// The updates sit behind the same web login the app signed in to.
ServerSession.headers.forEach(request.headers.set);
final response = await request.close();
if (response.statusCode == 401 || response.statusCode == 302) {
await response.drain<void>();
throw const HttpException('Sign in first (Settings → Sign in).');
}
if (response.statusCode != 200) {
await response.drain<void>();
throw HttpException('The server answered ${response.statusCode}.');
}
return response;
}
Future<AppUpdate> fetchLatest(Uri base) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final response = await _get(client, base.resolve('version.json'));
final body = await response
.transform(const SystemEncoding().decoder)
.join();
final update = AppUpdate.parse(body, base);
if (update == null) throw const FormatException('No build is offered.');
return update;
} finally {
client.close(force: true);
}
}
Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final response = await _get(client, update.apk);
final total = response.contentLength;
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/pipelines-${update.versionCode}.apk');
final sink = file.openWrite();
var received = 0;
await for (final chunk in response) {
sink.add(chunk);
received += chunk.length;
if (total > 0) onProgress?.call(received / total);
}
await sink.close();
final result = await OpenFilex.open(
file.path,
type: 'application/vnd.android.package-archive',
);
if (result.type != ResultType.done) {
throw HttpException('Could not open the installer: ${result.message}');
}
} finally {
client.close(force: true);
}
}
@@ -0,0 +1,13 @@
import 'app_updates.dart';
bool get supported => false;
Future<int?> installedVersionCode() async => null;
Future<AppUpdate> fetchLatest(Uri base) async =>
throw StateError('Updates are installed from a phone.');
Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) async => throw StateError('Updates are installed from a phone.');
+128
View File
@@ -41,6 +41,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev"
source: hosted
version: "1.2.1"
collection:
dependency: transitive
description:
@@ -97,6 +105,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
ffi_leak_tracker:
dependency: transitive
description:
name: ffi_leak_tracker
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
file:
dependency: transitive
description:
@@ -168,6 +184,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
hooks:
dependency: transitive
description:
name: hooks
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
html:
dependency: transitive
description:
@@ -200,6 +224,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
url: "https://pub.dev"
source: hosted
version: "1.0.4+1"
jni_util:
dependency: transitive
description:
@@ -240,6 +272,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.0"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
@@ -264,6 +304,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.18.0"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e
url: "https://pub.dev"
source: hosted
version: "9.5.0"
open_filex:
dependency: "direct main"
description:
name: open_filex
sha256: "0c3fe80e73f0b3200fef6e175b83dae9790dd23c9cdbb6d15f46e2ff10ae84ad"
url: "https://pub.dev"
source: hosted
version: "5.0.0"
package_config:
dependency: transitive
description:
@@ -272,6 +328,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.0"
package_info_plus:
dependency: "direct main"
description:
name: package_info_plus
sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908"
url: "https://pub.dev"
source: hosted
version: "10.2.2"
package_info_plus_platform_interface:
dependency: transitive
description:
name: package_info_plus_platform_interface
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
url: "https://pub.dev"
source: hosted
version: "4.1.0"
path:
dependency: transitive
description:
@@ -280,6 +352,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: "direct main"
description:
name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
path_provider_linux:
dependency: transitive
description:
@@ -328,6 +424,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
record_use:
dependency: transitive
description:
name: record_use
sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"
url: "https://pub.dev"
source: hosted
version: "0.6.0"
shared_preferences:
dependency: "direct main"
description:
@@ -565,6 +677,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.26.2"
win32:
dependency: transitive
description:
name: win32
sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d
url: "https://pub.dev"
source: hosted
version: "6.4.0"
xdg_directories:
dependency: transitive
description:
@@ -581,6 +701,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
yaml:
dependency: transitive
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.12.2 <4.0.0"
flutter: ">=3.44.0"
+3
View File
@@ -42,6 +42,9 @@ dependencies:
video_player: ^2.14.1
webview_flutter: ^4.14.1
flutter_local_notifications: ^22.3.2
package_info_plus: ^10.2.2
path_provider: ^2.1.6
open_filex: ^5.0.0
dev_dependencies:
flutter_test:
@@ -0,0 +1,27 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/updates/app_updates.dart';
void main() {
test('builds live beside the server, under the preview origin', () {
expect(
updatesBaseFor(Uri.parse('wss://host.ts.net:8443/connect')).toString(),
'https://host.ts.net:8096/updates/',
);
});
test('version.json names the build and its APK', () {
final base = Uri.parse('https://host.ts.net:8096/updates/');
final update = AppUpdate.parse(
'{"versionCode": 29960000, "versionName": "0.1.29960000", '
'"apk": "pipelines.apk", "notes": "fixes"}',
base,
)!;
expect(update.versionCode, 29960000);
expect(
update.apk.toString(),
'https://host.ts.net:8096/updates/pipelines.apk',
);
expect(AppUpdate.parse('{}', base), isNull);
expect(AppUpdate.parse('not json', base), isNull);
});
}
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Builds the Android app and offers it to phones through Check for updates.
#
# Usage (from app/ on main): sh tool/publish_apk.sh ["notes"]
# The build number is minutes since the epoch, so every build is newer than
# the last. The APK and version.json go to build/updates/ (kept across preview
# publishes) and are copied into the live preview at build/web/updates/,
# served behind the web login at https://<host>:8096/updates/. Never restarts
# any server.
set -eu
notes="${1:-}"
FLUTTER="${FLUTTER:-/Users/alan/development/flutter/bin/flutter}"
export JAVA_HOME="${JAVA_HOME:-/Applications/Android Studio.app/Contents/jbr/Contents/Home}"
export ANDROID_HOME="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
code=$(( $(date +%s) / 60 ))
name="0.1.$code"
"$FLUTTER" build apk --release --build-number="$code" --build-name="$name"
mkdir -p build/updates
cp build/app/outputs/flutter-apk/app-release.apk build/updates/pipelines.apk
cat > build/updates/version.json <<JSON
{"versionCode": $code, "versionName": "$name", "apk": "pipelines.apk", "notes": "$notes"}
JSON
if [ -d build/web ]; then
rm -rf build/web/updates
cp -R build/updates build/web/updates
fi
echo "APK $code $(shasum build/updates/pipelines.apk | cut -c1-8) $(pwd)/build/updates/pipelines.apk"
+2
View File
@@ -13,5 +13,7 @@ FLUTTER="${FLUTTER:-/Users/alan/development/flutter/bin/flutter}"
rollback="build/web-before-${name}-$(date +%s)"
if [ -d build/web ]; then mv build/web "$rollback"; fi
mv build/web-next build/web
# Keep the phone builds offered by Check for updates (tool/publish_apk.sh).
if [ -d build/updates ]; then cp -R build/updates build/web/updates; fi
echo "ROLLBACK $rollback"
echo "JS $(shasum build/web/main.dart.js | cut -c1-8)"