diff --git a/.github/workflows/enhanced-apk.yml b/.github/workflows/enhanced-apk.yml new file mode 100644 index 00000000..37320758 --- /dev/null +++ b/.github/workflows/enhanced-apk.yml @@ -0,0 +1,75 @@ +name: Build Atrium Enhanced APK +on: + workflow_dispatch: + push: + branches: + - rmg + - 'feature/**' + - 'fix/**' + - 'refactor/**' +permissions: + contents: write +jobs: + build: + if: github.event_name == 'workflow_dispatch' || contains(github.event.head_commit.message, '[build apk]') + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + cache-dependency-path: | + app/android/**/*.gradle* + app/android/gradle/wrapper/gradle-wrapper.properties + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.41.9' + channel: stable + cache: true + pub-cache: true + - name: Restore release signing credentials + env: + KEYSTORE: ${{ secrets.ATRIUM_KEYSTORE_BASE64 }} + STORE_PASSWORD: ${{ secrets.ATRIUM_KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.ATRIUM_KEY_ALIAS }} + KEY_PASSWORD: ${{ secrets.ATRIUM_KEY_PASSWORD }} + run: | + set -eu + test -n "$KEYSTORE" && test -n "$STORE_PASSWORD" && test -n "$KEY_ALIAS" && test -n "$KEY_PASSWORD" + printf '%s' "$KEYSTORE" | base64 --decode > "$RUNNER_TEMP/atrium-release.jks" + chmod 600 "$RUNNER_TEMP/atrium-release.jks" + printf 'storeFile=%s\nstorePassword=%s\nkeyAlias=%s\nkeyPassword=%s\n' "$RUNNER_TEMP/atrium-release.jks" "$STORE_PASSWORD" "$KEY_ALIAS" "$KEY_PASSWORD" > app/android/key.properties + chmod 600 app/android/key.properties + - name: Resolve dependencies + working-directory: app + run: | + flutter config --no-analytics + flutter pub get --enforce-lockfile + - name: Generate sources + run: dart run tool/build_all.dart + # Build 19 passed installation and channel discovery; next release tests in-app installation. + - name: Build signed universal APK + working-directory: app + run: flutter build apk --release --build-number="$GITHUB_RUN_NUMBER" + - name: Verify APK signature + run: | + APKSIGNER="$(find "$ANDROID_HOME/build-tools" -name apksigner -type f | sort -V | tail -n 1)" + "$APKSIGNER" verify --print-certs app/build/app/outputs/flutter-apk/app-release.apk + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -eu + APK="Atrium-Enhanced-${GITHUB_RUN_NUMBER}.apk" + cp app/build/app/outputs/flutter-apk/app-release.apk "$APK" + printf 'Branch: %s\nBuild: %s\nCommit: %s\n' "$GITHUB_REF_NAME" "$GITHUB_RUN_NUMBER" "$GITHUB_SHA" > release-notes.txt + if [ "$GITHUB_REF_NAME" = rmg ]; then + gh release create "enhanced-$GITHUB_RUN_NUMBER" "$APK" --target "$GITHUB_SHA" --title "Atrium Enhanced build $GITHUB_RUN_NUMBER" --notes-file release-notes.txt + else + gh release create "enhanced-$GITHUB_RUN_NUMBER" "$APK" --target "$GITHUB_SHA" --prerelease --title "Atrium Enhanced test build $GITHUB_RUN_NUMBER" --notes-file release-notes.txt + fi + - name: Remove signing material + if: always() + run: rm -f app/android/key.properties "$RUNNER_TEMP/atrium-release.jks" diff --git a/.github/workflows/enhanced-validate.yml b/.github/workflows/enhanced-validate.yml new file mode 100644 index 00000000..b849cd11 --- /dev/null +++ b/.github/workflows/enhanced-validate.yml @@ -0,0 +1,28 @@ +name: Validate Enhanced updater +on: + workflow_dispatch: + push: + branches: + - 'feature/**' + - 'fix/**' + - rmg +permissions: + contents: read +jobs: + validate: + if: github.event_name == 'workflow_dispatch' || contains(github.event.head_commit.message, '[validate updater]') + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.41.9' + channel: stable + cache: true + - run: flutter pub get --enforce-lockfile + working-directory: app + - run: dart run tool/build_all.dart + - run: dart analyze lib/src/update_check + working-directory: app + - run: flutter test test/update_check + working-directory: app diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts index 1a71e73d..12c075dd 100644 --- a/app/android/app/build.gradle.kts +++ b/app/android/app/build.gradle.kts @@ -48,7 +48,7 @@ android { } defaultConfig { - applicationId = "app.atrium" + applicationId = "com.koinupapi.atrium.enhanced" // local_auth + flutter_secure_storage need API 23+ (BiometricPrompt, // EncryptedSharedPreferences). Floor at 23 regardless of Flutter's // default. @@ -61,7 +61,7 @@ android { val appNameProp = if (project.hasProperty("appName")) { project.property("appName") as String } else { - "Atrium" + "Atrium Enhanced" } manifestPlaceholders["appName"] = appNameProp } diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index dc919bd0..65e4accf 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -6,6 +6,8 @@ + + + + + + try { + when (call.method) { + "installedBuild" -> { + @Suppress("DEPRECATION") + val info = packageManager.getPackageInfo(packageName, 0) + @Suppress("DEPRECATION") + val version = if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong() + result.success(version) + } + "cacheDirectory" -> result.success(java.io.File(cacheDir, "updates").apply { mkdirs() }.absolutePath) + "sha256" -> { + val directory = java.io.File(cacheDir, "updates").canonicalFile + val file = java.io.File(requireNotNull(call.argument("path"))).canonicalFile + require(file.parentFile == directory && file.isFile) + Thread { + try { + val digest = java.security.MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buffer = ByteArray(65536) + while (true) { + val count = input.read(buffer) + if (count < 0) break + digest.update(buffer, 0, count) + } + } + val hash = digest.digest().joinToString("") { "%02x".format(it) } + runOnUiThread { result.success(hash) } + } catch (e: Exception) { + runOnUiThread { result.error("HASH_ERROR", e.message, null) } + } + }.start() + } + "install" -> { + val directory = java.io.File(cacheDir, "updates").canonicalFile + val file = java.io.File(requireNotNull(call.argument("path"))).canonicalFile + require(file.parentFile == directory && file.extension == "apk" && file.isFile) + if (Build.VERSION.SDK_INT >= 26 && !packageManager.canRequestPackageInstalls()) { + startActivity(Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:$packageName"))) + result.success(false) + } else { + val uri = androidx.core.content.FileProvider.getUriForFile(this, "$packageName.updates", file) + startActivity(Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + }) + result.success(true) + } + } + else -> result.notImplemented() + } + } catch (e: Exception) { + result.error("UPDATE_ERROR", e.message, null) + } + } + pendingShareIntent = intent shareChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, SHARE_CHANNEL).apply { diff --git a/app/android/app/src/main/res/values/colors.xml b/app/android/app/src/main/res/values/colors.xml index 9b5e432e..0adf1e08 100644 --- a/app/android/app/src/main/res/values/colors.xml +++ b/app/android/app/src/main/res/values/colors.xml @@ -1,4 +1,4 @@ - #6750A4 - \ No newline at end of file + #243A67 + diff --git a/app/android/app/src/main/res/xml/enhanced_update_paths.xml b/app/android/app/src/main/res/xml/enhanced_update_paths.xml new file mode 100644 index 00000000..19969447 --- /dev/null +++ b/app/android/app/src/main/res/xml/enhanced_update_paths.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/lib/src/update_check/enhanced_download.dart b/app/lib/src/update_check/enhanced_download.dart new file mode 100644 index 00000000..46e4abb6 --- /dev/null +++ b/app/lib/src/update_check/enhanced_download.dart @@ -0,0 +1,40 @@ +import 'dart:io'; +import 'package:dio/dio.dart'; +import 'package:flutter/services.dart'; +import 'enhanced_release.dart'; + +class EnhancedDownload { + static const channel = MethodChannel('app.atrium/enhanced_updates'); + static Future installedBuild() async => + (await channel.invokeMethod('installedBuild'))!; + static Future install(String path) async => + (await channel.invokeMethod('install', {'path': path})) ?? false; + + Future download(EnhancedRelease release, CancelToken token, + void Function(int, int) progress) async { + final directory = (await channel.invokeMethod('cacheDirectory'))!; + final target = File('$directory/Atrium-Enhanced-${release.build}.apk'); + final part = File('${target.path}.part'); + final dio = Dio(BaseOptions(connectTimeout: const Duration(seconds: 15), + receiveTimeout: const Duration(seconds: 60))); + try { + await dio.download(release.url, part.path, cancelToken: token, + onReceiveProgress: progress); + final size = await part.length(); + if (size == 0 || (release.size > 0 && size != release.size)) { + throw StateError('APK size mismatch'); + } + if (release.digest.isNotEmpty) { + final actual = await channel.invokeMethod('sha256', {'path': part.path}); + if ('sha256:$actual' != release.digest.toLowerCase()) { + throw StateError('APK checksum mismatch'); + } + } + if (token.isCancelled) throw StateError('Download cancelled'); + return (await part.rename(target.path)).path; + } finally { + dio.close(force: true); + if (await part.exists()) await part.delete(); + } + } +} diff --git a/app/lib/src/update_check/enhanced_release.dart b/app/lib/src/update_check/enhanced_release.dart new file mode 100644 index 00000000..122518d3 --- /dev/null +++ b/app/lib/src/update_check/enhanced_release.dart @@ -0,0 +1,75 @@ +import 'package:dio/dio.dart'; + +class EnhancedRelease { + const EnhancedRelease(this.build, this.branch, this.url, this.page, + this.digest, this.notes, this.date, this.size); + final int build; + final String branch, url, page, digest, notes, date; + final int size; + + static EnhancedRelease? parse(Map data) { + if (data['draft'] == true) return null; + final match = RegExp(r'^enhanced-(\d+)$').firstMatch(data['tag_name'] as String? ?? ''); + if (match == null) return null; + final build = int.parse(match.group(1)!); + final notes = data['body'] as String? ?? ''; + final branch = RegExp(r'^Branch: (.+)$', multiLine: true).firstMatch(notes)?.group(1)?.trim(); + if (branch == null || !allowedBranch(branch)) return null; + for (final raw in data['assets'] as List? ?? []) { + final asset = Map.from(raw as Map); + if (asset['name'] != 'Atrium-Enhanced-$build.apk') continue; + final url = asset['browser_download_url'] as String? ?? ''; + if (url != 'https://github.com/koinupapi/Atrium-Enhanced/releases/download/enhanced-$build/Atrium-Enhanced-$build.apk') continue; + return EnhancedRelease(build, branch, url, data['html_url'] as String? ?? '', + asset['digest'] as String? ?? '', notes, data['published_at'] as String? ?? '', + asset['size'] as int? ?? 0); + } + return null; + } + + static bool allowedBranch(String branch) => branch == 'rmg' || + ['feature/', 'fix/', 'refactor/'].any(branch.startsWith); +} + +class EnhancedReleaseRepository { + EnhancedReleaseRepository(this.dio); + final Dio dio; + static const repo = 'repos/koinupapi/Atrium-Enhanced'; + + Future> _pages(String endpoint) async { + final items = []; + for (var page = 1; ; page++) { + final response = await dio.get>('$repo/$endpoint', + queryParameters: {'per_page': 100, 'page': page}); + final batch = response.data ?? []; + items.addAll(batch); + if (batch.length < 100) return items; + } + } + + Future> branches() async { + final names = (await _pages('branches')).map((e) => e['name'] as String) + .where(EnhancedRelease.allowedBranch).toSet()..add('rmg'); + return names.toList()..sort((a,b) => a == b ? 0 : a == 'rmg' ? -1 : b == 'rmg' ? 1 : a.compareTo(b)); + } + + Future latest(String branch) async { + final releases = (await _pages('releases')) + .map((e) => EnhancedRelease.parse(Map.from(e as Map))) + .whereType().where((e) => e.branch == branch).toList() + ..sort((a,b) => b.build.compareTo(a.build)); + return releases.isEmpty ? null : releases.first; + } + + static String describeError(Object error) { + if (error is DioException) { + final response = error.response; + final reset = int.tryParse(response?.headers.value('x-ratelimit-reset') ?? ''); + if (response?.headers.value('x-ratelimit-remaining') == '0' && reset != null) { + return 'GitHub rate limit reached. Retry after ${DateTime.fromMillisecondsSinceEpoch(reset * 1000).toLocal()}.'; + } + return 'GitHub request failed: ${response?.statusCode ?? error.type.name}'; + } + return error.toString(); + } +} diff --git a/app/lib/src/update_check/update_check_state.dart b/app/lib/src/update_check/update_check_state.dart index ce4ebb89..9a433a18 100644 --- a/app/lib/src/update_check/update_check_state.dart +++ b/app/lib/src/update_check/update_check_state.dart @@ -22,6 +22,7 @@ class UpdateCheckState { this.checkedAt, this.latestNotes, this.latestDate, + this.newerBuild, }); final UpdateStatus status; @@ -30,10 +31,11 @@ class UpdateCheckState { final DateTime? checkedAt; final String? latestNotes; final String? latestDate; + final bool? newerBuild; /// True when the last known latest release is newer than the running app. bool get hasNewer => - latestVersion != null && compareVersions(latestVersion!, appVersion) > 0; + newerBuild ?? (latestVersion != null && compareVersions(latestVersion!, appVersion) > 0); UpdateCheckState copyWith({UpdateStatus? status}) => UpdateCheckState( status: status ?? this.status, @@ -42,5 +44,6 @@ class UpdateCheckState { checkedAt: checkedAt, latestNotes: latestNotes, latestDate: latestDate, + newerBuild: newerBuild, ); } diff --git a/app/lib/src/update_check/update_check_tile.dart b/app/lib/src/update_check/update_check_tile.dart index 8795ae21..bab02602 100644 --- a/app/lib/src/update_check/update_check_tile.dart +++ b/app/lib/src/update_check/update_check_tile.dart @@ -1,55 +1,115 @@ +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../external_links.dart'; +import 'enhanced_download.dart'; +import 'enhanced_release.dart'; import 'update_check_state.dart'; import 'update_checker.dart'; -/// Settings tile that runs the manual update check and shows its result. -class UpdateCheckTile extends ConsumerWidget { +class UpdateCheckTile extends ConsumerStatefulWidget { const UpdateCheckTile({super.key}); + @override + ConsumerState createState() => _UpdateCheckTileState(); +} + +class _UpdateCheckTileState extends ConsumerState { + CancelToken? token; + double? progress; + String? downloaded; + int? downloadedBuild; + bool busy = false; + + @override + void dispose() { + token?.cancel(); + super.dispose(); + } + + void message(String text) { + if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text))); + } + + Future choose(UpdateChecker checker) async { + setState(() => busy = true); + try { + final branches = await checker.branches(); + if (!mounted) return; + final chosen = await showDialog(context: context, builder: (context) => + SimpleDialog(title: const Text('Update channel'), children: [ + for (final branch in branches) + SimpleDialogOption(onPressed: () => Navigator.pop(context, branch), + child: Text(branch == 'rmg' ? 'Stable — rmg' : branch)), + ])); + if (chosen != null && mounted) { + downloaded = null; + await checker.selectBranch(chosen); + } + } catch (error) { + message(EnhancedReleaseRepository.describeError(error)); + } finally { + if (mounted) setState(() => busy = false); + } + } + + Future install(EnhancedRelease release) async { + setState(() { busy = true; progress = null; }); + final cancel = CancelToken(); + token = cancel; + try { + if (downloaded == null || downloadedBuild != release.build) { + downloaded = await EnhancedDownload().download(release, cancel, (received, total) { + if (mounted) setState(() => progress = total > 0 ? received / total : null); + }); + downloadedBuild = release.build; + } + if (!mounted || cancel.isCancelled) return; + final launched = await EnhancedDownload.install(downloaded!); + if (!launched) message('Allow installs from Atrium Enhanced, then tap Install again.'); + } catch (error) { + downloaded = null; + if (!cancel.isCancelled) message('Update failed: $error'); + } finally { + token = null; + if (mounted) setState(() { busy = false; progress = null; }); + } + } @override - Widget build(BuildContext context, WidgetRef ref) { - final UpdateCheckState state = ref.watch(updateCheckProvider); - final UpdateChecker checker = ref.read(updateCheckProvider.notifier); - - final (String subtitle, Widget? trailing, bool tappable) = - switch (state.status) { - UpdateStatus.idle => ('Tap to check', null, true), - UpdateStatus.checking => ( - 'Checking...', - const SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator(strokeWidth: 2), - ), - false, - ), - UpdateStatus.upToDate => ('Up to date', null, true), - UpdateStatus.updateAvailable => ( - 'Version ${state.latestVersion} is available', - const Icon(Icons.open_in_new, size: 18), - true, - ), - UpdateStatus.error => ('Could not check, tap to retry', null, true), - }; - - return ListTile( - leading: const Icon(Icons.system_update_outlined), - title: const Text('Check for updates'), - subtitle: Text(subtitle), - trailing: trailing, - onTap: !tappable - ? null - : () { - if (state.status == UpdateStatus.updateAvailable && - state.releaseUrl != null) { - openExternal(ScaffoldMessenger.of(context), state.releaseUrl!); - } else { - checker.check(); - } - }, - ); + Widget build(BuildContext context) { + final state = ref.watch(updateCheckProvider); + final checker = ref.read(updateCheckProvider.notifier); + final checking = state.status == UpdateStatus.checking; + final release = checker.release; + return Column(mainAxisSize: MainAxisSize.min, children: [ + ListTile(leading: const Icon(Icons.alt_route), title: const Text('Update channel'), + subtitle: Text(checker.branch), onTap: busy || checking ? null : () => choose(checker)), + ListTile(leading: const Icon(Icons.system_update_outlined), + title: const Text('Check for updates'), + subtitle: Text(switch (state.status) { + UpdateStatus.idle => 'Tap to check', + UpdateStatus.checking => 'Checking...', + UpdateStatus.upToDate => checker.diagnostic ?? 'Up to date', + UpdateStatus.updateAvailable => 'Build ${state.latestVersion} is available', + UpdateStatus.error => checker.diagnostic ?? 'Could not check, tap to retry', + }), + trailing: checking ? const SizedBox(width: 18, height: 18, + child: CircularProgressIndicator(strokeWidth: 2)) : null, + onTap: busy || checking ? null : () => checker.check()), + if (checker.installed != null) + ListTile(title: Text('Installed build #${checker.installed}'), + subtitle: Text(checker.diagnostic ?? '')), + if (state.status == UpdateStatus.updateAvailable && release != null) ...[ + ListTile(title: Text(downloadedBuild == release.build && downloaded != null ? 'Install update' : 'Download and install'), + leading: const Icon(Icons.download), onTap: busy ? null : () => install(release)), + ListTile(title: const Text('View release on GitHub'), leading: const Icon(Icons.open_in_new), + onTap: () => openExternal(ScaffoldMessenger.of(context), release.page)), + ], + if (token != null) ...[ + LinearProgressIndicator(value: progress), + TextButton(onPressed: () => token?.cancel(), child: const Text('Cancel download')), + ], + ]); } } diff --git a/app/lib/src/update_check/update_checker.dart b/app/lib/src/update_check/update_checker.dart index 2f1186c1..20d189b6 100644 --- a/app/lib/src/update_check/update_checker.dart +++ b/app/lib/src/update_check/update_checker.dart @@ -1,12 +1,12 @@ +import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:hive_ce/hive.dart'; -import '../external_links.dart'; +import 'enhanced_release.dart'; +import 'enhanced_download.dart'; import '../preferences.dart'; -import 'app_version.dart'; import 'update_check_state.dart'; -import 'version_compare.dart'; /// A plain Dio for the GitHub API, no per-instance auth. Overridden in tests. final Provider githubDioProvider = Provider((Ref ref) { @@ -50,91 +50,77 @@ String? extractWhatsNew(String body) { /// Checks GitHub for a newer release, only when [check] is called. Never /// fetches on construction; [build] only reads the persisted last result. class UpdateChecker extends Notifier { - static const String _latestKey = 'update.latestVersion'; - static const String _urlKey = 'update.releaseUrl'; - static const String _checkedAtKey = 'update.checkedAt'; - static const String _notesKey = 'update.latestNotes'; - static const String _dateKey = 'update.latestDate'; - Box get _box => ref.read(settingsBoxProvider); + String get cacheKey => 'enhanced.release.$branch'; + String get branch => _box.get('enhanced.branch') ?? 'rmg'; + EnhancedRelease? release; + int? installed; + String? diagnostic; + EnhancedReleaseRepository get repository => EnhancedReleaseRepository(ref.read(githubDioProvider)); @override UpdateCheckState build() { - final String? latest = _box.get(_latestKey); - final String? url = _box.get(_urlKey); - final String? checkedAtRaw = _box.get(_checkedAtKey); - final DateTime? checkedAt = - checkedAtRaw == null ? null : DateTime.tryParse(checkedAtRaw); - final String? notes = _box.get(_notesKey); - final String? date = _box.get(_dateKey); - - final UpdateStatus status; - if (latest == null) { - status = UpdateStatus.idle; - } else if (compareVersions(latest, appVersion) > 0) { - status = UpdateStatus.updateAvailable; - } else { - status = UpdateStatus.upToDate; + final raw = _box.get(cacheKey); + if (raw == null) return const UpdateCheckState(); + try { + final data = jsonDecode(raw) as Map; + final latest = EnhancedRelease.parse(data['release'] as Map); + if (latest == null || latest.branch != branch) return const UpdateCheckState(); + release = latest; + // A fresh check reads Android's actual version before offering installation. + return UpdateCheckState(latestVersion: latest.build.toString(), + releaseUrl: latest.page, latestNotes: latest.notes, + latestDate: latest.date.split('T').first, newerBuild: false, + checkedAt: DateTime.tryParse(data['checkedAt'] as String)); + } catch (_) { + return const UpdateCheckState(); } - return UpdateCheckState( - status: status, - latestVersion: latest, - releaseUrl: url, - checkedAt: checkedAt, - latestNotes: notes, - latestDate: date, - ); } - /// Fetches the latest release and updates state. Errors keep the durable - /// fields so a known "available" banner survives a failed check. + Future> branches() => repository.branches(); + + Future selectBranch(String value) async { + if (!EnhancedRelease.allowedBranch(value)) return; + await _box.put('enhanced.branch', value); + release = null; + state = const UpdateCheckState(); + await check(); + } + Future check() async { + if (state.status == UpdateStatus.checking) return; state = state.copyWith(status: UpdateStatus.checking); try { - final Dio dio = ref.read(githubDioProvider); - final Response> res = - await dio.get>( - 'repos/retransmit/Atrium/releases/latest', - ); - final Map data = res.data ?? {}; - final String? tag = data['tag_name'] as String?; - if (tag == null || tag.isEmpty) { - state = state.copyWith(status: UpdateStatus.error); - return; - } - final String latest = tag.startsWith('v') ? tag.substring(1) : tag; - final String url = (data['html_url'] as String?) ?? AtriumLinks.releases; - final String? body = data['body'] as String?; - final String? notes = body == null ? null : extractWhatsNew(body); - final String? publishedAt = data['published_at'] as String?; - final String? date = (publishedAt != null && publishedAt.length >= 10) - ? publishedAt.substring(0, 10) - : null; - final DateTime now = DateTime.now(); - await _box.put(_latestKey, latest); - await _box.put(_urlKey, url); - await _box.put(_checkedAtKey, now.toIso8601String()); - if (notes == null) { - await _box.delete(_notesKey); + installed = await EnhancedDownload.installedBuild(); + release = await repository.latest(branch); + final latest = release; + diagnostic = latest == null ? 'No APK releases for $branch.' : + 'Latest release for $branch: build ${latest.build}. Installed: $installed.'; + final newer = latest != null && latest.build > installed!; + if (latest == null) { + await _box.delete(cacheKey); } else { - await _box.put(_notesKey, notes); - } - if (date == null) { - await _box.delete(_dateKey); - } else { - await _box.put(_dateKey, date); + await _box.put(cacheKey, jsonEncode({ + 'checkedAt': DateTime.now().toIso8601String(), + 'release': { + 'tag_name': 'enhanced-${latest.build}', 'body': latest.notes, + 'html_url': latest.page, 'published_at': latest.date, + 'assets': [{'name': 'Atrium-Enhanced-${latest.build}.apk', + 'browser_download_url': latest.url, 'digest': latest.digest, 'size': latest.size}] + } + })); } state = UpdateCheckState( - status: compareVersions(latest, appVersion) > 0 - ? UpdateStatus.updateAvailable - : UpdateStatus.upToDate, - latestVersion: latest, - releaseUrl: url, - checkedAt: now, - latestNotes: notes, - latestDate: date, + status: newer ? UpdateStatus.updateAvailable : UpdateStatus.upToDate, + latestVersion: latest?.build.toString(), + releaseUrl: latest?.page, + checkedAt: DateTime.now(), + latestNotes: latest?.notes, + latestDate: latest?.date.split('T').first, + newerBuild: newer, ); - } catch (_) { + } catch (error) { + diagnostic = EnhancedReleaseRepository.describeError(error); state = state.copyWith(status: UpdateStatus.error); } } diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 1dbd41b5..96a4edac 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -86,7 +86,7 @@ flutter_launcher_icons: android: true ios: false image_path: "assets/icon/atrium_icon.png" - adaptive_icon_background: "#6750A4" + adaptive_icon_background: "#243A67" adaptive_icon_foreground: "assets/icon/atrium_foreground.png" adaptive_icon_monochrome: "assets/icon/atrium_foreground.png" min_sdk_android: 23 diff --git a/app/test/update_check/update_check_widgets_test.dart b/app/test/update_check/update_check_widgets_test.dart index 4b56a3c1..9f74e8a0 100644 --- a/app/test/update_check/update_check_widgets_test.dart +++ b/app/test/update_check/update_check_widgets_test.dart @@ -1,3 +1,4 @@ +import 'package:atrium/src/update_check/enhanced_release.dart'; import 'package:atrium/src/update_check/update_check_state.dart'; import 'package:atrium/src/update_check/update_check_tile.dart'; import 'package:atrium/src/update_check/update_checker.dart'; @@ -7,7 +8,14 @@ import 'package:flutter_riverpod/misc.dart'; import 'package:flutter_test/flutter_test.dart'; class _FixedChecker extends UpdateChecker { - _FixedChecker(this._fixed); + _FixedChecker(this._fixed) { + if (_fixed.status == UpdateStatus.updateAvailable) { + release = const EnhancedRelease(99, 'rmg', 'https://example/apk', + 'https://example/tag', '', '', '', 100); + } + } + @override + String get branch => 'rmg'; final UpdateCheckState _fixed; @override UpdateCheckState build() => _fixed; @@ -31,20 +39,24 @@ void main() { await _pump(tester, const UpdateCheckState(), const UpdateCheckTile()); expect(find.text('Check for updates'), findsOneWidget); expect(find.text('Tap to check'), findsOneWidget); + expect(find.text('Update channel'), findsOneWidget); + expect(find.text('rmg'), findsOneWidget); + expect(find.text('Download and install'), findsNothing); }); - testWidgets('tile shows the available version and an open icon', + testWidgets('tile shows the available build and install action', (WidgetTester tester) async { await _pump( tester, const UpdateCheckState( status: UpdateStatus.updateAvailable, - latestVersion: '9.9.9', + latestVersion: '99', releaseUrl: 'https://example/tag', ), const UpdateCheckTile(), ); - expect(find.text('Version 9.9.9 is available'), findsOneWidget); + expect(find.text('Build 99 is available'), findsOneWidget); expect(find.byIcon(Icons.open_in_new), findsOneWidget); + expect(find.text('Download and install'), findsOneWidget); }); } diff --git a/app/test/update_check/update_checker_test.dart b/app/test/update_check/update_checker_test.dart index 2966fc45..1e36eea9 100644 --- a/app/test/update_check/update_checker_test.dart +++ b/app/test/update_check/update_checker_test.dart @@ -1,144 +1,42 @@ -import 'dart:io'; - -import 'package:atrium/src/preferences.dart'; -import 'package:atrium/src/update_check/update_check_state.dart'; +import 'package:atrium/src/update_check/enhanced_release.dart'; import 'package:atrium/src/update_check/update_checker.dart'; -import 'package:dio/dio.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_riverpod/misc.dart'; -import 'package:hive_ce/hive.dart'; - +import 'package:dio/dio.dart'; import '../support/fake_http_client_adapter.dart'; -Dio _dio(({int status, Object? data}) Function(RequestOptions) factory) { - final Dio dio = Dio(BaseOptions(baseUrl: 'https://api.github.com/')); - dio.httpClientAdapter = FakeHttpClientAdapter(factory); - return dio; -} - -ProviderContainer _container(Box box, Dio dio) { - final ProviderContainer container = ProviderContainer( - overrides: [ - settingsBoxProvider.overrideWithValue(box), - githubDioProvider.overrideWithValue(dio), - ], - ); - addTearDown(container.dispose); - return container; -} +Map release(int build, String branch) => { + 'tag_name': 'enhanced-$build', + 'body': 'Branch: $branch\nBuild: $build', + 'assets': [{ + 'name': 'Atrium-Enhanced-$build.apk', + 'browser_download_url': 'https://github.com/koinupapi/Atrium-Enhanced/releases/download/enhanced-$build/Atrium-Enhanced-$build.apk', + 'size': 100, + }], +}; void main() { - late Directory tempDir; - late Box box; - - setUp(() async { - tempDir = Directory.systemTemp.createTempSync('atrium_update'); - Hive.init(tempDir.path); - box = await Hive.openBox('settings'); - }); - - tearDown(() async { - await box.close(); - await Hive.deleteBoxFromDisk('settings'); - tempDir.deleteSync(recursive: true); - }); - - test('a newer release marks updateAvailable and is persisted', () async { - final ProviderContainer c = _container( - box, - _dio((RequestOptions o) => ( - status: 200, - data: { - 'tag_name': 'v9.9.9', - 'html_url': 'https://github.com/retransmit/Atrium/releases/tag/v9.9.9', - }, - )), - ); - await c.read(updateCheckProvider.notifier).check(); - final UpdateCheckState s = c.read(updateCheckProvider); - expect(s.status, UpdateStatus.updateAvailable); - expect(s.latestVersion, '9.9.9'); - expect(box.get('update.latestVersion'), '9.9.9'); - }); - - test('the same release marks upToDate', () async { - final ProviderContainer c = _container( - box, - _dio((RequestOptions o) => - (status: 200, data: {'tag_name': 'v1.3.3'})), - ); - await c.read(updateCheckProvider.notifier).check(); - expect(c.read(updateCheckProvider).status, UpdateStatus.upToDate); - expect(c.read(updateCheckProvider).hasNewer, isFalse); - }); - - test('a server error sets error but keeps a known available banner', () async { - await box.put('update.latestVersion', '9.9.9'); - final ProviderContainer c = _container( - box, - _dio((RequestOptions o) => (status: 500, data: {})), - ); - // build() re-derived updateAvailable from the cached 9.9.9. - expect(c.read(updateCheckProvider).status, UpdateStatus.updateAvailable); - await c.read(updateCheckProvider.notifier).check(); - final UpdateCheckState s = c.read(updateCheckProvider); - expect(s.status, UpdateStatus.error); - expect(s.hasNewer, isTrue); - }); - - test('build re-derives from cache with no network', () async { - await box.put('update.latestVersion', '9.9.9'); - final ProviderContainer c = _container( - box, - _dio((RequestOptions o) => throw StateError('must not be called')), - ); - final UpdateCheckState s = c.read(updateCheckProvider); - expect(s.status, UpdateStatus.updateAvailable); - expect(s.latestVersion, '9.9.9'); - }); - - test('extractWhatsNew returns the section between the markers', () { - const String body = - 'Intro line.\n\n## What\'s new\n\n**Feature.** Did a thing.\n\n## Which APK\n\nMost phones want arm64.'; - expect(extractWhatsNew(body), '**Feature.** Did a thing.'); - }); - - test('extractWhatsNew returns null without the marker', () { - expect(extractWhatsNew('No headings here, just text.'), isNull); - }); - - test('a newer release persists and exposes its notes and date', () async { - final ProviderContainer c = _container( - box, - _dio((RequestOptions o) => ( - status: 200, - data: { - 'tag_name': 'v9.9.9', - 'html_url': 'https://github.com/retransmit/Atrium/releases/tag/v9.9.9', - 'published_at': '2026-08-01T10:00:00Z', - 'body': 'Intro.\n\n## What\'s new\n\n**Nice thing.** Details.\n\n## Which APK\n\narm64.', - }, - )), - ); - await c.read(updateCheckProvider.notifier).check(); - final UpdateCheckState s = c.read(updateCheckProvider); - expect(s.latestNotes, '**Nice thing.** Details.'); - expect(s.latestDate, '2026-08-01'); - expect(box.get('update.latestNotes'), '**Nice thing.** Details.'); - expect(box.get('update.latestDate'), '2026-08-01'); - }); - - test('build re-derives notes and date from cache with no network', () async { - await box.put('update.latestVersion', '9.9.9'); - await box.put('update.latestNotes', '**Cached.** From disk.'); - await box.put('update.latestDate', '2026-09-09'); - final ProviderContainer c = _container( - box, - _dio((RequestOptions o) => throw StateError('must not be called')), - ); - final UpdateCheckState s = c.read(updateCheckProvider); - expect(s.latestNotes, '**Cached.** From disk.'); - expect(s.latestDate, '2026-09-09'); + test('parses signed release metadata', () { + final result = EnhancedRelease.parse(release(12, 'rmg')); + expect(result?.build, 12); + expect(result?.branch, 'rmg'); + }); + test('rejects upstream branches, drafts and unexpected asset URLs', () { + expect(EnhancedRelease.parse(release(12, 'main')), isNull); + expect(EnhancedRelease.parse({...release(12, 'rmg'), 'draft': true}), isNull); + expect(EnhancedRelease.parse({...release(12, 'rmg'), 'assets': [ + {'name': 'Atrium-Enhanced-12.apk', 'browser_download_url': 'https://example.com/file.apk'} + ]}), isNull); + }); + test('selects highest numeric build on requested branch', () async { + final dio = Dio(BaseOptions(baseUrl: 'https://api.github.com/')); + dio.httpClientAdapter = FakeHttpClientAdapter((_) => (status: 200, data: [ + release(9, 'rmg'), release(10, 'rmg'), release(99, 'feature/test') + ])); + expect((await EnhancedReleaseRepository(dio).latest('rmg'))?.build, 10); + expect(await EnhancedReleaseRepository(dio).latest('fix/missing'), isNull); + }); + test('extracts changelog section', () { + expect(extractWhatsNew("Intro\n## What's new\nFeature\n## APK\nOther"), 'Feature'); + expect(extractWhatsNew('No headings'), isNull); }); }