Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@

import org.iiab.controller.config.BoxEndpoints;
import org.iiab.controller.util.AppExecutors;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public final class DashboardClient {
private DashboardClient() {}
Expand All @@ -35,6 +39,7 @@ private DashboardClient() {}
private static final String URL_REBUILD = BoxEndpoints.API + "/system/dashboard/rebuild";
private static final String URL_REBUILD_STATUS = BoxEndpoints.API + "/system/dashboard/rebuild/status";
private static final String URL_REBUILD_CANCEL = BoxEndpoints.API + "/system/dashboard/rebuild/cancel";
private static final String URL_REBUILD_LOG = BoxEndpoints.API + "/system/dashboard/rebuild/log"; // ADFA-5339
private static final Handler MAIN = new Handler(Looper.getMainLooper());

public interface UpdateCb {
Expand Down Expand Up @@ -63,13 +68,21 @@ public interface RebuildCancelCb {
void onErr(String message);
}

/** ADFA-5339: the rebuild log tail (last ~200 lines), for the card's expandable Details. */
public interface RebuildLogCb {
void onLines(List<String> lines);
void onErr(String message);
}

/** ADFA-5051: trigger the in-server blue-green rebuild (POST). Fire-and-forget: the box returns 202
* at once (or 409 if one is already running); the caller then polls {@link #rebuildStatus}. */
public static void rebuildStart(RebuildStartCb cb) {
* at once (or 409 if one is already running); the caller then polls {@link #rebuildStatus}.
* ADFA-5339: {@code updateSite} sends {site:true} so the finalize step also refreshes the served
* landing page. A box older than 1.2.12 (or the proot rebuild path) ignores the body — harmless. */
public static void rebuildStart(boolean updateSite, RebuildStartCb cb) {
AppExecutors.get().io().execute(() -> {
int[] status = {0};
try {
httpPost(URL_REBUILD, status);
httpPostJson(URL_REBUILD, "{\"site\":" + updateSite + "}", status);
MAIN.post(() -> cb.onStarted(false));
} catch (Exception e) {
if (status[0] == 409) { MAIN.post(() -> cb.onStarted(true)); return; }
Expand All @@ -78,6 +91,22 @@ public static void rebuildStart(RebuildStartCb cb) {
});
}

/** ADFA-5339: fetch the rebuild log tail. A box without the endpoint (older dash-node) or no rebuild
* yet yields an empty list rather than an error the UI would have to special-case — the Details
* panel simply shows nothing / no chevron. */
public static void rebuildLog(RebuildLogCb cb) {
AppExecutors.get().io().execute(() -> {
try {
JSONArray arr = new JSONObject(httpGet(URL_REBUILD_LOG)).optJSONArray("lines");
final List<String> lines = new ArrayList<>();
if (arr != null) for (int i = 0; i < arr.length(); i++) lines.add(arr.optString(i, ""));
MAIN.post(() -> cb.onLines(lines));
} catch (Exception e) {
MAIN.post(() -> cb.onErr(e.getMessage()));
}
});
}

/** ADFA-5333: ask the box to cancel the in-flight rebuild. 200 => cancelled; 409 with promoting=true
* => too late (swap finishing); 409 otherwise => nothing running. The body carries the flags, so this
* reads it directly rather than going through the shared bodyless POST. */
Expand Down Expand Up @@ -159,16 +188,19 @@ private static String httpGet(String urlStr) throws Exception {
}
}

/** POST with no body; {@code statusOut[0]} receives the HTTP status so callers can map 409. The
* trigger returns immediately (202), so a short read timeout is fine. */
private static void httpPost(String urlStr, int[] statusOut) throws Exception {
/** POST a JSON body; {@code statusOut[0]} receives the HTTP status so callers can map 409. Like the
* bodyless trigger, the box answers 202 immediately, so a short read timeout is fine. */
private static void httpPostJson(String urlStr, String body, int[] statusOut) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
c.setUseCaches(false);
c.setConnectTimeout(5000);
c.setReadTimeout(10000);
c.setRequestMethod("POST"); // bodyless trigger; no doOutput/body needed
c.setRequestMethod("POST");
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("Content-Type", "application/json");
c.setDoOutput(true);
try (OutputStream os = c.getOutputStream()) { os.write(body.getBytes(StandardCharsets.UTF_8)); }
int code = c.getResponseCode();
statusOut[0] = code;
readAll(code >= 200 && code < 400 ? c.getInputStream() : c.getErrorStream());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ public class DashboardDetailFragment extends Fragment {
private View updatingRow; // ADFA-5333: in-progress indicator (indeterminate bar + label + Cancel)
private View updatingCancel; // ADFA-5333: the Cancel affordance beside the bar
private boolean updating; // ADFA-5333: a background rebuild is in flight; don't re-emphasize Rebuild
private boolean updateAvailable; // ADFA-5339: last-known — the confirm dialog matches the button
// ADFA-5339: expandable Details — the live rebuild log, minimized by default. The toggle is hidden
// until there are lines (an older box without /rebuild/log, or a rebuild that hasn't logged yet).
private TextView detailsToggle;
private android.widget.ScrollView logScroll;
private TextView logText;
private boolean logExpanded;
private static final long LOG_POLL_MS = 1500L;
private final Runnable logPoll = this::pollLog;

/** ADFA-5333: the live update runs in the background (DashboardRebuildService), which broadcasts each
* state change. While this card is on screen we show/hide an in-progress bar and, on done, refresh
Expand Down Expand Up @@ -104,7 +113,7 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
// "Rebuild"; hide the secondary "Install now".
rebuild = root.findViewById(R.id.k2go_moddet_schedule);
rebuild.setText(R.string.k2go_dash_rebuild);
rebuild.setOnClickListener(v -> DashboardRebuild.confirmAndStart(this, root));
rebuild.setOnClickListener(v -> DashboardRebuild.confirmAndStart(this, root, updateAvailable));
root.findViewById(R.id.k2go_moddet_install_now).setVisibility(View.GONE);
rebuildHint = buildRebuildHint(rebuild); // ADFA-5026: "no rebuild needed" note (hidden until on-latest)
updatingRow = buildUpdatingRow(rebuild); // ADFA-5333: in-progress bar (hidden until updating)
Expand Down Expand Up @@ -194,6 +203,7 @@ private void applyCardState(DashboardCardState s) {
sub.setText(R.string.k2go_dash_detail_sub);
}
}
updateAvailable = s.primaryIsUpdate(); // ADFA-5339: so the confirm dialog matches the button
if (updating) return; // ADFA-5333: a rebuild is in flight — leave the button/bar as they are
if (rebuild != null) {
if (s.primaryIsUpdate()) {
Expand Down Expand Up @@ -297,6 +307,33 @@ private View buildUpdatingRow(Button rebuildBtn) {
updatingCancel = cancel;

row.addView(line);

// ADFA-5339: Details — a "Show details" toggle (hidden until there are log lines) that reveals
// the live rebuild log in place. Mirrors the module-install Details pattern; the button above
// stays fixed. Text chevron (▾/▴) to avoid a new drawable.
detailsToggle = new TextView(requireContext());
detailsToggle.setText(getString(R.string.k2go_maps_log_show) + " ▾");
detailsToggle.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_LabelLarge);
detailsToggle.setTextColor(ContextCompat.getColor(requireContext(), R.color.k2go_teal));
detailsToggle.setPadding(0, Math.round(8 * d), 0, Math.round(4 * d));
detailsToggle.setClickable(true);
detailsToggle.setVisibility(View.GONE);
detailsToggle.setOnClickListener(v -> toggleLog());
row.addView(detailsToggle);

logScroll = new android.widget.ScrollView(requireContext());
LinearLayout.LayoutParams slp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, Math.round(160 * d));
logScroll.setLayoutParams(slp);
logScroll.setVisibility(View.GONE);
logText = new TextView(requireContext());
logText.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodySmall);
logText.setTextColor(ContextCompat.getColor(requireContext(), R.color.k2go_muted));
logText.setTypeface(android.graphics.Typeface.MONOSPACE);
logText.setTextIsSelectable(true);
logScroll.addView(logText);
row.addView(logScroll);

row.setVisibility(View.GONE);
parent.addView(row, parent.indexOfChild(rebuildBtn));
return row;
Expand Down Expand Up @@ -330,6 +367,54 @@ private void setUpdating(boolean on) {
if (updatingCancel != null) updatingCancel.setEnabled(on); // re-enable when a new update shows
if (rebuild != null) { rebuild.setEnabled(!on); rebuild.setAlpha(on ? 0.5f : 1f); }
if (on && rebuildHint != null) rebuildHint.setVisibility(View.GONE);
// ADFA-5339: the Details log only exists while a rebuild runs. Poll it on, tear it down on off.
main.removeCallbacks(logPoll);
if (on) {
main.post(logPoll);
} else if (detailsToggle != null) {
detailsToggle.setVisibility(View.GONE);
if (logScroll != null) logScroll.setVisibility(View.GONE);
}
}

/** ADFA-5339: reveal/hide the live log in place; the Rebuild button and everything else stay put. */
private void toggleLog() {
logExpanded = !logExpanded;
if (logScroll != null) logScroll.setVisibility(logExpanded ? View.VISIBLE : View.GONE);
if (detailsToggle != null) {
detailsToggle.setText(getString(
logExpanded ? R.string.k2go_maps_log_hide : R.string.k2go_maps_log_show)
+ (logExpanded ? " ▴" : " ▾"));
}
}

/** ADFA-5339: poll the rebuild log tail while updating. Fork B — the toggle appears only once there
* are lines, so an older box without the endpoint (empty) shows no Details affordance. Reschedules
* itself while {@code updating}; setUpdating(false) and onDestroyView remove the callback. */
private void pollLog() {
if (!isAdded() || !updating) return;
DashboardClient.rebuildLog(new DashboardClient.RebuildLogCb() {
@Override public void onLines(java.util.List<String> lines) {
if (!isAdded() || !updating) return;
if (!lines.isEmpty()) {
if (detailsToggle != null) detailsToggle.setVisibility(View.VISIBLE);
if (logText != null) logText.setText(android.text.TextUtils.join("\n", lines));
if (logExpanded && logScroll != null) {
logScroll.post(() -> logScroll.fullScroll(View.FOCUS_DOWN));
}
}
main.postDelayed(logPoll, LOG_POLL_MS);
}
@Override public void onErr(String message) {
// No endpoint / transient: keep the toggle as-is (hidden if never populated) and retry.
if (isAdded() && updating) main.postDelayed(logPoll, LOG_POLL_MS);
}
});
}

@Override public void onDestroyView() {
main.removeCallbacks(logPoll); // ADFA-5339: never poll past the view's life
super.onDestroyView();
}

/** Read the installed version from the rootfs package.json on disk (authoritative, always present;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ private DashboardRebuild() {}
* snackbars show. A visible dashboard card refreshes itself on
* {@link DashboardRebuildService#ACTION_STATE} (ADFA-5333), so there is no completion callback to
* pass here — the background update outlives this fragment. */
public static void confirmAndStart(@NonNull Fragment host, @NonNull View anchor) {
public static void confirmAndStart(@NonNull Fragment host, @NonNull View anchor, boolean updateAvailable) {
Context ctx = host.requireContext();
if (org.iiab.controller.env.EnvironmentLock.isHeld(ctx)) {
Snackbars.make(anchor, org.iiab.controller.util.BusyMessage.resFor(ctx)).show();
Expand All @@ -57,18 +57,47 @@ public static void confirmAndStart(@NonNull Fragment host, @NonNull View anchor)
Snackbars.make(anchor, R.string.k2go_dash_needs_internet).show();
return;
}
// ADFA-5339: a versionless "Update the Website" checkbox (default on) rides on the confirm. It
// refreshes the served landing page in the same run — a SEPARATE, unversioned artifact, so it
// carries no version label. Built in code to leave the shared dialog usage untouched.
final com.google.android.material.checkbox.MaterialCheckBox siteBox =
new com.google.android.material.checkbox.MaterialCheckBox(ctx);
siteBox.setText(R.string.k2go_dash_update_site);
siteBox.setChecked(true);
siteBox.setCompoundDrawablePadding(Math.round(8 * ctx.getResources().getDisplayMetrics().density));
// Align the checkbox's left edge with the dialog's title/message, which are inset by
// dialogPreferredPadding — the custom view otherwise sits flush left. A container carries that
// inset so the checkbox's own left padding stays 0 and the box lines up with the text above.
int pad = dialogPadding(ctx);
android.widget.FrameLayout holder = new android.widget.FrameLayout(ctx);
holder.setPadding(pad, Math.round(8 * ctx.getResources().getDisplayMetrics().density), pad, 0);
holder.addView(siteBox);
// ADFA-5339: the confirm matches the primary action — "Update" when a newer build exists,
// "Rebuild" for a manual re-apply — so the dialog can't say "Rebuild" over an "Update" button.
new MaterialAlertDialogBuilder(ctx)
.setTitle(R.string.k2go_dash_rebuild_confirm_title)
.setTitle(updateAvailable ? R.string.k2go_dash_update_confirm_title
: R.string.k2go_dash_rebuild_confirm_title)
.setMessage(R.string.k2go_dash_rebuild_confirm_msg)
.setView(holder)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.k2go_dash_rebuild, (d, w) -> start(host, anchor))
.setPositiveButton(updateAvailable ? R.string.k2go_dash_update : R.string.k2go_dash_rebuild,
(d, w) -> start(host, anchor, siteBox.isChecked()))
.show();
}

/** The dialog's horizontal content inset (title/message use it); the custom view must match it. */
private static int dialogPadding(Context ctx) {
android.util.TypedValue tv = new android.util.TypedValue();
if (ctx.getTheme().resolveAttribute(androidx.appcompat.R.attr.dialogPreferredPadding, tv, true)) {
return android.util.TypedValue.complexToDimensionPixelSize(tv.data, ctx.getResources().getDisplayMetrics());
}
return Math.round(24 * ctx.getResources().getDisplayMetrics().density); // Material default
}

/** ADFA-5051: route by the installed dash-node version. >= 1.2.0 updates live over REST; older
* installs take the proot rebuild once as a bridge to 1.2.0. The version read hits disk, so it
* runs off the main thread; the routing itself is posted back to the UI. */
private static void start(@NonNull Fragment host, @NonNull View anchor) {
private static void start(@NonNull Fragment host, @NonNull View anchor, boolean updateSite) {
final Context app = host.requireContext().getApplicationContext();
final Handler main = new Handler(Looper.getMainLooper());
AppExecutors.get().io().execute(() -> {
Expand All @@ -84,7 +113,9 @@ private static void start(@NonNull Fragment host, @NonNull View anchor) {
final Operation op = Operation.of("dashboard", Operation.Kind.APP_INSTALL, cls);
main.post(() -> {
if (!host.isAdded()) return;
if (op.isLive()) startRest(host, anchor);
// ADFA-5339: the site refresh only applies to the LIVE REST path; the proot bridge rebuild
// (< 1.2.0) has no site step, so the checkbox is simply not carried there.
if (op.isLive()) startRest(host, anchor, updateSite);
else startProot(host);
});
});
Expand All @@ -106,8 +137,8 @@ private static void startProot(@NonNull Fragment host) {
* notification) and let the user go — the service POSTs the rebuild and polls the box until it
* reports done/error, with no time cap. A visible dashboard card refreshes on the service's
* completion broadcast; nothing pins this screen. */
private static void startRest(@NonNull Fragment host, @NonNull View anchor) {
DashboardRebuildService.start(host.requireContext().getApplicationContext());
private static void startRest(@NonNull Fragment host, @NonNull View anchor, boolean updateSite) {
DashboardRebuildService.start(host.requireContext().getApplicationContext(), updateSite);
if (host.isAdded()) Snackbars.make(anchor, R.string.k2go_dash_update_started).show();
}

Expand Down
Loading
Loading