mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 11:36:05 +00:00
Compare commits
245 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c001febea | |||
| 9890f31d10 | |||
| 04e0dc26e1 | |||
| eb56e77600 | |||
| 1a50e7f0ac | |||
| 2a134babbc | |||
| 2180175040 | |||
| 856d1e5ea5 | |||
| ea5542f8eb | |||
| 40dea84085 | |||
| 89f7908359 | |||
| f02c4c57c3 | |||
| 5b0412bc2c | |||
| aa8d041a33 | |||
| 24bc132476 | |||
| f728b568ed | |||
| c4a2a91578 | |||
| a58d0117c6 | |||
| 439736e904 | |||
| 71510a62f3 | |||
| a65342574a | |||
| 783a697d95 | |||
| b8966330e0 | |||
| cb1b5dd88c | |||
| a1f063c703 | |||
| b65a1bb65c | |||
| d1cb0a418a | |||
| 5536d29cbf | |||
| 7bbb5a9f71 | |||
| a1bf57b71a | |||
| 87bcb5a519 | |||
| c72c8dcaf7 | |||
| bac4599d64 | |||
| 535761dbd5 | |||
| 5be521199f | |||
| f71acb08bd | |||
| d6905435ae | |||
| ba562c9047 | |||
| 6bcc49fc6f | |||
| 64847e906e | |||
| 75d458b06b | |||
| a76a96ccca | |||
| bfdbf4d811 | |||
| b068e593fc | |||
| d3ec833ab7 | |||
| 5e97123bdf | |||
| 2bcef51664 | |||
| 0f42b8b8ae | |||
| c67c95201b | |||
| e6f35158c5 | |||
| d541bfa838 | |||
| ef5deada83 | |||
| e1090d5427 | |||
| 335dd9c788 | |||
| c23518dae0 | |||
| 91f8deb3f3 | |||
| a40ae60abb | |||
| 5caa890523 | |||
| a3620f9e05 | |||
| dbda2d7d7c | |||
| b6a296ffea | |||
| ae3dfa2eb7 | |||
| bab1ca9dca | |||
| e1e8c4c63d | |||
| 5f49c87f4a | |||
| 01653f81e3 | |||
| a0764b9c96 | |||
| 94ac7673a5 | |||
| 5fe3dea4cc | |||
| 608f76f32c | |||
| a2cc7af695 | |||
| dfbe23e5b8 | |||
| 6ac7bd2d96 | |||
| a67361c6bd | |||
| 7a40225852 | |||
| 29816f81a9 | |||
| 4337969c2c | |||
| 6789ee1cb6 | |||
| 7ed15a77b4 | |||
| 4806c62976 | |||
| 3957b292be | |||
| 783f679124 | |||
| 7e1de86f0b | |||
| c13c288f00 | |||
| 89b67a791f | |||
| 2ee413368b | |||
| 1aa586d829 | |||
| 53833fd212 | |||
| a7adef5353 | |||
| bd11cd347d | |||
| b19bd8e709 | |||
| 8dedab0375 | |||
| cbd1800976 | |||
| 44f669cd0e | |||
| 1d052f725f | |||
| f7bad3c5b3 | |||
| 264f352502 | |||
| 32291ce8b4 | |||
| c35f39add1 | |||
| 993ed4b472 | |||
| e7db110417 | |||
| 011cc9f11f | |||
| 844d03a9cd | |||
| 1bfaf4ea98 | |||
| 6309064f40 | |||
| 7d3ed21a03 | |||
| f319b3610a | |||
| 81d27d8e8d | |||
| de7de4b8de | |||
| 340454cfc7 | |||
| 5f600cf263 | |||
| aa84d71302 | |||
| baa906fb6b | |||
| 53ebc9d632 | |||
| 332206089b | |||
| 57d0b42726 | |||
| d01f973e62 | |||
| d557f08e28 | |||
| 5dc1de0e5b | |||
| d2b12cd3dd | |||
| 64418489e2 | |||
| 7238f8ae25 | |||
| e525e0b838 | |||
| 2d95bf6744 | |||
| 41134cc455 | |||
| 27f12c2245 | |||
| 4796615439 | |||
| 154563f34d | |||
| 3365511b10 | |||
| c2c0535d52 | |||
| d6799d1205 | |||
| 9cbf31da27 | |||
| 71cc97822a | |||
| c2ba78253d | |||
| 75aeba29ed | |||
| bd58f17ec0 | |||
| 721a610a70 | |||
| eda27f1e59 | |||
| a08d4b944e | |||
| 5137bcb86a | |||
| 7861006bf5 | |||
| 5f6594f697 | |||
| fcbb538c24 | |||
| 43a8984e4c | |||
| e958a9a2bb | |||
| 986dabf11f | |||
| 318e71aa0c | |||
| 308daec14e | |||
| 3f68c8a50e | |||
| 74af74fb5e | |||
| 924b4e0787 | |||
| d5d9428cf2 | |||
| b9231ffb53 | |||
| 489ba93c0c | |||
| 2a448722c6 | |||
| cd53d0a895 | |||
| db6bb911c2 | |||
| 69552ffeef | |||
| 1f710bd217 | |||
| 11e4fe6ae3 | |||
| 3e98938c95 | |||
| 7283b75cac | |||
| cae04e83dd | |||
| 72e8b1f8d9 | |||
| 73ac4b29ad | |||
| 208af03212 | |||
| 8401428ca7 | |||
| 12406bbbf4 | |||
| 12ae32b69e | |||
| 5176dc29d6 | |||
| 0eac3a9f49 | |||
| 64b86c2403 | |||
| 66d85729ff | |||
| e7bff6681e | |||
| c7cfa5a64f | |||
| 72fc61a016 | |||
| a70eea5bf2 | |||
| c9c419b4ad | |||
| 6759277c3b | |||
| 10d5f3ed46 | |||
| 2934319722 | |||
| d4c81bc5f2 | |||
| 35e0613986 | |||
| ccfa92f650 | |||
| fdb2095ced | |||
| d6a6b49b6b | |||
| 0855bafca7 | |||
| a39f3fe40c | |||
| f13a0aa6ee | |||
| 10d1a61614 | |||
| 2bcfc1bfcb | |||
| b6e3c9bf39 | |||
| 736dc5dda9 | |||
| ae26a6c61c | |||
| 8979bd1fcd | |||
| 74d243d8e0 | |||
| 56b9bac031 | |||
| 4983b3407c | |||
| ed1728feec | |||
| 11472c05ff | |||
| f2ac12ca4f | |||
| b53130ca0d | |||
| a3a4f7cf79 | |||
| ac7094df05 | |||
| 80130f7946 | |||
| fc648bc7e4 | |||
| 9005d6b333 | |||
| 52f0fb882f | |||
| b8ec428ad1 | |||
| a1d3ffc2ce | |||
| 46b9df54bf | |||
| 3c0c3b3f6e | |||
| 5395d53332 | |||
| ec08032e98 | |||
| cc5eca5553 | |||
| 1323183cce | |||
| 009be05d22 | |||
| 860ffc1dee | |||
| c515f95d17 | |||
| 855bf8610a | |||
| 742edc4a79 | |||
| 1975a23aab | |||
| 80c8d9c602 | |||
| 948c9ef57b | |||
| bac968c0bf | |||
| 520562ef86 | |||
| 001253c39b | |||
| 5345b50d17 | |||
| a3622e91b6 | |||
| be305c3daf | |||
| ec78cfbdd0 | |||
| 8023be452a | |||
| 5112c96c05 | |||
| 04b1fb72bb | |||
| a9d11ccb2e | |||
| 848e3f90e1 | |||
| e83b6741ad | |||
| 0a3d93b59b | |||
| 102e2141ec | |||
| 768fd6f439 | |||
| 231a610466 | |||
| 7db5ec0721 | |||
| a2b9d96e86 | |||
| e0022c12c4 | |||
| 66b8f2c906 |
@@ -458,7 +458,10 @@ jobs:
|
||||
# tsconfig.strict.json is the same program with strictNullChecks and
|
||||
# noImplicitAny; its errors per file may not rise above
|
||||
# scripts/strict-baseline.json, and a file without an entry, every new
|
||||
# one included, has to be clean (scripts/strict-lint.mjs).
|
||||
# one included, has to be clean (scripts/strict-lint.mjs). It holds the
|
||||
# whole program with strict checks, past Node's default ~4 GB heap.
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
run: cd client && npm run lint:strict
|
||||
|
||||
- name: Page pattern check
|
||||
@@ -1276,6 +1279,10 @@ jobs:
|
||||
--set httpRoute.enabled=true \
|
||||
--set 'httpRoute.parentRefs[0].name=gateway' \
|
||||
> "$out/http-route.yaml"
|
||||
helm template trek charts/trek \
|
||||
--set 'persistence.data.accessModes[0]=ReadWriteMany' \
|
||||
--set 'persistence.uploads.accessModes[0]=ReadWriteMany' \
|
||||
> "$out/access-modes.yaml"
|
||||
helm template trek charts/trek \
|
||||
--set podSecurityContext.runAsUser=1000 \
|
||||
--set podSecurityContext.runAsGroup=1000 \
|
||||
|
||||
@@ -20,7 +20,23 @@ geoBoundaries is licensed under **CC BY 4.0**
|
||||
The bundled files are simplified (coordinate-quantized) and re-tagged with the
|
||||
property names TREK consumes. Country borders (`admin0`) derive from the geoBoundaries
|
||||
CGAZ composite; sub-national regions (`admin1`) derive from the per-country open
|
||||
(gbOpen) release.
|
||||
(gbOpen) release, except for Ireland (below).
|
||||
|
||||
## Tailte Éireann — counties of Ireland
|
||||
|
||||
Ireland's regions in the same files (`admin1/IE.geojson.gz`, and its features in
|
||||
`admin1.geojson.gz`) are the 26 counties from Tailte Éireann's *Counties - National
|
||||
Statutory Boundaries - 2019 - Generalised 20m*, because geoBoundaries has no county
|
||||
layer for Ireland.
|
||||
|
||||
Contains Tailte Éireann data, © Tailte Éireann, licensed under **CC BY 4.0**
|
||||
(https://creativecommons.org/licenses/by/4.0/). Source:
|
||||
https://data-osi.opendata.arcgis.com/
|
||||
|
||||
The outlines are simplified, coordinate-quantized and re-tagged with ISO 3166-2:IE
|
||||
codes by `server/scripts/build-atlas-geo.mjs`. Tailte Éireann publishes the
|
||||
generalised boundaries for reference only; they may not match the statutory
|
||||
boundaries exactly.
|
||||
|
||||
## OpenStreetMap — geocoding, place details & descriptions
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
#### 🗺️ Atlas, Vacay and Collections
|
||||
|
||||
- **Atlas**: countries and regions visited on [geoBoundaries](https://www.geoboundaries.org/) outlines, a bucket list, travel stats, and a tour activities tab with planned against recorded totals
|
||||
- **Vacay**: leave calendar with half days, public holidays from date.nager.at, school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
|
||||
- **Vacay**: leave calendar with half days, public holidays from [nagerholidays.com](https://nagerholidays.com), school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
|
||||
- **Collections** (off by default): a place library outside any trip with lists, labels, ratings, a status per place, cover images, GPX and file export, copy into a trip, and sharing by invite
|
||||
- **Dawarich** (off by default): link a Dawarich instance for recorded tracks, suggested stays and countries for the Atlas
|
||||
|
||||
@@ -276,6 +276,8 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
|
||||
|
||||
`COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it.
|
||||
|
||||
**TrueNAS SCALE:** Install TREK directly from the Community catalog. See the [TrueNAS SCALE installation guide](https://github.com/liketrek/TREK/wiki/Install-TrueNAS-SCALE).
|
||||
|
||||
> [!TIP]
|
||||
> **No server yet?** TREK's own public services run on [**dataforest cloud**](https://cloud.dataforest.net/en?mtm_campaign=trek), our infrastructure sponsor. A small seed is plenty for a TREK instance and is ready within a minute.
|
||||
|
||||
@@ -348,7 +350,7 @@ TREK then launches fullscreen with its own icon, just like a native app.
|
||||
## Updating
|
||||
|
||||
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
|
||||
Docker run, Helm, Portainer, Unraid and Proxmox, plus the encryption-key note.
|
||||
Docker run, Helm, Portainer, Unraid, TrueNAS SCALE and Proxmox, plus the encryption-key note.
|
||||
|
||||
<br />
|
||||
|
||||
@@ -437,8 +439,9 @@ Every variable, its default and what it does: see
|
||||
|
||||
The Atlas map's country and sub-national (province/county) boundaries come from
|
||||
[**geoBoundaries**](https://www.geoboundaries.org/) (Runfola et al., 2020), licensed
|
||||
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). See [NOTICE.md](NOTICE.md)
|
||||
for full third-party attributions.
|
||||
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); Ireland's counties come from
|
||||
[**Tailte Éireann**](https://data-osi.opendata.arcgis.com/), also CC BY 4.0. See
|
||||
[NOTICE.md](NOTICE.md) for full third-party attributions.
|
||||
|
||||
<br />
|
||||
|
||||
|
||||
+2
-1
@@ -43,7 +43,8 @@ See `values.yaml` for more options.
|
||||
## Notes
|
||||
- Ingress is off by default. Enable and configure hosts for your domain.
|
||||
- PVCs use the cluster's default StorageClass. Set `persistence.data.storageClassName` and/or `persistence.uploads.storageClassName` to bind a specific class.
|
||||
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, annotations) are then ignored.
|
||||
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
|
||||
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
|
||||
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
|
||||
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
|
||||
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
apiVersion: v2
|
||||
name: trek
|
||||
version: 5.1.3
|
||||
version: 5.1.4
|
||||
description: Minimal Helm chart for TREK app
|
||||
appVersion: "5.1.3"
|
||||
appVersion: "5.1.4"
|
||||
|
||||
@@ -11,7 +11,7 @@ metadata:
|
||||
{{- end }}
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
{{- toYaml (.Values.persistence.data.accessModes | default (list "ReadWriteOnce")) | nindent 4 }}
|
||||
{{- with .Values.persistence.data.storageClassName }}
|
||||
storageClassName: {{ . | quote }}
|
||||
{{- end }}
|
||||
@@ -33,7 +33,7 @@ metadata:
|
||||
{{- end }}
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
{{- toYaml (.Values.persistence.uploads.accessModes | default (list "ReadWriteOnce")) | nindent 4 }}
|
||||
{{- with .Values.persistence.uploads.storageClassName }}
|
||||
storageClassName: {{ . | quote }}
|
||||
{{- end }}
|
||||
|
||||
+10
-1
@@ -247,12 +247,21 @@ persistence:
|
||||
size: 1Gi
|
||||
# Leave empty to use the cluster's default StorageClass; set to bind a specific class.
|
||||
storageClassName: ""
|
||||
# Bind an existing PVC. The other values (size, storageClassName, annotations) are then ignored.
|
||||
# Access modes of the claim. ReadWriteMany lets another pod mount the volume, for
|
||||
# example a backup sidecar, but only for reading: SQLite needs every writer on one
|
||||
# host, so two pods writing travel.db over a network filesystem corrupt it.
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
# Bind an existing PVC. The other values (size, storageClassName, accessModes,
|
||||
# annotations) are then ignored.
|
||||
existingClaim: ""
|
||||
annotations: {}
|
||||
uploads:
|
||||
size: 1Gi
|
||||
storageClassName: ""
|
||||
# Access modes of the claim; ReadWriteMany lets other pods read or add uploads.
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
# Specify an existing PVC to bind. The other values are then ignored.
|
||||
existingClaim: ""
|
||||
annotations: {}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Scope: the **`@trek/client`** workspace (React 19 + Vite + Zustand + Tailwind PW
|
||||
|
||||
```bash
|
||||
npm run dev # Vite dev server; proxies the API/ws/uploads/MCP/OAuth paths → http://localhost:3001
|
||||
npm run build # prebuild generates PWA icons, then vite build
|
||||
npm run build # prebuild generates PWA icons, then vite build; postbuild writes a Brotli copy beside each hashed asset for the server to hand out
|
||||
npm run typecheck # tsc --noEmit (CI)
|
||||
npm run lint:strict # tsc over tsconfig.strict.json (strictNullChecks + noImplicitAny): errors per file may only shrink against scripts/strict-baseline.json, a new file starts at zero (CI gate; --list shows them, --update lowers it)
|
||||
npm run lint # eslint . (CI runs lint:warnings instead, which fails on the same errors)
|
||||
|
||||
+9
@@ -36,3 +36,12 @@
|
||||
@android.webkit.JavascriptInterface <methods>;
|
||||
}
|
||||
-keep public class * extends com.getcapacitor.Plugin
|
||||
|
||||
# The stored copy of the server's UI gets Capacitor's bridge the way the
|
||||
# server's own page does (TrekOfflineShell.withBridge reads it by reflection).
|
||||
-keepclassmembers class com.getcapacitor.Bridge {
|
||||
private com.getcapacitor.JSInjector getJSInjector();
|
||||
}
|
||||
-keep class com.getcapacitor.JSInjector {
|
||||
public java.io.InputStream getInjectedStream(java.io.InputStream);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import androidx.glance.appwidget.GlanceRemoteViews
|
||||
import com.liketrek.trek.tripday.TripDayNotification
|
||||
import com.liketrek.trek.widget.AtlasWidget
|
||||
import com.liketrek.trek.widget.BookingsWidget
|
||||
import com.liketrek.trek.widget.FlightWidget
|
||||
import com.liketrek.trek.widget.CollabWidget
|
||||
import com.liketrek.trek.widget.PackingWidget
|
||||
import com.liketrek.trek.widget.TodayWidget
|
||||
@@ -74,6 +75,7 @@ class WidgetGalleryActivity : Activity() {
|
||||
"trip" to TripWidget(),
|
||||
"today" to TodayWidget(),
|
||||
"bookings" to BookingsWidget(),
|
||||
"flight" to FlightWidget(),
|
||||
"todos" to TodosWidget(),
|
||||
"packing" to PackingWidget(),
|
||||
"atlas" to AtlasWidget(),
|
||||
|
||||
@@ -142,6 +142,15 @@
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_bookings" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.FlightWidgetReceiver"
|
||||
android:label="@string/widget_flight_name"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_flight" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.TodosWidgetReceiver"
|
||||
android:label="@string/widget_todos_name"
|
||||
|
||||
@@ -10,6 +10,7 @@ import android.view.KeyboardShortcutGroup;
|
||||
import android.view.Menu;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.CookieManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
@@ -34,7 +35,19 @@ public class MainActivity extends BridgeActivity {
|
||||
// runs and on its own origin. BridgeActivity reads `config` while it
|
||||
// builds the bridge inside super.onCreate().
|
||||
boolean restarting = TrekServerStore.consumeRestart(this);
|
||||
TrekServerStore.recheckAfterUpdate(this);
|
||||
// Without a network the server cannot answer: with a copy of its UI the
|
||||
// app starts on that at once (TrekOfflineShell), as it does when the
|
||||
// address screen found the server out of reach. The check an update asks
|
||||
// for waits for a launch that can reach the server.
|
||||
boolean offlineStart = TrekServerStore.consumeOfflineStart(this)
|
||||
|| (!TrekOfflineShell.hasNetwork(this) && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this)));
|
||||
if (offlineStart && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this))) {
|
||||
TrekServerStore.restoreForOffline(this);
|
||||
TrekOfflineShell.activate(TrekServerStore.getUrl(this));
|
||||
} else {
|
||||
TrekOfflineShell.deactivate();
|
||||
TrekServerStore.recheckAfterUpdate(this);
|
||||
}
|
||||
String server = TrekServerStore.getUrl(this);
|
||||
boolean onServer = server != null && !TrekServerStore.consumeShellOnce(this);
|
||||
config = TrekServerStore.configFor(this, onServer ? server : null, restarting);
|
||||
@@ -47,7 +60,13 @@ public class MainActivity extends BridgeActivity {
|
||||
// Set before any WebView callback can run: they are posted to this thread.
|
||||
if (onServer) {
|
||||
bridge.setWebViewClient(
|
||||
new TrekWebViewClient(bridge, this::showAddressScreen, this::showSignInBar, TrekServerStore.getSignInHosts(this))
|
||||
new TrekWebViewClient(
|
||||
bridge,
|
||||
this::showAddressScreen,
|
||||
this::showSignInBar,
|
||||
this::showErrorPageBar,
|
||||
TrekServerStore.getSignInHosts(this)
|
||||
)
|
||||
);
|
||||
}
|
||||
TrekSharedFiles.receive(this, getIntent());
|
||||
@@ -73,6 +92,18 @@ public class MainActivity extends BridgeActivity {
|
||||
if (group != null) data.add(group);
|
||||
}
|
||||
|
||||
/**
|
||||
* The web view keeps new cookies in memory and writes them to disk on its
|
||||
* own schedule, about half a minute later. An app Android ends in that time
|
||||
* (swiped away, or reclaimed for memory) forgets the sign-in it just had, so
|
||||
* the session is written down whenever the app leaves the screen.
|
||||
*/
|
||||
@Override
|
||||
public void onPause() {
|
||||
super.onPause();
|
||||
CookieManager.getInstance().flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
@@ -84,7 +115,10 @@ public class MainActivity extends BridgeActivity {
|
||||
private View signInBar;
|
||||
/** Whether the page is a proxy's sign-in page, and whether the keyboard is up over it. */
|
||||
private boolean onSignInPage;
|
||||
/** Whether the page is an error page in place of the server's (TrekWebViewClient.onReceivedHttpError). */
|
||||
private boolean onErrorPage;
|
||||
private boolean keyboardUp;
|
||||
private TextView signInHint;
|
||||
|
||||
/**
|
||||
* Over a proxy's sign-in page (Pangolin, authentik, ...): the server's UI is
|
||||
@@ -100,9 +134,22 @@ public class MainActivity extends BridgeActivity {
|
||||
});
|
||||
}
|
||||
|
||||
/** The same bar over an error page in place of the server's, with words for that. */
|
||||
private void showErrorPageBar(boolean show) {
|
||||
runOnUiThread(() -> {
|
||||
onErrorPage = show;
|
||||
if (show && signInBar == null) signInBar = buildSignInBar();
|
||||
updateSignInBar();
|
||||
});
|
||||
}
|
||||
|
||||
/** Out of the way while the keyboard is up: the form needs the room, and the bar is there again once it closes. */
|
||||
private void updateSignInBar() {
|
||||
if (signInBar != null) signInBar.setVisibility(onSignInPage && !keyboardUp ? View.VISIBLE : View.GONE);
|
||||
if (signInBar == null) return;
|
||||
if (signInHint != null) {
|
||||
signInHint.setText(onSignInPage ? TrekServerStore.signInHintLabel(this) : TrekServerStore.errorPageHintLabel(this));
|
||||
}
|
||||
signInBar.setVisibility((onSignInPage || onErrorPage) && !keyboardUp ? View.VISIBLE : View.GONE);
|
||||
}
|
||||
|
||||
private View buildSignInBar() {
|
||||
@@ -110,16 +157,20 @@ public class MainActivity extends BridgeActivity {
|
||||
LinearLayout bar = new LinearLayout(this);
|
||||
bar.setOrientation(LinearLayout.HORIZONTAL);
|
||||
bar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
bar.setPadding(Math.round(14 * dp), Math.round(10 * dp), Math.round(8 * dp), Math.round(10 * dp));
|
||||
bar.setPaddingRelative(Math.round(16 * dp), Math.round(10 * dp), Math.round(10 * dp), Math.round(10 * dp));
|
||||
// The look of the app's own first screens: a white card with a sand edge,
|
||||
// warm grey text and a dark button, over whatever page the proxy shows.
|
||||
GradientDrawable background = new GradientDrawable();
|
||||
background.setColor(0xF2111827);
|
||||
background.setCornerRadius(16 * dp);
|
||||
background.setColor(0xF7FFFFFF);
|
||||
background.setCornerRadius(18 * dp);
|
||||
background.setStroke(Math.max(1, Math.round(dp)), 0xFFEFE4D8);
|
||||
bar.setBackground(background);
|
||||
bar.setElevation(6 * dp);
|
||||
bar.setElevation(8 * dp);
|
||||
|
||||
TextView hint = new TextView(this);
|
||||
signInHint = hint;
|
||||
hint.setText(TrekServerStore.signInHintLabel(this));
|
||||
hint.setTextColor(0xFFE5E7EB);
|
||||
hint.setTextColor(0xFF6B5F57);
|
||||
hint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f);
|
||||
bar.addView(hint, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
|
||||
|
||||
@@ -127,12 +178,21 @@ public class MainActivity extends BridgeActivity {
|
||||
change.setText(TrekServerStore.changeServerLabel(this));
|
||||
change.setAllCaps(false);
|
||||
change.setTextColor(0xFFFFFFFF);
|
||||
GradientDrawable pill = new GradientDrawable();
|
||||
pill.setColor(0xFF111827);
|
||||
pill.setCornerRadius(12 * dp);
|
||||
change.setBackground(pill);
|
||||
change.setMinHeight(0);
|
||||
change.setMinimumHeight(0);
|
||||
change.setPaddingRelative(Math.round(14 * dp), Math.round(9 * dp), Math.round(14 * dp), Math.round(9 * dp));
|
||||
LinearLayout.LayoutParams changeParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
changeParams.setMarginStart(Math.round(10 * dp));
|
||||
change.setOnClickListener((v) -> {
|
||||
TrekServerStore.setUrl(this, null);
|
||||
TrekServerStore.markRestart(this);
|
||||
recreate();
|
||||
});
|
||||
bar.addView(change, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||
bar.addView(change, changeParams);
|
||||
|
||||
int margin = Math.round(12 * dp);
|
||||
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.Network;
|
||||
import android.net.NetworkCapabilities;
|
||||
import android.net.Uri;
|
||||
import android.util.Log;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebResourceResponse;
|
||||
import com.getcapacitor.Bridge;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The server's UI kept on the device, so the app starts without its server: on
|
||||
* a trip without reception, or away from home with a server on the home
|
||||
* network. The web view runs no service worker on a plain-http server, the
|
||||
* usual address of a server at home, so the app keeps the start page and every
|
||||
* file of the build itself (refreshed by native/offlineShell.ts while the
|
||||
* server is reachable) and serves them under the server's own origin while it
|
||||
* is not. The data comes from the UI's own offline store; the API is tried as
|
||||
* usual and answers again once the server is back.
|
||||
*/
|
||||
final class TrekOfflineShell {
|
||||
|
||||
private static final String DIR = "offline-shell";
|
||||
private static final String PAGE = "index.html";
|
||||
private static final String STAMP = "server.txt";
|
||||
private static final String FILES = "files";
|
||||
/** A path of the build: no "..", no query, nothing outside the copy's folder. */
|
||||
private static final Pattern SAFE_PATH = Pattern.compile("^[A-Za-z0-9._@\\-]+(?:/[A-Za-z0-9._@\\-]+)*$");
|
||||
private static final Map<String, String> TYPES = new HashMap<>();
|
||||
|
||||
static {
|
||||
TYPES.put("js", "text/javascript");
|
||||
TYPES.put("mjs", "text/javascript");
|
||||
TYPES.put("css", "text/css");
|
||||
TYPES.put("json", "application/json");
|
||||
TYPES.put("webmanifest", "application/manifest+json");
|
||||
TYPES.put("svg", "image/svg+xml");
|
||||
TYPES.put("png", "image/png");
|
||||
TYPES.put("jpg", "image/jpeg");
|
||||
TYPES.put("jpeg", "image/jpeg");
|
||||
TYPES.put("webp", "image/webp");
|
||||
TYPES.put("ico", "image/x-icon");
|
||||
TYPES.put("woff", "font/woff");
|
||||
TYPES.put("woff2", "font/woff2");
|
||||
TYPES.put("ttf", "font/ttf");
|
||||
TYPES.put("wasm", "application/wasm");
|
||||
TYPES.put("html", "text/html");
|
||||
}
|
||||
|
||||
/**
|
||||
* The server whose copy the UI comes from in this run: it did not answer
|
||||
* when the app started. Null while the UI comes from the server itself.
|
||||
* Bound to the server, so a copy never answers for another one.
|
||||
*/
|
||||
private static volatile String activeServer;
|
||||
/** Capacitor's JSInjector (package-private there) and its getInjectedStream, found once. */
|
||||
private static volatile Object injector;
|
||||
private static volatile Method injectMethod;
|
||||
private static volatile boolean injectorLooked;
|
||||
|
||||
private TrekOfflineShell() {}
|
||||
|
||||
static boolean isActive() {
|
||||
return activeServer != null;
|
||||
}
|
||||
|
||||
static void activate(String server) {
|
||||
activeServer = server;
|
||||
}
|
||||
|
||||
/**
|
||||
* A start that goes to the server. The flag lives in the process, and
|
||||
* restart() recreates the activity in that same process (another server
|
||||
* picked, the address screen, a reload once the server is back), so each
|
||||
* start sets it anew instead of keeping the last run's copy in front.
|
||||
*/
|
||||
static void deactivate() {
|
||||
activeServer = null;
|
||||
}
|
||||
|
||||
/** Whether the copy stands in for this server in this run. */
|
||||
static boolean isActiveFor(String server) {
|
||||
String current = activeServer;
|
||||
return current != null && current.equals(server);
|
||||
}
|
||||
|
||||
private static File root(Context context) {
|
||||
return new File(context.getFilesDir(), DIR);
|
||||
}
|
||||
|
||||
/** Whether there is a copy of this server's UI to start from. */
|
||||
static boolean hasCopy(Context context, String server) {
|
||||
return hasCopy(root(context), server);
|
||||
}
|
||||
|
||||
static boolean hasCopy(File root, String server) {
|
||||
if (server == null) return false;
|
||||
File page = new File(root, PAGE);
|
||||
return page.isFile() && server.equals(readStamp(root));
|
||||
}
|
||||
|
||||
/** Whether the device has a network at all; with none, the server cannot answer and the copy starts at once. */
|
||||
static boolean hasNetwork(Context context) {
|
||||
try {
|
||||
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
if (cm == null) return true;
|
||||
Network network = cm.getActiveNetwork();
|
||||
if (network == null) return false;
|
||||
NetworkCapabilities caps = cm.getNetworkCapabilities(network);
|
||||
return caps != null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
|
||||
} catch (RuntimeException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Before a refresh fetches the files of a build: a copy of another server
|
||||
* is thrown away, one of this server stays as it is until savePage.
|
||||
*/
|
||||
static boolean beginRefresh(Context context, String server) {
|
||||
return beginRefresh(root(context), server);
|
||||
}
|
||||
|
||||
static boolean beginRefresh(File root, String server) {
|
||||
if (!server.equals(readStamp(root))) deleteTree(root);
|
||||
return root.isDirectory() || root.mkdirs();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the start page, and only once every file it names is stored: the
|
||||
* page points at the build's files by their hashes, so a refresh cut off
|
||||
* halfway (no reception, the app ended) keeps the previous page with its
|
||||
* complete build instead of a new page whose scripts are missing.
|
||||
*/
|
||||
static boolean savePage(Context context, String server, byte[] html) {
|
||||
return savePage(root(context), server, html);
|
||||
}
|
||||
|
||||
static boolean savePage(File root, String server, byte[] html) {
|
||||
if (!root.isDirectory() && !root.mkdirs()) return false;
|
||||
return write(new File(root, STAMP), server.getBytes(StandardCharsets.UTF_8)) && write(new File(root, PAGE), html);
|
||||
}
|
||||
|
||||
static boolean hasFile(Context context, String path) {
|
||||
return hasFile(root(context), path);
|
||||
}
|
||||
|
||||
static boolean hasFile(File root, String path) {
|
||||
File file = fileFor(root, path);
|
||||
return file != null && file.isFile();
|
||||
}
|
||||
|
||||
static boolean saveFile(Context context, String path, byte[] data) {
|
||||
return saveFile(root(context), path, data);
|
||||
}
|
||||
|
||||
static boolean saveFile(File root, String path, byte[] data) {
|
||||
File file = fileFor(root, path);
|
||||
if (file == null) return false;
|
||||
File parent = file.getParentFile();
|
||||
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) return false;
|
||||
return write(file, data);
|
||||
}
|
||||
|
||||
/** Drops the files of older builds once the current one is complete. */
|
||||
static void prune(Context context, Set<String> keep) {
|
||||
prune(root(context), keep);
|
||||
}
|
||||
|
||||
static void prune(File root, Set<String> keep) {
|
||||
File base = new File(root, FILES);
|
||||
pruneDir(base, base, keep);
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy's answer for a request of the server's UI while it is active:
|
||||
* the start page for any page of the app (it routes itself), with
|
||||
* Capacitor's bridge injected as into the server's own page, and a file of
|
||||
* the build by its path. Null for anything else, which goes on as usual.
|
||||
*/
|
||||
static WebResourceResponse serve(Context context, Bridge bridge, String server, WebResourceRequest request) {
|
||||
if (!isActiveFor(server) || !"GET".equalsIgnoreCase(request.getMethod())) return null;
|
||||
Uri url = request.getUrl();
|
||||
Uri origin = Uri.parse(server);
|
||||
if (!sameOrigin(url, origin)) return null;
|
||||
try {
|
||||
if (request.isForMainFrame()) {
|
||||
File page = new File(root(context), PAGE);
|
||||
if (!page.isFile()) return null;
|
||||
InputStream html = withBridge(bridge, new FileInputStream(page));
|
||||
return response("text/html", html);
|
||||
}
|
||||
String path = url.getPath();
|
||||
if (path == null) return null;
|
||||
File file = fileFor(root(context), path);
|
||||
if (file == null || !file.isFile()) return null;
|
||||
return response(typeOf(path), new FileInputStream(file));
|
||||
} catch (IOException e) {
|
||||
Log.w("TrekShell", "Offline copy could not answer " + url, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static WebResourceResponse response(String type, InputStream body) {
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Cache-Control", "no-store");
|
||||
String charset = type.startsWith("text/") || type.endsWith("json") ? "utf-8" : null;
|
||||
return new WebResourceResponse(type, charset, 200, "OK", headers, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Capacitor injects its bridge into the server's page as it passes through;
|
||||
* the copy gets the same script. Its builder is internal to Capacitor, hence
|
||||
* the reflection on both (kept in proguard-rules.pro). Without it the UI still runs,
|
||||
* as it would in a browser, just without the app's native parts.
|
||||
*/
|
||||
private static InputStream withBridge(Bridge bridge, InputStream html) {
|
||||
if (!injectorLooked) {
|
||||
injectorLooked = true;
|
||||
try {
|
||||
Method method = Bridge.class.getDeclaredMethod("getJSInjector");
|
||||
method.setAccessible(true);
|
||||
Object built = method.invoke(bridge);
|
||||
if (built != null) {
|
||||
Method inject = built.getClass().getDeclaredMethod("getInjectedStream", InputStream.class);
|
||||
inject.setAccessible(true);
|
||||
injectMethod = inject;
|
||||
injector = built;
|
||||
}
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
Log.w("TrekShell", "No bridge for the offline copy", e);
|
||||
}
|
||||
}
|
||||
Object current = injector;
|
||||
Method inject = injectMethod;
|
||||
if (current == null || inject == null) return html;
|
||||
try {
|
||||
Object injected = inject.invoke(current, html);
|
||||
return injected instanceof InputStream ? (InputStream) injected : html;
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
Log.w("TrekShell", "Bridge not injected into the offline copy", e);
|
||||
return html;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean sameOrigin(Uri a, Uri b) {
|
||||
if (a.getScheme() == null || b.getScheme() == null || a.getHost() == null || b.getHost() == null) return false;
|
||||
return a.getScheme().equalsIgnoreCase(b.getScheme())
|
||||
&& a.getHost().equalsIgnoreCase(b.getHost())
|
||||
&& port(a) == port(b);
|
||||
}
|
||||
|
||||
private static int port(Uri uri) {
|
||||
if (uri.getPort() != -1) return uri.getPort();
|
||||
return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
|
||||
}
|
||||
|
||||
private static File fileFor(File root, String path) {
|
||||
String clean = path.startsWith("/") ? path.substring(1) : path;
|
||||
if (clean.isEmpty() || clean.contains("..") || !SAFE_PATH.matcher(clean).matches()) return null;
|
||||
return new File(new File(root, FILES), clean);
|
||||
}
|
||||
|
||||
private static String typeOf(String path) {
|
||||
int dot = path.lastIndexOf('.');
|
||||
String ext = dot < 0 ? "" : path.substring(dot + 1).toLowerCase(Locale.ROOT);
|
||||
String type = TYPES.get(ext);
|
||||
return type == null ? "application/octet-stream" : type;
|
||||
}
|
||||
|
||||
private static String readStamp(File root) {
|
||||
File stamp = new File(root, STAMP);
|
||||
if (!stamp.isFile()) return null;
|
||||
try (FileInputStream in = new FileInputStream(stamp)) {
|
||||
byte[] data = new byte[(int) Math.min(stamp.length(), 4096)];
|
||||
int read = in.read(data);
|
||||
return read <= 0 ? null : new String(data, 0, read, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Written beside the target and moved over it, so a cut-off write never leaves half a file. */
|
||||
private static boolean write(File target, byte[] data) {
|
||||
File temp = new File(target.getPath() + ".part");
|
||||
try (FileOutputStream out = new FileOutputStream(temp)) {
|
||||
out.write(data);
|
||||
out.getFD().sync();
|
||||
} catch (IOException e) {
|
||||
temp.delete();
|
||||
return false;
|
||||
}
|
||||
return temp.renameTo(target);
|
||||
}
|
||||
|
||||
private static void pruneDir(File base, File dir, Set<String> keep) {
|
||||
File[] children = dir.listFiles();
|
||||
if (children == null) return;
|
||||
for (File child : children) {
|
||||
if (child.isDirectory()) {
|
||||
pruneDir(base, child, keep);
|
||||
String[] left = child.list();
|
||||
if (left != null && left.length == 0) child.delete();
|
||||
} else {
|
||||
String relative = base.toURI().relativize(child.toURI()).getPath();
|
||||
if (!keep.contains(relative)) child.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteTree(File file) {
|
||||
File[] children = file.listFiles();
|
||||
if (children != null) for (File child : children) deleteTree(child);
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ final class TrekServerStore {
|
||||
private static final String KEY_SERVER_CHECK = "server_check";
|
||||
private static final String KEY_LABEL_SIGN_IN_HINT = "label_sign_in_hint";
|
||||
private static final String KEY_LABEL_CHANGE_SERVER = "label_change_server";
|
||||
private static final String KEY_LABEL_ERROR_PAGE_HINT = "label_error_page_hint";
|
||||
|
||||
/**
|
||||
* The server API this build needs (MIN_NATIVE_API in serverAddress.ts). A
|
||||
@@ -33,10 +34,11 @@ final class TrekServerStore {
|
||||
* launch after an update that raised it puts the address screen back up,
|
||||
* filled in with that server (getPreviousUrl). Raise both together.
|
||||
*/
|
||||
private static final int SERVER_CHECK = 2;
|
||||
private static final int SERVER_CHECK = 3;
|
||||
private static final String KEY_SIGN_IN_HOSTS = "sign_in_hosts";
|
||||
private static final String KEY_SHELL_ONCE = "shell_once";
|
||||
private static final String KEY_RESTART = "restart";
|
||||
private static final String KEY_OFFLINE_START = "offline_start";
|
||||
private static final String KEY_WELCOME = "welcome";
|
||||
private static final String CONFIG_DIR = "trek-server-config";
|
||||
|
||||
@@ -83,13 +85,21 @@ final class TrekServerStore {
|
||||
* as the address screen passed them (setServer's `labels`): the server's UI
|
||||
* is not there to say them. Null keeps the English fallback.
|
||||
*/
|
||||
static void setLabels(Context context, String signInHint, String changeServer) {
|
||||
static void setLabels(Context context, String signInHint, String changeServer, String errorPageHint) {
|
||||
SharedPreferences.Editor editor = prefs(context).edit();
|
||||
if (signInHint != null) editor.putString(KEY_LABEL_SIGN_IN_HINT, signInHint);
|
||||
if (changeServer != null) editor.putString(KEY_LABEL_CHANGE_SERVER, changeServer);
|
||||
if (errorPageHint != null) editor.putString(KEY_LABEL_ERROR_PAGE_HINT, errorPageHint);
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
static String errorPageHintLabel(Context context) {
|
||||
return prefs(context).getString(
|
||||
KEY_LABEL_ERROR_PAGE_HINT,
|
||||
"This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server."
|
||||
);
|
||||
}
|
||||
|
||||
static String signInHintLabel(Context context) {
|
||||
return prefs(context).getString(
|
||||
KEY_LABEL_SIGN_IN_HINT,
|
||||
@@ -147,6 +157,24 @@ final class TrekServerStore {
|
||||
}
|
||||
|
||||
/** Start the next launch on the bundled address screen, even with a server remembered. */
|
||||
private static final String KEY_FAILURE = "last_failure";
|
||||
|
||||
/**
|
||||
* Why the server's page did not load, in the WebView's own terms
|
||||
* ("net::ERR_NAME_NOT_RESOLVED (-2)", "HTTP 503"): the address screen shows
|
||||
* it small under its message, so a report carries the cause.
|
||||
*/
|
||||
static void setFailure(Context context, String failure) {
|
||||
prefs(context).edit().putString(KEY_FAILURE, failure).commit();
|
||||
}
|
||||
|
||||
/** The failure behind this address screen, once. */
|
||||
static String takeFailure(Context context) {
|
||||
String failure = prefs(context).getString(KEY_FAILURE, null);
|
||||
if (failure != null) prefs(context).edit().remove(KEY_FAILURE).commit();
|
||||
return failure;
|
||||
}
|
||||
|
||||
static void showShellOnce(Context context) {
|
||||
prefs(context).edit().putBoolean(KEY_SHELL_ONCE, true).commit();
|
||||
}
|
||||
@@ -164,6 +192,37 @@ final class TrekServerStore {
|
||||
return consume(context, KEY_RESTART);
|
||||
}
|
||||
|
||||
/** The next onCreate starts on the stored copy of the server's UI (TrekOfflineShell). */
|
||||
static void markOfflineStart(Context context) {
|
||||
prefs(context).edit().putBoolean(KEY_OFFLINE_START, true).commit();
|
||||
}
|
||||
|
||||
static boolean consumeOfflineStart(Context context) {
|
||||
return consume(context, KEY_OFFLINE_START);
|
||||
}
|
||||
|
||||
/**
|
||||
* The remembered server, or the one an update asked to check again: the
|
||||
* server the stored copy of the UI belongs to.
|
||||
*/
|
||||
static String getUrlOrPrevious(Context context) {
|
||||
String url = getUrl(context);
|
||||
return url != null ? url : getPreviousUrl(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starting on the stored copy while the check an update asked for could not
|
||||
* run: the server goes back in place, unchecked for now, and the check runs
|
||||
* again on the next launch, which reaches the server.
|
||||
*/
|
||||
static void restoreForOffline(Context context) {
|
||||
SharedPreferences prefs = prefs(context);
|
||||
if (prefs.getString(KEY_URL, null) != null) return;
|
||||
String previous = prefs.getString(KEY_PREVIOUS_URL, null);
|
||||
if (previous == null) return;
|
||||
prefs.edit().putString(KEY_URL, previous).remove(KEY_PREVIOUS_URL).putInt(KEY_SERVER_CHECK, 0).commit();
|
||||
}
|
||||
|
||||
private static boolean consume(Context context, String key) {
|
||||
boolean set = prefs(context).getBoolean(key, false);
|
||||
if (set) prefs(context).edit().remove(key).commit();
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.liketrek.trek;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
@@ -314,6 +315,8 @@ public class TrekShellPlugin extends Plugin {
|
||||
JSObject result = new JSObject();
|
||||
result.put("url", url == null ? JSONObject.NULL : url);
|
||||
result.put("previousUrl", previous == null ? JSONObject.NULL : previous);
|
||||
String failure = TrekServerStore.takeFailure(getContext());
|
||||
result.put("failure", failure == null ? JSONObject.NULL : failure);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@@ -328,7 +331,12 @@ public class TrekShellPlugin extends Plugin {
|
||||
TrekServerStore.setServer(getContext(), url, signInHostsOf(call));
|
||||
JSObject labels = call.getObject("labels");
|
||||
if (labels != null) {
|
||||
TrekServerStore.setLabels(getContext(), labels.getString("signInHint"), labels.getString("changeServer"));
|
||||
TrekServerStore.setLabels(
|
||||
getContext(),
|
||||
labels.getString("signInHint"),
|
||||
labels.getString("changeServer"),
|
||||
labels.getString("errorPageHint")
|
||||
);
|
||||
}
|
||||
// A TREK Cloud purchase: the code that signs the buyer in, opened once after the first page.
|
||||
String welcome = call.getString("welcome");
|
||||
@@ -428,7 +436,11 @@ public class TrekShellPlugin extends Plugin {
|
||||
}
|
||||
Uri data = intent.getData();
|
||||
PluginCall call = pendingAuthCall();
|
||||
if (call == null || data == null || !authScheme.equals(data.getScheme())) return;
|
||||
if (call == null) {
|
||||
keepOrphanAuthReturn(intent);
|
||||
return;
|
||||
}
|
||||
if (data == null || !authScheme.equals(data.getScheme())) return;
|
||||
JSObject result = new JSObject();
|
||||
result.put("url", data.toString());
|
||||
call.resolve(result);
|
||||
@@ -454,6 +466,48 @@ public class TrekShellPlugin extends Plugin {
|
||||
}, CANCEL_GRACE_MS);
|
||||
}
|
||||
|
||||
private static final String AUTH_PREFS = "trek_auth_return";
|
||||
/** As long as the server keeps the code it carries (NATIVE_HANDOFF_CODE_TTL_MS), with room to spare. */
|
||||
private static final long ORPHAN_AUTH_TTL_MS = 2 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* A return to the sign-in scheme with no call waiting for it: Android ended
|
||||
* the app while the browser was in front, and the browser's return started
|
||||
* it anew (the launch intent comes through here as well). Kept on disk, as
|
||||
* the process may be new too, until the sign-in page takes it. The return
|
||||
* is then taken off the activity's intent: Capacitor hands the launch intent
|
||||
* in again whenever the activity is created, and Android does as well when
|
||||
* it rebuilds the task from the recent apps.
|
||||
*/
|
||||
private void keepOrphanAuthReturn(Intent intent) {
|
||||
Uri data = intent.getData();
|
||||
if (data == null || !"auth".equals(data.getHost())) return;
|
||||
if (!getContext().getString(R.string.custom_url_scheme).equals(data.getScheme())) return;
|
||||
if (getActivity() != null && getActivity().getIntent() != null && getActivity().getIntent().getData() != null
|
||||
&& data.equals(getActivity().getIntent().getData())) {
|
||||
getActivity().setIntent(new Intent(getActivity().getIntent()).setData(null));
|
||||
}
|
||||
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return;
|
||||
getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString("url", data.toString())
|
||||
.putLong("at", System.currentTimeMillis())
|
||||
.commit();
|
||||
}
|
||||
|
||||
/** The kept return of a sign-in (keepOrphanAuthReturn), once and while fresh; null otherwise. */
|
||||
@PluginMethod
|
||||
public void takeAuthCallback(PluginCall call) {
|
||||
android.content.SharedPreferences prefs = getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE);
|
||||
String url = prefs.getString("url", null);
|
||||
long at = prefs.getLong("at", 0);
|
||||
prefs.edit().clear().commit();
|
||||
boolean fresh = url != null && System.currentTimeMillis() - at <= ORPHAN_AUTH_TTL_MS;
|
||||
JSObject result = new JSObject();
|
||||
result.put("url", fresh ? url : JSONObject.NULL);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
private PluginCall pendingAuthCall() {
|
||||
return authCallId == null ? null : getBridge().getSavedCall(authCallId);
|
||||
}
|
||||
@@ -472,19 +526,98 @@ public class TrekShellPlugin extends Plugin {
|
||||
authBrowserOpen = false;
|
||||
}
|
||||
|
||||
/** iOS only: Android keeps the service worker, which already starts TREK offline. */
|
||||
/**
|
||||
* Keeps the server's UI on the device for a start without the server
|
||||
* (TrekOfflineShell): the start page, and each file of the build that
|
||||
* native/offlineShell.ts lists from the server's manifest and the copy does
|
||||
* not hold yet. Once all of them are there, files of older builds go. A web
|
||||
* view runs no service worker on a plain-http server, the usual address of a
|
||||
* server at home, so without this the app could not start away from it.
|
||||
*/
|
||||
@PluginMethod
|
||||
public void refreshOfflineCopy(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("saved", false);
|
||||
call.resolve(result);
|
||||
Context context = getContext();
|
||||
String server = TrekServerStore.getUrl(context);
|
||||
JSArray listed = call.getArray("files");
|
||||
if (server == null || TrekOfflineShell.isActive()) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("saved", false);
|
||||
call.resolve(result);
|
||||
return;
|
||||
}
|
||||
new Thread(() -> {
|
||||
JSObject result = new JSObject();
|
||||
byte[] page = download(server, "", "text/html");
|
||||
boolean complete = page != null && TrekOfflineShell.beginRefresh(context, server);
|
||||
Set<String> keep = new HashSet<>();
|
||||
if (complete && listed != null) {
|
||||
for (int i = 0; i < listed.length(); i++) {
|
||||
String path = listed.optString(i, null);
|
||||
if (path == null || path.isEmpty()) continue;
|
||||
String clean = path.startsWith("/") ? path.substring(1) : path;
|
||||
keep.add(clean);
|
||||
if (TrekOfflineShell.hasFile(context, clean)) continue;
|
||||
byte[] data = download(server, clean, null);
|
||||
if (data == null || !TrekOfflineShell.saveFile(context, clean, data)) complete = false;
|
||||
}
|
||||
}
|
||||
// The new page goes in last: until all its files are there the
|
||||
// stored page stays the previous one, whose build is still whole.
|
||||
boolean saved = complete && TrekOfflineShell.savePage(context, server, page);
|
||||
complete = saved;
|
||||
if (saved && listed != null) TrekOfflineShell.prune(context, keep);
|
||||
result.put("saved", saved);
|
||||
result.put("complete", complete);
|
||||
call.resolve(result);
|
||||
}).start();
|
||||
}
|
||||
|
||||
/** A file of the server's UI, or null: only a 200 counts, and the page only as HTML. */
|
||||
private static byte[] download(String server, String path, String wantType) {
|
||||
java.net.HttpURLConnection connection = null;
|
||||
try {
|
||||
java.net.URL base = new java.net.URL(server.endsWith("/") ? server : server + "/");
|
||||
java.net.URL url = new java.net.URL(base, path);
|
||||
connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
connection.setConnectTimeout(15000);
|
||||
connection.setReadTimeout(30000);
|
||||
connection.setInstanceFollowRedirects(true);
|
||||
if (wantType != null) connection.setRequestProperty("Accept", wantType);
|
||||
if (connection.getResponseCode() != 200) return null;
|
||||
String type = connection.getContentType();
|
||||
if (wantType != null && (type == null || !type.startsWith(wantType))) return null;
|
||||
try (java.io.InputStream in = connection.getInputStream()) {
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[16384];
|
||||
for (int n = in.read(buffer); n > 0; n = in.read(buffer)) out.write(buffer, 0, n);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} catch (java.io.IOException | RuntimeException e) {
|
||||
return null;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The address screen found the server out of reach: with a copy of its UI
|
||||
* the app restarts on that instead (TrekOfflineShell), the same way it
|
||||
* leaves the server for the address screen. Also for the server an update
|
||||
* asked to check again, whose check then waits for the next launch.
|
||||
*/
|
||||
@PluginMethod
|
||||
public void openOfflineCopy(PluginCall call) {
|
||||
Context context = getContext();
|
||||
JSObject result = new JSObject();
|
||||
result.put("opened", false);
|
||||
if (!TrekOfflineShell.hasCopy(context, TrekServerStore.getUrlOrPrevious(context)) || getActivity() == null) {
|
||||
result.put("opened", false);
|
||||
call.resolve(result);
|
||||
return;
|
||||
}
|
||||
TrekServerStore.markOfflineStart(context);
|
||||
result.put("opened", true);
|
||||
call.resolve(result);
|
||||
restart();
|
||||
}
|
||||
|
||||
// ---- Widgets, shortcuts and the travel day ----
|
||||
@@ -679,6 +812,12 @@ public class TrekShellPlugin extends Plugin {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.restore(getContext(), call);
|
||||
}
|
||||
|
||||
/** Whether this Google account already holds a delivered cloud subscription. */
|
||||
@PluginMethod
|
||||
public void storeHeld(PluginCall call) {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.held(getContext(), call);
|
||||
}
|
||||
|
||||
/** A paid subscription never delivered (it cleared while the app was closed), for the shell to redeem. */
|
||||
@PluginMethod
|
||||
public void storeUnfinished(PluginCall call) {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.net.Uri;
|
||||
import android.util.Log;
|
||||
import android.webkit.ClientCertRequest;
|
||||
import android.webkit.WebResourceError;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebResourceResponse;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import com.getcapacitor.Bridge;
|
||||
import com.getcapacitor.BridgeWebViewClient;
|
||||
import com.liketrek.trek.clientcert.TrekClientIdentity;
|
||||
@@ -27,14 +29,31 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
private final Runnable onUnreachable;
|
||||
/** Told whether the page now shown is a proxy's sign-in page, for the bar with the way out. */
|
||||
private final Consumer<Boolean> onSignInPage;
|
||||
/** Told whether the page now shown is an error page in place of the server's, for the same bar. */
|
||||
private final Consumer<Boolean> onErrorPage;
|
||||
/** The main-frame address that last came back as a 4xx page nobody else handled. */
|
||||
private String errorPageUrl;
|
||||
private final Set<String> signInHosts;
|
||||
/** A page of the server has shown since launch; from then on no sign-in host is learned (SignInRedirect). */
|
||||
private boolean serverShown;
|
||||
/** The page itself failed on the network once already; the next failure goes to the address screen. */
|
||||
private boolean retriedMainFrame;
|
||||
/** The page loaded again after a network error, until that load starts: its error page counts for nothing. */
|
||||
private String retryUrl;
|
||||
private final Bridge bridge;
|
||||
|
||||
TrekWebViewClient(Bridge bridge, Runnable onUnreachable, Consumer<Boolean> onSignInPage, Set<String> signInHosts) {
|
||||
TrekWebViewClient(
|
||||
Bridge bridge,
|
||||
Runnable onUnreachable,
|
||||
Consumer<Boolean> onSignInPage,
|
||||
Consumer<Boolean> onErrorPage,
|
||||
Set<String> signInHosts
|
||||
) {
|
||||
super(bridge);
|
||||
this.bridge = bridge;
|
||||
this.onUnreachable = onUnreachable;
|
||||
this.onSignInPage = onSignInPage;
|
||||
this.onErrorPage = onErrorPage;
|
||||
this.signInHosts = new HashSet<>(signInHosts);
|
||||
}
|
||||
|
||||
@@ -69,13 +88,22 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
@Override
|
||||
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
|
||||
super.doUpdateVisitedHistory(view, url, isReload);
|
||||
if (retryUrl != null) return;
|
||||
onSignInPage.accept(url != null && isSignInHost(Uri.parse(url)));
|
||||
// The 4xx answer arrives before this commit or after it; either way the
|
||||
// flag is read once here, so the next page clears the bar again.
|
||||
boolean error = url != null && url.equals(errorPageUrl);
|
||||
errorPageUrl = null;
|
||||
onErrorPage.accept(error);
|
||||
}
|
||||
|
||||
/** After the server's first page, a pending welcome code opens the welcome page once (TrekServerStore.takeWelcomeUrl). */
|
||||
@Override
|
||||
public void onPageFinished(WebView view, String url) {
|
||||
super.onPageFinished(view, url);
|
||||
// The error page of a load that is about to be retried: not the server's
|
||||
// first page, so no welcome page and no learning of sign-in hosts yet.
|
||||
if (retryUrl != null) return;
|
||||
if (SignInRedirect.onServer(TrekServerStore.getUrl(view.getContext()), url)) serverShown = true;
|
||||
String welcome = TrekServerStore.takeWelcomeUrl(view.getContext());
|
||||
if (welcome != null) view.loadUrl(welcome);
|
||||
@@ -89,9 +117,15 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
return signInHosts.contains(key) || (url.getPort() != -1 && signInHosts.contains(key + ":" + url.getPort()));
|
||||
}
|
||||
|
||||
/** Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt). */
|
||||
/**
|
||||
* Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt),
|
||||
* and while the server is out of reach the UI comes from its stored copy
|
||||
* (TrekOfflineShell).
|
||||
*/
|
||||
@Override
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
|
||||
WebResourceResponse copy = TrekOfflineShell.serve(view.getContext(), bridge, TrekServerStore.getUrl(view.getContext()), request);
|
||||
if (copy != null) return copy;
|
||||
if (com.liketrek.trek.tiles.TrekTileStore.INSTANCE.handles(request)) {
|
||||
WebResourceResponse stored = com.liketrek.trek.tiles.TrekTileStore.INSTANCE.serve(request);
|
||||
if (stored != null) return stored;
|
||||
@@ -117,13 +151,44 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
String server = TrekServerStore.getUrl(view.getContext());
|
||||
Uri serverUri = server == null ? null : Uri.parse(server);
|
||||
if (serverUri != null && TrekClientIdentity.matches(String.valueOf(serverUri.getHost()), serverUri.getPort() > 0 ? serverUri.getPort() : 443, request.getHost(), request.getPort())) {
|
||||
com.liketrek.trek.clientcert.ClientCertWatch.serverAsked(view.getContext(), server, onUnreachable);
|
||||
com.liketrek.trek.clientcert.ClientCertWatch.serverAsked(view.getContext(), server, () -> {
|
||||
TrekServerStore.setFailure(view.getContext(), "client certificate requested");
|
||||
onUnreachable.run();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A page that failed on the network is loaded once more before the app says
|
||||
* the server is unreachable. Started from the background, as when the
|
||||
* browser hands a sign-in back to an app Android had ended, a Samsung phone
|
||||
* may hold its network back for a moment, and the first load fails with the
|
||||
* server there all along. The error is logged, as a report has nothing else.
|
||||
*/
|
||||
@Override
|
||||
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
|
||||
if (request.isForMainFrame()) {
|
||||
Log.w("TrekShell", "Page failed: " + error.getErrorCode() + " " + error.getDescription());
|
||||
if (!retriedMainFrame && isNetworkError(error.getErrorCode())) {
|
||||
retriedMainFrame = true;
|
||||
retryUrl = request.getUrl().toString();
|
||||
view.postDelayed(() -> {
|
||||
String url = retryUrl;
|
||||
retryUrl = null;
|
||||
view.loadUrl(url);
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
// Out of reach for good (a trip without reception, a server at home):
|
||||
// the stored copy of the UI takes over, with the app's own offline data.
|
||||
String server = TrekServerStore.getUrl(view.getContext());
|
||||
if (isNetworkError(error.getErrorCode()) && !TrekOfflineShell.isActive() && TrekOfflineShell.hasCopy(view.getContext(), server)) {
|
||||
TrekOfflineShell.activate(server);
|
||||
String url = request.getUrl().toString();
|
||||
view.post(() -> view.loadUrl(url));
|
||||
return;
|
||||
}
|
||||
TrekServerStore.setFailure(view.getContext(), error.getDescription() + " (" + error.getErrorCode() + ")");
|
||||
onUnreachable.run();
|
||||
return;
|
||||
}
|
||||
@@ -132,10 +197,12 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
|
||||
/**
|
||||
* Only a 5xx on the page itself means the server is down (a proxy's 502 or
|
||||
* 503 while TREK restarts). A 4xx page is left alone: the server answered,
|
||||
* and TREK serves its UI for every other path. The exception is a proxy
|
||||
* that asked this page for a client certificate and got none, as Cloudflare
|
||||
* does with a 403: the address screen then says so and offers to add one.
|
||||
* 503 while TREK restarts). A 4xx page is not TREK's, which serves its UI for
|
||||
* every path: a proxy that asked this page for a client certificate and got
|
||||
* none, as Cloudflare does with a 403, sends the app to the address screen,
|
||||
* which says so and offers to add one. Any other 4xx page (a proxy's block
|
||||
* page, a certificate it refused) stays up with the bar and its way out, so
|
||||
* the app is never stuck on a page without TREK's UI.
|
||||
*/
|
||||
@Override
|
||||
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
|
||||
@@ -143,10 +210,22 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
if (!request.isForMainFrame()) {
|
||||
super.onReceivedHttpError(view, request, errorResponse);
|
||||
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
|
||||
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
|
||||
onUnreachable.run();
|
||||
} else if (status >= 400) {
|
||||
errorPageUrl = request.getUrl().toString();
|
||||
onErrorPage.accept(true);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isNetworkError(int code) {
|
||||
return code == WebViewClient.ERROR_HOST_LOOKUP
|
||||
|| code == WebViewClient.ERROR_CONNECT
|
||||
|| code == WebViewClient.ERROR_TIMEOUT
|
||||
|| code == WebViewClient.ERROR_IO
|
||||
|| code == WebViewClient.ERROR_UNKNOWN;
|
||||
}
|
||||
|
||||
private static boolean wantedCertificate(Uri url) {
|
||||
TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest();
|
||||
return asked != null && !asked.getServed() && TrekClientIdentity.matches(asked.getHost(), asked.getPort(), url.getHost(), url.getPort());
|
||||
|
||||
@@ -119,23 +119,38 @@ object TrekBilling {
|
||||
val id = call.getString("productId") ?: return call.reject("productId is required")
|
||||
ready(activity) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
|
||||
details(activity, listOf(id)) { found ->
|
||||
val product = found.firstOrNull()
|
||||
val offer = product?.let(::baseOffer)
|
||||
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
|
||||
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
|
||||
pendingPurchase = call
|
||||
pendingProduct = id
|
||||
val params = BillingFlowParams.newBuilder()
|
||||
.setProductDetailsParamsList(
|
||||
listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()),
|
||||
)
|
||||
.build()
|
||||
activity.runOnUiThread {
|
||||
val launch = client(activity).launchBillingFlow(activity, params)
|
||||
if (launch.responseCode != BillingClient.BillingResponseCode.OK) {
|
||||
settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null)
|
||||
}
|
||||
// One subscription per Google account: a second plan would run beside the first.
|
||||
// A delivered one stops the purchase here; one that was paid but never set up is
|
||||
// handed back as bought, so its instance is set up now.
|
||||
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
|
||||
client(activity).queryPurchasesAsync(params) { result, purchases ->
|
||||
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
|
||||
when {
|
||||
held == null -> launchPurchase(activity, call, id)
|
||||
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
else -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) {
|
||||
details(activity, listOf(id)) { found ->
|
||||
val product = found.firstOrNull()
|
||||
val offer = product?.let(::baseOffer)
|
||||
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
|
||||
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
|
||||
pendingPurchase = call
|
||||
pendingProduct = id
|
||||
val params = BillingFlowParams.newBuilder()
|
||||
.setProductDetailsParamsList(
|
||||
listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()),
|
||||
)
|
||||
.build()
|
||||
activity.runOnUiThread {
|
||||
val launch = client(activity).launchBillingFlow(activity, params)
|
||||
if (launch.responseCode != BillingClient.BillingResponseCode.OK) {
|
||||
settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,6 +223,19 @@ object TrekBilling {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this Google account holds a delivered subscription under `prefix`; while one runs, the shell offers no purchase. */
|
||||
fun held(context: Context, call: PluginCall) {
|
||||
val prefix = call.getString("prefix") ?: PREFIX
|
||||
ready(context) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject().put("held", false))
|
||||
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
|
||||
client(context).queryPurchasesAsync(params) { result, purchases ->
|
||||
val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, prefix) else null
|
||||
call.resolve(JSObject().put("held", found?.isAcknowledged == true))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The newest active subscription under `prefix` on this Google account, if any. */
|
||||
fun restore(context: Context, call: PluginCall) {
|
||||
val prefix = call.getString("prefix") ?: "cloud."
|
||||
|
||||
@@ -32,6 +32,10 @@ class BookingsWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = BookingsWidget()
|
||||
}
|
||||
|
||||
class FlightWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = FlightWidget()
|
||||
}
|
||||
|
||||
class TodosWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = TodosWidget()
|
||||
}
|
||||
@@ -56,6 +60,7 @@ object TrekWidgetUpdater {
|
||||
TripWidgetReceiver::class,
|
||||
TodayWidgetReceiver::class,
|
||||
BookingsWidgetReceiver::class,
|
||||
FlightWidgetReceiver::class,
|
||||
TodosWidgetReceiver::class,
|
||||
PackingWidgetReceiver::class,
|
||||
AtlasWidgetReceiver::class,
|
||||
|
||||
@@ -448,6 +448,173 @@ private fun BookingRow(booking: WidgetSnapshot.Booking, labels: WidgetSnapshot.L
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Flight ----
|
||||
|
||||
/**
|
||||
* Where a flight stands now (as FlightMoment on iOS). What the feed saw wins: a
|
||||
* flight still at the gate past its planned departure is not flown along the
|
||||
* arc, and it is only landed once confirmed. Only a flight the feed never heard
|
||||
* of moves on by its schedule alone; a lost one stops two hours after arrival.
|
||||
*/
|
||||
private class FlightMoment(f: WidgetSnapshot.Flight, nowSeconds: Long) {
|
||||
val start: Long = f.depActual ?: f.depExpected ?: f.dep
|
||||
val end: Long = maxOf(f.arrExpected ?: f.arr, start + 60)
|
||||
private val heard = f.seen != null
|
||||
val landed = f.landed || (!heard && nowSeconds >= end) || nowSeconds >= end + 7200
|
||||
val airborne = !landed && (f.airborne || f.depActual != null || (!heard && nowSeconds >= start))
|
||||
val ready = !landed && !airborne && nowSeconds >= start
|
||||
val progress: Float = when {
|
||||
landed -> 1f
|
||||
airborne -> ((nowSeconds - start).toFloat() / (end - start)).coerceIn(0f, 0.98f)
|
||||
else -> 0f
|
||||
}
|
||||
}
|
||||
|
||||
/** A duration in the app's words: "2 d 4 h", "1 h 5 min", "12 min". */
|
||||
private fun durationText(seconds: Long, labels: WidgetSnapshot.Labels): String {
|
||||
val minutes = ((seconds + 59) / 60).coerceAtLeast(1)
|
||||
val days = minutes / 1440
|
||||
val hours = (minutes % 1440) / 60
|
||||
val rest = minutes % 60
|
||||
return when {
|
||||
days > 0 -> labels.durDaysHours.replace("{d}", "$days").replace("{h}", "$hours")
|
||||
hours > 0 -> labels.durHoursMinutes.replace("{h}", "$hours").replace("{m}", "$rest")
|
||||
else -> labels.durMinutes.replace("{m}", "$rest")
|
||||
}
|
||||
}
|
||||
|
||||
/** "Departs in 2 h 10 min", "Lands in 1 h 5 min", "Landed". */
|
||||
private fun momentText(m: FlightMoment, labels: WidgetSnapshot.Labels, nowSeconds: Long): String = when {
|
||||
m.landed -> labels.flightLanded
|
||||
m.ready -> labels.flightReady
|
||||
m.airborne -> labels.flightLands.replace("{time}", durationText(m.end - nowSeconds, labels))
|
||||
else -> labels.flightDeparts.replace("{time}", durationText(m.start - nowSeconds, labels))
|
||||
}
|
||||
|
||||
/** The delay as a chip's text and colour; nothing to say without data. */
|
||||
private fun delayChip(delay: Int?, labels: WidgetSnapshot.Labels): Pair<String, ColorProvider>? = when {
|
||||
delay == null -> null
|
||||
delay > 5 -> labels.flightLate.replace("{m}", "$delay") to (if (delay >= 30) TrekStatus.danger else TrekStatus.pending)
|
||||
delay < -5 -> labels.flightEarly.replace("{m}", "${-delay}") to TrekStatus.confirmed
|
||||
else -> labels.flightOnTime to TrekStatus.confirmed
|
||||
}
|
||||
|
||||
private const val FLIGHT_BLUE = 0xFF4A7DDB.toInt()
|
||||
|
||||
/**
|
||||
* The trip's next flight, or the one in the air: both airports large, the
|
||||
* route as an arc with the aircraft on it, the moment in words and the delay.
|
||||
* The arc and the words follow the clock each time the widget is drawn.
|
||||
*/
|
||||
class FlightWidget : TrekWidget() {
|
||||
@Composable
|
||||
override fun Content(snapshot: WidgetSnapshot?) {
|
||||
val context = LocalContext.current
|
||||
val size = LocalSize.current
|
||||
val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context))
|
||||
val flight = snapshot.flight
|
||||
WidgetFrame(onClick = openPath(context, flight?.path ?: snapshot.trip?.path ?: "/")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) {
|
||||
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 14.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
Eyebrow(flight?.number ?: labels.flight, GlanceTheme.colors.primary, GlanceModifier.defaultWeight())
|
||||
flight?.let { f ->
|
||||
delayChip(f.delay, labels)?.let { (text, color) ->
|
||||
if (size.isWide || (f.delay ?: 0) > 5) Chip(text, GlanceTheme.colors.surfaceVariant, color)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (flight == null) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Line(labels.noFlight, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
} else {
|
||||
FlightBody(flight, labels, size.isWide, size.isTall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The origin stands on the right in a right-to-left layout, so the drawn arc is
|
||||
* mirrored with it. Read from the locale the widget speaks, not from the
|
||||
* Configuration, which a composition may not read directly.
|
||||
*/
|
||||
private fun isRtl(): Boolean =
|
||||
android.text.TextUtils.getLayoutDirectionFromLocale(java.util.Locale.getDefault()) == android.view.View.LAYOUT_DIRECTION_RTL
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.FlightBody(f: WidgetSnapshot.Flight, labels: WidgetSnapshot.Labels, wide: Boolean, tall: Boolean) {
|
||||
val now = System.currentTimeMillis() / 1000
|
||||
val m = FlightMoment(f, now)
|
||||
val arrival = f.arrTimeExpected ?: f.arrTime
|
||||
val momentColor = if (m.airborne) GlanceTheme.colors.primary else GlanceTheme.colors.onSurface
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
if (!wide) Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold, maxLines = 2)
|
||||
Spacer(GlanceModifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) {
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
Line(f.from, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold)
|
||||
if (wide) f.fromCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
|
||||
}
|
||||
if (wide) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = GlanceModifier.width(120.dp).height(26.dp),
|
||||
)
|
||||
}
|
||||
Column(modifier = GlanceModifier.defaultWeight(), horizontalAlignment = Alignment.End) {
|
||||
Line(f.to, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold)
|
||||
if (wide) f.toCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
|
||||
}
|
||||
}
|
||||
if (!wide) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.FillBounds,
|
||||
modifier = GlanceModifier.fillMaxWidth().height(22.dp),
|
||||
)
|
||||
}
|
||||
Spacer(GlanceModifier.height(4.dp))
|
||||
Row(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
Line(f.depTime, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold, modifier = GlanceModifier.defaultWeight())
|
||||
Line(arrival, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold)
|
||||
}
|
||||
if (wide) {
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold)
|
||||
if (m.airborne) {
|
||||
Spacer(GlanceModifier.height(5.dp))
|
||||
Bar(m.progress, GlanceTheme.colors.primary, GlanceTheme.colors.surfaceVariant, 5.dp)
|
||||
}
|
||||
}
|
||||
if (tall) {
|
||||
Spacer(GlanceModifier.height(10.dp))
|
||||
f.aircraft?.let { FlightFact(it) }
|
||||
f.fromCity?.let { from -> f.toCity?.let { to -> FlightFact("$from \u2192 $to") } }
|
||||
}
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FlightFact(text: String) {
|
||||
Row(
|
||||
modifier = GlanceModifier.fillMaxWidth().background(GlanceTheme.colors.surfaceVariant).cornerRadius(12.dp)
|
||||
.padding(horizontal = 10.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 13.dp)
|
||||
Spacer(GlanceModifier.width(7.dp))
|
||||
Line(text, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium)
|
||||
}
|
||||
Spacer(GlanceModifier.height(5.dp))
|
||||
}
|
||||
|
||||
// ---- To-dos ----
|
||||
|
||||
/** What is still open for the trip, and how far the packing has come. */
|
||||
|
||||
@@ -149,4 +149,100 @@ object WidgetArt {
|
||||
}
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/**
|
||||
* A flight's route as an arc: dashed ahead, solid where it has flown, a dot
|
||||
* at either airport and an airliner riding the curve at its heading. White
|
||||
* on a translucent track, like the ring; the widget tints nothing, so the
|
||||
* caller passes the flight colour.
|
||||
*/
|
||||
fun flightArc(
|
||||
progress: Float,
|
||||
color: Int,
|
||||
track: Int,
|
||||
width: Int = 600,
|
||||
height: Int = 120,
|
||||
showPlane: Boolean = true,
|
||||
rtl: Boolean = false,
|
||||
): Bitmap {
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
// Right to left the origin stands on the right: the whole drawing is mirrored.
|
||||
if (rtl) canvas.scale(-1f, 1f, width / 2f, height / 2f)
|
||||
val p = progress.coerceIn(0f, 1f)
|
||||
val inset = height * 0.14f
|
||||
val sx = inset
|
||||
val sy = height - inset
|
||||
val ex = width - inset
|
||||
val ey = height - inset
|
||||
val cx = width / 2f
|
||||
val cy = -height * 0.45f
|
||||
val path = android.graphics.Path().apply {
|
||||
moveTo(sx, sy)
|
||||
quadTo(cx, cy, ex, ey)
|
||||
}
|
||||
val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeWidth = height * 0.035f
|
||||
this.color = track
|
||||
pathEffect = android.graphics.DashPathEffect(floatArrayOf(height * 0.02f, height * 0.07f), 0f)
|
||||
}
|
||||
canvas.drawPath(path, line)
|
||||
val measure = android.graphics.PathMeasure(path, false)
|
||||
if (p > 0f) {
|
||||
val flown = android.graphics.Path()
|
||||
measure.getSegment(0f, measure.length * p, flown, true)
|
||||
line.pathEffect = null
|
||||
line.strokeWidth = height * 0.045f
|
||||
line.color = color
|
||||
canvas.drawPath(flown, line)
|
||||
}
|
||||
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
|
||||
canvas.drawCircle(sx, sy, height * 0.05f, dot)
|
||||
val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = if (p >= 1f) Paint.Style.FILL else Paint.Style.STROKE
|
||||
strokeWidth = height * 0.03f
|
||||
this.color = color
|
||||
}
|
||||
canvas.drawCircle(ex, ey, height * 0.06f, ring)
|
||||
if (showPlane) {
|
||||
val pos = FloatArray(2)
|
||||
val tan = FloatArray(2)
|
||||
measure.getPosTan(measure.length * p, pos, tan)
|
||||
canvas.save()
|
||||
canvas.translate(pos[0], pos[1])
|
||||
canvas.rotate(Math.toDegrees(kotlin.math.atan2(tan[1].toDouble(), tan[0].toDouble())).toFloat())
|
||||
val scale = height * 0.012f
|
||||
canvas.scale(scale, scale)
|
||||
canvas.drawCircle(0f, 0f, 13f, Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE })
|
||||
canvas.drawPath(airliner(), Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color })
|
||||
canvas.restore()
|
||||
}
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/** An airliner seen from above, nose along +x, about 18 units long, centred. */
|
||||
private fun airliner(): android.graphics.Path = android.graphics.Path().apply {
|
||||
moveTo(9f, 0f)
|
||||
cubicTo(9f, -0.9f, 8.3f, -1.3f, 7.4f, -1.3f)
|
||||
lineTo(3.2f, -1.3f)
|
||||
lineTo(-1.6f, -7.6f)
|
||||
lineTo(-3.7f, -7.6f)
|
||||
lineTo(-1.4f, -1.3f)
|
||||
lineTo(-5.5f, -1.3f)
|
||||
lineTo(-7.2f, -3.7f)
|
||||
lineTo(-8.8f, -3.7f)
|
||||
lineTo(-7.8f, 0f)
|
||||
lineTo(-8.8f, 3.7f)
|
||||
lineTo(-7.2f, 3.7f)
|
||||
lineTo(-5.5f, 1.3f)
|
||||
lineTo(-1.4f, 1.3f)
|
||||
lineTo(-3.7f, 7.6f)
|
||||
lineTo(-1.6f, 7.6f)
|
||||
lineTo(3.2f, 1.3f)
|
||||
lineTo(7.4f, 1.3f)
|
||||
cubicTo(8.3f, 1.3f, 9f, 0.9f, 9f, 0f)
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,19 @@ import org.json.JSONObject
|
||||
* (WidgetSnapshot.sample in TrekFamily.swift).
|
||||
*/
|
||||
object WidgetSamples {
|
||||
/** In the air on a running trip, two days ahead before one: the same LH 716 as the iOS sample. */
|
||||
private fun flightJson(running: Boolean): String {
|
||||
val now = System.currentTimeMillis() / 1000
|
||||
val dep = if (running) now - 4 * 3600 else now + 2 * 86_400 + 5 * 3600
|
||||
val live = if (running) {
|
||||
""""depActual": ${dep + 18 * 60}, "arrExpected": ${dep + 12 * 3600 + 41 * 60}, "arrTimeExpected": "08:46", "delay": 16, "aircraft": "A359 D-AIXA","""
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return """{"number": "LH 716", "from": "FRA", "to": "HND", "fromCity": "Frankfurt", "toCity": "Tokyo Haneda",
|
||||
"dep": $dep, "arr": ${dep + 12 * 3600 + 25 * 60}, $live "depTime": "13:05", "arrTime": "08:30", "path": "/trips/1?booking=1"}"""
|
||||
}
|
||||
|
||||
fun emptyText(context: Context): String = context.getString(R.string.widget_empty)
|
||||
|
||||
fun snapshot(running: Boolean, now: LocalDate = LocalDate.now()): WidgetSnapshot = WidgetSnapshot.fromJson(JSONObject(json(running, now)))
|
||||
@@ -37,6 +50,7 @@ object WidgetSamples {
|
||||
"place": "Kyoto, Japan", "dayCount": 9, "placeCount": 34, "memberCount": 3},
|
||||
$today
|
||||
"weather": {"temp": 18, "high": 21, "low": 11, "main": "${if (running) "Clear" else "Clouds"}", "label": "Mostly sunny", "place": "Kyoto", "rain": 10},
|
||||
"flight": ${flightJson(running)},
|
||||
"bookings": [
|
||||
{"title": "LH 716", "kind": "flight", "date": "${iso(if (running) 6 else 12)}", "time": "13:05", "detail": "FRA → HND", "confirmed": true, "path": "/trips/1"},
|
||||
{"title": "Shinkansen Nozomi 21", "kind": "train", "date": "${iso(if (running) 0 else 13)}", "time": "09:12", "detail": "Tokyo → Kyoto", "confirmed": true, "path": "/trips/1"},
|
||||
|
||||
@@ -25,6 +25,8 @@ data class WidgetSnapshot(
|
||||
val atlas: Atlas?,
|
||||
val collab: Collab?,
|
||||
val labels: Labels,
|
||||
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
|
||||
val flight: Flight? = null,
|
||||
) {
|
||||
data class Trip(
|
||||
val title: String,
|
||||
@@ -105,6 +107,39 @@ data class WidgetSnapshot(
|
||||
|
||||
data class Collab(val members: List<Member>, val messages: List<Message>, val poll: Poll?, val path: String)
|
||||
|
||||
/**
|
||||
* The flight widget's flight. Times are epoch seconds, so the widget moves on
|
||||
* with the clock between two snapshots; the clock times at either airport
|
||||
* come formatted, since the widget has no zone data.
|
||||
*/
|
||||
data class Flight(
|
||||
val number: String,
|
||||
val from: String,
|
||||
val to: String,
|
||||
val fromCity: String?,
|
||||
val toCity: String?,
|
||||
val dep: Long,
|
||||
val arr: Long,
|
||||
/** Observed take-off. */
|
||||
val depActual: Long?,
|
||||
/** Before take-off: the planned departure plus the delay seen so far. */
|
||||
val depExpected: Long?,
|
||||
/** The feed saw the aircraft in the air when the app last looked. */
|
||||
val airborne: Boolean,
|
||||
/** Touchdown once landed, else the estimate while in the air. */
|
||||
val arrExpected: Long?,
|
||||
val landed: Boolean,
|
||||
val depTime: String,
|
||||
val arrTime: String,
|
||||
val arrTimeExpected: String?,
|
||||
/** Minutes late against the schedule, negative when early. */
|
||||
val delay: Int?,
|
||||
val aircraft: String?,
|
||||
/** When the feed last heard the aircraft; null for a flight it never heard of. */
|
||||
val seen: Long?,
|
||||
val path: String,
|
||||
)
|
||||
|
||||
/** The labels, translated by the app. The optional ones fall back to English. */
|
||||
data class Labels(private val raw: JSONObject) {
|
||||
val nextTrip get() = text("nextTrip", "Next trip")
|
||||
@@ -137,6 +172,23 @@ data class WidgetSnapshot(
|
||||
val votes get() = text("votes", "votes")
|
||||
val noMessages get() = text("noMessages", "No messages yet")
|
||||
val departure get() = text("departure", "Departure")
|
||||
val flight get() = text("flight", "Flight")
|
||||
/** Contains "{time}". */
|
||||
val flightDeparts get() = text("flightDeparts", "Departs in {time}")
|
||||
/** Contains "{time}". */
|
||||
val flightLands get() = text("flightLands", "Lands in {time}")
|
||||
val flightLanded get() = text("flightLanded", "Landed")
|
||||
val flightReady get() = text("flightReady", "Ready for departure")
|
||||
val noFlight get() = text("noFlight", "No flight ahead")
|
||||
val flightOnTime get() = text("flightOnTime", "On time")
|
||||
/** Contains "{m}". */
|
||||
val flightLate get() = text("flightLate", "+{m} min")
|
||||
/** Contains "{m}". */
|
||||
val flightEarly get() = text("flightEarly", "{m} min early")
|
||||
/** Contain "{d}" and "{h}", "{h}" and "{m}", and "{m}". */
|
||||
val durDaysHours get() = text("durDaysHours", "{d} d {h} h")
|
||||
val durHoursMinutes get() = text("durHoursMinutes", "{h} h {m} min")
|
||||
val durMinutes get() = text("durMinutes", "{m} min")
|
||||
|
||||
private fun text(key: String, fallback: String): String = raw.optString(key).ifBlank { fallback }
|
||||
}
|
||||
@@ -240,6 +292,29 @@ data class WidgetSnapshot(
|
||||
)
|
||||
},
|
||||
labels = Labels(o.optJSONObject("labels") ?: JSONObject()),
|
||||
flight = o.optJSONObject("flight")?.let { f ->
|
||||
Flight(
|
||||
number = f.optString("number"),
|
||||
from = f.optString("from"),
|
||||
to = f.optString("to"),
|
||||
fromCity = f.str("fromCity"),
|
||||
toCity = f.str("toCity"),
|
||||
dep = f.optLong("dep"),
|
||||
arr = f.optLong("arr"),
|
||||
depActual = f.long("depActual"),
|
||||
depExpected = f.long("depExpected"),
|
||||
airborne = f.optBoolean("airborne"),
|
||||
arrExpected = f.long("arrExpected"),
|
||||
landed = f.optBoolean("landed"),
|
||||
depTime = f.optString("depTime"),
|
||||
arrTime = f.optString("arrTime"),
|
||||
arrTimeExpected = f.str("arrTimeExpected"),
|
||||
delay = f.int("delay"),
|
||||
aircraft = f.str("aircraft"),
|
||||
seen = f.long("seen"),
|
||||
path = f.optString("path", "/"),
|
||||
)
|
||||
}?.takeIf { it.dep > 0 && it.arr > 0 },
|
||||
)
|
||||
|
||||
fun day(iso: String?): LocalDate? {
|
||||
@@ -258,6 +333,8 @@ data class WidgetSnapshot(
|
||||
|
||||
private fun JSONObject.int(key: String): Int? = if (has(key) && !isNull(key)) optInt(key) else null
|
||||
|
||||
private fun JSONObject.long(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null
|
||||
|
||||
private fun JSONArray?.objects(): List<JSONObject> =
|
||||
if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">خطة اليوم كخط زمني، مع الطقس والمحطة التالية.</string>
|
||||
<string name="widget_bookings_name">الحجوزات</string>
|
||||
<string name="widget_bookings_description">رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها.</string>
|
||||
<string name="widget_flight_name">الرحلة</string>
|
||||
<string name="widget_flight_description">رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول.</string>
|
||||
<string name="widget_todos_name">المهام</string>
|
||||
<string name="widget_todos_description">ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة.</string>
|
||||
<string name="widget_packing_name">قائمة الأمتعة</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Günün planı zaman xətti kimi, hava və növbəti dayanacaqla.</string>
|
||||
<string name="widget_bookings_name">Bronlar</string>
|
||||
<string name="widget_bookings_description">Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə.</string>
|
||||
<string name="widget_flight_name">Uçuş</string>
|
||||
<string name="widget_flight_description">Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş.</string>
|
||||
<string name="widget_todos_name">Tapşırıqlar</string>
|
||||
<string name="widget_todos_description">Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu.</string>
|
||||
<string name="widget_packing_name">Yük siyahısı</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">以时间线显示今天的计划,附带天气和下一站。</string>
|
||||
<string name="widget_bookings_name">预订</string>
|
||||
<string name="widget_bookings_description">你接下来的航班、火车、酒店和餐厅,以及时间。</string>
|
||||
<string name="widget_flight_name">航班</string>
|
||||
<string name="widget_flight_description">实时查看下一班航班:起飞倒计时、飞行中的飞机、延误和到达。</string>
|
||||
<string name="widget_todos_name">待办</string>
|
||||
<string name="widget_todos_description">旅行还剩哪些事没做,以及行李收拾到哪一步。</string>
|
||||
<string name="widget_packing_name">行李</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">以時間軸顯示今天的計畫,附上天氣與下一站。</string>
|
||||
<string name="widget_bookings_name">預訂</string>
|
||||
<string name="widget_bookings_description">你接下來的航班、火車、飯店與餐廳,以及時間。</string>
|
||||
<string name="widget_flight_name">航班</string>
|
||||
<string name="widget_flight_description">即時查看下一班航班:起飛倒數、飛行中的飛機、延誤和抵達。</string>
|
||||
<string name="widget_todos_name">待辦</string>
|
||||
<string name="widget_todos_description">旅行還剩哪些事沒做,以及行李整理到哪一步。</string>
|
||||
<string name="widget_packing_name">行李</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">El pla del dia com a línia de temps, amb el temps i la propera parada.</string>
|
||||
<string name="widget_bookings_name">Reserves</string>
|
||||
<string name="widget_bookings_description">Els teus propers vols, trens, hotels i taules, i quan toquen.</string>
|
||||
<string name="widget_flight_name">Vol</string>
|
||||
<string name="widget_flight_description">El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada.</string>
|
||||
<string name="widget_todos_name">Tasques</string>
|
||||
<string name="widget_todos_description">El que encara queda per al viatge i com va l\'equipatge.</string>
|
||||
<string name="widget_packing_name">Equipatge</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Plán dne jako časová osa, s počasím a další zastávkou.</string>
|
||||
<string name="widget_bookings_name">Rezervace</string>
|
||||
<string name="widget_bookings_description">Tvoje další lety, vlaky, hotely a stoly, a kdy tě čekají.</string>
|
||||
<string name="widget_flight_name">Let</string>
|
||||
<string name="widget_flight_description">Tvůj další let živě: odpočet do odletu, letadlo na cestě, zpoždění a přílet.</string>
|
||||
<string name="widget_todos_name">Úkoly</string>
|
||||
<string name="widget_todos_description">Co ještě zbývá k cestě a jak daleko je balení.</string>
|
||||
<string name="widget_packing_name">Balení</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Der Tagesplan als Zeitleiste, mit dem Wetter und dem nächsten Stopp.</string>
|
||||
<string name="widget_bookings_name">Buchungen</string>
|
||||
<string name="widget_bookings_description">Deine nächsten Flüge, Züge, Hotels und Tische, und wann sie anstehen.</string>
|
||||
<string name="widget_flight_name">Flug</string>
|
||||
<string name="widget_flight_description">Dein nächster Flug live: Countdown bis zum Abflug, die Maschine unterwegs, Verspätung und Ankunft.</string>
|
||||
<string name="widget_todos_name">To-dos</string>
|
||||
<string name="widget_todos_description">Was für die Reise noch offen ist und wie weit das Packen ist.</string>
|
||||
<string name="widget_packing_name">Packliste</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Το πρόγραμμα της ημέρας ως χρονολόγιο, με τον καιρό και την επόμενη στάση.</string>
|
||||
<string name="widget_bookings_name">Κρατήσεις</string>
|
||||
<string name="widget_bookings_description">Οι επόμενες πτήσεις, τα τρένα, τα ξενοδοχεία και τα τραπέζια σου, και πότε είναι.</string>
|
||||
<string name="widget_flight_name">Πτήση</string>
|
||||
<string name="widget_flight_description">Η επόμενη πτήση σου ζωντανά: αντίστροφη μέτρηση για την αναχώρηση, το αεροσκάφος καθ’ οδόν, καθυστέρηση και άφιξη.</string>
|
||||
<string name="widget_todos_name">Εκκρεμότητες</string>
|
||||
<string name="widget_todos_description">Τι μένει ακόμα για το ταξίδι και πόσο έχει προχωρήσει το πακετάρισμα.</string>
|
||||
<string name="widget_packing_name">Αποσκευές</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">El plan del día como línea de tiempo, con el tiempo y la próxima parada.</string>
|
||||
<string name="widget_bookings_name">Reservas</string>
|
||||
<string name="widget_bookings_description">Tus próximos vuelos, trenes, hoteles y mesas, y cuándo tocan.</string>
|
||||
<string name="widget_flight_name">Vuelo</string>
|
||||
<string name="widget_flight_description">Tu próximo vuelo en directo: cuenta atrás de la salida, el avión en camino, retraso y llegada.</string>
|
||||
<string name="widget_todos_name">Tareas</string>
|
||||
<string name="widget_todos_description">Lo que aún queda para el viaje y cómo va la maleta.</string>
|
||||
<string name="widget_packing_name">Equipaje</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Päeva plaan ajajoonena, koos ilma ja järgmise peatusega.</string>
|
||||
<string name="widget_bookings_name">Broneeringud</string>
|
||||
<string name="widget_bookings_description">Sinu järgmised lennud, rongid, hotellid ja lauad ning millal need on.</string>
|
||||
<string name="widget_flight_name">Lend</string>
|
||||
<string name="widget_flight_description">Sinu järgmine lend otse: loendus väljumiseni, lennuk teel, hilinemine ja saabumine.</string>
|
||||
<string name="widget_todos_name">Ülesanded</string>
|
||||
<string name="widget_todos_description">Mis reisi jaoks veel tegemata on ja kui kaugel pakkimine on.</string>
|
||||
<string name="widget_packing_name">Pakkimine</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Le programme du jour en frise, avec la météo et la prochaine étape.</string>
|
||||
<string name="widget_bookings_name">Réservations</string>
|
||||
<string name="widget_bookings_description">Vos prochains vols, trains, hôtels et tables, et quand ils arrivent.</string>
|
||||
<string name="widget_flight_name">Vol</string>
|
||||
<string name="widget_flight_description">Votre prochain vol en direct : compte à rebours du départ, l’avion en route, retard et arrivée.</string>
|
||||
<string name="widget_todos_name">À faire</string>
|
||||
<string name="widget_todos_description">Ce qui reste à faire pour le voyage et où en sont les bagages.</string>
|
||||
<string name="widget_packing_name">Bagages</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">A nap terve idővonalon, az időjárással és a következő megállóval.</string>
|
||||
<string name="widget_bookings_name">Foglalások</string>
|
||||
<string name="widget_bookings_description">A következő járataid, vonataid, szállásaid és asztalfoglalásaid, és hogy mikor esedékesek.</string>
|
||||
<string name="widget_flight_name">Járat</string>
|
||||
<string name="widget_flight_description">A következő járatod élőben: visszaszámlálás az indulásig, a gép útközben, késés és érkezés.</string>
|
||||
<string name="widget_todos_name">Teendők</string>
|
||||
<string name="widget_todos_description">Ami még hátravan az utazáshoz, és hol tart a csomagolás.</string>
|
||||
<string name="widget_packing_name">Csomagolás</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Rencana hari ini sebagai linimasa, dengan cuaca dan perhentian berikutnya.</string>
|
||||
<string name="widget_bookings_name">Pemesanan</string>
|
||||
<string name="widget_bookings_description">Penerbangan, kereta, hotel, dan meja berikutnya, beserta waktunya.</string>
|
||||
<string name="widget_flight_name">Penerbangan</string>
|
||||
<string name="widget_flight_description">Penerbangan berikutnya secara langsung: hitung mundur keberangkatan, pesawat dalam perjalanan, keterlambatan, dan kedatangan.</string>
|
||||
<string name="widget_todos_name">Tugas</string>
|
||||
<string name="widget_todos_description">Yang masih tersisa untuk perjalanan dan sejauh mana persiapan barang.</string>
|
||||
<string name="widget_packing_name">Barang bawaan</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Il programma del giorno come linea del tempo, con il meteo e la prossima tappa.</string>
|
||||
<string name="widget_bookings_name">Prenotazioni</string>
|
||||
<string name="widget_bookings_description">I tuoi prossimi voli, treni, hotel e tavoli, e quando sono.</string>
|
||||
<string name="widget_flight_name">Volo</string>
|
||||
<string name="widget_flight_description">Il tuo prossimo volo in tempo reale: conto alla rovescia per la partenza, l’aereo in viaggio, ritardo e arrivo.</string>
|
||||
<string name="widget_todos_name">Da fare</string>
|
||||
<string name="widget_todos_description">Cosa manca ancora per il viaggio e a che punto è la valigia.</string>
|
||||
<string name="widget_packing_name">Bagagli</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">תוכנית היום כציר זמן, עם מזג האוויר והעצירה הבאה.</string>
|
||||
<string name="widget_bookings_name">הזמנות</string>
|
||||
<string name="widget_bookings_description">הטיסות, הרכבות, המלונות והשולחנות הבאים שלך, ומתי הם.</string>
|
||||
<string name="widget_flight_name">טיסה</string>
|
||||
<string name="widget_flight_description">הטיסה הבאה שלך בזמן אמת: ספירה לאחור עד ההמראה, המטוס בדרך, עיכוב והגעה.</string>
|
||||
<string name="widget_todos_name">משימות</string>
|
||||
<string name="widget_todos_description">מה עוד פתוח לטיול וכמה התקדמה האריזה.</string>
|
||||
<string name="widget_packing_name">אריזה</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">今日の予定をタイムラインで、天気と次の予定とともに表示します。</string>
|
||||
<string name="widget_bookings_name">予約</string>
|
||||
<string name="widget_bookings_description">次のフライト、列車、ホテル、レストランとその日時。</string>
|
||||
<string name="widget_flight_name">フライト</string>
|
||||
<string name="widget_flight_description">次のフライトをライブで:出発までのカウントダウン、飛行中の機体、遅延と到着。</string>
|
||||
<string name="widget_todos_name">やること</string>
|
||||
<string name="widget_todos_description">旅行のために残っていることと、荷造りの進み具合。</string>
|
||||
<string name="widget_packing_name">持ち物</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">오늘 일정을 타임라인으로, 날씨와 다음 장소와 함께 보여 줍니다.</string>
|
||||
<string name="widget_bookings_name">예약</string>
|
||||
<string name="widget_bookings_description">다가오는 항공편, 기차, 호텔, 식당과 그 시간.</string>
|
||||
<string name="widget_flight_name">항공편</string>
|
||||
<string name="widget_flight_description">다음 항공편을 실시간으로: 출발 카운트다운, 비행 중인 항공기, 지연과 도착.</string>
|
||||
<string name="widget_todos_name">할 일</string>
|
||||
<string name="widget_todos_description">여행을 위해 남은 일과 짐 싸기 진행 상황.</string>
|
||||
<string name="widget_packing_name">짐 싸기</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Het dagplan als tijdlijn, met het weer en de volgende stop.</string>
|
||||
<string name="widget_bookings_name">Boekingen</string>
|
||||
<string name="widget_bookings_description">Je volgende vluchten, treinen, hotels en tafels, en wanneer ze zijn.</string>
|
||||
<string name="widget_flight_name">Vlucht</string>
|
||||
<string name="widget_flight_description">Je volgende vlucht live: aftellen tot vertrek, het toestel onderweg, vertraging en aankomst.</string>
|
||||
<string name="widget_todos_name">Taken</string>
|
||||
<string name="widget_todos_description">Wat er nog openstaat voor de reis en hoe ver het inpakken is.</string>
|
||||
<string name="widget_packing_name">Bagage</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Plan dnia jako oś czasu, z pogodą i kolejnym przystankiem.</string>
|
||||
<string name="widget_bookings_name">Rezerwacje</string>
|
||||
<string name="widget_bookings_description">Twoje najbliższe loty, pociągi, hotele i stoliki oraz ich terminy.</string>
|
||||
<string name="widget_flight_name">Lot</string>
|
||||
<string name="widget_flight_description">Twój następny lot na żywo: odliczanie do odlotu, samolot w drodze, opóźnienie i przylot.</string>
|
||||
<string name="widget_todos_name">Zadania</string>
|
||||
<string name="widget_todos_description">Co jeszcze zostało do zrobienia przed podróżą i jak idzie pakowanie.</string>
|
||||
<string name="widget_packing_name">Pakowanie</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">O plano do dia como linha do tempo, com o clima e a próxima parada.</string>
|
||||
<string name="widget_bookings_name">Reservas</string>
|
||||
<string name="widget_bookings_description">Seus próximos voos, trens, hotéis e mesas, e quando acontecem.</string>
|
||||
<string name="widget_flight_name">Voo</string>
|
||||
<string name="widget_flight_description">Seu próximo voo ao vivo: contagem regressiva para a partida, o avião a caminho, atraso e chegada.</string>
|
||||
<string name="widget_todos_name">Tarefas</string>
|
||||
<string name="widget_todos_description">O que ainda falta para a viagem e quanto da mala já está pronto.</string>
|
||||
<string name="widget_packing_name">Bagagem</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">План дня в виде ленты времени, с погодой и следующей остановкой.</string>
|
||||
<string name="widget_bookings_name">Бронирования</string>
|
||||
<string name="widget_bookings_description">Ближайшие рейсы, поезда, отели и столики и когда они.</string>
|
||||
<string name="widget_flight_name">Рейс</string>
|
||||
<string name="widget_flight_description">Ваш следующий рейс в реальном времени: отсчёт до вылета, самолёт в пути, задержка и прибытие.</string>
|
||||
<string name="widget_todos_name">Задачи</string>
|
||||
<string name="widget_todos_description">Что ещё осталось сделать к поездке и как идут сборы.</string>
|
||||
<string name="widget_packing_name">Сборы</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Plán dňa ako časová os, s počasím a ďalšou zastávkou.</string>
|
||||
<string name="widget_bookings_name">Rezervácie</string>
|
||||
<string name="widget_bookings_description">Tvoje ďalšie lety, vlaky, hotely a stoly a kedy ťa čakajú.</string>
|
||||
<string name="widget_flight_name">Let</string>
|
||||
<string name="widget_flight_description">Tvoj ďalší let naživo: odpočet do odletu, lietadlo na ceste, meškanie a prílet.</string>
|
||||
<string name="widget_todos_name">Úlohy</string>
|
||||
<string name="widget_todos_description">Čo ešte zostáva na cestu a ako ďaleko je balenie.</string>
|
||||
<string name="widget_packing_name">Balenie</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Dagens plan som tidslinje, med vädret och nästa stopp.</string>
|
||||
<string name="widget_bookings_name">Bokningar</string>
|
||||
<string name="widget_bookings_description">Dina nästa flyg, tåg, hotell och bord, och när de är.</string>
|
||||
<string name="widget_flight_name">Flyg</string>
|
||||
<string name="widget_flight_description">Ditt nästa flyg live: nedräkning till avgång, planet på väg, försening och ankomst.</string>
|
||||
<string name="widget_todos_name">Att göra</string>
|
||||
<string name="widget_todos_description">Vad som återstår inför resan och hur långt packningen har kommit.</string>
|
||||
<string name="widget_packing_name">Packning</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">แผนของวันนี้เป็นไทม์ไลน์ พร้อมสภาพอากาศและจุดหมายถัดไป</string>
|
||||
<string name="widget_bookings_name">การจอง</string>
|
||||
<string name="widget_bookings_description">เที่ยวบิน รถไฟ โรงแรม และร้านอาหารถัดไปของคุณ และเวลาของแต่ละรายการ</string>
|
||||
<string name="widget_flight_name">เที่ยวบิน</string>
|
||||
<string name="widget_flight_description">เที่ยวบินถัดไปแบบสด: นับถอยหลังถึงเวลาออกเดินทาง เครื่องบินระหว่างทาง ความล่าช้า และเวลาถึง</string>
|
||||
<string name="widget_todos_name">สิ่งที่ต้องทำ</string>
|
||||
<string name="widget_todos_description">สิ่งที่ยังค้างอยู่สำหรับทริป และความคืบหน้าการจัดกระเป๋า</string>
|
||||
<string name="widget_packing_name">จัดกระเป๋า</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Günün planı zaman çizelgesi olarak, hava durumu ve sonraki durakla.</string>
|
||||
<string name="widget_bookings_name">Rezervasyonlar</string>
|
||||
<string name="widget_bookings_description">Sıradaki uçuşların, trenlerin, otellerin ve masaların, ne zaman oldukları ile.</string>
|
||||
<string name="widget_flight_name">Uçuş</string>
|
||||
<string name="widget_flight_description">Bir sonraki uçuşun canlı: kalkışa geri sayım, yoldaki uçak, gecikme ve varış.</string>
|
||||
<string name="widget_todos_name">Yapılacaklar</string>
|
||||
<string name="widget_todos_description">Seyahat için hâlâ açık olanlar ve bavulun ne durumda olduğu.</string>
|
||||
<string name="widget_packing_name">Bavul</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">План дня у вигляді стрічки часу, з погодою і наступною зупинкою.</string>
|
||||
<string name="widget_bookings_name">Бронювання</string>
|
||||
<string name="widget_bookings_description">Найближчі рейси, поїзди, готелі й столики та коли вони.</string>
|
||||
<string name="widget_flight_name">Рейс</string>
|
||||
<string name="widget_flight_description">Ваш наступний рейс наживо: відлік до вильоту, літак у дорозі, затримка й прибуття.</string>
|
||||
<string name="widget_todos_name">Завдання</string>
|
||||
<string name="widget_todos_description">Що ще лишилося зробити до подорожі і як просувається пакування.</string>
|
||||
<string name="widget_packing_name">Пакування</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Kế hoạch hôm nay dạng dòng thời gian, kèm thời tiết và điểm dừng tiếp theo.</string>
|
||||
<string name="widget_bookings_name">Đặt chỗ</string>
|
||||
<string name="widget_bookings_description">Các chuyến bay, tàu, khách sạn và bàn sắp tới của bạn, cùng thời gian.</string>
|
||||
<string name="widget_flight_name">Chuyến bay</string>
|
||||
<string name="widget_flight_description">Chuyến bay tiếp theo trực tiếp: đếm ngược giờ khởi hành, máy bay đang bay, độ trễ và giờ đến.</string>
|
||||
<string name="widget_todos_name">Việc cần làm</string>
|
||||
<string name="widget_todos_description">Những gì còn lại cho chuyến đi và việc soạn hành lý đã tới đâu.</string>
|
||||
<string name="widget_packing_name">Hành lý</string>
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
<string name="widget_today_description">Today\'s plan as a timeline, with the weather and what is next.</string>
|
||||
<string name="widget_bookings_name">Bookings</string>
|
||||
<string name="widget_bookings_description">Your next flights, trains, hotels and tables, and when they are due.</string>
|
||||
<string name="widget_flight_name">Flight</string>
|
||||
<string name="widget_flight_description">Your next flight live: departure countdown, the aircraft on its way, delay and arrival.</string>
|
||||
<string name="widget_todos_name">To-dos</string>
|
||||
<string name="widget_todos_description">What is still open for the trip, and how far the packing has come.</string>
|
||||
<string name="widget_packing_name">Packing</string>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The flight widget (widget/TrekWidgets.kt). Sizes in cells for Android 12+, dp before.
|
||||
No previewImage: Glance draws the picker preview from the sample trip (providePreview). -->
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:description="@string/widget_flight_description"
|
||||
android:initialLayout="@layout/glance_default_loading_layout"
|
||||
android:minWidth="110dp"
|
||||
android:minHeight="110dp"
|
||||
android:minResizeWidth="110dp"
|
||||
android:minResizeHeight="110dp"
|
||||
android:maxResizeWidth="530dp"
|
||||
android:maxResizeHeight="450dp"
|
||||
android:targetCellWidth="4"
|
||||
android:targetCellHeight="2"
|
||||
android:resizeMode="horizontal|vertical"
|
||||
android:updatePeriodMillis="1800000"
|
||||
android:widgetCategory="home_screen"
|
||||
android:configure="com.liketrek.trek.widget.WidgetConfigActivity"
|
||||
android:widgetFeatures="reconfigurable|configuration_optional" />
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.liketrek.trek
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** The stored copy of the server's UI (TrekOfflineShell), on a plain folder. */
|
||||
class TrekOfflineShellTest {
|
||||
private val root: File = Files.createTempDirectory("offline-shell").toFile()
|
||||
|
||||
@After
|
||||
fun cleanUp() {
|
||||
TrekOfflineShell.deactivate()
|
||||
root.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theCopyAnswersOnlyForTheServerItWasStartedFor() {
|
||||
TrekOfflineShell.activate("https://a.example.com")
|
||||
assertTrue(TrekOfflineShell.isActive())
|
||||
assertTrue(TrekOfflineShell.isActiveFor("https://a.example.com"))
|
||||
// Another server picked in the same process: its pages come from the server.
|
||||
assertFalse(TrekOfflineShell.isActiveFor("https://b.example.com"))
|
||||
assertFalse(TrekOfflineShell.isActiveFor(null))
|
||||
// A start that reaches the server leaves the copy behind.
|
||||
TrekOfflineShell.deactivate()
|
||||
assertFalse(TrekOfflineShell.isActive())
|
||||
assertFalse(TrekOfflineShell.isActiveFor("https://a.example.com"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefreshCutOffHalfwayKeepsThePreviousBuildWhole() {
|
||||
val server = "https://a.example.com"
|
||||
val oldPage = "<script src=/assets/index-old.js>".toByteArray()
|
||||
assertTrue(TrekOfflineShell.beginRefresh(root, server))
|
||||
assertTrue(TrekOfflineShell.saveFile(root, "assets/index-old.js", byteArrayOf(1)))
|
||||
assertTrue(TrekOfflineShell.savePage(root, server, oldPage))
|
||||
assertTrue(TrekOfflineShell.hasCopy(root, server))
|
||||
|
||||
// The next build: one file arrives, then the connection drops before the page is taken over.
|
||||
assertTrue(TrekOfflineShell.beginRefresh(root, server))
|
||||
assertTrue(TrekOfflineShell.saveFile(root, "assets/index-new.js", byteArrayOf(2)))
|
||||
|
||||
assertTrue(TrekOfflineShell.hasCopy(root, server))
|
||||
assertArrayEquals(oldPage, File(root, "index.html").readBytes())
|
||||
assertTrue(TrekOfflineShell.hasFile(root, "assets/index-old.js"))
|
||||
// The file already fetched stays for the next try.
|
||||
assertTrue(TrekOfflineShell.hasFile(root, "assets/index-new.js"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCompleteRefreshTakesTheNewPageAndDropsTheOldBuild() {
|
||||
val server = "https://a.example.com"
|
||||
TrekOfflineShell.beginRefresh(root, server)
|
||||
TrekOfflineShell.saveFile(root, "assets/index-old.js", byteArrayOf(1))
|
||||
TrekOfflineShell.savePage(root, server, "old".toByteArray())
|
||||
|
||||
TrekOfflineShell.beginRefresh(root, server)
|
||||
TrekOfflineShell.saveFile(root, "assets/index-new.js", byteArrayOf(2))
|
||||
assertTrue(TrekOfflineShell.savePage(root, server, "new".toByteArray()))
|
||||
TrekOfflineShell.prune(root, setOf("assets/index-new.js"))
|
||||
|
||||
assertArrayEquals("new".toByteArray(), File(root, "index.html").readBytes())
|
||||
assertTrue(TrekOfflineShell.hasFile(root, "assets/index-new.js"))
|
||||
assertFalse(TrekOfflineShell.hasFile(root, "assets/index-old.js"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefreshForAnotherServerThrowsTheOldCopyAwayFirst() {
|
||||
TrekOfflineShell.beginRefresh(root, "https://a.example.com")
|
||||
TrekOfflineShell.saveFile(root, "assets/index-a.js", byteArrayOf(1))
|
||||
TrekOfflineShell.savePage(root, "https://a.example.com", "a".toByteArray())
|
||||
|
||||
assertTrue(TrekOfflineShell.beginRefresh(root, "https://b.example.com"))
|
||||
|
||||
assertFalse(TrekOfflineShell.hasCopy(root, "https://a.example.com"))
|
||||
assertFalse(TrekOfflineShell.hasCopy(root, "https://b.example.com"))
|
||||
assertFalse(TrekOfflineShell.hasFile(root, "assets/index-a.js"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pathsOutsideTheCopyAreRefused() {
|
||||
assertFalse(TrekOfflineShell.saveFile(root, "../escape.js", byteArrayOf(1)))
|
||||
assertFalse(TrekOfflineShell.saveFile(root, "assets/index.js?v=1", byteArrayOf(1)))
|
||||
assertFalse(TrekOfflineShell.hasFile(root, ""))
|
||||
}
|
||||
}
|
||||
@@ -375,7 +375,7 @@ const SCRIPTS: Record<string, GuideScript> = {
|
||||
only(p => section(p, 'Authentication Methods').getByText('Password Login', { exact: true }).locator('xpath=../..')),
|
||||
// The SSO rows exist only once OIDC is configured; the run shows where that happens.
|
||||
only(p => section(p, 'Single Sign-On (OIDC)')),
|
||||
only(p => section(p, 'Require two-factor authentication (2FA)')),
|
||||
only(p => section(p, 'Require 2FA')),
|
||||
],
|
||||
},
|
||||
'admin-passkeys': {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// The chunk group that holds the lucide icons the app loads at startup (vite.config.js).
|
||||
//
|
||||
// Every lucide icon is a module of its own, and the plugin icon lookup
|
||||
// (src/components/shared/PluginIcon.tsx) reaches all of them by name, from the navigation
|
||||
// every page renders. Left to itself the bundler puts each icon that some other chunk
|
||||
// also uses into a chunk of its own, so that neither side holds a copy: 187 files of a few
|
||||
// hundred bytes each, every one a request of its own on a first visit and an entry of its
|
||||
// own in the service worker's precache. In one group they are one file, whose hash changes
|
||||
// only when lucide-react does.
|
||||
//
|
||||
// `tags: ['$initial']` for the reason the other groups carry it: without it the group would
|
||||
// also take icons that today sit behind a lazy route and make them part of the first load.
|
||||
export const ICON_CHUNK = {
|
||||
name: 'vendor-icons',
|
||||
priority: 20,
|
||||
tags: ['$initial'],
|
||||
test: /[\\/]node_modules[\\/]lucide-react[\\/]/,
|
||||
};
|
||||
@@ -37,6 +37,7 @@
|
||||
512499AF65E091B2BBC9A7BB /* UniformTypeIdentifiers.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E45050B942C96E1ACCAB7CE9 /* UniformTypeIdentifiers.framework */; };
|
||||
5480CCC12F42E9605044AB6B /* ShareHandoff.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56050CCA8DE4BEB4680D9E0B /* ShareHandoff.swift */; };
|
||||
5A4D344328829E0F0B4D2B94 /* BookingsContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */; };
|
||||
F11E0C0A9B7D4E2A8C3F5A01 /* FlightContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */; };
|
||||
5BBE9EE02A47EC67C31F5E21 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = D0A4B2C6C93971E884561CFA /* Localizable.strings */; };
|
||||
612BB9680DC27BB8BF553060 /* TrekFamily.swift in Sources */ = {isa = PBXBuildFile; fileRef = A030A06726542A2D7F61C54B /* TrekFamily.swift */; };
|
||||
634F4E63DC7C2A0027F0D118 /* Details.swift in Sources */ = {isa = PBXBuildFile; fileRef = F406A4A31BD875A880A7CA14 /* Details.swift */; };
|
||||
@@ -305,6 +306,7 @@
|
||||
E5800E4ECECED54A47CDABAA /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/Localizable.strings; sourceTree = "<group>"; };
|
||||
E6831E849332626BE8D54CEF /* ShareView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ShareView.swift; sourceTree = "<group>"; };
|
||||
E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BookingsContent.swift; sourceTree = "<group>"; };
|
||||
F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FlightContent.swift; sourceTree = "<group>"; };
|
||||
EAFBDD97043B34E4B64FDA86 /* pt-BR */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/Localizable.strings"; sourceTree = "<group>"; };
|
||||
EC8D1292C9FC6430C059960A /* nl */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = nl; path = nl.lproj/Localizable.strings; sourceTree = "<group>"; };
|
||||
ECC80E1314B31ED2D2347411 /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/Localizable.strings; sourceTree = "<group>"; };
|
||||
@@ -538,6 +540,7 @@
|
||||
DE6873D246AC6B8E2CB6C8B4 /* TripContent.swift */,
|
||||
24B175DE91E1E6E850DB0285 /* TodayContent.swift */,
|
||||
E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */,
|
||||
F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */,
|
||||
AEF7DCAA1AEE67F1291668D1 /* TodosContent.swift */,
|
||||
);
|
||||
name = TREKWidgets;
|
||||
@@ -849,6 +852,7 @@
|
||||
8FC5873BE6A8CB2AFB31A46A /* TripContent.swift in Sources */,
|
||||
9A175689CFCC630BE9BB9EE1 /* TodayContent.swift in Sources */,
|
||||
5A4D344328829E0F0B4D2B94 /* BookingsContent.swift in Sources */,
|
||||
F11E0C0A9B7D4E2A8C3F5A01 /* FlightContent.swift in Sources */,
|
||||
F1E29B18C5B1E75A5BC01B57 /* TodosContent.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<string>TREK</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
|
||||
@@ -17,6 +17,11 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
for context in connectionOptions.urlContexts where context.url.isFileURL {
|
||||
TrekSharedFiles.receive(context.url)
|
||||
}
|
||||
// Launched by a tap on a widget or a Live Activity: held like a quick action.
|
||||
// Capacitor still hears of the link, the UI ignores it there (feature appLinks).
|
||||
for context in connectionOptions.urlContexts {
|
||||
if let path = TrekQuickActions.appLinkPath(context.url) { TrekQuickActions.open(path: path) }
|
||||
}
|
||||
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
|
||||
}
|
||||
|
||||
@@ -40,7 +45,14 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
// com.liketrek.trek://share: the share sheet left an item for the import.
|
||||
let handoffs = URLContexts.filter { $0.url.scheme == "com.liketrek.trek" && $0.url.host == "share" }
|
||||
if !handoffs.isEmpty { TrekSharedFiles.receiveFromShareExtension() }
|
||||
let others = URLContexts.subtracting(files).subtracting(handoffs)
|
||||
// com.liketrek.trek://navigate/<path>: a widget or Live Activity tap. Through
|
||||
// Capacitor it was an event a page reloading after the system ended its process
|
||||
// never heard, and that page then took the same link for one already followed.
|
||||
let appLinks = URLContexts.filter { TrekQuickActions.appLinkPath($0.url) != nil }
|
||||
for context in appLinks {
|
||||
if let path = TrekQuickActions.appLinkPath(context.url) { TrekQuickActions.open(path: path) }
|
||||
}
|
||||
let others = URLContexts.subtracting(files).subtracting(handoffs).subtracting(appLinks)
|
||||
if !others.isEmpty { SceneDelegateProxy.shared.scene(scene, openURLContexts: others) }
|
||||
}
|
||||
|
||||
@@ -104,10 +116,25 @@ enum TrekQuickActions {
|
||||
|
||||
static func open(_ item: UIApplicationShortcutItem) -> Bool {
|
||||
guard let path = item.userInfo?[pathKey] as? String, path.hasPrefix("/") else { return false }
|
||||
if let onOpen { onOpen(path) } else { pending = path }
|
||||
open(path: path)
|
||||
return true
|
||||
}
|
||||
|
||||
/// A path to open: at once when the UI listens, else held for it to take.
|
||||
/// Widget and Live Activity taps come this way too, so each is followed once.
|
||||
static func open(path: String) {
|
||||
if let onOpen { onOpen(path) } else { pending = path }
|
||||
}
|
||||
|
||||
/// The path in com.liketrek.trek://navigate/<path>, the link widgets and Live Activities open.
|
||||
static func appLinkPath(_ url: URL) -> String? {
|
||||
let prefix = "com.liketrek.trek://navigate"
|
||||
guard url.absoluteString.hasPrefix(prefix) else { return nil }
|
||||
let path = String(url.absoluteString.dropFirst(prefix.count))
|
||||
if path.isEmpty { return "/" }
|
||||
return path.hasPrefix("/") ? path : nil
|
||||
}
|
||||
|
||||
/// The action the app was launched with, once.
|
||||
static func take() -> String? {
|
||||
defer { pending = nil }
|
||||
|
||||
@@ -41,6 +41,8 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
// reachable" with a server that was there all along.
|
||||
if let webView, let inner = webView.navigationDelegate {
|
||||
let proxy = TrekNavigationProxy(inner: inner)
|
||||
proxy.onErrorPage = { [weak self] error in self?.errorPageChanged(error) }
|
||||
proxy.onPageShown = { [weak self] in self?.publishSafeArea(force: true) }
|
||||
navigationProxy = proxy
|
||||
webView.navigationDelegate = proxy
|
||||
}
|
||||
@@ -55,6 +57,108 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
// A long press on a link would lift a preview of the page it points to,
|
||||
// which no native list does; the press means "drag" or nothing here.
|
||||
webView?.allowsLinkPreview = false
|
||||
paintBehindWebView()
|
||||
}
|
||||
|
||||
// MARK: - What shows where the web view does not reach
|
||||
|
||||
/// The UI reports its theme through StatusBar.setStyle (native/nativeApp.ts),
|
||||
/// which lands here; the colour behind the web view follows it.
|
||||
override func setNeedsStatusBarAppearanceUpdate() {
|
||||
super.setNeedsStatusBarAppearanceUpdate()
|
||||
paintBehindWebView()
|
||||
}
|
||||
|
||||
/// Some iOS releases (27.0.x) lay the web view out below the status bar
|
||||
/// instead of under it, and the strip above the page then showed this
|
||||
/// view's black. It now carries the top colour of the screen background
|
||||
/// (mobile.css --m-scr), so the strip reads as part of the page on every
|
||||
/// release, and the rubber band at the ends shows the same colour.
|
||||
private func paintBehindWebView() {
|
||||
let dark: Bool
|
||||
switch preferredStatusBarStyle {
|
||||
case .lightContent: dark = true
|
||||
case .darkContent: dark = false
|
||||
default: dark = traitCollection.userInterfaceStyle == .dark
|
||||
}
|
||||
let color = dark
|
||||
? UIColor(red: 0x17 / 255, green: 0x17 / 255, blue: 0x1C / 255, alpha: 1)
|
||||
: UIColor(red: 0xFB / 255, green: 0xFA / 255, blue: 0xF7 / 255, alpha: 1)
|
||||
view.backgroundColor = color
|
||||
webView?.scrollView.backgroundColor = color
|
||||
webView?.underPageBackgroundColor = color
|
||||
}
|
||||
|
||||
// MARK: - The safe area the page keeps clear of
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
publishSafeArea()
|
||||
}
|
||||
|
||||
override func viewSafeAreaInsetsDidChange() {
|
||||
super.viewSafeAreaInsetsDidChange()
|
||||
publishSafeArea()
|
||||
}
|
||||
|
||||
private var publishedSafeArea: UIEdgeInsets?
|
||||
|
||||
/// WebKit's env(safe-area-inset-*) is the window's safe area only where the
|
||||
/// web view overlaps it. Where a release lays the web view out below the
|
||||
/// status bar it reports 0, yet a camera in a corner can still reach into
|
||||
/// the page. The part of the window's safe area (and of the status bar) that
|
||||
/// falls inside the web view goes to the page as --trek-native-safe-*, which
|
||||
/// mobile.css takes as a floor under env(), never in its place.
|
||||
func publishSafeArea(force: Bool = false) {
|
||||
guard let webView, let window = view.window else { return }
|
||||
let frame = webView.convert(webView.bounds, to: window)
|
||||
let safe = window.safeAreaInsets
|
||||
let statusBar = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
|
||||
let insets = UIEdgeInsets(
|
||||
top: max(0, max(safe.top, statusBar) - frame.minY),
|
||||
left: max(0, safe.left - frame.minX),
|
||||
bottom: max(0, safe.bottom - (window.bounds.maxY - frame.maxY)),
|
||||
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
|
||||
)
|
||||
let corner = cornerElement(in: frame, window: window)
|
||||
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
|
||||
publishedSafeArea = insets
|
||||
publishedCorner = corner
|
||||
let px = { (v: CGFloat) in "'\(Int(v.rounded(.up)))px'" }
|
||||
let js = "(function(s){"
|
||||
+ "s.setProperty('--trek-native-safe-top',\(px(insets.top)));"
|
||||
+ "s.setProperty('--trek-native-safe-left',\(px(insets.left)));"
|
||||
+ "s.setProperty('--trek-native-safe-right',\(px(insets.right)));"
|
||||
+ "s.setProperty('--trek-native-safe-bottom',\(px(insets.bottom)));"
|
||||
+ "s.setProperty('--trek-native-corner-bottom',\(px(corner.top)));"
|
||||
+ "s.setProperty('--trek-native-corner-left',\(px(corner.left)));"
|
||||
+ "s.setProperty('--trek-native-corner-right',\(px(corner.right)));"
|
||||
+ "})(document.documentElement.style)"
|
||||
webView.evaluateJavaScript(js, completionHandler: nil)
|
||||
}
|
||||
|
||||
private var publishedCorner: UIEdgeInsets?
|
||||
|
||||
/// An element in a top corner of the screen, such as the status capsule of
|
||||
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
|
||||
/// side (left/right), in the web view's coordinates; zero where there is
|
||||
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
|
||||
/// the corner avoided vertically reaches lower than the one avoiding it
|
||||
/// horizontally, which in turn is wider on the corner's side. The page puts
|
||||
/// its top bar beside the element and starts its content below it, using
|
||||
/// the full width (mobile.css), instead of giving up a strip of the whole
|
||||
/// height.
|
||||
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
|
||||
guard #available(iOS 26.0, *) else { return .zero }
|
||||
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
|
||||
let horizontal = view.edgeInsets(for: .safeArea(cornerAdaptation: .horizontal))
|
||||
guard vertical.top > horizontal.top + 1 else { return .zero }
|
||||
return UIEdgeInsets(
|
||||
top: max(0, vertical.top - frame.minY),
|
||||
left: max(0, horizontal.left - vertical.left - frame.minX),
|
||||
bottom: 0,
|
||||
right: max(0, horizontal.right - vertical.right - (window.bounds.maxX - frame.maxX))
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - A proxy's sign-in page
|
||||
@@ -68,6 +172,10 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
private var urlObservation: NSKeyValueObservation?
|
||||
private var insetObservation: NSKeyValueObservation?
|
||||
private var onSignInPage = false
|
||||
/// Whether the main frame shows an error page in place of the server's (a 4xx
|
||||
/// nobody else handled: a proxy's block page, a client certificate it refused).
|
||||
private var onErrorPage = false
|
||||
private var signInHint: UILabel?
|
||||
private var keyboardUp = false
|
||||
/// How far the keyboard reaches into the view while it is up.
|
||||
private var keyboardRoom: CGFloat = 0
|
||||
@@ -97,9 +205,20 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
updateSignInBar()
|
||||
}
|
||||
|
||||
private func errorPageChanged(_ error: Bool) {
|
||||
onErrorPage = error
|
||||
if error && signInBar == nil { signInBar = makeSignInBar() }
|
||||
updateSignInBar()
|
||||
}
|
||||
|
||||
/// Out of the way while the keyboard is up: the form needs the room.
|
||||
private func updateSignInBar() {
|
||||
signInBar?.isHidden = !(onSignInPage && !keyboardUp)
|
||||
let labels = TrekServerStore.labels
|
||||
signInHint?.text = onSignInPage
|
||||
? labels["signInHint"]
|
||||
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
|
||||
: labels["errorPageHint"] ?? "This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server."
|
||||
signInBar?.isHidden = !((onSignInPage || onErrorPage) && !keyboardUp)
|
||||
applyInset()
|
||||
}
|
||||
|
||||
@@ -108,7 +227,7 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
private func applyInset() {
|
||||
guard let scrollView = webView?.scrollView else { return }
|
||||
let wanted: CGFloat
|
||||
if onSignInPage {
|
||||
if onSignInPage || onErrorPage {
|
||||
if keyboardUp {
|
||||
wanted = keyboardRoom
|
||||
} else if let bar = signInBar {
|
||||
@@ -159,24 +278,38 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
|
||||
private func makeSignInBar() -> UIView {
|
||||
let labels = TrekServerStore.labels
|
||||
// The look of the app's own first screens: a white card with a sand edge,
|
||||
// warm grey text and a dark button, over whatever page the proxy shows.
|
||||
let bar = UIView()
|
||||
bar.backgroundColor = UIColor(red: 17 / 255, green: 24 / 255, blue: 39 / 255, alpha: 0.95)
|
||||
bar.layer.cornerRadius = 16
|
||||
bar.backgroundColor = UIColor(white: 1, alpha: 0.97)
|
||||
bar.layer.cornerRadius = 18
|
||||
bar.layer.cornerCurve = .continuous
|
||||
bar.layer.borderWidth = 1
|
||||
bar.layer.borderColor = UIColor(red: 0xEF / 255, green: 0xE4 / 255, blue: 0xD8 / 255, alpha: 1).cgColor
|
||||
bar.layer.shadowColor = UIColor(red: 0x1F / 255, green: 0x1A / 255, blue: 0x17 / 255, alpha: 1).cgColor
|
||||
bar.layer.shadowOpacity = 0.18
|
||||
bar.layer.shadowRadius = 18
|
||||
bar.layer.shadowOffset = CGSize(width: 0, height: 10)
|
||||
bar.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
let hint = UILabel()
|
||||
hint.text = labels["signInHint"]
|
||||
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
|
||||
hint.textColor = UIColor(white: 0.9, alpha: 1)
|
||||
hint.textColor = UIColor(red: 0x6B / 255, green: 0x5F / 255, blue: 0x57 / 255, alpha: 1)
|
||||
hint.font = .preferredFont(forTextStyle: .footnote)
|
||||
hint.adjustsFontForContentSizeCategory = true
|
||||
hint.numberOfLines = 0
|
||||
signInHint = hint
|
||||
hint.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
let change = UIButton(type: .system)
|
||||
var look = UIButton.Configuration.filled()
|
||||
look.baseBackgroundColor = UIColor(red: 0x11 / 255, green: 0x18 / 255, blue: 0x27 / 255, alpha: 1)
|
||||
look.baseForegroundColor = .white
|
||||
look.cornerStyle = .fixed
|
||||
look.background.cornerRadius = 12
|
||||
look.contentInsets = NSDirectionalEdgeInsets(top: 9, leading: 14, bottom: 9, trailing: 14)
|
||||
let change = UIButton(configuration: look)
|
||||
change.setTitle(labels["changeServer"] ?? "Change server", for: .normal)
|
||||
change.setTitleColor(.white, for: .normal)
|
||||
change.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
|
||||
change.addTarget(self, action: #selector(changeServerFromSignIn), for: .touchUpInside)
|
||||
change.translatesAutoresizingMaskIntoConstraints = false
|
||||
@@ -308,6 +441,22 @@ enum TrekKeyCommands {
|
||||
enum TrekServerStore {
|
||||
private static let key = "TrekServerURL"
|
||||
|
||||
private static let failureKey = "TrekLastFailure"
|
||||
|
||||
/// Why the server's page did not load ("NSURLErrorDomain -1003"): the
|
||||
/// address screen shows it small under its message, so a report carries
|
||||
/// the cause. Taken once.
|
||||
static func noteFailure(_ error: Error) {
|
||||
let ns = error as NSError
|
||||
UserDefaults.standard.set("\(ns.domain) \(ns.code)", forKey: failureKey)
|
||||
}
|
||||
|
||||
static func takeFailure() -> String? {
|
||||
let failure = UserDefaults.standard.string(forKey: failureKey)
|
||||
UserDefaults.standard.removeObject(forKey: failureKey)
|
||||
return failure
|
||||
}
|
||||
|
||||
private static let previousKey = "TrekPreviousServerURL"
|
||||
|
||||
private static let checkedKey = "TrekServerCheck"
|
||||
@@ -326,7 +475,7 @@ enum TrekServerStore {
|
||||
/// A server remembered under a lower value is checked once more: the first
|
||||
/// launch after an update that raised it puts the address screen back up,
|
||||
/// filled in with that server (previousURL). Raise both together.
|
||||
private static let serverCheck = 2
|
||||
private static let serverCheck = 3
|
||||
|
||||
/// Runs before the first bridge is built, so a server picked under an older
|
||||
/// minimum is not loaded unchecked.
|
||||
@@ -335,10 +484,26 @@ enum TrekServerStore {
|
||||
guard defaults.integer(forKey: checkedKey) < serverCheck else { return }
|
||||
defaults.set(serverCheck, forKey: checkedKey)
|
||||
guard let server = url else { return }
|
||||
url = nil
|
||||
// Not through `url`, which throws the offline copy away: it still belongs
|
||||
// to this server, and is what the app starts on if the check cannot run.
|
||||
defaults.removeObject(forKey: key)
|
||||
defaults.removeObject(forKey: signInHostsKey)
|
||||
defaults.set(server, forKey: previousKey)
|
||||
}
|
||||
|
||||
/// The check an update asked for cannot run (the server is out of reach),
|
||||
/// but there is a copy of its UI: the server goes back in place, unchecked
|
||||
/// for now, and the check runs again on the next launch.
|
||||
static func restoreForOffline() -> Bool {
|
||||
let defaults = UserDefaults.standard
|
||||
guard url == nil, let previous = previousURL,
|
||||
FileManager.default.fileExists(atPath: offlineCopyURL.path) else { return false }
|
||||
defaults.set(previous, forKey: key)
|
||||
defaults.removeObject(forKey: previousKey)
|
||||
defaults.set(0, forKey: checkedKey)
|
||||
return true
|
||||
}
|
||||
|
||||
/// The server an update asked to check again, until a server is set.
|
||||
static var previousURL: String? {
|
||||
UserDefaults.standard.string(forKey: previousKey)
|
||||
@@ -665,6 +830,10 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
|
||||
private let inner: WKNavigationDelegate
|
||||
/// A page of the server has shown since launch; from then on no sign-in host is learned (TrekSignInRedirect).
|
||||
private var serverShown = false
|
||||
/// Told on the main thread whether the main frame now shows an error page in place of the server's.
|
||||
var onErrorPage: ((Bool) -> Void)?
|
||||
/// Told when a page has finished loading: a new document starts without the safe area the controller handed the last one.
|
||||
var onPageShown: (() -> Void)?
|
||||
|
||||
init(inner: WKNavigationDelegate) {
|
||||
self.inner = inner
|
||||
@@ -717,7 +886,12 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
|
||||
/// page once (TrekServerStore.takeWelcomeURL); it is on the server's origin.
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
inner.webView?(webView, didFinish: navigation)
|
||||
if TrekSignInRedirect.onServer(server: TrekServerStore.url, url: webView.url) { serverShown = true }
|
||||
onPageShown?()
|
||||
if TrekSignInRedirect.onServer(server: TrekServerStore.url, url: webView.url) {
|
||||
serverShown = true
|
||||
// The server's page is up: an earlier failure is no cause any more.
|
||||
_ = TrekServerStore.takeFailure()
|
||||
}
|
||||
if let welcome = TrekServerStore.takeWelcomeURL() {
|
||||
webView.load(URLRequest(url: welcome))
|
||||
}
|
||||
@@ -733,6 +907,7 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
|
||||
TrekClientCertWatch.serverAsked(host: space.host, port: space.port) { [weak self, weak webView] in
|
||||
guard let self, let webView else { return }
|
||||
// Capacitor's own answer to a failed load: the address screen (errorPath).
|
||||
TrekServerStore.noteFailure(URLError(.clientCertificateRejected))
|
||||
self.inner.webView?(webView, didFailProvisionalNavigation: nil, withError: URLError(.clientCertificateRejected))
|
||||
}
|
||||
return
|
||||
@@ -748,16 +923,23 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
|
||||
/// A proxy that asked the page for a client certificate, got none and
|
||||
/// answered with its own refusal (Cloudflare's 403, nginx's 400) sends the
|
||||
/// app to the address screen, which says so and offers to add one, rather
|
||||
/// than leaving the proxy's error page up.
|
||||
/// than leaving the proxy's error page up. Any other 4xx page is not TREK's,
|
||||
/// which serves its UI for every path (a proxy's block page, a certificate it
|
||||
/// refused): it stays up with the bar and its way out to another server.
|
||||
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
|
||||
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
|
||||
if navigationResponse.isForMainFrame, let http = navigationResponse.response as? HTTPURLResponse,
|
||||
http.statusCode >= 400, http.statusCode < 500, let asked = TrekClientIdentity.lastRequest, !asked.served,
|
||||
let url = http.url, url.host?.lowercased() == asked.host, (url.port ?? 443) == asked.port {
|
||||
decisionHandler(.cancel)
|
||||
TrekServerStore.noteFailure(URLError(.clientCertificateRequired))
|
||||
inner.webView?(webView, didFailProvisionalNavigation: nil, withError: URLError(.clientCertificateRequired))
|
||||
return
|
||||
}
|
||||
if navigationResponse.isForMainFrame, let http = navigationResponse.response as? HTTPURLResponse {
|
||||
let error = http.statusCode >= 400 && http.statusCode < 500
|
||||
DispatchQueue.main.async { [weak self] in self?.onErrorPage?(error) }
|
||||
}
|
||||
let selector = NSSelectorFromString("webView:decidePolicyForNavigationResponse:decisionHandler:")
|
||||
guard (inner as AnyObject).responds(to: selector) else {
|
||||
decisionHandler(.allow)
|
||||
@@ -768,11 +950,13 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
|
||||
|
||||
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||
if Self.isReplaced(error) { return }
|
||||
TrekServerStore.noteFailure(error)
|
||||
inner.webView?(webView, didFail: navigation, withError: error)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
||||
if Self.isReplaced(error) { return }
|
||||
TrekServerStore.noteFailure(error)
|
||||
inner.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
CAPPluginMethod(name: "storePurchase", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "storeFinish", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "storeRestore", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "storeHeld", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "addToWallet", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "setWatchSnapshot", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "takeWatchActions", returnType: CAPPluginReturnPromise),
|
||||
@@ -68,7 +69,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
/// builds a snapshot for nothing; "wallet" only where Wallet can take a pass (an
|
||||
/// iPhone: an iPad has no Wallet app), so the UI offers no button that does nothing.
|
||||
static var features: [String] {
|
||||
var names = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet", "keyCommands", "quickActions", "clientCertificate", "filePreview"]
|
||||
var names = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet", "keyCommands", "quickActions", "appLinks", "clientCertificate", "filePreview"]
|
||||
if canAddWalletPasses { names.append("wallet") }
|
||||
if TrekWatchLink.isAvailable { names.append("watch") }
|
||||
return names
|
||||
@@ -93,8 +94,9 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
TrekKeyCommands.onPress = { [weak self] id in
|
||||
self?.notifyListeners("keyCommand", data: ["id": id])
|
||||
}
|
||||
// Kept until a listener takes it: a tap while the page reloads reaches the new page.
|
||||
TrekQuickActions.onOpen = { [weak self] path in
|
||||
DispatchQueue.main.async { self?.notifyListeners("quickAction", data: ["path": path]) }
|
||||
DispatchQueue.main.async { self?.notifyListeners("quickAction", data: ["path": path], retainUntilConsumed: true) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +174,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
nextName: nextName,
|
||||
nextTime: call.getString("nextTime"),
|
||||
done: call.getInt("done") ?? 0,
|
||||
total: call.getInt("total") ?? 0
|
||||
total: call.getInt("total") ?? 0,
|
||||
flight: TrekShellPlugin.activityFlight(call.getObject("flight"))
|
||||
)
|
||||
// Stale at the end of the day, so a forgotten one fades out on its own.
|
||||
let stale = Calendar.current.startOfDay(for: Date().addingTimeInterval(86_400))
|
||||
@@ -192,6 +195,19 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
call.resolve(["running": false])
|
||||
}
|
||||
|
||||
/// The day's flight the UI sent along (native/widgets.ts tripDayState), when complete.
|
||||
@available(iOS 16.1, *)
|
||||
static func activityFlight(_ raw: JSObject?) -> TripDayAttributes.Flight? {
|
||||
guard let raw, let number = raw["number"] as? String, let from = raw["from"] as? String, let to = raw["to"] as? String,
|
||||
let dep = (raw["dep"] as? NSNumber)?.doubleValue, let arr = (raw["arr"] as? NSNumber)?.doubleValue, arr > dep,
|
||||
let depTime = raw["depTime"] as? String, let arrTime = raw["arrTime"] as? String else { return nil }
|
||||
return TripDayAttributes.Flight(
|
||||
number: number, from: from, to: to, dep: dep, arr: arr, depTime: depTime, arrTime: arrTime,
|
||||
delay: (raw["delay"] as? NSNumber)?.intValue,
|
||||
airborne: (raw["airborne"] as? Bool) ?? false
|
||||
)
|
||||
}
|
||||
|
||||
@objc func endTripDay(_ call: CAPPluginCall) {
|
||||
#if canImport(ActivityKit)
|
||||
if #available(iOS 16.2, *) {
|
||||
@@ -351,6 +367,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
call.resolve([
|
||||
"url": TrekServerStore.url ?? NSNull(),
|
||||
"previousUrl": TrekServerStore.previousURL ?? NSNull(),
|
||||
"failure": TrekServerStore.takeFailure() ?? NSNull(),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -460,6 +477,18 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
|
||||
}
|
||||
|
||||
@objc func openOfflineCopy(_ call: CAPPluginCall) {
|
||||
// The server an update asked to check again, out of reach: back to it on
|
||||
// its copy. The new bridge loads the server, fails, and this screen comes
|
||||
// back with the server set, which then opens the copy below.
|
||||
if TrekServerStore.url == nil {
|
||||
if TrekServerStore.restoreForOffline() {
|
||||
call.resolve(["opened": true])
|
||||
restartBridge()
|
||||
} else {
|
||||
call.resolve(["opened": false])
|
||||
}
|
||||
return
|
||||
}
|
||||
// With the trailing slash, like the bridge's serverURL: Capacitor only
|
||||
// keeps a navigation in the app when it starts with that exact string,
|
||||
// and hands anything else to Safari.
|
||||
@@ -679,6 +708,17 @@ extension TrekShellPlugin {
|
||||
return
|
||||
}
|
||||
Task {
|
||||
// One subscription per Apple ID: another plan would change it, not add one.
|
||||
// A held one that was delivered stops the purchase here. One that was paid
|
||||
// but never set up is handed back as bought, so its instance is set up now.
|
||||
if let held = await TrekStore.currentEntitlement(prefix: "cloud.") {
|
||||
if await TrekStore.awaitingSetup(held) {
|
||||
call.resolve(["kind": "bought", "jws": held.jws, "transactionId": String(held.id), "productId": held.productId])
|
||||
} else {
|
||||
call.resolve(["kind": "subscribed"])
|
||||
}
|
||||
return
|
||||
}
|
||||
do {
|
||||
guard let product = try await Product.products(for: [id]).first else {
|
||||
call.resolve(["kind": "failed"])
|
||||
@@ -735,6 +775,21 @@ extension TrekShellPlugin {
|
||||
call.resolve(["jws": found.jws, "transactionId": String(found.id)])
|
||||
}
|
||||
}
|
||||
|
||||
/// Feature storeKit: whether this Apple ID holds a delivered subscription under
|
||||
/// `prefix`. Read from the entitlements on the device, so no password is asked;
|
||||
/// while one runs, the shell offers no purchase.
|
||||
@objc func storeHeld(_ call: CAPPluginCall) {
|
||||
let prefix = call.getString("prefix") ?? "cloud."
|
||||
Task {
|
||||
guard let held = await TrekStore.currentEntitlement(prefix: prefix) else {
|
||||
call.resolve(["held": false])
|
||||
return
|
||||
}
|
||||
let awaiting = await TrekStore.awaitingSetup(held)
|
||||
call.resolve(["held": !awaiting])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum TrekStore {
|
||||
@@ -765,17 +820,62 @@ enum TrekStore {
|
||||
}
|
||||
}
|
||||
|
||||
static func currentEntitlement(prefix: String) async -> (jws: String, id: UInt64)? {
|
||||
var newest: (date: Date, jws: String, id: UInt64)?
|
||||
typealias Held = (jws: String, id: UInt64, productId: String, firstPurchase: Bool)
|
||||
|
||||
/// The subscription this Apple ID holds under `prefix`, newest first. The
|
||||
/// entitlements on the device come first; on a fresh install they can still
|
||||
/// be empty while the subscription runs, so the status of the subscription
|
||||
/// group, which StoreKit asks the App Store for, decides then.
|
||||
static func currentEntitlement(prefix: String) async -> Held? {
|
||||
var newest: (date: Date, held: Held)?
|
||||
for await result in Transaction.currentEntitlements {
|
||||
guard case .verified(let transaction) = result,
|
||||
transaction.productID.hasPrefix(prefix),
|
||||
transaction.revocationDate == nil else { continue }
|
||||
if newest == nil || transaction.purchaseDate > newest!.date {
|
||||
newest = (transaction.purchaseDate, result.jwsRepresentation, transaction.id)
|
||||
newest = (transaction.purchaseDate, held(result.jwsRepresentation, transaction))
|
||||
}
|
||||
}
|
||||
return newest.map { ($0.jws, $0.id) }
|
||||
if let newest { return newest.held }
|
||||
return await subscriptionGroupHeld(prefix: prefix)
|
||||
}
|
||||
|
||||
/// The plans the control plane sells (`cloud.<plan>.<monthly|yearly>`, as
|
||||
/// productIdFor in iap.ts); one of them is enough to find their group.
|
||||
private static let plans = ["start", "basis", "plus", "pro"]
|
||||
|
||||
private static func subscriptionGroupHeld(prefix: String) async -> Held? {
|
||||
let ids = plans.flatMap { ["\(prefix)\($0).monthly", "\(prefix)\($0).yearly"] }
|
||||
guard let products = try? await Product.products(for: ids),
|
||||
let group = products.compactMap({ $0.subscription?.subscriptionGroupID }).first,
|
||||
let statuses = try? await Product.SubscriptionInfo.status(for: group) else { return nil }
|
||||
let running: [Product.SubscriptionInfo.RenewalState] = [.subscribed, .inGracePeriod, .inBillingRetryPeriod]
|
||||
for status in statuses where running.contains(status.state) {
|
||||
if case .verified(let transaction) = status.transaction, transaction.revocationDate == nil {
|
||||
return held(status.transaction.jwsRepresentation, transaction)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func held(_ jws: String, _ transaction: Transaction) -> Held {
|
||||
(jws: jws, id: transaction.id, productId: transaction.productID, firstPurchase: transaction.originalID == transaction.id)
|
||||
}
|
||||
|
||||
/// A first purchase that was paid but whose instance was never set up: handed
|
||||
/// back as bought so it is set up now. A renewal the device has not finished
|
||||
/// yet is no such purchase; its subscription is running and counts as held.
|
||||
static func awaitingSetup(_ held: Held) async -> Bool {
|
||||
guard held.firstPurchase else { return false }
|
||||
return await isUnfinished(held.id)
|
||||
}
|
||||
|
||||
/// Paid but not delivered yet: the shell finishes a transaction once its instance exists.
|
||||
static func isUnfinished(_ id: UInt64) async -> Bool {
|
||||
for await result in Transaction.unfinished {
|
||||
if case .verified(let transaction) = result, transaction.id == id { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The trip's next flight, or the one in the air: both airports large, the
|
||||
/// route as an arc with the aircraft riding it, the moment in words with a
|
||||
/// countdown the system keeps running, and the delay. Between two snapshots
|
||||
/// the widget moves on with the clock: it takes off at the observed (or
|
||||
/// planned) time, flies along the arc and lands at the expected (or planned)
|
||||
/// arrival.
|
||||
struct FlightContent: View {
|
||||
let snapshot: WidgetSnapshot?
|
||||
let family: TrekFamily
|
||||
let now: Date
|
||||
@Environment(\.colorScheme) private var scheme
|
||||
|
||||
private let accent = Trek.booking("flight").color
|
||||
|
||||
var body: some View {
|
||||
if let flight = snapshot?.flight, let labels = snapshot?.labels {
|
||||
let moment = FlightMoment(flight, now: now)
|
||||
switch family {
|
||||
case .circular: circular(flight, moment)
|
||||
case .rectangular: rectangular(flight, moment, labels)
|
||||
case .inline: inline(flight, moment, labels)
|
||||
case .small: small(flight, moment, labels)
|
||||
case .medium: medium(flight, moment, labels)
|
||||
default: large(flight, moment, labels)
|
||||
}
|
||||
} else {
|
||||
empty(snapshot?.labels)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Small: the moment above, the route below
|
||||
|
||||
private func small(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "airplane").font(.system(size: 12, weight: .bold)).foregroundStyle(accent)
|
||||
Text(f.number).font(.system(size: 12, weight: .heavy)).foregroundStyle(Trek.ink(scheme)).lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
delayChip(f, labels, compact: true)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
momentText(f, m, labels)
|
||||
.font(.system(size: 13, weight: .bold))
|
||||
.foregroundStyle(m.stage == .airborne ? accent : Trek.ink(scheme))
|
||||
.lineLimit(2)
|
||||
.minimumScaleFactor(0.85)
|
||||
Spacer(minLength: 6)
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
Text(f.from).font(Trek.number(24, .heavy)).foregroundStyle(Trek.ink(scheme))
|
||||
Spacer(minLength: 2)
|
||||
Text(f.to).font(Trek.number(24, .heavy)).foregroundStyle(Trek.ink(scheme))
|
||||
}
|
||||
RouteArc(progress: m.progress, color: accent).flipsForRightToLeftLayoutDirection(true).frame(height: 20).padding(.vertical, 3)
|
||||
HStack {
|
||||
Text(f.depTime).font(Trek.number(12, .bold)).foregroundStyle(Trek.muted(scheme))
|
||||
Spacer(minLength: 2)
|
||||
Text(f.arrTimeExpected ?? f.arrTime).font(Trek.number(12, .bold)).foregroundStyle(Trek.muted(scheme))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Medium: a boarding pass
|
||||
|
||||
private func medium(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 7) {
|
||||
Text(labels.flight ?? "").trekEyebrow(scheme)
|
||||
Text(f.number).font(.system(size: 11, weight: .heavy)).foregroundStyle(accent)
|
||||
Spacer(minLength: 4)
|
||||
delayChip(f, labels, compact: false)
|
||||
}
|
||||
Spacer(minLength: 4)
|
||||
HStack(alignment: .center, spacing: 10) {
|
||||
airport(f.from, f.fromCity, time: f.depTime, planned: nil, align: .leading)
|
||||
VStack(spacing: 4) {
|
||||
RouteArc(progress: m.progress, color: accent).flipsForRightToLeftLayoutDirection(true).frame(height: 30)
|
||||
progressBar(m)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
airport(f.to, f.toCity, time: f.arrTimeExpected ?? f.arrTime, planned: f.arrTimeExpected.flatMap { $0 == f.arrTime ? nil : f.arrTime }, align: .trailing)
|
||||
}
|
||||
Spacer(minLength: 6)
|
||||
momentText(f, m, labels)
|
||||
.font(.system(size: 13, weight: .bold))
|
||||
.foregroundStyle(m.stage == .airborne ? accent : Trek.ink(scheme))
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.85)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Large and extra large: the pass with the details under it
|
||||
|
||||
private func large(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
medium(f, m, labels).frame(maxHeight: 150)
|
||||
Rectangle().fill(Trek.track(scheme)).frame(height: 0.8)
|
||||
LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) {
|
||||
if let aircraft = f.aircraft { detail(systemImage: "airplane.circle", value: aircraft) }
|
||||
detail(systemImage: "clock", value: "\(f.depTime) → \(f.arrTimeExpected ?? f.arrTime)")
|
||||
if let fromCity = f.fromCity { detail(systemImage: "airplane.departure", value: fromCity) }
|
||||
if let toCity = f.toCity { detail(systemImage: "airplane.arrival", value: toCity) }
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Lock screen
|
||||
|
||||
private func circular(_ f: WidgetSnapshot.Flight, _ m: FlightMoment) -> some View {
|
||||
ProgressRing(value: m.progress, lineWidth: 5, colors: [.white], trackColor: Color.white.opacity(0.25)) {
|
||||
Image(systemName: m.stage == .landed ? "airplane.arrival" : m.stage == .airborne ? "airplane" : "airplane.departure")
|
||||
.font(.system(size: 17, weight: .bold))
|
||||
}
|
||||
.padding(4)
|
||||
}
|
||||
|
||||
private func rectangular(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: "airplane").font(.system(size: 11, weight: .bold))
|
||||
Text("\(f.number) \(f.from) → \(f.to)").font(.system(size: 12, weight: .heavy)).lineLimit(1)
|
||||
}
|
||||
momentText(f, m, labels).font(.system(size: 13, weight: .semibold)).lineLimit(1)
|
||||
if m.stage == .airborne {
|
||||
ProgressView(timerInterval: m.start...m.end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
|
||||
.progressViewStyle(.linear)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
private func inline(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
|
||||
Text("\(Image(systemName: "airplane")) \(f.number) ") + momentText(f, m, labels)
|
||||
}
|
||||
|
||||
// MARK: Parts
|
||||
|
||||
private func airport(_ code: String, _ city: String?, time: String, planned: String?, align: HorizontalAlignment) -> some View {
|
||||
VStack(alignment: align, spacing: 1) {
|
||||
Text(code).font(Trek.number(28, .heavy)).foregroundStyle(Trek.ink(scheme))
|
||||
if let city { Text(city).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Trek.faint(scheme)).lineLimit(1) }
|
||||
if let planned { Text(planned).font(Trek.number(10.5, .bold)).strikethrough().foregroundStyle(Trek.faint(scheme)) }
|
||||
Text(time).font(Trek.number(14, .heavy)).foregroundStyle(Trek.ink(scheme))
|
||||
}
|
||||
.frame(maxWidth: 96, alignment: align == .leading ? .leading : .trailing)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func progressBar(_ m: FlightMoment) -> some View {
|
||||
if m.stage == .airborne {
|
||||
// The system runs this bar on its own, so it fills between two snapshots too.
|
||||
ProgressView(timerInterval: m.start...m.end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
|
||||
.progressViewStyle(.linear)
|
||||
.tint(accent)
|
||||
} else {
|
||||
Capsule().fill(m.stage == .landed ? accent : Trek.track(scheme)).frame(height: 4)
|
||||
}
|
||||
}
|
||||
|
||||
private func detail(systemImage: String, value: String) -> some View {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: systemImage).font(.system(size: 12, weight: .semibold)).foregroundStyle(accent)
|
||||
Text(value).font(.system(size: 12, weight: .semibold)).foregroundStyle(Trek.muted(scheme)).lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 8)
|
||||
.background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Trek.card(scheme)))
|
||||
}
|
||||
|
||||
/// "Departs in 2 hr, 10 min", "Lands in 1 hr", "Landed": the countdowns are the system's own running text.
|
||||
private func momentText(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> Text {
|
||||
switch m.stage {
|
||||
case .upcoming:
|
||||
return Countdown.text(labels.flightDeparts ?? "{time}", until: m.start)
|
||||
case .ready:
|
||||
return Text(labels.flightReady ?? "")
|
||||
case .airborne:
|
||||
// "In the air" is what the blue line and the moving aircraft say; the words count down to landing.
|
||||
return Countdown.text(labels.flightLands ?? "{time}", until: m.end)
|
||||
case .landed:
|
||||
return Text(labels.flightLanded ?? "")
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func delayChip(_ f: WidgetSnapshot.Flight, _ labels: WidgetSnapshot.Labels, compact: Bool) -> some View {
|
||||
if let delay = f.delay {
|
||||
let late = delay > 5
|
||||
let early = delay < -5
|
||||
let color = late ? (delay >= 30 ? Trek.danger : Trek.pending) : Trek.confirmed
|
||||
let text = late
|
||||
? (labels.flightLate ?? "+{m}").replacingOccurrences(of: "{m}", with: "\(delay)")
|
||||
: early ? (labels.flightEarly ?? "{m}").replacingOccurrences(of: "{m}", with: "\(-delay)") : (labels.flightOnTime ?? "")
|
||||
if !(compact && !late) {
|
||||
Text(text)
|
||||
.font(.system(size: 10.5, weight: .heavy))
|
||||
.foregroundStyle(color)
|
||||
.padding(.horizontal, 7)
|
||||
.padding(.vertical, 3)
|
||||
.background(Capsule().fill(color.opacity(scheme == .dark ? 0.22 : 0.14)))
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func empty(_ labels: WidgetSnapshot.Labels?) -> some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(labels?.flight ?? "").trekEyebrow(scheme)
|
||||
Spacer(minLength: 0)
|
||||
Image(systemName: "airplane").font(.system(size: 30, weight: .bold)).foregroundStyle(accent.opacity(0.35))
|
||||
Text(labels?.noFlight ?? labels?.noBookings ?? "").font(.system(size: 13, weight: .semibold)).foregroundStyle(Trek.muted(scheme)).lineLimit(2)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a flight stands at a given moment, from the snapshot's times. What the
|
||||
/// feed saw wins: a flight still at the gate past its planned departure is not
|
||||
/// flown along the arc, and a flight is only landed once confirmed. Only a
|
||||
/// flight the feed never heard of moves on by its schedule alone.
|
||||
struct FlightMoment {
|
||||
enum Stage { case upcoming, ready, airborne, landed }
|
||||
|
||||
let stage: Stage
|
||||
/// 0 at the gate, 1 at the destination.
|
||||
let progress: Double
|
||||
/// Take-off and touchdown the moment is measured between: observed or expected where known, planned otherwise.
|
||||
let start: Date
|
||||
let end: Date
|
||||
|
||||
init(_ f: WidgetSnapshot.Flight, now: Date) {
|
||||
let start = Date(timeIntervalSince1970: f.depActual ?? f.depExpected ?? f.dep)
|
||||
let end = max(Date(timeIntervalSince1970: f.arrExpected ?? f.arr), start.addingTimeInterval(60))
|
||||
self.start = start
|
||||
self.end = end
|
||||
let heard = f.seen != nil
|
||||
let flying = f.airborne == true || f.depActual != nil || (!heard && now >= start)
|
||||
// A flight the feed lost stops counting two hours after its arrival.
|
||||
if f.landed == true || (!heard && now >= end) || now >= end.addingTimeInterval(7200) {
|
||||
stage = .landed
|
||||
progress = 1
|
||||
} else if flying {
|
||||
stage = .airborne
|
||||
// Unconfirmed, it never quite arrives on the arc.
|
||||
progress = min(0.98, max(0, now.timeIntervalSince(start) / end.timeIntervalSince(start)))
|
||||
} else if now >= start {
|
||||
stage = .ready
|
||||
progress = 0
|
||||
} else {
|
||||
stage = .upcoming
|
||||
progress = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A sentence with "{time}" in it, the placeholder replaced by a countdown the system keeps running.
|
||||
enum Countdown {
|
||||
static func text(_ sentence: String, until date: Date) -> Text {
|
||||
let parts = sentence.components(separatedBy: "{time}")
|
||||
guard parts.count == 2 else { return Text(sentence) }
|
||||
return Text(parts[0]) + Text(date, style: .relative) + Text(parts[1])
|
||||
}
|
||||
}
|
||||
@@ -158,6 +158,30 @@ private struct BookingsFamilyView: View {
|
||||
var body: some View { BookingsContent(snapshot: entry.snapshot, family: TrekFamily(family), now: entry.date) }
|
||||
}
|
||||
|
||||
// MARK: - Flight
|
||||
|
||||
struct FlightWidget: Widget {
|
||||
var body: some WidgetConfiguration {
|
||||
AppIntentConfiguration(kind: "TripFlight", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
|
||||
TrekContainer(link: entry.snapshot?.flight.flatMap { WidgetSnapshot.link($0.path) }) {
|
||||
FlightFamilyView(entry: entry)
|
||||
} background: {
|
||||
TrekPaper()
|
||||
}
|
||||
}
|
||||
.configurationDisplayName("widget.flight.name")
|
||||
.description("widget.flight.description")
|
||||
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .accessoryCircular, .accessoryRectangular, .accessoryInline])
|
||||
}
|
||||
}
|
||||
|
||||
private struct FlightFamilyView: View {
|
||||
@Environment(\.widgetFamily) private var family
|
||||
let entry: TrekEntry
|
||||
|
||||
var body: some View { FlightContent(snapshot: entry.snapshot, family: TrekFamily(family), now: entry.date) }
|
||||
}
|
||||
|
||||
// MARK: - To-dos
|
||||
|
||||
struct TodosWidget: Widget {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import SwiftUI
|
||||
import WidgetKit
|
||||
|
||||
/// The TREK widgets: the trip, today's plan, the bookings ahead, the to-dos,
|
||||
/// The TREK widgets: the trip, today's plan, the bookings ahead, the next flight, the to-dos,
|
||||
/// the packing list, the Atlas and the travel group on the home and lock
|
||||
/// screen, and the travel day as a Live Activity.
|
||||
@main
|
||||
@@ -10,6 +10,7 @@ struct TREKWidgetsBundle: WidgetBundle {
|
||||
NextTripWidget()
|
||||
TodayWidget()
|
||||
BookingsWidget()
|
||||
FlightWidget()
|
||||
TodosWidget()
|
||||
PackingWidget()
|
||||
AtlasWidget()
|
||||
|
||||
@@ -115,6 +115,29 @@ extension WidgetSnapshot {
|
||||
poll: "Poll", votes: "votes", noMessages: "No messages yet", departure: "Departure"
|
||||
)
|
||||
)
|
||||
// In the air on a running trip, two days ahead before one.
|
||||
let departure = running ? now.addingTimeInterval(-4 * 3600) : now.addingTimeInterval(2 * 86_400 + 5 * 3600)
|
||||
snapshot.flight = Flight(
|
||||
number: "LH 716", from: "FRA", to: "HND", fromCity: "Frankfurt", toCity: "Tokyo Haneda",
|
||||
dep: departure.timeIntervalSince1970, arr: departure.addingTimeInterval(12 * 3600 + 25 * 60).timeIntervalSince1970,
|
||||
depActual: running ? departure.addingTimeInterval(18 * 60).timeIntervalSince1970 : nil,
|
||||
depExpected: nil, airborne: running ? true : nil,
|
||||
arrExpected: running ? departure.addingTimeInterval(12 * 3600 + 41 * 60).timeIntervalSince1970 : nil,
|
||||
landed: nil, depTime: "13:05", arrTime: "08:30", arrTimeExpected: running ? "08:46" : nil,
|
||||
delay: running ? 16 : nil, aircraft: running ? "A359 D-AIXA" : nil, seen: running ? now.timeIntervalSince1970 : nil,
|
||||
path: "/trips/1?booking=1"
|
||||
)
|
||||
snapshot.labels.flight = "Flight"
|
||||
snapshot.labels.flightDeparts = "Departs in {time}"
|
||||
snapshot.labels.flightInAir = "In the air"
|
||||
snapshot.labels.flightLands = "Lands in {time}"
|
||||
snapshot.labels.flightLanded = "Landed"
|
||||
snapshot.labels.flightOnTime = "On time"
|
||||
snapshot.labels.flightLate = "+{m} min"
|
||||
snapshot.labels.flightEarly = "{m} min early"
|
||||
snapshot.labels.flightEstimated = "estimated"
|
||||
snapshot.labels.flightReady = "Ready for departure"
|
||||
snapshot.labels.noFlight = "No flight ahead"
|
||||
snapshot.packing?.bags = [
|
||||
.init(name: "Suitcase", color: "#4A7DDB", grams: 14_200, limit: 23_000, packed: 15, total: 19),
|
||||
.init(name: "Daypack", color: "#2FA37A", grams: 4_100, limit: 8_000, packed: 8, total: 12),
|
||||
@@ -174,6 +197,7 @@ extension WidgetSnapshot {
|
||||
snapshot.packing = nil
|
||||
snapshot.atlas = Atlas(count: 0, codes: [], recent: [], continents: [])
|
||||
snapshot.collab = nil
|
||||
snapshot.flight = nil
|
||||
return snapshot
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,27 @@ struct TripDayAttributes: ActivityAttributes {
|
||||
/// Stops behind, out of the day's stops.
|
||||
var done: Int
|
||||
var total: Int
|
||||
/// The day's flight while it is near or in the air, so the activity turns into
|
||||
/// a boarding pass. Optional: a state written by an older app decodes without it.
|
||||
var flight: Flight?
|
||||
}
|
||||
|
||||
/// A flight the activity follows on its own between two updates: the system
|
||||
/// runs the bar and the countdown from the two times.
|
||||
struct Flight: Codable, Hashable {
|
||||
var number: String
|
||||
var from: String
|
||||
var to: String
|
||||
/// Take-off and touchdown, epoch seconds: observed or expected where known.
|
||||
var dep: Double
|
||||
var arr: Double
|
||||
/// The clock at either airport, formatted by the app.
|
||||
var depTime: String
|
||||
var arrTime: String
|
||||
/// Minutes late, for the colour of the arrival time.
|
||||
var delay: Int?
|
||||
/// In the air when the app last looked: the countdown runs to touchdown.
|
||||
var airborne: Bool?
|
||||
}
|
||||
|
||||
var tripTitle: String
|
||||
|
||||
@@ -7,11 +7,17 @@ import WidgetKit
|
||||
struct TripDayLiveActivity: Widget {
|
||||
var body: some WidgetConfiguration {
|
||||
ActivityConfiguration(for: TripDayAttributes.self) { context in
|
||||
TripDayBanner(
|
||||
tripTitle: context.attributes.tripTitle, dayLabel: context.state.dayLabel,
|
||||
nextName: context.state.nextName, nextTime: context.state.nextTime,
|
||||
done: context.state.done, total: context.state.total
|
||||
)
|
||||
Group {
|
||||
if let flight = context.state.flight {
|
||||
FlightBanner(flight: flight, tripTitle: context.attributes.tripTitle)
|
||||
} else {
|
||||
TripDayBanner(
|
||||
tripTitle: context.attributes.tripTitle, dayLabel: context.state.dayLabel,
|
||||
nextName: context.state.nextName, nextTime: context.state.nextTime,
|
||||
done: context.state.done, total: context.state.total
|
||||
)
|
||||
}
|
||||
}
|
||||
.activityBackgroundTint(Color(hex: 0x0C0C0F).opacity(0.92))
|
||||
.activitySystemActionForegroundColor(.white)
|
||||
.widgetURL(WidgetSnapshot.link(context.attributes.path))
|
||||
@@ -33,17 +39,32 @@ struct TripDayLiveActivity: Widget {
|
||||
}
|
||||
}
|
||||
DynamicIslandExpandedRegion(.bottom) {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(state.nextName).font(.system(size: 17, weight: .heavy)).lineLimit(1)
|
||||
DayStopProgress(done: state.done, total: state.total)
|
||||
if let flight = state.flight {
|
||||
FlightPass(flight: flight).padding(.horizontal, 4)
|
||||
} else {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(state.nextName).font(.system(size: 17, weight: .heavy)).lineLimit(1)
|
||||
DayStopProgress(done: state.done, total: state.total)
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
} compactLeading: {
|
||||
Image(systemName: "mappin.circle.fill").foregroundStyle(Trek.confirmed)
|
||||
if let flight = state.flight {
|
||||
HStack(spacing: 3) {
|
||||
Image(systemName: "airplane").foregroundStyle(Trek.info)
|
||||
Text(flight.to).font(Trek.number(13, .heavy))
|
||||
}
|
||||
} else {
|
||||
Image(systemName: "mappin.circle.fill").foregroundStyle(Trek.confirmed)
|
||||
}
|
||||
} compactTrailing: {
|
||||
Text(state.nextTime ?? "\(state.done)/\(state.total)")
|
||||
.font(Trek.number(13, .heavy))
|
||||
if let flight = state.flight {
|
||||
FlightCountdown(flight: flight).font(Trek.number(13, .heavy)).frame(maxWidth: 64)
|
||||
} else {
|
||||
Text(state.nextTime ?? "\(state.done)/\(state.total)")
|
||||
.font(Trek.number(13, .heavy))
|
||||
}
|
||||
} minimal: {
|
||||
ZStack {
|
||||
Circle().stroke(Color.white.opacity(0.25), lineWidth: 2.5)
|
||||
@@ -59,3 +80,76 @@ struct TripDayLiveActivity: Widget {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The day's flight on the lock screen: both airports, the bar the system runs
|
||||
/// from take-off to touchdown, and a countdown to whichever comes next.
|
||||
struct FlightBanner: View {
|
||||
let flight: TripDayAttributes.Flight
|
||||
let tripTitle: String
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "airplane").font(.system(size: 12, weight: .bold)).foregroundStyle(Trek.info)
|
||||
Text(flight.number).font(.system(size: 12, weight: .heavy)).foregroundStyle(.white)
|
||||
Text(tripTitle)
|
||||
.font(.system(size: 11, weight: .bold))
|
||||
.tracking(0.5)
|
||||
.textCase(.uppercase)
|
||||
.foregroundStyle(.white.opacity(0.55))
|
||||
.lineLimit(1)
|
||||
Spacer(minLength: 4)
|
||||
FlightCountdown(flight: flight).font(Trek.number(15, .heavy)).foregroundStyle(.white)
|
||||
}
|
||||
FlightPass(flight: flight)
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
}
|
||||
|
||||
/// The two airports with their times and the bar between them.
|
||||
struct FlightPass: View {
|
||||
let flight: TripDayAttributes.Flight
|
||||
|
||||
var body: some View {
|
||||
let start = Date(timeIntervalSince1970: flight.dep)
|
||||
let end = Date(timeIntervalSince1970: flight.arr)
|
||||
let late = (flight.delay ?? 0) > 5
|
||||
HStack(alignment: .center, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
Text(flight.from).font(Trek.number(26, .heavy)).foregroundStyle(.white)
|
||||
Text(flight.depTime).font(Trek.number(13, .bold)).foregroundStyle(.white.opacity(0.7))
|
||||
}
|
||||
VStack(spacing: 4) {
|
||||
Image(systemName: "airplane").font(.system(size: 13, weight: .bold)).foregroundStyle(Trek.info)
|
||||
ProgressView(timerInterval: start...end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
|
||||
.progressViewStyle(.linear)
|
||||
.tint(Trek.info)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
VStack(alignment: .trailing, spacing: 0) {
|
||||
Text(flight.to).font(Trek.number(26, .heavy)).foregroundStyle(.white)
|
||||
Text(flight.arrTime).font(Trek.number(13, .bold)).foregroundStyle(late ? Trek.pending : .white.opacity(0.7))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A running countdown, in the system's own format: to touchdown once the app saw
|
||||
/// the aircraft in the air, to take-off before. The system runs it between two
|
||||
/// updates; the stage changes with the app's next update after take-off.
|
||||
struct FlightCountdown: View {
|
||||
let flight: TripDayAttributes.Flight
|
||||
|
||||
var body: some View {
|
||||
let start = Date(timeIntervalSince1970: flight.dep)
|
||||
let end = Date(timeIntervalSince1970: flight.arr)
|
||||
let flying = flight.airborne == true
|
||||
let target = flying ? end : start
|
||||
HStack(spacing: 3) {
|
||||
Image(systemName: flying ? "airplane.arrival" : "airplane.departure")
|
||||
Text(timerInterval: min(Date(), target)...target, countsDown: true)
|
||||
.multilineTextAlignment(.trailing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +160,38 @@ struct WidgetSnapshot: Codable {
|
||||
}
|
||||
}
|
||||
|
||||
/// The trip's next flight or the one in the air, for the flight widget.
|
||||
/// Times are epoch seconds, so the widget moves its countdown and its
|
||||
/// aircraft on with the clock between two snapshots; the clock times at
|
||||
/// either airport come formatted, the widget has no zone data.
|
||||
struct Flight: Codable {
|
||||
var number: String
|
||||
var from: String
|
||||
var to: String
|
||||
var fromCity: String?
|
||||
var toCity: String?
|
||||
var dep: Double
|
||||
var arr: Double
|
||||
/// Observed take-off.
|
||||
var depActual: Double?
|
||||
/// Before take-off: the planned departure plus the delay seen so far.
|
||||
var depExpected: Double?
|
||||
/// The feed saw the aircraft in the air when the app last looked.
|
||||
var airborne: Bool?
|
||||
/// Touchdown once landed, else the estimate while in the air.
|
||||
var arrExpected: Double?
|
||||
var landed: Bool?
|
||||
var depTime: String
|
||||
var arrTime: String
|
||||
var arrTimeExpected: String?
|
||||
/// Minutes late against the schedule, negative when early.
|
||||
var delay: Int?
|
||||
var aircraft: String?
|
||||
/// When the feed last heard the aircraft.
|
||||
var seen: Double?
|
||||
var path: String
|
||||
}
|
||||
|
||||
struct Labels: Codable {
|
||||
var nextTrip: String
|
||||
var today: String
|
||||
@@ -193,6 +225,22 @@ struct WidgetSnapshot: Codable {
|
||||
var votes: String?
|
||||
var noMessages: String?
|
||||
var departure: String?
|
||||
var flight: String?
|
||||
/// Contains "{time}", where the widget puts its running countdown.
|
||||
var flightDeparts: String?
|
||||
var flightInAir: String?
|
||||
/// Contains "{time}".
|
||||
var flightLands: String?
|
||||
var flightLanded: String?
|
||||
var flightOnTime: String?
|
||||
/// Contains "{m}".
|
||||
var flightLate: String?
|
||||
/// Contains "{m}".
|
||||
var flightEarly: String?
|
||||
var flightEstimated: String?
|
||||
/// Past the departure time with the aircraft not yet in the air.
|
||||
var flightReady: String?
|
||||
var noFlight: String?
|
||||
}
|
||||
|
||||
var trip: Trip?
|
||||
@@ -203,6 +251,7 @@ struct WidgetSnapshot: Codable {
|
||||
var packing: Packing?
|
||||
var atlas: Atlas?
|
||||
var collab: Collab?
|
||||
var flight: Flight?
|
||||
var labels: Labels
|
||||
|
||||
/// The dashboard's snapshot.
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "خطة اليوم كخط زمني، مع الطقس والمحطة التالية.";
|
||||
"widget.bookings.name" = "الحجوزات";
|
||||
"widget.bookings.description" = "رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها.";
|
||||
"widget.flight.name" = "الرحلة";
|
||||
"widget.flight.description" = "رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول.";
|
||||
"widget.todos.name" = "المهام";
|
||||
"widget.todos.description" = "ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة.";
|
||||
"widget.packing.name" = "قائمة الأمتعة";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Günün planı zaman xətti kimi, hava və növbəti dayanacaqla.";
|
||||
"widget.bookings.name" = "Bronlar";
|
||||
"widget.bookings.description" = "Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə.";
|
||||
"widget.flight.name" = "Uçuş";
|
||||
"widget.flight.description" = "Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş.";
|
||||
"widget.todos.name" = "Tapşırıqlar";
|
||||
"widget.todos.description" = "Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu.";
|
||||
"widget.packing.name" = "Yük siyahısı";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "El pla del dia com a línia de temps, amb el temps i la propera parada.";
|
||||
"widget.bookings.name" = "Reserves";
|
||||
"widget.bookings.description" = "Els teus propers vols, trens, hotels i taules, i quan toquen.";
|
||||
"widget.flight.name" = "Vol";
|
||||
"widget.flight.description" = "El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada.";
|
||||
"widget.todos.name" = "Tasques";
|
||||
"widget.todos.description" = "El que encara queda per al viatge i com va l'equipatge.";
|
||||
"widget.packing.name" = "Equipatge";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Plán dne jako časová osa, s počasím a další zastávkou.";
|
||||
"widget.bookings.name" = "Rezervace";
|
||||
"widget.bookings.description" = "Tvoje další lety, vlaky, hotely a stoly, a kdy tě čekají.";
|
||||
"widget.flight.name" = "Let";
|
||||
"widget.flight.description" = "Tvůj další let živě: odpočet do odletu, letadlo na cestě, zpoždění a přílet.";
|
||||
"widget.todos.name" = "Úkoly";
|
||||
"widget.todos.description" = "Co ještě zbývá k cestě a jak daleko je balení.";
|
||||
"widget.packing.name" = "Balení";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Der Tagesplan als Zeitleiste, mit dem Wetter und dem nächsten Stopp.";
|
||||
"widget.bookings.name" = "Buchungen";
|
||||
"widget.bookings.description" = "Deine nächsten Flüge, Züge, Hotels und Tische, und wann sie anstehen.";
|
||||
"widget.flight.name" = "Flug";
|
||||
"widget.flight.description" = "Dein nächster Flug live: Countdown bis zum Abflug, die Maschine unterwegs, Verspätung und Ankunft.";
|
||||
"widget.todos.name" = "To-dos";
|
||||
"widget.todos.description" = "Was für die Reise noch offen ist und wie weit das Packen ist.";
|
||||
"widget.packing.name" = "Packliste";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Το πρόγραμμα της ημέρας ως χρονολόγιο, με τον καιρό και την επόμενη στάση.";
|
||||
"widget.bookings.name" = "Κρατήσεις";
|
||||
"widget.bookings.description" = "Οι επόμενες πτήσεις, τα τρένα, τα ξενοδοχεία και τα τραπέζια σου, και πότε είναι.";
|
||||
"widget.flight.name" = "Πτήση";
|
||||
"widget.flight.description" = "Η επόμενη πτήση σου ζωντανά: αντίστροφη μέτρηση για την αναχώρηση, το αεροσκάφος καθ’ οδόν, καθυστέρηση και άφιξη.";
|
||||
"widget.todos.name" = "Εκκρεμότητες";
|
||||
"widget.todos.description" = "Τι μένει ακόμα για το ταξίδι και πόσο έχει προχωρήσει το πακετάρισμα.";
|
||||
"widget.packing.name" = "Αποσκευές";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Today's plan as a timeline, with the weather and what is next.";
|
||||
"widget.bookings.name" = "Bookings";
|
||||
"widget.bookings.description" = "Your next flights, trains, hotels and tables, and when they are due.";
|
||||
"widget.flight.name" = "Flight";
|
||||
"widget.flight.description" = "Your next flight live: departure countdown, the aircraft on its way, delay and arrival.";
|
||||
"widget.todos.name" = "To-dos";
|
||||
"widget.todos.description" = "What is still open for the trip, and how far the packing has come.";
|
||||
"widget.packing.name" = "Packing";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "El plan del día como línea de tiempo, con el tiempo y la próxima parada.";
|
||||
"widget.bookings.name" = "Reservas";
|
||||
"widget.bookings.description" = "Tus próximos vuelos, trenes, hoteles y mesas, y cuándo tocan.";
|
||||
"widget.flight.name" = "Vuelo";
|
||||
"widget.flight.description" = "Tu próximo vuelo en directo: cuenta atrás de la salida, el avión en camino, retraso y llegada.";
|
||||
"widget.todos.name" = "Tareas";
|
||||
"widget.todos.description" = "Lo que aún queda para el viaje y cómo va la maleta.";
|
||||
"widget.packing.name" = "Equipaje";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Päeva plaan ajajoonena, koos ilma ja järgmise peatusega.";
|
||||
"widget.bookings.name" = "Broneeringud";
|
||||
"widget.bookings.description" = "Sinu järgmised lennud, rongid, hotellid ja lauad ning millal need on.";
|
||||
"widget.flight.name" = "Lend";
|
||||
"widget.flight.description" = "Sinu järgmine lend otse: loendus väljumiseni, lennuk teel, hilinemine ja saabumine.";
|
||||
"widget.todos.name" = "Ülesanded";
|
||||
"widget.todos.description" = "Mis reisi jaoks veel tegemata on ja kui kaugel pakkimine on.";
|
||||
"widget.packing.name" = "Pakkimine";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Le programme du jour en frise, avec la météo et la prochaine étape.";
|
||||
"widget.bookings.name" = "Réservations";
|
||||
"widget.bookings.description" = "Vos prochains vols, trains, hôtels et tables, et quand ils arrivent.";
|
||||
"widget.flight.name" = "Vol";
|
||||
"widget.flight.description" = "Votre prochain vol en direct : compte à rebours du départ, l’avion en route, retard et arrivée.";
|
||||
"widget.todos.name" = "À faire";
|
||||
"widget.todos.description" = "Ce qui reste à faire pour le voyage et où en sont les bagages.";
|
||||
"widget.packing.name" = "Bagages";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "תוכנית היום כציר זמן, עם מזג האוויר והעצירה הבאה.";
|
||||
"widget.bookings.name" = "הזמנות";
|
||||
"widget.bookings.description" = "הטיסות, הרכבות, המלונות והשולחנות הבאים שלך, ומתי הם.";
|
||||
"widget.flight.name" = "טיסה";
|
||||
"widget.flight.description" = "הטיסה הבאה שלך בזמן אמת: ספירה לאחור עד ההמראה, המטוס בדרך, עיכוב והגעה.";
|
||||
"widget.todos.name" = "משימות";
|
||||
"widget.todos.description" = "מה עוד פתוח לטיול וכמה התקדמה האריזה.";
|
||||
"widget.packing.name" = "אריזה";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "A nap terve idővonalon, az időjárással és a következő megállóval.";
|
||||
"widget.bookings.name" = "Foglalások";
|
||||
"widget.bookings.description" = "A következő járataid, vonataid, szállásaid és asztalfoglalásaid, és hogy mikor esedékesek.";
|
||||
"widget.flight.name" = "Járat";
|
||||
"widget.flight.description" = "A következő járatod élőben: visszaszámlálás az indulásig, a gép útközben, késés és érkezés.";
|
||||
"widget.todos.name" = "Teendők";
|
||||
"widget.todos.description" = "Ami még hátravan az utazáshoz, és hol tart a csomagolás.";
|
||||
"widget.packing.name" = "Csomagolás";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Rencana hari ini sebagai linimasa, dengan cuaca dan perhentian berikutnya.";
|
||||
"widget.bookings.name" = "Pemesanan";
|
||||
"widget.bookings.description" = "Penerbangan, kereta, hotel, dan meja berikutnya, beserta waktunya.";
|
||||
"widget.flight.name" = "Penerbangan";
|
||||
"widget.flight.description" = "Penerbangan berikutnya secara langsung: hitung mundur keberangkatan, pesawat dalam perjalanan, keterlambatan, dan kedatangan.";
|
||||
"widget.todos.name" = "Tugas";
|
||||
"widget.todos.description" = "Yang masih tersisa untuk perjalanan dan sejauh mana persiapan barang.";
|
||||
"widget.packing.name" = "Barang bawaan";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Il programma del giorno come linea del tempo, con il meteo e la prossima tappa.";
|
||||
"widget.bookings.name" = "Prenotazioni";
|
||||
"widget.bookings.description" = "I tuoi prossimi voli, treni, hotel e tavoli, e quando sono.";
|
||||
"widget.flight.name" = "Volo";
|
||||
"widget.flight.description" = "Il tuo prossimo volo in tempo reale: conto alla rovescia per la partenza, l’aereo in viaggio, ritardo e arrivo.";
|
||||
"widget.todos.name" = "Da fare";
|
||||
"widget.todos.description" = "Cosa manca ancora per il viaggio e a che punto è la valigia.";
|
||||
"widget.packing.name" = "Bagagli";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "今日の予定をタイムラインで、天気と次の予定とともに表示します。";
|
||||
"widget.bookings.name" = "予約";
|
||||
"widget.bookings.description" = "次のフライト、列車、ホテル、レストランとその日時。";
|
||||
"widget.flight.name" = "フライト";
|
||||
"widget.flight.description" = "次のフライトをライブで:出発までのカウントダウン、飛行中の機体、遅延と到着。";
|
||||
"widget.todos.name" = "やること";
|
||||
"widget.todos.description" = "旅行のために残っていることと、荷造りの進み具合。";
|
||||
"widget.packing.name" = "持ち物";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "오늘 일정을 타임라인으로, 날씨와 다음 장소와 함께 보여 줍니다.";
|
||||
"widget.bookings.name" = "예약";
|
||||
"widget.bookings.description" = "다가오는 항공편, 기차, 호텔, 식당과 그 시간.";
|
||||
"widget.flight.name" = "항공편";
|
||||
"widget.flight.description" = "다음 항공편을 실시간으로: 출발 카운트다운, 비행 중인 항공기, 지연과 도착.";
|
||||
"widget.todos.name" = "할 일";
|
||||
"widget.todos.description" = "여행을 위해 남은 일과 짐 싸기 진행 상황.";
|
||||
"widget.packing.name" = "짐 싸기";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Het dagplan als tijdlijn, met het weer en de volgende stop.";
|
||||
"widget.bookings.name" = "Boekingen";
|
||||
"widget.bookings.description" = "Je volgende vluchten, treinen, hotels en tafels, en wanneer ze zijn.";
|
||||
"widget.flight.name" = "Vlucht";
|
||||
"widget.flight.description" = "Je volgende vlucht live: aftellen tot vertrek, het toestel onderweg, vertraging en aankomst.";
|
||||
"widget.todos.name" = "Taken";
|
||||
"widget.todos.description" = "Wat er nog openstaat voor de reis en hoe ver het inpakken is.";
|
||||
"widget.packing.name" = "Bagage";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Plan dnia jako oś czasu, z pogodą i kolejnym przystankiem.";
|
||||
"widget.bookings.name" = "Rezerwacje";
|
||||
"widget.bookings.description" = "Twoje najbliższe loty, pociągi, hotele i stoliki oraz ich terminy.";
|
||||
"widget.flight.name" = "Lot";
|
||||
"widget.flight.description" = "Twój następny lot na żywo: odliczanie do odlotu, samolot w drodze, opóźnienie i przylot.";
|
||||
"widget.todos.name" = "Zadania";
|
||||
"widget.todos.description" = "Co jeszcze zostało do zrobienia przed podróżą i jak idzie pakowanie.";
|
||||
"widget.packing.name" = "Pakowanie";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "O plano do dia como linha do tempo, com o clima e a próxima parada.";
|
||||
"widget.bookings.name" = "Reservas";
|
||||
"widget.bookings.description" = "Seus próximos voos, trens, hotéis e mesas, e quando acontecem.";
|
||||
"widget.flight.name" = "Voo";
|
||||
"widget.flight.description" = "Seu próximo voo ao vivo: contagem regressiva para a partida, o avião a caminho, atraso e chegada.";
|
||||
"widget.todos.name" = "Tarefas";
|
||||
"widget.todos.description" = "O que ainda falta para a viagem e quanto da mala já está pronto.";
|
||||
"widget.packing.name" = "Bagagem";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "План дня в виде ленты времени, с погодой и следующей остановкой.";
|
||||
"widget.bookings.name" = "Бронирования";
|
||||
"widget.bookings.description" = "Ближайшие рейсы, поезда, отели и столики и когда они.";
|
||||
"widget.flight.name" = "Рейс";
|
||||
"widget.flight.description" = "Ваш следующий рейс в реальном времени: отсчёт до вылета, самолёт в пути, задержка и прибытие.";
|
||||
"widget.todos.name" = "Задачи";
|
||||
"widget.todos.description" = "Что ещё осталось сделать к поездке и как идут сборы.";
|
||||
"widget.packing.name" = "Сборы";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Plán dňa ako časová os, s počasím a ďalšou zastávkou.";
|
||||
"widget.bookings.name" = "Rezervácie";
|
||||
"widget.bookings.description" = "Tvoje ďalšie lety, vlaky, hotely a stoly a kedy ťa čakajú.";
|
||||
"widget.flight.name" = "Let";
|
||||
"widget.flight.description" = "Tvoj ďalší let naživo: odpočet do odletu, lietadlo na ceste, meškanie a prílet.";
|
||||
"widget.todos.name" = "Úlohy";
|
||||
"widget.todos.description" = "Čo ešte zostáva na cestu a ako ďaleko je balenie.";
|
||||
"widget.packing.name" = "Balenie";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Dagens plan som tidslinje, med vädret och nästa stopp.";
|
||||
"widget.bookings.name" = "Bokningar";
|
||||
"widget.bookings.description" = "Dina nästa flyg, tåg, hotell och bord, och när de är.";
|
||||
"widget.flight.name" = "Flyg";
|
||||
"widget.flight.description" = "Ditt nästa flyg live: nedräkning till avgång, planet på väg, försening och ankomst.";
|
||||
"widget.todos.name" = "Att göra";
|
||||
"widget.todos.description" = "Vad som återstår inför resan och hur långt packningen har kommit.";
|
||||
"widget.packing.name" = "Packning";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "แผนของวันนี้เป็นไทม์ไลน์ พร้อมสภาพอากาศและจุดหมายถัดไป";
|
||||
"widget.bookings.name" = "การจอง";
|
||||
"widget.bookings.description" = "เที่ยวบิน รถไฟ โรงแรม และร้านอาหารถัดไปของคุณ และเวลาของแต่ละรายการ";
|
||||
"widget.flight.name" = "เที่ยวบิน";
|
||||
"widget.flight.description" = "เที่ยวบินถัดไปแบบสด: นับถอยหลังถึงเวลาออกเดินทาง เครื่องบินระหว่างทาง ความล่าช้า และเวลาถึง";
|
||||
"widget.todos.name" = "สิ่งที่ต้องทำ";
|
||||
"widget.todos.description" = "สิ่งที่ยังค้างอยู่สำหรับทริป และความคืบหน้าการจัดกระเป๋า";
|
||||
"widget.packing.name" = "จัดกระเป๋า";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Günün planı zaman çizelgesi olarak, hava durumu ve sonraki durakla.";
|
||||
"widget.bookings.name" = "Rezervasyonlar";
|
||||
"widget.bookings.description" = "Sıradaki uçuşların, trenlerin, otellerin ve masaların, ne zaman oldukları ile.";
|
||||
"widget.flight.name" = "Uçuş";
|
||||
"widget.flight.description" = "Bir sonraki uçuşun canlı: kalkışa geri sayım, yoldaki uçak, gecikme ve varış.";
|
||||
"widget.todos.name" = "Yapılacaklar";
|
||||
"widget.todos.description" = "Seyahat için hâlâ açık olanlar ve bavulun ne durumda olduğu.";
|
||||
"widget.packing.name" = "Bavul";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "План дня у вигляді стрічки часу, з погодою і наступною зупинкою.";
|
||||
"widget.bookings.name" = "Бронювання";
|
||||
"widget.bookings.description" = "Найближчі рейси, поїзди, готелі й столики та коли вони.";
|
||||
"widget.flight.name" = "Рейс";
|
||||
"widget.flight.description" = "Ваш наступний рейс наживо: відлік до вильоту, літак у дорозі, затримка й прибуття.";
|
||||
"widget.todos.name" = "Завдання";
|
||||
"widget.todos.description" = "Що ще лишилося зробити до подорожі і як просувається пакування.";
|
||||
"widget.packing.name" = "Пакування";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "Kế hoạch hôm nay dạng dòng thời gian, kèm thời tiết và điểm dừng tiếp theo.";
|
||||
"widget.bookings.name" = "Đặt chỗ";
|
||||
"widget.bookings.description" = "Các chuyến bay, tàu, khách sạn và bàn sắp tới của bạn, cùng thời gian.";
|
||||
"widget.flight.name" = "Chuyến bay";
|
||||
"widget.flight.description" = "Chuyến bay tiếp theo trực tiếp: đếm ngược giờ khởi hành, máy bay đang bay, độ trễ và giờ đến.";
|
||||
"widget.todos.name" = "Việc cần làm";
|
||||
"widget.todos.description" = "Những gì còn lại cho chuyến đi và việc soạn hành lý đã tới đâu.";
|
||||
"widget.packing.name" = "Hành lý";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "以时间线显示今天的计划,附带天气和下一站。";
|
||||
"widget.bookings.name" = "预订";
|
||||
"widget.bookings.description" = "你接下来的航班、火车、酒店和餐厅,以及时间。";
|
||||
"widget.flight.name" = "航班";
|
||||
"widget.flight.description" = "实时查看下一班航班:起飞倒计时、飞行中的飞机、延误和到达。";
|
||||
"widget.todos.name" = "待办";
|
||||
"widget.todos.description" = "旅行还剩哪些事没做,以及行李收拾到哪一步。";
|
||||
"widget.packing.name" = "行李";
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"widget.today.description" = "以時間軸顯示今天的計畫,附上天氣與下一站。";
|
||||
"widget.bookings.name" = "預訂";
|
||||
"widget.bookings.description" = "你接下來的航班、火車、飯店與餐廳,以及時間。";
|
||||
"widget.flight.name" = "航班";
|
||||
"widget.flight.description" = "即時查看下一班航班:起飛倒數、飛行中的飛機、延誤和抵達。";
|
||||
"widget.todos.name" = "待辦";
|
||||
"widget.todos.description" = "旅行還剩哪些事沒做,以及行李整理到哪一步。";
|
||||
"widget.packing.name" = "行李";
|
||||
|
||||
@@ -375,6 +375,7 @@ struct LockAccessory: View {
|
||||
switch kind {
|
||||
case .trip: TripContent(snapshot: snapshot, family: family, now: now)
|
||||
case .bookings: BookingsContent(snapshot: snapshot, family: family, now: now)
|
||||
case .flight: FlightContent(snapshot: snapshot, family: family, now: now)
|
||||
case .todos: TodosContent(snapshot: snapshot, family: family, now: now)
|
||||
case .packing: PackingContent(snapshot: snapshot, family: family, now: now)
|
||||
case .atlas: AtlasContent(snapshot: snapshot, family: family)
|
||||
|
||||
@@ -107,13 +107,14 @@ struct Render {
|
||||
}
|
||||
|
||||
enum WidgetKind: String, CaseIterable {
|
||||
case trip, today, bookings, todos, packing, atlas, collab
|
||||
case trip, today, bookings, flight, todos, packing, atlas, collab
|
||||
|
||||
var families: [TrekFamily] {
|
||||
switch self {
|
||||
case .trip: return [.small, .medium, .large, .extraLarge, .circular, .rectangular, .inline]
|
||||
case .today: return [.medium, .large, .extraLarge]
|
||||
case .bookings: return [.small, .medium, .large, .extraLarge, .rectangular, .inline]
|
||||
case .flight: return [.small, .medium, .large, .circular, .rectangular, .inline]
|
||||
case .todos: return [.small, .medium, .large, .circular, .rectangular]
|
||||
case .packing: return [.small, .medium, .large, .circular, .rectangular]
|
||||
case .atlas: return [.small, .medium, .large, .circular, .rectangular, .inline]
|
||||
@@ -158,6 +159,7 @@ struct WidgetFrame: View {
|
||||
case .trip: TripContent(snapshot: snapshot, family: family, now: now)
|
||||
case .today: TodayContent(snapshot: snapshot, family: family, now: now)
|
||||
case .bookings: BookingsContent(snapshot: snapshot, family: family, now: now)
|
||||
case .flight: FlightContent(snapshot: snapshot, family: family, now: now)
|
||||
case .todos: TodosContent(snapshot: snapshot, family: family, now: now)
|
||||
case .packing: PackingContent(snapshot: snapshot, family: family, now: now)
|
||||
case .atlas: AtlasContent(snapshot: snapshot, family: family)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The amount inside a price as the store writes it ("4,90 €", "$4.99",
|
||||
* "CHF 12.90", "1.290 ₽"), and a way to write another amount the same way: the
|
||||
* same currency, the same decimal mark, the same digit grouping. The plan picker
|
||||
* counts a price up to its new value with it, and turns a yearly price into what
|
||||
* it makes a month, without knowing the store's locale.
|
||||
*/
|
||||
interface Amount {
|
||||
/** The amount as a number, in the price's own unit (4.9 for "4,90 €"). */
|
||||
value: number;
|
||||
/** The price written for another amount, in the same format. */
|
||||
render(value: number): string;
|
||||
}
|
||||
|
||||
// Digits with the marks stores put between them: . , any space (\s takes the
|
||||
// no-break ones too) and the apostrophes Swiss formats group thousands with.
|
||||
const NUMBER = /\d[\d.,\s'’]*\d|\d/;
|
||||
|
||||
export function amountIn(label: string): Amount | null {
|
||||
const match = NUMBER.exec(label);
|
||||
if (!match) return null;
|
||||
const raw = match[0];
|
||||
// The decimal mark is the last . or , followed by one or two digits to the end.
|
||||
const decimal = /([.,])(\d{1,2})$/.exec(raw);
|
||||
const decimals = decimal ? decimal[2].length : 0;
|
||||
const mark = decimal ? decimal[1] : '';
|
||||
const whole = decimal ? raw.slice(0, raw.length - decimal[0].length) : raw;
|
||||
const group = /[.,\s'’]/.exec(whole)?.[0] ?? '';
|
||||
const digits = whole.replace(/\D/g, '') + (decimal ? `.${decimal[2]}` : '');
|
||||
const value = Number(digits);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const before = label.slice(0, match.index);
|
||||
const after = label.slice(match.index + raw.length);
|
||||
return {
|
||||
value,
|
||||
render(next: number) {
|
||||
const fixed = Math.max(0, next).toFixed(decimals);
|
||||
const [int, frac] = fixed.split('.');
|
||||
const grouped = group ? int.replace(/\B(?=(\d{3})+(?!\d))/g, group) : int;
|
||||
return `${before}${grouped}${frac !== undefined ? mark + frac : ''}${after}`;
|
||||
},
|
||||
};
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user