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 '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 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 _get( HttpClient client, Uri uri, [ Map 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(); throw const HttpException('Sign in first (Settings → Sign in).'); } if (response.statusCode != 200) { await response.drain(); throw HttpException('The server answered ${response.statusCode}.'); } return response; } Future fetchLatest(Uri base) => fetchLatestScoped(base, ServerSession.headersFor); /// Reads at most [limit] bytes of [response]. Future> _body(HttpClientResponse response, int limit) async { final chunks = []; 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 _signature( HttpClient client, Uri feed, Map 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 fetchLatestScoped( Uri base, Map Function(Uri) headers, { List>? 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 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 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); } 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}', ); } }