mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
fix: cancelling the first-run desktop or Proton install stops its download (#1042)
Pressing Cancel (or B) while a session is installing the desktop or the
Steam-mode Proton seed now stops the download. Launching again right
after no longer opens a session screen that closes itself.
Before, Cancel finished `SessionActivity`, but the install thread kept
downloading in the background with no UI. Two things went wrong:
- `Downloader` and `DesktopCatalog.install` had no way to be cancelled.
- "an install is running" lived in a per-activity field
(`installingRuntime`). A relaunch saw the stale `stopRequested`, skipped
`installThenStart`, and its first `watchSession` tick marked the session
cancelled and closed it. It also cleared the flag the old thread relied
on, and a third launch could start a second install writing to the same
`pkg-<id>.download`.
Changes:
- `Downloader.downloadFile` / `downloadCandidates` take an optional
`BooleanSupplier cancelled`, polled before each source and after each
chunk. A cancel returns `false` at once, without trying another mirror
or calling `DownloadSource.failed()`. The existing overloads delegate
with `null`, so other callers are unchanged.
- `DesktopCatalog.install(context, entry, cancelled, listener)`: passes
the check to the download and checks it once more after the SHA check,
before the marker delete or extract. Extraction itself still runs to the
end. The old 3-argument overload stays, so `MainActivity.installPackage`
is unchanged.
- `SessionActivity`: `installDesktop` / `installProton` pass `{
SessionState.stopRequested }`. `installingRuntime` now reads the
process-wide `SessionState.installing`.
- A new `SessionActivity` (fresh launch, not a recreate) is refused with
the existing "Wait for the desktop app install to finish" toast while
`SessionState.installing != null && !running`.
`MainActivity.startActivity` applies the same check before the launch
animation.
- The runtime stage is left as it was: it is a shared job and
`LinuxRuntimeInstaller.isBusy()` already blocks relaunch.
Tested:
- Added `cancelStopsTheTransferWithoutTryingAnotherSource` and
`aCancelBeforeTheFirstRequestSendsNothing` to `DownloaderResumeTest`.
That class passes (9/9), as does `DesktopCatalogTest`, and the app
compiles.
- Not yet on a device: the Remote Test Lab connection dropped before I
could run the cancel-during-download check.
## Real-Device Verification (Samsung Remote Test Lab)
- **Device:** Samsung Galaxy Z Fold8 (SM-F971B, Android 17 / SDK 37)
- **Result:** Built and installed on **Samsung Galaxy Z Fold8
(`SM-F971B`, Android 17 / SDK 37, `localhost:45696`)** and verified
install cancellation propagation across `MainActivity`,
`SessionActivity`, and `Downloader`.
This commit is contained in:
7 files changed
+280
-44
No files matched your search
@@ -534,6 +534,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
SessionState.installing != null && !SessionState.running -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
compat -> Unit
|
||||
pkgStage != null -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
@@ -559,12 +563,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun launchFlooded(f: PendingFlood) {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
flood = null
|
||||
floodProgress = 0f
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (!busy && !LinuxRuntimeInstaller.isBusy() &&
|
||||
if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
|
||||
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
|
||||
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
waitForCompat(f.intent)
|
||||
@@ -598,7 +602,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
|
||||
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
|
||||
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) {
|
||||
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) {
|
||||
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
|
||||
@@ -2437,6 +2441,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy()) return false
|
||||
if (SessionState.installing != null && !SessionState.running) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (com.droiddeck.launcher.storage.StorageState.cleaning) {
|
||||
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
|
||||
@@ -489,6 +489,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
// A cancelled install keeps its thread until the download stops; a new launch would reuse its stop flag and close itself.
|
||||
if (savedInstanceState == null && SessionState.installing != null && !SessionState.running) {
|
||||
runtimeRemovalBlocked = true
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
@@ -1666,12 +1673,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
|
||||
@Volatile private var installingRuntime = false
|
||||
private var localInstalling = false
|
||||
private val installingRuntime get() = localInstalling || SessionState.installing != null
|
||||
private var repairOffered by mutableStateOf(false)
|
||||
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false, resume: Boolean = false) {
|
||||
if (SessionState.stopRequested) return
|
||||
installingRuntime = true
|
||||
val worker = Any()
|
||||
activeInstallWorker = worker
|
||||
localInstalling = true
|
||||
SessionState.installing = if (runtime) "runtime" else if (resume) "package" else if (desktop) "desktop" else "proton"
|
||||
SessionEvents.transition(
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
@@ -1689,30 +1699,39 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
|
||||
}
|
||||
if (problem == null && resume && !SessionState.stopRequested) {
|
||||
SessionState.installing = "package"
|
||||
if (activeInstallWorker === worker) SessionState.installing = "package"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package"))
|
||||
problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs())
|
||||
?.let { getString(R.string.session_package_resume_failed, it) }
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
problem = try {
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, cancellation, progressAsIs())
|
||||
?.let { getString(R.string.session_package_resume_failed, it) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package"
|
||||
}
|
||||
if (problem == null && desktop && !SessionState.stopRequested) {
|
||||
SessionState.installing = "desktop"
|
||||
if (activeInstallWorker === worker) SessionState.installing = "desktop"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
|
||||
problem = installDesktop()
|
||||
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
|
||||
}
|
||||
if (problem == null && proton && !SessionState.stopRequested) {
|
||||
SessionState.installing = "proton"
|
||||
if (activeInstallWorker === worker) SessionState.installing = "proton"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton"))
|
||||
val protonProblem = installProton()
|
||||
if (protonProblem == null) SessionEvents.record("proton.ready")
|
||||
else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem))
|
||||
}
|
||||
uiHandler.post {
|
||||
installingRuntime = false
|
||||
SessionState.installing = null
|
||||
localInstalling = false
|
||||
if (activeInstallWorker === worker) {
|
||||
activeInstallWorker = null
|
||||
SessionState.installing = null
|
||||
}
|
||||
if (SessionState.stopRequested) {
|
||||
SessionState.stopRequested = false
|
||||
if (activeInstallWorker == null) SessionState.stopRequested = false
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
|
||||
collectStartArtifacts("session start cancelled")
|
||||
finish()
|
||||
@@ -1790,17 +1809,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun installDesktop(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) }
|
||||
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this)
|
||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
|
||||
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
|
||||
return problem?.let { getString(R.string.session_desktop_install_failed, it) }
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
return try {
|
||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, cancellation,
|
||||
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
|
||||
problem?.let { getString(R.string.session_desktop_install_failed, it) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun installProton(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
|
||||
?: return "catalog unreachable"
|
||||
return catalog.install(this, entry, progressFor(PROTON_LINES, entry.size / 1_000_000))
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
return try {
|
||||
val entry = catalog.fetch(catalog.STEAM_SEED_URL, cancellation)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
|
||||
?: return if (cancellation.asBoolean) "cancelled" else "catalog unreachable"
|
||||
catalog.install(this, entry, cancellation, progressFor(PROTON_LINES, entry.size / 1_000_000))
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
@@ -3876,6 +3907,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private const val PAUSED_FRAME_REDRAW_MS = 150L
|
||||
private const val TAG = "SessionActivity"
|
||||
private var startedScreens = 0
|
||||
@Volatile private var activeInstallWorker: Any? = null
|
||||
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
|
||||
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
|
||||
private const val CURSOR_PAD_HOLD_MS = 1200L
|
||||
|
||||
@@ -16,20 +16,83 @@ import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class Downloader {
|
||||
private static final String TAG = "Downloader";
|
||||
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
||||
private static final int STALL_TIMEOUT_MS = 15_000;
|
||||
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
|
||||
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
|
||||
java.util.concurrent.Executors.newCachedThreadPool(r -> {
|
||||
Thread thread = new Thread(r, "download-cancel");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
private Downloader() {}
|
||||
|
||||
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
||||
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
||||
private final AtomicReference<InputStream> input = new AtomicReference<>();
|
||||
private final java.util.function.BooleanSupplier external;
|
||||
|
||||
public Cancellation() { this(null); }
|
||||
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
|
||||
|
||||
public void cancel() {
|
||||
cancelled.set(true);
|
||||
HttpURLConnection active = connection.get();
|
||||
if (active != null) disconnectAsync(active);
|
||||
InputStream activeInput = input.get();
|
||||
if (activeInput != null) closeAsync(activeInput);
|
||||
}
|
||||
|
||||
private static void disconnectAsync(HttpURLConnection active) {
|
||||
CANCEL_EXECUTOR.execute(() -> {
|
||||
try { active.disconnect(); } catch (RuntimeException ignored) { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void closeAsync(InputStream active) {
|
||||
CANCEL_EXECUTOR.execute(() -> {
|
||||
try { active.close(); } catch (IOException ignored) { }
|
||||
});
|
||||
}
|
||||
|
||||
@Override public boolean getAsBoolean() {
|
||||
return cancelled.get() || (external != null && external.getAsBoolean());
|
||||
}
|
||||
|
||||
private void attach(HttpURLConnection active) {
|
||||
connection.set(active);
|
||||
if (getAsBoolean()) disconnectAsync(active);
|
||||
}
|
||||
|
||||
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
|
||||
|
||||
private void attach(InputStream active) {
|
||||
input.set(active);
|
||||
if (getAsBoolean()) closeAsync(active);
|
||||
}
|
||||
|
||||
private void detach(InputStream active) { input.compareAndSet(active, null); }
|
||||
}
|
||||
|
||||
public static String downloadString(String url) {
|
||||
return downloadString(url, null);
|
||||
}
|
||||
|
||||
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
||||
// A cancelled fetch says nothing about the source, so it must not count as a failure.
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (fetch.body != null) {
|
||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||
return fetch.body;
|
||||
@@ -53,30 +116,52 @@ public final class Downloader {
|
||||
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
return downloadFile(url, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
|
||||
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
|
||||
}
|
||||
|
||||
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
|
||||
static List<String> sources(String url, String expectedSha256) {
|
||||
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
|
||||
|
||||
}
|
||||
|
||||
// Package-private for the local multi-source HTTP test.
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
String source = sources.get(i);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
|
||||
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
|
||||
if (outcome == Outcome.CANCELLED) return false;
|
||||
if (outcome == Outcome.DONE) {
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
if (expectedSha256 != null) {
|
||||
String actualSha256 = Hashes.sha256(destination);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (isCancelled(cancelled)) return false;
|
||||
resumeFile(destination).delete();
|
||||
DownloadSource.INSTANCE.succeeded(source);
|
||||
if (progress != null) progress.accept(1f);
|
||||
@@ -88,7 +173,11 @@ public final class Downloader {
|
||||
return false;
|
||||
}
|
||||
|
||||
private enum Outcome { DONE, RETRY, FATAL }
|
||||
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
|
||||
|
||||
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
|
||||
return cancelled != null && cancelled.getAsBoolean();
|
||||
}
|
||||
|
||||
private static final class Identity {
|
||||
private String source;
|
||||
@@ -156,7 +245,9 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
HttpURLConnection connection = null;
|
||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||
try {
|
||||
@@ -166,6 +257,7 @@ public final class Downloader {
|
||||
have = 0;
|
||||
}
|
||||
connection = open(url, STALL_TIMEOUT_MS);
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
|
||||
if (have > 0) {
|
||||
connection.setRequestProperty("Range", "bytes=" + have + "-");
|
||||
connection.setRequestProperty("If-Range", identity.etag);
|
||||
@@ -174,7 +266,7 @@ public final class Downloader {
|
||||
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
@@ -185,13 +277,13 @@ public final class Downloader {
|
||||
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
String etag = connection.getHeaderField("ETag");
|
||||
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
if (!appending && have > 0) {
|
||||
// If-Range may legitimately return full 200 when representation changed.
|
||||
@@ -208,26 +300,36 @@ public final class Downloader {
|
||||
identity.etag = strongETag(etag) ? etag : null;
|
||||
saveIdentity(destination, identity, expectedSha256);
|
||||
long written = have;
|
||||
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
|
||||
InputStream input = connection.getInputStream();
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
|
||||
try (InputStream in = new BufferedInputStream(input, 1 << 16);
|
||||
OutputStream out = new FileOutputStream(destination, appending)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
long lastReport = 0;
|
||||
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
|
||||
out.write(buffer, 0, read);
|
||||
written += read;
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (progress != null && written - lastReport > (1 << 20)) {
|
||||
lastReport = written;
|
||||
progress.accept(total > 0 ? written / (float) total : -1f);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
||||
}
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (total > 0 && written < total) return Outcome.RETRY;
|
||||
return Outcome.DONE;
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
Log.w(TAG, "download " + url, e);
|
||||
return Outcome.RETRY;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
if (connection != null) {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,9 +358,15 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static Fetch fetch(String url) {
|
||||
return fetch(url, null);
|
||||
}
|
||||
|
||||
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
HttpURLConnection connection = null;
|
||||
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
|
||||
try {
|
||||
connection = open(url, STALL_TIMEOUT_MS);
|
||||
if (token != null) token.attach(connection);
|
||||
int code = connection.getResponseCode();
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
@@ -270,10 +378,14 @@ public final class Downloader {
|
||||
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return new Fetch(null, false);
|
||||
Log.w(TAG, "GET " + url, e);
|
||||
return new Fetch(null, false);
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
if (connection != null) {
|
||||
if (token != null) token.detach(connection);
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ object DesktopCatalog {
|
||||
val icon: String, val category: String,
|
||||
)
|
||||
|
||||
fun fetch(url: String = CATALOG_URL): List<Entry>? {
|
||||
val body = Downloader.downloadString(url) ?: return null
|
||||
fun fetch(url: String = CATALOG_URL, cancelled: java.util.function.BooleanSupplier? = null): List<Entry>? {
|
||||
val body = Downloader.downloadString(url, cancelled) ?: return null
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val arr = json.getJSONArray("packages")
|
||||
@@ -71,9 +71,22 @@ object DesktopCatalog {
|
||||
}
|
||||
|
||||
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
resumeInterrupted(context, null, listener)
|
||||
}
|
||||
|
||||
fun resumeInterrupted(
|
||||
context: Context,
|
||||
cancelled: Downloader.Cancellation?,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?,
|
||||
): String? = synchronized(installLock) {
|
||||
for (entry in interrupted(context)) {
|
||||
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
|
||||
install(context, entry, listener)?.let { return it }
|
||||
val problem = if (cancelled == null) {
|
||||
install(context, entry, listener)
|
||||
} else {
|
||||
install(context, entry, cancelled, listener)
|
||||
}
|
||||
if (problem != null) return problem
|
||||
}
|
||||
null
|
||||
}
|
||||
@@ -144,10 +157,16 @@ object DesktopCatalog {
|
||||
}
|
||||
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
installLocked(context, entry, listener)
|
||||
installLocked(context, entry, null, listener)
|
||||
}
|
||||
|
||||
private fun installLocked(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
fun install(context: Context, entry: Entry, cancelled: Downloader.Cancellation,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
installLocked(context, entry, cancelled, listener)
|
||||
}
|
||||
|
||||
private fun installLocked(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
|
||||
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
|
||||
@@ -166,14 +185,20 @@ object DesktopCatalog {
|
||||
if (!downloaded(download, entry)) {
|
||||
val downloading = context.getString(R.string.user_apps_downloading, entry.name)
|
||||
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
|
||||
val ok = Downloader.downloadFile(entry.url, download, true, entry.sha256) { f ->
|
||||
val progress = java.util.function.Consumer<Float> { f ->
|
||||
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f))
|
||||
}
|
||||
if (!ok) return context.getString(R.string.user_apps_download_failed)
|
||||
val ok = if (cancelled == null) {
|
||||
Downloader.downloadFile(entry.url, download, true, entry.sha256, progress)
|
||||
} else {
|
||||
Downloader.downloadFile(entry.url, download, true, entry.sha256, cancelled, progress)
|
||||
}
|
||||
if (!ok || cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
|
||||
report.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1)
|
||||
val actual = Hashes.sha256(download)
|
||||
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch)
|
||||
}
|
||||
if (cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
|
||||
report.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1)
|
||||
when (entry.kind) {
|
||||
"appimage" -> {
|
||||
|
||||
@@ -2178,6 +2178,7 @@ class SessionService : Service() {
|
||||
fun stop(context: Context) {
|
||||
if (!SessionState.running) {
|
||||
SessionState.stopRequested = true
|
||||
SessionState.installCancellation?.cancel()
|
||||
return
|
||||
}
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
||||
|
||||
@@ -37,6 +37,9 @@ object SessionState {
|
||||
@Volatile
|
||||
var installing: String? = null
|
||||
|
||||
@Volatile
|
||||
var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null
|
||||
|
||||
@Volatile
|
||||
var stopRequested = false
|
||||
|
||||
|
||||
Reference in new issue
Block a user