Merge commit '394fd672'

This commit is contained in:
2026-11-08 16:49:58 +00:00
16 changed files with 615 additions and 58 deletions
@@ -88,7 +88,13 @@ extension _SettingsTopicPages on _SettingsScreenState {
if (widget.showAndroidDownload)
_single('Android app', const SettingsAndroidDownloadSection()),
if (widget.showSignIn && appUpdatesSupported)
_single('App updates', SettingsUpdatesSection(endpoint: _endpoint)),
_single(
'App updates',
SettingsUpdatesSection(
endpoint: _endpoint,
servers: widget.servers,
),
),
if (!widget.showAndroidDownload &&
!(widget.showSignIn && appUpdatesSupported))
_single(
@@ -3,14 +3,20 @@ import 'package:flutter/material.dart';
import '../../ui/adaptive/host.dart';
import '../updates/app_updates.dart';
import 'server_connections.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});
const SettingsUpdatesSection({
super.key,
required this.endpoint,
this.servers,
});
/// The server's websocket address; its builds sit beside it.
final String endpoint;
final ServerConnections? servers;
@override
State<SettingsUpdatesSection> createState() => _SettingsUpdatesSectionState();
@@ -44,15 +50,25 @@ class _SettingsUpdatesSectionState extends State<SettingsUpdatesSection> {
_available = null;
});
try {
final latest = await fetchLatestUpdate(base);
final latest = widget.servers == null
? await fetchLatestUpdate(base)
: await newestServerUpdate(
widget.servers!.catalog.servers,
stillTrusted: (source, uri) => updateSourceStillTrusted(
widget.servers!.catalog.servers,
source,
uri,
),
);
if (!mounted) return;
final installed = _installed ?? 0;
setState(() {
if (latest.versionCode > installed) {
_available = latest;
_message = 'Build ${latest.versionCode} is available.';
_message =
'Build ${latest.versionCode} is available${latest.sourceName.isEmpty ? '' : ' from ${latest.sourceName}'}.';
} else {
_message = 'Up to date.';
_message = 'No newer compatible build found on reachable servers.';
}
});
} catch (error) {
@@ -77,7 +93,7 @@ class _SettingsUpdatesSectionState extends State<SettingsUpdatesSection> {
if (mounted) setState(() => _progress = value);
},
);
if (mounted) setState(() => _message = 'Opened the installer.');
if (mounted) setState(() => _message = 'Opened the downloaded update.');
} catch (error) {
if (mounted) setState(() => _message = '$error');
} finally {
@@ -139,7 +155,7 @@ class _SettingsUpdatesSectionState extends State<SettingsUpdatesSection> {
if (_available != null)
button(
const Key('settings-install-update'),
'Download and install',
'Download update',
_busy ? null : _install,
true,
),
+128 -5
View File
@@ -1,5 +1,8 @@
import 'dart:convert';
import '../../core/servers/server_catalog.dart';
import '../../core/session/server_session.dart';
import 'app_updates_stub.dart'
if (dart.library.io) 'app_updates_io.dart'
as impl;
@@ -11,23 +14,73 @@ class AppUpdate {
required this.versionName,
required this.apk,
this.notes = '',
this.sourceName = '',
this.headersFor,
this.platform = 'android',
this.sha256 = '',
});
final int versionCode;
final String versionName;
final Uri apk;
final String notes;
final String sourceName;
final String platform;
final String sha256;
final Map<String, String> Function(Uri)? headersFor;
AppUpdate fromServer(
String name,
Map<String, String> Function(Uri) headers,
) => AppUpdate(
versionCode: versionCode,
versionName: versionName,
apk: apk,
notes: notes,
platform: platform,
sourceName: name,
sha256: sha256,
headersFor: headers,
);
/// Reads `version.json`; the APK path is relative to [base].
static AppUpdate? parse(String body, Uri base) {
static AppUpdate? parse(
String body,
Uri base, {
String platform = 'android',
String architecture = 'arm64',
}) {
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;
final file = '${json[platform == 'android' ? 'apk' : 'file'] ?? ''}'
.trim();
if (code is! int ||
code < 1 ||
file.isEmpty ||
!RegExp(r'^[a-zA-Z0-9][a-zA-Z0-9._-]*$').hasMatch(file)) {
return null;
}
final digest = '${json['sha256'] ?? ''}';
if (digest.isNotEmpty && !RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(digest)) {
return null;
}
if (platform == 'android' &&
json['platform'] != null &&
json['platform'] != 'android') {
return null;
}
if (platform != 'android' &&
(json['platform'] != platform ||
json['architectures'] is! List ||
!(json['architectures'] as List).contains(architecture))) {
return null;
}
return AppUpdate(
versionCode: code.toInt(),
versionCode: code,
platform: platform,
sha256: '${json['sha256'] ?? ''}',
versionName: '${json['versionName'] ?? ''}',
apk: base.resolve(file),
notes: '${json['notes'] ?? ''}',
@@ -65,7 +118,7 @@ Uri? updatesBaseFor(Uri endpoint, {String configured = configuredUpdatesUrl}) {
);
}
/// Whether this build can update itself (an Android phone).
/// Whether this native build supports platform-compatible update downloads.
bool get appUpdatesSupported => impl.supported;
/// The installed build number, or null where there is none to compare.
@@ -80,3 +133,73 @@ Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) => impl.downloadAndInstall(update, onProgress: onProgress);
/// Checks each logical machine independently; aliases share only its credential.
/// Failed machines cannot hide a newer compatible build on a healthy machine.
Future<AppUpdate> newestServerUpdate(
Iterable<SavedServer> servers, {
Future<AppUpdate> Function(Uri, Map<String, String> Function(Uri))? read,
bool Function(SavedServer server, Uri uri)? stillTrusted,
}) async {
final results = await Future.wait(
servers.map((server) async {
Map<String, String> Function(Uri) headers;
try {
headers = await ServerSession.credentialReader(
id: server.id,
endpoints: server.endpoints.map(Uri.parse),
);
} catch (_) {
return null;
}
final snapshotHeaders = headers;
headers = (uri) {
if (stillTrusted != null && !stillTrusted(server, uri)) {
throw StateError(
'The update server is no longer a saved trusted address.',
);
}
return snapshotHeaders(uri);
};
final candidates = await Future.wait(
server.endpoints.map((endpoint) async {
final base = updatesBaseFor(Uri.parse(endpoint), configured: '');
if (base == null) return null;
try {
final update = await (read ?? impl.fetchLatestScoped)(
base,
headers,
).timeout(const Duration(seconds: 15));
return update.fromServer(server.name, headers);
} catch (_) {
return null;
}
}),
);
final builds = candidates.whereType<AppUpdate>().toList()
..sort((a, b) => b.versionCode.compareTo(a.versionCode));
return builds.isEmpty ? null : builds.first;
}),
);
final available = results.whereType<AppUpdate>().toList()
..sort((a, b) => b.versionCode.compareTo(a.versionCode));
if (available.isEmpty) {
throw const FormatException(
'No compatible update could be read. Check your saved servers and sign-ins.',
);
}
return available.first;
}
/// Retained offers must stop trusting an alias if its profile is edited/removed.
bool updateSourceStillTrusted(
Iterable<SavedServer> current,
SavedServer source,
Uri uri,
) => current.any(
(server) =>
server.id == source.id &&
server.endpoints.any(
(endpoint) => loginUriFor(Uri.parse(endpoint)) == loginUriFor(uri),
),
);
+121 -35
View File
@@ -1,4 +1,8 @@
import 'dart:io';
import 'dart:convert';
import 'dart:ffi';
import 'package:crypto/crypto.dart' as crypto;
import 'package:open_filex/open_filex.dart';
import 'package:package_info_plus/package_info_plus.dart';
@@ -7,19 +11,37 @@ import 'package:path_provider/path_provider.dart';
import '../../core/session/server_session.dart';
import 'app_updates.dart';
bool get supported => Platform.isAndroid;
bool get supported =>
Platform.isAndroid || Platform.isLinux || Platform.isMacOS;
String get nativePlatform => Platform.isMacOS
? 'macos'
: Platform.isLinux
? 'linux'
: 'android';
String get nativeArchitecture {
final abi = Abi.current().toString();
if (abi.endsWith('_arm64')) return 'arm64';
if (abi.endsWith('_x64')) return 'x64';
return 'unsupported';
}
Future<int?> installedVersionCode() async {
const embedded = int.fromEnvironment('PIPELINES_NATIVE_BUILD_CODE');
if (embedded > 0) return embedded;
final info = await PackageInfo.fromPlatform();
return int.tryParse(info.buildNumber);
}
Future<HttpClientResponse> _get(HttpClient client, Uri uri) async {
final request = await client.getUrl(uri);
Future<HttpClientResponse> _get(
HttpClient client,
Uri uri, [
Map<String, String> Function(Uri)? headers,
]) async {
final request = await client.getUrl(uri).timeout(const Duration(seconds: 15));
request.followRedirects = false;
// The updates sit behind the same web login the app signed in to.
ServerSession.headersFor(uri).forEach(request.headers.set);
final response = await request.close();
(headers ?? ServerSession.headersFor)(uri).forEach(request.headers.set);
final response = await request.close().timeout(const Duration(seconds: 15));
if (response.statusCode == 401 || response.statusCode == 302) {
await response.drain<void>();
throw const HttpException('Sign in first (Settings → Sign in).');
@@ -31,47 +53,111 @@ Future<HttpClientResponse> _get(HttpClient client, Uri uri) async {
return response;
}
Future<AppUpdate> fetchLatest(Uri base) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
Future<AppUpdate> fetchLatest(Uri base) =>
fetchLatestScoped(base, ServerSession.headersFor);
Future<AppUpdate> fetchLatestScoped(
Uri base,
Map<String, String> Function(Uri) headers,
) async {
final platform = nativePlatform;
if (platform == 'linux' && nativeArchitecture != 'x64') {
throw const FormatException(
'No Linux build is available for this architecture.',
);
}
final feed = platform == 'android'
? base
: base.resolve(platform == 'linux' ? 'linux-x64/' : 'macos/');
final client = HttpClient()..connectionTimeout = const Duration(seconds: 10);
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.');
final response = await _get(client, feed.resolve('version.json'), headers);
var bytes = 0;
final chunks = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 10))) {
bytes += chunk.length;
if (bytes > 65536) {
throw const FormatException('Update metadata is too large.');
}
chunks.addAll(chunk);
}
final update = AppUpdate.parse(
utf8.decode(chunks),
feed,
platform: platform,
architecture: nativeArchitecture,
);
if (update == null) {
throw const FormatException('No compatible build is offered.');
}
return update;
} finally {
client.close(force: true);
}
}
/// Downloads to a partial file and publishes it only after integrity checks.
Future<File> downloadUpdate(
AppUpdate update,
Directory dir, {
void Function(double progress)? onProgress,
}) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
final suffix = update.platform == 'android'
? 'apk'
: update.platform == 'macos'
? 'zip'
: 'tar.gz';
final file = File('${dir.path}/pipelines-${update.versionCode}.$suffix');
final partial = File('${file.path}.part');
try {
final response = await _get(client, update.apk, update.headersFor);
final total = response.contentLength;
final sink = partial.openWrite();
var received = 0;
try {
await for (final chunk in response.timeout(const Duration(seconds: 30))) {
sink.add(chunk);
received += chunk.length;
if (total > 0) onProgress?.call(received / total);
}
} finally {
await sink.close();
}
if (total >= 0 && received != total) {
throw const HttpException('The update download was incomplete.');
}
if (update.sha256.isNotEmpty) {
final digest = await crypto.sha256.bind(partial.openRead()).first;
if (digest.toString() != update.sha256.toLowerCase()) {
throw const FormatException(
'The downloaded update failed its integrity check.',
);
}
}
await partial.rename(file.path);
return file;
} finally {
client.close(force: true);
if (await partial.exists()) await partial.delete();
}
}
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',
final dir = Platform.isAndroid
? await getTemporaryDirectory()
: (await getDownloadsDirectory() ?? await getTemporaryDirectory());
final file = await downloadUpdate(update, dir, onProgress: onProgress);
final result = await OpenFilex.open(
file.path,
type: Platform.isAndroid ? 'application/vnd.android.package-archive' : null,
);
if (result.type != ResultType.done) {
throw HttpException(
'Could not open the downloaded update: ${result.message}',
);
if (result.type != ResultType.done) {
throw HttpException('Could not open the installer: ${result.message}');
}
} finally {
client.close(force: true);
}
}
@@ -11,3 +11,8 @@ Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) async => throw StateError('Updates are installed from a phone.');
Future<AppUpdate> fetchLatestScoped(
Uri base,
Map<String, String> Function(Uri) headers,
) => fetchLatest(base);
+6 -2
View File
@@ -67,6 +67,8 @@ class LaunchUpdateChecker {
required Future<String?> Function(Uri) readWeb,
required Future<int?> Function() installedVersion,
required Future<AppUpdate> Function(Uri) readAndroid,
Future<AppUpdate> Function()? readNative,
String nativeScope = '',
}) async {
final feed = web
? webReleaseUri(page)
@@ -76,7 +78,7 @@ class LaunchUpdateChecker {
if (feed == null || (web ? webBuildId.trim().isEmpty : !android)) {
return null;
}
final key = '${web ? 'web' : 'android'}:$feed';
final key = '${web ? 'web' : 'native'}:$feed:$nativeScope';
if (_attempt == key) return null;
_attempt = key;
LaunchUpdate? update;
@@ -89,7 +91,9 @@ class LaunchUpdateChecker {
);
if (installed != null) {
update = androidUpdateFor(
await readAndroid(feed).timeout(const Duration(seconds: 15)),
await (readNative == null ? readAndroid(feed) : readNative()).timeout(
const Duration(seconds: 30),
),
installed,
);
}
@@ -8,6 +8,8 @@ Future<bool?> showLaunchUpdateDialog(
BuildContext context, {
required bool web,
required bool cupertino,
String sourceName = '',
String nativePlatform = 'android',
}) => cupertino
? showCupertinoDialog<bool>(
context: context,
@@ -16,7 +18,11 @@ Future<bool?> showLaunchUpdateDialog(
content: Text(
web
? 'A newer Pipelines web build is available.'
: 'A newer Android build is available.',
: 'A newer ${nativePlatform == 'macos'
? 'macOS'
: nativePlatform == 'linux'
? 'Linux'
: 'Android'} build is available${sourceName.isEmpty ? '' : ' from $sourceName'}.${nativePlatform == 'android' ? '' : ' Download and extract the archive to update the app.'}',
),
actions: [
CupertinoDialogAction(
@@ -38,7 +44,11 @@ Future<bool?> showLaunchUpdateDialog(
content: Text(
web
? 'A newer Pipelines web build is available.'
: 'A newer Android build is available.',
: 'A newer ${nativePlatform == 'macos'
? 'macOS'
: nativePlatform == 'linux'
? 'Linux'
: 'Android'} build is available${sourceName.isEmpty ? '' : ' from $sourceName'}.${nativePlatform == 'android' ? '' : ' Download and extract the archive to update the app.'}',
),
actions: [
TextButton(