6d58b3fb03
Like Linux, the macOS app downloads the verified archive, unpacks it with ditto beside the installed bundle, swaps it in (keeping the previous bundle to roll back) and relaunches once the old process has quit.
242 lines
7.6 KiB
Dart
242 lines
7.6 KiB
Dart
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';
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import '../../core/session/server_session.dart';
|
|
import 'app_updates.dart';
|
|
import 'linux_self_update.dart';
|
|
import 'macos_self_update.dart';
|
|
import 'update_feed_signature.dart';
|
|
|
|
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, [
|
|
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.
|
|
(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).');
|
|
}
|
|
if (response.statusCode != 200) {
|
|
await response.drain<void>();
|
|
throw HttpException('The server answered ${response.statusCode}.');
|
|
}
|
|
return response;
|
|
}
|
|
|
|
Future<AppUpdate> fetchLatest(Uri base) =>
|
|
fetchLatestScoped(base, ServerSession.headersFor);
|
|
|
|
/// Reads at most [limit] bytes of [response].
|
|
Future<List<int>> _body(HttpClientResponse response, int limit) async {
|
|
final chunks = <int>[];
|
|
await for (final chunk in response.timeout(const Duration(seconds: 10))) {
|
|
if (chunks.length + chunk.length > limit) {
|
|
throw const FormatException('Update metadata is too large.');
|
|
}
|
|
chunks.addAll(chunk);
|
|
}
|
|
return chunks;
|
|
}
|
|
|
|
/// The detached feed signature, or null when the server offers none.
|
|
Future<String?> _signature(
|
|
HttpClient client,
|
|
Uri feed,
|
|
Map<String, String> Function(Uri) headers,
|
|
) async {
|
|
try {
|
|
final response = await _get(
|
|
client,
|
|
feed.resolve('version.json.sig'),
|
|
headers,
|
|
);
|
|
return utf8.decode(await _body(response, 4096));
|
|
} on HttpException {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<AppUpdate> fetchLatestScoped(
|
|
Uri base,
|
|
Map<String, String> Function(Uri) headers, {
|
|
List<List<int>>? trustedKeys,
|
|
}) async {
|
|
final trusted = trustedKeys ?? trustedUpdateKeys();
|
|
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, feed.resolve('version.json'), headers);
|
|
final chunks = await _body(response, 65536);
|
|
// The signature is checked before anything in the feed (the artifact's
|
|
// sha256 above all) is believed.
|
|
final problem = feedSignatureProblem(
|
|
chunks,
|
|
trusted.isEmpty ? null : await _signature(client, feed, headers),
|
|
trusted,
|
|
);
|
|
if (problem != null) throw FormatException(problem);
|
|
final update = AppUpdate.parse(
|
|
utf8.decode(chunks),
|
|
feed,
|
|
platform: platform,
|
|
architecture: nativeArchitecture,
|
|
installedSignature: platform == 'android'
|
|
? (await PackageInfo.fromPlatform()).buildSignature
|
|
: null,
|
|
signed: trusted.isNotEmpty,
|
|
);
|
|
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 {
|
|
if (Platform.isLinux) {
|
|
// Linux installs in place: download, verify, swap the bundle, relaunch.
|
|
final installer = LinuxSelfUpdate.current();
|
|
final problem = await installer.problem();
|
|
if (problem != null) throw FileSystemException(problem);
|
|
final file = await downloadUpdate(
|
|
update,
|
|
await getTemporaryDirectory(),
|
|
onProgress: onProgress,
|
|
);
|
|
final String executable;
|
|
try {
|
|
executable = await installer.install(
|
|
file,
|
|
versionCode: update.versionCode,
|
|
);
|
|
} finally {
|
|
if (await file.exists()) await file.delete();
|
|
}
|
|
await LinuxSelfUpdate.relaunch(executable);
|
|
}
|
|
if (Platform.isMacOS) {
|
|
// macOS installs in place too: download, verify, swap the bundle, relaunch.
|
|
final installer = MacSelfUpdate.current();
|
|
final problem = await installer.problem();
|
|
if (problem != null) throw FileSystemException(problem);
|
|
final file = await downloadUpdate(
|
|
update,
|
|
await getTemporaryDirectory(),
|
|
onProgress: onProgress,
|
|
);
|
|
final String app;
|
|
try {
|
|
app = await installer.install(file, versionCode: update.versionCode);
|
|
} finally {
|
|
if (await file.exists()) await file.delete();
|
|
}
|
|
await MacSelfUpdate.relaunch(app);
|
|
}
|
|
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}',
|
|
);
|
|
}
|
|
}
|