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
@@ -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.');