Files
pipelines/app/lib/features/updates/app_updates.dart
T

83 lines
2.7 KiB
Dart

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 build set its update feed (`--dart-define=PIPELINES_UPDATES_URL`),
/// blank for the default.
const configuredUpdatesUrl = String.fromEnvironment('PIPELINES_UPDATES_URL');
/// The update feed for [endpoint]: `/updates/` on the server's own web origin
/// (the installed web proxy serves the APK there), or [configured] when the
/// build named another feed.
Uri? updatesBaseFor(Uri endpoint, {String configured = configuredUpdatesUrl}) {
final override = configured.trim();
if (override.isNotEmpty) {
final parsed = Uri.tryParse(override);
if (parsed != null && parsed.hasScheme && parsed.host.isNotEmpty) {
return parsed.path.endsWith('/')
? parsed
: parsed.replace(path: '${parsed.path}/');
}
}
if (endpoint.host.isEmpty) return null;
final secure = endpoint.scheme == 'wss' || endpoint.scheme == 'https';
return Uri(
scheme: secure ? 'https' : 'http',
host: endpoint.host,
port: endpoint.hasPort ? endpoint.port : null,
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);