diff --git a/CHANGELOG.md b/CHANGELOG.md index bcbf464b..6e09f79c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **Get mods: HMG-API's catalogue on the head unit.** Mods tab → Get mods lists `catalog/` + (each mod's own GitHub release, pinned by SHA-256 and author key) with what installing it + would do here; Install downloads it over home Wi-Fi and installs it. No server of our own: + the catalogue comes from `catalog/index.json` when there is one (`tools/catalog.py index`), + else from GitHub's listing of the folder. Engine: `catalog`, `catalog-plan`, `catalog-install`. - **Dependencies are installed with a mod.** A mod's `requires` (copied into its catalogue entry by `catalog.py add`, and read again from the downloaded zip's `mod.json`) are met by what's installed, or by the catalogue's version, installed first; a required mod that's @@ -20,6 +25,22 @@ installed or turned on, signed with the installed key) into `/data/hmgapi/pending/`, which nothing loads; `engine apply` puts them in place first and keeps the previous version in `/data/hmgapi/previous/`. +- **Updates.** Mods tab → Updates (with how many) lists installed mods with a newer catalogue + version, and a newer HMG-API release (on a pre-release, only that version's next ones), with + its release notes, Update and Update all (each mod that can go; the ones that can't are listed + with why). "Install anyway" is per mod and says for what: not listed for this head unit, or an + author who isn't on the trusted list. A mod's row in the list says "update x.y.z". HMG-API checks by itself each time + home Wi-Fi comes up, at most every 6 hours (owner switch `no_update_check` turns that off), and + can also download and stage the mods' plain updates then (`auto_stage_updates`, off by + default): they wait aside until the owner applies. + HMG-API itself only updates on the owner's tap: its update zip is checked against its + release's `SHA256SUMS`, then against the release key as from a USB stick. Engine: `updates`, + `update ... | --all | hmgapi`, `update-check`; `logs/hmgapi/updates.log`. +- **HMG-API's own HTTPS** (`/data/hmgapi/lib/libhmgapi_fetch.so`, `core/fetch`): Android 4.4's + Java TLS can't reach GitHub, so the engine uses the unit's own `libssl.so` (TLS 1.2), on a + socket marked for home Wi-Fi only, with its own DNS lookup on home Wi-Fi's server. Tested + first as a mod on an Ioniq 5 US 260507 (HMG-API rc.10): the catalogue and three packages + over home Wi-Fi, each with its SHA-256. - **Home Wi-Fi joins on cars whose Wi-Fi library checks a checksum** (Ioniq 5 US 260507). The stock library starts the car's Wi-Fi client only if `wpa_supplicant_crc32.conf` holds the CRC-32 of `wpa_supplicant.conf`; HMG-API's saved networks didn't update it, so the client diff --git a/core/app/java/hmgapi/app/CatalogFlow.java b/core/app/java/hmgapi/app/CatalogFlow.java new file mode 100644 index 00000000..791e0678 --- /dev/null +++ b/core/app/java/hmgapi/app/CatalogFlow.java @@ -0,0 +1,339 @@ +package hmgapi.app; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Installing or updating from the catalogue, for the Catalogue and Updates screens: what it takes + * first (engine catalog-plan: the mods they require, in order), the owner's OK, then the downloads + * and installs (engine catalog-install / update). The owner's "Install anyway" is per mod and per + * reason (not listed for this head unit: --any-car=; an author key that isn't on the trusted + * list: --any-author=). Update all plans each mod on its own (update --all): the ones that can't + * go now are listed, the rest go. When a mod zip turns out to need more than the plan said, the + * engine stops (exit 5) and the new plan is shown for a second OK. Nothing is applied here: the + * screen hands back RESULT_OK and the main screen applies (plan first), as after a USB install. + */ +final class CatalogFlow { + private CatalogFlow() {} + + /** the engine's exit when the mod zips need more steps than the plan the owner saw */ + static final int PLAN_CHANGED = 5; + + abstract static class Done { + abstract void installed(String output); + + abstract void failed(String output); + + /** + * No answer in time (the install goes on by itself in the engine). The screen should hand back + * RESULT_OK all the same: the main screen's plan waits for the engine, then shows what changed. + */ + void lost(String message) { + failed(message); + } + } + + /** what the owner said yes to, per mod */ + static final class Choice { + final Set anyCar = new LinkedHashSet(), anyAuthor = new LinkedHashSet(); + + void args(List c) { + if (!anyCar.isEmpty()) c.add("--any-car=" + join(anyCar)); + if (!anyAuthor.isEmpty()) c.add("--any-author=" + join(anyAuthor)); + } + } + + static String join(Iterable s) { + StringBuilder b = new StringBuilder(); + for (String x : s) b.append(b.length() > 0 ? "," : "").append(x); + return b.toString(); + } + + /** JSON in an engine answer (it may print notes first) */ + static JSONObject json(String output) throws Exception { + String t = output.trim(); + int i = t.indexOf('{'); + if (i < 0) throw new Exception(t.isEmpty() ? "no answer" : t); + return new JSONObject(t.substring(i)); + } + + /** "update": engine update (ids are installed mods), else engine catalog-install */ + static void start(Activity a, List ids, boolean update, Done done) { + plan(a, ids, update, false, new Choice(), done); + } + + /** Update all: each installed mod with an update, planned on its own */ + static void startAll(Activity a, Done done) { + plan(a, new ArrayList(), true, true, new Choice(), done); + } + + private static void plan(final Activity a, final List ids, final boolean update, final boolean all, final Choice ch, final Done done) { + final AlertDialog wait = new AlertDialog.Builder(a).setMessage("Checking what it needs…").show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + List c = new ArrayList(Arrays.asList("engine", "catalog-plan")); + if (all) c.add("--all"); + else c.addAll(ids); + if (update) c.add("--update"); + ch.args(c); + return Hmgapid.call(180000, c.toArray(new String[0])); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + JSONObject p; + try { + if (e != null) throw e; + p = json(r.output); + } catch (Exception x) { + done.failed("Couldn't check: " + x.getMessage()); + return; + } + confirm(a, p, ids, update, all, ch, null, done); + } + }.start(a); + } + + /** the yes-or-no's in a plan: its own, and (update all) the left-out mods' */ + private static List overrides(JSONObject p) { + List out = new ArrayList(); + JSONArray o = p.optJSONArray("overrides"); + for (int i = 0; o != null && i < o.length(); i++) out.add(o.optJSONObject(i)); + JSONArray sk = p.optJSONArray("skipped"); + for (int i = 0; sk != null && i < sk.length(); i++) { + JSONArray so = sk.optJSONObject(i).optJSONArray("overrides"); + for (int k = 0; so != null && k < so.length(); k++) out.add(so.optJSONObject(k)); + } + return out; + } + + private static void confirm(final Activity a, final JSONObject p, final List ids, final boolean update, final boolean all, + final Choice ch, String intro, final Done done) { + StringBuilder msg = new StringBuilder(intro == null ? "" : intro + "\n\n"); + JSONArray steps = p.optJSONArray("steps"); + boolean untrusted = false; + int n = steps == null ? 0 : steps.length(); + for (int i = 0; i < n; i++) { + JSONObject s = steps.optJSONObject(i); + String act = s.optString("action"); + String line = "enable".equals(act) ? "Turn on " + s.optString("name") + : "update".equals(act) ? "Update " + s.optString("name") + " from " + s.optString("installed") + " to " + s.optString("version") + : "Install " + s.optString("name") + " " + s.optString("version"); + if (s.optBoolean("turn_on")) line += ", and turn it on"; + if (s.has("for")) line += " (needed by " + s.optString("for") + ")"; + if (s.optBoolean("any_car")) line += " (not listed for this head unit: your choice)"; + msg.append("• ").append(line).append('\n'); + if ("install".equals(act) && !s.optBoolean("trusted", true)) untrusted = true; + } + final List ov = overrides(p); + JSONArray probs = p.optJSONArray("problems"); + JSONArray skipped = p.optJSONArray("skipped"); + JSONArray notes = p.optJSONArray("notes"); + if (probs != null && probs.length() > 0) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < probs.length(); i++) b.append("• ").append(probs.optString(i)).append('\n'); + AlertDialog.Builder d = new AlertDialog.Builder(a).setTitle(update ? "Can't update it" : "Can't install it").setMessage(b.toString().trim()); + d.setPositiveButton("OK", null); + if (!ov.isEmpty()) anyway(a, d, ov, ids, update, all, ch, done); + d.show(); + return; + } + if (skipped != null && skipped.length() > 0) { + msg.append(n > 0 ? "\nNot updated now:\n" : "None of them can be updated now:\n"); + for (int i = 0; i < skipped.length(); i++) { + JSONObject s = skipped.optJSONObject(i); + msg.append("• ").append(s.optString("id")).append(": ").append(s.optString("why")).append('\n'); + } + } + if (n == 0) { + String t = msg.length() > 0 ? msg.toString().trim() + : notes != null && notes.length() > 0 ? notes.optString(0) : "Nothing to install: it's installed already."; + AlertDialog.Builder d = new AlertDialog.Builder(a).setMessage(t).setPositiveButton("OK", null); + if (!ov.isEmpty()) anyway(a, d, ov, ids, update, all, ch, done); + d.show(); + return; + } + for (int i = 0; notes != null && i < notes.length(); i++) msg.append('\n').append(notes.optString(i)).append('\n'); + msg.append("\nDownloaded over home Wi-Fi from each mod's GitHub release, checked against the catalogue's checksum and " + + "the author's signature, all before the first one is installed. Nothing changes on the head unit until you apply."); + if (untrusted) { + msg.append("\n\nYou chose to install mods by authors who aren't on HMG-API's trusted author list. A mod's code runs inside " + + "the head unit's apps."); + } + // what goes: the plan's own list (update all: the mods it kept), so a later check can't add any + final List go = new ArrayList(); + JSONArray w = p.optJSONArray("wanted"); + for (int i = 0; w != null && i < w.length(); i++) go.add(w.optString(i)); + if (go.isEmpty()) go.addAll(ids); + AlertDialog.Builder d = new AlertDialog.Builder(a) + .setTitle(n == 1 ? (update ? "Update this mod?" : "Install this mod?") : "These " + n + " steps?") + .setMessage(msg.toString().trim()) + .setNegativeButton("Cancel", null) + .setPositiveButton(update ? "Update" : "Install", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int which) { + run(a, go, update, ch, done); + } + }); + if (!ov.isEmpty()) anyway(a, d, ov, ids, update, all, ch, done); + d.show(); + } + + /** + * "Install anyway…": the owner picks, mod by mod, what to say yes to (each with its reason), after + * a warning that says what each kind of yes means. Then the plan again with those. + */ + private static void anyway(final Activity a, AlertDialog.Builder d, final List ov, final List ids, final boolean update, + final boolean all, final Choice ch, final Done done) { + d.setNeutralButton(update ? "Update anyway…" : "Install anyway…", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int which) { + final String[] items = new String[ov.size()]; + final boolean[] picked = new boolean[ov.size()]; + boolean car = false, author = false; + for (int i = 0; i < ov.size(); i++) { + JSONObject o = ov.get(i); + boolean isCar = "car".equals(o.optString("kind")); + car |= isCar; + author |= !isCar; + items[i] = o.optString("id") + ": " + (isCar ? "not listed for this head unit (" + o.optString("why") + ")" : o.optString("why")); + } + StringBuilder warn = new StringBuilder(); + if (car) warn.append("Not listed for this head unit: its author didn't list this car, so it may not work here. HMG-API keeps " + + "a backup of every file it changes, and removing the mod puts them back. "); + if (author) warn.append("An author who isn't on the trusted list: the catalogue isn't signed, so HMG-API can't tell this key " + + "is really the author's. A mod's code runs inside the head unit's apps: say yes only if you know and trust its author. "); + new AlertDialog.Builder(a).setTitle("Which ones, at your own risk?") + .setMultiChoiceItems(items, picked, new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface y, int i, boolean on) { + picked[i] = on; + } + }) + .setNegativeButton("Cancel", null) + .setPositiveButton("Next", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface y, int ww) { + Choice next = new Choice(); + next.anyCar.addAll(ch.anyCar); + next.anyAuthor.addAll(ch.anyAuthor); + boolean any = false; + for (int i = 0; i < ov.size(); i++) { + if (!picked[i]) continue; + any = true; + String id = ov.get(i).optString("id"); + if ("car".equals(ov.get(i).optString("kind"))) next.anyCar.add(id); + else next.anyAuthor.add(id); + } + if (any) plan(a, ids, update, all, next, done); + } + }).show(); + new AlertDialog.Builder(a).setTitle("At your own risk").setMessage(warn.toString().trim()) + .setPositiveButton("I understand", null).show(); + } + }); + } + + private static void run(final Activity a, final List ids, final boolean update, final Choice ch, final Done done) { + final AlertDialog wait = new AlertDialog.Builder(a) + .setMessage("Downloading and installing… (leave the head unit on)").setCancelable(false).show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + List c = new ArrayList(Arrays.asList("engine", update ? "update" : "catalog-install")); + c.addAll(ids); + ch.args(c); + return Hmgapid.call(1800000, c.toArray(new String[0])); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + if (e != null) { + done.lost("No answer from HMG-API in time (" + e.getMessage() + "). The download and install go on by themselves: " + + "back on the main screen, HMG-API waits for them, then shows what changed."); + } else if (r.code == PLAN_CHANGED) { + JSONObject q; + try { + q = json(r.output); + } catch (Exception x) { + done.failed(MainActivity.readable(r.output)); + return; + } + confirm(a, q, ids, update, false, ch, "The downloaded mod zips need more than the catalogue said, so nothing was " + + "installed yet. This is what it takes now:", done); + } else if (r.code != 0) { + done.failed(MainActivity.readable(r.output)); + } else { + done.installed(r.output); + } + } + }.start(a); + } + + /** "checked …" for a time the engine saved, when the unit's clock was plausible */ + static String checked(JSONObject d) { + long t = d.optLong("checked", 0); + if (t <= 0) return "Not checked yet."; + if (t < 1735689600000L) return "Checked since the head unit started."; // the clock before GPS time: 2015 + return "Checked " + new java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.US).format(new java.util.Date(t)) + "."; + } + + /** Home Wi-Fi for a while (the car in P), so a check can run now: hmgapid wifi now 15 */ + static void connect(final Activity a, final Runnable then) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + Hmgapid.Result r = Hmgapid.call("wifi", "now", "15"); + if (r.code != 0) return r; + for (int i = 0; i < 45; i++) { // up to 90 s to join + Thread.sleep(2000); + java.io.File f = new java.io.File("/data/hmgapi/public/wifi.json"); + try { + if ("up".equals(new JSONObject(UsbFolders.read(f)).optString("state"))) return r; + } catch (Exception ignored) { + // not written yet + } + } + r.code = 1; + r.output = "Home Wi-Fi didn't connect within 90 seconds. Is the car near your network, and is it saved in Settings → Home Wi-Fi?"; + return r; + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (e != null || r.code != 0) { + new AlertDialog.Builder(a).setTitle("Not connected").setMessage(e != null ? e.getMessage() : r.output.trim()) + .setPositiveButton("OK", null).show(); + return; + } + then.run(); + } + }.start(a); + } + + /** an install or update done (staged, not applied): what it did, and applying it now (the main screen's plan, then its OK) */ + static void applyNow(final MainActivity a, String title, String text) { + new AlertDialog.Builder(a).setTitle(title) + .setMessage(text + "\n\nNothing on the head unit changes until the changes are applied.") + .setNegativeButton("Later", null) + .setPositiveButton("Apply now", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + a.plan(); + } + }).show(); + } +} diff --git a/core/app/java/hmgapi/app/CatalogTab.java b/core/app/java/hmgapi/app/CatalogTab.java new file mode 100644 index 00000000..6b0653df --- /dev/null +++ b/core/app/java/hmgapi/app/CatalogTab.java @@ -0,0 +1,158 @@ +package hmgapi.app; + +import android.app.AlertDialog; +import android.graphics.Color; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.Arrays; + +/** + * Get mods: HMG-API's mod catalogue (engine catalog, kept from the last check; "Check now" + * fetches it again over home Wi-Fi). Each mod with what installing it would do here; Install + * takes the mods it requires too (CatalogFlow), then offers to apply. A tab of the main screen. + */ +final class CatalogTab { + final MainActivity a; + + CatalogTab(MainActivity a) { + this.a = a; + } + + private LinearLayout rows; + private TextView message, when; + private Button connect; + + View view() { + LinearLayout root = Ui.column(a); + root.setBackgroundColor(Ui.BG); + LinearLayout list = Ui.scrolling(root, 1, LinearLayout.LayoutParams.MATCH_PARENT); + list.setPadding(Ui.dp(a, 32), Ui.dp(a, 16), Ui.dp(a, 32), Ui.dp(a, 24)); + Ui.text(list, "Get mods", 30, true, Ui.GREEN); + Ui.text(list, "HMG-API's mod catalogue: mods the HMG-API project lists, each from its author's own GitHub release. " + + "Mods they need are installed with them. Checked and downloaded over home Wi-Fi only.", 16, false, Color.GRAY); + when = Ui.text(list, "", 15, false, Color.GRAY); + message = Ui.text(list, "", 18, false, Ui.WARN); + LinearLayout buttons = Ui.row(a); + Ui.button(buttons, "Check now", new View.OnClickListener() { + @Override + public void onClick(View v) { + load(true); + } + }); + connect = Ui.button(buttons, "Connect to home Wi-Fi (15 min)", new View.OnClickListener() { + @Override + public void onClick(View v) { + message.setText("Connecting to home Wi-Fi… (wireless CarPlay and Android Auto are off meanwhile)"); + CatalogFlow.connect(a, new Runnable() { + @Override + public void run() { + load(true); + } + }); + } + }); + connect.setVisibility(View.GONE); + list.addView(buttons); + rows = new LinearLayout(a); + rows.setOrientation(LinearLayout.VERTICAL); + list.addView(rows); + load(false); + return root; + } + + private void load(final boolean refresh) { + message.setText(refresh ? "Checking the catalogue…" : "Loading…"); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return refresh ? Hmgapid.call(180000, "engine", "catalog", "--refresh") : Hmgapid.call(60000, "engine", "catalog"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + rows.removeAllViews(); + JSONObject d; + try { + if (e != null) throw e; + d = CatalogFlow.json(r.output); + } catch (Exception x) { + message.setText(e != null ? Hmgapid.unreachable(e) : "Couldn't read the catalogue: " + x.getMessage()); + return; + } + boolean online = d.optBoolean("online"); + connect.setVisibility(online ? View.GONE : View.VISIBLE); + when.setText(CatalogFlow.checked(d)); + JSONArray mods = d.optJSONArray("mods"); + if (d.has("error")) message.setText("Not checked: " + d.optString("error")); + else if (mods == null || mods.length() == 0) message.setText(online ? "Tap Check now to get the catalogue." + : "Not checked yet. " + d.optString("offline", "") + ". Tap Connect to home Wi-Fi, in P, to check now."); + else message.setText(online ? "" : "Offline (" + d.optString("offline") + "): showing the last check."); + for (int i = 0; mods != null && i < mods.length(); i++) row(mods.optJSONObject(i), online); + } + }.start(a); + } + + private void row(final JSONObject m, boolean online) { + Ui.gap(rows, 14); + String st = m.optString("status"); + boolean unfit = m.has("unfit"), hmgapiUnfit = unfit && !m.optString("unfit").startsWith("car: "); + Ui.text(rows, m.optString("name", m.optString("id")) + " " + m.optString("version"), 22, true, hmgapiUnfit ? Color.GRAY : Color.WHITE); + String what; + if ("same".equals(st)) what = "Installed" + (m.optBoolean("enabled", true) ? "" : " (turned off)"); + else if ("update".equals(st)) what = "Update from " + m.optString("installed"); + else if ("older".equals(st)) what = "Installed " + m.optString("installed") + " (newer than the catalogue's)"; + else what = "Not installed"; + Ui.text(rows, what, 16, false, "update".equals(st) ? Ui.GREEN : Color.LTGRAY); + if (m.optString("description").length() > 0) Ui.text(rows, m.optString("description"), 15, false, Color.GRAY); + JSONArray au = m.optJSONArray("authors"); + StringBuilder by = new StringBuilder(); + for (int i = 0; au != null && i < au.length(); i++) by.append(i > 0 ? ", " : "").append(au.optString(i)); + if (by.length() > 0) Ui.text(rows, "By " + by + (m.optBoolean("trusted") ? "" : " · not on HMG-API's trusted author list" + + ("new".equals(st) ? ": installing it needs your yes" : "")), 15, false, + m.optBoolean("trusted") ? Color.GRAY : Ui.WARN); + JSONArray req = m.optJSONArray("requires"); + if (req != null && req.length() > 0) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < req.length(); i++) b.append(i > 0 ? ", " : "").append(req.optString(i)); + Ui.text(rows, "Needs " + b + " (installed with it if missing)", 15, false, Color.GRAY); + } + if (unfit) Ui.text(rows, hmgapiUnfit ? "Can't install: " + m.optString("unfit") : "Not listed for this head unit: " + m.optString("unfit").substring(5) + + (m.optBoolean("any_car") ? " (you chose to use it here)" : ""), + 15, false, hmgapiUnfit ? Ui.ERROR : Ui.WARN); + if (hmgapiUnfit || "older".equals(st) || ("same".equals(st) && m.optBoolean("enabled", true))) return; + final boolean update = "update".equals(st); + String label = update ? "Update" : "same".equals(st) ? "Turn on" : "Install"; + Button b = Ui.button(rows, label, new View.OnClickListener() { + @Override + public void onClick(View v) { + CatalogFlow.start(a, Arrays.asList(m.optString("id")), update, new CatalogFlow.Done() { + @Override + public void installed(String output) { + CatalogFlow.applyNow(a, "Installed", MainActivity.readable(output)); + load(false); + } + + @Override + public void failed(String output) { + new AlertDialog.Builder(a).setTitle("Not installed").setMessage(output) + .setPositiveButton("OK", null).show(); + load(false); + } + + @Override + void lost(String message) { + new AlertDialog.Builder(a).setTitle("Still installing").setMessage(message) + .setPositiveButton("OK", null).show(); + } + }); + } + }); + if (!online && !"same".equals(st)) b.setEnabled(false); + } +} diff --git a/core/app/java/hmgapi/app/LogsTab.java b/core/app/java/hmgapi/app/LogsTab.java index dfe28b08..4b1df750 100644 --- a/core/app/java/hmgapi/app/LogsTab.java +++ b/core/app/java/hmgapi/app/LogsTab.java @@ -35,7 +35,7 @@ View view() { @Override public void onClick(View v) { problem = true; - a.show(3); + a.show(MainActivity.LOGS); } }); Ui.button(bar, "Refresh", new View.OnClickListener() { diff --git a/core/app/java/hmgapi/app/MainActivity.java b/core/app/java/hmgapi/app/MainActivity.java index cc499f09..96c024ab 100644 --- a/core/app/java/hmgapi/app/MainActivity.java +++ b/core/app/java/hmgapi/app/MainActivity.java @@ -24,7 +24,8 @@ * by category), Car Report, Logs. */ public class MainActivity extends Activity { - static final String[] TABS = { "Mods", "Settings", "Car Report", "Logs" }; + static final String[] TABS = { "Installed mods", "Catalogue", "Updates", "Settings", "Car Report", "Logs" }; + static final int MODS = 0, CATALOGUE = 1, UPDATES_TAB = 2, SETTINGS = 3, REPORT = 4, LOGS = 5; private LinearLayout pills; private FrameLayout content; private final TextView[] tabs = new TextView[TABS.length]; @@ -90,7 +91,7 @@ public void onClick(View v) { final int n = i; LinearLayout t = Ui.column(this); tabs[i] = new TextView(this); - tabs[i].setText(TABS[i]); + tabs[i].setText(i == UPDATES_TAB ? updatesLabel() : TABS[i]); Ui.size(tabs[i], 21); tabs[i].setPadding(Ui.dp(this, 4), Ui.dp(this, 6), Ui.dp(this, 4), Ui.dp(this, 8)); t.addView(tabs[i]); @@ -166,11 +167,23 @@ void show(int n) { marks[i].setVisibility(i == n ? View.VISIBLE : View.INVISIBLE); } content.removeAllViews(); - View v = n == 0 ? new ModsTab(this).view() : n == 1 ? new SettingsTab(this).view() - : n == 2 ? new ReportTab(this).view() : new LogsTab(this).view(); + tabs[UPDATES_TAB].setText(updatesLabel()); + View v = n == MODS ? new ModsTab(this).view() : n == CATALOGUE ? new CatalogTab(this).view() + : n == UPDATES_TAB ? new UpdatesTab(this).view() : n == SETTINGS ? new SettingsTab(this).view() + : n == REPORT ? new ReportTab(this).view() : new LogsTab(this).view(); content.addView(v); } + /** "Updates (n)" when the last check found any (public/updates.json, written by the engine) */ + static String updatesLabel() { + try { + int n = new org.json.JSONObject(UsbFolders.read(new java.io.File("/data/hmgapi/public/updates.json"))).optInt("count"); + return n > 0 ? "Updates (" + n + ")" : "Updates"; + } catch (Exception e) { + return "Updates"; + } + } + /** "1.0.0 · Kia EV6 (usa 260507)" from the hook runtime's status */ static String subtitle() { try { @@ -239,6 +252,7 @@ void needRestart() { @Override protected void onActivityResult(int request, int result, Intent data) { + if (request == UPDATES && current == MODS) show(MODS); // the Mods tab again: new mods, versions, the updates count if (request == UPDATES && result == RESULT_OK) plan(); // mods were installed: apply them (plan first) } diff --git a/core/app/java/hmgapi/app/ModsTab.java b/core/app/java/hmgapi/app/ModsTab.java index 9baaa9f2..bca66626 100644 --- a/core/app/java/hmgapi/app/ModsTab.java +++ b/core/app/java/hmgapi/app/ModsTab.java @@ -26,9 +26,15 @@ final class ModsTab { LinearLayout list, detail; List mods = new ArrayList(); String chosen; + int updates; // public/updates.json's count (mods and HMG-API) static final class Mod { String id, name, version = "", description = "", authors = "", license = "", state, error; + String update; // a newer version in the catalogue or the mod's releases (public/updates.json), or null + String updateRepo; // the update is from this repo's releases (not the catalogue), or null + String source = "", repo, choice, withdrawn; // where its updates come from (catalogue, releases, off); a maintainer's withdrawal + boolean listed; + List requires = new ArrayList(); boolean enabled, hasCode; List services = new ArrayList(); @@ -80,6 +86,16 @@ List work() throws Exception { // hooks not running: states unknown } List out = new ArrayList(); + JSONObject up = null; + try { + up = new JSONObject(UsbFolders.read(new java.io.File("/data/hmgapi/public/updates.json"))); + } catch (Exception ignored) { + // no check yet + } + updates = up == null ? 0 : up.optInt("count"); + JSONArray ups = up == null ? null : up.optJSONArray("mods"); + JSONObject srcs = up == null ? null : up.optJSONObject("sources"); + JSONArray wds = up == null ? null : up.optJSONArray("withdrawn"); for (String line : Hmgapid.call("mods").output.split("\n")) { String[] w = line.split("\t"); if (w.length < 2) continue; @@ -96,6 +112,12 @@ List work() throws Exception { JSONArray au = j.optJSONArray("authors"); for (int i = 0; au != null && i < au.length(); i++) m.authors += (i > 0 ? ", " : "") + au.optString(i); m.hasCode = j.has("hooks"); + JSONArray rq = j.optJSONArray("requires"); + for (int i = 0; rq != null && i < rq.length(); i++) { + Object o = rq.get(i); + String rid = o instanceof JSONObject ? ((JSONObject) o).optString("id") : String.valueOf(o).trim().split(" ")[0]; + if (!(o instanceof JSONObject && ((JSONObject) o).optBoolean("optional"))) m.requires.add(rid); + } JSONArray sv = j.optJSONArray("services"); for (int i = 0; sv != null && i < sv.length(); i++) m.services.add(sv.getJSONObject(i).optString("name")); } catch (Exception e) { @@ -109,6 +131,23 @@ List work() throws Exception { if (m.state == null) m.state = s.optString("state"); if (m.error == null && s.has("error")) m.error = s.optString("error"); } + for (int i = 0; ups != null && i < ups.length(); i++) { + JSONObject u = ups.getJSONObject(i); + if (!m.id.equals(u.optString("id")) || !m.version.equals(u.optString("installed"))) continue; + m.update = u.optString("version"); + if ("release".equals(u.optString("source"))) m.updateRepo = u.optString("repo").replace("https://github.com/", ""); + } + JSONObject src = srcs == null ? null : srcs.optJSONObject(m.id); + if (src != null) { + m.source = src.optString("source"); + m.repo = src.has("repo") ? src.optString("repo") : null; + m.choice = src.has("choice") ? src.optString("choice") : null; + m.listed = src.optBoolean("listed"); + } + for (int i = 0; wds != null && i < wds.length(); i++) { + JSONObject wo = wds.getJSONObject(i); + if (m.id.equals(wo.optString("id")) && m.version.equals(wo.optString("version"))) m.withdrawn = wo.optString("why"); + } out.add(m); } return out; @@ -123,8 +162,8 @@ void done(List r, Exception e) { } mods = r; if (r.isEmpty()) { - Ui.text(list, " No mods installed. Put mod packages in HMGAPI/updates/ on a USB stick and use Check USB updates.", - 17, false, Ui.GREY); + Ui.text(list, " No mods installed. Get some in the Catalogue tab (over home Wi-Fi), or put mod zips in " + + "HMGAPI/updates/ on a USB stick and use Check USB updates.", 17, false, Ui.GREY); return; } if (chosen == null) chosen = r.get(0).id; @@ -143,7 +182,8 @@ void drawList() { row.addView(Ui.dot(a, m.color(), 18)); LinearLayout t = Ui.column(a); Ui.text(t, m.name, 19, false, Ui.TEXT).setPadding(0, 0, 0, 0); - TextView sub = Ui.text(t, m.version + " · " + m.label(), 15, false, m.color() == Ui.ACCENT || m.color() == Ui.OFF ? Ui.GREY : m.color()); + TextView sub = Ui.text(t, m.version + " · " + m.label() + (m.update != null ? " · update " + m.update : ""), 15, false, + m.color() == Ui.ACCENT || m.color() == Ui.OFF ? (m.update != null ? Ui.GREEN : Ui.GREY) : m.color()); sub.setPadding(0, 0, 0, 0); row.addView(t); row.setOnClickListener(new View.OnClickListener() { @@ -207,7 +247,7 @@ void done(Hmgapid.Result r, Exception e) { Ui.button(detail, "Make a Car Report", new View.OnClickListener() { @Override public void onClick(View v) { - a.show(2); + a.show(MainActivity.REPORT); } }); } @@ -215,6 +255,43 @@ public void onClick(View v) { Ui.pill(detail, m.label(), m.color()); } if (!m.description.isEmpty()) Ui.text(detail, m.description, 16, false, Ui.GREY); + if (m.withdrawn != null) { + TextView box = Ui.text(detail, "Withdrawn\nHMG-API's maintainers withdrew " + m.name + " " + m.version + ": " + m.withdrawn + + ". Update it, or turn it off until there's a fixed version.", 17, false, Ui.TEXT); + box.setBackground(Ui.box(a, 0xff3a3320, Ui.WARN, 10)); + int p = Ui.dp(a, 14); + box.setPadding(p, p, p, p); + } + if (m.update != null) { + Ui.text(detail, m.updateRepo != null ? "Version " + m.update + " is in " + m.updateRepo + "'s releases (signed by the same author; " + + "not reviewed for the catalogue)." : "Version " + m.update + " is in the catalogue.", 17, false, Ui.GREEN); + Ui.button(detail, "Update to " + m.update, true, new View.OnClickListener() { + @Override + public void onClick(View v) { + CatalogFlow.start(a, java.util.Arrays.asList(m.id), true, new CatalogFlow.Done() { + @Override + public void installed(String output) { + a.message("Updated " + m.name, MainActivity.readable(output)); + load(); + a.plan(); + } + + @Override + public void failed(String output) { + a.message("Not updated", output); + } + + @Override + void lost(String message) { + a.message("Still updating", message); + a.plan(); // waits for the engine, then shows what changed + } + }); + } + }); + } + if (!m.requires.isEmpty()) Ui.text(detail, "Needs " + join(m.requires.toArray(new String[0])).replace(" · ", ", "), 15, false, Ui.GREY); + if (m.listed || m.repo != null) updatesFrom(m); Ui.line(detail); Ui.text(detail, "Settings", 21, true, Ui.GREEN); @@ -265,6 +342,45 @@ public void onClick(View v) { }); } + /** where the mod's updates come from: the catalogue, its own GitHub releases, or nowhere (engine update-source) */ + void updatesFrom(final Mod m) { + Ui.line(detail); + Ui.text(detail, "Updates", 21, true, Ui.GREEN); + String repo = m.repo == null ? null : m.repo.replace("https://github.com/", ""); + Ui.text(detail, "catalogue".equals(m.source) ? "From HMG-API's catalogue." + (repo != null ? " Its own releases (" + repo + ") can be followed instead, " + + "for example to test a new version before it's listed." : "") + : "releases".equals(m.source) ? "From " + repo + "'s releases on GitHub" + (m.listed ? ", instead of the catalogue." : ": it isn't in " + + "the catalogue.") + " Only a release signed with the same author key as the installed version is offered." + : "Off: HMG-API doesn't check for updates of " + m.name + ".", 16, false, Ui.GREY); + LinearLayout row = Ui.row(a); + if (m.listed && !"catalogue".equals(m.source)) source(row, m, "From the catalogue", "catalogue"); + if (repo != null && !"releases".equals(m.source)) source(row, m, "From its releases", "releases"); + if (!"off".equals(m.source)) source(row, m, "Don't check", "off"); + if (m.choice != null) source(row, m, "Default", "default"); + detail.addView(row); + } + + private void source(LinearLayout row, final Mod m, String label, final String to) { + Ui.button(row, label, new View.OnClickListener() { + @Override + public void onClick(View v) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call("engine", "update-source", m.id, to); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (e != null || r.code != 0) a.message("Not changed", e != null ? e.getMessage() : MainActivity.readable(r.output)); + else android.widget.Toast.makeText(a, MainActivity.readable(r.output).trim(), android.widget.Toast.LENGTH_LONG).show(); + load(); + } + }.start(a); + } + }); + } + static String join(String... parts) { StringBuilder s = new StringBuilder(); for (String p : parts) if (p != null && !p.isEmpty()) s.append(s.length() > 0 ? " · " : "").append(p); @@ -281,9 +397,13 @@ static String tail(String s, int lines) { /** A mod off the head unit: its folder goes now; what it changed goes back to stock with the next apply. */ void confirmRemove(final Mod m) { + List need = new ArrayList(); + for (Mod o : mods) if (o.requires.contains(m.id)) need.add(o.name); new AlertDialog.Builder(a) .setTitle("Remove " + m.name + "?") - .setMessage("Everything it changed goes back to stock when you apply the changes. Its settings are kept " + .setMessage((need.isEmpty() ? "" : join(need.toArray(new String[0])).replace(" · ", ", ") + (need.size() == 1 ? " needs" : " need") + + " it: " + (need.size() == 1 ? "it" : "they") + " won't load until it's installed again.\n\n") + + "Everything it changed goes back to stock when you apply the changes. Its settings are kept " + "in case you install it again.") .setNegativeButton("Cancel", null) .setPositiveButton("Remove", new DialogInterface.OnClickListener() { diff --git a/core/app/java/hmgapi/app/ProblemPage.java b/core/app/java/hmgapi/app/ProblemPage.java index 482ad77f..5b7efaaa 100644 --- a/core/app/java/hmgapi/app/ProblemPage.java +++ b/core/app/java/hmgapi/app/ProblemPage.java @@ -41,7 +41,7 @@ View view() { @Override public void onClick(View v) { LogsTab.problem = false; - a.show(3); + a.show(MainActivity.LOGS); } }); Ui.text(list, "Record a problem", 28, true, Ui.TEXT); @@ -119,10 +119,10 @@ void done(String r, Exception e) { recording = false; result = r; error = e == null ? null : String.valueOf(e.getMessage()); - if (LogsTab.problem && a.current == 3) a.show(3); // redraw, if the page is still open + if (LogsTab.problem && a.current == MainActivity.LOGS) a.show(MainActivity.LOGS); // redraw, if the page is still open } }.start(a); - a.show(3); + a.show(MainActivity.LOGS); } void stop(final Button go) { diff --git a/core/app/java/hmgapi/app/SettingsTab.java b/core/app/java/hmgapi/app/SettingsTab.java index 773fff2a..41a183c9 100644 --- a/core/app/java/hmgapi/app/SettingsTab.java +++ b/core/app/java/hmgapi/app/SettingsTab.java @@ -2,7 +2,6 @@ import android.app.AlertDialog; import android.content.DialogInterface; -import android.content.Intent; import android.view.View; import android.widget.LinearLayout; import android.widget.Switch; @@ -16,12 +15,13 @@ /** * HMG-API's own settings, by category: Vehicle (the owner's switches for mods' - * commands), Updates, Phone projection (what mods set), Hook map (this car's map, - * checks, mapping it from its own files), About. The switches are kept by hmgapid + * commands), Home Wi-Fi, Phone projection (what mods set), Hook map (this car's map, + * checks, mapping it from its own files), About. Updates (the catalogue's, USB, the car's own + * over-the-air ones) are the Updates tab's. The switches are kept by hmgapid * (allow ). */ final class SettingsTab { - static final String[] CATS = { "Vehicle", "Updates", "Home Wi-Fi", "Phone projection", "Hook map", "About" }; + static final String[] CATS = { "Vehicle", "Home Wi-Fi", "Phone projection", "Hook map", "About" }; final MainActivity a; LinearLayout cats, page; static int current; // the category shown last, kept while the app runs @@ -46,6 +46,7 @@ View view() { } void show(int n) { + if (n < 0 || n >= CATS.length) n = 0; current = n; cats.removeAllViews(); for (int i = 0; i < CATS.length; i++) { @@ -62,11 +63,11 @@ public void onClick(View v) { } page.removeAllViews(); Ui.text(page, CATS[n], 28, true, Ui.TEXT); - if (n == 0) vehicle(); - else if (n == 1) updates(); - else if (n == 2) homeWifi(); - else if (n == 3) projection(); - else if (n == 4) hookMap(); + String c = CATS[n]; + if ("Vehicle".equals(c)) vehicle(); + else if ("Home Wi-Fi".equals(c)) homeWifi(); + else if ("Phone projection".equals(c)) projection(); + else if ("Hook map".equals(c)) hookMap(); else about(); } @@ -183,30 +184,6 @@ void homeWifi() { new HomeWifiPage(a, page).show(this); } - void updates() { - if (!hooksOn()) { - Ui.text(page, "HMG-API's hooks aren't running on this car (see Hook map), so it isn't blocking over-the-air updates: " - + "the car can download and install them. The car's own switch is what counts until the hooks run: Settings > " - + "General > Install Infotainment System Updates Automatically.", 16, true, Ui.TEXT); - } - owner("Over-the-air updates", "Off (the default): HMG-API blocks the car's own update downloads, so an update can't " - + "replace what HMG-API and your mods depend on. USB and dealer updates still work. Takes effect at the next restart.", - "Allow over-the-air updates", "ota_updates", false, new Runnable() { - @Override - public void run() { - a.needRestart(); - } - }); - Ui.text(page, "Updates from USB", 21, true, Ui.TEXT); - Ui.text(page, "HMG-API releases and mod packages (zips) in HMGAPI/updates/ on a USB stick.", 16, false, Ui.GREY); - Ui.button(page, "Check the USB stick", new View.OnClickListener() { - @Override - public void onClick(View v) { - a.startActivityForResult(new Intent(a, UpdatesActivity.class), MainActivity.UPDATES); - } - }); - } - void projection() { Ui.text(page, "What mods change in Android Auto and CarPlay (set in each mod's settings). Changes take effect the " + "next time the phone connects after a restart.", 16, false, Ui.GREY); diff --git a/core/app/java/hmgapi/app/UpdatesTab.java b/core/app/java/hmgapi/app/UpdatesTab.java new file mode 100644 index 00000000..4b18b468 --- /dev/null +++ b/core/app/java/hmgapi/app/UpdatesTab.java @@ -0,0 +1,355 @@ +package hmgapi.app; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.graphics.Color; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.Switch; +import android.widget.TextView; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Updates: installed mods with a newer version in the catalogue, and a newer HMG-API release + * (engine updates; HMG-API checks by itself when home Wi-Fi comes up, at most every 6 hours; + * "Check now" checks again). An update takes any new mods it requires (CatalogFlow); Update all + * plans each mod on its own, so one that can't go doesn't hold back the rest. HMG-API's own runs + * its installer, then the head unit restarts. Mod updates are applied from here (Apply now) or with + * Apply changes; ones the automatic check downloaded ("staged") wait aside until then. A tab of the + * main screen. + */ +final class UpdatesTab { + final MainActivity a; + + UpdatesTab(MainActivity a) { + this.a = a; + } + + private LinearLayout rows; + private TextView message, when; + private Button connect, all; + + View view() { + LinearLayout root = Ui.column(a); + root.setBackgroundColor(Ui.BG); + LinearLayout list = Ui.scrolling(root, 1, LinearLayout.LayoutParams.MATCH_PARENT); + list.setPadding(Ui.dp(a, 32), Ui.dp(a, 16), Ui.dp(a, 32), Ui.dp(a, 24)); + Ui.text(list, "Updates", 30, true, Ui.GREEN); + Ui.text(list, "Newer versions of your mods from HMG-API's catalogue (or, for a mod it doesn't list, from the mod's own releases " + + "on GitHub), and of HMG-API itself. HMG-API checks each time " + + "the head unit joins your home Wi-Fi (the car off at home), and never over the car's mobile data.", 16, false, Color.GRAY); + when = Ui.text(list, "", 15, false, Color.GRAY); + message = Ui.text(list, "", 18, false, Ui.WARN); + LinearLayout buttons = Ui.row(a); + Ui.button(buttons, "Check now", new View.OnClickListener() { + @Override + public void onClick(View v) { + load(true); + } + }); + connect = Ui.button(buttons, "Connect to home Wi-Fi (15 min)", new View.OnClickListener() { + @Override + public void onClick(View v) { + message.setText("Connecting to home Wi-Fi… (wireless CarPlay and Android Auto are off meanwhile)"); + CatalogFlow.connect(a, new Runnable() { + @Override + public void run() { + load(true); + } + }); + } + }); + connect.setVisibility(View.GONE); + all = Ui.button(buttons, "Update all mods", true, null); + all.setVisibility(View.GONE); + list.addView(buttons); + rows = new LinearLayout(a); + rows.setOrientation(LinearLayout.VERTICAL); + list.addView(rows); + + Ui.line(list); + Ui.text(list, "Automatic", 21, true, Ui.GREEN); + Switch check = Ui.switchRow(list, "Check for updates when home Wi-Fi connects"); + Ui.allowSwitch(a, check, "no_update_check", true, null); + Switch stage = Ui.switchRow(list, "Also download mod updates then: they wait until you apply"); + Ui.allowSwitch(a, stage, "auto_stage_updates", false, null); + Ui.text(list, "Only plain updates are downloaded by themselves: one that needs another mod installed or turned on waits for your " + + "Update. Nothing downloaded runs before you apply. HMG-API itself is only ever updated when you tap its Update.", 15, false, Color.GRAY); + + Ui.line(list); + Ui.text(list, "Updates from USB", 21, true, Ui.GREEN); + Ui.text(list, "HMG-API releases and mod zips in HMGAPI/updates/ on a USB stick: for a car with no home Wi-Fi, " + + "or a mod that isn't in the catalogue.", 15, false, Color.GRAY); + Ui.button(list, "Check the USB stick", new View.OnClickListener() { + @Override + public void onClick(View v) { + a.startActivityForResult(new android.content.Intent(a, UpdatesActivity.class), MainActivity.UPDATES); + } + }); + + Ui.line(list); + Ui.text(list, "The car's own updates", 21, true, Ui.GREEN); + if (!SettingsTab.hooksOn()) { + Ui.text(list, "HMG-API's hooks aren't running on this car (Settings > Hook map), so it isn't blocking over-the-air updates: " + + "the car can download and install them. The car's own switch is what counts until the hooks run: Settings > " + + "General > Install Infotainment System Updates Automatically.", 15, true, Ui.TEXT); + } + Ui.text(list, "Off (the default): HMG-API blocks the car's own over-the-air update downloads, so an update can't replace what " + + "HMG-API and your mods depend on. USB and dealer updates still work. Takes effect at the next restart.", 15, false, Color.GRAY); + Switch ota = Ui.switchRow(list, "Allow over-the-air updates"); + Ui.allowSwitch(a, ota, "ota_updates", false, new Runnable() { + @Override + public void run() { + a.needRestart(); + } + }); + load(false); + return root; + } + + private void load(final boolean refresh) { + message.setText(refresh ? "Checking for updates…" : "Loading…"); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return refresh ? Hmgapid.call(180000, "engine", "updates", "--refresh") : Hmgapid.call(60000, "engine", "updates"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + rows.removeAllViews(); + JSONObject d; + try { + if (e != null) throw e; + d = CatalogFlow.json(r.output); + } catch (Exception x) { + message.setText(e != null ? Hmgapid.unreachable(e) : "Couldn't read the updates: " + x.getMessage()); + return; + } + final boolean online = d.optBoolean("online"); + connect.setVisibility(online ? View.GONE : View.VISIBLE); + when.setText(CatalogFlow.checked(d)); + JSONArray mods = d.optJSONArray("mods"); + int n = d.optInt("count"); + if (d.has("error")) message.setText("Not checked: " + d.optString("error")); + else if (n == 0) message.setText(d.optLong("checked", 0) > 0 ? "Everything is up to date." : "Not checked yet: tap Check now" + + (online ? "." : " (home Wi-Fi isn't connected: Connect to home Wi-Fi, in P).")); + else message.setText(n + (n == 1 ? " update" : " updates") + " available" + (online ? "." : " (offline: connect to install).")); + JSONArray wd = d.optJSONArray("withdrawn"); + for (int i = 0; wd != null && i < wd.length(); i++) { + JSONObject w = wd.optJSONObject(i); + Ui.gap(rows, 14); + Ui.text(rows, "Withdrawn: " + w.optString("id") + " " + w.optString("version"), 20, true, Ui.WARN); + Ui.text(rows, "HMG-API's maintainers withdrew this version: " + w.optString("why") + ". Update it if there's a newer one " + + "below, or turn it off in Installed mods.", 15, false, Color.GRAY); + } + if (d.has("hmgapi")) hmgapiRow(d.optJSONObject("hmgapi"), online); + int count = 0; + for (int i = 0; mods != null && i < mods.length(); i++) { + row(mods.optJSONObject(i), online); + count++; + } + all.setVisibility(count > 1 ? View.VISIBLE : View.GONE); + all.setEnabled(online); + all.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + update(null); // each mod planned on its own (update --all) + } + }); + } + }.start(a); + } + + private void row(final JSONObject m, boolean online) { + Ui.gap(rows, 14); + Ui.text(rows, m.optString("name", m.optString("id")), 22, true, Color.WHITE); + Ui.text(rows, m.optString("installed") + " → " + m.optString("version") + (m.optBoolean("prerelease") ? " (pre-release)" : ""), + 16, false, Ui.GREEN); + if (m.optString("description").length() > 0) Ui.text(rows, m.optString("description"), 15, false, Color.GRAY); + if ("release".equals(m.optString("source"))) { + Ui.text(rows, "From " + m.optString("repo").replace("https://github.com/", "") + "'s releases on GitHub: signed by the same author as " + + "the installed version, but not reviewed for HMG-API's catalogue.", 15, false, Ui.WARN); + } + if (m.optBoolean("staged")) Ui.text(rows, "Downloaded by the automatic check: it goes in when you apply", 15, false, Ui.WARN); + JSONArray req = m.optJSONArray("requires"); + if (req != null && req.length() > 0) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < req.length(); i++) b.append(i > 0 ? ", " : "").append(req.optString(i)); + Ui.text(rows, "Needs " + b + " (installed or updated with it if needed)", 15, false, Color.GRAY); + } + LinearLayout buttons = Ui.row(a); + Button b = Ui.button(buttons, "Update", new View.OnClickListener() { + @Override + public void onClick(View v) { + update(Arrays.asList(m.optString("id"))); + } + }); + b.setEnabled(online); + if (m.optString("notes").length() > 0 || m.optString("page").length() > 0) { + Ui.button(buttons, "Release notes", new View.OnClickListener() { + @Override + public void onClick(View v) { + notes(m.optString("name", m.optString("id")), m); + } + }); + } + rows.addView(buttons); + } + + /** ids null: update all */ + private void update(List ids) { + CatalogFlow.Done done = new CatalogFlow.Done() { + @Override + public void installed(String output) { + CatalogFlow.applyNow(a, "Updated", MainActivity.readable(output)); + load(false); + } + + @Override + public void failed(String output) { + new AlertDialog.Builder(a).setTitle("Not updated").setMessage(output) + .setPositiveButton("OK", null).show(); + load(false); + } + + @Override + void lost(String message) { + new AlertDialog.Builder(a).setTitle("Still updating").setMessage(message) + .setPositiveButton("OK", null).show(); + } + }; + if (ids == null) CatalogFlow.startAll(a, done); + else CatalogFlow.start(a, ids, true, done); + } + + private void hmgapiRow(final JSONObject h, boolean online) { + Ui.gap(rows, 14); + Ui.text(rows, "HMG-API", 22, true, Color.WHITE); + Ui.text(rows, h.optString("installed") + " → " + h.optString("version") + (h.optBoolean("prerelease") ? " (pre-release)" : ""), + 16, false, Ui.GREEN); + if (h.optString("notes").length() > 0 || h.optString("page").length() > 0) { + Ui.button(rows, "Release notes", new View.OnClickListener() { + @Override + public void onClick(View v) { + notes("HMG-API", h); + } + }); + } + Button b = Ui.button(rows, "Update HMG-API", true, new View.OnClickListener() { + @Override + public void onClick(View v) { + new AlertDialog.Builder(a) + .setTitle("Update HMG-API to " + h.optString("version") + "?") + .setMessage("It's downloaded over home Wi-Fi and checked against its release's checksums and HMG-API's release " + + "key. Then HMG-API's installer runs (a minute; leave the head unit on) and the head unit needs a restart. " + + "Your mods and settings stay.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Update", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int w) { + updateHmgApi(false); + } + }).show(); + } + }); + b.setEnabled(online); + } + + /** the release's notes (the engine keeps them from GitHub: the head unit may have no browser), and its page */ + private void notes(String what, JSONObject h) { + final String page = h.optString("page"); + String text = h.optString("notes").length() > 0 ? h.optString("notes").replace("\r", "") : "No notes with this release."; + android.widget.ScrollView sv = new android.widget.ScrollView(a); + TextView t = new TextView(a); + t.setText(text + (page.length() > 0 ? "\n\n" + page : "")); + t.setTextIsSelectable(true); + Ui.size(t, 16); + int pad = Ui.dp(a, 16); + t.setPadding(pad, pad, pad, pad); + sv.addView(t); + AlertDialog.Builder d = new AlertDialog.Builder(a).setTitle(what + " " + h.optString("version")).setView(sv) + .setPositiveButton("OK", null); + final android.content.Intent open = new android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(page)); + if (page.startsWith("https://") && open.resolveActivity(a.getPackageManager()) != null) { + d.setNeutralButton("Open the page", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + try { + a.startActivity(open); + } catch (Exception ignored) { + // no browser after all: the link is in the text + } + } + }); + } + d.show(); + } + + /** force: the owner's "Update anyway" after mods that wouldn't take the new version were named */ + private void updateHmgApi(final boolean force) { + final AlertDialog wait = new AlertDialog.Builder(a) + .setMessage("Downloading and installing HMG-API… (leave the head unit on)").setCancelable(false).show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return force ? Hmgapid.call(900000, "engine", "update", "hmgapi", "--force") : Hmgapid.call(900000, "engine", "update", "hmgapi"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + if (e != null) { + message.setText("Lost contact while updating (" + e.getMessage() + "). The installer finishes on its own; restart the " + + "head unit once it's done."); + return; + } + AlertDialog.Builder d = new AlertDialog.Builder(a) + .setTitle(r.code == 0 ? "HMG-API updated" : "Not updated").setMessage(MainActivity.readable(r.output)); + if (r.code == 0) { + d.setNegativeButton("Later", null).setPositiveButton("Restart now", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call("reboot"); + } + + @Override + void done(Hmgapid.Result rr, Exception ee) {} + }.start(a); + } + }); + } else if (!force && r.output.contains("engine update hmgapi --force")) { // mods that wouldn't load with it: the owner decides + d.setNegativeButton("Cancel", null).setNeutralButton("Update anyway", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + new AlertDialog.Builder(a).setTitle("Update anyway?") + .setMessage("The mods named won't load with the new HMG-API, and applying changes stops until you update or " + + "turn them off.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Update anyway", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface y, int ww) { + updateHmgApi(true); + } + }).show(); + } + }); + } else { + d.setPositiveButton("OK", null); + } + d.show(); + message.setText(r.code == 0 ? "HMG-API updated: restart the head unit." : "Not updated."); + } + }.start(a); + } +}