167 lines
5.3 KiB
Dart
167 lines
5.3 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';
|
|
|
|
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);
|
|
|
|
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, 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,
|
|
installedSignature: platform == 'android'
|
|
? (await PackageInfo.fromPlatform()).buildSignature
|
|
: null,
|
|
);
|
|
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 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}',
|
|
);
|
|
}
|
|
}
|