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
|
|
@ -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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue