Offer platform-specific updates at startup and foreground return

This commit is contained in:
2026-11-08 00:14:53 +00:00
parent 81b3515369
commit 97f190e1b1
12 changed files with 996 additions and 0 deletions
+109
View File
@@ -0,0 +1,109 @@
import 'dart:convert';
import 'app_updates.dart';
typedef UpdateInstaller =
Future<void> Function(
AppUpdate update, {
void Function(double progress)? onProgress,
});
sealed class LaunchUpdate {
const LaunchUpdate();
}
class WebLaunchUpdate extends LaunchUpdate {
const WebLaunchUpdate(this.buildId);
final String buildId;
}
class AndroidLaunchUpdate extends LaunchUpdate {
const AndroidLaunchUpdate(this.update);
final AppUpdate update;
}
LaunchUpdate? webUpdateFor(String compiled, String body) {
final current = compiled.trim();
if (current.isEmpty) return null;
try {
final value = jsonDecode(body);
if (value is! Map || value['schema'] != 1 || value['platform'] != 'web') {
return null;
}
final latest = '${value['buildId'] ?? ''}'.trim();
return latest.isEmpty || latest == current ? null : WebLaunchUpdate(latest);
} on FormatException {
return null;
}
}
AndroidLaunchUpdate? androidUpdateFor(AppUpdate latest, int? installed) {
if (installed == null || latest.versionCode <= installed) return null;
return AndroidLaunchUpdate(latest);
}
/// Page hosting and RPC servers may differ; web releases belong to the page.
Uri webReleaseUri(Uri page) => Uri(
scheme: page.scheme,
host: page.host,
port: page.hasPort ? page.port : null,
path: '/release.json',
);
/// One opportunistic request per foreground visit and feed. Declined releases
/// stay dismissed for this application session, while a newer release can ask.
class LaunchUpdateChecker {
String? _attempt;
final _offered = <String>{};
void beginVisit() => _attempt = null;
Future<LaunchUpdate?> check({
required bool web,
required bool android,
required String webBuildId,
required Uri page,
required Uri? endpoint,
required Future<String?> Function(Uri) readWeb,
required Future<int?> Function() installedVersion,
required Future<AppUpdate> Function(Uri) readAndroid,
}) async {
final feed = web
? webReleaseUri(page)
: endpoint == null
? null
: updatesBaseFor(endpoint);
if (feed == null || (web ? webBuildId.trim().isEmpty : !android)) {
return null;
}
final key = '${web ? 'web' : 'android'}:$feed';
if (_attempt == key) return null;
_attempt = key;
LaunchUpdate? update;
if (web) {
final body = await readWeb(feed).timeout(const Duration(seconds: 15));
if (body != null) update = webUpdateFor(webBuildId, body);
} else {
final installed = await installedVersion().timeout(
const Duration(seconds: 15),
);
if (installed != null) {
update = androidUpdateFor(
await readAndroid(feed).timeout(const Duration(seconds: 15)),
installed,
);
}
}
return update == null || _offered.contains(_identity(update))
? null
: update;
}
void markOffered(LaunchUpdate update) => _offered.add(_identity(update));
String _identity(LaunchUpdate update) => switch (update) {
WebLaunchUpdate(:final buildId) => 'web:$buildId',
AndroidLaunchUpdate(:final update) =>
'android:${update.apk}:${update.versionCode}',
};
}
@@ -0,0 +1,188 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'app_updates.dart';
import 'launch_update.dart';
Future<bool?> showLaunchUpdateDialog(
BuildContext context, {
required bool web,
required bool cupertino,
}) => cupertino
? showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Update available'),
content: Text(
web
? 'A newer Pipelines web build is available.'
: 'A newer Android build is available.',
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Later'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => Navigator.pop(context, true),
child: Text(web ? 'Refresh' : 'Download'),
),
],
),
)
: showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Update available'),
content: Text(
web
? 'A newer Pipelines web build is available.'
: 'A newer Android build is available.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Later'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: Text(web ? 'Refresh' : 'Download'),
),
],
),
);
Future<void> showLaunchUpdateFailure(
BuildContext context,
Object error, {
required bool cupertino,
}) async {
if (cupertino) {
await showCupertinoDialog<void>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Update failed'),
content: Text('$error'),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
} else {
await showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Update failed'),
content: Text('$error'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
}
}
/// Reuses the Settings installer while keeping download progress visible.
Future<void> installLaunchUpdate(
BuildContext context,
AppUpdate update, {
required UpdateInstaller installer,
required bool cupertino,
}) async {
final result = cupertino
? await showCupertinoDialog<_InstallResult>(
context: context,
builder: (_) => _InstallProgress(
update: update,
installer: installer,
cupertino: true,
),
)
: await showDialog<_InstallResult>(
context: context,
barrierDismissible: false,
builder: (_) => _InstallProgress(
update: update,
installer: installer,
cupertino: false,
),
);
if (result?.error case final Object error) throw error;
}
class _InstallResult {
const _InstallResult([this.error]);
final Object? error;
}
class _InstallProgress extends StatefulWidget {
const _InstallProgress({
required this.update,
required this.installer,
required this.cupertino,
});
final AppUpdate update;
final UpdateInstaller installer;
final bool cupertino;
@override
State<_InstallProgress> createState() => _InstallProgressState();
}
class _InstallProgressState extends State<_InstallProgress> {
double? _progress;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
Object? error;
try {
await widget.installer(
widget.update,
onProgress: (progress) {
if (mounted) setState(() => _progress = progress.clamp(0, 1));
},
);
} catch (failure) {
error = failure;
}
if (mounted) Navigator.of(context).pop(_InstallResult(error));
});
}
@override
Widget build(BuildContext context) {
final progress = _progress;
final content = Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
progress == null
? 'Downloading update…'
: 'Downloading update… ${(progress * 100).round()}%',
),
const SizedBox(height: 16),
widget.cupertino
? const CupertinoActivityIndicator()
: LinearProgressIndicator(value: progress),
],
);
return PopScope(
canPop: false,
child: widget.cupertino
? CupertinoAlertDialog(
title: const Text('App update'),
content: content,
)
: AlertDialog(title: const Text('App update'), content: content),
);
}
}
@@ -0,0 +1,8 @@
import 'web_release_stub.dart'
if (dart.library.js_interop) 'web_release_web.dart'
as impl;
const compiledWebBuildId = String.fromEnvironment('PIPELINES_WEB_BUILD_ID');
Future<String?> fetchLatestWebBuild(Uri uri) => impl.fetchLatestWebBuild(uri);
Future<void> refreshWebPage() => impl.refreshWebPage();
@@ -0,0 +1,2 @@
Future<String?> fetchLatestWebBuild(Uri uri) async => null;
Future<void> refreshWebPage() async {}
@@ -0,0 +1,26 @@
import 'dart:js_interop';
@JS('fetch')
external JSPromise<_ReleaseResponse> _fetch(JSString input, _FetchOptions init);
@JS('location.reload')
external void _reload();
extension type _FetchOptions._(JSObject _) implements JSObject {
external factory _FetchOptions({JSString credentials, JSString cache});
}
extension type _ReleaseResponse._(JSObject _) implements JSObject {
external int get status;
external JSPromise<JSString> text();
}
Future<String?> fetchLatestWebBuild(Uri uri) async {
final response = await _fetch(
uri.toString().toJS,
_FetchOptions(credentials: 'same-origin'.toJS, cache: 'no-store'.toJS),
).toDart;
if (response.status != 200) return null;
return (await response.text().toDart).toDart;
}
Future<void> refreshWebPage() async => _reload();