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