Stores: GOG downloads use every CDN host; progress bars glide

GOG's secure link lists several CDN hosts and only the first was taken,
so every request went to one host. All are parsed now and kept as one
set, refreshed together when the link expires; the built-in pool takes
them in turn and the native engine gets the first until its contract
takes a list. The progress bar fill glides to each new value over a
quarter second, drawn without relayout.
This commit is contained in:
The412Banner committed 2026-10-09 06:02:37 -04:00
1 parent 90a8a526d5
commit 889e783520
4 files changed
+93 -19

No files matched your search

@@ -562,7 +562,9 @@ public final class GogDownloadManager {
okRef.set(success); linkExpiryRef.set(linkExpiry); errRef.set(error == null ? "" : error); latch.countDown();
}
};
long handle = GogNative.start(kind, manifests, base, installPath.getAbsolutePath(), donePaths.toArray(new String[0]), "",
// The engine takes one base today; it gets the first of the set (JNI.md).
if (run == 1) cb.onLog("gog: " + base.split("\n").length + " CDN host(s) offered");
long handle = GogNative.start(kind, manifests, firstCdn(base), installPath.getAbsolutePath(), donePaths.toArray(new String[0]), "",
workers, process, sortLargestFirst, label + " run=" + run, listener);
if (handle == 0L) { cb.onLog("gog: native start failed"); anyFailed.set(true); return; }
boolean interrupted = false;
@@ -651,24 +653,53 @@ public final class GogDownloadManager {
return tmpFile.renameTo(outFile);
}
/**
* Every CDN the secure link offers, as one value - their bases, one per line - so the set is
* refreshed (and compared on expiry) as a whole. GOG answers with several hosts in {@code urls[]};
* taking only the first left every request on one host.
*/
private static String parseCdnUrl(String json) {
if (json == null) return null;
java.util.List<String> all = parseCdnUrls(json);
return all.isEmpty() ? null : String.join("\n", all);
}
/** The CDN bases of a secure_link answer, in the order GOG gives them. */
static java.util.List<String> parseCdnUrls(String json) {
java.util.List<String> out = new ArrayList<>();
if (json == null) return out;
try {
JSONArray urls = new JSONObject(json).optJSONArray("urls");
if (urls == null || urls.length() == 0) return null;
JSONObject first = urls.getJSONObject(0);
String urlFormat = first.optString("url_format");
JSONObject params = first.optJSONObject("parameters");
if (urlFormat == null || params == null) return null;
java.util.Iterator<String> keys = params.keys();
while (keys.hasNext()) { String k = keys.next(); urlFormat = urlFormat.replace("{" + k + "}", params.optString(k)); }
urlFormat = urlFormat.replace("\\/", "/");
int idx = urlFormat.indexOf("/{path}");
if (idx >= 0) urlFormat = urlFormat.substring(0, idx);
return urlFormat;
} catch (Exception e) {
return null;
if (urls == null) return out;
for (int i = 0; i < urls.length(); i++) {
JSONObject u = urls.optJSONObject(i);
if (u == null) continue;
String urlFormat = u.optString("url_format");
JSONObject params = u.optJSONObject("parameters");
if (urlFormat == null || urlFormat.isEmpty() || params == null) continue;
java.util.Iterator<String> keys = params.keys();
while (keys.hasNext()) { String k = keys.next(); urlFormat = urlFormat.replace("{" + k + "}", params.optString(k)); }
urlFormat = urlFormat.replace("\\/", "/");
int idx = urlFormat.indexOf("/{path}");
if (idx >= 0) urlFormat = urlFormat.substring(0, idx);
if (!out.contains(urlFormat)) out.add(urlFormat);
}
} catch (Exception ignored) {
}
return out;
}
private static final AtomicInteger CDN_TURN = new AtomicInteger();
/** One of the set's CDNs, in turn, so the Java pool spreads its requests over all of them. */
static String pickCdn(String set) {
String[] all = set.split("\n");
return all[Math.floorMod(CDN_TURN.getAndIncrement(), all.length)];
}
/** The first CDN of the set - what a caller that takes a single base gets. */
static String firstCdn(String set) {
int nl = set.indexOf('\n');
return nl < 0 ? set : set.substring(0, nl);
}
private static boolean downloadRange(String url, long offset, long size, File out) {
@@ -850,7 +881,7 @@ public final class GogDownloadManager {
while (guard++ < 8) {
if (cancelled.get()) return null;
String base = cdnBaseRef.get();
HttpResult res = fetchBytesEx(buildChunkUrl(base, chunkPath), null);
HttpResult res = fetchBytesEx(buildChunkUrl(pickCdn(base), chunkPath), null);
if (res.body == null) {
int code = res.status;
if ((code == 401 || code == 403 || code == 404 || code == 500) && tryRefreshCdn(cdnBaseRef, base, secureLinkUrl, token, cdnRefreshCount, maxCdnRefresh, cb)) continue;
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.blur
@@ -567,9 +568,15 @@ internal fun ProgressBarThin(fraction: Float, paused: Boolean = false, verify: B
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val fill = when { done -> pal.good; paused -> Color(0xFFFFC24D); verify -> Color(0xFF9B6DFF); else -> pal.signal }
Box(Modifier.fillMaxWidth().height(height).clip(RoundedCornerShape(height / 2)).background(colors.surfaceVariant)) {
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).height(height).background(fill))
}
// The fill glides to each new value over a quarter second - progress arrives a few times a second
// and in steps - and is read only while drawing, so the bar animates without relayout.
val shown = androidx.compose.animation.core.animateFloatAsState(
fraction.coerceIn(0f, 1f), androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing), label = "bar",
)
Box(
Modifier.fillMaxWidth().height(height).clip(RoundedCornerShape(height / 2)).background(colors.surfaceVariant)
.drawBehind { drawRect(fill, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height)) },
)
}
@Composable
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.stores.gog
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Every CDN GOG's secure link offers is used, not only the first. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogCdnTest {
private val answer = """{"urls":[
{"endpoint_name":"fastly","url_format":"https:\/\/gog-cdn-fastly.gog.com\/token=nva={expires_at}~token={token}/{path}","parameters":{"expires_at":1,"token":"t"}},
{"endpoint_name":"akamai","url_format":"{base_url}/{path}","parameters":{"base_url":"https://gog-cdn-akamai.gog.com/s"}},
{"endpoint_name":"lumen","url_format":"https://cdn.gog.com/{path}","parameters":{}}
]}"""
@Test fun allHostsAreParsedInOrderAndTakenInTurn() {
val all = GogDownloadManager.parseCdnUrls(answer)
assertEquals(3, all.size)
assertEquals("https://gog-cdn-fastly.gog.com/token=nva=1~token=t", all[0])
assertEquals("https://gog-cdn-akamai.gog.com/s", all[1])
assertEquals("https://cdn.gog.com", all[2])
val set = all.joinToString("\n")
assertEquals(all[0], GogDownloadManager.firstCdn(set))
val picks = (0 until 6).map { GogDownloadManager.pickCdn(set) }.toSet()
assertEquals(all.toSet(), picks)
assertEquals(0, GogDownloadManager.parseCdnUrls("not json").size)
}
}