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

77 lines
2.5 KiB
Dart

import 'dart:io';
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;
Future<int?> installedVersionCode() async {
final info = await PackageInfo.fromPlatform();
return int.tryParse(info.buildNumber);
}
Future<HttpClientResponse> _get(HttpClient client, Uri uri) async {
final request = await client.getUrl(uri);
// The updates sit behind the same web login the app signed in to.
ServerSession.headers.forEach(request.headers.set);
final response = await request.close();
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) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final response = await _get(client, base.resolve('version.json'));
final body = await response
.transform(const SystemEncoding().decoder)
.join();
final update = AppUpdate.parse(body, base);
if (update == null) throw const FormatException('No build is offered.');
return update;
} finally {
client.close(force: true);
}
}
Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final response = await _get(client, update.apk);
final total = response.contentLength;
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/pipelines-${update.versionCode}.apk');
final sink = file.openWrite();
var received = 0;
await for (final chunk in response) {
sink.add(chunk);
received += chunk.length;
if (total > 0) onProgress?.call(received / total);
}
await sink.close();
final result = await OpenFilex.open(
file.path,
type: 'application/vnd.android.package-archive',
);
if (result.type != ResultType.done) {
throw HttpException('Could not open the installer: ${result.message}');
}
} finally {
client.close(force: true);
}
}