feat: automatic settings/trip backup that survives uninstall, mic and camera tests

Dev build 0.4.1.24. Also includes previously uncommitted work in the tree.
This commit is contained in:
bonzi committed 2026-11-03 18:49:53 +00:00
1 parent 37a1189fe6
commit dcbd41d37b
35 files changed
+1752 -1115

No files matched your search

+4 -2
View File
@@ -1,7 +1,6 @@
# Generated Android build output
/build/
telemetry-service/data/
telemetry-service/data/*.sqlite*
# Local signing material
*.keystore
@@ -12,3 +11,6 @@ telemetry-service/data/*.sqlite*
.env
.env.*
!.env.example
# Private telemetry service source and runtime live outside this repository
telemetry-service/*
!telemetry-service/client-config.json
+9 -2
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cloud.molberg.mgutility" android:versionCode="3" android:versionName="0.3.0">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cloud.molberg.mgutility" android:sharedUserId="android.uid.system" android:versionCode="3" android:versionName="0.3.0">
<uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
<queries>
<intent>
@@ -24,6 +24,11 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
@@ -38,7 +43,7 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application android:allowBackup="false" android:label="MG Utility" android:icon="@drawable/ic_mg_utility" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" android:resizeableActivity="true" android:maxAspectRatio="3.0">
<application android:name=".MgApp" android:allowBackup="false" android:label="MG Utility" android:icon="@drawable/ic_launcher" android:roundIcon="@drawable/ic_launcher" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" android:resizeableActivity="true" android:maxAspectRatio="3.0">
<activity android:name=".MainActivity" android:launchMode="singleTask" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:resizeableActivity="true" android:maxAspectRatio="3.0">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -56,6 +61,8 @@
<activity android:name=".SoundboardActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".DebugActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".MicRouteDiagnosticActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".MicTestActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".CameraTestActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".SettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".HermesSettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
<activity android:name=".HermesVoiceActivity" android:taskAffinity="cloud.molberg.mgutility.hermes" android:excludeFromRecents="true" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
+40 -328
View File
@@ -1,297 +1,66 @@
# MG Utility
A configurable Android home-screen replacement and vehicle dashboard for SAIC-based MG cars.
MG Utility brings live vehicle information, media, trips, charging tools, shortcuts, and custom controls into one landscape-first interface that can be selected as the vehicle's Android **Home** app.
A landscape-first Android home-screen replacement and vehicle dashboard for Android-based MG/SAIC infotainment systems.
The app is designed to run across MG vehicles by detecting available services and falling back gracefully when an OEM capability is unavailable. Vehicle services, hardware, permissions, and firmware vary by model and trim. **The MG4 Luxury 2022 is the trim used for development and live validation.**
![MG Utility home screen](docs/mg-utility-home-screen.jpg)
> **Safety first:** MG Utility is not an MG/SAIC-approved product. Configure it only while parked, follow local law, and never use the screen or controls in a way that distracts from driving. Safety-critical systems remain excluded or read-only.
> **Safety:** MG Utility is not approved by MG/SAIC. Configure it only while parked. Vehicle-affecting actions are capability-gated, reversible where possible, and excluded from safety-critical systems.
![MG Utility home screen on an MG head unit](docs/mg-utility-home-screen.jpg)
## Features
*Example home screen captured on the development vehicle: 0 km/h, 346 km estimated range, 414.3 V battery voltage, 80% SOC, 8.0 kWh drive use, and media playback.*
## Table of contents
- [What it does](#what-it-does)
- [Feature list](#feature-list)
- [Home dashboard and launcher](#home-dashboard-and-launcher)
- [Vehicle data and energy](#vehicle-data-and-energy)
- [Trips and maps](#trips-and-maps)
- [Charging tools](#charging-tools)
- [Driver utilities](#driver-utilities)
- [Settings and backup](#settings-and-backup)
- [Capability-gated vehicle settings](#capability-gated-vehicle-settings)
- [Compatibility](#compatibility)
- [Safety boundaries](#safety-boundaries)
- [Install and first run](#install-and-first-run)
- [Build from source](#build-from-source)
- [Requirements](#requirements)
- [Build](#build)
- [Permissions and privacy](#permissions-and-privacy)
- [Read-only vehicle data provider](#read-only-vehicle-data-provider)
- [Development and testing](#development-and-testing)
- [Plugin SDK and marketplace](#plugin-sdk-and-marketplace)
- [Troubleshooting](#troubleshooting)
- [The dashboard shows connecting or unavailable vehicle values](#the-dashboard-shows-connecting-or-unavailable-vehicle-values)
- [Trip tracking does not start after reboot or sleep](#trip-tracking-does-not-start-after-reboot-or-sleep)
- [Routes have no map background](#routes-have-no-map-background)
- [The music panel is empty](#the-music-panel-is-empty)
- [The visualizer is silent](#the-visualizer-is-silent)
- [A vehicle setting is unavailable](#a-vehicle-setting-is-unavailable)
- [Repository layout](#repository-layout)
- [Status and limitations](#status-and-limitations)
## What it does
MG Utility is a local-first dashboard for Android-based MG infotainment systems. It can be used as a complete replacement for the Android home experience while leaving the OEM vehicle software in place underneath it.
The main screen combines:
- vehicle state and energy information when the SAIC vehicle service is available;
- media playback information and album art;
- a configurable app drawer and quick-control panel;
- shortcuts to trips, energy, charging, settings, and other utilities;
- live audio visualisation and custom themes.
The app does not require an internet connection for its core dashboard or local trip history. Network access is used for optional features such as OpenStreetMap tiles and electricity-price data.
## Feature list
### Home dashboard and launcher
- Landscape-first MG dashboard with speed, range, battery voltage, SOC, drive use, and charging status.
- Android `HOME` intent support: choose MG Utility as the default Home app when the head unit offers that option.
- Full-width music panel with notification-based media title, artist, album art, progress, and playback controls.
- Configurable themes, palettes, fonts, home-screen options, and visualizer settings.
- Automatic daily screen-brightness schedule with smooth fade-in/fade-out (see Settings → Appearance → Screen brightness).
- Swipe-up app drawer populated from the user's pinned applications.
- Swipe-down control panel with configurable quick controls, sliders, toggles, and shortcuts.
- Quick controls include automatic brightness, Liquid Sound Balance, adaptive audio leveling, the official SAIC launcher, Software Update, and Vehicle Settings. Hold a toggle to open its settings. Existing custom layouts are preserved; add controls from **Settings → Appearance → Configure control panel**, or restore defaults to show the expanded layout.
- Physical key remapping for supported foreground actions, with short, long, double, and repeat gestures.
### Vehicle data and energy
- Read-only integration with the SAIC vehicle service where the vehicle exposes it.
- Vehicle speed, estimated range, battery voltage, state of charge, energy counters, regenerated energy/range, and charging status.
- Energy dashboard with live values and connection status.
- Graceful connecting, unavailable, and fallback states on vehicles without the expected OEM service.
- Read-only content-provider sample for companion tools and diagnostics.
### Trips and maps
- Automatic background trip tracking after first-run setup.
- Drive distance, duration, top speed, SOC drop, reported energy use, estimated-range drop, sample counts, and GPS point counts.
- Regenerative-braking event detection from positive OEM counter deltas.
- Trip history with overview, per-drive details, raw samples, route display, recovery totals, and personal bests.
- Export selected or all drives as JSON, CSV, or styled HTML reports.
- Touch-pannable and pinch-zoomable OpenStreetMap route view with attribution.
- Named arrival areas with configurable radius and enabled state.
- Arrival briefings with drive statistics and optional charging price-window recommendations.
### Charging tools
- Charging automation built from editable `IF … THEN …` blocks.
- Conditions for SOC, electricity price, and time windows, including overnight windows.
- Live Strømligning price data for Danish DK1/DK2 when network access is available.
- Top-to-bottom evaluation with last matching rule winning.
- Parked-and-connected guards before charging commands are sent.
- Does not modify the OEM reservation schedule, target SOC, or current setting.
### Driver utilities
- 0–100 km/h tester using OEM vehicle speed when available, with GPS fallback.
- Local top-five acceleration leaderboard; records remain on the device.
- Soundboard for locked, booted, regeneration-best, and battery-threshold events.
- Speed-reactive audio with configurable clip, speed range, pitch, playback rate, volume, and playback mode.
- Adaptive audio leveling with three configurable speed/multiplier points; manual media-volume changes remain the reference level.
- Optional live music visualizer using the Android audio FFT callback.
- Spectrum Bars, Oscilloscope, Speed Gauge Ring, and Ferrofluid visualizer effects.
- Ferrofluid uses the Robert Leitl WebGL2 simulation as a transparent background layer;
Android playback FFT bass energy drives its audio response. Devices without WebGL2
automatically use the bundled GLES shader fallback.
- Configurable visualizer framerate, subject to the head unit's supported capture rate.
### Settings and backup
- Centralized configuration store for themes, palettes, fonts, launcher options, pinned apps, trips, charging, vehicle defaults, key mappings, audio, and map cache settings.
- Versioned, human-readable `mg-utility-settings.json` export/import through Android's document picker.
- Reset-to-defaults action.
- Automatic migration from legacy per-feature preference stores on upgrade.
- Separate JSON, CSV, and HTML drive-log exports.
### Capability-gated vehicle settings
- Vehicle settings catalog covering captured drive/energy, assistance, convenience, lighting, trim-dependent, and status rows.
- New installations default every row to **Do not change**.
- Validated writable profiles are enabled only when the matching capability is detected.
- Saved startup profiles apply once per ignition session only after positive ignition, Park, and stationary-speed checks.
- Every one-way write is followed by a getter read-back.
- Experimental parked regeneration level 5 action with acknowledgement, previous-value capture, verification, and restoration.
- **Vehicle dashboard** — speed, estimated range, battery voltage, state of charge, energy counters, charging status, and connection state.
- **Home replacement** — use MG Utility as the Android Home app with a configurable app drawer and quick-control panel.
- **Media** — now-playing metadata, album art, playback controls, progress, and notification-based media integration.
- **Trips and maps** — automatic trip tracking, drive history, route maps, statistics, regenerative-braking events, and JSON/CSV/HTML exports.
- **Charging tools** — editable `IF … THEN …` automation rules for SOC, price, and time windows, with Park and connection safeguards.
- **Audio and visualizers** — speed-reactive audio, adaptive audio leveling, soundboard events, FFT visualizers, and Ferrofluid effects.
- **Vehicle settings** — capability-detected settings with parked/stationary checks and getter read-back after writes.
- **Customization** — themes, palettes, fonts, brightness schedules, key remapping, pinned apps, and control-panel layouts.
- **Backup and plugins** — versioned settings export/import plus a scoped Java 8 plugin SDK and marketplace foundation.
- **Local-first storage** — settings, trip history, reports, and the acceleration leaderboard remain on the head unit unless explicitly exported or an optional network feature is used.
## Compatibility
MG Utility targets Android-based SAIC/MG head units and uses capability detection rather than assuming every vehicle exposes the same private OEM interfaces.
The **MG4 Luxury 2022** is the development and validation reference. Other MG/SAIC trims and firmware versions may expose different services and capabilities. The app detects unavailable OEM services and falls back to usable local features instead of assuming compatibility.
| Area | Expected behaviour |
|---|---|
| Dashboard UI, themes, settings, local history | Available on compatible Android head units running the app. |
| Android Home replacement | Available where the head unit permits a third-party app to be selected as the default Home app. |
| Media panel | Uses Android media/notification access; playback information depends on the media app and permissions. |
| Vehicle values | Requires the vehicle's SAIC service and compatible exposed data paths. Otherwise the UI reports connecting/unavailable states. |
| Automatic trips | Vehicle-only logging can work without GPS; route and location features require location permission, a usable fix, and suitable firmware. |
| Charging automation | Requires compatible charging data/commands, a connected vehicle, Park, and electricity-price network access for price conditions. |
| Maps | Requires internet access for tiles; route data can remain visible without map tiles. |
| Audio visualizer | Requires Android audio-recording permission and a supported output-visualizer/FFT path. |
| Vehicle settings | Only validated, capability-gated profiles are writable. Unknown firmware remains read-only. |
| Physical keys | Works only for keys Android exposes to the foreground application; OEM-consumed keys may not be observable. |
Minimum Android version: **API 28**. Live vehicle data requires the vehicle's exposed SAIC service. Maps and electricity-price conditions require network access; core dashboard and local history do not.
The **MG4 Luxury 2022** is the development and validation reference, not a promise that every MG trim exposes identical services or controls. Test on the specific vehicle before relying on any optional integration.
## Install
## Safety boundaries
MG Utility deliberately keeps the risky surface small:
- The dashboard and exported vehicle data provider are read-only.
- Vehicle writes are capability-gated and limited to validated profiles.
- Automatic vehicle-profile writes require confirmed ignition/run state, Park, and speed at or below 0.5 km/h.
- One-way vehicle setters require getter read-back before the app reports success.
- ADAS, ESP/traction, safety systems, and hardware-moving commands are excluded or read-only.
- Ambient lighting is excluded where the target hardware is absent.
- Regeneration level 5 is experimental, parked-only, acknowledgement-gated, never a preset, and never an unattended startup value.
- The app does not replace firmware, alter the OEM launcher permanently, or claim OEM approval.
- Configure the app and acknowledge prompts only while parked. Keep control of the vehicle at all times.
## Install and first run
1. Obtain a build of `MG-Utility.apk` from a trusted source or build it locally using the instructions below.
2. Install it on the Android head unit using the OEM-approved installation path.
3. Open MG Utility once after installation. Open it once again after an update if Android has force-stopped the package.
4. Grant only the permissions needed for the features you intend to use:
1. Obtain `MG-Utility.apk` from a trusted release or build it locally.
2. Install it on the Android head unit using the approved installation path.
3. Open MG Utility and grant only the permissions needed for the features you use:
- location for GPS routes and arrival areas;
- notification access for media information;
- audio recording for the live music visualizer;
- any Android settings or Bluetooth permissions requested by enabled controls.
5. If Android asks which Home app to use, select MG Utility and choose the default/always option if desired.
6. Configure themes, pinned apps, the app drawer, control panel, and optional automation from **Settings**.
7. If tracking does not resume after the car sleeps, enable the head unit's **Auto-start** permission and remove MG Utility from battery/task restrictions. Some OEM firmware force-stops third-party apps and suppresses their boot broadcasts.
- audio recording for the live visualizer.
4. Select MG Utility as the default Home app if desired.
5. Configure the dashboard, apps, controls, trips, charging, and optional integrations in **Settings**.
The app is designed to coexist with the OEM software. Selecting it as Home does not uninstall or replace the underlying MG/SAIC applications.
## Build
## Build from source
Requirements: Linux, a JDK, Android SDK build-tools 34 or newer, an Android platform SDK, and the local signing keystore.
### Requirements
- Linux development environment with a JDK and Android SDK.
- Android SDK build-tools 34 or newer and an Android platform SDK.
- A local signing keystore. The repository's development keystore is intentionally not part of public artifacts and is ignored by Git.
### Build
From the repository root:
```bash
```sh
./build.sh
```
Every ordinary build is a local Dev-channel build. It uses the stable base version
with a `.0` suffix unless a release script supplies an explicit version:
```bash
./build.sh
```
Dev releases use the Vault-backed wrapper, which supplies `GITEA_TOKEN` only
through the environment and verifies the downloaded release artifact:
```bash
./scripts/release-dev.sh # next Dev release, including verification
./scripts/release-dev.sh --dry-run # authenticated version calculation only
```
Never store the token in `.env`, source, command arguments, or logs. Stable
releases require explicit intent and use `scripts/release.sh --stable` with
credentials supplied securely through the environment.
Stable releases use `X.Y.Z`. Dev releases use `X.Y.Z.N`, where `N` increments
from the latest stable release. `--stable` increments the patch component and
publishes both `X.Y.Z` and its first `X.Y.Z.1` Dev build. Android `versionCode`
is assigned automatically above every existing release so channel switching
never attempts an Android downgrade. The publisher creates a Gitea Release with
the signed `MG-Utility.apk` and a machine-readable JSON release body containing
the channel, branch, versionCode, versionName, and SHA-256 checksum. Dev
releases are marked pre-release; Stable releases are normal releases.
When the Dev channel has no newer Dev build but a newer Stable release exists,
the app presents that stable artifact as the equivalent Dev version `X.Y.Z.0`.
The APK is byte-for-byte the Stable artifact; `.0` is only the Dev-channel
presentation used to make the transition explicit.
The app reads releases from
`https://git.molberg.cloud/api/v1/repos/alex/mg-utility` and only accepts HTTPS
APK assets from `git.molberg.cloud` whose package name, version code, checksum,
and signing certificate match the installed app. Keep `.env`, `GITEA_TOKEN`, and
all signing material out of the repository.
### In-app updates
Open **Settings → Config → Software updates**. The page displays the installed
version and its embedded channel/branch, lets the user choose **Dev** or
**Stable**, and provides an immediate check/download/install action. Downloads
are stored in app-private storage until verified. Android still displays its
required final package-install confirmation (and the one-time “install unknown
apps” permission on Android 8+).
**Notify on updates** is enabled by default. When enabled, MG Utility schedules
a network-aware check approximately every six hours and repairs the schedule
after boot or app replacement. A short, clickable notification opens the update
page; disabling the toggle cancels the scheduled check.
The update page also lists the current build, newer releases, and up to five
previous releases for the selected channel. Selecting an older release requires
confirmation with a warning that configuration or other app-data changes may
make features incompatible after downgrading.
The script compiles the Java sources and resources without Gradle, creates a signed APK, and writes:
The signed APK is written to:
```text
build/MG-Utility.apk
```
The manifest currently targets Android API 28 and declares a minimum Android API level of 28, matching the development MG4 head unit. The app may run on newer Android versions, but OEM behaviour and private vehicle APIs must still be validated per vehicle.
For the authenticated Dev release workflow:
Do not commit generated `build/` output, keystores, passwords, or other signing material.
## Permissions and privacy
MG Utility is local-first:
- Trip history, settings, key mappings, and the acceleration leaderboard are stored on the head unit.
- The app does not upload trip logs or leaderboard records.
- Settings and drive reports are exported only when the user explicitly chooses a destination through Android's document picker.
- OpenStreetMap tiles and Strømligning price data require network access and are optional.
- Review Android permission prompts and disable features whose permissions you do not want to grant.
- No credentials or private signing material belong in this repository.
## Read-only vehicle data provider
The exported provider exposes one typed, read-only vehicle sample for a companion process or diagnostic tool:
```bash
adb shell content call \
--uri content://cloud.molberg.mgutility.vehicle \
--method sample
```sh
./scripts/release-dev.sh
```
The returned bundle can contain state of charge, estimated range, vehicle speed, battery voltage, consumption since charge, regenerated energy/range since vehicle start, and charging status. The first call after process startup may report `status=connecting`; retry after the service binding completes.
The provider accepts shell, root, or same-app callers through the declared dump permission. It implements no write methods and sends no vehicle-control Binder transactions.
## Development and testing
The repository includes a compatibility wrapper around the shared `mg4_api28` Android emulator workflow:
The repository includes an API 28 emulator wrapper for UI and local-feature testing:
```bash
```sh
./emulator.sh start
./emulator.sh install
./emulator.sh launch
@@ -299,72 +68,15 @@ The repository includes a compatibility wrapper around the shared `mg4_api28` An
./emulator.sh stop
```
The shared emulator is API 28, landscape 1920×720, and is intended for UI, database, service-lifecycle, map, and synthetic-GPS testing. For synthetic GPS, for example:
The emulator does not include SAIC's proprietary vehicle service, so live vehicle integration must be validated on compatible hardware.
```bash
adb -s emulator-5554 emu geo fix 12.5683 55.6761
```
## Documentation
The emulator does **not** contain SAIC's proprietary `com.saicmotor.service.vehicle.VehicleService`, so live vehicle values remain unavailable there. Vehicle-service integration must be validated on compatible hardware.
- [Plugin SDK](docs/PLUGIN_SDK.md)
- [Settings navigation](docs/settings-navigation.md)
- [Vehicle settings reference](docs/STARTUP_VEHICLE_SETTINGS.md)
- [Third-party notices](THIRD_PARTY_NOTICES.md)
## Troubleshooting
## Limitations
### The dashboard shows connecting or unavailable vehicle values
Confirm that the target vehicle exposes the expected SAIC service and that the app is running on the intended head unit. This is a compatibility signal, not proof that the app is broken. The UI and local features remain usable without live OEM values.
### Trip tracking does not start after reboot or sleep
Open MG Utility once after installation/update, grant the requested setup permissions, then check Auto-start and battery/task restrictions in the OEM settings. The ongoing `MG Utility trip tracking` notification is the definitive indication that the tracker is running.
### Routes have no map background
The route line can be displayed without tiles. Check internet access and allow the OpenStreetMap tile request if a background map is required. OSM attribution is displayed in the map view.
### The music panel is empty
Enable the requested notification/media access and check that a supported media application is currently playing. Some OEM media implementations do not expose complete metadata.
### The visualizer is silent
Enable audio-recording permission and confirm that the selected visualizer effect is supported by the head unit. The visualizer uses real audio FFT callbacks and intentionally becomes silent when no output is available.
### A vehicle setting is unavailable
Unknown or unsupported profiles remain read-only by design. Do not force a setting or bypass the capability gate. Verify the vehicle trim, firmware, Park state, and stationary state first.
## Repository layout
```text
.
├── AndroidManifest.xml # Package, permissions, Home intent, services, provider
├── build.sh # Gradle-free signed APK build and verification
├── emulator.sh # Compatibility wrapper for the API 28 emulator workflow
├── docs/ # Supporting project documentation and screenshots
├── res/ # Android resources and drawable assets
├── src/ # Java application sources
├── tests/ # Test and validation material
└── README.md # This document
```
## Plugin SDK and marketplace
MG Utility now includes a Java 8 plugin SDK and a built-in marketplace foundation. Plugins are
separate APKs declaring `assets/mg-plugin.json`, implementing the SDK `Plugin` lifecycle, and
contributing dashboard tiles, settings pages, key actions, or background work through scoped host
registries. Plugin preferences are isolated by plugin ID and repository APKs must be HTTPS downloads
with a matching SHA-256 checksum before installation.
Open **Settings → Config → Plugin marketplace** to add repository index URLs. A reserved official
repository entry is shown as “coming soon”; the remote official repository itself has not been
created. Existing speed-reactive audio, soundboard, and key-remapping features remain built into
the app for now. Their extraction into plugins will happen after the host contracts are validated.
See [docs/PLUGIN_SDK.md](docs/PLUGIN_SDK.md) for the manifest format, lifecycle guidance, capability
allow-list, repository schema, and a minimal plugin example.
## Status and limitations
MG Utility is a vehicle-specific Android integration project intended to be adaptable across SAIC-based MG cars. Its generic UI, local storage, launcher behaviour, and fallback paths are designed for broad use; live vehicle data and vehicle settings depend on private OEM services and the specific MG trim/firmware.
Before distributing a build publicly, test it on the target vehicle, review the requested permissions, confirm the Home-app behaviour, and validate that all vehicle-affecting actions remain parked-only and capability-gated. The development reference remains the MG4 Luxury 2022.
MG Utility leaves the OEM software and firmware in place. Unknown vehicle capabilities remain read-only. Test every optional integration on the target vehicle before relying on it, and never operate the app in a way that distracts from driving.
+11 -3
View File
@@ -13,7 +13,11 @@ TOOLS=$(find "$SDK/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail
ANDROID_JAR=$(find "$SDK/platforms" -mindepth 2 -maxdepth 2 -name android.jar -type f | sort -V | tail -n 1)
OUT="$ROOT/build"
APK="$OUT/MG-Utility.apk"
KEYSTORE="$ROOT/mg-utility.keystore"
# Signed with the head unit's platform key (public AOSP test key, which the MG4
# ships with). Together with android:sharedUserId="android.uid.system" this is
# what grants access to /dev/video*. Same approach as Tommasov/MG4_Dashcam.
PLATFORM_KEY=${PLATFORM_KEY:-"$ROOT/signing/platform.pk8"}
PLATFORM_CERT=${PLATFORM_CERT:-"$ROOT/signing/platform.x509.pem"}
BASE_VERSION=$(sed -n 's/.*android:versionName="\([^"]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1)
BASE_CODE=$(sed -n 's/.*android:versionCode="\([0-9]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1)
BRANCH=${UPDATE_BRANCH:-$(git -C "$ROOT" branch --show-current 2>/dev/null || true)}
@@ -32,6 +36,10 @@ case "$BUILD_VERSION_CODE" in
esac
[ "$BUILD_VERSION_CODE" -le 2147483647 ] || { echo "versionCode must fit Android's signed 32-bit limit" >&2; exit 2; }
if [ ! -f "$PLATFORM_KEY" ] || [ ! -f "$PLATFORM_CERT" ]; then
echo "Platform signing key missing: $PLATFORM_KEY / $PLATFORM_CERT" >&2
exit 1
fi
if [ -z "$TOOLS" ] || [ -z "$ANDROID_JAR" ]; then
echo "Android SDK build-tools and a platform are required (set ANDROID_HOME)." >&2
exit 1
@@ -68,8 +76,8 @@ cp "$OUT/resources.apk" "$OUT/MG-Utility-unsigned.apk"
"$TOOLS/zipalign" -f 4 "$OUT/MG-Utility-unsigned.apk" "$APK"
rm -f "$APK.idsig"
"$TOOLS/apksigner" sign \
--ks "$KEYSTORE" --ks-pass pass:android --ks-key-alias androiddebugkey --key-pass pass:android \
--key "$PLATFORM_KEY" --cert "$PLATFORM_CERT" \
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
--v4-signing-enabled false --min-sdk-version 23 "$APK"
"$TOOLS/apksigner" verify -v --min-sdk-version 23 "$APK"
"$TOOLS/apksigner" verify -v --print-certs --min-sdk-version 23 "$APK"
echo "Built $APK"
-1
View File
@@ -88,7 +88,6 @@ System
Run setup wizard → SetupWizardActivity (review mode)
Diagnostics
Debug console → DebugActivity
Upload diagnostics → consent dialog; upload only after confirmation
Keys and launcher
Key remapping → KeyRemappingActivity
Official SAIC launcher → OEM home activity; generic home intent fallback
+4
View File
@@ -0,0 +1,4 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
+5
View File
@@ -0,0 +1,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
+15
View File
@@ -0,0 +1,15 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<size android:width="64dp" android:height="64dp" />
<gradient android:angle="315"
android:startColor="#203443"
android:centerColor="#111E2B"
android:endColor="#080E17" />
<corners android:radius="16dp" />
</shape>
</item>
<item android:drawable="@drawable/ic_mg_utility"
android:left="6dp" android:top="6dp"
android:right="6dp" android:bottom="6dp" />
</layer-list>
+7
View File
@@ -0,0 +1,7 @@
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:angle="315"
android:startColor="#203443"
android:centerColor="#111E2B"
android:endColor="#080E17" />
</shape>
+3
View File
@@ -0,0 +1,3 @@
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ic_mg_utility"
android:inset="20.37037%" />
+30 -7
View File
@@ -1,9 +1,32 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="48dp"
android:viewportWidth="48"
android:viewportHeight="48">
<path android:fillColor="#10252B" android:pathData="M4,6C4,3.8 5.8,2 8,2H40C42.2,2 44,3.8 44,6V42C44,44.2 42.2,46 40,46H8C5.8,46 4,44.2 4,42Z"/>
<path android:fillColor="#00D8A5" android:pathData="M15,12H33C34.1,12 35,12.9 35,14V34C35,35.1 34.1,36 33,36H15C13.9,36 13,35.1 13,34V14C13,12.9 13.9,12 15,12M35,19H39V29H35Z"/>
<path android:fillColor="#10252B" android:pathData="M26,15L18,26H24L22,33L30,22H24Z"/>
xmlns:aapt="http://schemas.android.com/aapt"
android:width="64dp"
android:height="64dp"
android:viewportWidth="64"
android:viewportHeight="64">
<path
android:fillColor="#00000000"
android:strokeWidth="4.5"
android:strokeLineCap="round"
android:pathData="M14.32,49.68A25,25 0,1 1,49.68 49.68">
<aapt:attr name="android:strokeColor">
<gradient android:type="linear"
android:startX="10" android:startY="10"
android:endX="53" android:endY="51">
<item android:offset="0" android:color="#46CFFF" />
<item android:offset="0.5" android:color="#00D4D6" />
<item android:offset="1" android:color="#48EDB5" />
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M36.9,15.5C37.6,14.7 38.8,15.4 38.5,16.4L35.1,28H43.4C44.5,28 45,29.2 44.3,30L27.1,49.5C26.4,50.3 25.2,49.6 25.5,48.6L28.9,37H20.6C19.5,37 19,35.8 19.7,35Z">
<aapt:attr name="android:fillColor">
<gradient android:type="linear"
android:startX="27" android:startY="16"
android:endX="37" android:endY="50"
android:startColor="#FFFFFF"
android:endColor="#CDE8F2" />
</aapt:attr>
</path>
</vector>
+3
View File
@@ -0,0 +1,3 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:fillColor="#FFFFFFFF" android:pathData="M17 10.5V7c0-0.55-0.45-1-1-1H4c-0.55 0-1 0.45-1 1v10c0 0.55 0.45 1 1 1h12c0.55 0 1-0.45 1-1v-3.5l4 4v-11l-4 4z" />
</vector>
@@ -0,0 +1,34 @@
package cloud.molberg.mgutility;
/** Pure microphone-level math shared by the mic test screen and its unit test. */
final class AudioLevel {
static final double SILENT_PEAK = 0.002;
static final double QUIET_PEAK = 0.02;
private AudioLevel() { }
/** Root-mean-square of 16-bit PCM, normalised to 0..1. */
static double rms(short[] pcm, int count) {
if (count <= 0) return 0;
double sum = 0;
for (int i = 0; i < count; i++) sum += (double) pcm[i] * pcm[i];
return Math.sqrt(sum / count) / 32768.0;
}
/** Largest absolute sample, normalised to 0..1. */
static double peak(short[] pcm, int count) {
int peak = 0;
for (int i = 0; i < count; i++) peak = Math.max(peak, Math.abs((int) pcm[i]));
return peak / 32768.0;
}
static double dbfs(double linear) {
return linear <= 0.00001 ? -100.0 : 20.0 * Math.log10(linear);
}
static String verdict(double peak) {
if (peak < SILENT_PEAK) return "SILENT - no signal reaching the app";
if (peak < QUIET_PEAK) return "VERY QUIET - signal present but faint";
return "OK - microphone signal detected";
}
}
@@ -0,0 +1,143 @@
package cloud.molberg.mgutility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Pure (Android-free) codec for the automatic settings backup. Every SharedPreferences
* file is stored with typed values so a restore reproduces Boolean/Int/Long/Float/String/
* StringSet entries exactly.
*/
final class BackupCodec {
static final int SCHEMA = 1;
static final String TYPE = "mg-utility-settings-backup";
private BackupCodec() { }
/** files: prefsFileName -> (key -> value). */
static String encode(Map<String, ? extends Map<String, ?>> files, long createdAt, String appVersion)
throws JSONException {
JSONObject root = new JSONObject();
root.put("schema", SCHEMA);
root.put("type", TYPE);
root.put("created_at", createdAt);
root.put("app_version", appVersion == null ? "" : appVersion);
root.put("fingerprint", fingerprint(files));
JSONObject out = new JSONObject();
for (Map.Entry<String, ? extends Map<String, ?>> file : new TreeMap<String, Map<String, ?>>(files).entrySet()) {
JSONObject entries = new JSONObject();
for (Map.Entry<String, ?> e : file.getValue().entrySet()) {
JSONObject typed = typed(e.getValue());
if (typed != null) entries.put(e.getKey(), typed);
}
out.put(file.getKey(), entries);
}
root.put("files", out);
return root.toString(1);
}
static Map<String, Map<String, Object>> decode(String json) throws JSONException {
JSONObject root = new JSONObject(json);
if (root.optInt("schema", -1) != SCHEMA || !TYPE.equals(root.optString("type")))
throw new IllegalArgumentException("Not an MG Utility settings backup");
JSONObject files = root.getJSONObject("files");
Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();
Iterator<String> names = files.keys();
while (names.hasNext()) {
String name = names.next();
JSONObject entries = files.getJSONObject(name);
Map<String, Object> values = new LinkedHashMap<String, Object>();
Iterator<String> keys = entries.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject typed = entries.getJSONObject(key);
Object value = untyped(typed);
if (value != null) values.put(key, value);
}
result.put(name, values);
}
return result;
}
static long createdAt(String json) {
try { return new JSONObject(json).optLong("created_at", 0L); } catch (Exception e) { return 0L; }
}
static int countKeys(Map<String, ? extends Map<String, ?>> files) {
int count = 0;
for (Map<String, ?> values : files.values()) count += values.size();
return count;
}
/** Order-independent SHA-256 over file names, keys, types and values. */
static String fingerprint(Map<String, ? extends Map<String, ?>> files) {
StringBuilder canonical = new StringBuilder();
for (Map.Entry<String, ? extends Map<String, ?>> file : new TreeMap<String, Map<String, ?>>(files).entrySet()) {
canonical.append('[').append(file.getKey()).append("]\n");
for (Map.Entry<String, ?> e : new TreeMap<String, Object>(file.getValue()).entrySet()) {
JSONObject typed = typed(e.getValue());
if (typed == null) continue;
canonical.append(e.getKey()).append('=').append(typed.optString("t")).append(':')
.append(typed.opt("v") instanceof JSONArray ? canonicalArray((JSONArray) typed.opt("v"))
: String.valueOf(typed.opt("v"))).append('\n');
}
}
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes("UTF-8"));
StringBuilder hex = new StringBuilder();
for (byte b : digest) hex.append(String.format("%02x", b & 0xff));
return hex.toString();
} catch (Exception e) {
return Integer.toHexString(canonical.toString().hashCode());
}
}
private static String canonicalArray(JSONArray array) {
TreeSet<String> sorted = new TreeSet<String>();
for (int i = 0; i < array.length(); i++) sorted.add(array.optString(i));
return sorted.toString();
}
private static JSONObject typed(Object value) {
try {
JSONObject o = new JSONObject();
if (value instanceof Boolean) { o.put("t", "b"); o.put("v", ((Boolean) value).booleanValue()); }
else if (value instanceof Integer) { o.put("t", "i"); o.put("v", ((Integer) value).intValue()); }
else if (value instanceof Long) { o.put("t", "l"); o.put("v", ((Long) value).longValue()); }
else if (value instanceof Float) { o.put("t", "f"); o.put("v", Float.toString(((Float) value).floatValue())); }
else if (value instanceof String) { o.put("t", "s"); o.put("v", (String) value); }
else if (value instanceof Set) {
JSONArray array = new JSONArray();
for (Object item : new TreeSet<Object>((Set<?>) value)) array.put(String.valueOf(item));
o.put("t", "ss"); o.put("v", array);
} else return null;
return o;
} catch (JSONException e) { return null; }
}
private static Object untyped(JSONObject typed) throws JSONException {
String t = typed.getString("t");
if ("b".equals(t)) return Boolean.valueOf(typed.getBoolean("v"));
if ("i".equals(t)) return Integer.valueOf(typed.getInt("v"));
if ("l".equals(t)) return Long.valueOf(typed.getLong("v"));
if ("f".equals(t)) return Float.valueOf(Float.parseFloat(typed.getString("v")));
if ("s".equals(t)) return typed.getString("v");
if ("ss".equals(t)) {
JSONArray array = typed.getJSONArray("v");
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) items.add(array.getString(i));
return new TreeSet<String>(items);
}
return null;
}
}
@@ -0,0 +1,438 @@
package cloud.molberg.mgutility;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Automatic settings + trip-report backup to shared storage (/sdcard/MG-Utility/backup).
* Files there are not owned by the app, so they survive uninstall/reinstall on Android 9.
*
* Safety rule: a backup is never written by an install until that install has either
* restored from the backup or confirmed that none exists. That stops a fresh, empty
* install from overwriting the good backup before it had a chance to be restored.
*/
final class BackupManager {
private static final String TAG = "MGBackup";
static final String DIR_NAME = "MG-Utility/backup";
static final String SETTINGS_FILE = "settings.json";
static final String TRIPS_FILE = "mg_trips.db";
private static final String TRIPS_PREV = "mg_trips.db.prev";
private static final String STATE = "mg_backup_state";
private static final String K_READY = "ready";
private static final String K_LAST_OK = "last_ok";
private static final String K_LAST_MSG = "last_msg";
private static final String K_FP = "settings_fp";
private static final String K_DB_SIG = "db_sig";
private static final String K_SNAP_AT = "snapshot_at";
private static final String K_PREV_AT = "db_prev_at";
private static final long PERIOD_MIN = 15;
private static final long SNAPSHOT_GAP_MS = 60L * 60L * 1000L;
private static final long DB_PREV_GAP_MS = 24L * 60L * 60L * 1000L;
private static final int MAX_SNAPSHOTS = 10;
private static final Set<String> EXCLUDED = new HashSet<String>(Arrays.asList(
STATE, "hermes_agent", "remote_diagnostics", "WebViewChromiumPrefs"));
private static final Object LOCK = new Object();
private static ScheduledExecutorService executor;
private BackupManager() { }
/** Called once from Application.onCreate. Restores synchronously, then schedules backups. */
static void start(Context context) {
final Context app = context.getApplicationContext();
try { restoreIfFresh(app); } catch (Throwable error) { Log.w(TAG, "startup restore failed", error); }
synchronized (LOCK) {
if (executor != null) return;
executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override public Thread newThread(Runnable r) {
Thread t = new Thread(r, "mg-backup"); t.setDaemon(true); return t;
}
});
executor.scheduleWithFixedDelay(new Runnable() {
@Override public void run() { backupNow(app); }
}, 1, PERIOD_MIN, TimeUnit.MINUTES);
}
}
/** Debounced-by-fingerprint background backup request. */
static void requestBackup(final Context context) {
final Context app = context.getApplicationContext();
ScheduledExecutorService ex;
synchronized (LOCK) { ex = executor; }
if (ex == null) return;
ex.execute(new Runnable() { @Override public void run() { backupNow(app); } });
}
static boolean hasStorageAccess(Context context) {
if (Build.VERSION.SDK_INT >= 23 && context.checkSelfPermission(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) return false;
File dir = backupDir();
if (dir == null) return false;
return dir.isDirectory() ? dir.canWrite() : dir.mkdirs() || dir.isDirectory();
}
static File backupDir() {
try {
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return null;
return new File(Environment.getExternalStorageDirectory(), DIR_NAME);
} catch (Throwable t) { return null; }
}
/** True when a restorable settings backup exists on disk. */
static boolean hasBackup() {
File dir = backupDir();
return dir != null && new File(dir, SETTINGS_FILE).isFile();
}
static String status(Context context) {
SharedPreferences s = state(context);
File dir = backupDir();
String where = dir == null ? "storage unavailable" : dir.getAbsolutePath();
long ok = s.getLong(K_LAST_OK, 0L);
String when = ok == 0L ? "no backup yet" : "last " + new SimpleDateFormat("d MMM HH:mm", Locale.US).format(new Date(ok));
return when + " • " + where;
}
static String lastMessage(Context context) { return state(context).getString(K_LAST_MSG, ""); }
// ---- backup ----------------------------------------------------------------------
/** Returns a short human-readable result; never throws. */
static String backupNow(Context context) {
synchronized (LOCK) {
Context app = context.getApplicationContext();
SharedPreferences state = state(app);
try {
if (!hasStorageAccess(app)) return remember(state, "Waiting for storage permission", false);
if (!state.getBoolean(K_READY, false)) {
if (hasBackup()) {
// A backup exists that this install has not restored yet: do it now, never overwrite.
String r = restoreSettingsAndTrips(app);
state.edit().putBoolean(K_READY, true).commit();
return remember(state, r, true);
}
state.edit().putBoolean(K_READY, true).commit();
}
File dir = backupDir();
StringBuilder msg = new StringBuilder();
msg.append(backupSettings(app, dir, state));
msg.append("; ").append(backupTrips(app, dir, state));
return remember(state, msg.toString(), true);
} catch (Throwable error) {
Log.w(TAG, "backup failed", error);
return remember(state, "Backup failed: " + error.getClass().getSimpleName() + " " + error.getMessage(), false);
}
}
}
private static String backupSettings(Context app, File dir, SharedPreferences state) throws Exception {
Map<String, Map<String, ?>> files = snapshotPrefs(app);
String fp = BackupCodec.fingerprint(files);
File current = new File(dir, SETTINGS_FILE);
if (fp.equals(state.getString(K_FP, "")) && current.isFile()) return "settings unchanged";
long now = System.currentTimeMillis();
String json = BackupCodec.encode(files, now, UpdateManager.installedVersion(app));
writeAtomically(current, json.getBytes("UTF-8"));
if (now - state.getLong(K_SNAP_AT, 0L) >= SNAPSHOT_GAP_MS) {
String stamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(new Date(now));
writeAtomically(new File(dir, "settings-" + stamp + ".json"), json.getBytes("UTF-8"));
pruneSnapshots(dir);
state.edit().putLong(K_SNAP_AT, now).apply();
}
state.edit().putString(K_FP, fp).apply();
return "settings saved (" + BackupCodec.countKeys(files) + " keys)";
}
private static void pruneSnapshots(File dir) {
File[] all = dir.listFiles();
if (all == null) return;
List<String> names = new ArrayList<String>();
for (File f : all) if (f.getName().startsWith("settings-") && f.getName().endsWith(".json")) names.add(f.getName());
Collections.sort(names);
for (int i = 0; i < names.size() - MAX_SNAPSHOTS; i++) new File(dir, names.get(i)).delete();
}
private static String backupTrips(Context app, File dir, SharedPreferences state) throws Exception {
File db = app.getDatabasePath("mg_trips.db");
if (!db.isFile()) return "no trips yet";
SQLiteDatabase source = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
File temp = new File(app.getCacheDir(), "trips-backup.tmp");
try {
String sig = signature(source);
File target = new File(dir, TRIPS_FILE);
if (sig.equals(state.getString(K_DB_SIG, "")) && target.isFile()) return "trips unchanged";
if (sig.startsWith("0|")) return "no trips yet"; // never replace a backup with an empty database
deleteDbFiles(temp);
snapshotDatabase(source, temp);
long now = System.currentTimeMillis();
File prev = new File(dir, TRIPS_PREV);
if (target.isFile() && now - state.getLong(K_PREV_AT, 0L) >= DB_PREV_GAP_MS) {
copyFile(target, new File(dir, TRIPS_PREV + ".tmp"));
prev.delete();
new File(dir, TRIPS_PREV + ".tmp").renameTo(prev);
state.edit().putLong(K_PREV_AT, now).apply();
}
File staged = new File(dir, TRIPS_FILE + ".tmp");
copyFile(temp, staged);
target.delete();
if (!staged.renameTo(target)) throw new IOException("rename failed");
state.edit().putString(K_DB_SIG, sig).apply();
return "trips saved (" + sig.substring(0, sig.indexOf('|')) + ")";
} finally {
source.close();
deleteDbFiles(temp);
}
}
private static String signature(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT (SELECT COUNT(*) FROM trips), (SELECT COALESCE(MAX(end_time),0) FROM trips),"
+ " (SELECT COALESCE(MAX(id),0) FROM trip_samples), (SELECT COALESCE(MAX(id),0) FROM trip_points),"
+ " (SELECT COALESCE(MAX(id),0) FROM regen_events)", null);
try {
c.moveToFirst();
return c.getLong(0) + "|" + c.getLong(1) + "|" + c.getLong(2) + "|" + c.getLong(3) + "|" + c.getLong(4);
} finally { c.close(); }
}
/** Consistent point-in-time copy via ATTACH; works while the trip service keeps writing. */
private static void snapshotDatabase(SQLiteDatabase source, File temp) {
List<String> schema = new ArrayList<String>();
List<String> tables = new ArrayList<String>();
Cursor c = source.rawQuery("SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL"
+ " AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%' ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END", null);
try {
while (c.moveToNext()) {
String type = c.getString(0), name = c.getString(1), sql = c.getString(2);
if ("table".equals(type)) {
tables.add(name);
schema.add(sql.replaceFirst("(?i)CREATE\\s+TABLE\\s+(IF\\s+NOT\\s+EXISTS\\s+)?\"?" + java.util.regex.Pattern.quote(name) + "\"?",
"CREATE TABLE bk.\"" + name + "\""));
} else if ("index".equals(type)) {
schema.add(sql.replaceFirst("(?i)CREATE\\s+(UNIQUE\\s+)?INDEX\\s+(IF\\s+NOT\\s+EXISTS\\s+)?\"?" + java.util.regex.Pattern.quote(name) + "\"?",
"CREATE $1INDEX bk.\"" + name + "\""));
}
}
} finally { c.close(); }
int version = source.getVersion();
source.execSQL("ATTACH DATABASE '" + temp.getPath().replace("'", "''") + "' AS bk");
try {
for (String sql : schema) source.execSQL(sql);
source.beginTransaction();
try {
for (String table : tables) source.execSQL("INSERT INTO bk.\"" + table + "\" SELECT * FROM main.\"" + table + "\"");
source.setTransactionSuccessful();
} finally { source.endTransaction(); }
source.execSQL("PRAGMA bk.user_version = " + version);
} finally {
source.execSQL("DETACH DATABASE bk");
}
}
// ---- restore ---------------------------------------------------------------------
/** Restore on first run of an install when a backup is available. */
static boolean restoreIfFresh(Context context) {
Context app = context.getApplicationContext();
SharedPreferences state = state(app);
if (state.getBoolean(K_READY, false)) return false;
if (!hasStorageAccess(app)) return false;
synchronized (LOCK) {
if (!hasBackup()) { state.edit().putBoolean(K_READY, true).commit(); return false; }
String result = restoreSettingsAndTrips(app);
state.edit().putBoolean(K_READY, true).commit();
remember(state, result, true);
return true;
}
}
/** Explicit user-requested restore of the latest backup. Returns a result message. */
static String restoreLatest(Context context) {
synchronized (LOCK) {
Context app = context.getApplicationContext();
if (!hasStorageAccess(app)) return "Storage permission is required";
if (!hasBackup()) return "No backup found in " + backupDir();
String result = restoreSettingsAndTrips(app);
SharedPreferences state = state(app);
state.edit().putBoolean(K_READY, true).commit();
return remember(state, result, true);
}
}
private static String restoreSettingsAndTrips(Context app) {
StringBuilder out = new StringBuilder();
File dir = backupDir();
try {
byte[] bytes = readAll(new File(dir, SETTINGS_FILE));
Map<String, Map<String, Object>> files = BackupCodec.decode(new String(bytes, "UTF-8"));
int applied = 0;
for (Map.Entry<String, Map<String, Object>> file : files.entrySet()) {
if (EXCLUDED.contains(file.getKey())) continue;
SharedPreferences.Editor editor = app.getSharedPreferences(file.getKey(), Context.MODE_PRIVATE).edit();
for (Map.Entry<String, Object> e : file.getValue().entrySet()) {
Object v = e.getValue();
if (v instanceof Boolean) editor.putBoolean(e.getKey(), (Boolean) v);
else if (v instanceof Integer) editor.putInt(e.getKey(), (Integer) v);
else if (v instanceof Long) editor.putLong(e.getKey(), (Long) v);
else if (v instanceof Float) editor.putFloat(e.getKey(), (Float) v);
else if (v instanceof String) editor.putString(e.getKey(), (String) v);
else if (v instanceof Set) {
Set<String> set = new HashSet<String>(); for (Object item : (Set<?>) v) set.add(String.valueOf(item));
editor.putStringSet(e.getKey(), set);
} else continue;
applied++;
}
editor.commit();
}
out.append("restored ").append(applied).append(" settings");
} catch (Throwable error) {
Log.w(TAG, "settings restore failed", error);
out.append("settings restore failed: ").append(error.getClass().getSimpleName());
}
try { out.append("; ").append(restoreTrips(app, dir)); }
catch (Throwable error) { Log.w(TAG, "trip restore failed", error); out.append("; trips restore failed: ").append(error.getClass().getSimpleName()); }
return out.toString();
}
private static String restoreTrips(Context app, File dir) throws Exception {
File backup = new File(dir, TRIPS_FILE);
if (!backup.isFile()) return "no trip backup";
SQLiteDatabase check = SQLiteDatabase.openDatabase(backup.getPath(), null, SQLiteDatabase.OPEN_READONLY);
long backupTrips;
try {
Cursor c = check.rawQuery("SELECT COUNT(*) FROM trips", null);
try { c.moveToFirst(); backupTrips = c.getLong(0); } finally { c.close(); }
if (check.getVersion() > 4) return "trip backup is from a newer app version; skipped";
} finally { check.close(); }
File db = app.getDatabasePath("mg_trips.db");
if (db.isFile()) {
SQLiteDatabase existing = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READONLY);
long localTrips;
try {
Cursor c = existing.rawQuery("SELECT COUNT(*) FROM trips", null);
try { c.moveToFirst(); localTrips = c.getLong(0); } finally { c.close(); }
} finally { existing.close(); }
if (localTrips >= backupTrips && localTrips > 0) return "kept " + localTrips + " existing trips";
// Keep whatever was there so a restore is itself reversible.
copyFile(db, new File(db.getParentFile(), "mg_trips.db.before-restore"));
}
db.getParentFile().mkdirs();
deleteDbFiles(db);
copyFile(backup, db);
return "restored " + backupTrips + " trips";
}
/** Relaunch the home activity in a fresh process so every cache re-reads restored data. */
static void restartApp(final Context context) {
final Context app = context.getApplicationContext();
new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
@Override public void run() {
try {
android.content.Intent launch = new android.content.Intent(app, MainActivity.class)
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK);
android.app.PendingIntent pi = android.app.PendingIntent.getActivity(app, 7421, launch,
android.app.PendingIntent.FLAG_CANCEL_CURRENT);
((android.app.AlarmManager) app.getSystemService(Context.ALARM_SERVICE))
.set(android.app.AlarmManager.RTC, System.currentTimeMillis() + 600L, pi);
} catch (Throwable ignored) { }
android.os.Process.killProcess(android.os.Process.myPid());
}
}, 1800L);
}
// ---- helpers ---------------------------------------------------------------------
private static Map<String, Map<String, ?>> snapshotPrefs(Context app) {
Map<String, Map<String, ?>> files = new LinkedHashMap<String, Map<String, ?>>();
File prefsDir = new File(app.getApplicationInfo().dataDir, "shared_prefs");
File[] list = prefsDir.listFiles();
if (list == null) return files;
for (File f : list) {
String n = f.getName();
if (!n.endsWith(".xml")) continue;
String name = n.substring(0, n.length() - 4);
if (EXCLUDED.contains(name) || name.startsWith("WebView") || name.startsWith("com.google")) continue;
Map<String, ?> all = app.getSharedPreferences(name, Context.MODE_PRIVATE).getAll();
if (!all.isEmpty()) files.put(name, new LinkedHashMap<String, Object>(all));
}
return files;
}
private static SharedPreferences state(Context context) {
return context.getApplicationContext().getSharedPreferences(STATE, Context.MODE_PRIVATE);
}
private static String remember(SharedPreferences state, String message, boolean ok) {
SharedPreferences.Editor e = state.edit().putString(K_LAST_MSG, message);
if (ok) e.putLong(K_LAST_OK, System.currentTimeMillis());
e.apply();
return message;
}
private static void writeAtomically(File target, byte[] bytes) throws IOException {
File parent = target.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) throw new IOException("cannot create " + parent);
File tmp = new File(parent, target.getName() + ".tmp");
FileOutputStream out = new FileOutputStream(tmp);
try { out.write(bytes); out.getFD().sync(); } finally { out.close(); }
target.delete();
if (!tmp.renameTo(target)) throw new IOException("rename failed for " + target);
}
private static byte[] readAll(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192]; int n;
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
return out.toByteArray();
} finally { in.close(); }
}
private static void copyFile(File from, File to) throws IOException {
InputStream in = new FileInputStream(from);
try {
OutputStream out = new FileOutputStream(to);
try {
byte[] buf = new byte[65536]; int n;
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
out.flush();
if (out instanceof FileOutputStream) ((FileOutputStream) out).getFD().sync();
} finally { out.close(); }
} finally { in.close(); }
}
private static void deleteDbFiles(File db) {
db.delete();
new File(db.getPath() + "-wal").delete();
new File(db.getPath() + "-shm").delete();
new File(db.getPath() + "-journal").delete();
}
}
@@ -0,0 +1,245 @@
package cloud.molberg.mgutility;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Locale;
/** Settings → System → Camera test: lists every camera path the head unit exposes and previews the chosen one. */
public final class CameraTestActivity extends AnimatedActivity implements TextureView.SurfaceTextureListener {
private static final int REQUEST_CAMERA = 5102;
private final Handler ui = new Handler(Looper.getMainLooper());
private TextureView preview;
private TextView status;
private TextView info;
private Button cameraButton;
private Button previewButton;
private Camera camera;
private SurfaceTexture surface;
private int legacyCount;
private int selected;
private boolean previewing;
private long frames;
private long startedAt;
@Override public void onCreate(Bundle state) {
super.onCreate(state);
UiTheme.applyFontScale(this);
setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
try { legacyCount = Camera.getNumberOfCameras(); } catch (Throwable t) { legacyCount = 0; }
setContentView(buildUi());
updateCameraLabel();
info.setText(describeHardware());
if (!hasPermission() && Build.VERSION.SDK_INT >= 23) requestPermissions(new String[] { Manifest.permission.CAMERA }, REQUEST_CAMERA);
}
private View buildUi() {
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
root.setPadding(28, 18, 28, 18);
root.setBackgroundColor(UiTheme.BACKGROUND);
LinearLayout header = new LinearLayout(this);
header.setGravity(Gravity.CENTER_VERTICAL);
header.addView(UiTheme.title(this, "CAMERA TEST", 28), new LinearLayout.LayoutParams(0, 56, 1));
header.addView(UiTheme.backButton(this, new View.OnClickListener() {
@Override public void onClick(View v) { finish(); }
}), new LinearLayout.LayoutParams(120, 52));
root.addView(header);
LinearLayout body = new LinearLayout(this);
body.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout left = new LinearLayout(this);
left.setOrientation(LinearLayout.VERTICAL);
cameraButton = UiTheme.button(this, "", new View.OnClickListener() {
@Override public void onClick(View v) { cycleCamera(); }
}, false);
previewButton = UiTheme.button(this, "START PREVIEW", new View.OnClickListener() {
@Override public void onClick(View v) { if (previewing) stopPreview("Stopped"); else startPreview(); }
}, true);
Button rescan = UiTheme.button(this, "RESCAN", new View.OnClickListener() {
@Override public void onClick(View v) {
try { legacyCount = Camera.getNumberOfCameras(); } catch (Throwable t) { legacyCount = 0; }
updateCameraLabel(); info.setText(describeHardware());
}
}, false);
left.addView(cameraButton, new LinearLayout.LayoutParams(-1, 52));
left.addView(previewButton, new LinearLayout.LayoutParams(-1, 52));
left.addView(rescan, new LinearLayout.LayoutParams(-1, 52));
status = UiTheme.text(this, "Idle", 14, UiTheme.TEXT, android.graphics.Typeface.BOLD);
left.addView(status, new LinearLayout.LayoutParams(-1, 70));
info = UiTheme.text(this, "", 12, UiTheme.MUTED, android.graphics.Typeface.NORMAL);
ScrollView scroll = new ScrollView(this);
scroll.addView(info);
left.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
body.addView(left, new LinearLayout.LayoutParams(0, -1, 4));
FrameLayout frame = new FrameLayout(this);
frame.setBackground(UiTheme.surface(UiTheme.SURFACE, 8));
preview = new TextureView(this);
preview.setSurfaceTextureListener(this);
frame.addView(preview, new FrameLayout.LayoutParams(-1, -1));
LinearLayout.LayoutParams fp = new LinearLayout.LayoutParams(0, -1, 6);
fp.setMargins(14, 8, 0, 8);
body.addView(frame, fp);
root.addView(body, new LinearLayout.LayoutParams(-1, 0, 1));
return root;
}
private boolean hasPermission() {
return Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
super.onRequestPermissionsResult(code, permissions, results);
if (code == REQUEST_CAMERA) {
boolean granted = results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED;
status.setText(granted ? "Camera permission granted" : "Camera permission DENIED");
status.setTextColor(granted ? UiTheme.TEXT : UiTheme.WARNING);
info.setText(describeHardware());
}
}
private void updateCameraLabel() {
cameraButton.setText(legacyCount == 0 ? "NO CAMERAS FOUND" : "CAMERA " + selected + " OF " + legacyCount);
}
private void cycleCamera() {
if (legacyCount == 0) return;
boolean was = previewing;
if (was) stopPreview("Switching");
selected = (selected + 1) % legacyCount;
updateCameraLabel();
if (was) startPreview();
}
private String describeHardware() {
StringBuilder sb = new StringBuilder();
sb.append("Permission: ").append(hasPermission() ? "granted" : "NOT granted").append('\n');
sb.append("Camera API (legacy): ").append(legacyCount).append(" camera(s)\n");
for (int i = 0; i < legacyCount; i++) {
try {
Camera.CameraInfo ci = new Camera.CameraInfo();
Camera.getCameraInfo(i, ci);
sb.append(" #").append(i).append(ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ? " front" : " back")
.append(", orientation ").append(ci.orientation).append("°\n");
} catch (Throwable t) { sb.append(" #").append(i).append(" info error: ").append(t.getMessage()).append('\n'); }
}
try {
CameraManager cm = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String[] ids = cm.getCameraIdList();
sb.append("Camera2 API: ").append(ids.length).append(" id(s) ").append(Arrays.toString(ids)).append('\n');
} catch (Throwable t) { sb.append("Camera2 API: ").append(t.getClass().getSimpleName()).append(" ").append(t.getMessage()).append('\n'); }
File[] nodes = new File("/dev").listFiles();
int video = 0;
StringBuilder raw = new StringBuilder();
if (nodes != null) {
Arrays.sort(nodes);
for (File f : nodes) {
if (!f.getName().startsWith("video")) continue;
video++;
boolean readable = f.canRead();
String openResult = "not tried";
if (readable) {
try { new FileInputStream(f).close(); openResult = "open OK"; }
catch (Throwable t) { openResult = "open failed: " + t.getMessage(); }
}
raw.append(" ").append(f.getPath()).append(" read=").append(readable).append(" write=").append(f.canWrite())
.append(" ").append(openResult).append('\n');
}
}
sb.append("Raw V4L2 nodes (/dev/video*): ").append(video == 0 ? "none visible to this app" : video).append('\n').append(raw);
return sb.toString();
}
private void startPreview() {
if (previewing) return;
if (legacyCount == 0) { setStatus("No camera reported by Android. See raw nodes list below.", true); return; }
if (!hasPermission()) {
setStatus("Camera permission not granted", true);
if (Build.VERSION.SDK_INT >= 23) requestPermissions(new String[] { Manifest.permission.CAMERA }, REQUEST_CAMERA);
return;
}
if (surface == null) { setStatus("Preview surface not ready yet, try again", true); return; }
try {
camera = Camera.open(selected);
Camera.Parameters params = camera.getParameters();
Camera.Size size = params.getPreviewSize();
camera.setPreviewTexture(surface);
frames = 0; startedAt = System.currentTimeMillis();
camera.setErrorCallback(new Camera.ErrorCallback() {
@Override public void onError(int error, Camera cam) { stopPreview("Camera error " + error); }
});
camera.setPreviewCallback(new Camera.PreviewCallback() {
@Override public void onPreviewFrame(byte[] data, Camera cam) { frames++; }
});
camera.startPreview();
previewing = true;
previewButton.setText("STOP PREVIEW");
setStatus(String.format(Locale.US, "Opened camera %d %dx%d", selected, size.width, size.height), false);
ui.postDelayed(fpsTick, 1000);
} catch (Throwable error) {
releaseCamera();
setStatus("OPEN FAILED: " + error.getClass().getSimpleName() + " " + error.getMessage(), true);
}
}
private final Runnable fpsTick = new Runnable() {
@Override public void run() {
if (!previewing) return;
double seconds = Math.max(0.001, (System.currentTimeMillis() - startedAt) / 1000.0);
boolean live = frames > 0;
setStatus(String.format(Locale.US, "Camera %d streaming: %d frames, %.1f fps", selected, frames, frames / seconds), !live && seconds > 3);
if (!live && seconds > 3) status.setText("Opened but NO FRAMES received after " + (int) seconds + "s");
ui.postDelayed(this, 1000);
}
};
private void stopPreview(String message) {
previewing = false;
ui.removeCallbacks(fpsTick);
releaseCamera();
previewButton.setText("START PREVIEW");
setStatus(message, false);
}
private void releaseCamera() {
if (camera == null) return;
try { camera.setPreviewCallback(null); camera.stopPreview(); } catch (Throwable ignored) { }
try { camera.release(); } catch (Throwable ignored) { }
camera = null;
}
private void setStatus(String text, boolean warn) {
status.setText(text);
status.setTextColor(warn ? UiTheme.WARNING : UiTheme.TEXT);
}
@Override public void onSurfaceTextureAvailable(SurfaceTexture s, int w, int h) { surface = s; }
@Override public void onSurfaceTextureSizeChanged(SurfaceTexture s, int w, int h) { }
@Override public boolean onSurfaceTextureDestroyed(SurfaceTexture s) { stopPreview("Stopped"); surface = null; return true; }
@Override public void onSurfaceTextureUpdated(SurfaceTexture s) { }
@Override protected void onPause() {
if (previewing) stopPreview("Stopped (screen left)");
super.onPause();
}
}
@@ -106,7 +106,7 @@ public final class DiagnosticsClient {
} }, "mg-startup-analytics").start();
}
private static String getAppVersion(Context context) {
static String getAppVersion(Context context) {
try { String value = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; return value == null ? "unknown" : value; }
catch (Exception ignored) { return "unknown"; }
}
@@ -7,6 +7,8 @@ final class IconPack {
static String forLabel(String value) {
if (value == null) return "help";
String s = value.toLowerCase(java.util.Locale.ROOT);
if (s.contains("backup") || s.contains("back up") || s.contains("restore")) return "storage";
if (s.contains("camera")) return "videocam";
if (s.contains("update") || s.contains("version")) return "system_update";
if (s.contains("plugin")) return "extension";
if (s.contains("export")) return "file_upload";
+37 -13
View File
@@ -213,11 +213,7 @@ public class MainActivity extends AnimatedActivity {
final Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override public void uncaughtException(Thread thread, Throwable error) {
StringWriter trace = new StringWriter();
error.printStackTrace(new PrintWriter(trace));
prefs.edit().putString("crash_type", error.getClass().getName())
.putString("crash_message", error.getMessage() == null ? "" : error.getMessage())
.putString("crash_stack", trace.toString().substring(0, Math.min(trace.toString().length(), 12000))).commit();
DiagnosticsClient.queueCrash(getApplicationContext(), error);
if (previous != null) previous.uncaughtException(thread, error);
}
});
@@ -765,6 +761,7 @@ public class MainActivity extends AnimatedActivity {
}
@Override protected void onPause() {
BackupManager.requestBackup(this);
if (dashboardGauges != null) dashboardGauges.stopVisualizer();
MusicPlayerManager.setListener(null);
if (campingModeController != null) campingModeController.onActivityPaused();
@@ -775,8 +772,19 @@ public class MainActivity extends AnimatedActivity {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (controlPanel != null) controlPanel.onPermissionResult(requestCode);
if (requestCode == AUDIO_REQUEST) {
if (BackupManager.hasStorageAccess(this)) {
// A fresh install gets its permission only now: restore the surviving backup, then restart.
if (BackupManager.restoreIfFresh(this)) {
Toast.makeText(this, "Restored settings and trips from backup - restarting", Toast.LENGTH_LONG).show();
BackupManager.restartApp(this);
return;
}
BackupManager.requestBackup(this);
}
boolean granted = false;
for (int result : grantResults) if (result == android.content.pm.PackageManager.PERMISSION_GRANTED) granted = true;
for (String permission : permissions) if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
granted = checkSelfPermission(permission) == android.content.pm.PackageManager.PERMISSION_GRANTED;
}
if (dashboardGauges != null) dashboardGauges.setVisualizerEnabled(granted &&
getSharedPreferences(UI_PREFS, MODE_PRIVATE).getBoolean("home_visualizer_enabled", true));
if (!granted) Toast.makeText(this, "Live music visualizer needs microphone/audio permission", Toast.LENGTH_LONG).show();
@@ -1114,16 +1122,24 @@ public class MainActivity extends AnimatedActivity {
homeRow.setPadding(UiTheme.dp(this, 12), UiTheme.dp(this, 12),
UiTheme.dp(this, 12), UiTheme.dp(this, 12));
dashboardGauges = new DashboardGauges(this);
ferrofluidShader = new FerrofluidLayer(this);
// The app runs as android.uid.system (platform-signed, for /dev/video*
// access). Android refuses WebView in privileged processes and throws
// UnsupportedOperationException, so fall back to the native renderer.
try {
ferrofluidShader = new FerrofluidLayer(this);
} catch (Throwable webViewUnavailable) {
android.util.Log.w("MGUtility", "WebView unavailable; using native ferrofluid", webViewUnavailable);
ferrofluidShader = null;
}
ferrofluidFallback = new FerrofluidShaderView(this);
FrameLayout gaugeLayer = new FrameLayout(this);
gaugeLayer.setBackground(UiTheme.surface(UiTheme.SURFACE, 12));
gaugeLayer.addView(ferrofluidShader, new FrameLayout.LayoutParams(-1, -1));
if (ferrofluidShader != null) gaugeLayer.addView(ferrofluidShader, new FrameLayout.LayoutParams(-1, -1));
gaugeLayer.addView(ferrofluidFallback, new FrameLayout.LayoutParams(-1, -1));
// The GPU surface is deliberately the background; the Canvas gauge is
// drawn above it so arcs, values, labels, and touch handling remain clear.
gaugeLayer.addView(dashboardGauges, new FrameLayout.LayoutParams(-1, -1));
dashboardGauges.setFerrofluidShader(ferrofluidShader);
if (ferrofluidShader != null) dashboardGauges.setFerrofluidShader(ferrofluidShader);
dashboardGauges.setFerrofluidFallback(ferrofluidFallback);
musicPanel = new MusicPlayerPanel(this);
LinearLayout.LayoutParams musicParams = new LinearLayout.LayoutParams(0, -1, 1f);
@@ -1274,10 +1290,18 @@ public class MainActivity extends AnimatedActivity {
}
private void requestAudioAccess() {
if (Build.VERSION.SDK_INT < 23 || !getSharedPreferences(UI_PREFS, MODE_PRIVATE)
.getBoolean("home_visualizer_enabled", true)) return;
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED) return;
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST);
if (Build.VERSION.SDK_INT < 23) return;
java.util.ArrayList<String> needed = new java.util.ArrayList<String>();
if (getSharedPreferences(UI_PREFS, MODE_PRIVATE).getBoolean("home_visualizer_enabled", true)
&& checkSelfPermission(Manifest.permission.RECORD_AUDIO) != android.content.pm.PackageManager.PERMISSION_GRANTED)
needed.add(Manifest.permission.RECORD_AUDIO);
// Backups live on shared storage so they outlive an uninstall.
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
needed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
needed.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (needed.isEmpty()) return;
requestPermissions(needed.toArray(new String[0]), AUDIO_REQUEST);
}
private void openComponent(String pkg, String cls) {
+11
View File
@@ -0,0 +1,11 @@
package cloud.molberg.mgutility;
import android.app.Application;
/** Application entry point: restores a surviving backup (if any) before any component reads settings. */
public final class MgApp extends Application {
@Override public void onCreate() {
super.onCreate();
BackupManager.start(this);
}
}
@@ -0,0 +1,284 @@
package cloud.molberg.mgutility;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.Locale;
/** Settings → System → Microphone test: live level meter per audio source plus record-and-playback. */
public final class MicTestActivity extends AnimatedActivity {
private static final int REQUEST_AUDIO = 5101;
private static final int RATE = 16000;
private static final int[] SOURCES = {
MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.VOICE_RECOGNITION,
MediaRecorder.AudioSource.VOICE_COMMUNICATION, MediaRecorder.AudioSource.CAMCORDER,
MediaRecorder.AudioSource.DEFAULT };
private static final String[] NAMES = { "MIC", "VOICE_RECOGNITION", "VOICE_COMMUNICATION", "CAMCORDER", "DEFAULT" };
private final Handler ui = new Handler(Looper.getMainLooper());
private int sourceIndex;
private volatile boolean metering;
private volatile boolean busy;
private Thread worker;
private MicScopeView scope;
private TextView readout;
private TextView verdict;
private TextView devices;
private Button sourceButton;
private Button meterButton;
private Button loopButton;
@Override public void onCreate(Bundle state) {
super.onCreate(state);
UiTheme.applyFontScale(this);
setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(buildUi());
refreshDevices();
ensurePermission();
}
private View buildUi() {
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
root.setPadding(28, 18, 28, 18);
root.setBackgroundColor(UiTheme.BACKGROUND);
LinearLayout header = new LinearLayout(this);
header.setGravity(Gravity.CENTER_VERTICAL);
header.addView(UiTheme.title(this, "MICROPHONE TEST", 28), new LinearLayout.LayoutParams(0, 56, 1));
header.addView(UiTheme.backButton(this, new View.OnClickListener() {
@Override public void onClick(View v) { finish(); }
}), new LinearLayout.LayoutParams(120, 52));
root.addView(header);
root.addView(UiTheme.text(this, "Speak or tap near the microphone. The meter should move; pick another source if it stays silent.",
13, UiTheme.MUTED, android.graphics.Typeface.NORMAL), new LinearLayout.LayoutParams(-1, 38));
LinearLayout buttons = new LinearLayout(this);
sourceButton = UiTheme.button(this, "", new View.OnClickListener() {
@Override public void onClick(View v) { cycleSource(); }
}, false);
meterButton = UiTheme.button(this, "START LIVE METER", new View.OnClickListener() {
@Override public void onClick(View v) { toggleMeter(); }
}, true);
loopButton = UiTheme.button(this, "RECORD 4s + PLAY BACK", new View.OnClickListener() {
@Override public void onClick(View v) { recordAndPlay(); }
}, false);
LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(0, 52, 1);
bp.setMargins(0, 0, 10, 0);
buttons.addView(sourceButton, bp);
buttons.addView(meterButton, new LinearLayout.LayoutParams(bp));
buttons.addView(loopButton, new LinearLayout.LayoutParams(0, 52, 1));
root.addView(buttons, new LinearLayout.LayoutParams(-1, 56));
updateSourceLabel();
scope = new MicScopeView(this);
root.addView(scope, new LinearLayout.LayoutParams(-1, 110));
readout = UiTheme.text(this, "Level: —", 16, UiTheme.TEXT, android.graphics.Typeface.NORMAL);
root.addView(readout, new LinearLayout.LayoutParams(-1, 34));
verdict = UiTheme.text(this, "Not started", 18, UiTheme.MUTED, android.graphics.Typeface.BOLD);
root.addView(verdict, new LinearLayout.LayoutParams(-1, 40));
devices = UiTheme.text(this, "", 13, UiTheme.MUTED, android.graphics.Typeface.NORMAL);
ScrollView scroll = new ScrollView(this);
scroll.addView(devices);
root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
return root;
}
private void ensurePermission() {
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO }, REQUEST_AUDIO);
}
}
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
super.onRequestPermissionsResult(code, permissions, results);
if (code == REQUEST_AUDIO) {
boolean granted = results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED;
verdict.setText(granted ? "Microphone permission granted" : "Microphone permission DENIED");
verdict.setTextColor(granted ? UiTheme.MUTED : UiTheme.WARNING);
}
}
private boolean hasPermission() {
return Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
private void cycleSource() {
if (metering || busy) return;
sourceIndex = (sourceIndex + 1) % SOURCES.length;
updateSourceLabel();
}
private void updateSourceLabel() { sourceButton.setText("SOURCE: " + NAMES[sourceIndex]); }
private void refreshDevices() {
StringBuilder sb = new StringBuilder("INPUT DEVICES\n");
if (Build.VERSION.SDK_INT >= 23) {
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
AudioDeviceInfo[] inputs = am.getDevices(AudioManager.GET_DEVICES_INPUTS);
if (inputs.length == 0) sb.append(" (none reported by Android)\n");
for (AudioDeviceInfo d : inputs) {
sb.append(" • ").append(typeName(d.getType())).append(" ").append(d.getProductName()).append('\n');
}
} else sb.append(" (device listing needs Android 6+)\n");
sb.append("\nPCM format: ").append(RATE).append(" Hz mono 16-bit");
devices.setText(sb.toString());
}
private static String typeName(int type) {
switch (type) {
case 15: return "BUILTIN_MIC";
case 3: return "WIRED_HEADSET";
case 4: return "WIRED_HEADPHONES";
case 7: return "BLUETOOTH_SCO";
case 11: return "USB_DEVICE";
case 12: return "USB_ACCESSORY";
case 18: return "TELEPHONY";
case 25: return "REMOTE_SUBMIX";
default: return "TYPE_" + type;
}
}
private void toggleMeter() {
if (metering) { stopMeter(); return; }
if (busy) return;
if (!hasPermission()) { ensurePermission(); return; }
metering = true;
meterButton.setText("STOP METER");
loopButton.setEnabled(false);
final int source = SOURCES[sourceIndex];
worker = new Thread(new Runnable() { @Override public void run() { meterLoop(source); } }, "mic-test-meter");
worker.start();
}
private void stopMeter() {
metering = false;
meterButton.setText("START LIVE METER");
loopButton.setEnabled(true);
}
private void meterLoop(int source) {
AudioRecord record = null;
try {
int min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(source, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Math.max(min, 4096) * 2);
if (record.getState() != AudioRecord.STATE_INITIALIZED) { fail("Source did not initialise (busy or unsupported)"); return; }
record.startRecording();
short[] buffer = new short[1600]; // 100 ms
double sessionPeak = 0;
long frames = 0;
int zeroReads = 0;
while (metering) {
int count = record.read(buffer, 0, buffer.length);
if (count <= 0) { if (++zeroReads > 20) { fail("No audio frames returned (read=" + count + ")"); return; } continue; }
zeroReads = 0;
frames += count;
final double rms = AudioLevel.rms(buffer, count);
final double peak = AudioLevel.peak(buffer, count);
sessionPeak = Math.max(sessionPeak, peak);
final double best = sessionPeak;
final long total = frames;
ui.post(new Runnable() { @Override public void run() { showLevel(rms, peak, best, total); } });
}
} catch (Throwable error) {
fail(error.getClass().getSimpleName() + ": " + error.getMessage());
} finally {
if (record != null) { try { record.stop(); } catch (Throwable ignored) { } try { record.release(); } catch (Throwable ignored) { } }
ui.post(new Runnable() { @Override public void run() { if (!busy) stopMeter(); } });
}
}
private void showLevel(double rms, double peak, double sessionPeak, long frames) {
scope.setLevel((float) Math.min(1.0, rms * 8.0));
readout.setText(String.format(Locale.US, "RMS %.1f dBFS peak %.1f dBFS session peak %.1f dBFS %.1f s captured",
AudioLevel.dbfs(rms), AudioLevel.dbfs(peak), AudioLevel.dbfs(sessionPeak), frames / (double) RATE));
String text = AudioLevel.verdict(sessionPeak);
verdict.setText(text);
verdict.setTextColor(text.startsWith("OK") ? UiTheme.CYAN_BRIGHT : UiTheme.WARNING);
}
private void fail(final String message) {
ui.post(new Runnable() {
@Override public void run() {
verdict.setText("ERROR: " + message);
verdict.setTextColor(UiTheme.WARNING);
stopMeter();
}
});
}
private void recordAndPlay() {
if (metering || busy) return;
if (!hasPermission()) { ensurePermission(); return; }
busy = true;
loopButton.setEnabled(false); meterButton.setEnabled(false);
verdict.setText("Recording 4 seconds… speak now");
verdict.setTextColor(UiTheme.CYAN_BRIGHT);
final int source = SOURCES[sourceIndex];
new Thread(new Runnable() {
@Override public void run() {
AudioRecord record = null;
AudioTrack track = null;
final String[] result = { "" };
try {
int min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(source, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Math.max(min, 4096) * 2);
if (record.getState() != AudioRecord.STATE_INITIALIZED) throw new IllegalStateException("Source did not initialise");
short[] pcm = new short[RATE * 4];
record.startRecording();
int filled = 0;
long deadline = System.currentTimeMillis() + 6000L;
while (filled < pcm.length && System.currentTimeMillis() < deadline) {
int n = record.read(pcm, filled, Math.min(1600, pcm.length - filled));
if (n > 0) filled += n;
}
record.stop();
if (filled == 0) throw new IllegalStateException("No audio frames captured");
final double peak = AudioLevel.peak(pcm, filled);
final double rms = AudioLevel.rms(pcm, filled);
result[0] = String.format(Locale.US, "%s (peak %.1f dBFS, RMS %.1f dBFS)", AudioLevel.verdict(peak), AudioLevel.dbfs(peak), AudioLevel.dbfs(rms));
ui.post(new Runnable() { @Override public void run() { verdict.setText("Playing back… " + String.format(Locale.US, "peak %.1f dBFS", AudioLevel.dbfs(peak))); } });
track = new AudioTrack(AudioManager.STREAM_MUSIC, RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
filled * 2, AudioTrack.MODE_STATIC);
track.write(pcm, 0, filled);
track.play();
Thread.sleep(filled * 1000L / RATE + 400L);
} catch (Throwable error) {
result[0] = "ERROR: " + error.getClass().getSimpleName() + ": " + error.getMessage();
} finally {
if (record != null) { try { record.release(); } catch (Throwable ignored) { } }
if (track != null) { try { track.stop(); } catch (Throwable ignored) { } try { track.release(); } catch (Throwable ignored) { } }
}
ui.post(new Runnable() {
@Override public void run() {
busy = false;
verdict.setText(result[0]);
verdict.setTextColor(result[0].startsWith("OK") ? UiTheme.CYAN_BRIGHT : UiTheme.WARNING);
loopButton.setEnabled(true); meterButton.setEnabled(true);
}
});
}
}, "mic-test-loopback").start();
}
@Override protected void onPause() {
metering = false;
super.onPause();
}
}
@@ -92,6 +92,27 @@ public final class SettingsActivity extends AnimatedActivity {
rebuildCategory();
}
private void requestStorage() {
if (android.os.Build.VERSION.SDK_INT >= 23) requestPermissions(new String[] {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE }, 5103);
}
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
super.onRequestPermissionsResult(code, permissions, results);
if (code == 5103) {
if (BackupManager.hasStorageAccess(this)) {
Toast.makeText(this, "Storage granted - backing up", Toast.LENGTH_SHORT).show();
BackupManager.requestBackup(this);
} else Toast.makeText(this, "Storage permission denied - backups paused", Toast.LENGTH_LONG).show();
rebuildCategory();
}
}
@Override protected void onPause() {
BackupManager.requestBackup(this);
super.onPause();
}
private void rebuildCategory() { showCategory(selectedCategory); }
@Override protected void onSaveInstanceState(android.os.Bundle outState) {
@@ -182,6 +203,39 @@ public final class SettingsActivity extends AnimatedActivity {
private void system() {
section("System", "Updates, extensions, diagnostics, and settings maintenance");
systemTools();
subsection("Hardware tests", "Check that the head unit's microphone and cameras reach the app");
content.addView(row("◉", "Microphone test", "Live level meter, source selection and playback", open(MicTestActivity.class)));
content.addView(row("▣", "Camera test", "List cameras, raw video nodes and live preview", open(CameraTestActivity.class)));
subsection("Automatic backup", "Settings and trip reports are copied to " + BackupManager.DIR_NAME + " on internal storage and survive uninstall");
content.addView(row("↻", "Back up now", BackupManager.status(this), new View.OnClickListener() {
@Override public void onClick(View v) {
if (!BackupManager.hasStorageAccess(SettingsActivity.this)) { requestStorage(); return; }
new Thread(new Runnable() { @Override public void run() {
final String result = BackupManager.backupNow(SettingsActivity.this);
runOnUiThread(new Runnable() { @Override public void run() {
Toast.makeText(SettingsActivity.this, result, Toast.LENGTH_LONG).show(); rebuildCategory(); } });
} }, "mg-backup-now").start();
}
}));
content.addView(row("⇩", "Restore from backup", BackupManager.hasBackup() ? "Replace current settings and trips with the saved backup" : "No backup found yet", new View.OnClickListener() {
@Override public void onClick(View v) {
if (!BackupManager.hasStorageAccess(SettingsActivity.this)) { requestStorage(); return; }
if (!BackupManager.hasBackup()) { Toast.makeText(SettingsActivity.this, "No backup found", Toast.LENGTH_LONG).show(); return; }
UiTheme.dialog(SettingsActivity.this).setTitle("RESTORE BACKUP?")
.setMessage("Settings are replaced with the saved backup. Trip reports are restored if the backup has more trips than this device. The app restarts afterwards.")
.setNegativeButton("CANCEL", null)
.setPositiveButton("RESTORE", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
new Thread(new Runnable() { @Override public void run() {
final String result = BackupManager.restoreLatest(SettingsActivity.this);
runOnUiThread(new Runnable() { @Override public void run() {
Toast.makeText(SettingsActivity.this, result + " - restarting", Toast.LENGTH_LONG).show();
BackupManager.restartApp(SettingsActivity.this); } });
} }, "mg-backup-restore").start();
}
}).show();
}
}));
subsection("Software updates", "Choose the Gitea release channel and install updates inside MG Utility");
content.addView(row("↥", "Software updates",
UpdateManager.installedVersion(this) + " • " +
@@ -328,29 +382,6 @@ public final class SettingsActivity extends AnimatedActivity {
}));
}
private void confirmDiagnosticsUpload() {
UiTheme.dialog(this).setTitle("UPLOAD DIAGNOSTICS?")
.setMessage("This sends the diagnostic snapshot and filtered app-owned warnings/errors to help troubleshoot compatibility. It excludes unrestricted system logcat and VIN. Upload is only sent after you choose UPLOAD.")
.setNegativeButton("CANCEL", null)
.setPositiveButton("UPLOAD", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
final android.app.ProgressDialog progress = new android.app.ProgressDialog(SettingsActivity.this);
progress.setMessage("Preparing diagnostics…"); progress.setCancelable(false); progress.show();
new Thread(new Runnable() { @Override public void run() {
final org.json.JSONObject report = VehicleDiagnosticsCollector.collect(SettingsActivity.this);
DiagnosticsClient.uploadDiagnostics(SettingsActivity.this, report, new DiagnosticsClient.Callback() {
@Override public void complete(final String message) {
runOnUiThread(new Runnable() { @Override public void run() {
if (!isFinishing()) progress.dismiss();
Toast.makeText(SettingsActivity.this, message, Toast.LENGTH_LONG).show();
}});
}
});
}}).start();
}
}).show();
}
private void audio() {
section("Audio", "Playback, sound field, and assistant controls");
subsection("Sound and volume", "Configure event sounds and speed-aware playback");
@@ -418,11 +449,13 @@ public final class SettingsActivity extends AnimatedActivity {
startActivity(intent);
}
}));
subsection("Diagnostics", "Troubleshooting and voluntary diagnostic uploads");
subsection("Diagnostics", "Usage sharing and troubleshooting");
content.addView(toggleRow("↑", "Share usage data with developer",
"Send device/car compatibility details once, then app crashes and errors. No VIN or live vehicle data.",
"remote_diagnostics", "share_usage_data", true, new Runnable() {
@Override public void run() { UsageDataReporter.preferenceChanged(SettingsActivity.this); }
}));
content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class)));
content.addView(row("↑", "Upload diagnostics", "Review data and voluntarily upload detailed logs", new View.OnClickListener() {
@Override public void onClick(View v) { confirmDiagnosticsUpload(); }
}));
subsection("Keys and launcher", "Customize physical inputs and the home app");
content.addView(row("K", "Key remapping", "Assign physical head-unit keys", open(KeyRemappingActivity.class)));
@@ -573,6 +573,7 @@ public final class TripTrackingService extends Service {
Location arrivalLocation = usableLocation();
database.finishTrip(finishedTripId, parkedSince + PARKED_GRACE_MS, sample);
publishArrivalBriefing(finishedTripId, arrivalLocation);
BackupManager.requestBackup(this);
activeTripId = TripDatabase.NO_TRIP;
lastDistanceLocation = null;
lastStoredLocation = null;
@@ -0,0 +1,34 @@
package cloud.molberg.mgutility;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class UsageDataPolicy {
private static final Pattern LOG_LINE = Pattern.compile("^\\s*(\\d+\\.\\d+)\\s+(\\d+)\\s+\\d+\\s+([WEF])\\s+([^:]+):\\s?(.*)$");
private UsageDataPolicy() { }
public static String redact(String value, int limit) {
if (value == null) return "";
String safe = value.replaceAll("(?i)bearer\\s+[^\\s,;\"]+", "Bearer [REDACTED]");
safe = safe.replaceAll("(?i)((?:authorization|access[_-]?token|refresh[_-]?token|token|password|secret|api[_-]?key|vin|serial(?:number)?|imei|imsi|android[_ ]?id|mac(?: address)?)[\"']?\\s*[:=]\\s*)(?:\"[^\"]*\"|'[^']*'|[^\\s,;]+)", "$1[REDACTED]");
safe = safe.replaceAll("(?i)https?://[^\\s]+", "[REDACTED_URL]");
safe = safe.replaceAll("(?i)(?:[0-9a-f]{2}:){5}[0-9a-f]{2}", "[REDACTED_MAC]");
safe = safe.replaceAll("(?<![A-Za-z0-9])[A-HJ-NPR-Z0-9]{17}(?![A-Za-z0-9])", "[REDACTED_VIN_OR_SERIAL]");
return safe.substring(0, Math.min(safe.length(), limit));
}
public static String warning(String line, int pid, double after) {
Matcher match = LOG_LINE.matcher(line);
if (!match.matches() || !match.group(2).equals(String.valueOf(pid)) || Double.parseDouble(match.group(1)) <= after) return "";
String tag = match.group(4).trim();
if (!(tag.equals("MgServiceBridge") || tag.equals("VehicleDataProvider") || tag.startsWith("VehicleSettings")
|| tag.equals("EnergyActivity") || tag.equals("MGUtilityTracker") || tag.equals("MGUtilityBoot"))) return "";
return redact(line, 1500);
}
public static double timestamp(String line) {
Matcher match = LOG_LINE.matcher(line);
return match.matches() ? Double.parseDouble(match.group(1)) : 0;
}
}
@@ -0,0 +1,225 @@
package cloud.molberg.mgutility;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public final class UsageDataReporter {
private static final ScheduledExecutorService WORKER = Executors.newSingleThreadScheduledExecutor();
private static boolean started;
private static volatile HttpURLConnection activeConnection;
static final Object CONSENT_LOCK = new Object();
private UsageDataReporter() { }
private static SharedPreferences preferences(Context context) {
return context.getSharedPreferences("remote_diagnostics", Context.MODE_PRIVATE);
}
public static boolean isEnabled(Context context) {
return preferences(context).getBoolean("share_usage_data", true);
}
public static synchronized void start(Context context) {
final Context app = context.getApplicationContext();
if (!started) {
started = true;
WORKER.scheduleWithFixedDelay(new Runnable() {
@Override public void run() { DiagnosticsClient.refreshConfig(app); }
}, 15, 15, TimeUnit.MINUTES);
}
WORKER.execute(new Runnable() { @Override public void run() { upload(app); } });
}
public static void preferenceChanged(Context context) {
final Context app = context.getApplicationContext();
if (!isEnabled(app)) {
synchronized (CONSENT_LOCK) {
preferences(app).edit().remove("pending_crash").remove("pending_usage_errors")
.remove("crash_type").remove("crash_message").remove("crash_stack")
.putString("usage_log_cursor", String.valueOf(System.currentTimeMillis() / 1000.0)).apply();
}
HttpURLConnection connection = activeConnection;
if (connection != null) connection.disconnect();
} else {
preferences(app).edit().putString("usage_log_cursor", String.valueOf(System.currentTimeMillis() / 1000.0)).apply();
DiagnosticsClient.refreshConfig(app);
}
}
private static boolean allowed(Context context) {
return isEnabled(context) && preferences(context).getBoolean("telemetry_enabled", false);
}
private static JSONObject identity(Context context) throws Exception {
JSONObject payload = new JSONObject();
payload.put("vehicleId", DiagnosticsClient.getVehicleId(context));
payload.put("appVersion", DiagnosticsClient.getAppVersion(context));
return payload;
}
private static JSONObject registration(Context context) throws Exception {
JSONObject payload = identity(context);
payload.put("platform", "android-" + Build.VERSION.SDK_INT);
payload.put("manufacturer", Build.MANUFACTURER);
payload.put("carModel", Build.MODEL);
payload.put("carBuild", Build.FINGERPRINT);
payload.put("appProfile", VehicleSettingsProfile.UNKNOWN_READ_ONLY);
JSONObject details = new JSONObject();
details.put("schema", 1);
details.put("modelSource", "android_build_model_not_verified_vehicle_trim");
details.put("brand", Build.BRAND);
details.put("device", Build.DEVICE);
details.put("product", Build.PRODUCT);
details.put("board", Build.BOARD);
details.put("hardware", Build.HARDWARE);
details.put("androidRelease", Build.VERSION.RELEASE);
details.put("buildDisplay", Build.DISPLAY);
details.put("buildType", Build.TYPE);
details.put("supportedAbis", new JSONArray(Build.SUPPORTED_ABIS));
DisplayMetrics metrics = new DisplayMetrics();
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
manager.getDefaultDisplay().getRealMetrics(metrics);
details.put("screenWidthPx", metrics.widthPixels);
details.put("screenHeightPx", metrics.heightPixels);
details.put("densityDpi", metrics.densityDpi);
details.put("screenDensity", metrics.density);
details.put("availableProcessors", Runtime.getRuntime().availableProcessors());
android.app.ActivityManager.MemoryInfo memory = new android.app.ActivityManager.MemoryInfo();
((android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(memory);
details.put("totalMemoryBytes", memory.totalMem);
JSONObject snapshot = VehicleDiagnosticsCollector.collect(context);
JSONObject compatibility = new JSONObject();
for (String key : new String[]{"vehicleService", "vehicleServiceOperations", "systemSettingsServices", "vehicleSettingsCatalog", "appControlCatalog"}) {
if (snapshot.has(key)) compatibility.put(key, snapshot.get(key));
}
details.put("compatibility", compatibility);
payload.put("details", details);
return payload;
}
private static void upload(Context context) {
if (!allowed(context)) return;
SharedPreferences prefs = preferences(context);
String endpoint = prefs.getString("upload_url", "");
if (!endpoint.startsWith("https://")) return;
String base = endpoint.endsWith("/") ? endpoint : endpoint + "/";
try {
if (!prefs.getString("usage_registration_endpoint", "").equals(base)) {
if (!post(context, base + "v1/install", registration(context))) return;
prefs.edit().putString("usage_registration_endpoint", base).apply();
}
if (!allowed(context)) return;
String pending = prefs.getString("pending_crash", "");
if (!pending.isEmpty()) {
JSONObject old = new JSONObject(pending);
JSONObject crash = identity(context);
crash.put("reportId", old.optString("reportId", UUID.randomUUID().toString()));
crash.put("appVersion", old.optString("appVersion", DiagnosticsClient.getAppVersion(context)));
crash.put("exceptionType", UsageDataPolicy.redact(old.optString("exceptionType"), 160));
crash.put("message", UsageDataPolicy.redact(old.optString("message"), 2000));
crash.put("stack", UsageDataPolicy.redact(old.optString("stack"), 12000));
synchronized (CONSENT_LOCK) {
if (!allowed(context) || !prefs.getString("pending_crash", "").equals(pending)) return;
pending = crash.toString();
prefs.edit().putString("pending_crash", pending).apply();
}
if (!post(context, base + "v1/crashes", crash)) return;
synchronized (CONSENT_LOCK) {
if (prefs.getString("pending_crash", "").equals(pending)) prefs.edit().remove("pending_crash").apply();
}
}
if (!allowed(context)) return;
String errors = prefs.getString("pending_usage_errors", "");
if (errors.isEmpty()) {
JSONObject batch = collectErrors(context);
if (batch == null || !allowed(context)) return;
errors = batch.toString();
synchronized (CONSENT_LOCK) {
if (!allowed(context)) return;
prefs.edit().putString("pending_usage_errors", errors).apply();
}
}
JSONObject batch = new JSONObject(errors);
if (post(context, base + "v1/errors", batch)) {
synchronized (CONSENT_LOCK) {
if (!allowed(context)) return;
double cursor = Math.max(Double.parseDouble(prefs.getString("usage_log_cursor", "0")), batch.getDouble("cursor"));
prefs.edit().remove("pending_usage_errors").putString("usage_log_cursor", String.valueOf(cursor)).apply();
}
}
} catch (Exception ignored) { }
}
private static JSONObject collectErrors(Context context) throws Exception {
double cursor = Double.parseDouble(preferences(context).getString("usage_log_cursor", "0"));
StringBuilder lines = new StringBuilder();
final Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "epoch", "--pid=" + android.os.Process.myPid(), "-t", "250", "*:W"});
Timer timeout = new Timer(true);
timeout.schedule(new TimerTask() { @Override public void run() { process.destroy(); } }, 3000);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
double latest = cursor;
while ((line = reader.readLine()) != null) {
String warning = UsageDataPolicy.warning(line, android.os.Process.myPid(), cursor);
if (warning.isEmpty()) continue;
if (lines.length() + warning.length() > 14000) break;
lines.append(warning).append('\n');
latest = Math.max(latest, UsageDataPolicy.timestamp(line));
}
if (lines.length() == 0) return null;
JSONObject payload = identity(context);
payload.put("reportId", UUID.randomUUID().toString());
payload.put("details", lines.toString());
payload.put("cursor", String.valueOf(latest));
return payload;
} finally { timeout.cancel(); process.destroy(); }
}
private static boolean post(Context context, String url, JSONObject payload) throws Exception {
if (!allowed(context)) return false;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
activeConnection = connection;
try {
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if (!allowed(context)) return false;
try (OutputStream output = connection.getOutputStream()) { output.write(payload.toString().getBytes(StandardCharsets.UTF_8)); }
int status = connection.getResponseCode();
if (status == 404) preferences(context).edit().remove("usage_registration_endpoint").apply();
if (status != 202) return false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
char[] response = new char[2048];
StringBuilder text = new StringBuilder();
int count;
while ((count = reader.read(response)) != -1) {
text.append(response, 0, count);
if (text.length() > 4096) return false;
}
return new JSONObject(text.toString()).optBoolean("accepted", false);
}
} finally { activeConnection = null; connection.disconnect(); }
}
}
-50
View File
@@ -1,50 +0,0 @@
# MG Utility diagnostics service
The service listens on `0.0.0.0:7013`; the configured public origin is
`https://analytics.molberg.cloud/`.
## Routes
- `GET /health` — health check.
- `GET /v1/config` — public client config (`enabled`, `uploadUrl`, announcement,
changelog). `uploadUrl` is an HTTPS base URL; the app appends `v1/events`.
- `POST /v1/install` — automatic minimal install/build/car-model fingerprint on startup; no logs or live vehicle data.
- `POST /v1/crashes` — bounded automatic crash summary from a previous unclean app exit.
- `POST /v1/events` — detailed diagnostic uploads only after the user explicitly taps upload; controlled by the config's `enabled` field.
- `GET /admin/` — existing authenticated support dashboard for voluntary reports and remote client controls.
- `GET /admin/analytics` — separate authenticated compatibility dashboard with SQLite-backed install fingerprints, crash reports, voluntary diagnostics, and copy-to-clipboard summaries.
The admin password is stored in Vaultwarden as **MG Utility Analytics
Dashboard** (`login.password`). `run-server.sh` loads it at process start; it is
never written into the repository or runtime data directory. Admin event and
config APIs require the dashboard's signed session cookie. Sessions expire in
12 hours and are invalidated by process restart. The public dashboard is HTTPS
only in normal deployment; the cookie is Secure/HttpOnly/SameSite=Lax.
The dashboard is designed phone-first: bottom-sheet report details, 44px
minimum touch targets, sticky top bar, horizontally scrollable tabs, and safe-area
padding for notched devices.
## App config discovery
The APK contains only the stable public Gitea contents-API URL for
`alex/mg-utility`'s `telemetry-service/client-config.json`. That bootstrap file
contains `configUrl`; the app fetches live settings from that HTTPS API on
startup. The live API response supplies the upload endpoint. The upload URL is
not compiled into the APK. The Gitea bootstrap file must be published before
clients can discover this service.
## Data and privacy
Detailed diagnostic uploads happen only after the user taps **UPLOAD DIAGNOSTICS**, with a disclosure beside that button. Those uploads include the app diagnostic snapshot and filtered app-owned warning/error lines, but never unrestricted system logcat or optional “ALL PROPS”. Separately, startup sends an install-scoped random ID and bounded car/build fingerprint, and an unclean exit queues a crash summary for delivery on next launch. Automatic records never include detailed logs, VIN, Android ID, MAC, or live vehicle values. Dashboard data is stored in `data/analytics.sqlite` (directory mode 0700, database mode 0600), with a 20,000-event retention cap. Request IP addresses are not stored. The app profile is a compatibility catalog, not a VIN-verified trim.
## Local verification
```sh
npm test
curl -fsS http://127.0.0.1:7013/health
curl -fsS https://analytics.molberg.cloud/v1/config
```
Run under PM2 via `run-server.sh`, not `server.js` directly, so the dashboard
password is fetched from Vault at process launch. Runtime data stays under the
ignored `data/` directory.
-132
View File
@@ -1,132 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#0b1115"><meta name="robots" content="noindex,nofollow">
<title>MG Fielddesk · Analytics</title>
<style>
:root{color-scheme:dark;--bg:#0b1115;--panel:#111a20;--panel2:#162229;--line:#26383e;--text:#edf5f2;--muted:#93a7a7;--teal:#59e0c0;--amber:#ffc570;--red:#ff7c79;--radius:18px;--safe-bottom:env(safe-area-inset-bottom,0px)}
*{box-sizing:border-box}html{min-height:100%;background:var(--bg)}body{margin:0;background:radial-gradient(1000px 600px at 100% -10%,#153b3a 0,transparent 60%),var(--bg);color:var(--text);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
button,input,textarea,select{font:inherit;color:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
.hidden{display:none!important}.shell{max-width:1120px;margin:auto;padding:0 20px 50px}.topbar{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:14px;padding:12px 20px;background:#0b1115ed;border-bottom:1px solid #203238;backdrop-filter:blur(16px);margin:0 -20px}
.brandmark{width:38px;height:38px;border-radius:12px;display:grid;place-items:center;background:#173e39;color:var(--teal);font-weight:900;letter-spacing:-1px}.brand{font-weight:760;letter-spacing:-.3px}.brand small{display:block;color:var(--muted);font-size:11px;font-weight:550;letter-spacing:.12em;text-transform:uppercase}.topright{margin-left:auto;display:flex;gap:10px;align-items:center}.live{font-size:12px;color:var(--teal);display:flex;align-items:center;gap:7px}.dot{width:7px;height:7px;border-radius:50%;background:currentColor;box-shadow:0 0 10px currentColor}.iconbtn,.btn{border:1px solid var(--line);background:var(--panel2);border-radius:12px;padding:10px 14px;min-height:42px}.iconbtn{padding:9px 11px}.btn.primary{background:var(--teal);border-color:var(--teal);color:#06221d;font-weight:750}.btn.danger{color:#ffaaa3;border-color:#663936;background:#261918}.btn.small{padding:7px 10px;min-height:34px;font-size:13px}.panelhead>.btn.small{white-space:nowrap;flex-shrink:0}.nav{display:flex;gap:6px;overflow:auto;padding:14px 0 6px;scrollbar-width:none}.nav::-webkit-scrollbar{display:none}.nav button{white-space:nowrap;border:0;background:transparent;color:var(--muted);border-radius:10px;padding:10px 13px;min-height:44px}.nav button.active{background:#193b38;color:var(--teal);font-weight:700}
.view{display:none}.view.active{display:block}.hero{display:flex;justify-content:space-between;align-items:flex-end;gap:20px;padding:22px 0 18px}.eyebrow{color:var(--teal);font-size:11px;font-weight:800;letter-spacing:.16em;text-transform:uppercase}.hero h1{font-size:clamp(26px,5vw,38px);letter-spacing:-1.2px;line-height:1.1;margin:8px 0}.hero p{margin:0;color:var(--muted);max-width:580px}.date{color:var(--muted);font-size:13px;white-space:nowrap}
.grid{display:grid;gap:14px}.stats{grid-template-columns:repeat(4,minmax(0,1fr));margin:10px 0 22px}.stat,.panel{border:1px solid var(--line);background:linear-gradient(145deg,#132027,#10171c);border-radius:var(--radius);padding:18px}.stat label{display:block;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.09em}.stat strong{display:block;font-size:29px;letter-spacing:-.7px;margin-top:8px}.stat .hint{font-size:12px;color:var(--muted);margin-top:3px}.panel{margin-bottom:16px}.panelhead{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.panelhead h2{font-size:17px;margin:0;letter-spacing:-.2px}.subtle{color:var(--muted);font-size:13px}.split{display:grid;grid-template-columns:1.2fr .8fr;gap:15px}.productchips{display:flex;flex-wrap:wrap;gap:8px}.chip{border:1px solid var(--line);border-radius:999px;background:#162329;padding:8px 11px;color:#d9e6e2;font-size:13px}.chip b{color:var(--teal);margin-left:6px}
.toolbar{display:grid;grid-template-columns:minmax(180px,1fr) minmax(130px,.55fr) minmax(130px,.55fr) auto;gap:9px;margin-bottom:12px}.field{width:100%;min-height:44px;border:1px solid var(--line);background:#0d1519;border-radius:12px;padding:10px 12px}.field::placeholder{color:#6f8586}.report-list{display:grid;gap:10px}.report{border:1px solid var(--line);background:#10191e;border-radius:15px;padding:14px;cursor:pointer;transition:border-color .15s,transform .15s}.report:hover{border-color:#4c8881;transform:translateY(-1px)}.reporttop{display:flex;gap:10px;align-items:center}.badge{font-size:11px;letter-spacing:.04em;text-transform:uppercase;font-weight:760;color:#9cebd8;background:#163833;border:1px solid #245448;padding:4px 8px;border-radius:999px;max-width:45%;overflow:hidden;text-overflow:ellipsis}.reporttime{margin-left:auto;color:var(--muted);font-size:12px}.report h3{font-size:15px;margin:9px 0 4px;overflow-wrap:anywhere}.reportmeta{display:flex;gap:10px;flex-wrap:wrap;color:var(--muted);font-size:12px}.reportpreview{color:#c0d0cb;font-size:13px;margin-top:8px;white-space:pre-wrap;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow-wrap:anywhere}.empty{padding:38px 12px;text-align:center;color:var(--muted);border:1px dashed var(--line);border-radius:15px}.loadmore{width:100%;margin-top:10px}
.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.toggleline{display:flex;gap:12px;align-items:center;padding:14px;background:#0d1519;border:1px solid var(--line);border-radius:14px}.toggleline input{appearance:none;width:48px;height:28px;background:#38464a;border-radius:20px;position:relative;flex:0 0 auto;transition:.2s}.toggleline input:before{content:"";position:absolute;width:22px;height:22px;top:3px;left:3px;border-radius:50%;background:#e9f2ed;transition:.2s}.toggleline input:checked{background:#188d74}.toggleline input:checked:before{left:23px}.togglecopy strong{display:block}.togglecopy span{font-size:12px;color:var(--muted)}.help{font-size:12px;color:var(--muted);margin:8px 2px}.formrow{margin:14px 0}.formrow label{display:block;color:#b9c9c4;font-size:13px;margin:0 0 7px}.actions{display:flex;gap:9px;align-items:center;flex-wrap:wrap}.status{font-size:12px;color:var(--teal);min-height:18px}.notice{border-left:3px solid var(--amber);padding:10px 12px;background:#261f15;border-radius:0 10px 10px 0;color:#e9d5b5;font-size:13px;margin-top:12px}
.changelog{display:grid;gap:10px}.changeitem{border:1px solid var(--line);padding:12px;border-radius:14px;background:#0d1519}.changehead{display:grid;grid-template-columns:110px 1fr auto;gap:8px;align-items:center}.changeitem textarea{margin-top:8px;min-height:75px;resize:vertical}.dangerlink{border:0;background:transparent;color:var(--red);font-size:13px;padding:8px;min-width:44px;min-height:44px;border-radius:10px}
.overlay{position:fixed;inset:0;z-index:20;background:#0009;display:none;align-items:center;justify-content:center;padding:18px}.overlay.open{display:flex}.sheet{width:min(720px,100%);max-height:min(85vh,900px);overflow:auto;background:#111a20;border:1px solid #345057;border-radius:22px;padding:20px;box-shadow:0 30px 90px #000a}.sheethead{display:flex;gap:10px;align-items:flex-start}.sheethead h2{font-size:20px;margin:3px 0 4px;overflow-wrap:anywhere}.sheethead .iconbtn{margin-left:auto}.sheetmeta{color:var(--muted);font-size:13px}.details{white-space:pre-wrap;overflow-wrap:anywhere;background:#091014;border:1px solid var(--line);border-radius:13px;padding:14px;font:12px/1.55 ui-monospace,SFMono-Regular,monospace;max-height:45vh;overflow:auto;margin:16px 0}.toast{position:fixed;z-index:30;bottom:calc(18px + var(--safe-bottom));left:50%;transform:translateX(-50%);padding:11px 16px;border:1px solid #32665c;border-radius:999px;background:#132723;color:#dffff6;box-shadow:0 8px 30px #0008;display:none;max-width:calc(100vw - 32px);text-align:center}.toast.show{display:block}
#login{max-width:440px;margin:10vh auto;padding:24px}.logininput{font-size:17px;min-height:52px}.loginbtn{width:100%;margin-top:12px;min-height:50px}.foot{color:#6f8586;font-size:11px;padding:14px 2px;text-align:center}
@media(max-width:760px){.shell{padding:0 14px calc(30px + var(--safe-bottom))}.topbar{margin:0 -14px;padding:10px 14px}.brand small{font-size:10px}.live span:last-child{display:none}.hero{display:block;padding-top:18px}.hero h1{font-size:29px}.date{display:block;margin-top:8px}.stats{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.stat{padding:14px;border-radius:15px}.stat strong{font-size:25px}.stat label{font-size:10px}.split,.settings-grid{grid-template-columns:1fr}.toolbar{grid-template-columns:1fr 1fr}.toolbar .search{grid-column:1/-1}.toolbar button{width:100%}.panel{padding:14px;border-radius:16px}.panelhead{align-items:flex-start}.report{padding:13px}.reporttime{font-size:11px}.changehead{grid-template-columns:1fr auto}.changehead .version{grid-column:1}.changehead .title{grid-column:1/-1;grid-row:2}.changehead .remove{grid-column:2;grid-row:1}.overlay{align-items:flex-end;padding:0}.sheet{width:100%;max-height:90dvh;border-radius:22px 22px 0 0;padding:20px 16px calc(18px + var(--safe-bottom));border-bottom:0}.details{max-height:42dvh}.actions .btn{flex:1}#saveAnnouncement{flex:2}#clearAnnouncement{flex:1}.topright .iconbtn{min-width:43px}.btn.small{min-height:44px}.nav{margin:0 -14px;padding:10px 14px 4px}.brandmark{width:35px;height:35px}}
@media(max-width:370px){.topbar{gap:9px}.brand{font-size:14px}.stats{gap:7px}.stat{padding:11px}.toolbar{grid-template-columns:1fr}.toolbar .search{grid-column:auto}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;transition:none!important}}
</style>
</head>
<body>
<div class="shell">
<header class="topbar">
<div class="brandmark">MG</div><div class="brand">Fielddesk<small>Telemetry & support</small></div>
<div class="topright"><div class="live"><i class="dot"></i><span id="liveLabel">Connecting</span></div><button id="logout" class="iconbtn hidden" aria-label="Log out" title="Log out">↗</button></div>
</header>
<section id="login" class="panel hidden">
<div class="eyebrow">Restricted console</div><h1 style="margin:8px 0">Welcome back</h1><p class="subtle">Sign in to manage diagnostics and client settings.</p>
<form id="loginForm"><div class="formrow"><label for="pw">Admin password</label><input class="field logininput" id="pw" type="password" autocomplete="current-password" required></div><button class="btn primary loginbtn" type="submit">Sign in securely</button><p id="loginMsg" class="status"></p></form>
</section>
<div id="app" class="hidden">
<nav class="nav" aria-label="Dashboard sections">
<button class="active" data-view="overview">Overview</button><button data-view="reports">Reports</button><button data-view="fleet">Fleet & crashes</button><button data-view="controls">Client controls</button>
</nav>
<section id="view-overview" class="view active">
<div class="hero"><div><div class="eyebrow">Support operations</div><h1>Fleet pulse</h1><p>Keep an eye on user-submitted diagnostics and manage what clients receive.</p></div><div class="date" id="updatedAt">—</div></div>
<div class="grid stats">
<article class="stat"><label>Reports retained</label><strong id="statTotal">—</strong><div class="hint">Most recent 20,000</div></article>
<article class="stat"><label>Last 24 hours</label><strong id="statDay">—</strong><div class="hint">New support uploads</div></article>
<article class="stat"><label>App builds seen</label><strong id="statBuilds">—</strong><div class="hint">Distinct versions</div></article>
<article class="stat"><label>Products</label><strong id="statProducts">—</strong><div class="hint">SAIC apps reporting in</div></article>
<article class="stat"><label>Vehicles identified</label><strong id="statVehicles">—</strong><div class="hint">Random app-install IDs</div></article>
</div>
<div class="split">
<section class="panel"><div class="panelhead"><div><h2>Recent reports</h2><div class="subtle">Latest user-submitted diagnostics</div></div><button class="btn small" data-goto="reports">View all&nbsp; →</button></div><div id="recentList" class="report-list"></div></section>
<section class="panel"><div class="panelhead"><div><h2>Products in view</h2><div class="subtle">Auto-discovered from uploads</div></div></div><div id="productList" class="productchips"></div><div class="notice">Uploads are user-triggered. Review device/build details as potentially sensitive.</div></section>
</div>
</section>
<section id="view-reports" class="view">
<div class="hero"><div><div class="eyebrow">Triage queue</div><h1>Support reports</h1><p>Search recent submissions, narrow by product/category, then open a report for full diagnostic details.</p></div></div>
<section class="panel">
<div class="toolbar">
<input id="search" class="field search" type="search" placeholder="Search messages and details…" aria-label="Search reports">
<select id="filterProduct" class="field" aria-label="Filter by product"><option value="">All products</option></select>
<select id="filterCategory" class="field" aria-label="Filter by category"><option value="">All categories</option></select>
<select id="filterVehicle" class="field" aria-label="Filter by vehicle instance"><option value="">All vehicles</option></select>
<button id="refresh" class="btn">Refresh</button>
</div>
<div class="panelhead"><span id="reportCount" class="subtle">Loading…</span><button id="export" class="btn small">Export JSON ↓</button></div>
<div id="reportList" class="report-list"></div><button id="loadMore" class="btn loadmore hidden">Load older reports</button>
</section>
</section>
<section id="view-fleet" class="view">
<div class="hero"><div><div class="eyebrow">Automatic compatibility telemetry</div><h1>Fleet & crashes</h1><p>Install-level counts and minimal startup car/build fingerprints, plus crash reports captured when the app restarts after an unclean exit.</p></div></div>
<div class="grid stats"><article class="stat"><label>Known installs</label><strong id="fleetInstalls">—</strong></article><article class="stat"><label>Crash reports</label><strong id="fleetCrashes">—</strong></article></div>
<section class="panel"><div class="panelhead"><h2>Install fingerprints</h2><button id="copyFleet" class="btn small">Copy fleet summary</button></div><pre id="fleetList" class="details"></pre></section>
<section class="panel"><div class="panelhead"><h2>Crash reports</h2><button id="copyCrashes" class="btn small">Copy crash summary</button></div><div id="crashList" class="report-list"></div></section>
</section>
<section id="view-controls" class="view">
<div class="hero"><div><div class="eyebrow">Remote operations</div><h1>Client controls</h1><p>Changes here are served by the live config API; app clients refresh this config on launch.</p></div></div>
<section class="panel">
<div class="panelhead"><div><h2>Diagnostics intake</h2><div class="subtle">Route explicit user uploads to the selected HTTPS endpoint.</div></div><span id="intakeBadge" class="badge">—</span></div>
<div class="settings-grid">
<div><label class="toggleline"><input id="telemetryEnabled" type="checkbox"><span class="togglecopy"><strong>Automatic compatibility telemetry</strong><span>Controls startup fingerprints and crash summaries; logs remain user-triggered.</span></span></label><label class="toggleline" style="margin-top:9px"><input id="enabled" type="checkbox"><span class="togglecopy"><strong>Accept detailed uploads</strong><span>Users can voluntarily submit diagnostics after explicit confirmation.</span></span></label><p class="help">Automatic telemetry and detailed voluntary reports have separate switches.</p></div>
<div class="formrow" style="margin:0"><label for="uploadUrl">Upload endpoint base URL</label><input id="uploadUrl" class="field" type="url" inputmode="url" placeholder="https://host.example/" autocomplete="url"><p class="help">HTTPS required. The client appends <code>v1/events</code>.</p></div>
</div>
<div class="actions"><button id="saveConfig" class="btn primary">Save intake settings</button><span id="cfgStatus" class="status" role="status"></span></div>
</section>
<section class="panel">
<div class="panelhead"><div><h2>Announcement banner</h2><div class="subtle">Shown in the app while this text is published.</div></div><span id="annCount" class="subtle">0 / 2,000</span></div>
<textarea id="announcement" class="field" rows="3" maxlength="2000" placeholder="Share a short service notice or release message…" style="resize:vertical"></textarea>
<div class="actions" style="margin-top:10px"><button id="saveAnnouncement" class="btn primary">Publish announcement</button><button id="clearAnnouncement" class="btn">Clear</button><span id="annStatus" class="status" role="status"></span></div>
</section>
<section class="panel">
<div class="panelhead"><div><h2>Release notes</h2><div class="subtle">Versioned notices returned in remote config.</div></div><button id="addChangelog" class="btn small">+ Add note</button></div>
<div id="changelogList" class="changelog"></div>
<div class="actions" style="margin-top:12px"><button id="saveChangelog" class="btn primary">Save release notes</button><span id="changeStatus" class="status" role="status"></span></div>
</section>
<p class="foot">Bootstrap discovery remains controlled by the public Gitea config. These settings change the live API config only.</p>
</section>
</div>
<footer class="foot">MG FIELD DESK · private operator console · no user IPs stored</footer>
</div>
<div id="detailOverlay" class="overlay" role="dialog" aria-modal="true" aria-labelledby="detailTitle"><div class="sheet"><div class="sheethead"><div><div class="eyebrow" id="detailCategory">Report</div><h2 id="detailTitle"></h2><div id="detailMeta" class="sheetmeta"></div></div><button id="closeDetail" class="iconbtn" aria-label="Close report">✕</button></div><pre id="detailText" class="details"></pre><div class="actions"><button id="copyDetail" class="btn">Copy details</button><button id="deleteDetail" class="btn danger">Delete report</button></div></div></div>
<div id="toast" class="toast" role="status"></div>
<script>
const $=id=>document.getElementById(id);let timer=null,events=[],offset=0,limit=50,selected=null,config={},metrics={},fleet={installs:[],crashes:[]};
const api=async(path,opts={})=>{const r=await fetch(path,{credentials:'same-origin',...opts});return{status:r.status,body:await r.json().catch(()=>({}))}};
const esc=(node,value)=>{node.textContent=value==null?'':String(value);return node};
const fmtDate=value=>{try{return new Intl.DateTimeFormat(undefined,{month:'short',day:'numeric',hour:'numeric',minute:'2-digit'}).format(new Date(value))}catch(_){return value||''}};
function toast(message){esc($('toast'),message);$('toast').classList.add('show');setTimeout(()=>$('toast').classList.remove('show'),2400)}
function setView(name){document.querySelectorAll('.view').forEach(v=>v.classList.toggle('active',v.id==='view-'+name));document.querySelectorAll('.nav button').forEach(b=>b.classList.toggle('active',b.dataset.view===name));history.replaceState(null,'','#'+name);window.scrollTo({top:0,behavior:'smooth'});if(name==='reports')loadEvents(true);if(name==='fleet')loadFleet();if(name==='controls')loadConfig()}
async function check(){const c=await api('/admin/api/session');if(c.body.authorized){$('login').classList.add('hidden');$('app').classList.remove('hidden');$('logout').classList.remove('hidden');$('liveLabel').textContent='Live service';loadEvents(true);loadConfig();const route=location.hash.slice(1);if(['overview','reports','fleet','controls'].includes(route))setView(route);if(!timer)timer=setInterval(()=>{if($('view-overview').classList.contains('active'))loadEvents(true);if($('view-fleet').classList.contains('active'))loadFleet()},30000)}else{$('app').classList.add('hidden');$('login').classList.remove('hidden');$('logout').classList.add('hidden');$('liveLabel').textContent='Sign in'}}
async function loadFleet(){const r=await api('/admin/api/analytics');if(r.status!==200)return;fleet=r.body;$('fleetInstalls').textContent=String(r.body.stats?.activeInstalls||0);$('fleetCrashes').textContent=String(r.body.stats?.crashReports||0);$('fleetList').textContent=JSON.stringify(r.body.installs||[],null,2);const list=$('crashList');list.textContent='';(r.body.crashes||[]).forEach(c=>{const row=document.createElement('article');row.className='report';const title=document.createElement('h3');esc(title,(c.exceptionType||'Crash')+': '+(c.message||''));const meta=document.createElement('div');meta.className='reportmeta';esc(meta,[c.carModel,c.appProfile,c.appVersion,c.platform,fmtDate(c.receivedAt)].filter(Boolean).join(' · '));const pre=document.createElement('div');pre.className='reportpreview';esc(pre,c.stack||'');row.append(title,meta,pre);row.onclick=()=>{const pack=JSON.stringify(c,null,2);$('detailCategory').textContent='Crash report';$('detailTitle').textContent=c.exceptionType||'Crash';$('detailMeta').textContent=[c.carModel,c.appProfile,c.appVersion,fmtDate(c.receivedAt)].filter(Boolean).join(' · ');$('detailText').textContent=pack;$('detailOverlay').classList.add('open');document.body.style.overflow='hidden'};list.append(row)});if(!list.childNodes.length){const empty=document.createElement('div');empty.className='empty';esc(empty,'No crash reports received.');list.append(empty)}}
function makeReport(e){const card=document.createElement('article');card.className='report';card.tabIndex=0;card.setAttribute('role','button');card.setAttribute('aria-label','Open report '+(e.message||e.category));const top=document.createElement('div');top.className='reporttop';const badge=document.createElement('span');badge.className='badge';esc(badge,e.category||'report');const time=document.createElement('span');time.className='reporttime';esc(time,fmtDate(e.receivedAt));top.append(badge,time);const title=document.createElement('h3');esc(title,e.message||'Diagnostic details attached');const meta=document.createElement('div');meta.className='reportmeta';const vehicle=e.vehicleId?' · instance '+e.vehicleId.slice(0,8)+(e.appProfile?' · app profile '+e.appProfile:''):'';esc(meta,(e.product||'MG Utility')+' · '+(e.appVersion||'version unknown')+' · '+(e.platform||'platform unknown')+vehicle);card.append(top,title,meta);if(e.details){const pre=document.createElement('div');pre.className='reportpreview';esc(pre,e.details);card.append(pre)}card.onclick=()=>openDetail(e);card.onkeydown=ev=>{if(ev.key==='Enter'||ev.key===' '){ev.preventDefault();openDetail(e)}};return card}
function fillSelect(select,items,label){const current=select.value;select.textContent='';const all=document.createElement('option');all.value='';all.textContent=label;select.append(all);for(const value of items){const o=document.createElement('option');o.value=value;o.textContent=value;select.append(o)}select.value=items.includes(current)?current:''}
function copyText(value,label){navigator.clipboard.writeText(value).then(()=>toast(label+' copied')).catch(()=>toast('Clipboard unavailable'))}
async function loadEvents(reset=true,render=true){if(reset)offset=0;const q=new URLSearchParams({limit:String(limit),offset:String(offset)});if($('filterProduct').value)q.set('product',$('filterProduct').value);if($('filterCategory').value)q.set('category',$('filterCategory').value);if($('filterVehicle').value)q.set('vehicleId',$('filterVehicle').value);const r=await api('/admin/api/events?'+q);if(r.status!==200){if(r.status===401)check();return}const batch=r.body.events||[];if(reset)events=batch;else events=events.concat(batch);metrics=r.body.stats||{};$('updatedAt').textContent='Updated '+fmtDate(new Date().toISOString());$('reportCount').textContent=(r.body.total||0)+' matching · showing '+events.length;$('loadMore').classList.toggle('hidden',!r.body.hasMore);fillSelect($('filterProduct'),(r.body.products||[]).map(x=>x.name),'All products');fillSelect($('filterCategory'),r.body.categories||[],'All categories');fillSelect($('filterVehicle'),(r.body.vehicles||[]).map(v=>v.id),'All vehicles');if(render)renderEvents()}
function renderEvents(){const term=$('search').value.trim().toLowerCase();const visible=events.filter(e=>!term||[e.message,e.details,e.category,e.product,e.appVersion,e.vehicleId,e.appProfile].some(v=>String(v||'').toLowerCase().includes(term)));const list=$('reportList');list.textContent='';if(!visible.length){const empty=document.createElement('div');empty.className='empty';esc(empty,events.length?'No matching reports. Try a shorter search.':'No user uploads yet. Reports appear after a user submits diagnostics in the app.');list.append(empty)}else visible.forEach(e=>list.append(makeReport(e)));const recent=$('recentList');recent.textContent='';if(events.length)events.slice(0,4).forEach(e=>recent.append(makeReport(e)));else{const empty=document.createElement('div');empty.className='empty';esc(empty,'No reports received yet.');recent.append(empty)}$('statTotal').textContent=String(metrics.total||0);$('statDay').textContent=String(metrics.last24h||0);$('statBuilds').textContent=String(metrics.builds||0);$('statProducts').textContent=String(metrics.products||0);$('statVehicles').textContent=String(metrics.vehicles||0);const chips=$('productList');chips.textContent='';if((metrics.productList||[]).length)metrics.productList.forEach(item=>{const c=document.createElement('button');c.className='chip';esc(c,item.name);const b=document.createElement('b');esc(b,item.count);c.append(b);c.onclick=()=>{$('filterProduct').value=item.name;setView('reports')};chips.append(c)});else{const s=document.createElement('span');s.className='subtle';esc(s,'No product data yet');chips.append(s)}}
function openDetail(e){selected=e;$('detailCategory').textContent=e.category||'Report';$('detailTitle').textContent=e.message||'Diagnostic details';$('detailMeta').textContent=[e.product||'MG Utility',e.appVersion||'unknown version',e.platform||'unknown platform',e.appProfile?'app profile '+e.appProfile:'',e.vehicleId?'instance '+e.vehicleId:'',fmtDate(e.receivedAt)].filter(Boolean).join(' · ');$('detailText').textContent=JSON.stringify({vehicleId:e.vehicleId||null,appProfile:e.appProfile||null,details:e.details,appVersion:e.appVersion,platform:e.platform,product:e.product,category:e.category,id:e.id,receivedAt:e.receivedAt},null,2);$('detailOverlay').classList.add('open');document.body.style.overflow='hidden'}
function closeDetail(){$('detailOverlay').classList.remove('open');document.body.style.overflow='';selected=null}
function ensureEmptyNotes(){const list=$('changelogList');if(!list.querySelector('.changeitem')&&!list.querySelector('.empty')){const empty=document.createElement('div');empty.className='empty';esc(empty,'No release notes yet. Add a versioned note to announce what changed.');list.append(empty)}}
function changelogItem(item={}){const box=document.createElement('article');box.className='changeitem';const head=document.createElement('div');head.className='changehead';const version=document.createElement('input');version.className='field version';version.placeholder='Version';version.value=item.version||'';const title=document.createElement('input');title.className='field title';title.placeholder='Release title';title.value=item.title||'';const remove=document.createElement('button');remove.className='dangerlink remove';remove.type='button';remove.textContent='Remove';remove.onclick=()=>{box.remove();ensureEmptyNotes()};const notes=document.createElement('textarea');notes.className='field';notes.placeholder='Short release notes (plain text)';notes.value=item.notes||item.body||'';head.append(version,title,remove);box.append(head,notes);return box}
async function loadConfig(){const r=await api('/admin/api/config');if(r.status!==200)return;config=r.body;$('enabled').checked=!!config.enabled;$('telemetryEnabled').checked=config.telemetryEnabled!==false;$('uploadUrl').value=config.uploadUrl||'';$('announcement').value=config.announcement?config.announcement.text||'':'';$('annCount').textContent=$('announcement').value.length+' / 2,000';$('intakeBadge').textContent=config.enabled?'Detailed uploads enabled':'Detailed uploads paused';$('intakeBadge').style.color=config.enabled?'var(--teal)':'var(--amber)';const list=$('changelogList');list.textContent='';(config.changelog||[]).forEach(item=>list.append(changelogItem(item)));ensureEmptyNotes()}
async function saveConfig(extra={}){const body={enabled:$('enabled').checked,telemetryEnabled:$('telemetryEnabled').checked,uploadUrl:$('uploadUrl').value.trim(),...extra};const r=await api('/admin/api/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});return r}
$('loginForm').onsubmit=async ev=>{ev.preventDefault();const r=await api('/admin/api/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({password:$('pw').value})});if(r.status===200){$('pw').value='';$('loginMsg').textContent='';check()}else esc($('loginMsg'),r.body.error||'Sign-in failed')};
$('logout').onclick=async()=>{await api('/admin/api/logout',{method:'POST'});clearInterval(timer);timer=null;check()};
$('refresh').onclick=()=>loadEvents(true);$('loadMore').onclick=async()=>{offset=events.length;await loadEvents(false)};$('search').oninput=()=>renderEvents();$('filterProduct').onchange=()=>loadEvents(true);$('filterCategory').onchange=()=>loadEvents(true);$('filterVehicle').onchange=()=>loadEvents(true);
document.querySelectorAll('[data-view]').forEach(b=>b.onclick=()=>setView(b.dataset.view));document.querySelectorAll('[data-goto]').forEach(b=>b.onclick=()=>setView(b.dataset.goto));
$('enabled').onchange=()=>{$('intakeBadge').textContent=$('enabled').checked?'Uploads enabled':'Uploads paused';$('intakeBadge').style.color=$('enabled').checked?'var(--teal)':'var(--amber)'};
$('saveConfig').onclick=async()=>{const r=await saveConfig();esc($('cfgStatus'),r.status===200?'Settings saved.':'Save failed: '+(r.body.error||r.status));if(r.status===200)loadConfig()};
$('announcement').oninput=()=>$('annCount').textContent=$('announcement').value.length+' / 2,000';$('saveAnnouncement').onclick=async()=>{const r=await saveConfig({announcement:$('announcement').value});esc($('annStatus'),r.status===200?'Announcement published.':r.body.error||'Save failed');if(r.status===200)loadConfig()};$('clearAnnouncement').onclick=()=>{$('announcement').value='';$('annCount').textContent='0 / 2,000'};
$('addChangelog').onclick=()=>{$('changelogList').querySelector('.empty')?.remove();$('changelogList').prepend(changelogItem());$('changelogList').querySelector('input')?.focus()};$('saveChangelog').onclick=async()=>{const changelog=[...$('changelogList').querySelectorAll('.changeitem')].map(x=>({version:x.querySelector('.version').value.trim(),title:x.querySelector('.title').value.trim(),notes:x.querySelector('textarea').value.trim()})).filter(x=>x.version||x.title||x.notes);const r=await saveConfig({changelog});esc($('changeStatus'),r.status===200?'Release notes saved.':r.body.error||'Save failed');if(r.status===200)loadConfig()};
$('copyFleet').onclick=()=>copyText(JSON.stringify(fleet.installs||[],null,2),'Fleet summary');$('copyCrashes').onclick=()=>copyText(JSON.stringify(fleet.crashes||[],null,2),'Crash summary');$('export').onclick=()=>{location.href='/admin/api/export'};$('closeDetail').onclick=closeDetail;$('detailOverlay').onclick=e=>{if(e.target===$('detailOverlay'))closeDetail()};document.addEventListener('keydown',e=>{if(e.key==='Escape')closeDetail()});$('copyDetail').onclick=async()=>{try{await navigator.clipboard.writeText($('detailText').textContent);toast('Diagnostic details copied')}catch(_){toast('Clipboard unavailable')}};
$('deleteDetail').onclick=async()=>{if(!selected||!confirm('Delete this report permanently?'))return;const r=await api('/admin/api/events/'+encodeURIComponent(selected.id),{method:'DELETE'});if(r.status===200){closeDetail();await loadEvents(true);toast('Report deleted')}else toast('Could not delete report')};
check();
</script>
</body></html>
-8
View File
@@ -1,8 +0,0 @@
{
"name": "mg-utility-telemetry",
"version": "0.1.0",
"private": true,
"description": "Local MG Utility diagnostics and announcements service",
"scripts": {"start": "node server.js", "test": "node --test"},
"engines": {"node": ">=20"}
}
-18
View File
@@ -1,18 +0,0 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
VAULT_CLI=/root/.openclaw/workspace/scripts/bw
VAULT_ITEM_ID=b06d15fd-1a7f-4d65-a396-60211709b640
TMPDIR=/root/.hermes/cache/scratch
export TMPDIR
ITEM_FILE=$(mktemp)
chmod 600 "$ITEM_FILE"
trap 'rm -f "$ITEM_FILE"' EXIT HUP INT TERM
"$VAULT_CLI" get item "$VAULT_ITEM_ID" > "$ITEM_FILE"
ADMIN_PASSWORD=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["login"]["password"],end="")' "$ITEM_FILE")
test -n "$ADMIN_PASSWORD"
export ADMIN_PASSWORD
rm -f "$ITEM_FILE"
trap - EXIT HUP INT TERM
cd "$ROOT"
exec node server.js
-450
View File
@@ -1,450 +0,0 @@
'use strict';
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const { randomUUID, randomBytes, createHmac, timingSafeEqual } = require('node:crypto');
const { DatabaseSync } = require('node:sqlite');
const HOST = process.env.HOST || '0.0.0.0';
const PORT = Number(process.env.PORT || 7013);
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const CONFIG_FILE = process.env.CONFIG_FILE || path.join(__dirname, 'client-config.json');
const DATABASE_FILE = process.env.DATABASE_FILE || path.join(DATA_DIR, 'analytics.sqlite');
const SESSION_COOKIE = 'mgadm';
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
const MAX_BODY = 256 * 1024;
const MAX_EVENTS = 20000;
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
try { fs.chmodSync(DATA_DIR, 0o700); } catch (_) {}
const db = new DatabaseSync(DATABASE_FILE);
db.exec(`CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY, receivedAt TEXT NOT NULL, product TEXT NOT NULL, appVersion TEXT,
platform TEXT, vehicleId TEXT, appProfile TEXT, category TEXT NOT NULL, message TEXT,
details TEXT, kind TEXT NOT NULL DEFAULT 'support'
);
CREATE INDEX IF NOT EXISTS events_receivedAt_idx ON events(receivedAt);
CREATE INDEX IF NOT EXISTS events_vehicleId_idx ON events(vehicleId);
CREATE TABLE IF NOT EXISTS installs (vehicleId TEXT PRIMARY KEY, firstSeenAt TEXT NOT NULL, lastSeenAt TEXT NOT NULL,
appVersion TEXT, platform TEXT, manufacturer TEXT, carModel TEXT, carBuild TEXT, appProfile TEXT);
CREATE TABLE IF NOT EXISTS crashes (id TEXT PRIMARY KEY, receivedAt TEXT NOT NULL, vehicleId TEXT, appVersion TEXT, platform TEXT,
manufacturer TEXT, carModel TEXT, carBuild TEXT, appProfile TEXT, exceptionType TEXT, message TEXT, stack TEXT);
`);
try { fs.chmodSync(DATABASE_FILE, 0o600); } catch (_) {}
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
try { fs.chmodSync(DATA_DIR, 0o700); } catch (_) {}
// Admin password is injected from the credential store by the service launcher;
// never persist credentials beside application data. Session signing key is ephemeral.
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
const SESSION_SECRET = randomBytes(32).toString('hex');
function json(res, status, body) {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer' });
res.end(JSON.stringify(body));
}
function readBody(req, limit) {
return new Promise((resolve, reject) => {
let data = ''; let size = 0;
req.on('data', chunk => {
size += chunk.length;
if (size > (limit || MAX_BODY)) { reject(Object.assign(new Error('request too large'), { status: 413 })); req.destroy(); return; }
data += chunk.toString('utf8');
});
req.on('end', () => resolve(data));
req.on('error', reject);
});
}
function readJsonBody(req, limit) {
return readBody(req, limit).then(text => { try { return JSON.parse(text || '{}'); } catch (_) { throw Object.assign(new Error('invalid JSON'), { status: 400 }); } });
}
function safeText(value, limit) {
return typeof value === 'string' ? value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, limit) : '';
}
function loopback(req) {
const addr = req.socket.remoteAddress || '';
return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
}
function loadConfig() {
try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); }
catch (_) { return { schema: 1, enabled: false, uploadUrl: '', announcement: null, changelog: [] }; }
}
function saveConfig(config) {
const tmp = CONFIG_FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n');
fs.renameSync(tmp, CONFIG_FILE);
}
function registerInstall(event) {
const config = loadConfig();
if (config.telemetryEnabled === false) return false;
if (config.telemetryEnabled === undefined) { config.telemetryEnabled = true; saveConfig(config); }
const id = safeText(event.vehicleId, 80).replace(/[^a-zA-Z0-9._-]/g, '');
if (!id) return false;
const receivedAt = new Date().toISOString();
const values = [safeText(event.appVersion,40), safeText(event.platform,60), safeText(event.manufacturer,80), safeText(event.carModel,100), safeText(event.carBuild,180), safeText(event.appProfile,100)];
db.prepare(`INSERT INTO installs(vehicleId,firstSeenAt,lastSeenAt,appVersion,platform,manufacturer,carModel,carBuild,appProfile)
VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(vehicleId) DO UPDATE SET lastSeenAt=excluded.lastSeenAt,appVersion=excluded.appVersion,
platform=excluded.platform,manufacturer=excluded.manufacturer,carModel=excluded.carModel,carBuild=excluded.carBuild,appProfile=excluded.appProfile`)
.run(id,receivedAt,receivedAt,...values);
return true;
}
function insertCrash(input) {
const config = loadConfig();
if (config.telemetryEnabled === false) return false;
if (config.telemetryEnabled === undefined) { config.telemetryEnabled = true; saveConfig(config); }
const fields = [safeText(input.vehicleId,80),safeText(input.appVersion,40),safeText(input.platform,60),safeText(input.manufacturer,80),safeText(input.carModel,100),safeText(input.carBuild,180),safeText(input.appProfile,100),safeText(input.exceptionType,160),safeText(input.message,2000),safeText(input.stack,12000)];
if (!fields[0] || !fields[7]) return false;
db.prepare(`INSERT INTO crashes(id,receivedAt,vehicleId,appVersion,platform,manufacturer,carModel,carBuild,appProfile,exceptionType,message,stack)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(randomUUID(),new Date().toISOString(),...fields);
return true;
}
function analyticsPage() {
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>MG Utility Analytics</title><style>
:root{color-scheme:dark;--bg:#0b1115;--panel:#111a20;--line:#26383e;--text:#edf5f2;--muted:#93a7a7;--teal:#59e0c0;--red:#ff7c79}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,sans-serif}.shell{max-width:1100px;margin:auto;padding:20px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:15px;padding:18px;margin:14px 0}.row{display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap}.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.stat{padding:16px;background:#0d1519;border:1px solid var(--line);border-radius:12px}.stat small{color:var(--muted)}.stat b{display:block;font-size:28px}.entry{border-top:1px solid var(--line);padding:14px 0}.muted{color:var(--muted);font-size:13px}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#080e11;padding:14px;border-radius:10px;max-height:55vh;overflow:auto;font:12px/1.5 ui-monospace,monospace}button,input{font:inherit;color:inherit;background:#162329;border:1px solid var(--line);border-radius:10px;padding:10px 13px}button{cursor:pointer}button.primary{background:var(--teal);color:#06221d;font-weight:700}input{width:min(100%,340px)}#login{max-width:420px;margin:12vh auto}@media(max-width:650px){.stats{grid-template-columns:1fr 1fr}.shell{padding:14px}}
</style></head><body><main class="shell"><header class="row"><div><strong>MG Utility · Compatibility analytics</strong><div class="muted">Anonymous install fingerprints, crash summaries, and voluntary diagnostics</div></div><button id="logout" hidden>Sign out</button></header>
<section id="login" class="panel" hidden><h2>Admin sign in</h2><form id="loginForm"><input id="pw" type="password" autocomplete="current-password" placeholder="Admin password" required><button class="primary">Sign in</button><p id="loginMsg" class="muted"></p></form></section>
<section id="app" hidden><div class="stats"><div class="stat"><small>Known app installs</small><b id="installs">—</b></div><div class="stat"><small>Car models</small><b id="models">—</b></div><div class="stat"><small>Crash reports</small><b id="crashes">—</b></div></div>
<section class="panel"><div class="row"><div><h2>Car/build fingerprints</h2><div class="muted">Random app-install IDs; no VIN or hardware ID.</div></div><button id="copyFleet">Copy fleet summary</button></div><div id="fleet"></div></section>
<section class="panel"><div class="row"><div><h2>Crash reports</h2><div class="muted">Crash summaries captured locally then sent on next launch.</div></div><button id="copyCrashes">Copy crash summary</button></div><div id="crashList"></div></section>
<section class="panel"><div class="row"><div><h2>User-submitted diagnostics</h2><div class="muted">Only uploaded after the user requests it in Settings.</div><button id="copyReports">Copy report bundle</button></div></div><div id="reports"></div></section></section></main>
<script>const $=id=>document.getElementById(id);let data={};async function api(path,opts={}){const r=await fetch(path,{credentials:'same-origin',...opts});return{status:r.status,body:await r.json().catch(()=>({}))}}function copy(x){navigator.clipboard.writeText(JSON.stringify(x,null,2)).then(()=>alert('Copied'))}function card(host,title,meta,detail){const d=document.createElement('article');d.className='entry';const h=document.createElement('strong');h.textContent=title;const m=document.createElement('div');m.className='muted';m.textContent=meta;d.append(h,m);if(detail){const p=document.createElement('pre');p.textContent=detail;d.append(p)}host.append(d)}async function load(){const r=await api('/admin/api/analytics');if(r.status!==200)return;data=r.body;const installs=data.installs||[],crashes=data.crashes||[],reports=data.events||[];$('installs').textContent=data.stats?.activeInstalls||0;$('models').textContent=new Set(installs.map(x=>x.carModel).filter(Boolean)).size;$('crashes').textContent=data.stats?.crashReports||0;const f=$('fleet');f.textContent='';installs.forEach(x=>card(f,x.carModel||'Unknown model',[x.manufacturer,x.platform,'app '+x.appVersion,'first '+x.firstSeenAt,'last '+x.lastSeenAt].filter(Boolean).join(' · '),JSON.stringify(x,null,2)));if(!installs.length)f.textContent='No installs yet.';const c=$('crashList');c.textContent='';crashes.forEach(x=>card(c,x.exceptionType+': '+x.message,[x.carModel,x.manufacturer,x.appVersion,x.platform,x.receivedAt].filter(Boolean).join(' · '),JSON.stringify(x,null,2)));if(!crashes.length)c.textContent='No crash reports yet.';const e=$('reports');e.textContent='';reports.forEach(x=>card(e,x.message||x.category,[x.appVersion,x.platform,x.receivedAt].filter(Boolean).join(' · '),x.details));if(!reports.length)e.textContent='No detailed uploads yet.'}
async function check(){const r=await api('/admin/api/session');$('login').hidden=!!r.body.authorized;$('app').hidden=!r.body.authorized;$('logout').hidden=!r.body.authorized;if(r.body.authorized)load()}$('loginForm').onsubmit=async ev=>{ev.preventDefault();const r=await api('/admin/api/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({password:$('pw').value})});if(r.status===200){$('pw').value='';check()}else $('loginMsg').textContent=r.body.error||'Login failed'};$('logout').onclick=async()=>{await api('/admin/api/logout',{method:'POST'});check()};$('copyFleet').onclick=()=>copy(data.installs||[]);$('copyCrashes').onclick=()=>copy(data.crashes||[]);$('copyReports').onclick=()=>copy(data.events||[]);check();</script></body></html>`;
}
function readEvents() {
return db.prepare('SELECT * FROM events ORDER BY receivedAt ASC').all();
}
function appendEvent(event) {
db.prepare(`INSERT INTO events(id,receivedAt,product,appVersion,platform,vehicleId,appProfile,category,message,details,kind)
VALUES(?,?,?,?,?,?,?,?,?,?,?)`).run(event.id,event.receivedAt,event.product,event.appVersion,event.platform,event.vehicleId,event.appProfile,event.category,event.message,event.details,event.kind || 'support');
const old = db.prepare('SELECT id FROM events ORDER BY receivedAt DESC LIMIT -1 OFFSET ?').all(MAX_EVENTS);
const remove = db.prepare('DELETE FROM events WHERE id=?');
for (const row of old) remove.run(row.id);
}
// --- Sessions (HMAC-signed token; no server-side store) ---
function sign(value) { return createHmac('sha256', SESSION_SECRET).update(value).digest('base64url'); }
function issueSession() {
const payload = String(Date.now() + SESSION_TTL_MS);
return payload + '.' + sign(payload);
}
function validSession(token) {
if (typeof token !== 'string') return false;
const dot = token.lastIndexOf('.');
if (dot < 1) return false;
const payload = token.slice(0, dot), mac = token.slice(dot + 1);
const expected = sign(payload);
if (mac.length !== expected.length) return false;
try { if (!timingSafeEqual(Buffer.from(mac), Buffer.from(expected))) return false; } catch (_) { return false; }
return Number(payload) > Date.now();
}
function cookies(req) {
const out = {};
for (const part of String(req.headers.cookie || '').split(';')) {
const eq = part.indexOf('=');
if (eq > 0) out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
}
return out;
}
const loginFails = new Map();
function loginAllowed(ip) {
const entry = loginFails.get(ip);
return !entry || entry.until < Date.now();
}
function recordLoginFail(ip) {
const entry = loginFails.get(ip) || { count: 0, until: 0 };
entry.count += 1;
entry.until = Date.now() + Math.min(5 * entry.count, 30) * 1000;
loginFails.set(ip, entry);
}
function authorized(req) { return validSession(cookies(req)[SESSION_COOKIE]); }
// --- Dashboard (single page; all dynamic content rendered via textContent) ---
function legacyPage() {
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow"><title>MG Utility Telemetry</title>
<style>
:root{color-scheme:dark}
body{margin:0;font:14px/1.45 system-ui,sans-serif;background:#0e1116;color:#e6e6e6}
header{display:flex;gap:12px;align-items:center;padding:12px 20px;background:#161b22;border-bottom:1px solid #232a33}
header h1{font-size:16px;margin:0 auto 0 0}
main{max-width:1100px;margin:0 auto;padding:20px}
button,input,select,textarea{background:#1c232d;color:#e6e6e6;border:1px solid #333c47;border-radius:6px;padding:6px 10px;font:inherit}
button{cursor:pointer}button:hover{background:#253040}
table{width:100%;border-collapse:collapse;margin-top:12px}
th,td{text-align:left;padding:8px 10px;border-bottom:1px solid #232a33;vertical-align:top}
th{color:#9aa4b0;font-weight:600;font-size:12px;text-transform:uppercase}
tr.ev{cursor:pointer}tr.ev:hover{background:#161b22}
pre{white-space:pre-wrap;word-break:break-word;background:#161b22;border:1px solid #232a33;border-radius:6px;padding:10px;max-height:320px;overflow:auto}
.meta{color:#9aa4b0;font-size:12px}
.hidden{display:none}
.card{background:#161b22;border:1px solid #232a33;border-radius:8px;padding:16px;margin-bottom:16px}
.card h2{margin-top:0}
label{display:block;margin:8px 0 4px;color:#9aa4b0;font-size:12px;text-transform:uppercase}
label.inline{display:inline;margin:0;text-transform:none;color:#e6e6e6}
</style></head><body>
<header><h1>MG Utility Telemetry</h1><span id="who" class="meta"></span><button id="logout" class="hidden">Log out</button></header>
<main>
<section id="login" class="card hidden">
<h2>Admin log in</h2>
<form id="loginForm"><label for="pw">Password</label><input id="pw" type="password" autocomplete="current-password" style="width:280px">
<button type="submit">Log in</button><span id="loginMsg" class="meta" style="margin-left:10px"></span></form>
<p class="meta">Admin access requires the configured credential-store password.</p>
</section>
<section id="app" class="hidden">
<div class="card">
<h2>Events</h2>
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
<select id="product"><option value="">All products</option></select>
<select id="category"><option value="">All categories</option></select>
<button id="refresh">Refresh</button>
<label class="inline"><input type="checkbox" id="auto"> Auto-refresh 10s</label>
<span id="status" class="meta"></span>
</div>
<table><thead><tr><th style="width:160px">Received</th><th style="width:120px">Product</th><th style="width:90px">Version</th><th style="width:170px">Category</th><th>Message</th></tr></thead>
<tbody id="rows"></tbody></table>
</div>
<div class="card">
<h2>In-app announcement</h2>
<textarea id="announcement" rows="3" style="width:100%"></textarea>
<div style="margin-top:10px;display:flex;gap:10px;align-items:center">
<button id="saveAnnouncement">Save announcement</button><span id="annStatus" class="meta"></span>
</div>
</div>
<div class="card">
<h2>Client diagnostics configuration</h2>
<label class="inline"><input type="checkbox" id="enabled"> Enable diagnostic uploads</label>
<label for="uploadUrl">Upload endpoint base URL (HTTPS)</label>
<input id="uploadUrl" type="url" placeholder="https://your-host/" style="width:min(100%,600px)">
<div style="margin-top:10px;display:flex;gap:10px;align-items:center"><button id="saveConfig">Save client config</button><span id="cfgStatus" class="meta"></span></div>
</div>
</section>
</main>
<script>
const $=id=>document.getElementById(id);
function esc(node,text){node.textContent=text==null?'':String(text);return node}
let timer=null;
async function api(path,opts){const r=await fetch(path,Object.assign({credentials:'same-origin'},opts));return{status:r.status,body:await r.json().catch(()=>({}))}}
async function check(){
const c=await api('/admin/api/session');
if(c.body.authorized){$('login').classList.add('hidden');$('app').classList.remove('hidden');$('logout').classList.remove('hidden');$('who').textContent='admin';
loadEvents();loadConfig();
if(!$('auto').dataset.bound){$('auto').dataset.bound='1';$('auto').onchange=()=>{if($('auto').checked)timer=setInterval(loadEvents,10000);else clearInterval(timer)};}
} else {$('app').classList.add('hidden');$('login').classList.remove('hidden');$('logout').classList.add('hidden');$('who').textContent='';}
}
async function loadEvents(){
$('status').textContent='loading…';
const q=new URLSearchParams();if($('product').value)q.set('product',$('product').value);if($('category').value)q.set('category',$('category').value);
const r=await api('/admin/api/events?'+q);
if(r.status!==200){$('status').textContent='failed ('+r.status+')';return}
const events=r.body.events||[];
$('status').textContent=events.length+' event(s)';
const cats=new Set(),products=new Set();
const tbody=$('rows');tbody.textContent='';
for(const e of events.slice().reverse()){
products.add(e.product||'mg-utility');cats.add(e.category||'');
const tr=document.createElement('tr');tr.className='ev';
const td=(w,t)=>{const d=document.createElement('td');esc(d,t);if(w)d.style.width=w;return d};
tr.append(td('160px',(e.receivedAt||'').replace('T',' ').slice(0,19)),td('120px',e.product),td('90px',e.appVersion),td('170px',e.category),td(null,e.message));
tr.onclick=()=>show(e);tbody.append(tr);
}
fill($('product'),[...products]);fill($('category'),[...cats]);
}
function fill(sel,items){const cur=sel.value;for(const it of items){if(![...sel.options].some(o=>o.value===it)){const o=document.createElement('option');o.value=it;o.textContent=it;sel.append(o)}}sel.value=cur}
function show(e){
const old=document.getElementById('detail');if(old)old.remove();
const tr=document.createElement('tr');tr.id='detail';const td=document.createElement('td');td.colSpan=5;
const pre=document.createElement('pre');esc(pre,JSON.stringify({details:e.details,platform:e.platform,appVersion:e.appVersion,id:e.id,receivedAt:e.receivedAt},null,2));
td.append(pre);tr.append(td);$('rows').append(tr);
}
async function loadConfig(){const c=await api('/admin/api/config');if(c.status===200){$('announcement').value=c.body.announcement?c.body.announcement.text:'';$('enabled').checked=!!c.body.enabled;$('uploadUrl').value=c.body.uploadUrl||''}}
$('refresh').onclick=loadEvents;
$('logout').onclick=async()=>{await api('/admin/api/logout',{method:'POST'});clearInterval(timer);check()};
$('loginForm').onsubmit=async ev=>{ev.preventDefault();
const r=await api('/admin/api/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({password:$('pw').value})});
if(r.status===200){$('pw').value='';$('loginMsg').textContent='';check()}else{$('loginMsg').textContent=r.body.error||'login failed'}};
$('saveAnnouncement').onclick=async()=>{
const r=await api('/admin/api/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({announcement:$('announcement').value})});
$('annStatus').textContent=r.status===200?'saved':'save failed ('+r.status+')';setTimeout(()=>{$('annStatus').textContent=''},3000)};
$('saveConfig').onclick=async()=>{
const r=await api('/admin/api/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({enabled:$('enabled').checked,uploadUrl:$('uploadUrl').value})});
$('cfgStatus').textContent=r.status===200?'saved':'save failed ('+r.status+')';setTimeout(()=>{$('cfgStatus').textContent=''},3000)};
check();
</script></body></html>`;
}
function page() { return fs.readFileSync(path.join(__dirname, 'dashboard.html'), 'utf8'); }
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const p = url.pathname;
const ip = req.socket.remoteAddress || '';
if (req.method === 'GET' && p === '/health') return json(res, 200, { ok: true, service: 'mg-utility-telemetry' });
// Public client config: fetched by every app instance on startup.
if (req.method === 'GET' && p === '/v1/config') {
const c = loadConfig();
return json(res, 200, { schema: 1, enabled: !!c.enabled, telemetryEnabled: c.telemetryEnabled !== false, uploadUrl: String(c.uploadUrl || ''), announcement: c.announcement || null, changelog: Array.isArray(c.changelog) ? c.changelog.slice(-50) : [] });
}
// Minimal startup compatibility snapshot and crash-only intake.
if (req.method === 'POST' && p === '/v1/install') {
try {
const input = await readJsonBody(req, 8192);
if (!registerInstall(input)) return json(res, 400, { error: 'invalid install identity' });
return json(res, 202, { accepted: true });
} catch (error) { return json(res, error.status || 400, { error: 'invalid request' }); }
}
if (req.method === 'POST' && p === '/v1/crashes') {
try {
const input = await readJsonBody(req, 20000);
if (!insertCrash(input)) return json(res, 400, { error: 'invalid crash report' });
return json(res, 202, { accepted: true });
} catch (error) { return json(res, error.status || 400, { error: 'invalid request' }); }
}
// Public intake endpoint used by the app's explicit upload action.
if (req.method === 'POST' && p === '/v1/events') {
try {
const input = await readJsonBody(req);
if (!loadConfig().enabled) return json(res, 403, { error: 'intake disabled' });
const product = safeText(input.product, 60).replace(/[^a-zA-Z0-9._-]/g, '') || 'mg-utility';
const vehicleId = safeText(input.vehicleId, 80).replace(/[^a-zA-Z0-9._-]/g, '');
const event = {
id: randomUUID(), receivedAt: new Date().toISOString(),
product, appVersion: safeText(input.appVersion, 40), platform: safeText(input.platform, 60),
vehicleId, appProfile: safeText(input.appProfile, 80),
category: safeText(input.category, 40), message: safeText(input.message, 4000),
details: safeText(input.details, 60000), kind: 'support'
};
if (!event.category || (!event.message && !event.details)) return json(res, 400, { error: 'category and message or details required' });
if (!loadConfig().enabled) return json(res, 403, { error: 'intake disabled' });
appendEvent(event);
return json(res, 202, { accepted: true, id: event.id });
} catch (error) { return json(res, error.status || 400, { error: error.status === 413 ? 'request too large' : 'invalid request' }); }
}
// --- Admin dashboard ---
if (req.method === 'GET' && (p === '/admin' || p === '/admin/')) return sendHtml(res, page());
if (req.method === 'GET' && p === '/admin/analytics') return sendHtml(res, analyticsPage());
if (req.method === 'POST' && p === '/admin/api/login') {
if (!loginAllowed(ip)) return json(res, 429, { error: 'too many attempts; wait a moment' });
let body = {}; try { body = JSON.parse((await readBody(req, 4096)) || '{}'); } catch (_) { return json(res, 400, { error: 'invalid request' }); }
const pw = Buffer.from(String(body.password || ''));
if (!ADMIN_PASSWORD) return json(res, 503, { error: 'admin login is not configured' });
const expected = Buffer.from(ADMIN_PASSWORD);
if (pw.length === expected.length && timingSafeEqual(pw, expected)) {
res.setHeader('set-cookie', `${SESSION_COOKIE}=${issueSession()}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_TTL_MS / 1000}`);
loginFails.delete(ip);
return json(res, 200, { ok: true });
}
recordLoginFail(ip);
return json(res, 401, { error: 'invalid password' });
}
if (req.method === 'POST' && p === '/admin/api/logout') {
res.setHeader('set-cookie', `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
return json(res, 200, { ok: true });
}
if (p === '/admin/api/session') return json(res, 200, { authorized: authorized(req) });
if (p.startsWith('/admin/api/')) {
if (!authorized(req)) return json(res, 401, { error: 'unauthorized' });
if (req.method === 'GET' && p === '/admin/api/analytics') {
const installs = db.prepare('SELECT * FROM installs ORDER BY lastSeenAt DESC').all();
const crashes = db.prepare('SELECT * FROM crashes ORDER BY receivedAt DESC LIMIT 500').all();
const events = db.prepare('SELECT * FROM events ORDER BY receivedAt DESC LIMIT 500').all();
return json(res, 200, { installs, crashes, events, stats: { activeInstalls: db.prepare('SELECT COUNT(*) AS n FROM installs').get().n, crashReports: db.prepare('SELECT COUNT(*) AS n FROM crashes').get().n } });
}
if (req.method === 'GET' && p === '/admin/api/events') {
const product = url.searchParams.get('product') || '';
const category = url.searchParams.get('category') || '';
const vehicleId = url.searchParams.get('vehicleId') || '';
const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
const all = readEvents();
let events = all.slice();
if (product) events = events.filter(e => e.product === product);
if (category) events = events.filter(e => e.category === category);
if (vehicleId) events = events.filter(e => e.vehicleId === vehicleId);
const productCounts = new Map();
for (const event of all) {
const name = event.product || 'mg-utility';
productCounts.set(name, (productCounts.get(name) || 0) + 1);
}
const products = [...productCounts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => a.name.localeCompare(b.name));
const vehicleCounts = new Map();
for (const event of all) if (event.vehicleId) {
const row = vehicleCounts.get(event.vehicleId) || { id: event.vehicleId, appProfile: event.appProfile || '', count: 0 };
row.count++;
if (!row.appProfile && event.appProfile) row.appProfile = event.appProfile;
vehicleCounts.set(event.vehicleId, row);
}
const vehicles = [...vehicleCounts.values()].sort((a, b) => a.id.localeCompare(b.id));
const categories = [...new Set(all.map(e => e.category).filter(Boolean))].sort();
const dayStart = Date.now() - 86400000;
const stats = {
total: all.length,
last24h: all.filter(e => new Date(e.receivedAt).getTime() >= dayStart).length,
builds: new Set(all.map(e => e.appVersion).filter(Boolean)).size,
products: products.length,
vehicles: vehicles.length,
productList: products
};
events.reverse();
return json(res, 200, { events: events.slice(offset, offset + limit), total: events.length, hasMore: offset + limit < events.length, products, vehicles, categories, stats });
}
if (req.method === 'GET' && p === '/admin/api/export') {
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-disposition': 'attachment; filename="mg-utility-reports.json"', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
return res.end(JSON.stringify({ exportedAt: new Date().toISOString(), events: readEvents() }, null, 2));
}
if (req.method === 'DELETE' && p.startsWith('/admin/api/events/')) {
const id = p.slice('/admin/api/events/'.length);
if (!/^[a-f0-9-]{36}$/i.test(id)) return json(res, 400, { error: 'invalid report id' });
const result = db.prepare('DELETE FROM events WHERE id=?').run(id);
if (result.changes === 0) return json(res, 404, { error: 'report not found' });
return json(res, 200, { deleted: true });
}
if (req.method === 'GET' && p === '/admin/api/config') {
const c = loadConfig();
return json(res, 200, { announcement: c.announcement || null, enabled: !!c.enabled, telemetryEnabled: c.telemetryEnabled !== false, uploadUrl: String(c.uploadUrl || ''), changelog: c.changelog || [] });
}
if (req.method === 'POST' && p === '/admin/api/config') {
let body = {}; try { body = JSON.parse((await readBody(req, 65536)) || '{}'); } catch (_) { return json(res, 400, { error: 'invalid request' }); }
const c = loadConfig();
if (typeof body.announcement === 'string') {
c.announcement = body.announcement.trim() ? { text: body.announcement.trim().slice(0, 2000), updatedAt: new Date().toISOString() } : null;
}
if (typeof body.enabled === 'boolean') c.enabled = body.enabled;
if (typeof body.telemetryEnabled === 'boolean') c.telemetryEnabled = body.telemetryEnabled;
if (typeof body.uploadUrl === 'string') {
const value = body.uploadUrl.trim();
if (value && !/^https:\/\//i.test(value)) return json(res, 400, { error: 'uploadUrl must use HTTPS' });
c.uploadUrl = value;
}
if (Array.isArray(body.changelog)) {
if (body.changelog.length > 50) return json(res, 400, { error: 'maximum 50 release notes' });
c.changelog = body.changelog.map(item => ({
version: safeText(item && item.version, 40),
title: safeText(item && item.title, 120),
notes: safeText(item && item.notes, 2000)
})).filter(item => item.version || item.title || item.notes);
}
saveConfig(c);
return json(res, 200, { ok: true, announcement: c.announcement });
}
}
return json(res, 404, { error: 'not found' });
});
function sendHtml(res, html) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer', 'content-security-policy': "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'" });
res.end(html);
}
server.listen(PORT, HOST, () => console.log(`MG Utility telemetry listening on ${HOST}:${PORT}`));
-73
View File
@@ -1,73 +0,0 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawn } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
test('health, config and event intake/readback', async t => {
const port = 22000 + Math.floor(Math.random() * 20000);
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mg-telemetry-'));
const configFile = path.join(dataDir, 'config.json');
fs.writeFileSync(configFile, JSON.stringify({ schema: 1, enabled: true, telemetryEnabled: true, uploadUrl: 'https://test.invalid/', announcement: null, changelog: [] }));
const child = spawn(process.execPath, ['server.js'], { cwd: __dirname, env: { ...process.env, HOST: '127.0.0.1', PORT: String(port), DATA_DIR: dataDir, CONFIG_FILE: configFile, ADMIN_PASSWORD: 'test-only-password' }, stdio: 'ignore' });
t.after(() => { child.kill(); fs.rmSync(dataDir, { recursive: true, force: true }); });
async function request(method, route, body, cookie) {
return new Promise((resolve, reject) => {
const headers = body ? { 'content-type': 'application/json' } : {};
if (cookie) headers.cookie = cookie;
const req = http.request({ host: '127.0.0.1', port, path: route, method, headers }, res => {
let data = ''; res.on('data', c => data += c); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data), headers: res.headers }));
});
req.on('error', reject); if (body) req.write(JSON.stringify(body)); req.end();
});
}
let health;
for (let i = 0; i < 40; i++) { try { health = await request('GET', '/health'); break; } catch (_) { await new Promise(r => setTimeout(r, 50)); } }
assert.equal(health.status, 200);
assert.equal((await request('GET', '/v1/config')).body.schema, 1);
assert.equal((await request('GET', '/admin/api/events')).status, 401);
const login = await request('POST', '/admin/api/login', { password: 'test-only-password' });
assert.equal(login.status, 200);
const cookie = login.headers['set-cookie'][0].split(';')[0];
const vehicleId = 'd49300a0-85b2-4aa1-a8ee-27ac227d53a5';
const startup = await request('POST', '/v1/install', { vehicleId, appVersion: '0.3', platform: 'android-28', manufacturer: 'MG', carModel: 'MG4', carBuild: 'test-build', appProfile: 'unknown-read-only' });
assert.equal(startup.status, 202);
const crash = await request('POST', '/v1/crashes', { vehicleId, appVersion: '0.3', platform: 'android-28', manufacturer: 'MG', carModel: 'MG4', carBuild: 'test-build', exceptionType: 'IllegalStateException', message: 'synthetic', stack: 'synthetic stack' });
assert.equal(crash.status, 202);
const analyticsPage = await new Promise((resolve, reject) => http.get({ host: '127.0.0.1', port, path: '/admin/analytics' }, res => { let data = ''; res.on('data', c => data += c); res.on('end', () => resolve({ status: res.statusCode, body: data })); }).on('error', reject));
assert.equal(analyticsPage.status, 200);
assert.match(analyticsPage.body, /MG Utility · Compatibility analytics/);
assert.match(analyticsPage.body, /copyFleet/);
const analytics = await request('GET', '/admin/api/analytics', null, cookie);
assert.equal(analytics.body.stats.activeInstalls, 1);
assert.equal(analytics.body.installs[0].carModel, 'MG4');
assert.ok(fs.existsSync(path.join(dataDir, 'analytics.sqlite')));
assert.equal(analytics.body.stats.crashReports, 1);
assert.equal((await request('GET', '/admin/api/analytics', null, cookie)).body.events.length, 0);
assert.equal((await request('GET', '/admin/api/analytics')).status, 401);
const submitted = await request('POST', '/v1/events', { product: 'saic-demo', vehicleId, appProfile: 'mg4-luxury-2022-saic-v2', category: 'diagnostic', message: 'test event', details: 'safe test' });
assert.equal(submitted.status, 202);
const readback = await request('GET', '/admin/api/events', null, cookie);
assert.equal(readback.body.events.length, 1);
assert.equal(readback.body.events[0].message, 'test event');
assert.equal(readback.body.events[0].product, 'saic-demo');
assert.equal(readback.body.events[0].vehicleId, vehicleId);
assert.equal(readback.body.events[0].appProfile, 'mg4-luxury-2022-saic-v2');
assert.equal(readback.body.stats.vehicles, 1);
assert.equal((await request('GET', '/admin/api/events?vehicleId=' + vehicleId, null, cookie)).body.total, 1);
assert.equal(readback.body.stats.total, 1);
assert.equal(readback.body.stats.productList[0].name, 'saic-demo');
const deleted = await request('DELETE', '/admin/api/events/' + readback.body.events[0].id, null, cookie);
assert.equal(deleted.status, 200);
assert.equal((await request('GET', '/admin/api/events', null, cookie)).body.events.length, 0);
const config = await request('POST', '/admin/api/config', { enabled: false, telemetryEnabled: true, uploadUrl: 'https://test.invalid/', announcement: 'test announcement', changelog: [{ version: '1.2', title: 'Test release', notes: 'test notes' }] }, cookie);
assert.equal(config.status, 200);
const publicConfig = (await request('GET', '/v1/config')).body;
assert.equal(publicConfig.enabled, false);
assert.equal(publicConfig.telemetryEnabled, true);
assert.equal(publicConfig.changelog[0].title, 'Test release');
assert.equal((await request('POST', '/v1/events', {})).status, 403);
});
+21
View File
@@ -0,0 +1,21 @@
package cloud.molberg.mgutility;
public final class AudioLevelTest {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); System.out.println("ok - " + what); }
public static void main(String[] args) {
short[] silence = new short[1000];
check(AudioLevel.rms(silence, 1000) == 0, "silence rms is zero");
check(AudioLevel.verdict(AudioLevel.peak(silence, 1000)).startsWith("SILENT"), "silence flagged");
short[] loud = new short[1000]; for (int i = 0; i < loud.length; i++) loud[i] = (short) (i % 2 == 0 ? 16384 : -16384);
check(Math.abs(AudioLevel.rms(loud, 1000) - 0.5) < 1e-6, "square wave rms is half scale");
check(Math.abs(AudioLevel.peak(loud, 1000) - 0.5) < 1e-6, "peak is half scale");
check(Math.abs(AudioLevel.dbfs(0.5) + 6.0206) < 1e-3, "-6 dBFS at half scale");
check(AudioLevel.dbfs(0) == -100.0, "dbfs floor");
check(AudioLevel.verdict(0.5).startsWith("OK"), "loud is OK");
short[] faint = new short[100]; faint[3] = 200;
check(AudioLevel.verdict(AudioLevel.peak(faint, 100)).startsWith("VERY QUIET"), "faint flagged quiet");
short[] neg = { Short.MIN_VALUE };
check(AudioLevel.peak(neg, 1) == 1.0, "min value peak does not overflow");
check(AudioLevel.rms(loud, 0) == 0, "zero count safe");
}
}
+49
View File
@@ -0,0 +1,49 @@
package cloud.molberg.mgutility;
import java.util.*;
public final class BackupCodecTest {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); System.out.println("ok - " + what); }
public static void main(String[] args) throws Exception {
Map<String, Map<String, Object>> files = new LinkedHashMap<String, Map<String, Object>>();
Map<String, Object> ui = new LinkedHashMap<String, Object>();
ui.put("theme", 3); ui.put("dark", true); ui.put("ts", 1730000000000L);
ui.put("scale", 1.25f); ui.put("name", "MG \"4\" \u00e6\u00f8\u00e5\nline2");
ui.put("set", new TreeSet<String>(Arrays.asList("b", "a", "c")));
files.put("ui_state", ui);
Map<String, Object> trips = new LinkedHashMap<String, Object>();
trips.put("interval", 5000);
files.put("trip_tracker", trips);
String json = BackupCodec.encode(files, 1234L, "0.3.0.9");
Map<String, Map<String, Object>> back = BackupCodec.decode(json);
check(back.equals(files), "round trip preserves every type exactly");
check(back.get("ui_state").get("theme") instanceof Integer, "int stays int");
check(back.get("ui_state").get("ts") instanceof Long, "long stays long");
check(back.get("ui_state").get("scale") instanceof Float, "float stays float");
check(back.get("ui_state").get("set") instanceof Set, "string set stays set");
check(BackupCodec.countKeys(files) == 7, "key count");
check(BackupCodec.createdAt(json) == 1234L, "created_at");
Map<String, Map<String, Object>> reordered = new LinkedHashMap<String, Map<String, Object>>();
reordered.put("trip_tracker", new LinkedHashMap<String, Object>(trips));
Map<String, Object> ui2 = new LinkedHashMap<String, Object>(); List<String> keys = new ArrayList<String>(ui.keySet());
Collections.reverse(keys); for (String k : keys) ui2.put(k, ui.get(k));
reordered.put("ui_state", ui2);
check(BackupCodec.fingerprint(files).equals(BackupCodec.fingerprint(reordered)), "fingerprint ignores ordering");
ui2.put("theme", 4);
check(!BackupCodec.fingerprint(files).equals(BackupCodec.fingerprint(reordered)), "fingerprint detects a change");
boolean rejected = false;
try { BackupCodec.decode("{\"schema\":1,\"type\":\"other\",\"files\":{}}"); } catch (IllegalArgumentException e) { rejected = true; }
check(rejected, "wrong type rejected");
rejected = false;
try { BackupCodec.decode("{\"schema\":99,\"type\":\"mg-utility-settings-backup\",\"files\":{}}"); } catch (IllegalArgumentException e) { rejected = true; }
check(rejected, "wrong schema rejected");
rejected = false;
try { BackupCodec.decode("not json"); } catch (org.json.JSONException e) { rejected = true; }
check(rejected, "corrupt file rejected");
check(BackupCodec.decode(BackupCodec.encode(new HashMap<String, Map<String, Object>>(), 1L, null)).isEmpty(), "empty backup decodes");
}
}
+26
View File
@@ -0,0 +1,26 @@
import cloud.molberg.mgutility.UsageDataPolicy;
public final class UsageDataPolicyTest {
public static void main(String[] args) {
String line = "1720000000.123 123 456 W MgServiceBridge: failed password=hunter2";
check(UsageDataPolicy.warning(line, 123, 0).contains("password=[REDACTED]"), "own warning redacted");
check(UsageDataPolicy.warning(line, 999, 0).isEmpty(), "other process excluded");
check(UsageDataPolicy.warning(line, 123, 1720000000.123).isEmpty(), "acknowledged warning excluded");
check(UsageDataPolicy.warning(line.replace("MgServiceBridge", "OtherApp"), 123, 0).isEmpty(), "unknown tag excluded");
check(UsageDataPolicy.warning(line.replace("MgServiceBridge", "MGDiagnostics"), 123, 0).isEmpty(), "uploader errors excluded");
check(UsageDataPolicy.warning(line.replace(" W ", " I "), 123, 0).isEmpty(), "informational logs excluded");
check(UsageDataPolicy.warning("malformed", 123, 0).isEmpty(), "malformed line excluded");
String safe = UsageDataPolicy.redact("token=abc Bearer xyz vin=LSJW1234567890123 https://example.test/?secret=x aa:bb:cc:dd:ee:ff", 1000);
check(!safe.contains("abc") && !safe.contains("xyz") && !safe.contains("LSJW") && !safe.contains("example.test") && !safe.contains("aa:bb"), "sensitive fields removed");
check(!UsageDataPolicy.redact("Authorization: Bearer sensitive-token", 1000).contains("sensitive-token"), "authorization bearer redacted");
check(!UsageDataPolicy.redact("{\"password\":\"secret phrase\",\"token\":\"abc\"}", 1000).contains("secret phrase"), "quoted credentials redacted");
check(UsageDataPolicy.redact(null, 10).isEmpty(), "null text");
check(UsageDataPolicy.redact("123456", 3).equals("123"), "bounded text");
check(UsageDataPolicy.timestamp(line) == 1720000000.123, "log timestamp");
System.out.println("UsageDataPolicyTest passed");
}
private static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
+10
View File
@@ -4,6 +4,7 @@ ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
OUT=$(mktemp -d)
trap 'rm -rf "$OUT"' EXIT
javac -source 8 -target 8 -d "$OUT" \
"$ROOT/src/cloud/molberg/mgutility/UsageDataPolicy.java" "$ROOT/tests/UsageDataPolicyTest.java" \
"$ROOT/src/cloud/molberg/mgutility/PushToTalkPress.java" "$ROOT/tests/PushToTalkPressTest.java" \
"$ROOT/src/cloud/molberg/mgutility/VehicleSettingsCatalog.java" \
"$ROOT/src/cloud/molberg/mgutility/VehicleSettingsProfile.java" \
@@ -31,6 +32,7 @@ javac -source 8 -target 8 -d "$OUT" \
"$ROOT/src/cloud/molberg/mgutility/plugin/PluginSignatureVerifier.java" "$ROOT/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndexParser.java" \
"$ROOT/tests/PluginSdkTest.java" "$ROOT/tests/PluginMarketplaceTest.java"
java -cp "$OUT" VehicleSettingsCatalogTest
java -cp "$OUT" UsageDataPolicyTest
java -cp "$OUT" cloud.molberg.mgutility.PushToTalkPressTest
java -cp "$OUT" VehicleSettingsCoordinatorTest
java -cp "$OUT" cloud.molberg.mgutility.VehiclePowerOffControllerTest
@@ -56,3 +58,11 @@ javac -source 8 -target 8 -d "$OUT/audio" \
"$ROOT/src/cloud/molberg/mgutility/LiquidSoundBalanceManager.java" \
"$ROOT/tests/LiquidAudioIntegrationTest.java"
java -cp "$OUT/audio" cloud.molberg.mgutility.LiquidAudioIntegrationTest
mkdir -p "$OUT/backup"
JSON_JAR=$(find "$HOME/.gradle" -name 'json-20180813.jar' 2>/dev/null | head -n 1)
javac -source 8 -target 8 -d "$OUT/backup" "$ROOT/src/cloud/molberg/mgutility/AudioLevel.java" "$ROOT/tests/AudioLevelTest.java"
java -cp "$OUT/backup" cloud.molberg.mgutility.AudioLevelTest
if [ -n "$JSON_JAR" ]; then
javac -source 8 -target 8 -cp "$JSON_JAR" -d "$OUT/backup" "$ROOT/src/cloud/molberg/mgutility/BackupCodec.java" "$ROOT/tests/BackupCodecTest.java"
java -cp "$OUT/backup:$JSON_JAR" cloud.molberg.mgutility.BackupCodecTest
fi