Add scheduled TV updates from Forgejo
Check a commit-pinned manifest on a configurable schedule, notify about newer versions, verify downloaded APKs, and hand off installation to Android. Generate the feed with each signed build. Include the wake artwork recovery fix and on-device lifecycle and updater regression tests.
This commit is contained in:
parent
f5f1c0928f
commit
0d1a11d943
23 changed files with 1493 additions and 51 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -10,3 +10,5 @@ output/*.png
|
|||
output/*.xml
|
||||
output/*.txt
|
||||
output/*.log
|
||||
output/wake-before/
|
||||
output/Luma-wake-tests.apk*
|
||||
|
|
|
|||
40
README.md
40
README.md
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
A native, remote-first launcher built for the onn. 4K Plus Streaming device (Android 14, 2 GB RAM). It is installed alongside Projectivy as `tv.luma.launcher`. Home now opens Luma; Projectivy remains installed and enabled as a fallback.
|
||||
|
||||
Version **1.1.1** adds updates directly from the TV and includes the wake fix introduced in 1.0.1. Every resume restores missing images, including when Android briefly pauses the launcher without stopping it. Already-loaded tiles and images are kept on pause-only resumes; leaving the launcher still releases image memory.
|
||||
|
||||
## Use it
|
||||
|
||||
Press **Home**, or open **Luma** from Projectivy's app list. It can also be opened with:
|
||||
|
|
@ -68,6 +70,30 @@ Tokens are encrypted with AES-GCM using a key held in Android Keystore. **Discon
|
|||
|
||||
Media rendering and the connection/disconnection flow were checked against a temporary local Plex fixture. A real Plex server and account have not been connected, so account authorization and actual title playback remain to be verified with your library. Pairing is user initiated; no background account polling occurs.
|
||||
|
||||
## Updates on every TV
|
||||
|
||||
Open **Settings → Updates**. Checks default to **Daily**; alternatives are every 3, 6, or 12 hours, or Off. **Check now** works independently of the schedule. A check also runs when returning home if one is due. Android schedules one small, persisted, network-constrained job and may defer it while the TV is sleeping or offline. There is no continuous polling service and no automatic APK download.
|
||||
|
||||
When a newer version is found, Luma posts a TV notification once for that version and shows an **Update** button beside the clock. Notifications can be managed in the same panel. Neither the check nor the notification opens another screen while watching an app. Select **Download & install** to download the APK. The first time, Android asks you to allow installations from Luma; Android's package installer then asks you to confirm the update with the remote. Settings and app data are retained. This uses the system installer, not silent or root installation.
|
||||
|
||||
The default public HTTPS feed is:
|
||||
|
||||
```text
|
||||
https://git.elijahkuntz.com/Elijah/Luma/raw/branch/main/output/update.json
|
||||
```
|
||||
|
||||
No SSH key or Forgejo account token is stored on the TV. For branch-based Forgejo URLs, Luma resolves the branch to a commit first, then reads both the manifest and APK from that immutable commit. It bounds metadata to 64 KiB and APK downloads to 32 MiB. Before opening the installer, it checks the expected SHA-256 and file size, package name, increasing version code, Android compatibility, and the installed signing certificate. A different signing key is rejected. The provider grants read-only access to exactly the verified APK URI. Interrupted downloads are removed; completed APKs are removed after the updated app starts.
|
||||
|
||||
### Publish an update
|
||||
|
||||
1. Increase `versionCode` and `versionName` in both `app/src/main/AndroidManifest.xml` and `app/build.gradle`. Every published update needs a greater version code.
|
||||
2. Edit `docs/UPDATE_NOTES.md`, then run `scripts/build.sh` using the existing signing keystore. The build generates `output/Luma.apk` and `output/update.json` together, including the APK checksum and size.
|
||||
3. Commit and push the source changes, **both output files**, and release notes to `main`. The next scheduled/manual check on each TV discovers the update. No separate release upload or account setup is needed.
|
||||
|
||||
Preserve `.tools/luma-development.keystore` separately from Git: the same signing key is required for every update. The first updater-capable APK must be installed on each TV once, through ADB, Downloader, or a file manager; later updates can be handled within Luma.
|
||||
|
||||
Android scheduling and installation behavior follow the [JobInfo API](https://developer.android.com/reference/android/app/job/JobInfo.Builder) and [package installation API](https://developer.android.com/reference/android/content/pm/PackageManager#canRequestPackageInstalls()).
|
||||
|
||||
## Performance design
|
||||
|
||||
- Platform Java/Android views and Canvas; no WebView, Compose runtime, playback engine, or third-party runtime dependencies.
|
||||
|
|
@ -75,7 +101,7 @@ Media rendering and the connection/disconnection flow were checked against a tem
|
|||
- App artwork is rasterized to 288 × 162. Icon cache is capped at 3 MiB; visible tiles also hold their displayed images.
|
||||
- Plex image cache is capped at 3 MiB. Hero images are sampled to at most roughly 1280 × 720; rows and network response sizes are bounded.
|
||||
- At most the current and previous artwork are retained during a short crossfade. A focus debounce avoids loading artwork for every passing selection.
|
||||
- No boot receivers, alarms, PowerManager wake locks, or periodic background jobs. The optional Home override is an event-driven accessibility service in a separate process; turning it off removes that bound service. The optional DreamService runs only when Android explicitly binds it as a system screensaver.
|
||||
- No boot receiver, alarms, or PowerManager wake locks. Update checks use one brief JobScheduler job, normally daily. The optional Home override is an event-driven accessibility service in a separate process; turning it off removes that bound service. The optional DreamService runs only when Android explicitly binds it as a system screensaver.
|
||||
- Clock updates once per minute; optional scene rotation runs only while Luma is visible.
|
||||
- On pause, networking and scene animations are canceled. On stop, queued work, image references, and caches are cleared. Worker threads time out after ten idle seconds.
|
||||
- Android can reclaim the cached launcher process while another app is running. It is not kept alive artificially.
|
||||
|
|
@ -114,4 +140,16 @@ python3 scripts/device_smoke.py --part screensaver-timeout
|
|||
|
||||
The scripts operate the TV through ADB. Run one at a time with the TV awake. The customization checks expect the documented defaults. The Plex fixture requires `python3 scripts/plex_fixture.py` running on the host, followed by `python3 scripts/device_smoke.py --part plex`. It uses temporary ADB reverse forwarding to a loopback server and disconnects the fixture when finished.
|
||||
|
||||
The wake regression uses a separate test APK signed with the same development key, without adding any test interface to Luma. It replays interrupted background loading, a pause/resume without another start callback, memory trimming, and five stop/start cycles. The old 1.0.0 build fails the interrupted-wake case; 1.0.1 passes.
|
||||
|
||||
```sh
|
||||
bash scripts/build-wake-tests.sh
|
||||
.tools/platform-tools/adb -s 192.168.50.195:35635 install -r output/Luma-wake-tests.apk
|
||||
.tools/platform-tools/adb -s 192.168.50.195:35635 shell am instrument -w -r tv.luma.launcher.tests/.WakeRegressionInstrumentation
|
||||
.tools/platform-tools/adb -s 192.168.50.195:35635 uninstall tv.luma.launcher.tests
|
||||
```
|
||||
|
||||
Successful output ends with `INSTRUMENTATION_CODE: -1` and PASS lines for all cases. The runner controls activity lifecycle callbacks and should be run with no other device tests in progress.
|
||||
Android force-stops the target package during instrumentation and can mark its accessibility helper as stopped/crashed. After testing, check **Settings → Default launcher** and toggle **Luma Home button** off/on in Android Accessibility if needed, then reopen Luma. This is test-runner cleanup, not an action needed during normal TV wake.
|
||||
|
||||
See [docs/ASSETS.md](docs/ASSETS.md) for the wallpaper generation prompt and asset provenance. Android TV intent handling follows [Android's TV app guidance](https://developer.android.com/training/tv/get-started/create); Plex integration follows the [official Plex Media Server API documentation](https://developer.plex.tv/pms/).
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ android {
|
|||
applicationId 'tv.luma.launcher'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 1
|
||||
versionName '1.0.0'
|
||||
versionCode 4
|
||||
versionName '1.1.1'
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8; targetCompatibility JavaVersion.VERSION_1_8 }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tv.luma.launcher" android:versionCode="1" android:versionName="1.0.0">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tv.luma.launcher" android:versionCode="4" android:versionName="1.1.1">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
|
||||
<uses-feature android:name="android.software.leanback" android:required="true" />
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<queries>
|
||||
<intent><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /></intent>
|
||||
<intent><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent>
|
||||
|
|
@ -29,5 +32,10 @@
|
|||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_accessibility" />
|
||||
</service>
|
||||
<receiver android:name=".HomeControlReceiver" android:process=":home" android:exported="false" />
|
||||
<service android:name=".UpdateJob" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
|
||||
<receiver android:name=".UpdateReceiver" android:exported="false">
|
||||
<intent-filter><action android:name="android.intent.action.MY_PACKAGE_REPLACED" /></intent-filter>
|
||||
</receiver>
|
||||
<provider android:name=".UpdateProvider" android:authorities="tv.luma.launcher.updates" android:exported="false" android:grantUriPermissions="true" />
|
||||
</application>
|
||||
</manifest>
|
||||
|
|
|
|||
|
|
@ -94,6 +94,10 @@ final class AppTile extends LinearLayout {
|
|||
art.invalidate();
|
||||
}
|
||||
|
||||
boolean hasImage() {
|
||||
return art.bitmap != null && !art.bitmap.isRecycled();
|
||||
}
|
||||
|
||||
void progress(float value) {
|
||||
art.progress = value;
|
||||
art.invalidate();
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ public final class MainActivity extends Activity {
|
|||
private volatile int artGeneration = 0;
|
||||
private int rotation = 0;
|
||||
private volatile boolean foreground = false;
|
||||
private boolean appsNeedRefresh = true;
|
||||
private boolean moving = false;
|
||||
private volatile Dialog currentDialog;
|
||||
private PlexClient plex;
|
||||
|
|
@ -44,6 +45,11 @@ public final class MainActivity extends Activity {
|
|||
private boolean saverDownloading;
|
||||
private boolean refreshHomeSettings;
|
||||
private SaverMedia saverMedia;
|
||||
private Updater updater;
|
||||
private TextView updateButton;
|
||||
private boolean updateBusy, resumeUpdateInstall, pendingUpdateScreen;
|
||||
private Dialog updateDialog;
|
||||
private Future<?> updateTask;
|
||||
private final Runnable idleSaver =
|
||||
() -> {
|
||||
if (foreground && currentDialog == null && !moving) startSaver();
|
||||
|
|
@ -53,6 +59,7 @@ public final class MainActivity extends Activity {
|
|||
public void run() {
|
||||
if (!foreground) return;
|
||||
updateClock();
|
||||
updateBadge();
|
||||
handler.postDelayed(this, 60000 - System.currentTimeMillis() % 60000);
|
||||
}
|
||||
};
|
||||
|
|
@ -75,6 +82,9 @@ public final class MainActivity extends Activity {
|
|||
repository = new AppRepository(this);
|
||||
plex = new PlexClient(this);
|
||||
saverMedia = new SaverMedia(this);
|
||||
updater = new Updater(this);
|
||||
updater.cleanupInstalled();
|
||||
pendingUpdateScreen = Updater.SHOW_UPDATES.equals(getIntent().getAction());
|
||||
getWindow().getDecorView().setSystemUiVisibility(5894);
|
||||
getWindow().setNavigationBarColor(Ui.BG);
|
||||
buildShell();
|
||||
|
|
@ -142,6 +152,12 @@ public final class MainActivity extends Activity {
|
|||
header.addView(dot, dotLp);
|
||||
View spacer = new View(this);
|
||||
header.addView(spacer, new LinearLayout.LayoutParams(0, 1, 1));
|
||||
updateButton = chip("Update", v -> updatesSettings());
|
||||
updateButton.setContentDescription("Luma update available");
|
||||
updateButton.setVisibility(View.GONE);
|
||||
LinearLayout.LayoutParams updateLp = new LinearLayout.LayoutParams(d(76), d(32));
|
||||
updateLp.rightMargin = d(12);
|
||||
header.addView(updateButton, updateLp);
|
||||
clock = Ui.text(this, "", 13, Ui.WHITE);
|
||||
clock.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
|
||||
header.addView(clock, new LinearLayout.LayoutParams(d(125), d(32)));
|
||||
|
|
@ -285,18 +301,7 @@ public final class MainActivity extends Activity {
|
|||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
foreground = true;
|
||||
plex.resume();
|
||||
int g = ++generation;
|
||||
loadApps(g);
|
||||
work.execute(
|
||||
() -> {
|
||||
Bitmap b = SceneView.decodeWallpaper(this);
|
||||
handler.post(
|
||||
() -> {
|
||||
if (foreground && g == generation) scene.setWallpaper(b);
|
||||
});
|
||||
});
|
||||
appsNeedRefresh = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -304,11 +309,23 @@ public final class MainActivity extends Activity {
|
|||
super.onResume();
|
||||
foreground = true;
|
||||
plex.resume();
|
||||
restoreImages();
|
||||
handler.removeCallbacks(minuteTick);
|
||||
handler.post(minuteTick);
|
||||
handler.removeCallbacks(rotateScene);
|
||||
if (prefs.getBoolean("rotate", false)) handler.postDelayed(rotateScene, 90000);
|
||||
resetSaverTimer();
|
||||
UpdateJob.schedule(this);
|
||||
updateBadge();
|
||||
if (pendingUpdateScreen) {
|
||||
pendingUpdateScreen = false;
|
||||
updatesSettings();
|
||||
}
|
||||
if (resumeUpdateInstall) {
|
||||
resumeUpdateInstall = false;
|
||||
if (getPackageManager().canRequestPackageInstalls()) handler.post(this::installUpdate);
|
||||
else updatesSettings();
|
||||
} else if (updater.due() && !updateBusy) checkUpdates(false);
|
||||
if (refreshHomeSettings) {
|
||||
refreshHomeSettings = false;
|
||||
defaultLauncherSettings();
|
||||
|
|
@ -319,9 +336,19 @@ public final class MainActivity extends Activity {
|
|||
protected void onPause() {
|
||||
super.onPause();
|
||||
foreground = false;
|
||||
generation++;
|
||||
artGeneration++;
|
||||
work.getQueue().clear();
|
||||
network.getQueue().clear();
|
||||
handler.removeCallbacks(minuteTick);
|
||||
handler.removeCallbacks(rotateScene);
|
||||
plex.cancel();
|
||||
updater.cancel();
|
||||
if (updateTask != null) updateTask.cancel(true);
|
||||
if (updateBusy) {
|
||||
updateBusy = false;
|
||||
if (currentDialog == updateDialog) dismiss();
|
||||
}
|
||||
saverMedia.cancel();
|
||||
if (saverDownloading && currentDialog != null) {
|
||||
currentDialog.dismiss();
|
||||
|
|
@ -339,6 +366,7 @@ public final class MainActivity extends Activity {
|
|||
protected void onStop() {
|
||||
super.onStop();
|
||||
generation++;
|
||||
appsNeedRefresh = true;
|
||||
artGeneration++;
|
||||
work.getQueue().clear();
|
||||
network.getQueue().clear();
|
||||
|
|
@ -371,6 +399,8 @@ public final class MainActivity extends Activity {
|
|||
protected void onDestroy() {
|
||||
handler.removeCallbacksAndMessages(null);
|
||||
plex.cancel();
|
||||
updater.cancel();
|
||||
if (updateTask != null) updateTask.cancel(true);
|
||||
work.shutdownNow();
|
||||
network.shutdownNow();
|
||||
super.onDestroy();
|
||||
|
|
@ -379,10 +409,12 @@ public final class MainActivity extends Activity {
|
|||
private void loadApps(int g) {
|
||||
work.execute(
|
||||
() -> {
|
||||
if (!foreground || g != generation) return;
|
||||
List<AppRepository.App> found = repository.discover();
|
||||
handler.post(
|
||||
() -> {
|
||||
if (!foreground || g != generation) return;
|
||||
appsNeedRefresh = false;
|
||||
allApps.clear();
|
||||
allApps.addAll(found);
|
||||
renderApps();
|
||||
|
|
@ -391,6 +423,39 @@ public final class MainActivity extends Activity {
|
|||
});
|
||||
}
|
||||
|
||||
/** A wake can pause/resume without another start, after earlier loads have been discarded. */
|
||||
private void restoreImages() {
|
||||
final int g = generation;
|
||||
if (!scene.hasWallpaper()) {
|
||||
work.execute(
|
||||
() -> {
|
||||
if (!foreground || g != generation) return;
|
||||
Bitmap wallpaper = SceneView.decodeWallpaper(this);
|
||||
handler.post(
|
||||
() -> {
|
||||
if (foreground && g == generation) scene.setWallpaper(wallpaper);
|
||||
});
|
||||
});
|
||||
}
|
||||
if (appsNeedRefresh) {
|
||||
loadApps(g);
|
||||
return;
|
||||
}
|
||||
reloadIcons();
|
||||
if (mediaContainer.getChildCount() == 0) loadMedia();
|
||||
else
|
||||
for (AppTile tile : mediaTiles) {
|
||||
if (!tile.hasImage() && tile.getTag() instanceof PlexClient.Media)
|
||||
loadMediaThumbnail(tile, (PlexClient.Media) tile.getTag(), g);
|
||||
}
|
||||
if (!scene.hasMediaArt()) {
|
||||
View focused = getCurrentFocus();
|
||||
if (focused != null && focused.getTag() instanceof PlexClient.Media)
|
||||
featureArtwork(((PlexClient.Media) focused.getTag()).art);
|
||||
else if (selected.contains("plex") || selected.contains("plezy")) featurePlexArtwork();
|
||||
}
|
||||
}
|
||||
|
||||
private int columns() {
|
||||
return prefs.getInt("columns", 6);
|
||||
}
|
||||
|
|
@ -501,6 +566,7 @@ public final class MainActivity extends Activity {
|
|||
int ig = iconGeneration;
|
||||
for (AppRepository.App a : visibleApps) {
|
||||
final AppTile t = tiles.get(a.pkg);
|
||||
if (t == null || t.hasImage()) continue;
|
||||
work.execute(
|
||||
() -> {
|
||||
if (!foreground || g != generation || ig != iconGeneration) return;
|
||||
|
|
@ -609,6 +675,11 @@ public final class MainActivity extends Activity {
|
|||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
setIntent(intent);
|
||||
if (Updater.SHOW_UPDATES.equals(intent.getAction())) {
|
||||
if (foreground) updatesSettings();
|
||||
else pendingUpdateScreen = true;
|
||||
return;
|
||||
}
|
||||
if (intent.hasCategory(Intent.CATEGORY_HOME)) {
|
||||
refreshHomeSettings = false;
|
||||
dismiss();
|
||||
|
|
@ -719,6 +790,13 @@ public final class MainActivity extends Activity {
|
|||
"Idle timeout, art, scenic photos, and nature video",
|
||||
this::screensaverSettings);
|
||||
action(p, "App library", "Reorder, hide, or restore your apps", this::showAllApps);
|
||||
action(
|
||||
p,
|
||||
"Updates",
|
||||
updater.available() == null
|
||||
? "Automatic checks and TV installation"
|
||||
: "A new Luma version is available",
|
||||
this::updatesSettings);
|
||||
action(
|
||||
p, "Default launcher", "Home button routing and fallback", this::defaultLauncherSettings);
|
||||
action(
|
||||
|
|
@ -748,10 +826,250 @@ public final class MainActivity extends Activity {
|
|||
dismiss();
|
||||
fallback();
|
||||
});
|
||||
action(p, "About Luma", "Version 1.0 · Native Android TV", this::about);
|
||||
action(
|
||||
p,
|
||||
"About Luma",
|
||||
"Version " + updater.installedName() + " · Native Android TV",
|
||||
this::about);
|
||||
action(p, "Done", null, this::dismiss);
|
||||
}
|
||||
|
||||
private void updateBadge() {
|
||||
if (updateButton != null)
|
||||
updateButton.setVisibility(updater.available() == null ? View.GONE : View.VISIBLE);
|
||||
}
|
||||
|
||||
private void updatesSettings() {
|
||||
Updater.Release release = updater.available();
|
||||
long checked = updater.prefs.getLong("success", 0);
|
||||
String status =
|
||||
updateBusy
|
||||
? "Checking for updates…"
|
||||
: checked == 0
|
||||
? "No successful check yet"
|
||||
: "Last checked " + android.text.format.DateFormat.format("MMM d, h:mm a", checked);
|
||||
String error = updater.prefs.getString("error", "");
|
||||
LinearLayout p =
|
||||
panel(
|
||||
"Luma updates",
|
||||
"Installed "
|
||||
+ updater.installedName()
|
||||
+ "\n"
|
||||
+ status
|
||||
+ (error.isEmpty() ? "" : "\n" + error));
|
||||
updateDialog = currentDialog;
|
||||
if (release != null) {
|
||||
action(
|
||||
p,
|
||||
(updater.ready(release) ? "Install " : "Download & install ") + release.name,
|
||||
String.format(Locale.getDefault(), "%.1f MB", release.size / 1048576f)
|
||||
+ (release.notes.isEmpty() ? "" : "\n" + release.notes),
|
||||
this::installUpdate);
|
||||
}
|
||||
action(
|
||||
p,
|
||||
updateBusy ? "Checking…" : "Check now",
|
||||
release == null && checked > 0 && error.isEmpty() ? "Luma is up to date" : null,
|
||||
() -> checkUpdates(true));
|
||||
action(
|
||||
p,
|
||||
"Check frequency · "
|
||||
+ (updater.hours() == 0
|
||||
? "Off"
|
||||
: updater.hours() == 24 ? "Daily" : "Every " + updater.hours() + " hours"),
|
||||
"Checks only version information; downloads wait for you",
|
||||
() -> {
|
||||
LinearLayout q =
|
||||
panel(
|
||||
"Automatic update checks",
|
||||
"Android may defer checks while the TV sleeps or is offline.");
|
||||
for (int hours : new int[] {24, 12, 6, 3, 0})
|
||||
action(
|
||||
q,
|
||||
hours == 0 ? "Off" : hours == 24 ? "Daily" : "Every " + hours + " hours",
|
||||
null,
|
||||
() -> {
|
||||
updater.prefs.edit().putInt("hours", hours).apply();
|
||||
UpdateJob.schedule(this);
|
||||
updatesSettings();
|
||||
});
|
||||
});
|
||||
boolean notifications = getSystemService(NotificationManager.class).areNotificationsEnabled();
|
||||
action(
|
||||
p,
|
||||
"Notifications · " + (notifications ? "On" : "Off"),
|
||||
"The home-screen Update button also appears when an update is available",
|
||||
() -> {
|
||||
if (Build.VERSION.SDK_INT >= 33
|
||||
&& checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS)
|
||||
!= android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(new String[] {android.Manifest.permission.POST_NOTIFICATIONS}, 73);
|
||||
} else
|
||||
try {
|
||||
startActivity(
|
||||
new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName()));
|
||||
} catch (RuntimeException e) {
|
||||
toast("Open Android settings → Apps → Luma → Notifications");
|
||||
}
|
||||
});
|
||||
action(p, "Update source", updater.source(), this::updateSource);
|
||||
action(p, "Back", null, this::showSettings);
|
||||
}
|
||||
|
||||
private void checkUpdates(boolean manual) {
|
||||
if (updateBusy) return;
|
||||
updateBusy = true;
|
||||
int g = generation;
|
||||
if (manual) updatesSettings();
|
||||
updateTask =
|
||||
network.submit(
|
||||
() -> {
|
||||
String error = null;
|
||||
try {
|
||||
updater.check(true);
|
||||
} catch (Exception e) {
|
||||
error = Updater.message(e);
|
||||
}
|
||||
final String problem = error;
|
||||
handler.post(
|
||||
() -> {
|
||||
if (!foreground || g != generation) return;
|
||||
updateBusy = false;
|
||||
updateBadge();
|
||||
if (updateDialog != null && currentDialog == updateDialog) updatesSettings();
|
||||
if (manual && problem != null) toast(problem);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void updateSource() {
|
||||
LinearLayout p =
|
||||
panel("Update source", "A public HTTPS update.json URL. Your Forgejo repo is the default.");
|
||||
EditText field = new EditText(this);
|
||||
field.setTextColor(Ui.WHITE);
|
||||
field.setSingleLine(true);
|
||||
field.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
|
||||
field.setText(updater.source());
|
||||
p.addView(field, new LinearLayout.LayoutParams(-1, d(48)));
|
||||
action(
|
||||
p,
|
||||
"Save source",
|
||||
null,
|
||||
() -> {
|
||||
try {
|
||||
updater.source(field.getText().toString().trim());
|
||||
updateBadge();
|
||||
updatesSettings();
|
||||
} catch (Exception e) {
|
||||
toast(Updater.message(e));
|
||||
}
|
||||
});
|
||||
action(
|
||||
p,
|
||||
"Use default Forgejo repo",
|
||||
null,
|
||||
() -> {
|
||||
try {
|
||||
updater.source(Updater.DEFAULT_FEED);
|
||||
updateBadge();
|
||||
updatesSettings();
|
||||
} catch (Exception e) {
|
||||
toast(Updater.message(e));
|
||||
}
|
||||
});
|
||||
action(p, "Cancel", null, this::updatesSettings);
|
||||
}
|
||||
|
||||
private void installUpdate() {
|
||||
if (updateBusy) return;
|
||||
Updater.Release release = updater.available();
|
||||
if (release == null) {
|
||||
updatesSettings();
|
||||
return;
|
||||
}
|
||||
if (updater.ready(release) && !getPackageManager().canRequestPackageInstalls()) {
|
||||
resumeUpdateInstall = true;
|
||||
dismiss();
|
||||
try {
|
||||
startActivity(
|
||||
new Intent(
|
||||
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
|
||||
Uri.parse("package:" + getPackageName())));
|
||||
} catch (RuntimeException e) {
|
||||
resumeUpdateInstall = false;
|
||||
updatesSettings();
|
||||
toast("Allow Luma under Android settings → Apps → Special access → Install unknown apps");
|
||||
}
|
||||
return;
|
||||
}
|
||||
updateBusy = true;
|
||||
int g = generation;
|
||||
LinearLayout p = panel("Luma " + release.name, "Preparing your update…");
|
||||
updateDialog = currentDialog;
|
||||
TextView progress = Ui.text(this, "Verifying update…", 16, Ui.WHITE);
|
||||
p.addView(progress);
|
||||
action(
|
||||
p,
|
||||
"Cancel",
|
||||
null,
|
||||
() -> {
|
||||
updater.cancel();
|
||||
if (updateTask != null) updateTask.cancel(true);
|
||||
updateBusy = false;
|
||||
updatesSettings();
|
||||
});
|
||||
Dialog dialog = currentDialog;
|
||||
updateTask =
|
||||
network.submit(
|
||||
() -> {
|
||||
try {
|
||||
updater.resume();
|
||||
if (updater.ready(release)) updater.verify(updater.apk(), release);
|
||||
else
|
||||
updater.download(
|
||||
release,
|
||||
percent ->
|
||||
handler.post(
|
||||
() -> {
|
||||
if (foreground && currentDialog == dialog)
|
||||
progress.setText("Downloading · " + percent + "%");
|
||||
}));
|
||||
handler.post(
|
||||
() -> {
|
||||
if (!foreground || g != generation || currentDialog != dialog) return;
|
||||
updateBusy = false;
|
||||
if (!getPackageManager().canRequestPackageInstalls()) {
|
||||
installUpdate();
|
||||
return;
|
||||
}
|
||||
dismiss();
|
||||
Intent installer =
|
||||
new Intent(Intent.ACTION_VIEW)
|
||||
.setDataAndType(
|
||||
UpdateProvider.URI, "application/vnd.android.package-archive")
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
.putExtra(Intent.EXTRA_RETURN_RESULT, true);
|
||||
installer.setClipData(ClipData.newRawUri("Luma update", UpdateProvider.URI));
|
||||
try {
|
||||
startActivityForResult(installer, 74);
|
||||
} catch (RuntimeException e) {
|
||||
updatesSettings();
|
||||
toast("Android's APK installer is unavailable");
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
handler.post(
|
||||
() -> {
|
||||
if (!foreground || g != generation || currentDialog != dialog) return;
|
||||
updateBusy = false;
|
||||
updatesSettings();
|
||||
toast(Updater.message(e));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean homeOverrideEnabled() {
|
||||
String enabled =
|
||||
Settings.Secure.getString(
|
||||
|
|
@ -1058,12 +1376,11 @@ public final class MainActivity extends Activity {
|
|||
TextView t =
|
||||
Ui.text(
|
||||
this,
|
||||
"No ads or analytics."
|
||||
+ " Artwork and network requests stop when another app opens. Image caches are"
|
||||
+ " bounded and cleared when Luma leaves the screen.\n\n"
|
||||
+ "Menu opens settings. Hold OK on an app to customize it. Back stays on Luma."
|
||||
+ " Open Projectivy from Settings or its app tile.\n\n"
|
||||
+ "Manage the Home button in Settings → Default launcher.",
|
||||
"No ads or analytics. Wallpaper, app artwork, and Plex requests stop when another app"
|
||||
+ " opens. Image caches are bounded and cleared when Luma leaves the screen.\n\n"
|
||||
+ "Menu opens settings. Hold OK on an app to customize it. Back stays on Luma. Open"
|
||||
+ " Projectivy from Settings or its app tile.\n\n"
|
||||
+ "Manage Home routing and scheduled update checks in Settings.",
|
||||
13,
|
||||
Ui.MUTED);
|
||||
t.setLineSpacing(d(5), 1);
|
||||
|
|
@ -1463,6 +1780,7 @@ public final class MainActivity extends Activity {
|
|||
+ (m.progress > 0 ? ", " + Math.round(m.progress * 100) + " percent watched" : ""));
|
||||
row.addView(tile, new LinearLayout.LayoutParams(d(170), -2));
|
||||
mediaTiles.add(tile);
|
||||
tile.setTag(m);
|
||||
tile.setOnClickListener(v -> openMedia(m));
|
||||
tile.onFocused(
|
||||
f -> {
|
||||
|
|
@ -1471,39 +1789,31 @@ public final class MainActivity extends Activity {
|
|||
headline.setText(m.title);
|
||||
description.setText(m.subtitle);
|
||||
openHint.setText("● OK Open in Plex");
|
||||
int art = ++artGeneration;
|
||||
handler.postDelayed(
|
||||
() -> {
|
||||
if (!foreground || g != generation || art != artGeneration) return;
|
||||
network.execute(
|
||||
() -> {
|
||||
if (!foreground || g != generation || art != artGeneration) return;
|
||||
Bitmap b = plex.image(m.art, true);
|
||||
handler.post(
|
||||
() -> {
|
||||
if (foreground && g == generation && art == artGeneration)
|
||||
scene.setMediaArt(b);
|
||||
});
|
||||
});
|
||||
},
|
||||
180);
|
||||
featureArtwork(m.art);
|
||||
}
|
||||
});
|
||||
network.execute(
|
||||
() -> {
|
||||
if (!foreground || g != generation) return;
|
||||
Bitmap b = plex.image(m.thumb, false);
|
||||
handler.post(
|
||||
() -> {
|
||||
if (foreground && g == generation && mediaTiles.contains(tile)) tile.bitmap(b);
|
||||
});
|
||||
});
|
||||
loadMediaThumbnail(tile, m, g);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadMediaThumbnail(AppTile tile, PlexClient.Media media, int g) {
|
||||
network.execute(
|
||||
() -> {
|
||||
if (!foreground || g != generation) return;
|
||||
Bitmap bitmap = plex.image(media.thumb, false);
|
||||
handler.post(
|
||||
() -> {
|
||||
if (foreground && g == generation && mediaTiles.contains(tile)) tile.bitmap(bitmap);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void featurePlexArtwork() {
|
||||
if (plexFeatured == null || !foreground) return;
|
||||
final String path = plexFeatured.art;
|
||||
featureArtwork(plexFeatured.art);
|
||||
}
|
||||
|
||||
private void featureArtwork(String path) {
|
||||
final int g = generation, art = ++artGeneration;
|
||||
handler.postDelayed(
|
||||
() -> {
|
||||
|
|
@ -1926,6 +2236,10 @@ public final class MainActivity extends Activity {
|
|||
@Override
|
||||
protected void onActivityResult(int request, int result, Intent data) {
|
||||
super.onActivityResult(request, result, data);
|
||||
if (request == 74) {
|
||||
pendingUpdateScreen = true;
|
||||
return;
|
||||
}
|
||||
if (request != 41 || result != RESULT_OK || data == null || data.getData() == null) return;
|
||||
Uri uri = data.getData();
|
||||
try {
|
||||
|
|
@ -1950,6 +2264,17 @@ public final class MainActivity extends Activity {
|
|||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int request, String[] permissions, int[] grants) {
|
||||
super.onRequestPermissionsResult(request, permissions, grants);
|
||||
if (request == 73) {
|
||||
Updater.Release release = updater.available();
|
||||
if (release != null) updater.notifyAvailable(release);
|
||||
if (foreground) updatesSettings();
|
||||
else pendingUpdateScreen = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void openMedia(PlexClient.Media m) {
|
||||
try {
|
||||
String key = "/library/metadata/" + m.key;
|
||||
|
|
|
|||
|
|
@ -51,6 +51,14 @@ final class SceneView extends View {
|
|||
transitionArt(previous);
|
||||
}
|
||||
|
||||
boolean hasWallpaper() {
|
||||
return wallpaper != null && !wallpaper.isRecycled();
|
||||
}
|
||||
|
||||
boolean hasMediaArt() {
|
||||
return mediaArt != null && !mediaArt.isRecycled();
|
||||
}
|
||||
|
||||
void setMediaArt(Bitmap b) {
|
||||
if (mediaArt == b) return;
|
||||
Bitmap previous = currentArt();
|
||||
|
|
|
|||
57
app/src/main/java/tv/luma/launcher/UpdateJob.java
Normal file
57
app/src/main/java/tv/luma/launcher/UpdateJob.java
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package tv.luma.launcher;
|
||||
|
||||
import android.app.job.*;
|
||||
import android.content.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** Android wakes this service briefly for metadata; there is no resident polling loop. */
|
||||
public final class UpdateJob extends JobService {
|
||||
static final int ID = 7301;
|
||||
private ExecutorService worker;
|
||||
private Updater updater;
|
||||
|
||||
static void schedule(Context context) {
|
||||
JobScheduler scheduler = context.getSystemService(JobScheduler.class);
|
||||
int hours = new Updater(context).hours();
|
||||
if (hours == 0) {
|
||||
scheduler.cancel(ID);
|
||||
return;
|
||||
}
|
||||
long interval = hours * 3600000L;
|
||||
JobInfo current = scheduler.getPendingJob(ID);
|
||||
if (current != null && current.getIntervalMillis() == interval) return;
|
||||
scheduler.schedule(
|
||||
new JobInfo.Builder(ID, new ComponentName(context, UpdateJob.class))
|
||||
.setPeriodic(interval, Math.min(interval / 6, 3600000L))
|
||||
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
|
||||
.setPersisted(true)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onStartJob(JobParameters parameters) {
|
||||
updater = new Updater(this);
|
||||
if (!updater.due()) return false;
|
||||
worker = Executors.newSingleThreadExecutor();
|
||||
ExecutorService taskWorker = worker;
|
||||
Updater taskUpdater = updater;
|
||||
worker.execute(
|
||||
() -> {
|
||||
try {
|
||||
taskUpdater.check(true);
|
||||
} catch (Exception ignored) {
|
||||
} finally {
|
||||
jobFinished(parameters, false);
|
||||
taskWorker.shutdown();
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onStopJob(JobParameters parameters) {
|
||||
if (updater != null) updater.cancel();
|
||||
if (worker != null) worker.shutdownNow();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
71
app/src/main/java/tv/luma/launcher/UpdateProvider.java
Normal file
71
app/src/main/java/tv/luma/launcher/UpdateProvider.java
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
package tv.luma.launcher;
|
||||
|
||||
import android.content.*;
|
||||
import android.database.*;
|
||||
import android.net.Uri;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.provider.OpenableColumns;
|
||||
import java.io.*;
|
||||
|
||||
/** Grants the installer read access to exactly one private APK, never arbitrary files. */
|
||||
public final class UpdateProvider extends ContentProvider {
|
||||
static final Uri URI = Uri.parse("content://tv.luma.launcher.updates/apk");
|
||||
|
||||
private File file(Uri uri) throws FileNotFoundException {
|
||||
if (!URI.equals(uri)) throw new FileNotFoundException("Unknown update URI");
|
||||
return new Updater(getContext()).apk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType(Uri uri) {
|
||||
return "application/vnd.android.package-archive";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
|
||||
if (!"r".equals(mode)) throw new FileNotFoundException("Read only");
|
||||
return ParcelFileDescriptor.open(file(uri), ParcelFileDescriptor.MODE_READ_ONLY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cursor query(
|
||||
Uri uri, String[] projection, String selection, String[] arguments, String sort) {
|
||||
try {
|
||||
File file = file(uri);
|
||||
String[] columns =
|
||||
projection == null
|
||||
? new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}
|
||||
: projection;
|
||||
MatrixCursor cursor = new MatrixCursor(columns);
|
||||
Object[] values = new Object[columns.length];
|
||||
for (int i = 0; i < columns.length; i++) {
|
||||
if (OpenableColumns.DISPLAY_NAME.equals(columns[i])) values[i] = "Luma.apk";
|
||||
else if (OpenableColumns.SIZE.equals(columns[i])) values[i] = file.length();
|
||||
}
|
||||
cursor.addRow(values);
|
||||
return cursor;
|
||||
} catch (FileNotFoundException error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Uri insert(Uri uri, ContentValues values) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(Uri uri, String selection, String[] arguments) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int update(Uri uri, ContentValues values, String selection, String[] arguments) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
11
app/src/main/java/tv/luma/launcher/UpdateReceiver.java
Normal file
11
app/src/main/java/tv/luma/launcher/UpdateReceiver.java
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
package tv.luma.launcher;
|
||||
|
||||
import android.content.*;
|
||||
|
||||
/** Re-establish the persisted check after Android replaces this package. */
|
||||
public final class UpdateReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) UpdateJob.schedule(context);
|
||||
}
|
||||
}
|
||||
451
app/src/main/java/tv/luma/launcher/Updater.java
Normal file
451
app/src/main/java/tv/luma/launcher/Updater.java
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
package tv.luma.launcher;
|
||||
|
||||
import android.app.*;
|
||||
import android.content.*;
|
||||
import android.content.pm.*;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.regex.*;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** Bounded, credential-free metadata checks and user-initiated APK downloads. */
|
||||
final class Updater {
|
||||
static final String DEFAULT_FEED =
|
||||
"https://git.elijahkuntz.com/Elijah/Luma/raw/branch/main/output/update.json";
|
||||
static final String SHOW_UPDATES = "tv.luma.launcher.SHOW_UPDATES";
|
||||
static final int NOTICE = 7301;
|
||||
static final long MAX_APK = 32L * 1024 * 1024;
|
||||
private static final AtomicBoolean checking = new AtomicBoolean();
|
||||
private final Context context;
|
||||
final SharedPreferences prefs;
|
||||
private volatile boolean cancelled;
|
||||
private volatile HttpURLConnection active;
|
||||
|
||||
static final class Release {
|
||||
final long code, size;
|
||||
final String name, url, hash, notes;
|
||||
|
||||
Release(JSONObject json, URL feed) throws Exception {
|
||||
if (json.getInt("schema") != 1 || !json.getString("packageName").equals("tv.luma.launcher"))
|
||||
throw new IOException("This update feed is not for Luma.");
|
||||
code = json.getLong("versionCode");
|
||||
size = json.getLong("size");
|
||||
name = json.getString("versionName");
|
||||
hash = json.getString("sha256").toLowerCase(Locale.ROOT);
|
||||
notes = json.optString("notes", "");
|
||||
url = new URL(feed, json.getString("apk")).toString();
|
||||
if (code <= 0
|
||||
|| size <= 0
|
||||
|| size > MAX_APK
|
||||
|| name.length() > 60
|
||||
|| !hash.matches("[0-9a-f]{64}")
|
||||
|| notes.length() > 4000) throw new IOException("The update manifest is invalid.");
|
||||
if (json.optInt("minSdk", 26) > Build.VERSION.SDK_INT)
|
||||
throw new IOException("This update needs a newer Android version.");
|
||||
validUrl(url);
|
||||
}
|
||||
|
||||
JSONObject json() throws Exception {
|
||||
return new JSONObject()
|
||||
.put("schema", 1)
|
||||
.put("packageName", "tv.luma.launcher")
|
||||
.put("versionCode", code)
|
||||
.put("versionName", name)
|
||||
.put("size", size)
|
||||
.put("sha256", hash)
|
||||
.put("apk", url)
|
||||
.put("notes", notes);
|
||||
}
|
||||
}
|
||||
|
||||
Updater(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
prefs = this.context.getSharedPreferences("updates", Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
static long code(PackageInfo info) {
|
||||
return Build.VERSION.SDK_INT >= 28 ? info.getLongVersionCode() : info.versionCode;
|
||||
}
|
||||
|
||||
long installedCode() {
|
||||
try {
|
||||
return code(context.getPackageManager().getPackageInfo(context.getPackageName(), 0));
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
String installedName() {
|
||||
try {
|
||||
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
|
||||
} catch (Exception e) {
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
String source() {
|
||||
return prefs.getString("source", DEFAULT_FEED);
|
||||
}
|
||||
|
||||
int hours() {
|
||||
return prefs.getInt("hours", 24);
|
||||
}
|
||||
|
||||
boolean due() {
|
||||
long now = System.currentTimeMillis();
|
||||
return hours() > 0
|
||||
&& now - prefs.getLong("success", 0) >= hours() * 3600000L
|
||||
&& now - prefs.getLong("attempt", 0) >= 30 * 60000L;
|
||||
}
|
||||
|
||||
Release available() {
|
||||
try {
|
||||
Release release =
|
||||
new Release(new JSONObject(prefs.getString("release", "")), new URL(source()));
|
||||
return release.code > installedCode() ? release : null;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void source(String source) throws Exception {
|
||||
validUrl(source);
|
||||
cancel();
|
||||
prefs
|
||||
.edit()
|
||||
.putString("source", source)
|
||||
.remove("release")
|
||||
.remove("success")
|
||||
.remove("attempt")
|
||||
.remove("notified")
|
||||
.remove("error")
|
||||
.apply();
|
||||
deleteDownload();
|
||||
context.getSystemService(NotificationManager.class).cancel(NOTICE);
|
||||
}
|
||||
|
||||
Release check(boolean notify) throws Exception {
|
||||
if (!checking.compareAndSet(false, true))
|
||||
throw new IOException("An update check is already running.");
|
||||
cancelled = false;
|
||||
prefs.edit().putLong("attempt", System.currentTimeMillis()).apply();
|
||||
try {
|
||||
URL feed = validUrl(source());
|
||||
// Pin branch-based Forgejo feeds before reading either the manifest or its relative APK.
|
||||
Matcher path =
|
||||
Pattern.compile("^/([^/]+)/([^/]+)/raw/branch/([^/]+)/(.+)$").matcher(feed.getPath());
|
||||
if (path.matches()) {
|
||||
URL branch =
|
||||
new URL(
|
||||
feed.getProtocol(),
|
||||
feed.getHost(),
|
||||
feed.getPort(),
|
||||
"/api/v1/repos/"
|
||||
+ path.group(1)
|
||||
+ "/"
|
||||
+ path.group(2)
|
||||
+ "/branches/"
|
||||
+ path.group(3));
|
||||
String commit = json(branch).getJSONObject("commit").getString("id");
|
||||
if (!commit.matches("[0-9a-fA-F]{40,64}"))
|
||||
throw new IOException("Invalid repository commit.");
|
||||
feed =
|
||||
new URL(
|
||||
feed.getProtocol(),
|
||||
feed.getHost(),
|
||||
feed.getPort(),
|
||||
"/"
|
||||
+ path.group(1)
|
||||
+ "/"
|
||||
+ path.group(2)
|
||||
+ "/raw/commit/"
|
||||
+ commit
|
||||
+ "/"
|
||||
+ path.group(4));
|
||||
}
|
||||
Release release = new Release(json(feed), feed);
|
||||
requireActive();
|
||||
prefs
|
||||
.edit()
|
||||
.putString("release", release.json().toString())
|
||||
.putLong("success", System.currentTimeMillis())
|
||||
.remove("error")
|
||||
.apply();
|
||||
if (release.code <= installedCode()) {
|
||||
deleteDownload();
|
||||
context.getSystemService(NotificationManager.class).cancel(NOTICE);
|
||||
return null;
|
||||
}
|
||||
if (notify) notifyAvailable(release);
|
||||
return release;
|
||||
} catch (Exception e) {
|
||||
if (!cancelled) prefs.edit().putString("error", message(e)).apply();
|
||||
throw e;
|
||||
} finally {
|
||||
active = null;
|
||||
checking.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
File apk() {
|
||||
return new File(context.getCacheDir(), "updates/Luma.apk");
|
||||
}
|
||||
|
||||
private void deleteDownload() {
|
||||
apk().delete();
|
||||
new File(apk().getParentFile(), "Luma.apk.part").delete();
|
||||
prefs.edit().remove("ready").apply();
|
||||
}
|
||||
|
||||
void cleanupInstalled() {
|
||||
try {
|
||||
if (new JSONObject(prefs.getString("release", "")).getLong("versionCode")
|
||||
<= installedCode()) {
|
||||
deleteDownload();
|
||||
context.getSystemService(NotificationManager.class).cancel(NOTICE);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
boolean ready(Release release) {
|
||||
return release != null
|
||||
&& prefs.getLong("ready", 0) == release.code
|
||||
&& apk().isFile()
|
||||
&& apk().length() == release.size;
|
||||
}
|
||||
|
||||
interface Progress {
|
||||
void changed(int percent);
|
||||
}
|
||||
|
||||
File download(Release release, Progress progress) throws Exception {
|
||||
cancelled = false;
|
||||
File destination = apk(), partial = new File(destination.getParentFile(), "Luma.apk.part");
|
||||
destination.getParentFile().mkdirs();
|
||||
if (context.getCacheDir().getUsableSpace() < release.size * 2 + 4 * 1024 * 1024)
|
||||
throw new IOException("Not enough free space for this update.");
|
||||
HttpURLConnection connection = null;
|
||||
try {
|
||||
connection = open(validUrl(release.url));
|
||||
if (connection.getContentLengthLong() > MAX_APK)
|
||||
throw new IOException("The APK is too large.");
|
||||
try (InputStream input = connection.getInputStream();
|
||||
FileOutputStream out = new FileOutputStream(partial)) {
|
||||
byte[] bytes = new byte[32768];
|
||||
long count = 0;
|
||||
int previous = -1, n;
|
||||
while ((n = input.read(bytes)) != -1) {
|
||||
requireActive();
|
||||
count += n;
|
||||
if (count > release.size || count > MAX_APK)
|
||||
throw new IOException("The APK size does not match.");
|
||||
out.write(bytes, 0, n);
|
||||
int percent = (int) (count * 100 / release.size);
|
||||
if (percent != previous) {
|
||||
previous = percent;
|
||||
progress.changed(percent);
|
||||
}
|
||||
}
|
||||
out.getFD().sync();
|
||||
}
|
||||
verify(partial, release);
|
||||
requireActive();
|
||||
if (destination.exists() && !destination.delete())
|
||||
throw new IOException("Cannot replace the cached update.");
|
||||
if (!partial.renameTo(destination)) throw new IOException("Cannot save the update.");
|
||||
prefs.edit().putLong("ready", release.code).apply();
|
||||
return destination;
|
||||
} finally {
|
||||
partial.delete();
|
||||
if (connection != null) connection.disconnect();
|
||||
active = null;
|
||||
}
|
||||
}
|
||||
|
||||
void verify(File file, Release release) throws Exception {
|
||||
if (file.length() != release.size) throw new IOException("The downloaded APK is incomplete.");
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (InputStream in = new FileInputStream(file)) {
|
||||
byte[] bytes = new byte[32768];
|
||||
int n;
|
||||
while ((n = in.read(bytes)) != -1) {
|
||||
requireActive();
|
||||
digest.update(bytes, 0, n);
|
||||
}
|
||||
}
|
||||
if (!hex(digest.digest()).equals(release.hash))
|
||||
throw new IOException("The APK checksum does not match. Check again and retry.");
|
||||
PackageManager manager = context.getPackageManager();
|
||||
int flags =
|
||||
Build.VERSION.SDK_INT >= 28
|
||||
? PackageManager.GET_SIGNING_CERTIFICATES
|
||||
: PackageManager.GET_SIGNATURES;
|
||||
PackageInfo archive = manager.getPackageArchiveInfo(file.getAbsolutePath(), flags);
|
||||
PackageInfo installed = manager.getPackageInfo(context.getPackageName(), flags);
|
||||
if (archive == null
|
||||
|| !context.getPackageName().equals(archive.packageName)
|
||||
|| code(archive) != release.code
|
||||
|| code(archive) <= code(installed))
|
||||
throw new IOException("The APK is not a newer matching Luma update.");
|
||||
if (archive.applicationInfo == null
|
||||
|| archive.applicationInfo.minSdkVersion > Build.VERSION.SDK_INT)
|
||||
throw new IOException("This APK needs a newer Android version.");
|
||||
if (!signers(archive).equals(signers(installed)))
|
||||
throw new IOException("This APK was signed with a different key.");
|
||||
}
|
||||
|
||||
private Set<String> signers(PackageInfo info) throws Exception {
|
||||
Signature[] signatures =
|
||||
Build.VERSION.SDK_INT >= 28
|
||||
? info.signingInfo == null ? null : info.signingInfo.getApkContentsSigners()
|
||||
: info.signatures;
|
||||
if (signatures == null || signatures.length == 0)
|
||||
throw new IOException("Cannot verify the APK signing key.");
|
||||
Set<String> result = new TreeSet<>();
|
||||
for (Signature signature : signatures)
|
||||
result.add(hex(MessageDigest.getInstance("SHA-256").digest(signature.toByteArray())));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte b : bytes) result.append(String.format(Locale.ROOT, "%02x", b & 255));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private JSONObject json(URL url) throws Exception {
|
||||
HttpURLConnection connection = open(url);
|
||||
try (InputStream input = connection.getInputStream();
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[4096];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
requireActive();
|
||||
if (bytes.size() + n > 65536) throw new IOException("Update metadata is too large.");
|
||||
bytes.write(buffer, 0, n);
|
||||
}
|
||||
return new JSONObject(bytes.toString("UTF-8"));
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
active = null;
|
||||
}
|
||||
}
|
||||
|
||||
private HttpURLConnection open(URL url) throws Exception {
|
||||
for (int redirects = 0; redirects < 5; redirects++) {
|
||||
requireActive();
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
active = connection;
|
||||
connection.setConnectTimeout(10000);
|
||||
connection.setReadTimeout(15000);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setUseCaches(false);
|
||||
connection.setRequestProperty("User-Agent", "Luma-Updater");
|
||||
connection.setRequestProperty("Cache-Control", "no-cache");
|
||||
int status = connection.getResponseCode();
|
||||
if (status >= 300 && status <= 399) {
|
||||
String location = connection.getHeaderField("Location");
|
||||
connection.disconnect();
|
||||
if (location == null) throw new IOException("Invalid update redirect.");
|
||||
URL next = validUrl(new URL(url, location).toString());
|
||||
if (url.getProtocol().equals("https") && !next.getProtocol().equals("https"))
|
||||
throw new IOException("An HTTPS update cannot redirect to HTTP.");
|
||||
url = next;
|
||||
continue;
|
||||
}
|
||||
if (status != 200) {
|
||||
connection.disconnect();
|
||||
throw new IOException(
|
||||
status == 404
|
||||
? "No update has been published at this source yet."
|
||||
: "Update server returned HTTP " + status + ".");
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
throw new IOException("Too many update redirects.");
|
||||
}
|
||||
|
||||
static URL validUrl(String value) throws Exception {
|
||||
URL url = new URL(value);
|
||||
if (url.getUserInfo() != null || url.getRef() != null || value.length() > 2048)
|
||||
throw new IOException("Use a direct update URL without credentials.");
|
||||
boolean local =
|
||||
url.getHost().equals("localhost")
|
||||
|| url.getHost().matches("127\\.[0-9.]+")
|
||||
|| url.getHost().matches("10\\.[0-9.]+")
|
||||
|| url.getHost().matches("192\\.168\\.[0-9.]+")
|
||||
|| url.getHost().matches("172\\.(1[6-9]|2[0-9]|3[01])\\.[0-9.]+");
|
||||
if (!url.getProtocol().equals("https") && !(url.getProtocol().equals("http") && local))
|
||||
throw new IOException("Use HTTPS, or HTTP on a private local-network address.");
|
||||
return url;
|
||||
}
|
||||
|
||||
void cancel() {
|
||||
cancelled = true;
|
||||
HttpURLConnection connection = active;
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
|
||||
void resume() {
|
||||
cancelled = false;
|
||||
}
|
||||
|
||||
private void requireActive() throws IOException {
|
||||
if (cancelled || Thread.currentThread().isInterrupted())
|
||||
throw new IOException("Update request cancelled.");
|
||||
}
|
||||
|
||||
static String message(Exception error) {
|
||||
return error instanceof IOException
|
||||
? error.getMessage()
|
||||
: "Unable to read or verify this update.";
|
||||
}
|
||||
|
||||
void notifyAvailable(Release release) {
|
||||
NotificationManager manager = context.getSystemService(NotificationManager.class);
|
||||
if (!manager.areNotificationsEnabled() || prefs.getLong("notified", 0) >= release.code) return;
|
||||
manager.createNotificationChannel(
|
||||
new NotificationChannel("updates", "Luma updates", NotificationManager.IMPORTANCE_DEFAULT));
|
||||
Intent intent =
|
||||
new Intent(context, MainActivity.class)
|
||||
.setAction(SHOW_UPDATES)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||
PendingIntent open =
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
7301,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
|
||||
Notification notice =
|
||||
new Notification.Builder(context, "updates")
|
||||
.setSmallIcon(R.drawable.ic_luma)
|
||||
.setContentTitle("Luma " + release.name + " is available")
|
||||
.setContentText("Open to download and install the update.")
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setCategory(Notification.CATEGORY_STATUS)
|
||||
// TvExtender is absent from older public SDK stubs; use its AOSP bundle format.
|
||||
.extend(
|
||||
builder -> {
|
||||
Bundle tv = new Bundle();
|
||||
tv.putInt("flags", 1);
|
||||
tv.putBoolean("suppressShowOverApps", true);
|
||||
tv.putParcelable("content_intent", open);
|
||||
builder.getExtras().putBundle("android.tv.EXTENSIONS", tv);
|
||||
return builder;
|
||||
})
|
||||
.build();
|
||||
try {
|
||||
manager.notify(NOTICE, notice);
|
||||
prefs.edit().putLong("notified", release.code).apply();
|
||||
} catch (SecurityException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
1
docs/UPDATE_NOTES.md
Normal file
1
docs/UPDATE_NOTES.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
Adds scheduled update checks, TV notifications, and downloading/installing Luma updates directly from Settings. Includes the fix for missing app images and wallpaper after TV wake. Your appearance, screensaver, app order, and Home routing settings are preserved.
|
||||
|
|
@ -15,7 +15,17 @@ Validated on the user’s onn. 4K Plus Streaming device over ADB, October 17, 20
|
|||
- Projectivy fallback stays open when explicitly selected through its app tile or Settings. Back stays on Luma; from lower rows it returns to the first row. Home returns to Luma. Projectivy remains installed and enabled; only its competing “Override current launcher” preference is off. Its accessibility service and Button Mapper’s service are retained.
|
||||
- Luma’s override Off control removes only its own accessibility service. Re-enabling through Android’s actual Accessibility settings was verified. The service is system-bound in a separate `tv.luma.launcher:home` process. No view-content retrieval capability is requested.
|
||||
|
||||
## Performance
|
||||
## Wake regression — October 18, 2026
|
||||
|
||||
The original blank state was captured before sending input or restarting Luma. Android reported the existing activity as resumed; tiles were displaying their text placeholders and the alpine bitmap was absent. The recorded wake sequence included start/resume, a brief pause, and then resume without another start. Image work scheduled only from `onStart()` could be skipped or discarded while paused, with no retry when the activity resumed.
|
||||
|
||||
Version 1.0.1 moves restoration to `onResume()`, retries interrupted app discovery, and reloads missing wallpaper, app icons, and optional media artwork. Pausing invalidates stale asynchronous results; stopping still releases image references and caches. A pause-only resume retains existing tile views and decoded app images. This follows Android's documented [pause/resume lifecycle](https://developer.android.com/guide/components/activities/activity-lifecycle).
|
||||
|
||||
A separate same-signature instrumentation APK reproduces the interrupted-load sequence deterministically. The installed 1.0.0 build failed with missing artwork; the fixed build passed the same case, recovery of a partially rendered grid whose icon jobs were interrupted, pause-only memory trimming, reuse of existing loaded tiles/bitmaps, and five complete stop/start cycles. No preferences are rewritten by these tests. The temporary diagnostic APK was removed afterward.
|
||||
|
||||
One real sleep/wake cycle also passed screenshot checks for the alpine wallpaper and Plex banner without pressing Home or restarting the launcher. A subsequent automated wake was interrupted by HDMI standby (`mLastSleepReason=hdmi`), and One Touch Play timed out; no CEC settings were changed. The user turned the TV on again for the final screen check. The final screenshot shows the alpine wallpaper and app banners restored, with the user’s five-column layout preserved. Both the launcher and Home helper recorded zero CPU ticks over a ten-second background sample. Home returned correctly from Android settings and restored the UI after its cached process was explicitly reclaimed. The Home helper was re-bound after instrumentation cleanup, preserving the original enabled services. This is not an overnight endurance test.
|
||||
|
||||
## October 17 performance baseline
|
||||
|
||||
Final device sample with the Home override enabled:
|
||||
|
||||
|
|
@ -38,4 +48,10 @@ No launcher application was disabled or uninstalled. Screensaver selection at th
|
|||
|
||||
Build validation uses aapt2, javac, D8, zipalign, and apksigner signature verification. There are no third-party runtime libraries.
|
||||
|
||||
Final APK: 2,737,238 bytes. SHA-256: `46ca53681ff7fc34651402a8e4e806aa0fde7f7e49516aa94d8342ee762472a3`.
|
||||
Final APK (1.1.1): 2,749,526 bytes. SHA-256: `b145da41c95c927562f41d6052443723e377c7c40e775c078be0aa41ffefd19b`.
|
||||
|
||||
## Updater regression — October 18, 2026
|
||||
|
||||
The same-signature updater test ran against the installed 1.1.0 bootstrap and a newer signed 1.1.1 APK. It passed persisted daily network scheduling, Off cancellation, branch-to-commit pinning, a real APK download and certificate/package/version/checksum verification, and private provider read access. It rejected an incorrect checksum, another signing key, a different package, a mismatched version code, oversized metadata declarations, and public HTTP sources. The provider rejected write requests and unknown paths. The current version was not offered as an update. Test preferences were restored afterward.
|
||||
|
||||
The production default is the public HTTPS Forgejo feed in `output/update.json`, generated with the APK by `scripts/build.sh`. It requires no credentials on the TV. Native installer and unknown-source permission activities resolve on the onn. Android 14 device.
|
||||
|
|
|
|||
BIN
output/Luma.apk
BIN
output/Luma.apk
Binary file not shown.
Binary file not shown.
11
output/update.json
Normal file
11
output/update.json
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"packageName": "tv.luma.launcher",
|
||||
"versionCode": 4,
|
||||
"versionName": "1.1.1",
|
||||
"minSdk": 26,
|
||||
"apk": "Luma.apk",
|
||||
"size": 2749526,
|
||||
"sha256": "b145da41c95c927562f41d6052443723e377c7c40e775c078be0aa41ffefd19b",
|
||||
"notes": "Adds scheduled update checks, TV notifications, and downloading/installing Luma updates directly from Settings. Includes the fix for missing app images and wallpaper after TV wake. Your appearance, screensaver, app order, and Home routing settings are preserved."
|
||||
}
|
||||
20
scripts/build-wake-tests.sh
Normal file
20
scripts/build-wake-tests.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
TASK_ROOT="$PWD"
|
||||
export JAVA_HOME="${JAVA_HOME:-$TASK_ROOT/.tools/jdk/Contents/Home}"
|
||||
export ANDROID_HOME="${ANDROID_HOME:-$TASK_ROOT/.tools/sdk}"
|
||||
export PATH="$JAVA_HOME/bin:$PATH"
|
||||
BT="$ANDROID_HOME/build-tools/34.0.0"
|
||||
ANDROID_JAR="$ANDROID_HOME/platforms/android-34/android.jar"
|
||||
mkdir -p build/wake-tests/classes build/wake-tests/dex output
|
||||
"$BT/aapt2" link -o build/wake-tests/base.apk -I "$ANDROID_JAR" --manifest tests/device/AndroidManifest.xml
|
||||
javac -encoding UTF-8 -source 8 -target 8 -bootclasspath "$ANDROID_JAR:$BT/core-lambda-stubs.jar" -classpath build/classes -d build/wake-tests/classes tests/device/*.java
|
||||
find build/wake-tests/classes -name '*.class' > build/wake-tests/classes.txt
|
||||
"$BT/d8" --lib "$ANDROID_JAR" --min-api 26 --output build/wake-tests/dex @build/wake-tests/classes.txt
|
||||
cp build/wake-tests/base.apk build/wake-tests/with-dex.apk
|
||||
(cd build/wake-tests/dex && zip -q -u ../with-dex.apk classes*.dex)
|
||||
"$BT/zipalign" -f 4 build/wake-tests/with-dex.apk build/wake-tests/aligned.apk
|
||||
"$BT/apksigner" sign --ks .tools/luma-development.keystore --ks-key-alias luma --ks-pass pass:android --key-pass pass:android --out output/Luma-wake-tests.apk build/wake-tests/aligned.apk
|
||||
"$BT/apksigner" verify output/Luma-wake-tests.apk
|
||||
echo "Built $TASK_ROOT/output/Luma-wake-tests.apk"
|
||||
|
|
@ -23,4 +23,5 @@ if [ ! -f .tools/luma-development.keystore ]; then
|
|||
fi
|
||||
"$BT/apksigner" sign --ks .tools/luma-development.keystore --ks-key-alias luma --ks-pass pass:android --key-pass pass:android --out output/Luma.apk build/aligned.apk
|
||||
"$BT/apksigner" verify output/Luma.apk
|
||||
python3 scripts/make-update-manifest.py
|
||||
echo "Built $ROOT/output/Luma.apk"
|
||||
|
|
|
|||
27
scripts/make-update-manifest.py
Normal file
27
scripts/make-update-manifest.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Generate the small feed committed beside the signed APK; URLs resolve inside one Git commit."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
ns = '{http://schemas.android.com/apk/res/android}'
|
||||
manifest = ET.parse(root / 'app/src/main/AndroidManifest.xml').getroot()
|
||||
code = int(manifest.get(ns + 'versionCode'))
|
||||
name = manifest.get(ns + 'versionName')
|
||||
apk = root / 'output/Luma.apk'
|
||||
badging = subprocess.check_output([str(root / '.tools/sdk/build-tools/34.0.0/aapt2'), 'dump', 'badging', str(apk)], text=True)
|
||||
assert f"versionCode='{code}'" in badging and f"versionName='{name}'" in badging, 'Rebuild the APK before generating its update manifest'
|
||||
gradle = (root / 'app/build.gradle').read_text()
|
||||
assert re.search(r'versionCode\s+' + str(code) + r'\b', gradle), 'Manifest and Gradle version codes differ'
|
||||
assert "versionName '" + name + "'" in gradle, 'Manifest and Gradle version names differ'
|
||||
feed = dict(schema=1, packageName='tv.luma.launcher', versionCode=code, versionName=name,
|
||||
minSdk=int(manifest.find('uses-sdk').get(ns + 'minSdkVersion')), apk='Luma.apk',
|
||||
size=apk.stat().st_size, sha256=hashlib.sha256(apk.read_bytes()).hexdigest(),
|
||||
notes=(root / 'docs/UPDATE_NOTES.md').read_text().strip())
|
||||
assert len(feed['notes']) <= 4000
|
||||
(root / 'output/update.json').write_text(json.dumps(feed, indent=2) + '\n')
|
||||
print('Generated output/update.json for Luma ' + name)
|
||||
45
scripts/update_fixture.py
Normal file
45
scripts/update_fixture.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Loopback-only updater fixture. Never used by the shipping app."""
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMMIT = 'a' * 40
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args): pass
|
||||
def do_GET(self):
|
||||
path = self.path
|
||||
files = {'Luma.apk': ROOT/'output/Luma.apk', 'wrong.apk': ROOT/'build/update-tests/wrong-signer.apk',
|
||||
'other.apk': ROOT/'output/Luma-wake-tests.apk'}
|
||||
if path == '/api/v1/repos/Elijah/Luma/branches/main':
|
||||
payload = json.dumps({'commit': {'id': COMMIT}}).encode()
|
||||
elif path.endswith('.json'):
|
||||
feed = json.loads((ROOT/'output/update.json').read_text())
|
||||
mode = path.rsplit('/', 1)[-1]
|
||||
if mode == 'badhash.json': feed['sha256'] = '0' * 64
|
||||
elif mode == 'wrongkey.json':
|
||||
feed.update(apk='wrong.apk', size=files['wrong.apk'].stat().st_size,
|
||||
sha256=hashlib.sha256(files['wrong.apk'].read_bytes()).hexdigest())
|
||||
elif mode == 'wrongpackage.json':
|
||||
feed.update(apk='other.apk', size=files['other.apk'].stat().st_size,
|
||||
sha256=hashlib.sha256(files['other.apk'].read_bytes()).hexdigest())
|
||||
elif mode == 'wrongcode.json': feed['versionCode'] += 1
|
||||
elif mode == 'oversized.json': feed['size'] = 33 * 1024 * 1024
|
||||
elif mode == 'current.json': feed['versionCode'] = 3
|
||||
payload = json.dumps(feed).encode()
|
||||
elif path.rsplit('/', 1)[-1] in files:
|
||||
payload = files[path.rsplit('/', 1)[-1]].read_bytes()
|
||||
else:
|
||||
self.send_error(404); return
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.send_header('Content-Type', 'application/json' if path.endswith('.json') else 'application/octet-stream')
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('Updater fixture: 127.0.0.1:8766', flush=True)
|
||||
ThreadingHTTPServer(('127.0.0.1', 8766), Handler).serve_forever()
|
||||
6
tests/device/AndroidManifest.xml
Normal file
6
tests/device/AndroidManifest.xml
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tv.luma.launcher.tests">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
|
||||
<application android:label="Luma wake regression tests" />
|
||||
<instrumentation android:name=".WakeRegressionInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
|
||||
<instrumentation android:name="tv.luma.launcher.UpdaterInstrumentation" android:targetPackage="tv.luma.launcher" android:functionalTest="true" />
|
||||
</manifest>
|
||||
133
tests/device/UpdaterInstrumentation.java
Normal file
133
tests/device/UpdaterInstrumentation.java
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
package tv.luma.launcher;
|
||||
|
||||
import android.app.*;
|
||||
import android.app.job.*;
|
||||
import android.content.*;
|
||||
import android.net.Uri;
|
||||
import android.os.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Real Android archive/signature parsing, HTTP, private file grants, and job scheduling. */
|
||||
public final class UpdaterInstrumentation extends Instrumentation {
|
||||
private final StringBuilder results = new StringBuilder();
|
||||
private Updater updater;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle arguments) {
|
||||
super.onCreate(arguments);
|
||||
start();
|
||||
}
|
||||
|
||||
private void ok(String message) {
|
||||
results.append("PASS: ").append(message).append('\n');
|
||||
}
|
||||
|
||||
private void source(String name) throws Exception {
|
||||
updater.source("http://127.0.0.1:8766/" + name);
|
||||
}
|
||||
|
||||
private void rejected(String feed, String message) throws Exception {
|
||||
source(feed);
|
||||
try {
|
||||
Updater.Release release = updater.check(false);
|
||||
if (release != null) updater.download(release, percent -> {});
|
||||
} catch (Exception expected) {
|
||||
if (expected.getMessage() == null || !expected.getMessage().contains(message)) throw expected;
|
||||
if (new File(updater.apk().getParentFile(), "Luma.apk.part").exists())
|
||||
throw new AssertionError("partial file retained");
|
||||
ok(feed + " rejected: " + message);
|
||||
return;
|
||||
}
|
||||
throw new AssertionError(feed + " was accepted");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
Bundle result = new Bundle();
|
||||
Map<String, ?> original = null;
|
||||
int code = Activity.RESULT_CANCELED;
|
||||
try {
|
||||
updater = new Updater(getTargetContext());
|
||||
original = new HashMap<>(updater.prefs.getAll());
|
||||
if (updater.installedCode() != 3)
|
||||
throw new AssertionError("Install the 1.1.0 bootstrap before this fixture test");
|
||||
updater.prefs.edit().putInt("hours", 24).apply();
|
||||
UpdateJob.schedule(getTargetContext());
|
||||
JobInfo job =
|
||||
getTargetContext().getSystemService(JobScheduler.class).getPendingJob(UpdateJob.ID);
|
||||
if (job == null
|
||||
|| !job.isPersisted()
|
||||
|| job.getIntervalMillis() != 86400000L
|
||||
|| job.getNetworkType() != JobInfo.NETWORK_TYPE_ANY)
|
||||
throw new AssertionError("incorrect scheduled job");
|
||||
ok("daily job is persisted and requires a network");
|
||||
updater.source("http://127.0.0.1:8766/Elijah/Luma/raw/branch/main/output/update.json");
|
||||
Updater.Release release = updater.check(false);
|
||||
if (release == null
|
||||
|| !release.url.contains(
|
||||
"/raw/commit/" + String.join("", Collections.nCopies(40, "a")) + "/output/Luma.apk"))
|
||||
throw new AssertionError("APK is not pinned to the feed commit");
|
||||
updater.download(release, percent -> {});
|
||||
if (!updater.ready(release)) throw new AssertionError("verified APK not ready");
|
||||
try (ParcelFileDescriptor file =
|
||||
getTargetContext().getContentResolver().openFileDescriptor(UpdateProvider.URI, "r")) {
|
||||
if (file.getStatSize() != release.size)
|
||||
throw new AssertionError("installer cannot read APK");
|
||||
}
|
||||
ok("commit-pinned download passes checksum, package, version and signing-key verification");
|
||||
try {
|
||||
getTargetContext().getContentResolver().openFileDescriptor(UpdateProvider.URI, "w");
|
||||
throw new AssertionError("provider allowed writing");
|
||||
} catch (FileNotFoundException expected) {
|
||||
ok("installer provider denies write access");
|
||||
}
|
||||
try {
|
||||
getTargetContext()
|
||||
.getContentResolver()
|
||||
.openFileDescriptor(Uri.parse("content://tv.luma.launcher.updates/other"), "r");
|
||||
throw new AssertionError("provider exposed another path");
|
||||
} catch (FileNotFoundException expected) {
|
||||
ok("installer provider exposes only the APK URI");
|
||||
}
|
||||
rejected("badhash.json", "checksum");
|
||||
rejected("wrongkey.json", "different key");
|
||||
rejected("wrongpackage.json", "newer matching");
|
||||
rejected("wrongcode.json", "newer matching");
|
||||
rejected("oversized.json", "invalid");
|
||||
source("current.json");
|
||||
if (updater.check(false) != null || updater.available() != null)
|
||||
throw new AssertionError("current version offered as update");
|
||||
ok("current version is not offered as an update");
|
||||
try {
|
||||
Updater.validUrl("http://example.com/update.json");
|
||||
throw new AssertionError("public HTTP accepted");
|
||||
} catch (IOException expected) {
|
||||
ok("public sources require HTTPS");
|
||||
}
|
||||
updater.prefs.edit().putInt("hours", 0).apply();
|
||||
UpdateJob.schedule(getTargetContext());
|
||||
if (getTargetContext().getSystemService(JobScheduler.class).getPendingJob(UpdateJob.ID)
|
||||
!= null) throw new AssertionError("Off did not cancel the job");
|
||||
ok("Off cancels the automatic update job");
|
||||
code = Activity.RESULT_OK;
|
||||
} catch (Throwable error) {
|
||||
results.append("FAIL: ").append(error).append('\n');
|
||||
} finally {
|
||||
if (original != null) {
|
||||
SharedPreferences.Editor edit = updater.prefs.edit().clear();
|
||||
for (Map.Entry<String, ?> entry : original.entrySet()) {
|
||||
Object value = entry.getValue();
|
||||
if (value instanceof String) edit.putString(entry.getKey(), (String) value);
|
||||
else if (value instanceof Long) edit.putLong(entry.getKey(), (Long) value);
|
||||
else if (value instanceof Integer) edit.putInt(entry.getKey(), (Integer) value);
|
||||
else if (value instanceof Boolean) edit.putBoolean(entry.getKey(), (Boolean) value);
|
||||
}
|
||||
edit.commit();
|
||||
UpdateJob.schedule(getTargetContext());
|
||||
}
|
||||
result.putString("stream", results.toString());
|
||||
finish(code, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
207
tests/device/WakeRegressionInstrumentation.java
Normal file
207
tests/device/WakeRegressionInstrumentation.java
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
package tv.luma.launcher.tests;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Instrumentation;
|
||||
import android.content.ComponentCallbacks2;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Same-signature test APK. Exercises real activity callbacks without shipping a test interface. */
|
||||
public final class WakeRegressionInstrumentation extends Instrumentation {
|
||||
private Activity activity;
|
||||
private final StringBuilder results = new StringBuilder();
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle arguments) {
|
||||
super.onCreate(arguments);
|
||||
start();
|
||||
}
|
||||
|
||||
private Object field(Object owner, String name) throws Exception {
|
||||
Field field = owner.getClass().getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
return field.get(owner);
|
||||
}
|
||||
|
||||
private boolean imagesReady() throws Exception {
|
||||
Map<?, ?> tiles = (Map<?, ?>) field(activity, "tiles");
|
||||
if (tiles.isEmpty()) return false;
|
||||
for (Object tile : tiles.values()) {
|
||||
Bitmap image = (Bitmap) field(field(tile, "art"), "bitmap");
|
||||
if (image == null || image.isRecycled()) return false;
|
||||
}
|
||||
Bitmap wallpaper = (Bitmap) field(field(activity, "scene"), "wallpaper");
|
||||
return wallpaper != null && !wallpaper.isRecycled();
|
||||
}
|
||||
|
||||
private void awaitImages(String message) throws Exception {
|
||||
long end = android.os.SystemClock.uptimeMillis() + 7000;
|
||||
boolean[] ready = {false};
|
||||
while (android.os.SystemClock.uptimeMillis() < end) {
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
try {
|
||||
ready[0] = imagesReady();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
if (ready[0]) {
|
||||
results.append("PASS: ").append(message).append('\n');
|
||||
return;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
throw new AssertionError(message + ": app icons or wallpaper still missing");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
Bundle result = new Bundle();
|
||||
try {
|
||||
activity =
|
||||
startActivitySync(
|
||||
new Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_HOME)
|
||||
.setComponent(
|
||||
new ComponentName("tv.luma.launcher", "tv.luma.launcher.MainActivity"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
awaitImages("cold launch loads all app icons and wallpaper");
|
||||
ThreadPoolExecutor worker = (ThreadPoolExecutor) field(activity, "work");
|
||||
CountDownLatch blocked = new CountDownLatch(1), release = new CountDownLatch(1);
|
||||
worker.execute(
|
||||
() -> {
|
||||
blocked.countDown();
|
||||
try {
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
if (!blocked.await(3, TimeUnit.SECONDS)) throw new AssertionError("worker did not block");
|
||||
// Recorded TV sequence: restart/start -> resume -> pause -> resume, with decoding
|
||||
// interrupted.
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
callActivityOnPause(activity);
|
||||
callActivityOnStop(activity);
|
||||
callActivityOnRestart(activity);
|
||||
callActivityOnStart(activity);
|
||||
callActivityOnResume(activity);
|
||||
callActivityOnPause(activity);
|
||||
});
|
||||
CountDownLatch drained = new CountDownLatch(1);
|
||||
worker.execute(drained::countDown);
|
||||
release.countDown();
|
||||
if (!drained.await(3, TimeUnit.SECONDS)) throw new AssertionError("worker did not drain");
|
||||
waitForIdleSync();
|
||||
runOnMainSync(() -> callActivityOnResume(activity));
|
||||
awaitImages("interrupted wake recovers without another onStart or app restart");
|
||||
|
||||
Object[] firstTile = new Object[1], firstBitmap = new Object[1];
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
try {
|
||||
firstTile[0] = ((Map<?, ?>) field(activity, "tiles")).values().iterator().next();
|
||||
firstBitmap[0] = field(field(firstTile[0], "art"), "bitmap");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
callActivityOnPause(activity);
|
||||
activity.onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
|
||||
callActivityOnResume(activity);
|
||||
});
|
||||
awaitImages("pause-only memory trim restores wallpaper");
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
try {
|
||||
Object tile = ((Map<?, ?>) field(activity, "tiles")).values().iterator().next();
|
||||
if (tile != firstTile[0] || field(field(tile, "art"), "bitmap") != firstBitmap[0])
|
||||
throw new AssertionError(
|
||||
"pause-only resume unnecessarily rebuilt loaded app tiles");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
results.append("PASS: existing tile views and bitmaps survive pause-only resume\n");
|
||||
|
||||
// Let discovery render the real grid, but hold decoding until after the next pause.
|
||||
CountDownLatch beforeDiscovery = new CountDownLatch(1), discover = new CountDownLatch(1);
|
||||
CountDownLatch beforeIcons = new CountDownLatch(1), decode = new CountDownLatch(1);
|
||||
worker.execute(() -> block(beforeDiscovery, discover));
|
||||
if (!beforeDiscovery.await(3, TimeUnit.SECONDS))
|
||||
throw new AssertionError("discovery blocker");
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
callActivityOnPause(activity);
|
||||
callActivityOnStop(activity);
|
||||
callActivityOnRestart(activity);
|
||||
callActivityOnStart(activity);
|
||||
callActivityOnResume(activity);
|
||||
worker.execute(() -> block(beforeIcons, decode));
|
||||
});
|
||||
discover.countDown();
|
||||
if (!beforeIcons.await(3, TimeUnit.SECONDS)) throw new AssertionError("icon blocker");
|
||||
waitForIdleSync();
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
try {
|
||||
firstTile[0] = ((Map<?, ?>) field(activity, "tiles")).values().iterator().next();
|
||||
if (field(field(firstTile[0], "art"), "bitmap") != null)
|
||||
throw new AssertionError("icons were not held before pause");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
callActivityOnPause(activity);
|
||||
activity.onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
|
||||
});
|
||||
CountDownLatch iconsDrained = new CountDownLatch(1);
|
||||
worker.execute(iconsDrained::countDown);
|
||||
decode.countDown();
|
||||
if (!iconsDrained.await(3, TimeUnit.SECONDS)) throw new AssertionError("icon queue drain");
|
||||
runOnMainSync(() -> callActivityOnResume(activity));
|
||||
awaitImages("partially loaded app grid recovers after pause-only resume");
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
try {
|
||||
if (((Map<?, ?>) field(activity, "tiles")).values().iterator().next() != firstTile[0])
|
||||
throw new AssertionError("partial-grid recovery rebuilt the tiles");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
for (int i = 0; i < 5; i++) {
|
||||
runOnMainSync(
|
||||
() -> {
|
||||
callActivityOnPause(activity);
|
||||
callActivityOnStop(activity);
|
||||
callActivityOnRestart(activity);
|
||||
callActivityOnStart(activity);
|
||||
callActivityOnResume(activity);
|
||||
});
|
||||
awaitImages("stop/start recovery cycle " + (i + 1));
|
||||
}
|
||||
result.putString("stream", results.toString());
|
||||
finish(Activity.RESULT_OK, result);
|
||||
} catch (Throwable error) {
|
||||
result.putString("stream", results + "FAIL: " + error + "\n");
|
||||
finish(Activity.RESULT_CANCELED, result);
|
||||
}
|
||||
}
|
||||
|
||||
private void block(CountDownLatch entered, CountDownLatch release) {
|
||||
entered.countDown();
|
||||
try {
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue