Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1bfe57d75c | |||
| 7ca7dfd555 | |||
| c708b93824 | |||
| b50812d51d | |||
| 267e0e16a2 |
@@ -1,7 +1,6 @@
|
||||
node_modules
|
||||
client/node_modules
|
||||
server/node_modules
|
||||
shared/node_modules
|
||||
client/dist
|
||||
shared/dist
|
||||
data
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
# Commits that only reformat code. git blame skips them with
|
||||
# git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
# (GitHub reads this file on its own).
|
||||
|
||||
# style: format server and shared with prettier
|
||||
724c88c201b2c16d31317eaea5f59f43d314b833
|
||||
@@ -26,8 +26,5 @@
|
||||
*.eot binary
|
||||
*.pdf binary
|
||||
*.zip binary
|
||||
# Ski area graphs (SGR1) as the Places host writes them, byte for byte
|
||||
*.sgr binary
|
||||
*.gz binary
|
||||
# A GPX fixture whose byte-order mark and CRLF line endings are what it tests
|
||||
server/tests/fixtures/gpx/bom-crlf.gpx -text
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
# Version updates, weekly, into dev. Minor and patch bumps of one ecosystem
|
||||
# arrive as a single grouped PR; a major bump gets a PR of its own so its
|
||||
# breaking notes are read on their own.
|
||||
#
|
||||
# Security updates are a repository setting, not part of this file, and
|
||||
# GitHub opens them against the default branch whatever target-branch says.
|
||||
# enforce-target-branch.yml moves those onto dev.
|
||||
#
|
||||
# Every PR runs test.yml like any other, so ci-ok decides whether it can
|
||||
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
|
||||
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
|
||||
version: 2
|
||||
updates:
|
||||
# The root lockfile covers the client, server and shared workspaces.
|
||||
- package-ecosystem: npm
|
||||
directory: /
|
||||
target-branch: dev
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 5
|
||||
commit-message:
|
||||
prefix: chore(deps)
|
||||
prefix-development: chore(deps-dev)
|
||||
groups:
|
||||
npm-minor-and-patch:
|
||||
update-types: [minor, patch]
|
||||
|
||||
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
|
||||
- package-ecosystem: npm
|
||||
directory: /plugin-sdk
|
||||
target-branch: dev
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 3
|
||||
commit-message:
|
||||
prefix: chore(plugin-sdk)
|
||||
prefix-development: chore(plugin-sdk)
|
||||
groups:
|
||||
plugin-sdk-minor-and-patch:
|
||||
update-types: [minor, patch]
|
||||
|
||||
# Keeps the SHA pins of third-party actions current, comment included.
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
target-branch: dev
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 3
|
||||
commit-message:
|
||||
prefix: ci
|
||||
groups:
|
||||
actions-minor-and-patch:
|
||||
update-types: [minor, patch]
|
||||
|
||||
# The Dockerfile's base images. The Node major follows .nvmrc and the
|
||||
# engines ranges, so it moves by hand, together with them.
|
||||
- package-ecosystem: docker
|
||||
directory: /
|
||||
target-branch: dev
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 3
|
||||
commit-message:
|
||||
prefix: chore(docker)
|
||||
ignore:
|
||||
- dependency-name: node
|
||||
update-types: [version-update:semver-major]
|
||||
@@ -10,11 +10,10 @@ permissions:
|
||||
jobs:
|
||||
close-stale:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Close stale invalid-title issues
|
||||
uses: actions/github-script@v9
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const badTitles = [
|
||||
|
||||
@@ -11,11 +11,10 @@ permissions:
|
||||
jobs:
|
||||
close-stale:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Close stale wrong-base-branch PRs
|
||||
uses: actions/github-script@v9
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const { data: pulls } = await github.rest.pulls.list({
|
||||
|
||||
@@ -10,11 +10,10 @@ permissions:
|
||||
jobs:
|
||||
check-title:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Flag or redirect issue
|
||||
uses: actions/github-script@v9
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const title = context.payload.issue.title.trim();
|
||||
|
||||
@@ -1,18 +1,5 @@
|
||||
name: Build & Push Docker Image (Prerelease)
|
||||
|
||||
# The canary. Dispatched by hand, usually on dev, it builds the dispatched
|
||||
# commit as <next minor or major>-pre.N, publishes :VERSION, :MAJOR-pre and
|
||||
# :latest-pre, and tags the commit. Nothing moves :latest. Like the stable
|
||||
# release it refuses a commit whose ci-ok is not green. docker.yml with
|
||||
# bump=auto later finalizes the line once main carries it.
|
||||
#
|
||||
# A prerelease asks the TREK services issuer for a registration dialect of its
|
||||
# own -pre.N version (registration-dialect.yml, as the stable release does)
|
||||
# and builds it into the image; nothing of it is committed, dev keeps the
|
||||
# module of the last stable release, which it gets when main is merged back
|
||||
# into dev. Without one the image carries dev's module, with a warning when
|
||||
# that is the original one or old.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -24,7 +11,6 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
checks: read
|
||||
|
||||
concurrency:
|
||||
group: prerelease-build
|
||||
@@ -33,41 +19,23 @@ concurrency:
|
||||
jobs:
|
||||
version-bump:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.bump.outputs.VERSION }}
|
||||
sha: ${{ steps.bump.outputs.SHA }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# The dev push, the main push and any manual run each leave a ci-ok on
|
||||
# this commit. scripts/ci/ci-ok-verdict.mjs counts the newest attempt of
|
||||
# each, refuses while one is still going, and requires the one that
|
||||
# finished last to be green, so a later green run supersedes a flaky or
|
||||
# cancelled one. It prints the link of every run it counted.
|
||||
- name: Require a green ci-ok on the commit being built
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sha="$(git rev-parse HEAD)"
|
||||
runs="$RUNNER_TEMP/ci-ok-runs.json"
|
||||
gh api "repos/$GITHUB_REPOSITORY/commits/$sha/check-runs?check_name=ci-ok&filter=all&per_page=100" > "$runs"
|
||||
node scripts/ci/ci-ok-verdict.mjs "$runs" "$sha"
|
||||
|
||||
- name: Determine prerelease version
|
||||
id: bump
|
||||
env:
|
||||
BUMP_INPUT: ${{ inputs.bump || 'auto' }}
|
||||
run: |
|
||||
git fetch --tags
|
||||
|
||||
# Capture the exact commit we're building so build/merge jobs are pinned to it
|
||||
echo "SHA=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
echo "SHA=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
# Get latest stable tag (exclude prerelease tags)
|
||||
STABLE_TAG=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' | grep -v '\-pre\.' | sort -V | tail -1)
|
||||
@@ -75,12 +43,14 @@ jobs:
|
||||
STABLE="${STABLE:-0.0.0}"
|
||||
echo "Latest stable: $STABLE"
|
||||
|
||||
IFS='.' read -r MAJOR MINOR _ <<< "$STABLE"
|
||||
IFS='.' read -r MAJOR MINOR PATCH <<< "$STABLE"
|
||||
|
||||
# Detect any in-flight major prerelease (v(MAJOR+1).0.0-pre.*). Stay on that line if found.
|
||||
NEXT_MAJOR="$((MAJOR + 1)).0.0"
|
||||
MAJOR_PRE_EXISTS=$(git tag -l "v${NEXT_MAJOR}-pre.*" | head -1)
|
||||
|
||||
BUMP_INPUT="${{ github.event.inputs.bump || 'auto' }}"
|
||||
|
||||
if [ "$BUMP_INPUT" = "major" ] || { [ "$BUMP_INPUT" = "auto" ] && [ -n "$MAJOR_PRE_EXISTS" ]; }; then
|
||||
TARGET="$NEXT_MAJOR"
|
||||
else
|
||||
@@ -93,89 +63,31 @@ jobs:
|
||||
N=$(( ${LAST_N:-0} + 1 ))
|
||||
|
||||
NEW_VERSION="${TARGET}-pre.${N}"
|
||||
echo "VERSION=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "$STABLE to $NEW_VERSION"
|
||||
|
||||
# The registration dialect of this prerelease, fetched and checked in a job
|
||||
# without write access. It never fails the build.
|
||||
dialect:
|
||||
needs: version-bump
|
||||
uses: ./.github/workflows/registration-dialect.yml
|
||||
with:
|
||||
version: ${{ needs.version-bump.outputs.version }}
|
||||
ref: ${{ needs.version-bump.outputs.sha }}
|
||||
secrets:
|
||||
TREK_DIALECT_TOKEN: ${{ secrets.TREK_DIALECT_TOKEN }}
|
||||
echo "VERSION=$NEW_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "$STABLE → $NEW_VERSION"
|
||||
|
||||
build:
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 120
|
||||
needs: [version-bump, dialect]
|
||||
# Whatever became of the dialect job: without its artifact the image carries dev's module.
|
||||
if: ${{ !cancelled() && needs.version-bump.result == 'success' }}
|
||||
needs: version-bump
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-24.04
|
||||
runner: ubuntu-latest
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
steps:
|
||||
- name: Prepare platform tag-safe name
|
||||
env:
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
run: echo "PLATFORM_PAIR=${PLATFORM//\//-}" >> "$GITHUB_ENV"
|
||||
run: echo "PLATFORM_PAIR=$(echo ${{ matrix.platform }} | sed 's|/|-|g')" >> $GITHUB_ENV
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.version-bump.outputs.sha }}
|
||||
|
||||
- name: Take over the prerelease's dialect
|
||||
id: take
|
||||
uses: actions/download-artifact@v7
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: registration-dialect
|
||||
path: ${{ runner.temp }}/dialect
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
# Into the build context only; the commit stays as it is. Without a
|
||||
# dialect of its own the image speaks dev's module, which the issuer
|
||||
# takes for new installations for 180 days after it was made (longer
|
||||
# while it is the newest stable release's). That is warned about, never
|
||||
# stopped on, and a date that cannot be read only warns as well.
|
||||
- name: Place the dialect
|
||||
env:
|
||||
VERSION: ${{ needs.version-bump.outputs.version }}
|
||||
TAKEN: ${{ steps.take.outcome }}
|
||||
REPORT: ${{ matrix.platform == 'linux/amd64' }}
|
||||
run: |
|
||||
set -u
|
||||
target=server/src/nest/service-identity/registration-dialect.ts
|
||||
fetched="$RUNNER_TEMP/dialect/registration-dialect.ts"
|
||||
if [ "$TAKEN" = success ] && [ -f "$fetched" ]; then
|
||||
cp "$fetched" "$target"
|
||||
echo "$VERSION registers in dialect $(sed -n "s/^const DIALECT = '\(.*\)';$/\1/p" "$target") of its own."
|
||||
exit 0
|
||||
fi
|
||||
[ "$REPORT" = true ] || exit 0
|
||||
id="$(sed -n "s/^const DIALECT = '\(.*\)';$/\1/p" "$target")"
|
||||
created="$(sed -n "s/^ createdAt: '\(.*\)',$/\1/p" "$target")"
|
||||
if [ "$id" = 0 ]; then
|
||||
message="$VERSION got no dialect of its own and registers in the original one, which the issuer accepts only for a transition period."
|
||||
elif made="$(date -u -d "$created" +%s 2>/dev/null)"; then
|
||||
age=$(( ($(date -u +%s) - made) / 86400 ))
|
||||
message="$VERSION got no dialect of its own and registers in dev's dialect $id from $created, $age days old."
|
||||
[ "$age" -gt 150 ] || { echo "$message"; exit 0; }
|
||||
else
|
||||
message="$VERSION got no dialect of its own, and the date of dev's dialect cannot be read from $target."
|
||||
fi
|
||||
echo "::warning::$message"
|
||||
printf '### Registration dialect\n%s\n' "$message" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
@@ -188,7 +100,7 @@ jobs:
|
||||
|
||||
- name: Build and push by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: ${{ matrix.platform }}
|
||||
@@ -207,7 +119,7 @@ jobs:
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
|
||||
- name: Upload digest artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
path: /tmp/digests/*
|
||||
@@ -215,28 +127,26 @@ jobs:
|
||||
retention-days: 1
|
||||
|
||||
merge:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-latest
|
||||
needs: [version-bump, build]
|
||||
if: ${{ !cancelled() && needs.build.result == 'success' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.version-bump.outputs.sha }}
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Download build digests
|
||||
uses: actions/download-artifact@v7
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: /tmp/digests
|
||||
pattern: digests-*
|
||||
# Deliberately NOT merged: the per-platform folder names are what lets
|
||||
# the manifest below be assembled in a fixed order.
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
@@ -290,7 +200,7 @@ jobs:
|
||||
run: |
|
||||
KEEP=20
|
||||
VERSION="${{ needs.version-bump.outputs.version }}"
|
||||
BASE_VERSION="${VERSION%%-pre.*}"
|
||||
BASE_VERSION="$(echo "$VERSION" | sed 's/-pre\..*//')"
|
||||
git fetch --tags
|
||||
# Sort by numeric prerelease N (field after -pre.) to get correct ascending order
|
||||
mapfile -t ALL_TAGS < <(git tag -l "v${BASE_VERSION}-pre.*" | awk -F'-pre\\.' '{print $2" "$0}' | sort -n | awk '{print $2}')
|
||||
|
||||
@@ -1,36 +1,10 @@
|
||||
name: Build & Push Docker Image
|
||||
|
||||
# The stable release. Dispatched by hand on main, it:
|
||||
# 1. refuses to run unless ci-ok passed on the main commit it releases,
|
||||
# 2. works out the version from the tags and the bump input,
|
||||
# 3. asks the TREK services issuer for the registration dialect of that
|
||||
# version and checks it, in a job without write access
|
||||
# (registration-dialect.yml); without one the release ships the dialect
|
||||
# already on main, but only while that one still has 90 days to run,
|
||||
# 4. commits the bump to package.json, the lockfile, Chart.yaml and the
|
||||
# dialect, tags it and pushes,
|
||||
# 5. builds both platforms from exactly that bump commit (never from
|
||||
# whatever main points to by then) and publishes :VERSION,
|
||||
# :MAJOR.MINOR, :MAJOR and :latest,
|
||||
# 6. publishes the Helm chart from the same commit.
|
||||
#
|
||||
# Big or risky changes go out as a prerelease first (docker-dev.yml, tagged
|
||||
# :latest-pre and :<next>-pre.N); bump=auto here then finalizes that line.
|
||||
# Without a prerelease in flight there is no default: the run stops until
|
||||
# someone picks patch, minor or major.
|
||||
#
|
||||
# Each stable release registers new installations in a dialect of its own,
|
||||
# which the issuer accepts for 180 days, and for as long as it is the newest
|
||||
# release's; renewing a key needs none. dev gets the module when main is merged
|
||||
# back into dev after the release; a prerelease asks the issuer for one of its
|
||||
# own (docker-dev.yml). The issuer's side, and what to set up before the first
|
||||
# release with a dialect, is in the operations guide of the TREK services.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
bump:
|
||||
description: 'auto finalizes the prerelease in flight; otherwise pick patch, minor or major'
|
||||
description: 'Force bump line (auto = patch/finalize as today)'
|
||||
type: choice
|
||||
options: [auto, patch, minor, major]
|
||||
default: auto
|
||||
@@ -38,118 +12,50 @@ on:
|
||||
description: "Type MAJOR (all caps) to confirm a major release"
|
||||
type: string
|
||||
default: ''
|
||||
ci_from:
|
||||
description: 'Take ci-ok from this earlier commit instead of the one on main, when main differs from it only under .github/ (a fix to a release workflow needs no second test run)'
|
||||
type: string
|
||||
default: ''
|
||||
allow_stale_dialect:
|
||||
description: 'Ship without a dialect of its own even if the one on main is the original one or has under 90 days left'
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
checks: read
|
||||
|
||||
concurrency:
|
||||
group: stable-build
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
version:
|
||||
version-bump:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
checks: read
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.bump.outputs.VERSION }}
|
||||
base: ${{ steps.base.outputs.SHA }}
|
||||
steps:
|
||||
- name: Release from main only
|
||||
if: github.ref != 'refs/heads/main'
|
||||
run: |
|
||||
echo "::error::Dispatch this workflow on main, not on $GITHUB_REF."
|
||||
exit 1
|
||||
- uses: actions/create-github-app-token@v1
|
||||
id: app-token
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
persist-credentials: false
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
# The bump job checks out exactly this commit, so what ci-ok was checked
|
||||
# on is what gets released, however long the dialect takes.
|
||||
- name: Note the commit being released
|
||||
id: base
|
||||
run: echo "SHA=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# The dev push, the main push and any manual run each leave a ci-ok on
|
||||
# this commit. scripts/ci/ci-ok-verdict.mjs counts the newest attempt of
|
||||
# each, refuses while one is still going, and requires the one that
|
||||
# finished last to be green, so a later green run supersedes a flaky or
|
||||
# cancelled one. It prints the link of every run it counted.
|
||||
- name: Require a green ci-ok on the commit being released
|
||||
if: inputs.ci_from == ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sha="$(git rev-parse HEAD)"
|
||||
runs="$RUNNER_TEMP/ci-ok-runs.json"
|
||||
gh api "repos/$GITHUB_REPOSITORY/commits/$sha/check-runs?check_name=ci-ok&filter=all&per_page=100" > "$runs"
|
||||
node scripts/ci/ci-ok-verdict.mjs "$runs" "$sha"
|
||||
|
||||
# ci_from: main carries only workflow changes on top of a commit that
|
||||
# already passed. That commit must be an ancestor of main, everything
|
||||
# outside .github/ must be identical, and one of its ci-ok runs must be
|
||||
# green (its dev push, typically).
|
||||
- name: Require a green ci-ok on the commit main's code comes from
|
||||
if: inputs.ci_from != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
CI_FROM: ${{ inputs.ci_from }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
from="$(git rev-parse --verify "$CI_FROM^{commit}")"
|
||||
if ! git merge-base --is-ancestor "$from" HEAD; then
|
||||
echo "::error::$from is not an ancestor of main."
|
||||
exit 1
|
||||
fi
|
||||
outside="$(git diff --name-only "$from" HEAD -- . ':(exclude).github/**')"
|
||||
if [ -n "$outside" ]; then
|
||||
echo "::error::main differs from $from outside .github/:"
|
||||
echo "$outside"
|
||||
exit 1
|
||||
fi
|
||||
green="$(gh api "repos/$GITHUB_REPOSITORY/commits/$from/check-runs?check_name=ci-ok&filter=all&per_page=100" \
|
||||
--jq '[.check_runs[] | select(.status == "completed" and .conclusion == "success")] | length')"
|
||||
if [ "$green" -lt 1 ]; then
|
||||
echo "::error::$from has no green ci-ok."
|
||||
exit 1
|
||||
fi
|
||||
echo "main differs from $from only under .github/, and $from has $green green ci-ok run(s)."
|
||||
|
||||
- name: Determine bump type and version
|
||||
- name: Determine bump type and update version
|
||||
id: bump
|
||||
env:
|
||||
BUMP_INPUT: ${{ inputs.bump || 'auto' }}
|
||||
CONFIRM_MAJOR: ${{ inputs.confirm_major }}
|
||||
run: |
|
||||
set -eu
|
||||
git fetch --tags
|
||||
|
||||
# Derive version from git tags, no package.json dependency
|
||||
# Derive version from git tags — no package.json dependency
|
||||
STABLE_TAG=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' | grep -v '\-pre\.' | sort -V | tail -1)
|
||||
STABLE="${STABLE_TAG#v}"
|
||||
STABLE="${STABLE:-0.0.0}"
|
||||
|
||||
PRE_TAG=$(git tag -l 'v*-pre.*' | sort -V | tail -1)
|
||||
|
||||
BUMP_INPUT="${{ github.event.inputs.bump || 'auto' }}"
|
||||
IFS='.' read -r MAJOR MINOR PATCH <<< "$STABLE"
|
||||
|
||||
if [ "$BUMP_INPUT" = "major" ]; then
|
||||
if [ "$CONFIRM_MAJOR" != "MAJOR" ]; then
|
||||
if [ "${{ github.event.inputs.confirm_major }}" != "MAJOR" ]; then
|
||||
echo "::error::confirm_major must equal 'MAJOR' to cut a major release"
|
||||
exit 1
|
||||
fi
|
||||
@@ -162,187 +68,72 @@ jobs:
|
||||
NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH + 1))"
|
||||
BUMP="patch"
|
||||
else
|
||||
# auto finalizes the in-flight prerelease and nothing else. It used
|
||||
# to fall back to a patch, which would have shipped any change,
|
||||
# however big, as a patch nobody chose.
|
||||
PRE_BASE=""
|
||||
# auto: finalize in-flight prerelease if one exists, else patch
|
||||
if [ -n "$PRE_TAG" ]; then
|
||||
PRE_BASE="${PRE_TAG#v}"
|
||||
PRE_BASE="${PRE_BASE%-pre.*}"
|
||||
PRE_MAJOR="$(echo "$PRE_BASE" | cut -d. -f1)"
|
||||
# Refuse to auto-finalize a major bump — it bypasses confirm_major
|
||||
if [ "$PRE_MAJOR" -gt "$MAJOR" ]; then
|
||||
echo "::error::In-flight prerelease $PRE_TAG is a major bump ($STABLE → $PRE_BASE). Use bump=major with confirm_major=MAJOR to finalize."
|
||||
exit 1
|
||||
fi
|
||||
# If prerelease base is strictly greater than stable, finalize it
|
||||
HIGHEST=$(printf '%s\n' "$PRE_BASE" "$STABLE" | sort -V | tail -1)
|
||||
if [ "$HIGHEST" = "$PRE_BASE" ] && [ "$PRE_BASE" != "$STABLE" ]; then
|
||||
NEW_VERSION="$PRE_BASE"
|
||||
BUMP="finalize"
|
||||
else
|
||||
PATCH=$((PATCH + 1))
|
||||
NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
|
||||
BUMP="patch"
|
||||
fi
|
||||
else
|
||||
PATCH=$((PATCH + 1))
|
||||
NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
|
||||
BUMP="patch"
|
||||
fi
|
||||
HIGHEST=$(printf '%s\n' "$PRE_BASE" "$STABLE" | sort -V | tail -1)
|
||||
if [ -z "$PRE_BASE" ] || [ "$HIGHEST" != "$PRE_BASE" ] || [ "$PRE_BASE" = "$STABLE" ]; then
|
||||
echo "::error::No prerelease above $STABLE is in flight, so bump=auto has nothing to finalize. Dispatch again with bump=patch, minor or major."
|
||||
exit 1
|
||||
fi
|
||||
PRE_MAJOR="$(echo "$PRE_BASE" | cut -d. -f1)"
|
||||
# Refuse to auto-finalize a major bump, it would bypass confirm_major
|
||||
if [ "$PRE_MAJOR" -gt "$MAJOR" ]; then
|
||||
echo "::error::In-flight prerelease $PRE_TAG is a major bump ($STABLE to $PRE_BASE). Use bump=major with confirm_major=MAJOR to finalize."
|
||||
exit 1
|
||||
fi
|
||||
NEW_VERSION="$PRE_BASE"
|
||||
BUMP="finalize"
|
||||
fi
|
||||
|
||||
# Patch releases have carried migrations before, so this only warns:
|
||||
# whoever pinned :MAJOR.MINOR gets this schema change too.
|
||||
if [ "$BUMP" = "patch" ] && [ -n "$STABLE_TAG" ] \
|
||||
&& [ -n "$(git diff --name-only --diff-filter=A "$STABLE_TAG" HEAD -- server/src/db/migrations/)" ]; then
|
||||
echo "::warning::$NEW_VERSION is a patch release that adds database migrations."
|
||||
fi
|
||||
|
||||
echo "Bump type: $BUMP"
|
||||
echo "VERSION=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "$STABLE to $NEW_VERSION ($BUMP)"
|
||||
|
||||
# The registration dialect of this version, fetched and checked in a job
|
||||
# without write access. It never fails; without an artifact from it the
|
||||
# bump decides below whether the dialect on main may ship.
|
||||
dialect:
|
||||
needs: version
|
||||
uses: ./.github/workflows/registration-dialect.yml
|
||||
with:
|
||||
version: ${{ needs.version.outputs.version }}
|
||||
ref: ${{ needs.version.outputs.base }}
|
||||
secrets:
|
||||
TREK_DIALECT_TOKEN: ${{ secrets.TREK_DIALECT_TOKEN }}
|
||||
|
||||
# Runs whatever became of the dialect job, a timeout or a lost runner
|
||||
# included: no artifact means the dialect on main, if it may still ship.
|
||||
version-bump:
|
||||
needs: [version, dialect]
|
||||
if: ${{ !cancelled() && needs.version.result == 'success' }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
outputs:
|
||||
sha: ${{ steps.commit.outputs.SHA }}
|
||||
steps:
|
||||
- uses: actions/create-github-app-token@v3
|
||||
id: app-token
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.version.outputs.base }}
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Take over the checked dialect
|
||||
id: take
|
||||
uses: actions/download-artifact@v7
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: registration-dialect
|
||||
path: ${{ runner.temp }}/dialect
|
||||
|
||||
# Without a dialect of its own the release ships the one on main, but
|
||||
# only while the issuer takes new registrations in it for 90 more days:
|
||||
# dialect 0 closes on the issuer's transition date, and a dialect with
|
||||
# little left would shut out new installations of this release soon after
|
||||
# it is out. Then this stops before anything is committed, unless
|
||||
# allow_stale_dialect says to ship anyway. The issuer keeps the newest
|
||||
# release's dialect open past its date, so the date here is the least it
|
||||
# has, not the most.
|
||||
- name: Place the dialect
|
||||
env:
|
||||
VERSION: ${{ needs.version.outputs.version }}
|
||||
TAKEN: ${{ steps.take.outcome }}
|
||||
ALLOW_STALE: ${{ inputs.allow_stale_dialect }}
|
||||
run: |
|
||||
set -u
|
||||
target=server/src/nest/service-identity/registration-dialect.ts
|
||||
fetched="$RUNNER_TEMP/dialect/registration-dialect.ts"
|
||||
dialect_id() { sed -n "s/^const DIALECT = '\(.*\)';$/\1/p" "$1"; }
|
||||
report() {
|
||||
echo "$2$1"
|
||||
printf '### Registration dialect\n%s\n' "$1" >> "$GITHUB_STEP_SUMMARY"
|
||||
}
|
||||
if [ "$TAKEN" = success ] && [ -f "$fetched" ]; then
|
||||
cp "$fetched" "$target"
|
||||
report "$VERSION registers in dialect $(dialect_id "$target"), written by the issuer for it." ""
|
||||
exit 0
|
||||
fi
|
||||
id="$(dialect_id "$target")"
|
||||
created="$(sed -n "s/^ createdAt: '\(.*\)',$/\1/p" "$target")"
|
||||
left=""
|
||||
if [ -n "$id" ] && [ "$id" != 0 ] && made="$(date -u -d "$created" +%s 2>/dev/null)"; then
|
||||
left=$(( (made + 180 * 86400 - $(date -u +%s)) / 86400 ))
|
||||
fi
|
||||
if [ -n "$left" ] && [ "$left" -ge 90 ]; then
|
||||
report "$VERSION ships without a dialect of its own and registers in dialect $id from $created, which the issuer takes for new installations for $left more days at least. Its operator can write one by hand for the next patch." "::warning::"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$id" = 0 ]; then
|
||||
what="the original registration, which the issuer accepts only until the end of its transition period"
|
||||
elif [ -n "$left" ]; then
|
||||
what="dialect $id from $created, which has $left days left"
|
||||
else
|
||||
what="a dialect whose id or date cannot be read from $target"
|
||||
fi
|
||||
if [ "$ALLOW_STALE" = true ]; then
|
||||
report "$VERSION ships without a dialect of its own and registers in $what, as allow_stale_dialect asked." "::warning::"
|
||||
exit 0
|
||||
fi
|
||||
report "$VERSION got no dialect of its own and would register in $what. Nothing was committed or pushed. Make sure the issuer runs with its dialect seed and release token and that TREK_DIALECT_TOKEN is set, then run the release again, or tick allow_stale_dialect to ship anyway." "::error::"
|
||||
exit 1
|
||||
|
||||
- name: Update the version, commit, tag and push
|
||||
id: commit
|
||||
env:
|
||||
NEW_VERSION: ${{ needs.version.outputs.version }}
|
||||
run: |
|
||||
set -eu
|
||||
echo "VERSION=$NEW_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "$STABLE → $NEW_VERSION ($BUMP)"
|
||||
|
||||
# Update all workspace + root package.json files and the root lockfile in one shot
|
||||
npm version "$NEW_VERSION" --workspaces --include-workspace-root --no-git-tag-version
|
||||
sed -i "s/^version: .*/version: $NEW_VERSION/" charts/trek/Chart.yaml
|
||||
sed -i "s/^appVersion: .*/appVersion: \"$NEW_VERSION\"/" charts/trek/Chart.yaml
|
||||
|
||||
# Commit and tag. The push fast-forwards main from the commit ci-ok
|
||||
# was checked on, so it fails rather than release past anything that
|
||||
# landed on main in the meantime.
|
||||
# Commit and tag
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add package.json package-lock.json server/package.json client/package.json shared/package.json \
|
||||
charts/trek/Chart.yaml server/src/nest/service-identity/registration-dialect.ts
|
||||
git add package.json package-lock.json server/package.json client/package.json shared/package.json charts/trek/Chart.yaml
|
||||
git commit -m "chore: bump version to $NEW_VERSION [skip ci]"
|
||||
git tag -a "v$NEW_VERSION" -m "v$NEW_VERSION"
|
||||
git push origin HEAD:main --follow-tags
|
||||
|
||||
# build, merge and release-helm check out exactly this commit.
|
||||
echo "SHA=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
git push origin main --follow-tags
|
||||
|
||||
build:
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 120
|
||||
needs: [version, version-bump]
|
||||
# version-bump may run after a failed dialect job; that alone must not skip what follows it.
|
||||
if: ${{ !cancelled() && needs.version-bump.result == 'success' }}
|
||||
needs: version-bump
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-24.04
|
||||
runner: ubuntu-latest
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
steps:
|
||||
- name: Prepare platform tag-safe name
|
||||
env:
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
run: echo "PLATFORM_PAIR=${PLATFORM//\//-}" >> "$GITHUB_ENV"
|
||||
run: echo "PLATFORM_PAIR=$(echo ${{ matrix.platform }} | sed 's|/|-|g')" >> $GITHUB_ENV
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.version-bump.outputs.sha }}
|
||||
ref: main
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
@@ -355,14 +146,14 @@ jobs:
|
||||
|
||||
- name: Build and push by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,name=mauriceboe/trek,push-by-digest=true,name-canonical=true,push=true
|
||||
no-cache: true
|
||||
build-args: |
|
||||
APP_VERSION=${{ needs.version.outputs.version }}
|
||||
APP_VERSION=${{ needs.version-bump.outputs.version }}
|
||||
labels: |
|
||||
org.opencontainers.image.revision=${{ steps.meta.outputs.revision }}
|
||||
org.opencontainers.image.created=${{ steps.meta.outputs.created }}
|
||||
@@ -374,7 +165,7 @@ jobs:
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
|
||||
- name: Upload digest artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
path: /tmp/digests/*
|
||||
@@ -382,26 +173,24 @@ jobs:
|
||||
retention-days: 1
|
||||
|
||||
merge:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
needs: [version, version-bump, build]
|
||||
if: ${{ !cancelled() && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
needs: [version-bump, build]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.version-bump.outputs.sha }}
|
||||
ref: main
|
||||
|
||||
- name: Download build digests
|
||||
uses: actions/download-artifact@v7
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: /tmp/digests
|
||||
pattern: digests-*
|
||||
# Deliberately NOT merged: the per-platform folder names are what lets
|
||||
# the manifest below be assembled in a fixed order.
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
@@ -410,12 +199,8 @@ jobs:
|
||||
working-directory: /tmp/digests
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
VERSION="${{ needs.version-bump.outputs.version }}"
|
||||
MAJOR_TAG="$(echo "$VERSION" | cut -d. -f1)"
|
||||
# :MAJOR.MINOR takes the patches of one minor line and nothing else,
|
||||
# the conservative pin for an install that wants to wait out a
|
||||
# release that migrates.
|
||||
MINOR_TAG="$(echo "$VERSION" | cut -d. -f1-2)"
|
||||
# amd64 first, always. This used to be a glob over hash-named files, so
|
||||
# the order changed from one release to the next: 3.4.1 listed amd64
|
||||
# first and 4.0.0 listed arm64 first. Clients that read the first entry
|
||||
@@ -439,7 +224,6 @@ jobs:
|
||||
--annotation "index:org.opencontainers.image.licenses=AGPL-3.0-only" \
|
||||
-t "mauriceboe/trek:latest" \
|
||||
-t "mauriceboe/trek:$MAJOR_TAG" \
|
||||
-t "mauriceboe/trek:$MINOR_TAG" \
|
||||
-t "mauriceboe/trek:$VERSION" \
|
||||
"${digests[@]}"
|
||||
|
||||
@@ -447,18 +231,16 @@ jobs:
|
||||
run: docker buildx imagetools inspect mauriceboe/trek:latest
|
||||
|
||||
release-helm:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-latest
|
||||
needs: version-bump
|
||||
if: ${{ !cancelled() && needs.version-bump.result == 'success' }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.version-bump.outputs.sha }}
|
||||
ref: main
|
||||
|
||||
- name: Publish Helm chart
|
||||
uses: stefanprodan/helm-gh-pages@0ad2bb377311d61ac04ad9eb6f252fb68e207260 # v1.7.0
|
||||
uses: stefanprodan/helm-gh-pages@v1.7.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
charts_dir: charts
|
||||
|
||||
@@ -7,8 +7,7 @@ on:
|
||||
jobs:
|
||||
check-target:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
issues: write
|
||||
@@ -16,7 +15,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Flag or clear wrong base branch
|
||||
uses: actions/github-script@v9
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const base = context.payload.pull_request.base.ref;
|
||||
@@ -69,12 +68,12 @@ jobs:
|
||||
return;
|
||||
}
|
||||
|
||||
// Dependabot's security updates cannot be pointed at dev. `target-branch`
|
||||
// in .github/dependabot.yml applies to version updates only; security
|
||||
// updates always open against the default branch. Labelling them meant
|
||||
// close-stale-wrong-branch shut them 24 hours later, which is how 13 of
|
||||
// them died. Retarget instead: a bot cannot click "Edit" the way the
|
||||
// comment below asks a human to.
|
||||
// Dependabot cannot be pointed at dev. `target-branch` in dependabot.yml
|
||||
// applies to version updates only; security updates always open against
|
||||
// the default branch, and security updates are all this repository gets
|
||||
// (there is no dependabot.yml). Labelling them meant close-stale-wrong-branch
|
||||
// shut them 24 hours later, which is how 13 of them died. Retarget instead:
|
||||
// a bot cannot click "Edit" the way the comment below asks a human to.
|
||||
if (context.payload.pull_request.user.login === 'dependabot[bot]') {
|
||||
try {
|
||||
await github.rest.pulls.update({
|
||||
|
||||
@@ -9,34 +9,29 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
node-version: '24'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Run lint & format check
|
||||
# Both are check-only: lint used to run eslint --fix, which rewrote the
|
||||
# files before format:check looked at them, so neither could fail on
|
||||
# formatting. lint:format holds every file outside
|
||||
# scripts/format-baseline.json to Prettier; the list only shrinks.
|
||||
id: checks
|
||||
continue-on-error: true
|
||||
run: |
|
||||
cd shared
|
||||
npm run lint
|
||||
npm run lint:format
|
||||
npm run format:check
|
||||
|
||||
- name: Comment on PR if checks failed
|
||||
if: steps.checks.outcome == 'failure'
|
||||
uses: actions/github-script@v9
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
await github.rest.issues.createComment({
|
||||
@@ -50,9 +45,8 @@ jobs:
|
||||
'',
|
||||
'```bash',
|
||||
'cd shared',
|
||||
'npm run lint:fix',
|
||||
'npx prettier --write <file> # each file lint:format names',
|
||||
'npm run lint:format -- --update # when a listed file is formatted now',
|
||||
'npm run lint',
|
||||
'npm run format',
|
||||
'```',
|
||||
'',
|
||||
'Then commit and push the changes.',
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
name: Native apps release
|
||||
|
||||
# Builds the signed store builds of the iOS and Android apps and uploads them:
|
||||
# the Android App Bundle to a Google Play testing track, the iOS archive to
|
||||
# App Store Connect (TestFlight). Promotion to production stays a manual step
|
||||
# in both consoles.
|
||||
#
|
||||
# Runs only in liketrek/TREK, only by hand or on a version tag, and only after a
|
||||
# required reviewer approves the `store` environment, which holds every secret
|
||||
# (see wiki/Native-Apps.md for the list). Pull requests never reach it.
|
||||
#
|
||||
# Both stores get the same numbers: the version from client/package.json
|
||||
# without a prerelease suffix, and a build number that only grows. A prerelease
|
||||
# reuses its X.Y.Z with a higher build number and belongs on the internal track
|
||||
# and in TestFlight only.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
track:
|
||||
description: Google Play track
|
||||
type: choice
|
||||
options: [internal, alpha, beta]
|
||||
default: internal
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: native-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
android:
|
||||
# Gated on a repository variable so the release can ship iOS alone while the
|
||||
# Google Play account and its signing secrets are not yet in place. Set the
|
||||
# repository variable NATIVE_RELEASE_ANDROID to 1 to turn the Android half on.
|
||||
if: github.repository == 'liketrek/TREK' && vars.NATIVE_RELEASE_ANDROID == '1'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
environment: store
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 21
|
||||
cache: gradle
|
||||
|
||||
- name: Version and build number
|
||||
id: version
|
||||
run: |
|
||||
echo "version=$(node -p "require('./client/package.json').version.split('-')[0]")" >> "$GITHUB_OUTPUT"
|
||||
echo "build=$((GITHUB_RUN_NUMBER + 1000))" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install
|
||||
run: npm ci --workspace=shared --workspace=client
|
||||
|
||||
- name: Build shared
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Build the address screen and sync it into the shell
|
||||
working-directory: client
|
||||
run: npm run cap:sync -- android
|
||||
|
||||
- name: Upload key
|
||||
env:
|
||||
KEYSTORE_B64: ${{ secrets.ANDROID_UPLOAD_KEYSTORE_B64 }}
|
||||
run: printf '%s' "$KEYSTORE_B64" | base64 -d > "$RUNNER_TEMP/upload.jks"
|
||||
|
||||
- name: Build the signed App Bundle
|
||||
working-directory: client/android
|
||||
env:
|
||||
ORG_GRADLE_PROJECT_trekKeystorePassword: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ORG_GRADLE_PROJECT_trekKeyAlias: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ORG_GRADLE_PROJECT_trekKeyPassword: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
run: >-
|
||||
./gradlew bundleRelease --no-daemon
|
||||
-PtrekVersionName=${{ steps.version.outputs.version }}
|
||||
-PtrekVersionCode=${{ steps.version.outputs.build }}
|
||||
-PtrekKeystore="$RUNNER_TEMP/upload.jks"
|
||||
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: trek-android-${{ steps.version.outputs.version }}-${{ steps.version.outputs.build }}
|
||||
path: client/android/app/build/outputs/bundle/release/app-release.aab
|
||||
retention-days: 30
|
||||
|
||||
# Play only accepts API uploads once one bundle was uploaded by hand
|
||||
# (wiki/Native-Apps.md). `draft` until the app has left draft in the console.
|
||||
- name: Upload to Google Play
|
||||
uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1.1.5
|
||||
with:
|
||||
serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||
packageName: com.liketrek.trek
|
||||
releaseFiles: client/android/app/build/outputs/bundle/release/app-release.aab
|
||||
track: ${{ inputs.track || 'internal' }}
|
||||
status: draft
|
||||
|
||||
- name: Remove the upload key
|
||||
if: always()
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks"
|
||||
|
||||
ios:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 60
|
||||
environment: store
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
# App Store uploads must be built with Xcode 26; the image's default is older.
|
||||
- name: Select Xcode 26
|
||||
run: |
|
||||
XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1)
|
||||
test -n "$XCODE"
|
||||
sudo xcode-select -s "$XCODE"
|
||||
xcodebuild -version
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Version and build number
|
||||
id: version
|
||||
run: |
|
||||
echo "version=$(node -p "require('./client/package.json').version.split('-')[0]")" >> "$GITHUB_OUTPUT"
|
||||
echo "build=$((GITHUB_RUN_NUMBER + 1000))" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install
|
||||
run: npm ci --workspace=shared --workspace=client
|
||||
|
||||
- name: Build shared
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Build the address screen and sync it into the shell
|
||||
working-directory: client
|
||||
run: npm run cap:sync -- ios
|
||||
|
||||
- name: App Store Connect API key
|
||||
env:
|
||||
ASC_KEY_P8_B64: ${{ secrets.ASC_KEY_P8_B64 }}
|
||||
run: printf '%s' "$ASC_KEY_P8_B64" | base64 -d > "$RUNNER_TEMP/AuthKey.p8"
|
||||
|
||||
- name: Distribution certificate
|
||||
env:
|
||||
APPLE_DIST_CERT_P12_B64: ${{ secrets.APPLE_DIST_CERT_P12_B64 }}
|
||||
run: printf '%s' "$APPLE_DIST_CERT_P12_B64" | base64 -d > "$RUNNER_TEMP/dist.p12"
|
||||
|
||||
# Signs for distribution and uploads to TestFlight. Automatic signing cannot
|
||||
# run on a device-less CI runner (it signs for development and then needs a
|
||||
# development profile, which needs a registered device), so client/fastlane/Fastfile
|
||||
# imports the stored distribution certificate and creates the App Store profile
|
||||
# through the API key.
|
||||
# The tag's message, past its subject line, is what testers read under
|
||||
# "What to Test": one short line per change worth trying.
|
||||
- name: TestFlight notes from the tag
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
git fetch --force --depth=1 origin "+${GITHUB_REF}:${GITHUB_REF}"
|
||||
{
|
||||
echo 'TESTFLIGHT_NOTES<<TREK_NOTES_END'
|
||||
# A signed tag carries its signature at the end of the message.
|
||||
git for-each-ref "$GITHUB_REF" --format='%(contents:body)' | sed '/-----BEGIN .*SIGNATURE-----/,$d'
|
||||
echo 'TREK_NOTES_END'
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build and upload to TestFlight
|
||||
working-directory: client
|
||||
env:
|
||||
ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }}
|
||||
ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }}
|
||||
ASC_KEY_PATH: ${{ runner.temp }}/AuthKey.p8
|
||||
CERT_P12_PATH: ${{ runner.temp }}/dist.p12
|
||||
CERT_P12_PASSWORD: ${{ secrets.APPLE_DIST_CERT_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
MARKETING_VERSION: ${{ steps.version.outputs.version }}
|
||||
CURRENT_PROJECT_VERSION: ${{ steps.version.outputs.build }}
|
||||
FASTLANE_SKIP_UPDATE_CHECK: '1'
|
||||
FASTLANE_HIDE_CHANGELOG: '1'
|
||||
run: fastlane ios beta
|
||||
|
||||
- name: Remove secrets
|
||||
if: always()
|
||||
run: rm -f "$RUNNER_TEMP/AuthKey.p8" "$RUNNER_TEMP/dist.p12"
|
||||
@@ -1,161 +0,0 @@
|
||||
name: Native apps
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Builds the iOS and Android shells whenever they, their address screen or the
|
||||
# Capacitor plugins change. Nobody on the team has to own a Mac for the Swift
|
||||
# side to be compiled on every change, and every run leaves a debug APK to
|
||||
# install on a phone.
|
||||
#
|
||||
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
|
||||
# not get, and belong in a release workflow of their own.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'client/android/**'
|
||||
- 'client/ios/**'
|
||||
- 'client/native-shell/**'
|
||||
- 'client/src/native/trekShell.ts'
|
||||
- 'client/src/native/serverAddress.ts'
|
||||
- 'client/capacitor.config.ts'
|
||||
- 'client/vite.native.config.js'
|
||||
- 'client/scripts/check-store-metadata.mjs'
|
||||
- 'client/fastlane/**'
|
||||
- 'client/package.json'
|
||||
- 'package-lock.json'
|
||||
- 'shared/src/i18n/*/native.ts'
|
||||
- '.github/workflows/native.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: native-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# The store texts fit their limits and every listing image has its size and
|
||||
# no alpha channel (client/fastlane/README.md). Plain Node, no install.
|
||||
metadata:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
- name: Check the store listings
|
||||
run: node client/scripts/check-store-metadata.mjs
|
||||
|
||||
android:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 21
|
||||
cache: gradle
|
||||
|
||||
- name: Install
|
||||
run: npm ci --workspace=shared --workspace=client
|
||||
|
||||
- name: Build shared
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Build the address screen and sync it into the shells
|
||||
working-directory: client
|
||||
run: npm run cap:sync -- android
|
||||
|
||||
# The release build runs R8 with the keep rules in proguard-rules.pro, so a
|
||||
# rule that goes missing fails here rather than in the store build. It is
|
||||
# unsigned: the upload key only exists in native-release.yml.
|
||||
- name: Assemble debug and release APKs
|
||||
working-directory: client/android
|
||||
run: ./gradlew assembleDebug assembleRelease lintDebug testDebugUnitTest --no-daemon
|
||||
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: trek-android-debug
|
||||
path: client/android/app/build/outputs/apk/debug/app-debug.apk
|
||||
retention-days: 14
|
||||
|
||||
ios:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
# App Store uploads must be built with Xcode 26; the image's default is older.
|
||||
- name: Select Xcode 26
|
||||
run: |
|
||||
XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1)
|
||||
test -n "$XCODE"
|
||||
sudo xcode-select -s "$XCODE"
|
||||
xcodebuild -version
|
||||
|
||||
- name: Check the property lists
|
||||
run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements client/ios/App/TREKWidgets/Info.plist client/ios/App/TREKWidgets/TREKWidgets.entitlements client/ios/App/TREKWidgets/*.lproj/Localizable.strings client/ios/App/ShareExtension/Info.plist client/ios/App/ShareExtension/ShareExtension.entitlements client/ios/App/ShareExtension/*.lproj/Localizable.strings
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install
|
||||
run: npm ci --workspace=shared --workspace=client
|
||||
|
||||
- name: Build shared
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Build the address screen and sync it into the shells
|
||||
working-directory: client
|
||||
run: npm run cap:sync -- ios
|
||||
|
||||
- name: Build for the simulator
|
||||
working-directory: client/ios/App
|
||||
run: |
|
||||
xcodebuild build \
|
||||
-project App.xcodeproj \
|
||||
-scheme App \
|
||||
-configuration Debug \
|
||||
-sdk iphonesimulator \
|
||||
-destination 'generic/platform=iOS Simulator' \
|
||||
CODE_SIGNING_ALLOWED=NO
|
||||
|
||||
# The widgets drawn to PNGs (client/ios/WidgetPreviews): every size, light and
|
||||
# dark, for a trip ahead, a trip under way and none, plus a home screen and
|
||||
# a lock screen of them. Nobody has to install a build to see a widget change.
|
||||
widget-previews:
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Select Xcode 26
|
||||
run: |
|
||||
XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1)
|
||||
test -n "$XCODE"
|
||||
sudo xcode-select -s "$XCODE"
|
||||
|
||||
- name: Render the widgets
|
||||
working-directory: client/ios/WidgetPreviews
|
||||
run: |
|
||||
mkdir -p Sources/WidgetPreviews/Widgets
|
||||
cp ../App/TREKWidgets/WidgetSnapshot.swift ../App/TREKWidgets/TrekStyle.swift ../App/TREKWidgets/TrekFamily.swift ../App/TREKWidgets/WorldGrid.swift \
|
||||
../App/TREKWidgets/*Content.swift Sources/WidgetPreviews/Widgets/
|
||||
swift run -c release WidgetPreviews out "$PWD/../App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png"
|
||||
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: widget-previews
|
||||
path: client/ios/WidgetPreviews/out
|
||||
retention-days: 14
|
||||
@@ -15,18 +15,17 @@ permissions:
|
||||
jobs:
|
||||
publish:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: plugin-sdk
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
# The Node the TREK image runs the plugins on. It has the node:sqlite
|
||||
# the dev-server tests exercise.
|
||||
node-version-file: .nvmrc
|
||||
# 22 matches the TREK server runtime and has node:sqlite, which the
|
||||
# dev-server tests exercise.
|
||||
node-version: 22
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
- run: npm ci
|
||||
- run: npm publish
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
name: Registration dialect
|
||||
|
||||
# Asks the TREK services issuer for the registration dialect of one version and
|
||||
# checks it, for docker.yml (a stable release commits it with the version bump)
|
||||
# and docker-dev.yml (a prerelease only builds it into its image).
|
||||
#
|
||||
# The issuer's answer runs here, in a job that holds no write token and keeps
|
||||
# no git credentials; the token for the issuer is in the environment of the
|
||||
# one step that fetches. The answer is held to what a dialect is
|
||||
# (scripts/ci/check-registration-dialect.mjs), then type-checked and linted
|
||||
# the way TREK's CI would see it once it is on main and dev. Only a module that
|
||||
# passes all of it goes on, as the artifact `registration-dialect`; without
|
||||
# one the caller decides what ships. This workflow never fails its caller.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
version:
|
||||
description: 'The version the dialect is for, X.Y.Z or X.Y.Z-pre.N'
|
||||
type: string
|
||||
required: true
|
||||
ref:
|
||||
description: 'The commit whose checker, types and lint config the dialect is checked with'
|
||||
type: string
|
||||
required: true
|
||||
secrets:
|
||||
TREK_DIALECT_TOKEN:
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
dialect:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
# A failed or timed-out run leaves no artifact, which the caller already
|
||||
# handles; it must not fail the release around it.
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.ref }}
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
|
||||
# The only step that sees the token. The URL is fixed; the answer is
|
||||
# bounded in time and size and goes to a file nothing runs yet.
|
||||
- name: Fetch the dialect from the issuer
|
||||
id: fetch
|
||||
timeout-minutes: 3
|
||||
env:
|
||||
TREK_DIALECT_TOKEN: ${{ secrets.TREK_DIALECT_TOKEN }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
out="$RUNNER_TEMP/registration-dialect.ts"
|
||||
if [ -z "${TREK_DIALECT_TOKEN:-}" ]; then
|
||||
echo "::warning::TREK_DIALECT_TOKEN is not set; the issuer was not asked for a dialect for $VERSION."
|
||||
exit 0
|
||||
fi
|
||||
status=$(curl --silent --show-error --proto '=https' --tlsv1.2 --max-time 30 --retry 2 --retry-delay 5 \
|
||||
--max-filesize 262144 -H "Authorization: Bearer $TREK_DIALECT_TOKEN" -H 'Content-Type: application/json' \
|
||||
--data "{\"version\":\"$VERSION\"}" -o "$out" -w '%{http_code}' https://places.liketrek.com/v1/dialects) \
|
||||
|| status=000
|
||||
if [ "$status" != 200 ] && [ "$status" != 201 ]; then
|
||||
echo "::warning::The issuer handed out no registration dialect for $VERSION (HTTP $status)."
|
||||
rm -f "$out"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$(wc -c < "$out")" -gt 262144 ]; then
|
||||
echo "::warning::The issuer's registration dialect for $VERSION is larger than a dialect."
|
||||
rm -f "$out"
|
||||
exit 0
|
||||
fi
|
||||
echo "file=$out" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# A module that computes for long is refused by the clock as well.
|
||||
- name: Check the dialect
|
||||
id: check
|
||||
if: steps.fetch.outputs.file != ''
|
||||
timeout-minutes: 2
|
||||
env:
|
||||
FILE: ${{ steps.fetch.outputs.file }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
if ! node scripts/ci/check-registration-dialect.mjs "$FILE" "$VERSION"; then
|
||||
echo "::warning::The issuer's registration dialect for $VERSION failed its check."
|
||||
exit 0
|
||||
fi
|
||||
echo "What changes against the dialect in the tree:"
|
||||
git diff --no-index -- server/src/nest/service-identity/registration-dialect.ts "$FILE" || true
|
||||
echo "ok=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install the toolchain
|
||||
if: steps.check.outputs.ok == 'true'
|
||||
timeout-minutes: 8
|
||||
run: |
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run build --workspace=shared
|
||||
|
||||
# The bump commit skips CI, so this is where the module meets the strict
|
||||
# config (lint:strict lets a new file have no strict errors) and ESLint
|
||||
# with --max-warnings 0 (lint:warnings starts a new file at none) before
|
||||
# it lands on main.
|
||||
- name: Type-check and lint the dialect
|
||||
id: types
|
||||
if: steps.check.outputs.ok == 'true'
|
||||
timeout-minutes: 5
|
||||
working-directory: server
|
||||
env:
|
||||
FILE: ${{ steps.fetch.outputs.file }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
cp "$FILE" src/nest/service-identity/registration-dialect.ts
|
||||
# TypeScript 6 includes no @types by default and the dialect imports nothing
|
||||
# from node, so checked on its own it would not know Buffer: name node here.
|
||||
printf '%s\n' '{"extends": "./tsconfig.strict.json", "compilerOptions": {"types": ["node"]}, "include": [],' \
|
||||
'"files": ["src/nest/service-identity/registration-dialect.ts"]}' > tsconfig.dialect-check.json
|
||||
if ! npx tsc -p tsconfig.dialect-check.json --noEmit --pretty false; then
|
||||
echo "::warning::The issuer's registration dialect for $VERSION does not type-check under the strict config."
|
||||
exit 0
|
||||
fi
|
||||
if ! npx eslint --max-warnings 0 src/nest/service-identity/registration-dialect.ts; then
|
||||
echo "::warning::The issuer's registration dialect for $VERSION does not pass ESLint."
|
||||
exit 0
|
||||
fi
|
||||
echo "ok=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Hand the dialect on
|
||||
if: steps.types.outputs.ok == 'true'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: registration-dialect
|
||||
path: ${{ steps.fetch.outputs.file }}
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
@@ -1,27 +1,12 @@
|
||||
name: Security Scan
|
||||
|
||||
# Neither job is a required check. What they report depends on the advisory
|
||||
# databases as much as on the change: a CVE published overnight would turn
|
||||
# every open PR red at once, including the ones that cannot fix it. The
|
||||
# security floors that hold the fixes live in the root package.json's
|
||||
# overrides, which a regenerated lockfile keeps.
|
||||
#
|
||||
# - npm-audit reads the lockfile only, so it runs in seconds on every PR
|
||||
# and push into dev and main. It audits what the image installs (the
|
||||
# server and shared workspaces without dev dependencies) and the
|
||||
# standalone plugin-sdk.
|
||||
# - scout scans the built image, base image packages included. It needs
|
||||
# the Docker Hub login, so it runs on PRs and pushes into main only and
|
||||
# skips fork PRs. Whether the image builds at all is test.yml's
|
||||
# docker-image job, which a red scan cannot hide.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, dev]
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main, dev]
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
@@ -29,57 +14,29 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
npm-audit:
|
||||
name: npm audit
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
# The client's dependencies end up in a browser bundle, not in the
|
||||
# image, and are audited by hand until maplibre-gl's fix (a major) lands.
|
||||
- name: Audit the image's runtime dependencies
|
||||
run: npm audit --package-lock-only --omit=dev --audit-level=high --workspace=server --workspace=shared
|
||||
|
||||
- name: Audit trek-plugin-sdk
|
||||
working-directory: plugin-sdk
|
||||
run: npm audit --package-lock-only --omit=dev --audit-level=high
|
||||
|
||||
scout:
|
||||
# Docker Hub secrets are not exposed to pull requests from forks, so the
|
||||
# Scout login can never succeed there.
|
||||
if: >-
|
||||
github.repository == 'liketrek/TREK'
|
||||
&& github.event.pull_request.head.repo.fork != true
|
||||
&& (github.base_ref == 'main' || github.ref == 'refs/heads/main')
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
if: github.repository == 'liketrek/TREK' && github.event.pull_request.head.repo.fork != true
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
- uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: false
|
||||
load: true
|
||||
tags: trek:scan
|
||||
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- uses: docker/scout-action@e7e2a72bf1485d10a58f30696b6c513b261ce4fa # v1.29.0
|
||||
- uses: docker/scout-action@v1
|
||||
with:
|
||||
command: cves
|
||||
image: trek:scan
|
||||
|
||||
@@ -18,11 +18,10 @@ concurrency:
|
||||
jobs:
|
||||
deploy:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Publish to GitHub wiki
|
||||
uses: Andrew-Chen-Wang/github-wiki-action@1bbb4280446f9630e8e21a18012cbacf3b0f992e # v5.0.6
|
||||
uses: Andrew-Chen-Wang/github-wiki-action@v5
|
||||
with:
|
||||
strategy: clone
|
||||
|
||||
@@ -4,7 +4,6 @@ node_modules/
|
||||
# Build output
|
||||
client/dist/
|
||||
server/dist/
|
||||
server/VERSION
|
||||
shared/dist/
|
||||
server/public/*
|
||||
!server/public/.gitkeep
|
||||
@@ -55,8 +54,6 @@ coverage
|
||||
coverage-*/
|
||||
*.lcov
|
||||
.nyc_output
|
||||
# Blob reports of a sharded vitest run (test.yml)
|
||||
.vitest-reports
|
||||
|
||||
# Cache
|
||||
.npm
|
||||
|
||||
@@ -20,9 +20,8 @@ Run from the repo root unless noted. **Use `npm run ... --workspace=<pkg>`, not
|
||||
```bash
|
||||
npm run dev # build shared, then watch shared + server + client concurrently
|
||||
npm run build # build shared → server → client (order matters)
|
||||
npm run lint # lint all three workspaces, check-only (npm run lint:fix applies the fixes in shared and server)
|
||||
npm run lint # lint all three workspaces (server and shared run eslint --fix and rewrite files; client is check-only)
|
||||
npm run format # prettier --write all three
|
||||
npm run lint:knip # knip over client/server/shared (knip.jsonc): unused files, exports, types, deps may only shrink against scripts/ci/knip-baseline.json (CI gate; --update lowers it)
|
||||
```
|
||||
|
||||
Tests:
|
||||
@@ -33,34 +32,9 @@ npm run test --workspace=server # vitest run (server); also t
|
||||
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
|
||||
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
|
||||
cd client && npm run test # client vitest run
|
||||
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
|
||||
cd client && npm run e2e # Playwright (local only)
|
||||
cd client && npm run lint:pages # enforce the Page pattern (CI gate)
|
||||
cd client && npm run lint:rtl # physical left/right sides may only shrink per file (CI gate)
|
||||
cd client && npm run lint:dup # lines in copied code may only shrink per file, at SonarCloud's thresholds (CI gate)
|
||||
cd client && npm run lint:pairs # desktop and phone views of a feature import its shared hook; every phone screen is listed (CI gate)
|
||||
cd client && npm run lint:size # no source file past 1000 lines, longer ones only shrink (CI gate; server has the same)
|
||||
cd client && npm run lint:strict # strictNullChecks + noImplicitAny errors may only shrink per file; new files start at zero (CI gate)
|
||||
cd client && npm run lint:warnings # eslint (typed) errors fail, warnings per rule may only shrink, new rules start frozen (CI gate)
|
||||
cd server && npm run lint:warnings # the same for the server, against server/scripts/eslint-baseline.json (CI gate)
|
||||
cd server && npm run lint:format # Prettier outside the baseline list (CI gate; shared has the same in lint-prettier.yml)
|
||||
cd server && npm run lint:strict # strict type errors per file may only shrink, a new file has none (CI gate)
|
||||
cd client && npm run lint:format # Prettier outside the baseline list (CI gate)
|
||||
cd client && npm run lint:layers # components never import pages/ or mobile/ (CI gate)
|
||||
cd client && npm run lint:offline # views may not import src/api/ beyond the baseline (CI gate)
|
||||
cd client && npm run lint:skips # no .only; skipped tests may only shrink (CI gate)
|
||||
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
|
||||
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
|
||||
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
|
||||
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
|
||||
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
|
||||
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
|
||||
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
|
||||
cd server && npm run lint:test-new-service # hand-built services and repositories in tests/ may only shrink (CI gate)
|
||||
cd server && npm run lint:query-api # MikroORM QueryBuilder calls in the repositories may only shrink (CI gate)
|
||||
cd server && npm run lint:mcp-zod # inline zod in the MCP tool files may only shrink; fields derive from @trek/shared (CI gate)
|
||||
cd server && npm run lint:service-http # { error, status } results and their caller-side branches may only shrink; services throw DomainError (CI gate)
|
||||
cd server && npm run lint:response-contracts # route handlers without @ResponseContract may only shrink (CI gate)
|
||||
cd client && npm run theme:lint # styling that bypasses appearance tokens may only shrink per file (CI gate)
|
||||
cd client && npm run theme:lint # flag styling that bypasses appearance tokens (local only)
|
||||
npm run typecheck --workspace=server # tsc --noEmit (also client/shared; server also has typecheck:tests)
|
||||
```
|
||||
|
||||
@@ -78,7 +52,7 @@ npm run i18n:parity --workspace=shared # audit (exit 0)
|
||||
npm run i18n:parity:strict --workspace=shared # CI gate (exit 1 on drift)
|
||||
```
|
||||
|
||||
Dev ports: the server listens on **3001**; the Vite dev server proxies the API, websocket, uploads, MCP and OAuth paths to it (see `client/vite.config.js`). `.nvmrc` pins the Node major the Docker image runs and every CI job reads; `engines` in each package.json states the range that installs (npm only warns outside it). `server/.env.example` is the env-var reference.
|
||||
Dev ports: the server listens on **3001**; the Vite dev server proxies the API, websocket, uploads, MCP and OAuth paths to it (see `client/vite.config.js`). There is no Node version pin — the CI workflows and the Dockerfile define what is tested. `server/.env.example` is the env-var reference.
|
||||
|
||||
## Server invariants
|
||||
|
||||
@@ -88,8 +62,8 @@ Nest owns everything: every domain is a DI module under `server/src/nest/<domain
|
||||
- **`/mcp` bodies are raw by design** — the parser wrappers exempt `/mcp` so the MCP SDK reads the untouched stream; never `@Body()` a `/mcp` route.
|
||||
- **Auth is default-deny**: global guards run as `APP_GUARD`s; public routes opt out with `@Public()`, and a boot-time ratchet (`validate-route-guards.ts`) refuses any public route not on its allow-list.
|
||||
- **Trip-scoped routes** verify trip access (404) and the permission (403) — `@UseGuards(JwtAuthGuard, TripAccessGuard)` + `@RequirePermission('<action>')` per handler — and forward `X-Socket-Id` to the broadcast so the originating client doesn't echo its own change. **Never gate a multipart upload with a guard** (the client sees ECONNRESET instead of 403 — check in the handler).
|
||||
- **DB** (`server/src/db/`): `better-sqlite3`, WAL, FK on. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests** — the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` test builders are gone. Seeding is MikroORM's too (`db/seeders/`), applied at boot from `buildApp()`; the ORM shares the one better-sqlite3 connection (bound in `server/src/db/orm-driver.ts`) rather than opening its own. Queries go through repositories (`server/src/db/repositories/`) and `UnitOfWork` (`server/src/nest/database/unit-of-work.ts`) for transactions — there is no `DatabaseService`. `better-sqlite3` itself is ESLint-restricted to `src/db/` plus a short, named allow-list (`server/eslint.config.mjs`), so a domain reaching for the driver directly fails lint. `NODE_ENV=test` gives each vitest worker an isolated `:memory:` DB.
|
||||
- **Realtime**: `/ws` is a Nest gateway in `server/src/nest/realtime/` — inject `RealtimeService`. Tests observe broadcasts through a `FakeRealtimeService` (`server/tests/helpers/fake-realtime.ts`), never by mocking the transport module.
|
||||
- **DB** (`server/src/db/`): `better-sqlite3`, WAL, FK on. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests** — the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` test builders are gone. Seeding is MikroORM's too (`db/seeders/`), applied at boot from `buildApp()`; the ORM shares the one better-sqlite3 connection (bound in `db/orm-driver.ts`) rather than opening its own. Queries go through repositories (`server/src/db/repositories/`) and `UnitOfWork` (`server/src/nest/database/unit-of-work.ts`) for transactions — there is no `DatabaseService`. `better-sqlite3` itself is ESLint-restricted to `src/db/` plus a short, named allow-list (`server/eslint.config.mjs`), so a domain reaching for the driver directly fails lint. `NODE_ENV=test` gives each vitest worker an isolated `:memory:` DB.
|
||||
- **Realtime**: `/ws` is a Nest gateway in `server/src/nest/realtime/` — inject `RealtimeService`; `server/src/websocket.ts` is a legacy re-export stub.
|
||||
- **MCP**: tools are declared in `<domain>.mcp.ts` files beside each module, on the `server/src/nest-mcp/` decorator layer. A validation or permission change on a REST route must land in the parallel MCP tool in the same change. See `MCP.md`.
|
||||
- **Addons** are admin-toggleable feature modules keyed by `ADDON_IDS` in `server/src/addons.ts`.
|
||||
- **Plugins** (`server/src/nest/plugins/`): one forked child process per plugin, permission-gated RPC (a handler is registered only if the plugin holds the unlocking permission), install-time manifest/signature/egress/version-range gates. The protocol tables are **generated** into `plugin-sdk/` and `shared/` by `gen:plugin-facts`; `check:plugin-facts` is the CI gate. Author tooling is `plugin-sdk/`; the `trek-plugin-dev` skill covers authoring.
|
||||
@@ -101,16 +75,14 @@ Nest owns everything: every domain is a DI module under `server/src/nest/<domain
|
||||
Offline-first, with a layered data flow. A Page never owns state directly:
|
||||
|
||||
- **Page pattern** (enforced by `lint:pages`, spec in `client/src/pages/PATTERN.md`): a `*Page.tsx` is a **wiring container** composing a co-located `use<Page>()` hook; it must not call React state/effect/memo hooks itself.
|
||||
- **Data flow**: `store (Zustand, client/src/store/) → repo (client/src/repo/) → api (client/src/api/) | Dexie (client/src/db/offlineDb.ts)`. Writes go through `client/src/sync/mutationQueue.ts`: optimistic Dexie write, then a replay with an `X-Idempotency-Key` header on reconnect. `client/src/store/slices/remoteEventHandler.ts` applies incoming WebSocket events. Components never call the API directly.
|
||||
- **Styling**: semantic Tailwind tokens (`bg-surface*`, `text-content*`, `border-edge*`, `bg-accent*`) or the underlying `var(--token)` variables — never color literals, arbitrary-value color classes or numeric inline `fontSize`, so user-chosen scheme/transparency/text-size keep working. `theme:lint` holds the bypasses per file to a baseline that only shrinks (CI gate); mark intentional exceptions (map/PDF/brand) with a `theme-lint-disable` line comment, which is counted too.
|
||||
- **Reading direction**: Arabic runs the app right to left, so spacing, insets and alignment that follow the text use the logical forms (`ms-`/`me-`/`ps-`/`pe-`/`start-`/`end-`/`text-start`/`border-s`/`rounded-s`, `marginInlineStart`, `insetInlineEnd`, `textAlign: 'start'`). `lint:rtl` counts the physical ones per file against `client/scripts/rtl-baseline.json`, which may only shrink; geometry that is physical on purpose in new code (maps, measured positions, time axes) carries an `rtl-lint-disable` comment.
|
||||
- **Data flow**: `store (Zustand, client/src/store/) → repo (client/src/repo/) → api (client/src/api/) | Dexie (client/src/db/offlineDb.ts)`. Writes go through `sync/mutationQueue.ts`: optimistic Dexie write, then a replay with an `X-Idempotency-Key` header on reconnect. `store/slices/remoteEventHandler.ts` applies incoming WebSocket events. Components never call the API directly.
|
||||
- **Styling**: semantic Tailwind tokens (`bg-surface*`, `text-content*`, `border-edge*`, `bg-accent*`) or the underlying `var(--token)` variables — never color literals, arbitrary-value color classes or numeric inline `fontSize`, so user-chosen scheme/transparency/text-size keep working. `theme:lint` flags bypasses; suppress intentional exceptions (map/PDF/brand) with a `theme-lint-disable` line comment.
|
||||
- **PWA**: `vite-plugin-pwa` + Workbox cache tiles, API and uploads; `prebuild` generates icons.
|
||||
|
||||
## Shared contracts & i18n
|
||||
|
||||
- A route is "done" only once its contract lives in `shared/` and both sides import the inferred types. Edit the Zod schema, rebuild shared, then server (validation + DTO types) and client (typed requests) pick it up.
|
||||
- Locale files live in `shared/src/i18n/<locale>/`, one file per domain; `en/` is canonical. When you add or change a key, **add a real translation to every locale** — parity fails CI on missing keys, and an English placeholder is not acceptable in a non-`en` locale.
|
||||
- Count-bearing strings are plural groups: the key holds the general form and `key.one`, `.few` … the forms the language's `Intl.PluralRules` selects. Pass `{ count }` as a number and never choose between two keys with `count === 1`; details in `shared/CLAUDE.md`.
|
||||
|
||||
## Project direction
|
||||
|
||||
@@ -118,7 +90,7 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
|
||||
- **Protect the crown jewels.** The client's offline-first data core (repos + mutation queue + Dexie), the out-of-process plugin sandbox, the Zod contract layer, and the auth primitives are production-grade. Extend them; never route around them or rewrite them in anger.
|
||||
- **No "modern shell over legacy core."** The debt pattern is a modern frame delegating to the old approach underneath (on the client: feature components calling the raw API past the offline core). New code goes all-in on the target architecture; when touching a legacy seam, migrate it rather than adding another wrapper.
|
||||
- **Single source of truth over manual synchronization.** Never add a hand-mirrored copy of state, schema, or contract (server↔Dexie↔Zustand, schema↔SQL, the plugin contract). Derive from one source, or guard the copy with a parity test that cannot silently skip — the server entities are the precedent: `npm run gen:entities`/`check:entities --workspace=server` (`server/scripts/generate-entities.ts`) regenerate them from the live migrated schema instead of hand-editing, and a parity test (PARITY-009) pins entity-vs-DB drift (delete rules, index names) at zero skips. The Kysely table types the repositories query through are generated the same way (`gen:db-types`/`check:db-types`, `server/scripts/generate-db-types.ts`).
|
||||
- **Single source of truth over manual synchronization.** Never add a hand-mirrored copy of state, schema, or contract (server↔Dexie↔Zustand, schema↔SQL, the plugin contract). Derive from one source, or guard the copy with a parity test that cannot silently skip — the server entities are the precedent: `npm run gen:entities`/`check:entities --workspace=server` (`server/scripts/generate-entities.ts`) regenerate them from the live migrated schema instead of hand-editing, and a parity test (PARITY-009) pins entity-vs-DB drift (delete rules, index names) at zero skips.
|
||||
- **DI over global mutable module state.** New server code injects its dependencies; new client code avoids `window`-global buses and mutable module state.
|
||||
- **Use the runtime's native idioms.** Prefer React 19 features (`useOptimistic`, Actions, `use()`/Suspense) and Nest subsystems (providers, pipes, guards, `@nestjs/schedule`) over hand-rolled equivalents.
|
||||
- **Fail closed, gates stay on.** Security switches default to safe; misconfiguration must refuse, not degrade. Never lower a quality gate to land a change — no new `any`, no new `eslint-disable`, no downgrading rules to `warn`, no lowered coverage thresholds.
|
||||
@@ -134,16 +106,7 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
|
||||
## Quality gates in CI
|
||||
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in server-lint-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
|
||||
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
|
||||
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
|
||||
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
|
||||
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
|
||||
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
|
||||
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
|
||||
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`), `lint:check`, `lint:pages`, `check:plugin-facts`, `i18n:parity:strict`, the S3 contract suite, coverage for all four packages, then a SonarCloud scan. `lint-prettier.yml` additionally runs `lint` + `format:check` on `shared/`. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: `theme:lint`, Playwright, `check:gl-split` — run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
|
||||
**SonarCloud** (project `liketrek_TREK`, the built-in Sonar way gate; the run takes 20–25 min, so get it right before pushing) measures **new code only** on a PR; any failing condition blocks it:
|
||||
|
||||
@@ -154,7 +117,7 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
| Security / reliability / maintainability rating | A |
|
||||
| Security hotspots reviewed | 100% |
|
||||
|
||||
- **Duplication is the one that bites.** Desktop and phone shells (`client/src/components/<X>` ↔ `client/src/mobile/screens/.../M<X>`) are deliberate mirrors of each other's markup; their logic lives in one shared hook per feature. Every line added identically to both counts against the 3% budget, so a feature touching both shells fails on its own. Put the logic in ONE hook/module (precedents: `useInstanceSettings`, `useRangeBypass` under `client/src/components/Admin/`) and leave only markup in each shell. `lint:dup` finds the same copies in `client/src` before the push and holds every file to `client/scripts/dup-baseline.json`; `lint:pairs` holds each pair in `client/scripts/feature-pairs.json` to its shared hook and makes every new phone screen either join a pair or say why it has no twin. Locale files are excluded from duplication, so i18n additions are free.
|
||||
- **Duplication is the one that bites.** Desktop and phone shells (`client/src/components/<X>` ↔ `client/src/mobile/screens/.../M<X>`) are deliberate mirrors that are already heavily duplicated. Every line added identically to both counts against the 3% budget, so a feature touching both shells fails on its own. Put the logic in ONE hook/module (precedents: `useInstanceSettings`, `useRangeBypass` under `client/src/components/Admin/`) and leave only markup in each shell. Locale files are excluded from duplication, so i18n additions are free.
|
||||
- **Coverage is per new line across all four packages.** A new file without tests drags the PR under 80%. Files in `sonar.coverage.exclusions` don't count either way.
|
||||
- **Ratings are about new issues.** One new bug drops reliability; one new vulnerability drops security. Don't introduce hotspot patterns (`Math.random` in anything security-adjacent, `child_process` through PATH, backtracking regexes, secret-looking strings). Path-wide suppressions live only in `sonar-project.properties` with a written justification; one-off findings are resolved on SonarCloud, never with an inline `// NOSONAR`.
|
||||
- **Check it yourself.** The `sonarqube` MCP is connected: `list_pull_requests` → `get_project_quality_gate_status` shows each condition's value; `search_duplicated_files` + `get_duplications` show what tripped duplication; `search_sonar_issues_in_projects` lists new issues. Test files are excluded from analysis — when duplication fires, the source is the problem.
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
# Rebuild gosu with a current Go toolchain so the runtime image ships no stale
|
||||
# Go stdlib (Debian's apt gosu is built with an old Go that trips CVE scanners).
|
||||
# The binary and its runtime behaviour are identical to the apt package.
|
||||
FROM golang:1.26-alpine AS gosu-build
|
||||
# Pinned to the commit of gosu's 1.19 tag: @latest made every build pick up whatever
|
||||
# was pushed last, and the tag itself is not a semver version go install accepts.
|
||||
RUN CGO_ENABLED=0 GOBIN=/out go install github.com/tianon/gosu@6456aaa0f3c854d199d0f037f068eb97515b7513
|
||||
FROM golang:1.25-alpine AS gosu-build
|
||||
RUN CGO_ENABLED=0 GOBIN=/out go install github.com/tianon/gosu@latest
|
||||
|
||||
# ── Stage 1: shared ──────────────────────────────────────────────────────────
|
||||
FROM node:24-alpine AS shared-builder
|
||||
@@ -22,12 +20,10 @@ WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
COPY shared/package.json ./shared/
|
||||
COPY client/package.json ./client/
|
||||
COPY client/scripts/patch-maplibre.mjs ./client/scripts/
|
||||
RUN npm ci --workspace=client
|
||||
COPY --from=shared-builder /app/shared/dist ./shared/dist
|
||||
COPY client/ ./client/
|
||||
# A prerelease build does not bump client/package.json, so the bundle takes its
|
||||
# version from the same build argument the server's VERSION file comes from.
|
||||
ARG APP_VERSION=dev
|
||||
RUN npm run build --workspace=client
|
||||
|
||||
# ── Stage 3: server ──────────────────────────────────────────────────────────
|
||||
@@ -41,9 +37,7 @@ COPY server/package.json ./server/
|
||||
RUN npm ci --workspace=server --ignore-scripts
|
||||
COPY --from=shared-builder /app/shared/dist ./shared/dist
|
||||
COPY server/ ./server/
|
||||
# tsc needs more than the 2 GB heap Node picks on a host with about 12 GB of RAM;
|
||||
# on a bigger build machine the default is larger, so only small hosts failed.
|
||||
RUN NODE_OPTIONS=--max-old-space-size=4096 npm run build --workspace=server
|
||||
RUN npm run build --workspace=server
|
||||
|
||||
# ── Stage 4: production runtime ──────────────────────────────────────────────
|
||||
FROM node:24-trixie-slim
|
||||
@@ -74,7 +68,7 @@ RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
|
||||
libkitinerary-bin libsqlite3-0 && \
|
||||
npm ci --workspace=server --omit=dev --ignore-scripts && \
|
||||
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
|
||||
ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor; \
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
chown -R node:node /app
|
||||
|
||||
@@ -91,8 +85,7 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
|
||||
|
||||
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
|
||||
# Runtime data assets read from server/assets at runtime: airports.json (flight
|
||||
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map). The build
|
||||
# transport search) and atlas/*.geojson.gz (Atlas country/region map). The build
|
||||
# only emits dist, so these must be copied explicitly or the features silently
|
||||
# degrade to empty in the image.
|
||||
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
|
||||
@@ -127,13 +120,8 @@ RUN mkdir -p /app/data/logs /app/uploads/files /app/uploads/covers /app/uploads/
|
||||
ENV NODE_ENV=production
|
||||
ENV NODE_USE_ENV_PROXY=1
|
||||
ENV PORT=3000
|
||||
# The version goes into a file, not into ENV. A container keeps its environment
|
||||
# when it is recreated on a newer image (Portainer's recreate, a copied run
|
||||
# config), so an APP_VERSION env var would keep announcing the old release and
|
||||
# the clients would never pick up the new bundle. The server reads this file
|
||||
# first (server/src/app-config/image-version.ts).
|
||||
ARG APP_VERSION=dev
|
||||
RUN if [ "$APP_VERSION" != "dev" ]; then printf '%s\n' "$APP_VERSION" > /app/server/VERSION; fi
|
||||
ENV APP_VERSION=${APP_VERSION}
|
||||
|
||||
# OCI metadata: Renovate, Watchtower and the registries read the source label to
|
||||
# link an image update to its release notes (#1498). The release workflows add
|
||||
@@ -149,7 +137,7 @@ LABEL org.opencontainers.image.title="TREK" \
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD wget -qO- "http://localhost:${PORT:-3000}/api/health" || exit 1
|
||||
CMD wget -qO- http://localhost:3000/api/health || exit 1
|
||||
|
||||
# Start-up lives in a script, not an inline `sh -c` string: container management
|
||||
# UIs re-tokenise Config.Cmd when you edit a container in place, and a command
|
||||
|
||||
@@ -5,9 +5,8 @@ TREK bundles and uses third-party data that requires attribution.
|
||||
## geoBoundaries — country & sub-national boundaries
|
||||
|
||||
The Atlas map's administrative boundaries (admin-0 countries and admin-1
|
||||
provinces/counties), shipped at `server/assets/atlas/admin0.geojson.gz`,
|
||||
`server/assets/atlas/admin1.geojson.gz` and `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`
|
||||
(the same regions, one file per country) and generated by
|
||||
provinces/counties), shipped at `server/assets/atlas/admin0.geojson.gz` and
|
||||
`server/assets/atlas/admin1.geojson.gz` and generated by
|
||||
`server/scripts/build-atlas-geo.mjs`, are derived from **geoBoundaries**.
|
||||
|
||||
> Runfola, D. et al. (2020) geoBoundaries: A global database of political
|
||||
@@ -54,54 +53,3 @@ own switch in the admin panel. https://cloud.google.com/maps-platform/terms
|
||||
|
||||
`server/assets/airports.json` is built from **OurAirports**
|
||||
(https://ourairports.com/data/), released into the public domain.
|
||||
|
||||
## Typefaces: Studio books and the app
|
||||
|
||||
Every typeface a book can be set in, and the app's own (Poppins, MuseoModerno,
|
||||
Geist), is self-hosted from the **@fontsource** npm packages, which redistribute
|
||||
the families published on Google Fonts split into subsets by script. The catalogue of book faces is
|
||||
`shared/src/book/book-fonts.data.ts`. Each package carries its licence and the
|
||||
copyright notice of the family's authors in its `LICENSE` file.
|
||||
|
||||
Both licences allow a font to be bundled with software and embedded in a
|
||||
document made with it, so a printed or exported book may carry the faces it is
|
||||
set in. No family is renamed, redrawn or sold on its own. SIL OFL 1.1: https://openfontlicense.org. Apache 2.0:
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
| Family | Package | Licence |
|
||||
|---|---|---|
|
||||
| Abril Fatface | `@fontsource/abril-fatface` | SIL Open Font License 1.1 |
|
||||
| Alfa Slab One | `@fontsource/alfa-slab-one` | SIL Open Font License 1.1 |
|
||||
| Allura | `@fontsource/allura` | SIL Open Font License 1.1 |
|
||||
| Anton | `@fontsource/anton` | SIL Open Font License 1.1 |
|
||||
| Archivo Black | `@fontsource/archivo-black` | SIL Open Font License 1.1 |
|
||||
| Bebas Neue | `@fontsource/bebas-neue` | SIL Open Font License 1.1 |
|
||||
| Big Shoulders Display | `@fontsource/big-shoulders-display` | SIL Open Font License 1.1 |
|
||||
| Bodoni Moda | `@fontsource/bodoni-moda` | SIL Open Font License 1.1 |
|
||||
| Bricolage Grotesque | `@fontsource/bricolage-grotesque` | SIL Open Font License 1.1 |
|
||||
| Caveat | `@fontsource/caveat` | SIL Open Font License 1.1 |
|
||||
| Cormorant Garamond | `@fontsource/cormorant-garamond` | SIL Open Font License 1.1 |
|
||||
| Dancing Script | `@fontsource/dancing-script` | SIL Open Font License 1.1 |
|
||||
| DM Mono | `@fontsource/dm-mono` | SIL Open Font License 1.1 |
|
||||
| DM Serif Display | `@fontsource/dm-serif-display` | SIL Open Font License 1.1 |
|
||||
| EB Garamond | `@fontsource/eb-garamond` | SIL Open Font License 1.1 |
|
||||
| Fraunces | `@fontsource/fraunces` | SIL Open Font License 1.1 |
|
||||
| Great Vibes | `@fontsource/great-vibes` | SIL Open Font License 1.1 |
|
||||
| Homemade Apple | `@fontsource/homemade-apple` | Apache License 2.0 |
|
||||
| Inter | `@fontsource/inter` | SIL Open Font License 1.1 |
|
||||
| Kaushan Script | `@fontsource/kaushan-script` | SIL Open Font License 1.1 |
|
||||
| League Gothic | `@fontsource/league-gothic` | SIL Open Font License 1.1 |
|
||||
| Lora | `@fontsource/lora` | SIL Open Font License 1.1 |
|
||||
| Montserrat | `@fontsource/montserrat` | SIL Open Font License 1.1 |
|
||||
| MuseoModerno | `@fontsource/museomoderno` | SIL Open Font License 1.1 |
|
||||
| Oswald | `@fontsource/oswald` | SIL Open Font License 1.1 |
|
||||
| Pacifico | `@fontsource/pacifico` | SIL Open Font License 1.1 |
|
||||
| Parisienne | `@fontsource/parisienne` | SIL Open Font License 1.1 |
|
||||
| Permanent Marker | `@fontsource/permanent-marker` | Apache License 2.0 |
|
||||
| Playfair Display | `@fontsource/playfair-display` | SIL Open Font License 1.1 |
|
||||
| Poppins | `@fontsource/poppins` | SIL Open Font License 1.1 |
|
||||
| Sacramento | `@fontsource/sacramento` | SIL Open Font License 1.1 |
|
||||
| Satisfy | `@fontsource/satisfy` | Apache License 2.0 |
|
||||
| Shrikhand | `@fontsource/shrikhand` | SIL Open Font License 1.1 |
|
||||
| Yellowtail | `@fontsource/yellowtail` | Apache License 2.0 |
|
||||
| Geist Sans | `@fontsource/geist-sans` | SIL Open Font License 1.1 |
|
||||
|
||||
@@ -6,9 +6,14 @@
|
||||
<img src="docs/logo-trek-dark.svg" alt="TREK" height="96" />
|
||||
</picture>
|
||||
|
||||
### Every part of your trip. One app you own.
|
||||
<br />
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/subtitle-light.png" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="docs/subtitle-dark.png" />
|
||||
<img src="docs/subtitle-dark.png" alt="your trip. your plan." height="28" />
|
||||
</picture>
|
||||
|
||||
TREK has grown from a travel planner into a whole ecosystem for trips: plan together in real time on a live map, build hikes, tours and road trips, keep bookings and shared costs in order, pack, write the journal, lay out the photo book and hand the busy work to the built-in AI. Self-hosted, on the web, on your phone and offline.
|
||||
A self-hosted, real-time collaborative travel planner — with maps, budgets, packing lists, a journal, and AI built in.
|
||||
|
||||
<br />
|
||||
|
||||
@@ -27,23 +32,18 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
|
||||
<a href="https://ko-fi.com/mauriceboe"><img alt="Ko-fi" src="https://img.shields.io/badge/Ko--fi-support-FF5E5B?style=for-the-badge" /></a>
|
||||
|
||||
<a href="https://www.buymeacoffee.com/mauriceboe"><img alt="BMAC" src="https://img.shields.io/badge/BMAC-support-FFDD00?style=for-the-badge" /></a>
|
||||
|
||||
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/License-AGPL_v3-6B7280?style=for-the-badge" /></a>
|
||||
|
||||
<a href="https://github.com/liketrek/TREK/releases"><img alt="Latest Release" src="https://img.shields.io/github/v/release/liketrek/trek?include_prereleases&style=for-the-badge&label=Release&color=6B7280" /></a>
|
||||
|
||||
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/mauriceboe/trek?style=for-the-badge&label=Docker%20pulls&color=6B7280" /></a>
|
||||
|
||||
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a>
|
||||
|
||||
<sub>PUBLIC SERVICES PROUDLY SPONSORED BY</sub><br /><a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="30" /></picture></a>
|
||||
<br />
|
||||
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-AGPL_v3-6B7280?style=flat-square" /></a>
|
||||
<a href="https://github.com/liketrek/TREK/releases"><img alt="Latest Release" src="https://img.shields.io/github/v/release/liketrek/trek?include_prereleases&style=flat-square&color=6B7280" /></a>
|
||||
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/mauriceboe/trek?style=flat-square&color=6B7280" /></a>
|
||||
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=flat-square&color=6B7280" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
<img src="https://github.com/mauriceboe/trek-media/releases/download/readme-assets/TREK2.webp" alt="TREK, a tour of the app" width="100%" />
|
||||
<img src="https://github.com/mauriceboe/trek-media/releases/download/readme-assets/TREK1.webp" alt="TREK, a tour of the app" width="100%" />
|
||||
|
||||
</div>
|
||||
|
||||
@@ -62,7 +62,7 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
|
||||
|
||||
<br />
|
||||
|
||||
Most of what follows is an addon an admin switches on or off. Lists, Costs, Documents, Collab, Tours, Vacay and Atlas ship on; Journey, Collections, MCP, the AI assistant, AI Parsing, Road trip, Dawarich and AirTrail ship off and are marked below.
|
||||
Most of what follows is an addon an admin switches on or off. Lists, Costs, Documents, Collab, Vacay and Atlas ship on; Journey, Collections, MCP, AI Parsing and AirTrail ship off and are marked below.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
@@ -70,110 +70,76 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
|
||||
#### 🧭 Planning
|
||||
|
||||
- **Day plans**: drag places, notes and bookings between days with undo, or drop a map marker straight onto a day
|
||||
- **Maps**: Leaflet, Mapbox GL or MapLibre GL (OpenFreeMap, no token) with clustering, photo markers, route lines and a whole-trip route overview
|
||||
- **Places**: search the TREK Places index and OpenStreetMap with no key, or Google Places and Amap with one. Descriptions, hours and photos from Wikipedia, Wikidata and Wikimedia Commons, plus a rating and a custom image per place
|
||||
- **Explore**: nearby places by category for the map view, from the TREK Places index with Overpass as fallback
|
||||
- **Routes**: auto-sort a day (nearest neighbour then 2-opt, locked stops and hotels stay put), a travel mode per leg over OSRM or Valhalla, then open the day in Google Maps or CoMaps and a place in seven navigation apps
|
||||
- **Public transport**: door-to-door itineraries over Transitous, or Google where Transitous has no data
|
||||
- **Import and export**: Google Maps and Naver Maps lists, Google Maps directions links, GPX, KML and KMZ in; GPX and an ICS feed per trip or across all trips out
|
||||
- **Weather**: 16-day forecast from Open-Meteo, no key, and the archive for dates beyond it
|
||||
- **Trip dates**: move a trip and its days re-date themselves, with the bookings along or re-anchored. Trips also copy and archive
|
||||
- **Road trip** (off by default): drives with stops, day windows and arrival times that recompute, route alternatives, hazards and EV charging with range
|
||||
- **Day plans**: drag places between days and reorder inside a day, with undo. Notes and bookings drag the same way, and a map marker drops straight onto a day
|
||||
- **Maps**: Leaflet, Mapbox GL or MapLibre GL (OpenFreeMap, no token), with clustering, photo markers and route lines. 3D buildings and terrain are Mapbox only
|
||||
- **Place search**: Google Places when a key is set (photos, ratings, opening hours), otherwise OpenStreetMap with no key
|
||||
- **Place enrichment**: descriptions, facts, hours and photo candidates from OpenStreetMap, Wikipedia, Wikidata and Wikimedia Commons
|
||||
- **POI explore**: pull OpenStreetMap POIs by category for the current viewport over Overpass
|
||||
- **Import**: shared Google Maps and Naver Maps lists, plus GPX, KML and KMZ files
|
||||
- **Export**: GPX of a trip's places and tracks, and an ICS feed per trip or across all of them
|
||||
- **Routes**: auto-sort a day (nearest neighbour then 2-opt, locked stops and hotel anchors stay put), driving, walking or cycling profiles over OSRM, then open it in Google Maps or CoMaps
|
||||
- **Public transport**: door-to-door itineraries over Transitous
|
||||
- **Weather**: 16-day forecast from Open-Meteo, no key. Dates outside that window read the archive for the same date instead
|
||||
- **Day notes**: markdown body with an icon and a colour, reordered by drag and drop or moved to another day
|
||||
- **Trip dates**: move a trip and the days re-date themselves, either dragging the bookings along or re-anchoring them. Trips also copy and archive
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### 🥾 Tours
|
||||
|
||||
- **Seven tour types**: hike, city walk, run, bike (touring, road, gravel, MTB), paddle (kayak, canoe, SUP), horse ride, and ski and winter (alpine, cross-country, touring, snowshoe, winter hike)
|
||||
- **Routing**: legs routed over Valhalla with shaping points, hand-drawn legs, route variants, round hikes of a wished length and trip places as stops, all with undo
|
||||
- **Hikes**: routed within a maximum SAC grade (T1 to T6), the trail grades along the way, and via ferratas on the map
|
||||
- **Terrain**: elevation profile, ascent and descent, and a 3D terrain map with grade colouring and a flyover, no token needed. Topo, hiking, cycling and satellite bases with sea marks and ski pistes as overlays
|
||||
- **Multi-day tours**: one route cut into stages and spread across the trip's days
|
||||
- **Along the way**: viewpoints, huts, water, food and more within a corridor of the route, inserted as a stop with the detour it adds
|
||||
- **Ski, paddle and city walks**: a piste router by difficulty and lift type; a water router with portages, locks and a wind forecast; city walks with stays, opening hours and transit between stops
|
||||
- **Plan against reality**: link a recorded GPX to a planned day and compare distance, ascent and time. Import trails from a wanderer instance, save tours to a collection and take them into another trip
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### 🧳 Bookings and money
|
||||
|
||||
- **Reservations**: 18 booking types with status, confirmation code, travellers and attached files
|
||||
- **Flights and trains**: several legs with stopovers and endpoint timezones, against 4,045 bundled airports so local times resolve without a key
|
||||
- **Accommodation**: a stay spans a range of nights with a check-in window
|
||||
- **Booking import**: EML, PDF, PKPass, HTML, TXT and photos of confirmations, through [KItinerary](https://invent.kde.org/pim/kitinerary) or an AI model, with a review step before anything is saved. Prices become linked costs
|
||||
- **AirTrail** (off by default): import flights from a self-hosted AirTrail instance and keep them in sync
|
||||
- **Costs**: split in integer cents with equal or custom shares, several payers, settle-up suggestions, a per-person summary, a settlement log and CSV export. A receipt photo can fill in an expense
|
||||
- **Currencies**: one per expense with the rate frozen at entry, from Frankfurter with no key
|
||||
- **Packing lists and to-dos**: categories, templates, assignees and visibility tiers; bags with weights as an admin switch; to-dos with due dates, priorities and reminders
|
||||
- **Files**: attach to a trip, place, day or booking, 50 MB each and 500 MB for video, with trash and restore
|
||||
- **PDF export**: cover, place photos, day notes, bookings and costs, with an optional page break per day
|
||||
- **Reservations**: 16 booking types with status, confirmation code, travellers and attached files
|
||||
- **Flights and trains**: several legs with stopovers, per-leg times and endpoint timezones, against 4,045 bundled airports so local times resolve without a key
|
||||
- **Accommodation**: a stay spans a range of days with a check-in window, and shows on every night it covers
|
||||
- **Booking import**: EML, PDF, PKPass, HTML and TXT confirmations through [KItinerary](https://invent.kde.org/pim/kitinerary). Needs the `kitinerary-extractor` binary, which ships in the Docker image
|
||||
- **AirTrail** (off by default): link a self-hosted AirTrail instance to import flights as reservations and keep them in sync
|
||||
- **Costs**: split expenses in integer cents with equal or custom shares, several payers per expense, settle-up suggestions, a settlement log, and CSV export
|
||||
- **Currencies**: a currency per expense with the rate frozen at entry. Rates come from Frankfurter, no key
|
||||
- **Packing lists**: categories, admin-managed templates, assignees, three visibility tiers, and a packed-of-total line. Bags with weight roll-up are a separate admin switch, off by default
|
||||
- **To-dos**: assignee, due date, priority, and a reminder before one falls due
|
||||
- **Files**: attach to a trip, place, day entry or reservation. 50 MB each, 500 MB for video, with trash and restore
|
||||
- **PDF export**: cover page, place photos, day notes, bookings and costs, with an optional page break per day
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### 👥 Collaboration
|
||||
|
||||
- **Real-time sync** (WebSocket): edits land live for everyone who has the trip open
|
||||
- **Members**: add by email or username, hand over ownership, or add guests who have no login at all
|
||||
- **Permissions**: an admin maps each of 17 trip actions to admin, trip owner, trip member or everybody
|
||||
- **Invites**: one reusable link per trip with an optional expiry, and admin signup invites that drop a new account straight into a trip
|
||||
- **Public share**: a read-only trip page without an account, with switches for map, bookings, packing, costs and chat
|
||||
- **Collab**: group chat with replies, reactions and link previews, shared notes, links, polls and a What's Next list, each one its own switch
|
||||
- **Notifications**: an inbox grouped by day with answers right from the notification, and a per-user matrix of events against in-app, email, webhook, ntfy, Web Push and plugin channels
|
||||
- **Real-time sync** (WebSocket): edits land live for everyone who has that trip open
|
||||
- **Members**: add by email or username, hand ownership to someone else, or add guests who have no login at all
|
||||
- **Permissions**: an admin maps each of 16 trip actions to admin, trip owner, trip member or everybody
|
||||
- **Invite links**: one reusable link per trip with an optional expiry. Admins can also issue signup invites with a use limit that drop the new account straight into a trip
|
||||
- **Public share**: a read-only trip page anyone can open without an account
|
||||
- **Collab**: group chat with replies, reactions and link previews, shared notes with attachments, polls, and a What's Next list of upcoming activities. Each of the four switches on its own
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
#### 📔 Journal, Atlas and Vacay
|
||||
|
||||
#### 📔 Journey and TREK Studio
|
||||
|
||||
- **Journey** (off by default): dated entries with story, mood, weather and tags, photos and video from uploads, [Immich](https://immich.app) or Synology Photos, map views, co-authors, drafts and a public share link
|
||||
- **Linked journal**: a trip can show one journal as its own, with the members picked on the trip as viewers or editors
|
||||
- **Recorded days** (with Dawarich): keep a day's recorded route and turn its stays into entries
|
||||
- **TREK Studio**: turn a journal into a printable photo book. 34 print-licensed typefaces, 17 themes, 108 designed pages in twelve styles, 160 recolourable stickers, text effects, layers and a Travel tab with route maps, country stamps and trip figures
|
||||
- **Auto layout**: lays the whole book on the designed pages in the style of its theme, every photo in a frame, or rebuilds one spread
|
||||
- **Print and share**: PDF export as pages or spreads with crop marks, several people editing at once, and design files to move a spread into another book
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### 🗺️ 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
|
||||
- **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
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### 🤖 AI assistant and MCP
|
||||
|
||||
- **AI assistant** (off by default): a chat that plans with you in a trip, across all your trips, in a journal and in Studio, and works with tours, costs, bookings, packing, Vacay and the Atlas
|
||||
- **Your own model**: an API key for Anthropic, OpenAI, Gemini or OpenRouter, a ChatGPT plan, or any OpenAI-compatible endpoint, set for the instance or per user
|
||||
- **You stay in charge**: reads run at once, every change waits as a card to apply or discard and can be undone for 15 minutes. Nothing leaves before you agree to the provider, and a file's text only with your consent
|
||||
- **Attachments**: drop a booking confirmation, a GPX file or a photo into the chat, and the assistant offers what to do with it
|
||||
- **MCP server** (off by default): OAuth 2.1 with mandatory PKCE and dynamic client registration, 410 tools, 30 resources and 4 prompts, 35 scopes in 17 groups ticked on the consent screen, and every call in the audit log
|
||||
- **Addon-aware**: twelve addon gates decide which tools a session sees, and flipping one re-registers live sessions
|
||||
- **Journey** (off by default): dated entries with story, mood, weather and tags, photos and video from uploads or a linked [Immich](https://immich.app) or Synology Photos library, map views, co-authors, and a public share link
|
||||
- **Atlas**: mark countries and sub-national regions visited on [geoBoundaries](https://www.geoboundaries.org/) outlines, plus a bucket list, travel stats and a consecutive-years-travelled count
|
||||
- **Vacay**: leave calendar with half days, public holidays from date.nager.at, school holiday overlays for 16 European countries, carry-over between years, and joint or read-only sharing of a plan
|
||||
- **Collections** (off by default): a place library outside any trip, with labels, ratings, a custom image per place, copy-into-a-trip, and sharing by invite
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### 🧩 Plugins
|
||||
|
||||
- **Third-party plugins**: install from the TREK registry or sideload a zip, with their own pages under `/plugins/<id>`
|
||||
- **Sandboxed**: one child process per plugin, 66 grantable permissions, an admin-edited outbound host allowlist, memory and call caps
|
||||
- **Trust**: registry downloads are pinned by sha256 and checked against the author's minisign key, a sideloaded zip is marked unverified, and `TREK_PLUGINS_ENABLED=false` turns the whole system off
|
||||
- **Extension points**: map layers, place details, day schedules, PDF sections, Atlas layers, journal rows, trip warnings, search and photo providers, route profiles, notification channels and MCP tools
|
||||
- **SDK**: [`trek-plugin-sdk`](https://www.npmjs.com/package/trek-plugin-sdk) with a CLI to create, validate, run against real data, sign and publish
|
||||
- **Third-party plugins**: install from the TREK registry or sideload a zip, switch on per instance, with their own pages under `/plugins/<id>`
|
||||
- **Sandboxed**: one child process per plugin, 63 grantable permissions, an admin-edited outbound host allowlist, memory and RPC caps, and daily caps on AI and notification calls
|
||||
- **Trust**: registry downloads are pinned by sha256 and checked against the author's minisign key. A sideloaded zip is marked unverified, and `TREK_PLUGINS_ENABLED=false` turns the whole system off
|
||||
- **Extension points**: map markers and layers, place details, day schedules, PDF sections, Atlas layers, journal rows, trip warnings, calendar sources, route profiles and notification channels. Plugin pages run in an opaque-origin iframe
|
||||
- **SDK**: [`trek-plugin-sdk`](https://www.npmjs.com/package/trek-plugin-sdk) on npm, with a manifest validator, a mock host, and a dev-link mode that runs a local build against real data
|
||||
|
||||
#### 🤖 AI and MCP
|
||||
|
||||
- **MCP server** (off by default): OAuth 2.1 with mandatory PKCE and dynamic client registration. 199 tools, 30 resources, 4 prompts
|
||||
- **Scopes**: 29 scopes in 14 groups, each one tickable on the consent screen. Tokens are bound to the `/mcp` resource, and every tool call lands in the audit log
|
||||
- **Reach**: create trips and days, edit places, packing lists, to-dos, costs, reservations, collections and journeys, mark countries visited, all inside the scopes the token holds
|
||||
- **Prompts**: `trip-summary`, plus `packing-list` and `budget-overview` when those addons are on
|
||||
- **Addon-aware**: seven addon gates decide which tools and resources a session sees. Flipping one drops live sessions so the surface re-registers
|
||||
- **Booking extraction** (off by default): read a confirmation with a local Ollama server, any OpenAI-compatible endpoint, or Anthropic, configured instance-wide or per user
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
@@ -182,26 +148,30 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
|
||||
#### 📱 Mobile and offline
|
||||
|
||||
- **Apps**: TREK Travel Planner for iPhone, iPad and Android connects to any TREK server, and the browser installs TREK as a standalone app with a themed status bar too
|
||||
- **Phone layouts**: their own screens for every part of the app, with a bottom bar and dashboard widgets the user orders
|
||||
- **Offline reads**: the app shell is precached and trips, places, tours, files and nearby places live in a per-user IndexedDB store, so a trip opens with no network
|
||||
- **Offline writes**: changes queue and replay with an `X-Idempotency-Key`, and a stale edit waits for a keep-mine or keep-theirs choice
|
||||
- **Offline maps**: raster and vector tiles of a trip downloaded ahead, and a switch that takes the whole app offline on purpose
|
||||
- **Installable**: iOS and Android straight from the browser, no App Store. Runs standalone without browser chrome, with the status bar tinted per theme
|
||||
- **Phone layouts**: a separate shell below 768px with its own tokens, a bottom bar and safe-area insets. Which items sit in that bar is up to the user
|
||||
- **Offline reads**: the app shell and every route chunk are precached, and trips, places and file blobs live in a per-user IndexedDB store, so a trip opens with no network
|
||||
- **Offline writes**: mutations queue and replay with an `X-Idempotency-Key`, so a reconnect cannot double-apply. A stale edit is parked for a keep-mine or keep-theirs choice
|
||||
- **Offline maps**: pre-download a trip's raster tiles, and clear them again
|
||||
- **API responses are never cached** by the service worker. They vary per session, so they always come from the network
|
||||
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
|
||||
#### ⚙️ Admin, accounts and security
|
||||
|
||||
- **Sign-in**: password, OIDC and passkeys each switch on and off on their own, `OIDC_ONLY` leaves SSO as the only way in, and an OIDC claim can grant admin
|
||||
- **SSO and 2FA**: one OIDC provider by discovery with PKCE (Authentik, Keycloak, Google and the like), TOTP with backup codes that an admin can require, and passkeys that count as the second factor
|
||||
- **Sessions**: every sign-in is a session you can see and end, one by one or all others at once
|
||||
- **Hardening**: rate limits on sign-in, reset and 2FA, a password policy, secrets encrypted at rest and masked on read, and an SSRF guard on every URL you configure
|
||||
- **Admin panel**: users and the permission matrix, defaults for new users, categories and templates, addons, plugins, storage, notifications, MCP tokens, backups, audit log and releases
|
||||
- **Backups and storage**: scheduled backups with retention that restore their own secrets, and local or S3-compatible storage per content category with replicas
|
||||
- **Appearance**: light, dark or follow the OS, seven colour schemes plus a custom accent, transparency, density, reduced motion and text size
|
||||
- **28 languages**: en, de, es, fr, it, nl, hu, ru, zh, zh-TW, pl, cs, ar (right to left), he (right to left), br, id, tr, ja, ko, uk, gr, sv, vi, ca, az, et, sk, th
|
||||
- **Help center**: a ? in the top bar with 381 step-by-step guides with screenshots, searched together with the wiki that ships in the image
|
||||
- **Login methods**: password login, password registration, OIDC login, OIDC registration and passkey login each switch on and off on their own. `OIDC_ONLY` leaves SSO as the only way in
|
||||
- **SSO (OIDC)**: one provider by discovery, with PKCE and `id_token` verification (Authentik, Keycloak, Google and the like)
|
||||
- **2FA**: TOTP with ten single-use backup codes, and an admin can require it instance-wide
|
||||
- **Passkeys**: WebAuthn login by fingerprint, face, PIN or security key, off until an admin enables it. A passkey also satisfies the 2FA requirement
|
||||
- **Hardening**: per-IP limits on login, password reset and 2FA attempts, a password policy, secrets encrypted at rest and masked on read, and an SSRF guard on every URL you configure
|
||||
- **Admin panel**: users and invites, the permission matrix, packing templates, categories, addons, plugins, API keys, MCP tokens and OAuth sessions, backups, storage, audit log, and GitHub releases
|
||||
- **Backups**: manual or scheduled hourly, daily, weekly or monthly, with retention in days. The zip carries the at-rest key, so a restore can decrypt its own secrets
|
||||
- **Storage**: pluggable storage backends per content category — keep everything on local disk, or add S3-compatible backends and replicate any category to them, configured entirely from the admin panel
|
||||
- **Notifications**: a per-user matrix of events against in-app, email (SMTP), webhook, ntfy and Web Push (on every device you turn it on for, even with TREK closed), plus any channel a plugin registers
|
||||
- **Appearance**: light, dark or follow the OS, seven colour schemes plus a custom accent, transparency, compact density, reduce motion, and text size per tier
|
||||
- **27 languages**: en, de, es, fr, it, nl, hu, ru, zh, zh-TW, pl, cs, ar (right to left), br, id, tr, ja, ko, uk, gr, sv, vi, ca, az, et, sk, th
|
||||
- **In-app help**: the wiki ships inside the image and is served from disk at `/help`, so the docs match the version you are running
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
@@ -214,39 +184,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
<div align="center">
|
||||
<a href="docs/screenshots/showcase-desktop-1.webp"><img src="docs/screenshots/showcase-desktop-1.webp" alt="Atlas · dashboard · trip planner" width="100%" /></a>
|
||||
<a href="docs/screenshots/showcase-mobile.webp"><img src="docs/screenshots/showcase-mobile.webp" alt="Mobile PWA · dashboard, day plan, map, costs" width="100%" /></a>
|
||||
</div>
|
||||
|
||||
<br />
|
||||
|
||||
## Powered by [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek)
|
||||
|
||||
<div align="center">
|
||||
|
||||
<br />
|
||||
|
||||
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" />
|
||||
<img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="60" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
<br />
|
||||
<br />
|
||||
|
||||
**Every TREK installation in the world searches through servers that [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) sponsors.**
|
||||
|
||||
The place index with over 88 million places, the address search in every TREK language and the planet-wide routing all run on [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) in Frankfurt, Germany, free of charge for everyone who self-hosts TREK. Without this sponsorship, these services would not exist in this form.
|
||||
|
||||
Thank you, [dataforest](https://cloud.dataforest.net/en?mtm_campaign=trek), for backing open source this generously. 💚
|
||||
|
||||
<br />
|
||||
|
||||
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><img alt="Visit dataforest cloud" src="https://img.shields.io/badge/Visit-dataforest_cloud-02C382?style=for-the-badge" /></a>
|
||||
|
||||
Looking for a server for your own TREK? [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) is where TREK's own services live.
|
||||
|
||||
<a href="docs/screenshots/showcase-desktop-2.webp"><img src="docs/screenshots/showcase-desktop-2.webp" alt="Collections · journey journal · costs" width="100%" /></a>
|
||||
</div>
|
||||
|
||||
<br />
|
||||
@@ -266,18 +204,12 @@ the details.
|
||||
## Get started in 30 seconds
|
||||
|
||||
```bash
|
||||
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d --name trek -p 3000:3000 \
|
||||
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d -p 3000:3000 \
|
||||
-e ENCRYPTION_KEY=$ENCRYPTION_KEY \
|
||||
-e COOKIE_SECURE=false \
|
||||
-v ./data:/app/data -v ./uploads:/app/uploads mauriceboe/trek
|
||||
```
|
||||
|
||||
Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`).
|
||||
|
||||
`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.
|
||||
|
||||
> [!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.
|
||||
Open `http://localhost:3000`. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`).
|
||||
|
||||
<div align="center">
|
||||
|
||||
@@ -291,7 +223,7 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
@@ -335,7 +267,7 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM
|
||||
|
||||
<h2 id="install-as-app-pwa">Install as App (PWA)</h2>
|
||||
|
||||
TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead:
|
||||
TREK works as a Progressive Web App — no App Store needed.
|
||||
|
||||
1. Open TREK in the browser (HTTPS required)
|
||||
2. **iOS**: Share ▸ *Add to Home Screen*
|
||||
@@ -433,6 +365,16 @@ Caddy handles TLS and WebSockets automatically.
|
||||
Every variable, its default and what it does: see
|
||||
[Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables).
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/?repos=liketrek%2FTREK&type=date&legend=bottom-right">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=liketrek/TREK&type=date&theme=dark&legend=bottom-right&sealed_token=tW9agibKugOyPk0yPURgSdnizM7K72zbJENGD9iyk24ZcwYHtCUn-hk9jh1gdacO0O7xJ3Io7LaNrwYD3mChzcpzZIqDC8_HevYG1qnT0XNTmN6Ez4UZrQ" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=liketrek/TREK&type=date&legend=bottom-right&sealed_token=tW9agibKugOyPk0yPURgSdnizM7K72zbJENGD9iyk24ZcwYHtCUn-hk9jh1gdacO0O7xJ3Io7LaNrwYD3mChzcpzZIqDC8_HevYG1qnT0XNTmN6Ez4UZrQ" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=liketrek/TREK&type=date&legend=bottom-right&sealed_token=tW9agibKugOyPk0yPURgSdnizM7K72zbJENGD9iyk24ZcwYHtCUn-hk9jh1gdacO0O7xJ3Io7LaNrwYD3mChzcpzZIqDC8_HevYG1qnT0XNTmN6Ez4UZrQ" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## Data sources
|
||||
|
||||
The Atlas map's country and sub-national (province/county) boundaries come from
|
||||
|
||||
@@ -5,10 +5,9 @@ This is a minimal Helm chart for deploying the TREK app.
|
||||
## Features
|
||||
- Deploys the TREK container
|
||||
- Exposes port 3000 via Service
|
||||
- Optional persistent storage for `/app/data` and `/app/uploads`, plus extra volumes and mounts
|
||||
- Optional persistent storage for `/app/data` and `/app/uploads`
|
||||
- Configurable environment variables and secrets
|
||||
- Optional generic Ingress support
|
||||
- Optional Gateway API HTTPRoute support
|
||||
- Configurable health checks (liveness/readiness probes) on `/api/health`
|
||||
|
||||
## Helm Repository
|
||||
@@ -28,7 +27,7 @@ helm install trek trek/trek
|
||||
Or install directly from the local chart:
|
||||
|
||||
```sh
|
||||
helm install trek ./charts/trek \
|
||||
helm install trek ./chart \
|
||||
--set ingress.enabled=true \
|
||||
--set ingress.hosts[0].host=yourdomain.com
|
||||
```
|
||||
@@ -48,7 +47,7 @@ See `values.yaml` for more options.
|
||||
- `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.
|
||||
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
|
||||
- If exposing TREK through an Ingress or HTTPRoute, set `env.ALLOWED_ORIGINS` and `env.APP_URL` to the public URL. The chart does not sync these automatically.
|
||||
- If using ingress, you must manually keep `env.ALLOWED_ORIGINS` and `ingress.hosts` in sync to ensure CORS works correctly. The chart does not sync these automatically.
|
||||
- Set `env.ALLOW_INTERNAL_NETWORK: "true"` if Immich or other integrated services are hosted on a private/RFC-1918 address (e.g. a pod on the same cluster or a NAS on your LAN). Loopback (`127.x`) and link-local/metadata addresses (`169.254.x`) remain blocked regardless.
|
||||
- Set `env.ALLOW_LINK_LOCAL_IPS` to a single link-local address (e.g. `"169.254.1.2"`) only when a service TREK needs sits behind one, such as a host gateway. Cloud metadata addresses (`169.254.169.x`, `169.254.170.x`) cannot be listed.
|
||||
- `FORCE_HTTPS` is optional. Set `env.FORCE_HTTPS: "true"` only when ingress (or another proxy) terminates TLS. It enables HTTPS redirects, HSTS, CSP `upgrade-insecure-requests`, and forces the session cookie `secure` flag. Requires `TRUST_PROXY` to be set.
|
||||
@@ -56,5 +55,3 @@ See `values.yaml` for more options.
|
||||
- `COOKIE_SECURE` is auto-derived (on when `NODE_ENV=production` or `FORCE_HTTPS=true`). Set `env.COOKIE_SECURE: "false"` only during local testing without TLS. **Not recommended for production.**
|
||||
- Web Push needs no chart settings: TREK generates its key pair on first start and keeps it in the database on the data PVC. To bring your own pair, set `env.VAPID_PUBLIC_KEY` and `secretEnv.VAPID_PRIVATE_KEY` together (and optionally `env.VAPID_SUBJECT`); changing the pair later means every device has to turn push on again.
|
||||
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
|
||||
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
|
||||
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
apiVersion: v2
|
||||
name: trek
|
||||
version: 5.1.0
|
||||
version: 4.3.3
|
||||
description: Minimal Helm chart for TREK app
|
||||
appVersion: "5.1.0"
|
||||
appVersion: "4.3.3"
|
||||
|
||||
@@ -5,9 +5,8 @@
|
||||
- To use an existing Kubernetes secret, set `existingSecret` to the secret name. The chart then
|
||||
renders no Secret of its own and reads every secret env var from that secret: `ENCRYPTION_KEY`
|
||||
(renamable via `existingSecretKey`), plus `ADMIN_EMAIL`, `ADMIN_PASSWORD`, `OIDC_CLIENT_SECRET`,
|
||||
`UNSPLASH_ACCESS_KEY`, `PLACES_API_KEY`, `AMAP_API_KEY`, `AMAP_API_SECRET`,
|
||||
`VAPID_PRIVATE_KEY`, `SMTP_PASS`, `MAPBOX_ACCESS_TOKEN`, `CARTO_API_KEY` and
|
||||
`DEMO_ADMIN_PASS`. Missing keys are simply left unset, so only provide the ones you use.
|
||||
`UNSPLASH_ACCESS_KEY`, `PLACES_API_KEY`, `AMAP_API_KEY`, `AMAP_API_SECRET` and
|
||||
`VAPID_PRIVATE_KEY`. Missing keys are simply left unset, so only provide the ones you use.
|
||||
- If left empty, the server resolves the key automatically: existing installs fall back to
|
||||
data/.jwt_secret (encrypted data stays readable with no manual action); fresh installs
|
||||
auto-generate a key persisted to the data PVC.
|
||||
@@ -31,12 +30,3 @@
|
||||
The other values for that volume (size, storageClassName, annotations) are then ignored.
|
||||
- With `persistence.enabled=false` the volumes use an emptyDir — storage is ephemeral and is lost
|
||||
when the pod restarts. Use only for testing.
|
||||
{{- if .Values.httpRoute.enabled }}
|
||||
|
||||
6. HTTPRoute:
|
||||
- The chart creates an HTTPRoute v1 to the existing TREK Service. The Gateway, GatewayClass,
|
||||
listeners, TLS certificates and allowedRoutes are managed by your cluster operator.
|
||||
- Ingress and HTTPRoute may be enabled together.
|
||||
- Timeout fields are Standard Channel in Gateway API v1.2, but controller support varies. Omit
|
||||
them to use controller defaults; `0s` disables the corresponding timeout where supported.
|
||||
{{- end }}
|
||||
|
||||
@@ -16,12 +16,6 @@ data:
|
||||
{{- if .Values.env.TREK_WIKI_DIR }}
|
||||
TREK_WIKI_DIR: {{ .Values.env.TREK_WIKI_DIR | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.DEFAULT_LANGUAGE }}
|
||||
DEFAULT_LANGUAGE: {{ .Values.env.DEFAULT_LANGUAGE | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.MCP_MAX_SESSION_PER_USER }}
|
||||
MCP_MAX_SESSION_PER_USER: {{ .Values.env.MCP_MAX_SESSION_PER_USER | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.ALLOWED_ORIGINS }}
|
||||
ALLOWED_ORIGINS: {{ .Values.env.ALLOWED_ORIGINS | quote }}
|
||||
{{- end }}
|
||||
@@ -112,27 +106,6 @@ data:
|
||||
{{- if .Values.env.TREK_PLACES_URL }}
|
||||
TREK_PLACES_URL: {{ .Values.env.TREK_PLACES_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_PLACES_CONTRIBUTE }}
|
||||
TREK_PLACES_CONTRIBUTE: {{ .Values.env.TREK_PLACES_CONTRIBUTE | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_SERVICES }}
|
||||
TREK_SERVICES: {{ .Values.env.TREK_SERVICES | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_SERVICES_HOSTS }}
|
||||
TREK_SERVICES_HOSTS: {{ .Values.env.TREK_SERVICES_HOSTS | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_PHOTON_URL }}
|
||||
TREK_PHOTON_URL: {{ .Values.env.TREK_PHOTON_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_VALHALLA_URL }}
|
||||
TREK_VALHALLA_URL: {{ .Values.env.TREK_VALHALLA_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_WALLET_SIGNER_URL }}
|
||||
TREK_WALLET_SIGNER_URL: {{ .Values.env.TREK_WALLET_SIGNER_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.GOOGLE_LIST_DATA_BASE }}
|
||||
GOOGLE_LIST_DATA_BASE: {{ .Values.env.GOOGLE_LIST_DATA_BASE | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.AMAP_API_BASE }}
|
||||
AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }}
|
||||
{{- end }}
|
||||
|
||||
@@ -9,7 +9,7 @@ spec:
|
||||
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
|
||||
# RollingUpdate would start a second pod holding the same volume before the old one
|
||||
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
|
||||
# the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
# the old pod down first. Override to RollingUpdate only with a ReadWriteMany volume.
|
||||
strategy:
|
||||
type: {{ .Values.updateStrategy | default "Recreate" }}
|
||||
selector:
|
||||
@@ -29,31 +29,21 @@ spec:
|
||||
- name: {{ .name }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- with .Values.podSecurityContext }}
|
||||
securityContext:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
fsGroup: 1000
|
||||
containers:
|
||||
- name: trek
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- with .Values.securityContext }}
|
||||
securityContext:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- with .Values.resources }}
|
||||
resources:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: {{ .Values.env.PORT | default 3000 }}
|
||||
- containerPort: 3000
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: {{ include "trek.fullname" . }}-config
|
||||
{{- with .Values.extraEnvFrom }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
env:
|
||||
- name: ENCRYPTION_KEY
|
||||
valueFrom:
|
||||
@@ -91,12 +81,6 @@ spec:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: PLACES_API_KEY
|
||||
optional: true
|
||||
- name: TREK_SERVICES_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: TREK_SERVICES_KEY
|
||||
optional: true
|
||||
- name: AMAP_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
@@ -115,45 +99,11 @@ spec:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: VAPID_PRIVATE_KEY
|
||||
optional: true
|
||||
- name: SMTP_PASS
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: SMTP_PASS
|
||||
optional: true
|
||||
- name: MAPBOX_ACCESS_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: MAPBOX_ACCESS_TOKEN
|
||||
optional: true
|
||||
- name: CARTO_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: CARTO_API_KEY
|
||||
optional: true
|
||||
- name: DEMO_ADMIN_PASS
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: DEMO_ADMIN_PASS
|
||||
optional: true
|
||||
{{- with .Values.extraEnv }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /app/data
|
||||
- name: uploads
|
||||
mountPath: /app/uploads
|
||||
{{- with .Values.extraVolumeMounts }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- with (default dict .Values.probes).startup }}
|
||||
startupProbe:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- with (default dict .Values.probes).liveness }}
|
||||
livenessProbe:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
@@ -177,6 +127,3 @@ spec:
|
||||
{{- else }}
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- with .Values.extraVolumes }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
{{- if .Values.httpRoute.enabled -}}
|
||||
{{- if not .Values.httpRoute.parentRefs }}
|
||||
{{- fail "httpRoute.parentRefs must include at least one parent" }}
|
||||
{{- end }}
|
||||
{{- if not .Values.httpRoute.paths }}
|
||||
{{- fail "httpRoute.paths must include at least one path" }}
|
||||
{{- end }}
|
||||
apiVersion: gateway.networking.k8s.io/v1
|
||||
kind: HTTPRoute
|
||||
metadata:
|
||||
name: {{ include "trek.fullname" . }}
|
||||
labels:
|
||||
app: {{ include "trek.name" . }}
|
||||
{{- with .Values.httpRoute.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
parentRefs:
|
||||
{{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
|
||||
{{- with .Values.httpRoute.hostnames }}
|
||||
hostnames:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
rules:
|
||||
{{- range $path := .Values.httpRoute.paths }}
|
||||
- matches:
|
||||
- path:
|
||||
type: PathPrefix
|
||||
value: {{ $path | quote }}
|
||||
backendRefs:
|
||||
- name: {{ include "trek.fullname" $ }}
|
||||
port: {{ $.Values.service.port }}
|
||||
{{- with $.Values.httpRoute.timeouts }}
|
||||
timeouts:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -23,9 +23,6 @@ data:
|
||||
{{- if .Values.secretEnv.PLACES_API_KEY }}
|
||||
PLACES_API_KEY: {{ .Values.secretEnv.PLACES_API_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.TREK_SERVICES_KEY }}
|
||||
TREK_SERVICES_KEY: {{ .Values.secretEnv.TREK_SERVICES_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.AMAP_API_KEY }}
|
||||
AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
@@ -35,18 +32,6 @@ data:
|
||||
{{- if .Values.secretEnv.VAPID_PRIVATE_KEY }}
|
||||
VAPID_PRIVATE_KEY: {{ .Values.secretEnv.VAPID_PRIVATE_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.SMTP_PASS }}
|
||||
SMTP_PASS: {{ .Values.secretEnv.SMTP_PASS | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.MAPBOX_ACCESS_TOKEN }}
|
||||
MAPBOX_ACCESS_TOKEN: {{ .Values.secretEnv.MAPBOX_ACCESS_TOKEN | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.CARTO_API_KEY }}
|
||||
CARTO_API_KEY: {{ .Values.secretEnv.CARTO_API_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.DEMO_ADMIN_PASS }}
|
||||
DEMO_ADMIN_PASS: {{ .Values.secretEnv.DEMO_ADMIN_PASS | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if and (not .Values.existingSecret) (.Values.generateEncryptionKey) }}
|
||||
@@ -80,9 +65,6 @@ stringData:
|
||||
{{- if .Values.secretEnv.PLACES_API_KEY }}
|
||||
PLACES_API_KEY: {{ .Values.secretEnv.PLACES_API_KEY | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.TREK_SERVICES_KEY }}
|
||||
TREK_SERVICES_KEY: {{ .Values.secretEnv.TREK_SERVICES_KEY | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.AMAP_API_KEY }}
|
||||
AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY | quote }}
|
||||
{{- end }}
|
||||
@@ -92,16 +74,4 @@ stringData:
|
||||
{{- if .Values.secretEnv.VAPID_PRIVATE_KEY }}
|
||||
VAPID_PRIVATE_KEY: {{ .Values.secretEnv.VAPID_PRIVATE_KEY | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.SMTP_PASS }}
|
||||
SMTP_PASS: {{ .Values.secretEnv.SMTP_PASS | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.MAPBOX_ACCESS_TOKEN }}
|
||||
MAPBOX_ACCESS_TOKEN: {{ .Values.secretEnv.MAPBOX_ACCESS_TOKEN | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.CARTO_API_KEY }}
|
||||
CARTO_API_KEY: {{ .Values.secretEnv.CARTO_API_KEY | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.DEMO_ADMIN_PASS }}
|
||||
DEMO_ADMIN_PASS: {{ .Values.secretEnv.DEMO_ADMIN_PASS | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
@@ -8,7 +8,7 @@ spec:
|
||||
type: {{ .Values.service.type }}
|
||||
ports:
|
||||
- port: {{ .Values.service.port }}
|
||||
targetPort: http
|
||||
targetPort: 3000
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
|
||||
@@ -4,40 +4,11 @@ image:
|
||||
# tag: latest
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
|
||||
# during a RollingUpdate the new pod migrates the database while the old one still
|
||||
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
|
||||
# processes on one host, which network filesystems do not provide.
|
||||
# Deployment update strategy. Recreate is the safe default for the single-writer SQLite
|
||||
# DB on a ReadWriteOnce volume (the old pod is torn down before the new one starts).
|
||||
# Set to RollingUpdate only if you back the data volume with ReadWriteMany storage.
|
||||
updateStrategy: Recreate
|
||||
|
||||
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
|
||||
# to the data and uploads volumes; OnRootMismatch lets the kubelet skip its recursive
|
||||
# permission walk once the volume root already matches, so a big PVC does not hold up
|
||||
# every start.
|
||||
#
|
||||
# By default the container starts as root, hands any files that are not node's yet to
|
||||
# node, and then drops to node itself. To start it as node straight away (needed under
|
||||
# the "restricted" Pod Security Standard), add the user here and lock the container
|
||||
# down below; the image then skips the ownership step and the privilege drop:
|
||||
# podSecurityContext:
|
||||
# fsGroup: 1000
|
||||
# fsGroupChangePolicy: OnRootMismatch
|
||||
# runAsUser: 1000
|
||||
# runAsGroup: 1000
|
||||
# runAsNonRoot: true
|
||||
# seccompProfile:
|
||||
# type: RuntimeDefault
|
||||
# securityContext:
|
||||
# allowPrivilegeEscalation: false
|
||||
# capabilities:
|
||||
# drop: [ALL]
|
||||
podSecurityContext:
|
||||
fsGroup: 1000
|
||||
fsGroupChangePolicy: OnRootMismatch
|
||||
|
||||
# Security context of the trek container itself. Empty by default.
|
||||
securityContext: {}
|
||||
|
||||
# Optional image pull secrets for private registries
|
||||
imagePullSecrets: []
|
||||
# - name: my-registry-secret
|
||||
@@ -62,9 +33,9 @@ env:
|
||||
# DEFAULT_LANGUAGE: "en"
|
||||
# Default language on the login page for users with no saved preference.
|
||||
# Browser/OS language is auto-detected first; this is the fallback when no match is found.
|
||||
# Supported: ar, az, br, ca, cs, de, en, es, et, fr, gr, hu, id, it, ja, ko, nl, pl, ru, sk, sv, th, tr, uk, vi, zh, zh-TW
|
||||
# Supported: de, en, es, fr, hu, nl, br, cs, pl, ru, zh, zh-TW, it, ar
|
||||
# ALLOWED_ORIGINS: ""
|
||||
# NOTE: If using ingress or HTTPRoute, ensure env.ALLOWED_ORIGINS matches the public domains for proper CORS configuration.
|
||||
# NOTE: If using ingress, ensure env.ALLOWED_ORIGINS matches the domains in ingress.hosts for proper CORS configuration.
|
||||
# APP_URL: "https://trek.example.com"
|
||||
# Public base URL of this instance. Required when OIDC is enabled — must match the redirect URI registered with your IdP.
|
||||
# Also used as the base URL for links in email notifications and other external links.
|
||||
@@ -120,8 +91,7 @@ env:
|
||||
# Custom Nominatim base URL for every geocoding call the server makes (place search, reverse lookup, Atlas region
|
||||
# fill). When set it REPLACES the public OpenStreetMap service, with no fallback, so the instance behind it needs
|
||||
# the coverage you expect and has to speak the Nominatim API. TREK keeps its ~1 request per second spacing either
|
||||
# way, and search and reverse lookups no longer go to the TREK services' Photon. Defaults to
|
||||
# https://nominatim.openstreetmap.org.
|
||||
# way. Defaults to https://nominatim.openstreetmap.org.
|
||||
# OVERPASS_URL: ""
|
||||
# Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled
|
||||
# public mirrors — point it at an internal/self-hosted Overpass instance when the public mirrors are unreachable
|
||||
@@ -131,38 +101,15 @@ env:
|
||||
# lower value hangs up on answers that were still coming. Raise it for a slow self-hosted Overpass instance.
|
||||
# Defaults to 25000.
|
||||
# TREK_PLACES_ENABLED: "false"
|
||||
# Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads,
|
||||
# and the OpenStreetMap ways and horse routes Tours reads) asks the TREK Places API at https://places.liketrek.com by default, so the pod makes outbound requests to that
|
||||
# Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads)
|
||||
# asks the TREK Places API at https://places.liketrek.com by default, so the pod makes outbound requests to that
|
||||
# host. Set "false" to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send
|
||||
# nothing there. There is no switch in the admin panel on purpose: whether searches leave the instance is decided
|
||||
# here. Defaults to on.
|
||||
# TREK_PLACES_URL: ""
|
||||
# GOOGLE_LIST_DATA_BASE: ""
|
||||
# Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from
|
||||
# configuration rather than typed by a user, so an in-cluster address works without ALLOW_INTERNAL_NETWORK.
|
||||
# Defaults to https://places.liketrek.com.
|
||||
# TREK_PLACES_CONTRIBUTE: "off"
|
||||
# Whether an admin may let this installation send the place details its users typed in (website, phone, e-mail,
|
||||
# opening hours, description, picture) to the TREK Places API. "admin" leaves the choice to the admin panel, where
|
||||
# it stays off until an admin agrees; "off" takes it away. Defaults to admin.
|
||||
# TREK_SERVICES: "off"
|
||||
# Places search identifies this installation with a key it registers by itself on first use and keeps in the
|
||||
# database. "off" sends no key; searches then use the shared pool. A key issued to you goes under
|
||||
# secretEnv.TREK_SERVICES_KEY. Defaults to auto.
|
||||
# TREK_SERVICES_HOSTS: ""
|
||||
# Comma-separated hosts that receive the installation key over https. Defaults to
|
||||
# places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com.
|
||||
# TREK_PHOTON_URL: ""
|
||||
# The address search (Photon) of the TREK services. With a key, search and reverse lookups ask it before
|
||||
# Nominatim and fall back to Nominatim when it does not answer. Never asked when NOMINATIM_URL is set.
|
||||
# Defaults to https://photon.liketrek.com.
|
||||
# TREK_VALHALLA_URL: ""
|
||||
# The Valhalla of the TREK services, which this server relays routing to unless the admin picks another
|
||||
# routing service. The browser never talks to it. Defaults to https://valhalla.liketrek.com.
|
||||
# TREK_WALLET_SIGNER_URL: ""
|
||||
# Signs the Apple Wallet pass of a booking when someone taps "Add to Apple Wallet" in the iOS app.
|
||||
# Only the pass's texts go there, once per tap. Never asked with TREK_SERVICES=off.
|
||||
# Defaults to https://push.liketrek.com/v1/wallet/pass.
|
||||
# AMAP_API_BASE: ""
|
||||
# Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of
|
||||
# restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into
|
||||
@@ -215,28 +162,21 @@ secretEnv:
|
||||
# with signing enabled, because such a key rejects every unsigned request. Leave empty
|
||||
# otherwise. The endpoint itself is not a secret and is set under env.AMAP_API_BASE.
|
||||
AMAP_API_SECRET: ""
|
||||
# Optional key issued for this installation by the TREK services. Wins over the key TREK
|
||||
# registers by itself and turns that registration off. Leave empty to let TREK register.
|
||||
TREK_SERVICES_KEY: ""
|
||||
# Optional Web Push key pair, private half (base64url, 32 bytes). Only used together with
|
||||
# env.VAPID_PUBLIC_KEY; a pair whose halves do not belong together, or only one half, turns
|
||||
# push off with an error in the log until it is fixed, and every device stays registered.
|
||||
# Leave both empty to let TREK keep a generated pair in its database.
|
||||
VAPID_PRIVATE_KEY: ""
|
||||
|
||||
# If true, a random ENCRYPTION_KEY is generated at install and preserved across upgrades.
|
||||
# Only with helm install/upgrade against the cluster: under `helm template`, ArgoCD or Flux
|
||||
# the chart cannot read the existing secret and renders a new key every time. TREK then
|
||||
# refuses to start rather than lose its secrets; use existingSecret in those setups.
|
||||
# If true, a random ENCRYPTION_KEY is generated at install and preserved across upgrades
|
||||
generateEncryptionKey: false
|
||||
|
||||
# If set, the chart renders no Secret of its own and instead reads every secret env
|
||||
# var from this existing Kubernetes secret. Expected keys: ENCRYPTION_KEY (rename via
|
||||
# existingSecretKey), ADMIN_EMAIL, ADMIN_PASSWORD, OIDC_CLIENT_SECRET,
|
||||
# UNSPLASH_ACCESS_KEY, PLACES_API_KEY, AMAP_API_KEY, AMAP_API_SECRET, TREK_SERVICES_KEY,
|
||||
# VAPID_PRIVATE_KEY, SMTP_PASS, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_ADMIN_PASS.
|
||||
# Missing keys are simply left unset (they are optional), so only provide the ones your
|
||||
# setup needs.
|
||||
# UNSPLASH_ACCESS_KEY, PLACES_API_KEY, AMAP_API_KEY, AMAP_API_SECRET,
|
||||
# VAPID_PRIVATE_KEY. Missing keys are simply left unset (they are optional), so only
|
||||
# provide the ones your setup needs.
|
||||
existingSecret: ""
|
||||
existingSecretKey: ENCRYPTION_KEY
|
||||
|
||||
@@ -262,54 +202,20 @@ persistence:
|
||||
# httpGet handler. Switching handler means clearing the old one in the same override
|
||||
# (httpGet: null together with tcpSocket), otherwise the API rejects the pod with
|
||||
# "may not specify more than 1 handler type". Set probes.liveness to null to drop a probe.
|
||||
#
|
||||
# The startup probe gives a first boot, a long migration or a restore at boot up to ten
|
||||
# minutes before liveness takes over; liveness alone killed such a boot after about
|
||||
# 105 s, and the next start began it again. Readiness asks the database, so a pod whose
|
||||
# database does not answer stops getting traffic without being restarted.
|
||||
probes:
|
||||
startup:
|
||||
httpGet:
|
||||
path: /api/health
|
||||
port: http
|
||||
periodSeconds: 10
|
||||
failureThreshold: 60
|
||||
liveness:
|
||||
httpGet:
|
||||
path: /api/health
|
||||
port: http
|
||||
port: 3000
|
||||
initialDelaySeconds: 15
|
||||
periodSeconds: 30
|
||||
readiness:
|
||||
httpGet:
|
||||
path: /api/health/ready
|
||||
port: http
|
||||
path: /api/health
|
||||
port: 3000
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
|
||||
# Further environment variables, for any setting the env block above does not list.
|
||||
# extraEnv:
|
||||
# - name: SESSION_DURATION
|
||||
# value: 7d
|
||||
extraEnv: []
|
||||
# Whole ConfigMaps or Secrets:
|
||||
# extraEnvFrom:
|
||||
# - secretRef:
|
||||
# name: trek-smtp
|
||||
extraEnvFrom: []
|
||||
|
||||
# Further volumes for the pod. The chart does not create the objects they name.
|
||||
# extraVolumes:
|
||||
# - name: kitinerary-extractors
|
||||
# configMap:
|
||||
# name: trek-kitinerary-extractors
|
||||
extraVolumes: []
|
||||
# Where the trek container mounts them. For example, KItinerary
|
||||
# loads extractors for the booking import from this path:
|
||||
# extraVolumeMounts:
|
||||
# - name: kitinerary-extractors
|
||||
# mountPath: /usr/local/share/kitinerary/extractors
|
||||
# readOnly: true
|
||||
extraVolumeMounts: []
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
@@ -330,20 +236,3 @@ ingress:
|
||||
# - secretName: chart-example-tls
|
||||
# hosts:
|
||||
# - chart-example.local
|
||||
|
||||
httpRoute:
|
||||
enabled: false
|
||||
annotations: {}
|
||||
parentRefs: []
|
||||
# - name: gateway
|
||||
# namespace: gateway-system
|
||||
# sectionName: https
|
||||
hostnames: []
|
||||
# - trek.example.com
|
||||
paths:
|
||||
- /
|
||||
# Timeout fields are Standard Channel in Gateway API v1.2; controller support varies.
|
||||
# Leave empty for controller defaults. Use "0s" to disable the corresponding timeout.
|
||||
timeouts: {}
|
||||
# request: "0s"
|
||||
# backendRequest: "0s"
|
||||
|
||||
@@ -7,7 +7,3 @@ playwright/.cache/
|
||||
# vite-plugin-pwa dev output (devOptions.enabled)
|
||||
dev-dist/
|
||||
e2e/help/media.env
|
||||
|
||||
# The native apps' address screen (npm run build:native), copied into
|
||||
# android/ and ios/ by `cap sync`
|
||||
native-dist/
|
||||
|
||||
@@ -8,28 +8,15 @@ Scope: the **`@trek/client`** workspace (React 19 + Vite + Zustand + Tailwind PW
|
||||
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 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)
|
||||
npm run lint:warnings # eslint (typed), failing on any error and on any warning count per rule above scripts/eslint-baseline.json and on any entry above its count (app code, tests and eslint-disable'd messages counted apart; a `/* eslint <rule>: ... */` config comment fails outright; --update lowers it). Frozen as warnings: floating/misused promises, `.catch(() => {})` (trek/no-swallowed-catch), react-hooks v7 recommended, complexity/max-depth/max-params/max-lines-per-function (120 per .ts function, 300 per .tsx), `use*Store()` without a selector, `window.__*` and window.dispatchEvent buses (trek/no-window-globals), no-console, no-non-null-assertion; the local rules live in scripts/lib/eslint-rules.mjs
|
||||
npm run lint # eslint . (lint:check in CI)
|
||||
npm run lint:pages # enforce the Page pattern (CI gate)
|
||||
npm run lint:rtl # physical left/right sides and rtl-lint-disable comments may only shrink per file (CI gate; --list shows them, --update lowers both baselines)
|
||||
npm run lint:size # no source file or stylesheet past 1000 lines, no test (Playwright specs and fixtures under e2e/ included) past 2000, counted wrapped at 120 columns; longer ones may only shrink (CI gate; --update lowers the baseline)
|
||||
npm run lint:format # Prettier: every .ts/.tsx/.mjs/.css file under src/, tests/, e2e/ and scripts/ outside scripts/format-baseline.json must be formatted, the list only shrinks (CI gate; npx prettier --write <file>, then --update)
|
||||
npm run lint:layers # imports go downwards: components never import pages/ or mobile/, nothing under the views imports a view; per-file counts may only shrink (CI gate; --list, --update)
|
||||
npm run lint:offline # no view file (components/mobile/pages/hooks) imports src/api/ beyond scripts/offline-baseline.json, which only shrinks (CI gate; --list, --update)
|
||||
npm run lint:pairs # each desktop/phone pair in scripts/feature-pairs.json imports its shared hooks, and every file under src/mobile/screens is listed there, in a pair or under mobileOnly with a reason (CI gate; --list prints the pairs)
|
||||
npm run lint:dup # copied code: the lines of a file inside a block that repeats elsewhere (100 tokens over 10 lines, SonarCloud's thresholds; .ts and .tsx read as one language) may only shrink against scripts/dup-baseline.json (CI gate; --list shows each block with its other side, --update lowers it)
|
||||
npm run lint:skips # no .only anywhere; skipped/todo/fixme tests per file may only shrink against scripts/skip-baseline.json (CI gate; skipIf/runIf and Playwright's test.skip(condition, 'why') are fine, but skipIf(true) and runIf(false) count as skips)
|
||||
npm run lint:i18n-keys # every translation key src/ names exists in shared en, and en keys nothing in src/, server/src or plugin-sdk/src reaches may only shrink per en file against scripts/i18n-unused-baseline.json (CI gate; --unused lists them, --update lowers the baseline)
|
||||
npm run test # vitest run (tests/** + co-located src/**/*.test.{ts,tsx}); also test:unit / test:integration / test:coverage
|
||||
npm run e2e # Playwright (CI runs --project=public --project=app; e2e:report opens the last report)
|
||||
npm run e2e # Playwright (local only; e2e:report opens the last report)
|
||||
npm run shots # Playwright screenshot project (shots:promote to accept)
|
||||
npm run theme:lint # colour literals, palette classes, raw text sizes, z-index literals above z-50 and dark_mode reads may only shrink per file, theme-lint-disable markers too (CI gate; --list shows them, --update lowers both baselines)
|
||||
npm run check:gl-split # after build: fails if one chunk bundles both mapbox-gl and maplibre-gl (CI gate)
|
||||
npm run theme:lint # theme conformance audit (theme:lint:strict exits 1; local only)
|
||||
npm run check:gl-split # after build: fails if one chunk bundles both mapbox-gl and maplibre-gl (local only)
|
||||
```
|
||||
|
||||
Every baseline ratchet above also fails on an entry that allows more than the tree holds: a count above what its file or rule has now, or a file that is gone. Run the check with `--update` in the change that made it smaller, so a fixed file cannot grow back to its old entry and a new file at a deleted path does not inherit one.
|
||||
|
||||
Single test: `npx vitest run src/store/slices/budgetSlice.test.ts`, or `npx vitest run -t "optimistically adds the place"`.
|
||||
|
||||
The dev server needs the API on **:3001** — run `npm run dev` at the repo root to start both.
|
||||
@@ -45,16 +32,15 @@ The layering is **component → feature hook → store/slice → `repo/` → `ap
|
||||
- **`src/store/`** — Zustand. `tripStore.ts` is composed from slices in `store/slices/`; `slices/remoteEventHandler.ts` applies inbound WebSocket events to local state.
|
||||
- **`src/repo/`** — per-entity repositories mediating between the network and the offline cache: online, call REST and upsert into Dexie; offline, read Dexie. Always go through a repo for trip data.
|
||||
- **`src/api/client.ts`** — the single Axios instance, typed from `@trek/shared`. New API surface goes in a per-domain `api/<domain>.ts`, not the god module.
|
||||
- **`src/db/offlineDb.ts`** — the Dexie schema. Database and table names are the on-device contract — renaming one orphans every user's cache. Versions are append-only: a new `this.version(N)` adds its stores to `HISTORY` and a case to `UPGRADE_CASES` in `tests/unit/db/offlineDb.upgrade.test.ts`, which opens the previous version with seeded rows in fake-indexeddb and upgrades it to the current one; a guard there fails on a declared version without both. Never edit a shipped version's stores or `upgrade()`.
|
||||
- **`src/sync/`**: in `mutationQueue.ts`, offline writes do an optimistic Dexie write (temporary **negative id** for creates), then `flush()` replays REST on reconnect with the mutation's UUID as the **`X-Idempotency-Key`** header (matching the server interceptor) and reconciles the row. Writes to one entity keep their order: a write parked as `failed` or `conflict` holds back the later writes to the same `resource` + entity id until the user retries, resolves or discards it, and only that action deletes a parked row (trip eviction never does). Every row `enqueue()` writes carries `schemaVersion` (`MUTATION_SCHEMA_VERSION` in `offlineDb.ts`) and `buildVersion`; bump the constant when a row's fields or the way the replay reads them change incompatibly. A flush replays its own format and older ones (an unstamped row is format 1) and skips a row from a newer format without sending, marking or dropping it, holding back the later writes to its entity, so a tab still on an older bundle never replays a shape it does not know. The guard exists only from the release that introduced `schemaVersion` on; a bundle older than that replays every row, so the first bump of `MUTATION_SCHEMA_VERSION` must not ship while a rollback target older than the guard is still in play. A skipped row stays `pending` with no retry or discard path, so on a rolled-back install it holds its entity until the user clears the cache. Repos whose writes carry no version token (visits, day clears, tours, driving settings) ask `mutationQueue.mustQueue()` before an online write and queue it while an older write to the entity is still queued, so a retried write cannot land over a newer one made here online; places and packing items send `X-Base-Updated-At`, so the server refuses the stale replay with a 409 instead. `flush()` takes the Web Lock `trek-mutation-flush:<db name>` so only one tab replays at a time; a tab that finds it taken waits for it, and a `flush()` called while this tab's flush runs or waits for the lock gets that same flush back (with one more pass asked for), so `flush()` never resolves while a tab is still replaying and a re-seed chained onto it cannot lay older server rows over those writes (the in-tab flush alone where the API is missing). The rest of the directory drives reconnection sync, the auth gate that stops background loops before logout swaps the DB, offline preferences, and map pre-download (raster and vector prefetchers).
|
||||
- **`src/db/offlineDb.ts`** — the Dexie schema. Database and table names are the on-device contract — renaming one orphans every user's cache.
|
||||
- **`src/sync/`** — `mutationQueue.ts`: offline writes do an optimistic Dexie write (temporary **negative id** for creates), then `flush()` replays REST on reconnect with the mutation's UUID as the **`X-Idempotency-Key`** header (matching the server interceptor) and reconciles the row. The rest of the directory drives reconnection sync, the auth gate that stops background loops before logout swaps the DB, offline preferences, and map pre-download (raster and vector prefetchers).
|
||||
|
||||
## Rules for new code
|
||||
|
||||
The offline core is flagship work surrounded by a periphery that ignores it. New code extends the core's discipline, not the periphery's shortcuts:
|
||||
|
||||
- **One data path, no layer skips.** Never import `api/client` (or raw fetch/axios) from a component or modal, and especially never *write* from one. `lint:offline` enforces it: a file under `components/`, `mobile/`, `pages/` or `hooks/` may not import anything from `src/api/` except types. The long tail that already does is listed in `scripts/offline-baseline.json`; the list only shrinks (a file that stops leaves it via `--update`) and is debt, not precedent. A domain that is online-only on purpose (admin, auth) still puts its calls in a store or repo, not in the view.
|
||||
- **One data path, no layer skips.** Never import `api/client` (or raw fetch/axios) from a component or modal — especially never *write* from one. A long tail of existing files bypasses the layering and no lint ratchet holds the line yet; that is debt, not precedent.
|
||||
- **Offline-first is the product promise.** New domains get a repo with read-through and offline writes (temp id → optimistic Dexie write → idempotent queue entry). If a domain is deliberately online-only, say so explicitly.
|
||||
- **Imports go downwards** (`lint:layers`, rules in `scripts/lib/layers.mjs`). A component never imports `pages/` or `mobile/`, a shared hook no view, and stores, repos, sync, api, db and the helpers no view at all; a file directly in `src/` is the layer of its name, so `src/types.ts` follows the `types/` rules. A model or helper both sides need moves down (`utils/`, `hooks/`, `types/`); the counts in `scripts/layers-baseline.json` are debt, not precedent.
|
||||
- **No god components or god hooks.** The page pattern is a floor, not a ceiling. Decompose hooks by concern, split renders into memoizable sections, and don't pass huge prop bags with inline-arrow callbacks.
|
||||
- **Prefer React 19 idioms**: `useOptimistic`, `useActionState`/`useFormStatus`, `use()` + Suspense, `useSyncExternalStore` for external subscriptions (`hooks/useNetworkMode` is the reference).
|
||||
- **Optimistic writes must reconcile** — rollback + user-visible toast on failure. No `.catch(() => {})`, no bare `catch {}`.
|
||||
@@ -64,25 +50,19 @@ The offline core is flagship work surrounded by a periphery that ignores it. New
|
||||
- **Rendering security**: never interpolate user content into HTML strings (map popups included — build via DOM + `textContent`, or `escapeHtml` from `@trek/shared`); untrusted markdown gets `rehype-sanitize`; never `rehype-raw` near it.
|
||||
- **No `window` event buses or global mutable `window` state.** No `any` at boundaries: WS payloads and map renderer props get real types.
|
||||
- **Hygiene**: error boundaries around new shells/routes (`components/shared/ErrorBoundary.tsx`); every async `.then(setState)` needs a cancelled flag or `AbortController`; no routine `eslint-disable exhaustive-deps` (a missing dep has already shipped wrong money on screen); no sequential-await N+1 fetch loops; search for an existing utility before writing a duplicate.
|
||||
- **Theming**: use the semantic Tailwind tokens defined in `tailwind.config.js` (`bg-surface*`, `text-content*`, `border-edge*`, `bg-accent*`, status colors) — no palette classes, hex literals, arbitrary-value color classes, or invented CSS vars. Only `applyAppearance()` in `src/theme/` mutates `<html>` styling (see `src/theme/README.md`). `theme:lint` counts literals, `bg-[#...]`-style and palette classes, raw `text-sm`- and `text-[13px]`-style sizes, z-index literals and `dark_mode` reads per file against `scripts/theme-baseline.json`.
|
||||
- **Theming**: use the semantic Tailwind tokens defined in `tailwind.config.js` (`bg-surface*`, `text-content*`, `border-edge*`, `bg-accent*`, status colors) — no palette classes, hex literals, arbitrary-value color classes, or invented CSS vars. Only `applyAppearance()` in `src/theme/` mutates `<html>` styling (see `src/theme/README.md`). `theme:lint` catches literals and `bg-[#...]`-style classes but not named palette classes — review those by hand.
|
||||
|
||||
## Big-picture pieces
|
||||
|
||||
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working; the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other.
|
||||
- **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled; every other locale is a dynamic `import('@trek/shared/i18n/<locale>')` so Vite emits one chunk per locale. Strings live in `shared/`, never here. `t()` returns an unknown key unchanged, so `lint:i18n-keys` (`scripts/i18n-keys.mjs`) resolves every literal key in `t()`, `tHtml()`, `tr()`, `<TransHtml html>`, `translateApiError` and `*Key` props against `shared/src/i18n/en`; a template whose interpolations only choose between string literals is expanded and each branch checked as a key; any other template key is read with each interpolation as one key segment and passes by itself only when it reaches between 1 and `MAX_IMPLICIT_MATCHES` (30) en keys; a wider one, or one with no fixed dotted prefix, needs a `DYNAMIC_ALLOWED` entry keyed by file and template that says what bounds the value, and an entry the check no longer needs fails. Pass counts as numbers, and let a plural group pick the wording instead of switching keys on the count.
|
||||
- **Mobile shell** (`src/mobile/`): below the phone breakpoint (`useIsPhone`) `App.tsx` wraps routes in `MobileShell` and the `M*` screens under `mobile/screens/` take over. A UI change to a domain with an `M*` twin usually needs both, and the logic change goes into the shared hook (see "Desktop and phone views" below).
|
||||
- **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled; every other locale is a dynamic `import('@trek/shared/i18n/<locale>')` so Vite emits one chunk per locale. Strings live in `shared/`, never here.
|
||||
- **Mobile shell** (`src/mobile/`): below the phone breakpoint (`useIsPhone`) `App.tsx` wraps routes in `MobileShell` and the `M*` screens under `mobile/screens/` take over. A UI change to a domain with an `M*` twin usually needs both — and the shared-hook rule below.
|
||||
- **Plugins UI** (`src/components/Plugins/`): third-party surfaces render only inside the sandboxed `PluginFrame` iframe (postMessage bridge, live theme-token sync). Host-rendered contribution points (widgets, schedule rows, map layers, planner columns/actions) render server-normalized primitives only — plugin markup never runs inline. Authoring is covered by the `trek-plugin-dev` skill.
|
||||
- **Managed installs** (`src/managed/index.tsx`): the attachment point for screens that only exist on a centrally administered install. Empty here by design — an operator replaces it at build time. Don't put features there.
|
||||
|
||||
## Desktop and phone views
|
||||
## Desktop ↔ mobile shells and the SonarQube duplication gate
|
||||
|
||||
Most features have a desktop view (`components/`, `pages/`) and a phone view (`mobile/screens/`). They share one hook or model per feature that holds the logic (state, effects, loading, handlers, validation, derived values, store and repo calls); each view keeps only its own markup, layout and dialogs or sheets. `useInstanceSettings` and `useRangeBypass` under `components/Admin/` show the shape. `scripts/feature-pairs.json` lists every pair with its hooks.
|
||||
|
||||
- **Changing a feature:** change the shared hook, not one view. A behaviour that really differs between the two views is a parameter of the hook, so both stay visible in one place and its test covers both.
|
||||
- **A new feature with both views:** write the hook first under `components/<Feature>/` (or `hooks/`/`utils/` when it is not bound to one feature; a page's own logic stays in its `use<Page>` hook and models in `pages/<page>/`, which the phone shell imports too), give it its own test, build both views on it and add the pair to `scripts/feature-pairs.json`.
|
||||
- **A new phone screen:** list it in `scripts/feature-pairs.json`, as a view of the pair whose hook it runs on or under `mobileOnly` with the reason it has no twin. A file under `mobile/screens/` that is in neither fails `lint:pairs`.
|
||||
|
||||
Two CI gates hold this: `lint:pairs` fails when a listed view stops importing its pair's hook or a phone screen is not listed, and `lint:dup` holds the lines inside copied blocks to `scripts/dup-baseline.json`, so a copy that looks alike fails too. SonarCloud allows **≤ 3% duplicated lines on the PR's new code**, so the same lines added to both views fail a PR by themselves. Full gate rules in the root `CLAUDE.md`.
|
||||
Every desktop component with a phone twin is a deliberate copy that is already heavily duplicated. CI's SonarCloud gate allows **≤ 3% duplicated lines on the PR's new code**, so adding the same lines to both shells fails the PR by itself. Put logic in one shared hook/module (`useInstanceSettings`, `useRangeBypass` under `components/Admin/` are the pattern) and keep only markup in each shell. Full gate rules in the root `CLAUDE.md`.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
|
||||
|
||||
# Built application files
|
||||
*.apk
|
||||
*.aar
|
||||
*.ap_
|
||||
*.aab
|
||||
|
||||
# Files for the ART/Dalvik VM
|
||||
*.dex
|
||||
|
||||
# Java class files
|
||||
*.class
|
||||
|
||||
# Generated files
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
# Uncomment the following line in case you need and you don't have the release build type files in your app
|
||||
# release/
|
||||
|
||||
# Gradle files
|
||||
.gradle/
|
||||
build/
|
||||
|
||||
# Local configuration file (sdk path, etc)
|
||||
local.properties
|
||||
|
||||
# Proguard folder generated by Eclipse
|
||||
proguard/
|
||||
|
||||
# Log Files
|
||||
*.log
|
||||
|
||||
# Android Studio Navigation editor temp files
|
||||
.navigation/
|
||||
|
||||
# Android Studio captures folder
|
||||
captures/
|
||||
|
||||
# IntelliJ
|
||||
*.iml
|
||||
.idea/workspace.xml
|
||||
.idea/tasks.xml
|
||||
.idea/gradle.xml
|
||||
.idea/assetWizardSettings.xml
|
||||
.idea/dictionaries
|
||||
.idea/libraries
|
||||
# Android Studio 3 in .gitignore file.
|
||||
.idea/caches
|
||||
.idea/modules.xml
|
||||
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
|
||||
.idea/navEditor.xml
|
||||
|
||||
# Keystore files and store credentials. The upload key and the Play service
|
||||
# account live only in the release workflow's secrets and in the owner's
|
||||
# offline backup, never in the repository.
|
||||
*.jks
|
||||
*.keystore
|
||||
keystore.properties
|
||||
*service-account*.json
|
||||
|
||||
# External native build folder generated in Android Studio 2.2 and later
|
||||
.externalNativeBuild
|
||||
.cxx/
|
||||
|
||||
# Google Services (e.g. APIs or Firebase)
|
||||
# Push is not wired up and the build does not apply the google-services plugin,
|
||||
# so no CI secret is needed. Kept ignored so a stray Firebase config never lands
|
||||
# in the repository.
|
||||
google-services.json
|
||||
app/google-services.json
|
||||
|
||||
# Freeline
|
||||
freeline.py
|
||||
freeline/
|
||||
freeline_project_description.json
|
||||
|
||||
# fastlane
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots
|
||||
fastlane/test_output
|
||||
fastlane/readme.md
|
||||
|
||||
# Version control
|
||||
vcs.xml
|
||||
|
||||
# lint
|
||||
lint/intermediates/
|
||||
lint/generated/
|
||||
lint/outputs/
|
||||
lint/tmp/
|
||||
# lint/reports/
|
||||
|
||||
# Android Profiling
|
||||
*.hprof
|
||||
|
||||
# Cordova plugins for Capacitor
|
||||
capacitor-cordova-android-plugins
|
||||
|
||||
# Copied web assets
|
||||
app/src/main/assets/public
|
||||
|
||||
# Generated Config files
|
||||
app/src/main/assets/capacitor.config.json
|
||||
app/src/main/assets/capacitor.plugins.json
|
||||
app/src/main/res/xml/config.xml
|
||||
|
||||
# Kotlin compiler caches
|
||||
.kotlin/
|
||||
@@ -1,2 +0,0 @@
|
||||
/build/*
|
||||
!/build/.npmkeep
|
||||
@@ -1,116 +0,0 @@
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
apply plugin: 'org.jetbrains.kotlin.plugin.compose'
|
||||
|
||||
android {
|
||||
namespace = "com.liketrek.trek"
|
||||
compileSdk = rootProject.ext.compileSdkVersion
|
||||
defaultConfig {
|
||||
applicationId "com.liketrek.trek"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
// The release workflow (.github/workflows/native-release.yml) passes both:
|
||||
// the version from client/package.json and a build number that only grows.
|
||||
// Local and PR builds fall back to these placeholders.
|
||||
versionCode((project.findProperty('trekVersionCode') ?: '1') as Integer)
|
||||
versionName(project.findProperty('trekVersionName') ?: '0.0.0-dev')
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
||||
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
||||
}
|
||||
}
|
||||
// The upload key only exists in the release workflow, which decodes it from a
|
||||
// secret and passes its path and passwords as Gradle properties. Every other
|
||||
// build (local, fork, PR) stays unsigned and needs no secret.
|
||||
signingConfigs {
|
||||
release {
|
||||
if (project.hasProperty('trekKeystore')) {
|
||||
storeFile file(project.property('trekKeystore'))
|
||||
storePassword project.property('trekKeystorePassword')
|
||||
keyAlias project.property('trekKeyAlias')
|
||||
keyPassword project.property('trekKeyPassword')
|
||||
}
|
||||
}
|
||||
}
|
||||
// java.time in the widgets and the travel-day notification, back to Android 7.
|
||||
compileOptions {
|
||||
coreLibraryDesugaringEnabled true
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
// The app's languages, for the system's per-app language setting (Android 13+):
|
||||
// generated from the values-* folders, so a language added there is offered too.
|
||||
androidResources {
|
||||
generateLocaleConfig = true
|
||||
}
|
||||
testOptions {
|
||||
unitTests {
|
||||
includeAndroidResources = true
|
||||
returnDefaultValues = true
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
if (project.hasProperty('trekKeystore')) {
|
||||
signingConfig signingConfigs.release
|
||||
}
|
||||
minifyEnabled true
|
||||
shrinkResources true
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
flatDir{
|
||||
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||
implementation "androidx.browser:browser:$androidxBrowserVersion"
|
||||
implementation "androidx.biometric:biometric:1.1.0"
|
||||
implementation "androidx.core:core-ktx:$androidxCoreVersion"
|
||||
coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:2.1.5"
|
||||
// Home-screen widgets.
|
||||
implementation "androidx.glance:glance-appwidget:$glanceVersion"
|
||||
implementation "androidx.glance:glance-material3:$glanceVersion"
|
||||
// The share sheet and the widget's trip picker.
|
||||
implementation platform("androidx.compose:compose-bom:$composeBomVersion")
|
||||
implementation "androidx.compose.material3:material3"
|
||||
implementation "androidx.compose.material:material-icons-extended"
|
||||
implementation "androidx.compose.ui:ui-tooling-preview"
|
||||
debugImplementation "androidx.compose.ui:ui-tooling"
|
||||
implementation "androidx.activity:activity-compose:$androidxActivityVersion"
|
||||
// A foldable's posture and hinge, and the window's size, for the UI.
|
||||
implementation "androidx.window:window:1.4.0"
|
||||
// Ranks the trip shortcuts in the share sheet on Android 10 and earlier.
|
||||
implementation "androidx.sharetarget:sharetarget:1.2.0"
|
||||
// TREK Cloud subscriptions through Google Play, the counterpart of StoreKit.
|
||||
implementation "com.android.billingclient:billing:$playBillingVersion"
|
||||
// Push through liketrek's relay. No google-services plugin: Firebase reads
|
||||
// its project from res/values/firebase.xml, the strings the plugin would generate.
|
||||
implementation "com.google.firebase:firebase-messaging:24.1.2"
|
||||
implementation project(':capacitor-android')
|
||||
testImplementation "junit:junit:$junitVersion"
|
||||
testImplementation "org.json:json:20250517"
|
||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||
implementation project(':capacitor-cordova-android-plugins')
|
||||
}
|
||||
|
||||
apply from: 'capacitor.build.gradle'
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
||||
|
||||
android {
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
}
|
||||
}
|
||||
|
||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||
dependencies {
|
||||
implementation project(':capacitor-app')
|
||||
implementation project(':capacitor-filesystem')
|
||||
implementation project(':capacitor-haptics')
|
||||
implementation project(':capacitor-keyboard')
|
||||
implementation project(':capacitor-share')
|
||||
implementation project(':capacitor-splash-screen')
|
||||
implementation project(':capacitor-status-bar')
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (hasProperty('postBuildExtras')) {
|
||||
postBuildExtras()
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
|
||||
# TREK's own classes: TrekShellPlugin is reached from JavaScript by name and its
|
||||
# methods through reflection, so R8 must neither rename nor drop them.
|
||||
-keep class com.liketrek.trek.** { *; }
|
||||
|
||||
# Every Capacitor plugin: the bridge finds plugins by their annotation and calls
|
||||
# the annotated methods reflectively.
|
||||
-keep @com.getcapacitor.annotation.CapacitorPlugin public class * {
|
||||
@com.getcapacitor.PluginMethod public <methods>;
|
||||
}
|
||||
|
||||
# The WebView bridge: Capacitor's message handler is called from JavaScript
|
||||
# through @JavascriptInterface, and every plugin class is instantiated by name.
|
||||
-keepclassmembers class * {
|
||||
@android.webkit.JavascriptInterface <methods>;
|
||||
}
|
||||
-keep public class * extends com.getcapacitor.Plugin
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Debug builds only: the widget gallery (debug/WidgetGalleryActivity.kt). -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<activity
|
||||
android:name=".debug.WidgetGalleryActivity"
|
||||
android:theme="@style/AppTheme.NoActionBar"
|
||||
android:exported="true" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -1,125 +0,0 @@
|
||||
package com.liketrek.trek.debug
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.util.TypedValue
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ScrollView
|
||||
import android.widget.TextView
|
||||
import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi
|
||||
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.CollabWidget
|
||||
import com.liketrek.trek.widget.PackingWidget
|
||||
import com.liketrek.trek.widget.TodayWidget
|
||||
import com.liketrek.trek.widget.TodosWidget
|
||||
import com.liketrek.trek.widget.TrekSizes
|
||||
import com.liketrek.trek.widget.TrekWidget
|
||||
import com.liketrek.trek.widget.TrekWidgetTheme
|
||||
import com.liketrek.trek.widget.TripWidget
|
||||
import com.liketrek.trek.widget.WidgetSamples
|
||||
import com.liketrek.trek.widget.WidgetStore
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Debug builds only: every widget at every size, drawn by the real Glance code
|
||||
* into real RemoteViews, so they can be looked at and screenshot without placing
|
||||
* each on a home screen.
|
||||
*
|
||||
* adb shell am start -n com.liketrek.trek/.debug.WidgetGalleryActivity --es widget trip --ez running true --ez dark false
|
||||
*
|
||||
* --es seed sample also writes the sample trip as the app's snapshot, so the
|
||||
* placed widgets, the share sheet and the shortcuts have a trip to show; and
|
||||
* --ez tripday true posts the travel day's Live Update from the sample.
|
||||
*/
|
||||
@OptIn(ExperimentalGlanceRemoteViewsApi::class)
|
||||
class WidgetGalleryActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val running = intent.getBooleanExtra("running", true)
|
||||
val dark = intent.getBooleanExtra("dark", false)
|
||||
val only = intent.getStringExtra("widget")
|
||||
if (intent.getStringExtra("seed") == "sample") seed()
|
||||
if (intent.getBooleanExtra("tripday", false)) {
|
||||
TripDayNotification.show(
|
||||
this,
|
||||
TripDayNotification.State(
|
||||
"Autumn in Kyoto", "/trips/1", "Day 3 of 9", "Kiyomizu-dera", "13:30", 810, 2, 5,
|
||||
listOf("#D6273B", "#E8A13A", "#2FA37A", "#4A7DDB", "#8E6CD9"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val config = Configuration(resources.configuration).apply {
|
||||
uiMode = (uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO
|
||||
}
|
||||
val themed = createConfigurationContext(config)
|
||||
val list = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(px(16), px(if (intent.getBooleanExtra("bare", false)) 96 else 32), px(16), px(32))
|
||||
val bg = intent.getStringExtra("bg")
|
||||
setBackgroundColor(if (bg != null) Color.parseColor("#$bg") else if (dark) Color.rgb(28, 27, 31) else Color.rgb(222, 226, 236))
|
||||
}
|
||||
setContentView(ScrollView(this).apply { addView(list) })
|
||||
|
||||
val widgets: List<Pair<String, TrekWidget>> = listOf(
|
||||
"trip" to TripWidget(),
|
||||
"today" to TodayWidget(),
|
||||
"bookings" to BookingsWidget(),
|
||||
"todos" to TodosWidget(),
|
||||
"packing" to PackingWidget(),
|
||||
"atlas" to AtlasWidget(),
|
||||
"collab" to CollabWidget(),
|
||||
).filter { only == null || it.first == only }
|
||||
// --ez store true draws what the app really wrote, instead of the sample trip.
|
||||
val snapshot = if (intent.getBooleanExtra("store", false)) WidgetStore.load(this) else WidgetSamples.snapshot(running)
|
||||
CoroutineScope(Dispatchers.Main).launch {
|
||||
for ((name, widget) in widgets) {
|
||||
if (!intent.getBooleanExtra("bare", false)) list.addView(TextView(this@WidgetGalleryActivity).apply {
|
||||
text = name
|
||||
setTextColor(if (dark) Color.WHITE else Color.DKGRAY)
|
||||
setPadding(0, px(12), 0, px(6))
|
||||
})
|
||||
val onlySize = intent.getStringExtra("size")
|
||||
val sizes = listOf("small" to TrekSizes.SMALL, "wide" to TrekSizes.WIDE, "large" to TrekSizes.LARGE)
|
||||
for ((sizeName, size) in sizes) {
|
||||
if (onlySize != null && onlySize != sizeName) continue
|
||||
val result = GlanceRemoteViews().compose(themed, size) {
|
||||
TrekWidgetTheme.Themed { widget.Content(snapshot) }
|
||||
}
|
||||
val host = FrameLayout(this@WidgetGalleryActivity)
|
||||
host.addView(result.remoteViews.apply(themed, host), FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||
list.addView(host, LinearLayout.LayoutParams(px(size.width.value), px(size.height.value)).apply { bottomMargin = px(12) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun seed() {
|
||||
WidgetStore.write(this, "snapshot", WidgetSamples.json(running = true))
|
||||
WidgetStore.write(this, "trip.1", WidgetSamples.json(running = true))
|
||||
WidgetStore.write(this, "trip.2", WidgetSamples.json(running = false).replace("Autumn in Kyoto", "Lisbon long weekend"))
|
||||
WidgetStore.write(
|
||||
this,
|
||||
"trips",
|
||||
"""[{"id":1,"title":"Autumn in Kyoto","start":"${java.time.LocalDate.now().minusDays(2)}","end":"${java.time.LocalDate.now().plusDays(6)}"},
|
||||
{"id":2,"title":"Lisbon long weekend","start":"${java.time.LocalDate.now().plusDays(12)}","end":"${java.time.LocalDate.now().plusDays(15)}"},
|
||||
{"id":3,"title":"Norway by train","start":"2026-06-02","end":"2026-06-12"}]""",
|
||||
)
|
||||
com.liketrek.trek.widget.TrekWidgetUpdater.refreshAll(this)
|
||||
com.liketrek.trek.share.TrekShortcuts.publish(this)
|
||||
}
|
||||
|
||||
private fun px(dp: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics).toInt()
|
||||
|
||||
private fun px(dp: Int): Int = px(dp.toFloat())
|
||||
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:resizeableActivity="true"
|
||||
android:theme="@style/AppTheme">
|
||||
|
||||
<!-- Every window shape a tablet, a foldable, ChromeOS or desktop windowing
|
||||
offers. The UI lays itself out by the window's size (hooks/sizeClass.ts),
|
||||
so the activity takes size, fold and orientation changes itself
|
||||
(configChanges) instead of restarting and losing the page. -->
|
||||
<meta-data android:name="android.supports_size_changes" android:value="true" />
|
||||
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|smallestScreenSize|screenLayout|uiMode|navigation|density|fontScale|touchscreen|colorMode|fontWeightAdjustment"
|
||||
android:name=".MainActivity"
|
||||
android:label="@string/title_activity_main"
|
||||
android:theme="@style/AppTheme.NoActionBarLaunch"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="fullUser"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:exported="true">
|
||||
|
||||
<!-- The trips as launcher and direct-share shortcuts (TrekShortcuts). -->
|
||||
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!-- Deep links.
|
||||
|
||||
The scheme is @string/custom_url_scheme (com.liketrek.trek).
|
||||
launchMode is singleTask above, so a link delivers into the
|
||||
running task via onNewIntent rather than starting a second copy
|
||||
of the app on top of the first.
|
||||
|
||||
This is the return path for SSO and passkey sign-in: TrekShell
|
||||
opens the server's login page in a Custom Tab, and after the
|
||||
hand-off it redirects to com.liketrek.trek://auth?code=…, which
|
||||
lands here and in TrekShellPlugin.handleOnNewIntent.
|
||||
|
||||
Not an App Link (autoVerify + https). App Links are verified
|
||||
against a specific domain via assetlinks.json, and TREK is
|
||||
self-hosted — there is no single domain to verify against. A
|
||||
custom scheme is the only form that works for every user's
|
||||
server. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="@string/custom_url_scheme" />
|
||||
</intent-filter>
|
||||
|
||||
</activity>
|
||||
|
||||
<!-- "TREK" in the share sheet and "Open with TREK": a booking document, a
|
||||
mail, a page or a link, into a trip (share/ShareActivity.kt). -->
|
||||
<activity
|
||||
android:name=".share.ShareActivity"
|
||||
android:theme="@style/AppTheme.Sheet"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation"
|
||||
android:excludeFromRecents="true"
|
||||
android:taskAffinity="com.liketrek.trek.share"
|
||||
android:launchMode="standard"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="application/pdf" />
|
||||
<data android:mimeType="application/vnd.apple.pkpass" />
|
||||
<data android:mimeType="message/rfc822" />
|
||||
<data android:mimeType="text/calendar" />
|
||||
<data android:mimeType="text/html" />
|
||||
<data android:mimeType="text/plain" />
|
||||
<data android:mimeType="image/*" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="application/pdf" />
|
||||
<data android:mimeType="image/*" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<!-- content:// only: a file:// path would be read with TREK's own rights. -->
|
||||
<data android:scheme="content" />
|
||||
<data android:mimeType="application/pdf" />
|
||||
<data android:mimeType="text/calendar" />
|
||||
<data android:mimeType="application/vnd.apple.pkpass" />
|
||||
<data android:mimeType="message/rfc822" />
|
||||
</intent-filter>
|
||||
<!-- Lets the share sheet rank the trip shortcuts for this target. -->
|
||||
<meta-data android:name="android.service.chooser.chooser_target_service" android:value="androidx.sharetarget.ChooserTargetServiceCompat" />
|
||||
</activity>
|
||||
|
||||
<!-- "Choose trip" for a placed widget. -->
|
||||
<activity
|
||||
android:name=".widget.WidgetConfigActivity"
|
||||
android:theme="@style/AppTheme.Native"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- The home-screen widgets (widget/TrekWidgets.kt). -->
|
||||
<receiver
|
||||
android:name=".widget.TripWidgetReceiver"
|
||||
android:label="@string/widget_trip_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_trip" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.TodayWidgetReceiver"
|
||||
android:label="@string/widget_today_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_today" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.BookingsWidgetReceiver"
|
||||
android:label="@string/widget_bookings_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_bookings" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.TodosWidgetReceiver"
|
||||
android:label="@string/widget_todos_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_todos" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.PackingWidgetReceiver"
|
||||
android:label="@string/widget_packing_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_packing" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.AtlasWidgetReceiver"
|
||||
android:label="@string/widget_atlas_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_atlas" />
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".widget.CollabWidgetReceiver"
|
||||
android:label="@string/widget_collab_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_collab" />
|
||||
</receiver>
|
||||
<!-- Push: the relay's data messages, decrypted and shown here. -->
|
||||
<service
|
||||
android:name=".TrekPushService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="com.google.firebase.MESSAGING_EVENT" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths"></meta-data>
|
||||
</provider>
|
||||
|
||||
</application>
|
||||
|
||||
<!-- Permissions. Only what the WebView itself needs: the file picker's
|
||||
camera option and navigator.geolocation for "locate me" on the map,
|
||||
both granted at runtime through Capacitor's WebChromeClient. -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- COARSE is listed first because it is the weaker grant and is enough
|
||||
for "what city am I in". -->
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<!-- required="false" on purpose: TREK is a planner, and everything except
|
||||
"locate me" works without GPS hardware. Marking it required would have
|
||||
Play hide the app from tablets and other GPS-less devices. -->
|
||||
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<!-- Android 13 and later ask before an app may show notifications. -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Android 16: the travel day's Live Update may be promoted to the top of the shade. -->
|
||||
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<!-- Tablets, Chromebooks and TVs without these still get the app on Play. -->
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.screen.portrait" android:required="false" />
|
||||
</manifest>
|
||||
@@ -1,88 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.KeyboardShortcutGroup;
|
||||
import android.view.Menu;
|
||||
import android.view.View;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
import com.liketrek.trek.screen.TrekKeyCommands;
|
||||
import com.liketrek.trek.tiles.TrekTileStore;
|
||||
import com.liketrek.trek.widget.TrekWidgetUpdater;
|
||||
import java.util.List;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
|
||||
/** The share sheet (share/ShareActivity.kt) left an item for the import. */
|
||||
public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF";
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(TrekShellPlugin.class);
|
||||
TrekTileStore.INSTANCE.init(this);
|
||||
// With a server picked, the WebView loads that server instead of the
|
||||
// bundled address screen, so the UI arrives in the version the server
|
||||
// runs and on its own origin. BridgeActivity reads `config` while it
|
||||
// builds the bridge inside super.onCreate().
|
||||
boolean restarting = TrekServerStore.consumeRestart(this);
|
||||
String server = TrekServerStore.getUrl(this);
|
||||
boolean onServer = server != null && !TrekServerStore.consumeShellOnce(this);
|
||||
config = TrekServerStore.configFor(this, onServer ? server : null, restarting);
|
||||
super.onCreate(savedInstanceState);
|
||||
if (bridge == null) return;
|
||||
// The UI asks for no overscroll effect (overscroll-behavior: none on html)
|
||||
// and Chrome honours that, but the WebView draws the stretch on its root
|
||||
// scroller natively. It scales the whole view, top bar and bottom dock included.
|
||||
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER);
|
||||
// Set before any WebView callback can run: they are posted to this thread.
|
||||
if (onServer) bridge.setWebViewClient(new TrekWebViewClient(bridge, this::showAddressScreen));
|
||||
TrekSharedFiles.receive(this, getIntent());
|
||||
// Android 15's widget picker draws the widgets live from a sample trip.
|
||||
TrekWidgetUpdater.publishPreviews(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* A hardware keyboard's shortcut runs the UI's command (TrekKeyCommands),
|
||||
* wherever the focus is; everything else goes on to the WebView as usual.
|
||||
*/
|
||||
@Override
|
||||
public boolean dispatchKeyEvent(KeyEvent event) {
|
||||
if (TrekKeyCommands.INSTANCE.dispatch(event)) return true;
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
/** The UI's shortcuts in the system's list (Meta + /), under their names. */
|
||||
@Override
|
||||
public void onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
|
||||
super.onProvideKeyboardShortcuts(data, menu, deviceId);
|
||||
KeyboardShortcutGroup group = TrekKeyCommands.INSTANCE.shortcutGroup(getString(R.string.app_name));
|
||||
if (group != null) data.add(group);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
TrekSharedFiles.receive(this, intent);
|
||||
}
|
||||
|
||||
private boolean leavingServer;
|
||||
|
||||
/**
|
||||
* The server did not load: back to the address screen, which offers retry
|
||||
* and change. A fresh task rather than recreate(), because this usually
|
||||
* happens during launch, while the system splash is still up, and a
|
||||
* recreated activity leaves that splash lying over the new page.
|
||||
*/
|
||||
private void showAddressScreen() {
|
||||
// A failed page can report more than one error; restart only once.
|
||||
if (leavingServer) return;
|
||||
leavingServer = true;
|
||||
TrekServerStore.showShellOnce(this);
|
||||
TrekServerStore.markRestart(this);
|
||||
runOnUiThread(() -> {
|
||||
startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
|
||||
overridePendingTransition(0, 0);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.security.keystore.KeyGenParameterSpec;
|
||||
import android.security.keystore.KeyProperties;
|
||||
import android.util.Base64;
|
||||
import java.math.BigInteger;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.KeyStore;
|
||||
import java.security.interfaces.ECPrivateKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.SecureRandom;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
|
||||
/**
|
||||
* The device's Web Push key pair (P-256) and auth secret (RFC 8291). The server
|
||||
* encrypts every notification for these, and TrekPushService decrypts with
|
||||
* them. They are kept in the app's preferences, sealed with an AES key that
|
||||
* never leaves the Android Keystore, so a copy of the preferences alone opens
|
||||
* nothing.
|
||||
*/
|
||||
final class TrekPushKeys {
|
||||
|
||||
private static final String PREFS = "trek_push";
|
||||
private static final String WRAP_ALIAS = "trek_push_wrap";
|
||||
private static final String PRIVATE = "private";
|
||||
private static final String PUBLIC = "public";
|
||||
private static final String AUTH = "auth";
|
||||
|
||||
final ECPrivateKey privateKey;
|
||||
/** Uncompressed point, 65 bytes, as the server reads p256dh. */
|
||||
final byte[] publicKey;
|
||||
final byte[] auth;
|
||||
|
||||
TrekPushKeys(ECPrivateKey privateKey, byte[] publicKey, byte[] auth) {
|
||||
this.privateKey = privateKey;
|
||||
this.publicKey = publicKey;
|
||||
this.auth = auth;
|
||||
}
|
||||
|
||||
/** The stored keys, or null when the app never subscribed. */
|
||||
static synchronized TrekPushKeys load(Context context) throws Exception {
|
||||
SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
String sealedPrivate = prefs.getString(PRIVATE, null);
|
||||
String publicKey = prefs.getString(PUBLIC, null);
|
||||
String sealedAuth = prefs.getString(AUTH, null);
|
||||
if (sealedPrivate == null || publicKey == null || sealedAuth == null) return null;
|
||||
byte[] pkcs8 = unseal(sealedPrivate);
|
||||
ECPrivateKey key = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
|
||||
return new TrekPushKeys(key, Base64.decode(publicKey, Base64.NO_WRAP), unseal(sealedAuth));
|
||||
}
|
||||
|
||||
static synchronized TrekPushKeys loadOrCreate(Context context) throws Exception {
|
||||
TrekPushKeys existing;
|
||||
try {
|
||||
existing = load(context);
|
||||
} catch (Exception unreadable) {
|
||||
// The Keystore key is gone (backup restored to another device, data
|
||||
// cleared): start over, the next subscription carries the new keys.
|
||||
existing = null;
|
||||
}
|
||||
if (existing != null) return existing;
|
||||
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
|
||||
generator.initialize(new ECGenParameterSpec("secp256r1"));
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
byte[] publicKey = uncompressed((ECPublicKey) pair.getPublic());
|
||||
byte[] auth = new byte[16];
|
||||
new SecureRandom().nextBytes(auth);
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString(PRIVATE, seal(pair.getPrivate().getEncoded()))
|
||||
.putString(PUBLIC, Base64.encodeToString(publicKey, Base64.NO_WRAP))
|
||||
.putString(AUTH, seal(auth))
|
||||
.apply();
|
||||
return new TrekPushKeys((ECPrivateKey) pair.getPrivate(), publicKey, auth);
|
||||
}
|
||||
|
||||
static String base64url(byte[] data) {
|
||||
return Base64.encodeToString(data, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
|
||||
}
|
||||
|
||||
static byte[] uncompressed(ECPublicKey key) {
|
||||
byte[] out = new byte[65];
|
||||
out[0] = 0x04;
|
||||
copyFixed(key.getW().getAffineX(), out, 1);
|
||||
copyFixed(key.getW().getAffineY(), out, 33);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A coordinate as exactly 32 bytes: BigInteger adds a sign byte or drops leading zeros. */
|
||||
private static void copyFixed(BigInteger value, byte[] out, int offset) {
|
||||
byte[] raw = value.toByteArray();
|
||||
int start = Math.max(0, raw.length - 32);
|
||||
int length = raw.length - start;
|
||||
System.arraycopy(raw, start, out, offset + 32 - length, length);
|
||||
}
|
||||
|
||||
private static SecretKey wrapKey() throws Exception {
|
||||
KeyStore store = KeyStore.getInstance("AndroidKeyStore");
|
||||
store.load(null);
|
||||
if (store.containsAlias(WRAP_ALIAS)) return ((KeyStore.SecretKeyEntry) store.getEntry(WRAP_ALIAS, null)).getSecretKey();
|
||||
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
|
||||
generator.init(
|
||||
new KeyGenParameterSpec.Builder(WRAP_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build()
|
||||
);
|
||||
return generator.generateKey();
|
||||
}
|
||||
|
||||
private static String seal(byte[] plain) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, wrapKey());
|
||||
byte[] iv = cipher.getIV();
|
||||
byte[] sealed = cipher.doFinal(plain);
|
||||
byte[] out = new byte[iv.length + sealed.length];
|
||||
System.arraycopy(iv, 0, out, 0, iv.length);
|
||||
System.arraycopy(sealed, 0, out, iv.length, sealed.length);
|
||||
return Base64.encodeToString(out, Base64.NO_WRAP);
|
||||
}
|
||||
|
||||
private static byte[] unseal(String value) throws Exception {
|
||||
byte[] in = Base64.decode(value, Base64.NO_WRAP);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, wrapKey(), new GCMParameterSpec(128, in, 0, 12));
|
||||
return cipher.doFinal(in, 12, in.length - 12);
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.util.Base64;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.core.app.NotificationCompat;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import com.google.firebase.messaging.FirebaseMessagingService;
|
||||
import com.google.firebase.messaging.RemoteMessage;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/**
|
||||
* Receives the relay's data messages ({enc}: the server's encrypted Web Push
|
||||
* record), decrypts them with the device's keys and shows the notification.
|
||||
* Without the keys, or when the record does not open, it shows the same
|
||||
* neutral text the iOS extension falls back to, never the ciphertext.
|
||||
*/
|
||||
public class TrekPushService extends FirebaseMessagingService {
|
||||
|
||||
static final String CHANNEL = "trek";
|
||||
static final String EXTRA_URL = "trek.pushUrl";
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(@NonNull RemoteMessage message) {
|
||||
String enc = message.getData().get("enc");
|
||||
if (enc == null) return;
|
||||
String title = getString(R.string.push_fallback_title);
|
||||
String body = getString(R.string.push_fallback_body);
|
||||
String url = null;
|
||||
String tag = null;
|
||||
String event = null;
|
||||
try {
|
||||
TrekPushKeys keys = TrekPushKeys.load(this);
|
||||
if (keys != null) {
|
||||
byte[] plain = TrekWebPush.decrypt(Base64.decode(enc, Base64.DEFAULT), keys);
|
||||
JSONObject payload = new JSONObject(new String(plain, StandardCharsets.UTF_8));
|
||||
if (!payload.optString("title").isEmpty()) title = payload.optString("title");
|
||||
body = payload.optString("body", body);
|
||||
url = payload.optString("url", null);
|
||||
tag = payload.optString("tag", null);
|
||||
event = payload.optString("event", null);
|
||||
}
|
||||
} catch (Exception unreadable) {
|
||||
// Shown with the neutral text: the tap still opens the app.
|
||||
}
|
||||
show(this, title, body, url, tag, event);
|
||||
}
|
||||
|
||||
/** A new token means a new endpoint; the UI re-registers on its next start (resyncPushSubscription). */
|
||||
@Override
|
||||
public void onNewToken(@NonNull String token) {}
|
||||
|
||||
/** The channels, so each kind can be silenced, raised or kept on its own in the system settings. */
|
||||
static final String CHANNEL_CHAT = "chat";
|
||||
static final String CHANNEL_TRIPS = "trips";
|
||||
static final String CHANNEL_INVITES = "invites";
|
||||
|
||||
/**
|
||||
* The channel of a notification by the event the server names (PushPayload.event,
|
||||
* notification-events.ts). A server too old to send one lands in the general channel.
|
||||
*/
|
||||
static String channelFor(String event) {
|
||||
if (event == null) return CHANNEL;
|
||||
switch (event) {
|
||||
case "collab_message":
|
||||
return CHANNEL_CHAT;
|
||||
case "booking_change":
|
||||
case "trip_reminder":
|
||||
case "todo_due":
|
||||
case "packing_tagged":
|
||||
return CHANNEL_TRIPS;
|
||||
case "trip_invite":
|
||||
case "vacay_invite":
|
||||
case "vacay_share":
|
||||
case "collection_invite":
|
||||
case "photos_shared":
|
||||
return CHANNEL_INVITES;
|
||||
default:
|
||||
return CHANNEL;
|
||||
}
|
||||
}
|
||||
|
||||
static void ensureChannel(Context context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
|
||||
NotificationManager manager = context.getSystemService(NotificationManager.class);
|
||||
if (manager == null) return;
|
||||
create(manager, CHANNEL_CHAT, context.getString(R.string.push_channel_chat), NotificationManager.IMPORTANCE_HIGH);
|
||||
create(manager, CHANNEL_TRIPS, context.getString(R.string.push_channel_trips), NotificationManager.IMPORTANCE_DEFAULT);
|
||||
create(manager, CHANNEL_INVITES, context.getString(R.string.push_channel_invites), NotificationManager.IMPORTANCE_DEFAULT);
|
||||
create(manager, CHANNEL, context.getString(R.string.push_channel_name), NotificationManager.IMPORTANCE_DEFAULT);
|
||||
com.liketrek.trek.tripday.TripDayNotification.INSTANCE.ensureChannel(context);
|
||||
}
|
||||
|
||||
@androidx.annotation.RequiresApi(Build.VERSION_CODES.O)
|
||||
private static void create(NotificationManager manager, String id, String name, int importance) {
|
||||
NotificationChannel existing = manager.getNotificationChannel(id);
|
||||
if (existing != null) {
|
||||
// Only the name follows the app's language; what the user set stays theirs.
|
||||
if (!name.contentEquals(existing.getName())) {
|
||||
existing.setName(name);
|
||||
manager.createNotificationChannel(existing);
|
||||
}
|
||||
return;
|
||||
}
|
||||
manager.createNotificationChannel(new NotificationChannel(id, name, importance));
|
||||
}
|
||||
|
||||
private static void show(Context context, String title, String body, String url, String tag, String event) {
|
||||
ensureChannel(context);
|
||||
Intent open = new Intent(context, MainActivity.class)
|
||||
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
if (url != null) open.putExtra(EXTRA_URL, url);
|
||||
int id = tag != null ? tag.hashCode() : (int) (System.currentTimeMillis() & 0x7fffffff);
|
||||
PendingIntent tap = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
open,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
||||
);
|
||||
String channel = channelFor(event);
|
||||
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_stat_trek)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
.setStyle(new NotificationCompat.BigTextStyle().bigText(body))
|
||||
.setAutoCancel(true)
|
||||
.setColor(ContextCompat.getColor(context, R.color.notification_accent))
|
||||
.setCategory(CHANNEL_CHAT.equals(channel) ? NotificationCompat.CATEGORY_MESSAGE : NotificationCompat.CATEGORY_EVENT)
|
||||
// One stack per kind in the shade, rather than a loose pile.
|
||||
.setGroup("trek." + channel)
|
||||
.setContentIntent(tap);
|
||||
if (Build.VERSION.SDK_INT >= 33
|
||||
&& ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
NotificationManagerCompat.from(context).notify(tag, id, builder.build());
|
||||
// The stack's head: the system folds the group under it from two notifications on.
|
||||
NotificationCompat.Builder summary = new NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_stat_trek)
|
||||
.setColor(ContextCompat.getColor(context, R.color.notification_accent))
|
||||
.setGroup("trek." + channel)
|
||||
.setGroupSummary(true)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
|
||||
.setAutoCancel(true);
|
||||
NotificationManagerCompat.from(context).notify("trek.summary", channel.hashCode(), summary.build());
|
||||
} catch (SecurityException notAllowed) {
|
||||
// Notifications switched off for the app since it subscribed.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import com.getcapacitor.CapConfig;
|
||||
import com.getcapacitor.Logger;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** The server the user picked, and the Capacitor configuration that loads it. */
|
||||
final class TrekServerStore {
|
||||
|
||||
private static final String PREFS = "trek_shell";
|
||||
private static final String KEY_URL = "server_url";
|
||||
private static final String KEY_SHELL_ONCE = "shell_once";
|
||||
private static final String KEY_RESTART = "restart";
|
||||
private static final String CONFIG_DIR = "trek-server-config";
|
||||
|
||||
private TrekServerStore() {}
|
||||
|
||||
static String getUrl(Context context) {
|
||||
return prefs(context).getString(KEY_URL, null);
|
||||
}
|
||||
|
||||
static void setUrl(Context context, String url) {
|
||||
SharedPreferences.Editor editor = prefs(context).edit();
|
||||
if (url == null) {
|
||||
editor.remove(KEY_URL);
|
||||
} else {
|
||||
editor.putString(KEY_URL, url);
|
||||
}
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
/** Start the next launch on the bundled address screen, even with a server remembered. */
|
||||
static void showShellOnce(Context context) {
|
||||
prefs(context).edit().putBoolean(KEY_SHELL_ONCE, true).commit();
|
||||
}
|
||||
|
||||
static boolean consumeShellOnce(Context context) {
|
||||
return consume(context, KEY_SHELL_ONCE);
|
||||
}
|
||||
|
||||
/** The next onCreate is the app restarting itself, not a launch. */
|
||||
static void markRestart(Context context) {
|
||||
prefs(context).edit().putBoolean(KEY_RESTART, true).commit();
|
||||
}
|
||||
|
||||
static boolean consumeRestart(Context context) {
|
||||
return consume(context, KEY_RESTART);
|
||||
}
|
||||
|
||||
private static boolean consume(Context context, String key) {
|
||||
boolean set = prefs(context).getBoolean(key, false);
|
||||
if (set) prefs(context).edit().remove(key).commit();
|
||||
return set;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundled capacitor.config.json, adjusted for this start. Capacitor only
|
||||
* takes these settings from a config file, so this writes a copy into the
|
||||
* app's private storage and loads that; null means the bundled one as it is.
|
||||
*
|
||||
* With a server: server.url set, and server.errorPath dropped, because that
|
||||
* page would have no bridge on the server's origin (TrekWebViewClient
|
||||
* handles a failed load instead).
|
||||
*
|
||||
* On a restart: no launch splash. The splash plugin shows it again after
|
||||
* recreate() but cannot take it down when the page hides it early, which
|
||||
* left it covering a fully rendered page. A restart has no launch to cover.
|
||||
*/
|
||||
static CapConfig configFor(Context context, String url, boolean restarting) {
|
||||
if (url == null && !restarting) return null;
|
||||
try {
|
||||
JSONObject json = new JSONObject(readAsset(context, "capacitor.config.json"));
|
||||
if (url != null) {
|
||||
JSONObject server = child(json, "server");
|
||||
server.put("url", url);
|
||||
server.remove("errorPath");
|
||||
}
|
||||
if (restarting) {
|
||||
child(child(json, "plugins"), "SplashScreen").put("launchShowDuration", 0);
|
||||
}
|
||||
|
||||
File dir = new File(context.getFilesDir(), CONFIG_DIR);
|
||||
if (!dir.isDirectory() && !dir.mkdirs()) throw new IOException("Cannot create " + dir);
|
||||
try (FileOutputStream out = new FileOutputStream(new File(dir, "capacitor.config.json"))) {
|
||||
out.write(json.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return CapConfig.loadFromFile(context, dir.getAbsolutePath());
|
||||
} catch (IOException | JSONException ex) {
|
||||
Logger.error("TrekShell", "Could not adjust the app config for " + url, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JSONObject child(JSONObject parent, String key) throws JSONException {
|
||||
JSONObject existing = parent.optJSONObject(key);
|
||||
if (existing != null) return existing;
|
||||
JSONObject created = new JSONObject();
|
||||
parent.put(key, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
private static String readAsset(Context context, String name) throws IOException {
|
||||
try (InputStream in = context.getAssets().open(name); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[8192];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read);
|
||||
return out.toString("UTF-8");
|
||||
}
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.OpenableColumns;
|
||||
import android.util.Base64;
|
||||
import com.getcapacitor.JSObject;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* Booking documents shared to TREK (open with / share), held until the UI takes
|
||||
* them (TrekShell.takeSharedFile) and announced if it is already running.
|
||||
*/
|
||||
final class TrekSharedFiles {
|
||||
/** Above this the file is not a booking confirmation. */
|
||||
private static final int MAX_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
interface Listener {
|
||||
void onFile(JSObject file);
|
||||
}
|
||||
|
||||
private static JSObject pending;
|
||||
private static Listener listener;
|
||||
|
||||
private TrekSharedFiles() {}
|
||||
|
||||
static void setListener(Listener l) {
|
||||
listener = l;
|
||||
}
|
||||
|
||||
static JSObject take() {
|
||||
JSObject file = pending;
|
||||
pending = null;
|
||||
return file;
|
||||
}
|
||||
|
||||
static void receive(Context context, Intent intent) {
|
||||
if (intent == null) return;
|
||||
if (MainActivity.ACTION_SHARE_HANDOFF.equals(intent.getAction())) {
|
||||
receiveHandoff(context);
|
||||
return;
|
||||
}
|
||||
Uri uri = null;
|
||||
// A view intent also brings sign-in callbacks and widget links; only a file is a document.
|
||||
if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null
|
||||
&& "content".equals(intent.getData().getScheme())) {
|
||||
uri = intent.getData();
|
||||
}
|
||||
else if (Intent.ACTION_SEND.equals(intent.getAction())) uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
|
||||
// content:// only: a file:// path would be read with TREK's own rights.
|
||||
if (uri == null || !"content".equals(uri.getScheme())) return;
|
||||
try (InputStream in = context.getContentResolver().openInputStream(uri)) {
|
||||
if (in == null) return;
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[16384];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
out.write(buffer, 0, read);
|
||||
if (out.size() > MAX_BYTES) return;
|
||||
}
|
||||
JSObject file = new JSObject();
|
||||
file.put("name", displayName(context, uri));
|
||||
String type = context.getContentResolver().getType(uri);
|
||||
file.put("mimeType", type == null ? intent.getType() : type);
|
||||
file.put("data", Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP));
|
||||
pending = file;
|
||||
if (listener != null) listener.onFile(file);
|
||||
} catch (Exception ignored) {
|
||||
// Unreadable or gone: nothing to import.
|
||||
}
|
||||
}
|
||||
|
||||
/** The item the share sheet left (share/ShareHandoff.kt), with the trip picked for it there. */
|
||||
static void receiveHandoff(Context context) {
|
||||
kotlin.Pair<org.json.JSONObject, byte[]> item = com.liketrek.trek.share.ShareHandoff.INSTANCE.take(context);
|
||||
if (item == null || item.getSecond().length > MAX_BYTES) return;
|
||||
org.json.JSONObject meta = item.getFirst();
|
||||
JSObject file = new JSObject();
|
||||
file.put("name", meta.optString("name", "booking"));
|
||||
file.put("mimeType", meta.optString("mimeType", "application/octet-stream"));
|
||||
file.put("data", Base64.encodeToString(item.getSecond(), Base64.NO_WRAP));
|
||||
if (meta.has("tripId")) file.put("tripId", meta.optLong("tripId"));
|
||||
pending = file;
|
||||
if (listener != null) listener.onFile(file);
|
||||
}
|
||||
|
||||
private static String displayName(Context context, Uri uri) {
|
||||
try (Cursor cursor = context.getContentResolver().query(uri, new String[] { OpenableColumns.DISPLAY_NAME }, null, null, null)) {
|
||||
if (cursor != null && cursor.moveToFirst()) return cursor.getString(0);
|
||||
} catch (Exception ignored) {
|
||||
// Fall through to the path.
|
||||
}
|
||||
String last = uri.getLastPathSegment();
|
||||
return last == null ? "booking" : last;
|
||||
}
|
||||
}
|
||||
@@ -1,633 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import androidx.browser.customtabs.CustomTabsIntent;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PermissionState;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
import com.getcapacitor.annotation.Permission;
|
||||
import com.getcapacitor.annotation.PermissionCallback;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** The native half of client/src/native/trekShell.ts. */
|
||||
@CapacitorPlugin(
|
||||
name = "TrekShell",
|
||||
permissions = {
|
||||
@Permission(strings = { Manifest.permission.POST_NOTIFICATIONS }, alias = "notifications"),
|
||||
@Permission(strings = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, alias = "location"),
|
||||
}
|
||||
)
|
||||
public class TrekShellPlugin extends Plugin {
|
||||
|
||||
/** How long to wait after returning from the browser for the redirect to land. */
|
||||
private static final long CANCEL_GRACE_MS = 600;
|
||||
|
||||
private String authCallId;
|
||||
private String authScheme;
|
||||
private boolean authBrowserOpen;
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* What this binary offers the server's UI, raised with every native feature
|
||||
* an older binary lacks. The UI asks before it calls (native/capabilities.ts),
|
||||
* and a server can require a minimum (minNativeShellApi in /api/health/features).
|
||||
*/
|
||||
static final int SHELL_API = 2;
|
||||
/** The native features by name, so the UI can turn each on by itself. */
|
||||
static final String[] FEATURES = {
|
||||
"capabilities",
|
||||
"biometricLock",
|
||||
"sharedFiles",
|
||||
"nativePush",
|
||||
"geolocation",
|
||||
"tileCache",
|
||||
"widgets",
|
||||
"widgetTrips",
|
||||
"liveActivity",
|
||||
"shareSheet",
|
||||
"playBilling",
|
||||
"googleWallet",
|
||||
"keyCommands",
|
||||
"windowLayout",
|
||||
};
|
||||
|
||||
/** liketrek's push relay: the endpoint for this device's FCM token (trek-hosted push-relay.ts). */
|
||||
static final String PUSH_RELAY = "https://push.liketrek.com/v1/fcm/";
|
||||
|
||||
/** The notification the app was started from, until the UI asks for it. */
|
||||
private String openedPushUrl;
|
||||
|
||||
@PluginMethod
|
||||
public void getCapabilities(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("shellApi", SHELL_API);
|
||||
result.put("platform", "android");
|
||||
String version = "";
|
||||
String build = "";
|
||||
try {
|
||||
android.content.pm.PackageInfo info = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0);
|
||||
version = info.versionName == null ? "" : info.versionName;
|
||||
build = String.valueOf(androidx.core.content.pm.PackageInfoCompat.getLongVersionCode(info));
|
||||
} catch (android.content.pm.PackageManager.NameNotFoundException ignored) {
|
||||
// Our own package is always there; the fields simply stay empty.
|
||||
}
|
||||
result.put("appVersion", version);
|
||||
result.put("build", build);
|
||||
com.getcapacitor.JSArray features = new com.getcapacitor.JSArray();
|
||||
for (String feature : FEATURES) features.put(feature);
|
||||
result.put("features", features);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---- Shared booking documents ----
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
TrekSharedFiles.setListener(file -> notifyListeners("sharedFile", file));
|
||||
// A reloaded page starts without a stream; whatever the old one ran is stopped.
|
||||
if (location != null) location.stop();
|
||||
locationActive = false;
|
||||
// A pending purchase that cleared while the shell runs: redeemed like a restore.
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.setOnTransaction(receipt -> {
|
||||
notifyListeners("storeTransaction", receipt);
|
||||
return kotlin.Unit.INSTANCE;
|
||||
});
|
||||
com.liketrek.trek.screen.TrekKeyCommands.INSTANCE.setOnPress(id -> {
|
||||
JSObject pressed = new JSObject();
|
||||
pressed.put("id", id);
|
||||
notifyListeners("keyCommand", pressed);
|
||||
return kotlin.Unit.INSTANCE;
|
||||
});
|
||||
if (getActivity() != null) {
|
||||
com.liketrek.trek.screen.TrekWindowLayout.INSTANCE.observe(getActivity(), layout -> {
|
||||
notifyListeners("windowLayout", layout);
|
||||
return kotlin.Unit.INSTANCE;
|
||||
});
|
||||
}
|
||||
if (getActivity() != null && getActivity().getIntent() != null) {
|
||||
openedPushUrl = getActivity().getIntent().getStringExtra(TrekPushService.EXTRA_URL);
|
||||
getActivity().getIntent().removeExtra(TrekPushService.EXTRA_URL);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Push ----
|
||||
|
||||
/**
|
||||
* Permission, the FCM token and the device keys, as the Web Push subscription
|
||||
* the server stores (native/push.ts). Rejects with DENIED when the user
|
||||
* refuses notifications, as on iOS.
|
||||
*/
|
||||
@PluginMethod
|
||||
public void registerPush(PluginCall call) {
|
||||
if (Build.VERSION.SDK_INT >= 33 && getPermissionState("notifications") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("notifications", call, "pushPermissionAnswered");
|
||||
return;
|
||||
}
|
||||
subscribePush(call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void pushPermissionAnswered(PluginCall call) {
|
||||
if (getPermissionState("notifications") != PermissionState.GRANTED) {
|
||||
call.reject("Notifications are not allowed", "DENIED");
|
||||
return;
|
||||
}
|
||||
subscribePush(call);
|
||||
}
|
||||
|
||||
private void subscribePush(PluginCall call) {
|
||||
if (!NotificationManagerCompat.from(getContext()).areNotificationsEnabled()) {
|
||||
call.reject("Notifications are not allowed", "DENIED");
|
||||
return;
|
||||
}
|
||||
TrekPushService.ensureChannel(getContext());
|
||||
final TrekPushKeys keys;
|
||||
try {
|
||||
keys = TrekPushKeys.loadOrCreate(getContext());
|
||||
} catch (Exception e) {
|
||||
call.reject("Could not create the push keys", e);
|
||||
return;
|
||||
}
|
||||
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
|
||||
if (!task.isSuccessful() || task.getResult() == null) {
|
||||
call.reject("Could not get a push token", task.getException());
|
||||
return;
|
||||
}
|
||||
JSObject subscription = new JSObject();
|
||||
subscription.put("endpoint", PUSH_RELAY + task.getResult());
|
||||
JSObject keyObject = new JSObject();
|
||||
keyObject.put("p256dh", TrekPushKeys.base64url(keys.publicKey));
|
||||
keyObject.put("auth", TrekPushKeys.base64url(keys.auth));
|
||||
subscription.put("keys", keyObject);
|
||||
call.resolve(subscription);
|
||||
});
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void takeOpenedPush(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("url", openedPushUrl == null ? JSONObject.NULL : openedPushUrl);
|
||||
openedPushUrl = null;
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
/** The document shared to TREK before the UI was there to hear of it. */
|
||||
@PluginMethod
|
||||
public void takeSharedFile(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
JSObject file = TrekSharedFiles.take();
|
||||
result.put("file", file == null ? JSONObject.NULL : file);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---- App lock ----
|
||||
|
||||
private static final int AUTHENTICATORS =
|
||||
androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK
|
||||
| androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL;
|
||||
|
||||
/** Which biometry the device offers for the app lock, if any. */
|
||||
@PluginMethod
|
||||
public void biometryInfo(PluginCall call) {
|
||||
int status = androidx.biometric.BiometricManager.from(getContext()).canAuthenticate(AUTHENTICATORS);
|
||||
JSObject result = new JSObject();
|
||||
result.put("available", status == androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS);
|
||||
result.put("type", "biometric");
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
/** The system biometric prompt with the screen lock as the way out. */
|
||||
@PluginMethod
|
||||
public void authenticateBiometric(PluginCall call) {
|
||||
String reason = call.getString("reason", "Unlock TREK");
|
||||
getActivity().runOnUiThread(() -> {
|
||||
androidx.fragment.app.FragmentActivity activity = (androidx.fragment.app.FragmentActivity) getActivity();
|
||||
androidx.biometric.BiometricPrompt prompt = new androidx.biometric.BiometricPrompt(
|
||||
activity,
|
||||
androidx.core.content.ContextCompat.getMainExecutor(getContext()),
|
||||
new androidx.biometric.BiometricPrompt.AuthenticationCallback() {
|
||||
@Override
|
||||
public void onAuthenticationSucceeded(androidx.biometric.BiometricPrompt.AuthenticationResult result) {
|
||||
JSObject ok = new JSObject();
|
||||
ok.put("ok", true);
|
||||
call.resolve(ok);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAuthenticationError(int code, CharSequence message) {
|
||||
boolean cancelled = code == androidx.biometric.BiometricPrompt.ERROR_USER_CANCELED
|
||||
|| code == androidx.biometric.BiometricPrompt.ERROR_NEGATIVE_BUTTON
|
||||
|| code == androidx.biometric.BiometricPrompt.ERROR_CANCELED;
|
||||
call.reject(message.toString(), cancelled ? "CANCELLED" : "FAILED");
|
||||
}
|
||||
}
|
||||
);
|
||||
androidx.biometric.BiometricPrompt.PromptInfo info = new androidx.biometric.BiometricPrompt.PromptInfo.Builder()
|
||||
.setTitle(reason)
|
||||
.setAllowedAuthenticators(AUTHENTICATORS)
|
||||
.build();
|
||||
prompt.authenticate(info);
|
||||
});
|
||||
}
|
||||
|
||||
/** While on, the recent-apps screen shows no snapshot of the app. */
|
||||
@PluginMethod
|
||||
public void setPrivacyCover(PluginCall call) {
|
||||
boolean enabled = Boolean.TRUE.equals(call.getBoolean("enabled", false));
|
||||
getActivity().runOnUiThread(() -> {
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
getActivity().setRecentsScreenshotEnabled(!enabled);
|
||||
} else if (enabled) {
|
||||
getActivity().getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE);
|
||||
} else {
|
||||
getActivity().getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE);
|
||||
}
|
||||
});
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void getServer(PluginCall call) {
|
||||
String url = TrekServerStore.getUrl(getContext());
|
||||
JSObject result = new JSObject();
|
||||
result.put("url", url == null ? JSONObject.NULL : url);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void setServer(PluginCall call) {
|
||||
String url = call.getString("url");
|
||||
Uri parsed = url == null ? null : Uri.parse(url);
|
||||
if (parsed == null || parsed.getHost() == null || !("https".equals(parsed.getScheme()) || "http".equals(parsed.getScheme()))) {
|
||||
call.reject("A http(s) URL is required");
|
||||
return;
|
||||
}
|
||||
TrekServerStore.setUrl(getContext(), url);
|
||||
call.resolve();
|
||||
restart();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void resetServer(PluginCall call) {
|
||||
TrekServerStore.setUrl(getContext(), null);
|
||||
call.resolve();
|
||||
restart();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void reload(PluginCall call) {
|
||||
call.resolve();
|
||||
restart();
|
||||
}
|
||||
|
||||
/** The server URL is part of the bridge's configuration, so it takes a new activity. */
|
||||
private void restart() {
|
||||
locationActive = false;
|
||||
if (location != null) location.stop();
|
||||
TrekServerStore.markRestart(getContext());
|
||||
getActivity().runOnUiThread(() -> getActivity().recreate());
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void authenticate(PluginCall call) {
|
||||
String url = call.getString("url");
|
||||
String scheme = call.getString("callbackScheme");
|
||||
if (url == null || scheme == null) {
|
||||
call.reject("url and callbackScheme are required");
|
||||
return;
|
||||
}
|
||||
rejectPendingAuth("Superseded by a new sign-in");
|
||||
call.setKeepAlive(true);
|
||||
getBridge().saveCall(call);
|
||||
authCallId = call.getCallbackId();
|
||||
authScheme = scheme;
|
||||
authBrowserOpen = true;
|
||||
// A Custom Tab shares the browser's cookies, so a running SSO session at
|
||||
// the identity provider carries over. The redirect back to the app's
|
||||
// scheme arrives through the intent-filter in AndroidManifest.xml.
|
||||
new CustomTabsIntent.Builder().build().launchUrl(getActivity(), Uri.parse(url));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleOnNewIntent(Intent intent) {
|
||||
super.handleOnNewIntent(intent);
|
||||
String pushUrl = intent.getStringExtra(TrekPushService.EXTRA_URL);
|
||||
if (pushUrl != null) {
|
||||
intent.removeExtra(TrekPushService.EXTRA_URL);
|
||||
JSObject opened = new JSObject();
|
||||
opened.put("url", pushUrl);
|
||||
notifyListeners("pushOpened", opened);
|
||||
return;
|
||||
}
|
||||
Uri data = intent.getData();
|
||||
PluginCall call = pendingAuthCall();
|
||||
if (call == null || data == null || !authScheme.equals(data.getScheme())) return;
|
||||
JSObject result = new JSObject();
|
||||
result.put("url", data.toString());
|
||||
call.resolve(result);
|
||||
finishAuth(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Back in the app without a redirect means the user closed the browser.
|
||||
* onNewIntent runs before onResume when the redirect did arrive, so the
|
||||
* grace period only covers devices that deliver the two out of order.
|
||||
*/
|
||||
@Override
|
||||
protected void handleOnResume() {
|
||||
super.handleOnResume();
|
||||
if (locationActive && location != null && locationAllowed()) location.start(locationHighAccuracy);
|
||||
if (!authBrowserOpen) return;
|
||||
authBrowserOpen = false;
|
||||
handler.postDelayed(() -> {
|
||||
PluginCall call = pendingAuthCall();
|
||||
if (call == null) return;
|
||||
call.reject("Sign-in cancelled", "CANCELLED");
|
||||
finishAuth(call);
|
||||
}, CANCEL_GRACE_MS);
|
||||
}
|
||||
|
||||
private PluginCall pendingAuthCall() {
|
||||
return authCallId == null ? null : getBridge().getSavedCall(authCallId);
|
||||
}
|
||||
|
||||
private void rejectPendingAuth(String message) {
|
||||
PluginCall call = pendingAuthCall();
|
||||
if (call == null) return;
|
||||
call.reject(message, "CANCELLED");
|
||||
finishAuth(call);
|
||||
}
|
||||
|
||||
private void finishAuth(PluginCall call) {
|
||||
getBridge().releaseCall(call);
|
||||
authCallId = null;
|
||||
authScheme = null;
|
||||
authBrowserOpen = false;
|
||||
}
|
||||
|
||||
/** iOS only: Android keeps the service worker, which already starts TREK offline. */
|
||||
@PluginMethod
|
||||
public void refreshOfflineCopy(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("saved", false);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void openOfflineCopy(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("opened", false);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---- Widgets, shortcuts and the travel day ----
|
||||
|
||||
/**
|
||||
* What the home-screen widgets show (native/widgets.ts), as JSON: "snapshot"
|
||||
* (the dashboard's), "trip.<id>" or "trips" (the list a widget and the share
|
||||
* sheet pick from). The widgets redraw, and a new trip list rebuilds the
|
||||
* trip shortcuts.
|
||||
*/
|
||||
@PluginMethod
|
||||
public void setWidgetSnapshot(PluginCall call) {
|
||||
String json = call.getString("json");
|
||||
String key = call.getString("key", "snapshot");
|
||||
if (json == null) {
|
||||
call.reject("json is required");
|
||||
return;
|
||||
}
|
||||
if (!com.liketrek.trek.widget.WidgetStore.INSTANCE.isValidKey(key)) {
|
||||
call.reject("key must be snapshot, trips or trip.<id>");
|
||||
return;
|
||||
}
|
||||
android.content.Context context = getContext().getApplicationContext();
|
||||
try {
|
||||
com.liketrek.trek.widget.WidgetStore.INSTANCE.write(context, key, json);
|
||||
} catch (Exception e) {
|
||||
call.reject("Could not store the widget snapshot", e);
|
||||
return;
|
||||
}
|
||||
if ("trips".equals(key)) {
|
||||
new Thread(() -> com.liketrek.trek.share.TrekShortcuts.INSTANCE.publish(context)).start();
|
||||
} else {
|
||||
com.liketrek.trek.widget.TrekWidgetUpdater.refreshAll(context);
|
||||
}
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
/** Starts the travel day's Live Update, or updates the one showing. */
|
||||
@PluginMethod
|
||||
public void syncTripDay(PluginCall call) {
|
||||
String title = call.getString("tripTitle");
|
||||
String path = call.getString("path");
|
||||
String dayLabel = call.getString("dayLabel");
|
||||
String nextName = call.getString("nextName");
|
||||
if (title == null || path == null || dayLabel == null || nextName == null) {
|
||||
call.reject("tripTitle, path, dayLabel and nextName are required");
|
||||
return;
|
||||
}
|
||||
java.util.List<String> colors = new java.util.ArrayList<>();
|
||||
com.getcapacitor.JSArray raw = call.getArray("colors");
|
||||
if (raw != null) {
|
||||
for (int i = 0; i < raw.length(); i++) colors.add(raw.isNull(i) ? null : raw.optString(i, null));
|
||||
}
|
||||
com.liketrek.trek.tripday.TripDayNotification.State state = new com.liketrek.trek.tripday.TripDayNotification.State(
|
||||
title,
|
||||
path,
|
||||
dayLabel,
|
||||
nextName,
|
||||
call.getString("nextTime"),
|
||||
call.getInt("nextMinutes"),
|
||||
call.getInt("done", 0),
|
||||
call.getInt("total", 0),
|
||||
colors
|
||||
);
|
||||
boolean running = com.liketrek.trek.tripday.TripDayNotification.INSTANCE.show(getContext(), state);
|
||||
JSObject result = new JSObject();
|
||||
result.put("running", running);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void endTripDay(PluginCall call) {
|
||||
com.liketrek.trek.tripday.TripDayNotification.INSTANCE.end(getContext());
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
// ---- Location ----
|
||||
|
||||
private com.liketrek.trek.location.TrekLocation location;
|
||||
private boolean locationHighAccuracy;
|
||||
|
||||
private com.liketrek.trek.location.TrekLocation location() {
|
||||
if (location == null) {
|
||||
location = new com.liketrek.trek.location.TrekLocation(getContext(), payload -> {
|
||||
notifyListeners("location", payload);
|
||||
return kotlin.Unit.INSTANCE;
|
||||
});
|
||||
}
|
||||
return location;
|
||||
}
|
||||
|
||||
/** Whether the app may know where the device is: precisely, or "Approximate" only. */
|
||||
private boolean locationAllowed() {
|
||||
return androidx.core.content.ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
== android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
|| androidx.core.content.ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
== android.content.pm.PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
/** True while the UI has a stream running, so it resumes after the app was in the background. */
|
||||
private boolean locationActive;
|
||||
|
||||
/**
|
||||
* One location stream for the UI's navigator.geolocation, asking for the
|
||||
* permission the first time. "Approximate" counts as allowed; the stream then
|
||||
* runs on the coarse fixes Android gives.
|
||||
*/
|
||||
@PluginMethod
|
||||
public void startLocation(PluginCall call) {
|
||||
locationHighAccuracy = Boolean.TRUE.equals(call.getBoolean("highAccuracy", false));
|
||||
if (!locationAllowed()) {
|
||||
requestPermissionForAlias("location", call, "locationPermissionAnswered");
|
||||
return;
|
||||
}
|
||||
locationActive = true;
|
||||
location().start(locationHighAccuracy);
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void locationPermissionAnswered(PluginCall call) {
|
||||
if (!locationAllowed()) {
|
||||
location().emitError(1, "Location permission denied");
|
||||
} else {
|
||||
locationActive = true;
|
||||
location().start(locationHighAccuracy);
|
||||
}
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void stopLocation(PluginCall call) {
|
||||
locationActive = false;
|
||||
if (location != null) location.stop();
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
/** No location in the background, as in a browser: paused with the app, resumed with it. */
|
||||
@Override
|
||||
protected void handleOnPause() {
|
||||
super.handleOnPause();
|
||||
if (location != null) location.stop();
|
||||
}
|
||||
|
||||
/** The page and the activity are gone: nothing can stop the stream any more but this. */
|
||||
@Override
|
||||
protected void handleOnDestroy() {
|
||||
locationActive = false;
|
||||
if (location != null) location.stop();
|
||||
super.handleOnDestroy();
|
||||
}
|
||||
|
||||
// ---- Map tile store ----
|
||||
|
||||
@PluginMethod
|
||||
public void getTileCacheUsage(PluginCall call) {
|
||||
new Thread(() -> {
|
||||
JSObject result = new JSObject();
|
||||
result.put("bytes", com.liketrek.trek.tiles.TrekTileStore.INSTANCE.usage());
|
||||
result.put("limit", com.liketrek.trek.tiles.TrekTileStore.MAX_BYTES);
|
||||
call.resolve(result);
|
||||
}).start();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void clearTileCache(PluginCall call) {
|
||||
new Thread(() -> {
|
||||
com.liketrek.trek.tiles.TrekTileStore.INSTANCE.clear();
|
||||
call.resolve();
|
||||
}).start();
|
||||
}
|
||||
|
||||
// ---- Google Play Billing (the StoreKit methods' Android side) ----
|
||||
|
||||
@PluginMethod
|
||||
public void storeProducts(PluginCall call) {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.products(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void storePurchase(PluginCall call) {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.purchase(getActivity(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void storeFinish(PluginCall call) {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.finish(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void storeRestore(PluginCall call) {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.restore(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) {
|
||||
com.liketrek.trek.billing.TrekBilling.INSTANCE.unfinished(getContext(), call);
|
||||
}
|
||||
|
||||
// ---- Google Wallet ----
|
||||
|
||||
/** The only links this hands on: Google Wallet's save-to-wallet page. */
|
||||
static final String GOOGLE_WALLET_SAVE = "https://pay.google.com/gp/v/save/";
|
||||
|
||||
/**
|
||||
* Feature googleWallet: a booking's pass, by the save link the TREK services
|
||||
* signed, into Google Wallet. The Wallet app takes the link where it is
|
||||
* installed, the browser otherwise.
|
||||
*/
|
||||
@PluginMethod
|
||||
public void addToGoogleWallet(PluginCall call) {
|
||||
String url = call.getString("url");
|
||||
if (url == null || !url.startsWith(GOOGLE_WALLET_SAVE)) {
|
||||
call.reject("not a Google Wallet save link", "INVALID");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE));
|
||||
JSObject result = new JSObject();
|
||||
result.put("result", "opened");
|
||||
call.resolve(result);
|
||||
} catch (android.content.ActivityNotFoundException e) {
|
||||
call.reject("Nothing can open Google Wallet", "UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Large screens and keyboards ----
|
||||
|
||||
/** Feature keyCommands: the UI's keyboard shortcuts for the screen it shows. */
|
||||
@PluginMethod
|
||||
public void setKeyCommands(PluginCall call) {
|
||||
com.liketrek.trek.screen.TrekKeyCommands.INSTANCE.set(call.getArray("commands"));
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
/** Feature windowLayout: the window's size classes and a foldable's posture and hinge. */
|
||||
@PluginMethod
|
||||
public void getWindowLayout(PluginCall call) {
|
||||
// The last layout WindowManager reported, posture and hinge included; the bare window before the first.
|
||||
getActivity().runOnUiThread(() -> call.resolve(com.liketrek.trek.screen.TrekWindowLayout.INSTANCE.current(getActivity())));
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.interfaces.ECPrivateKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.spec.ECPoint;
|
||||
import java.security.spec.ECPublicKeySpec;
|
||||
import java.util.Arrays;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* Decrypts a Web Push record (RFC 8291, aes128gcm content coding of RFC 8188):
|
||||
* the same thing a browser does, and the counterpart of the iOS notification
|
||||
* extension's WebPushRecord. One record, as TREK's server always sends.
|
||||
*/
|
||||
final class TrekWebPush {
|
||||
|
||||
private TrekWebPush() {}
|
||||
|
||||
static byte[] decrypt(byte[] record, TrekPushKeys keys) throws Exception {
|
||||
if (record.length < 21) throw new IllegalArgumentException("record too short");
|
||||
byte[] salt = Arrays.copyOfRange(record, 0, 16);
|
||||
int idLength = record[20] & 0xff;
|
||||
if (idLength != 65 || record.length < 21 + idLength + 17) throw new IllegalArgumentException("unexpected header");
|
||||
byte[] senderKey = Arrays.copyOfRange(record, 21, 21 + idLength);
|
||||
byte[] ciphertext = Arrays.copyOfRange(record, 21 + idLength, record.length);
|
||||
|
||||
KeyAgreement agreement = KeyAgreement.getInstance("ECDH");
|
||||
agreement.init(keys.privateKey);
|
||||
agreement.doPhase(publicKeyFrom(senderKey, keys.privateKey), true);
|
||||
byte[] shared = agreement.generateSecret();
|
||||
|
||||
byte[] keyInfo = concat("WebPush: info\0".getBytes(StandardCharsets.US_ASCII), keys.publicKey, senderKey);
|
||||
byte[] ikm = hkdf(keys.auth, shared, keyInfo, 32);
|
||||
byte[] cek = hkdf(salt, ikm, "Content-Encoding: aes128gcm\0".getBytes(StandardCharsets.US_ASCII), 16);
|
||||
byte[] nonce = hkdf(salt, ikm, "Content-Encoding: nonce\0".getBytes(StandardCharsets.US_ASCII), 12);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cek, "AES"), new GCMParameterSpec(128, nonce));
|
||||
byte[] padded = cipher.doFinal(ciphertext);
|
||||
|
||||
// Padding: the content, one delimiter (2 for the last record), then zeros.
|
||||
int end = padded.length - 1;
|
||||
while (end >= 0 && padded[end] == 0) end--;
|
||||
if (end < 0 || padded[end] != 2) throw new IllegalArgumentException("bad padding");
|
||||
return Arrays.copyOf(padded, end);
|
||||
}
|
||||
|
||||
private static ECPublicKey publicKeyFrom(byte[] point, ECPrivateKey onCurve) throws Exception {
|
||||
if (point[0] != 0x04) throw new IllegalArgumentException("compressed key");
|
||||
BigInteger x = new BigInteger(1, Arrays.copyOfRange(point, 1, 33));
|
||||
BigInteger y = new BigInteger(1, Arrays.copyOfRange(point, 33, 65));
|
||||
return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), onCurve.getParams()));
|
||||
}
|
||||
|
||||
/** HKDF-SHA256 (RFC 5869) for outputs of at most one block. */
|
||||
private static byte[] hkdf(byte[] salt, byte[] ikm, byte[] info, int length) throws Exception {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(salt, "HmacSHA256"));
|
||||
byte[] prk = mac.doFinal(ikm);
|
||||
mac.init(new SecretKeySpec(prk, "HmacSHA256"));
|
||||
mac.update(info);
|
||||
mac.update((byte) 1);
|
||||
return Arrays.copyOf(mac.doFinal(), length);
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
int length = 0;
|
||||
for (byte[] part : parts) length += part.length;
|
||||
byte[] out = new byte[length];
|
||||
int offset = 0;
|
||||
for (byte[] part : parts) {
|
||||
System.arraycopy(part, 0, out, offset, part.length);
|
||||
offset += part.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.webkit.WebResourceError;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebResourceResponse;
|
||||
import android.webkit.WebView;
|
||||
import com.getcapacitor.Bridge;
|
||||
import com.getcapacitor.BridgeWebViewClient;
|
||||
|
||||
/**
|
||||
* Used while the WebView shows the user's server. When that server cannot be
|
||||
* loaded, Capacitor would show server.errorPath, but on Android it injects
|
||||
* its bridge only into the server's origin, so that local page could neither
|
||||
* retry nor change the server and stayed blank. Instead the app restarts on
|
||||
* the bundled address screen, where the bridge is present and the screen
|
||||
* offers exactly those two things.
|
||||
*/
|
||||
class TrekWebViewClient extends BridgeWebViewClient {
|
||||
|
||||
private final Runnable onUnreachable;
|
||||
|
||||
TrekWebViewClient(Bridge bridge, Runnable onUnreachable) {
|
||||
super(bridge);
|
||||
this.onUnreachable = onUnreachable;
|
||||
}
|
||||
|
||||
/** Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt). */
|
||||
@Override
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
|
||||
if (com.liketrek.trek.tiles.TrekTileStore.INSTANCE.handles(request)) {
|
||||
WebResourceResponse stored = com.liketrek.trek.tiles.TrekTileStore.INSTANCE.serve(request);
|
||||
if (stored != null) return stored;
|
||||
}
|
||||
return super.shouldInterceptRequest(view, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
|
||||
if (request.isForMainFrame()) {
|
||||
onUnreachable.run();
|
||||
return;
|
||||
}
|
||||
super.onReceivedError(view, request, error);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@Override
|
||||
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
|
||||
if (!request.isForMainFrame()) {
|
||||
super.onReceivedHttpError(view, request, errorResponse);
|
||||
} else if (errorResponse.getStatusCode() >= 500) {
|
||||
onUnreachable.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
package com.liketrek.trek.billing
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import com.android.billingclient.api.AcknowledgePurchaseParams
|
||||
import com.android.billingclient.api.BillingClient
|
||||
import com.android.billingclient.api.BillingClientStateListener
|
||||
import com.android.billingclient.api.BillingFlowParams
|
||||
import com.android.billingclient.api.BillingResult
|
||||
import com.android.billingclient.api.PendingPurchasesParams
|
||||
import com.android.billingclient.api.ProductDetails
|
||||
import com.android.billingclient.api.Purchase
|
||||
import com.android.billingclient.api.PurchasesUpdatedListener
|
||||
import com.android.billingclient.api.QueryProductDetailsParams
|
||||
import com.android.billingclient.api.QueryPurchasesParams
|
||||
import com.getcapacitor.JSArray
|
||||
import com.getcapacitor.JSObject
|
||||
import com.getcapacitor.PluginCall
|
||||
import com.liketrek.trek.BuildConfig
|
||||
|
||||
/**
|
||||
* TREK Cloud subscriptions through Google Play Billing, the counterpart of the
|
||||
* iOS app's StoreKit 2 (TrekShellPlugin.swift, feature storeKit). The UI drives
|
||||
* it through the same TrekShell methods (storeProducts, storePurchase,
|
||||
* storeFinish, storeRestore) behind native/iap.ts's IapClient, so the shell's
|
||||
* plan screens work unchanged; a purchase's token is the receipt the control
|
||||
* plane verifies with Google (iap-google.ts in trek-hosted).
|
||||
*
|
||||
* Products are subscriptions with the ids `cloud.<plan>.monthly|yearly`, one base
|
||||
* plan each. A purchase stays unacknowledged until storeFinish, after the
|
||||
* instance exists, so a purchase whose redeem never happened is offered again
|
||||
* by a restore rather than lost (Play refunds what is not acknowledged within
|
||||
* three days, and the control plane acknowledges too once it has verified).
|
||||
*/
|
||||
object TrekBilling {
|
||||
private var client: BillingClient? = null
|
||||
private var pendingPurchase: PluginCall? = null
|
||||
private var pendingProduct: String? = null
|
||||
private val waiting = mutableListOf<(Boolean) -> Unit>()
|
||||
private var connecting = false
|
||||
|
||||
private val listener = PurchasesUpdatedListener { result, purchases -> onPurchasesUpdated(result, purchases) }
|
||||
|
||||
/**
|
||||
* Told of a purchase that went through outside a purchase sheet: a payment
|
||||
* that was pending (cash, some carrier billing) and cleared later. The shell
|
||||
* redeems it like a restore (the "storeTransaction" event), since Play refunds
|
||||
* what is not acknowledged within three days.
|
||||
*/
|
||||
var onTransaction: ((JSObject) -> Unit)? = null
|
||||
|
||||
private fun client(context: Context): BillingClient = client ?: BillingClient.newBuilder(context.applicationContext)
|
||||
.setListener(listener)
|
||||
.enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().enablePrepaidPlans().build())
|
||||
.enableAutoServiceReconnection()
|
||||
.build()
|
||||
.also { client = it }
|
||||
|
||||
/** Runs [then] once connected; false when Play is not there (no Play Store, a sideloaded device). */
|
||||
private fun ready(context: Context, then: (Boolean) -> Unit) {
|
||||
val billing = client(context)
|
||||
if (billing.isReady) return then(true)
|
||||
synchronized(waiting) {
|
||||
waiting += then
|
||||
if (connecting) return
|
||||
connecting = true
|
||||
}
|
||||
billing.startConnection(object : BillingClientStateListener {
|
||||
override fun onBillingSetupFinished(result: BillingResult) = flush(result.responseCode == BillingClient.BillingResponseCode.OK)
|
||||
|
||||
override fun onBillingServiceDisconnected() = flush(false)
|
||||
})
|
||||
}
|
||||
|
||||
private fun flush(ok: Boolean) {
|
||||
val callbacks = synchronized(waiting) {
|
||||
connecting = false
|
||||
waiting.toList().also { waiting.clear() }
|
||||
}
|
||||
callbacks.forEach { it(ok) }
|
||||
}
|
||||
|
||||
private fun details(context: Context, ids: List<String>, done: (List<ProductDetails>) -> Unit) {
|
||||
if (ids.isEmpty()) return done(emptyList())
|
||||
val params = QueryProductDetailsParams.newBuilder()
|
||||
.setProductList(ids.map { QueryProductDetailsParams.Product.newBuilder().setProductId(it).setProductType(BillingClient.ProductType.SUBS).build() })
|
||||
.build()
|
||||
client(context).queryProductDetailsAsync(params) { result, found ->
|
||||
done(if (result.responseCode == BillingClient.BillingResponseCode.OK) found.productDetailsList else emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
/** The recurring price of a subscription's base plan, as Play formats it for the buyer. */
|
||||
internal fun displayPrice(product: ProductDetails): String? {
|
||||
val offer = baseOffer(product) ?: return null
|
||||
return offer.pricingPhases.pricingPhaseList.lastOrNull()?.formattedPrice
|
||||
}
|
||||
|
||||
/** The base plan's own offer: the one without an offer id (free trials and promotions carry one). */
|
||||
private fun baseOffer(product: ProductDetails): ProductDetails.SubscriptionOfferDetails? {
|
||||
val offers = product.subscriptionOfferDetails ?: return null
|
||||
return offers.firstOrNull { it.offerId == null } ?: offers.firstOrNull()
|
||||
}
|
||||
|
||||
fun products(context: Context, call: PluginCall) {
|
||||
val ids = call.getArray("ids")?.toList<String>().orEmpty()
|
||||
ready(context) { ok ->
|
||||
val result = JSObject().put("sandbox", BuildConfig.DEBUG)
|
||||
if (!ok) return@ready call.resolve(result.put("products", JSArray()))
|
||||
details(context, ids) { found ->
|
||||
val list = JSArray()
|
||||
for (product in found) displayPrice(product)?.let { list.put(JSObject().put("id", product.productId).put("displayPrice", it)) }
|
||||
call.resolve(result.put("products", list))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun purchase(activity: Activity, call: PluginCall) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onPurchasesUpdated(result: BillingResult, purchases: List<Purchase>?) {
|
||||
if (pendingPurchase == null) {
|
||||
// No sheet waiting: a pending purchase that cleared, or a renewal. Only an
|
||||
// undelivered one matters; renewals are acknowledged already.
|
||||
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
|
||||
undelivered(purchases.orEmpty(), PREFIX)?.let { onTransaction?.invoke(receipt(it)) }
|
||||
}
|
||||
return
|
||||
}
|
||||
when (result.responseCode) {
|
||||
BillingClient.BillingResponseCode.OK -> {
|
||||
val purchase = purchases?.firstOrNull { pendingProduct in it.products } ?: purchases?.firstOrNull()
|
||||
when (purchase?.purchaseState) {
|
||||
Purchase.PurchaseState.PURCHASED -> settle("bought", purchase)
|
||||
Purchase.PurchaseState.PENDING -> settle("pending", null)
|
||||
else -> settle("failed", null)
|
||||
}
|
||||
}
|
||||
BillingClient.BillingResponseCode.USER_CANCELED -> settle("cancelled", null)
|
||||
// Already subscribed on this Google account (a reinstall, another phone, a
|
||||
// redeem that never happened): that subscription is the purchase, and the
|
||||
// shell redeems it as it would a new one.
|
||||
BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> settleOwned()
|
||||
else -> settle("failed", null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun settleOwned() {
|
||||
val call = pendingPurchase ?: return
|
||||
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
|
||||
client?.queryPurchasesAsync(params) { result, purchases ->
|
||||
val owned = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
|
||||
if (pendingPurchase !== call) return@queryPurchasesAsync
|
||||
settle(if (owned != null) "bought" else "failed", owned)
|
||||
} ?: settle("failed", null)
|
||||
}
|
||||
|
||||
private fun receipt(purchase: Purchase): JSObject = JSObject()
|
||||
.put("purchaseToken", purchase.purchaseToken)
|
||||
.put("transactionId", purchase.purchaseToken)
|
||||
.put("productId", purchase.products.firstOrNull { it.startsWith(PREFIX) } ?: purchase.products.firstOrNull())
|
||||
|
||||
private fun settle(kind: String, purchase: Purchase?) {
|
||||
val call = pendingPurchase ?: return
|
||||
pendingPurchase = null
|
||||
val product = pendingProduct
|
||||
pendingProduct = null
|
||||
val out = JSObject().put("kind", kind)
|
||||
if (purchase != null) {
|
||||
out.put("purchaseToken", purchase.purchaseToken)
|
||||
out.put("transactionId", purchase.purchaseToken)
|
||||
out.put("productId", purchase.products.firstOrNull() ?: product)
|
||||
purchase.orderId?.let { out.put("orderId", it) }
|
||||
}
|
||||
call.resolve(out)
|
||||
}
|
||||
|
||||
/** Marks the purchase delivered, once its instance exists: acknowledged with Play. */
|
||||
fun finish(context: Context, call: PluginCall) {
|
||||
val token = call.getString("transactionId") ?: return call.reject("transactionId is required")
|
||||
ready(context) { ok ->
|
||||
if (!ok) return@ready call.resolve()
|
||||
val params = AcknowledgePurchaseParams.newBuilder().setPurchaseToken(token).build()
|
||||
client(context).acknowledgePurchase(params) { call.resolve() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The newest active subscription under `prefix` on this Google account, if any. */
|
||||
fun restore(context: Context, call: PluginCall) {
|
||||
val prefix = call.getString("prefix") ?: "cloud."
|
||||
ready(context) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject())
|
||||
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
|
||||
if (found == null) return@queryPurchasesAsync call.resolve(JSObject())
|
||||
call.resolve(
|
||||
JSObject()
|
||||
.put("purchaseToken", found.purchaseToken)
|
||||
.put("transactionId", found.purchaseToken)
|
||||
.put("productId", found.products.first { it.startsWith(prefix) }),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A paid cloud purchase that was never delivered (not acknowledged), for the
|
||||
* shell to redeem at its start: one that cleared while the app was closed.
|
||||
*/
|
||||
fun unfinished(context: Context, call: PluginCall) {
|
||||
val prefix = call.getString("prefix") ?: PREFIX
|
||||
ready(context) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject())
|
||||
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
|
||||
client(context).queryPurchasesAsync(params) { result, purchases ->
|
||||
val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) undelivered(purchases, prefix) else null
|
||||
call.resolve(found?.let(::receipt) ?: JSObject())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun undelivered(purchases: List<Purchase>, prefix: String): Purchase? =
|
||||
newest(purchases.filter { !it.isAcknowledged }, prefix)
|
||||
|
||||
private const val PREFIX = "cloud."
|
||||
|
||||
internal fun newest(purchases: List<Purchase>, prefix: String): Purchase? = purchases
|
||||
.filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } }
|
||||
.maxByOrNull { it.purchaseTime }
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.liketrek.trek.location
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import androidx.core.location.LocationListenerCompat
|
||||
import androidx.core.location.LocationManagerCompat
|
||||
import androidx.core.location.LocationRequestCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.getcapacitor.JSObject
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* One location stream for the UI's navigator.geolocation (native/geolocation.ts),
|
||||
* the counterpart of TrekLocation in TrekShellPlugin.swift: the system's fused
|
||||
* provider where there is one (Android 12+), GPS and network before, with
|
||||
* positions and errors shaped like the Geolocation API's. Asking for the
|
||||
* permission is the plugin's part; this starts once it is granted.
|
||||
*/
|
||||
class TrekLocation(context: Context, private val emit: (JSObject) -> Unit) {
|
||||
private val manager = context.getSystemService(LocationManager::class.java)
|
||||
private val executor = ContextCompat.getMainExecutor(context)
|
||||
private val listeners = mutableListOf<LocationListenerCompat>()
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun start(highAccuracy: Boolean) {
|
||||
stop()
|
||||
if (manager == null || !LocationManagerCompat.isLocationEnabled(manager)) {
|
||||
emitError(2, "Location services are off")
|
||||
return
|
||||
}
|
||||
val request = LocationRequestCompat.Builder(if (highAccuracy) 2_000L else 10_000L)
|
||||
.setQuality(if (highAccuracy) LocationRequestCompat.QUALITY_HIGH_ACCURACY else LocationRequestCompat.QUALITY_BALANCED_POWER_ACCURACY)
|
||||
.setMinUpdateDistanceMeters(if (highAccuracy) 2f else 25f)
|
||||
.build()
|
||||
val providers = when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && manager.hasProvider(LocationManager.FUSED_PROVIDER) -> listOf(LocationManager.FUSED_PROVIDER)
|
||||
else -> listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER).filter { manager.isProviderEnabled(it) }
|
||||
}
|
||||
if (providers.isEmpty()) {
|
||||
emitError(2, "No location provider")
|
||||
return
|
||||
}
|
||||
// The last known fix answers getCurrentPosition at once; a fresh one follows.
|
||||
providers.mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }
|
||||
.maxByOrNull { it.time }
|
||||
?.takeIf { System.currentTimeMillis() - it.time < 120_000 }
|
||||
?.let { emit(payload(it)) }
|
||||
for (provider in providers) {
|
||||
val listener = LocationListenerCompat { location -> emit(payload(location)) }
|
||||
try {
|
||||
LocationManagerCompat.requestLocationUpdates(manager, provider, request, executor, listener)
|
||||
listeners += listener
|
||||
} catch (e: SecurityException) {
|
||||
emitError(1, "Location permission denied")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Removing updates needs no permission of its own; one revoked meanwhile only means there is nothing left to stop.
|
||||
@SuppressLint("MissingPermission")
|
||||
fun stop() {
|
||||
val m = manager ?: return
|
||||
for (listener in listeners) {
|
||||
try {
|
||||
LocationManagerCompat.removeUpdates(m, listener)
|
||||
} catch (e: SecurityException) {
|
||||
// Nothing to stop.
|
||||
}
|
||||
}
|
||||
listeners.clear()
|
||||
}
|
||||
|
||||
fun emitError(code: Int, message: String) {
|
||||
emit(JSObject().put("error", JSObject().put("code", code).put("message", message)))
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun payload(location: Location): JSObject = JSObject()
|
||||
.put("latitude", location.latitude)
|
||||
.put("longitude", location.longitude)
|
||||
.put("accuracy", location.accuracy.toDouble())
|
||||
.put("altitude", if (location.hasAltitude()) location.altitude else JSONObject.NULL)
|
||||
.put("speed", if (location.hasSpeed()) location.speed.toDouble() else JSONObject.NULL)
|
||||
.put("heading", if (location.hasBearing()) location.bearing.toDouble() else JSONObject.NULL)
|
||||
.put("timestamp", location.time.toDouble())
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package com.liketrek.trek.screen
|
||||
|
||||
import android.view.KeyEvent
|
||||
import android.view.KeyboardShortcutGroup
|
||||
import android.view.KeyboardShortcutInfo
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The UI's keyboard shortcuts as the app's own (TrekShell.setKeyCommands, feature
|
||||
* keyCommands), the Android side of TrekKeyCommands in the iOS shell: a hardware
|
||||
* keyboard's shortcut runs the UI's command even while the focus sits outside the
|
||||
* page, and the system's shortcut list (Meta + /) shows them under their names in
|
||||
* the UI's language. Each screen replaces the list, so only what works here is on it.
|
||||
*
|
||||
* "command" is Ctrl on Android (Meta is accepted too, for keyboards made for a Mac),
|
||||
* "option" is Alt.
|
||||
*/
|
||||
object TrekKeyCommands {
|
||||
data class Command(val id: String, val title: String, val keyCode: Int, val modifiers: Int)
|
||||
|
||||
@Volatile var current: List<Command> = emptyList()
|
||||
private set
|
||||
|
||||
var onPress: ((String) -> Unit)? = null
|
||||
|
||||
fun set(raw: JSONArray?) {
|
||||
current = parse(raw)
|
||||
}
|
||||
|
||||
fun parse(raw: JSONArray?): List<Command> {
|
||||
if (raw == null) return emptyList()
|
||||
return (0 until raw.length()).mapNotNull { i ->
|
||||
val o: JSONObject = raw.optJSONObject(i) ?: return@mapNotNull null
|
||||
val id = o.optString("id").ifEmpty { return@mapNotNull null }
|
||||
val title = o.optString("title").ifEmpty { return@mapNotNull null }
|
||||
val key = keyCode(o.optString("input")) ?: return@mapNotNull null
|
||||
var meta = 0
|
||||
val mods = o.optJSONArray("modifiers")
|
||||
for (j in 0 until (mods?.length() ?: 0)) {
|
||||
meta = meta or when (mods!!.optString(j)) {
|
||||
"command", "control" -> KeyEvent.META_CTRL_ON
|
||||
"shift" -> KeyEvent.META_SHIFT_ON
|
||||
"option" -> KeyEvent.META_ALT_ON
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
Command(id, title, key, meta)
|
||||
}
|
||||
}
|
||||
|
||||
/** The key a UI input names: a letter, a digit, an arrow, escape or a punctuation mark. */
|
||||
fun keyCode(input: String): Int? = when (input.lowercase()) {
|
||||
"left" -> KeyEvent.KEYCODE_DPAD_LEFT
|
||||
"right" -> KeyEvent.KEYCODE_DPAD_RIGHT
|
||||
"up" -> KeyEvent.KEYCODE_DPAD_UP
|
||||
"down" -> KeyEvent.KEYCODE_DPAD_DOWN
|
||||
"escape" -> KeyEvent.KEYCODE_ESCAPE
|
||||
"enter", "\r" -> KeyEvent.KEYCODE_ENTER
|
||||
"," -> KeyEvent.KEYCODE_COMMA
|
||||
"." -> KeyEvent.KEYCODE_PERIOD
|
||||
"/" -> KeyEvent.KEYCODE_SLASH
|
||||
"[" -> KeyEvent.KEYCODE_LEFT_BRACKET
|
||||
"]" -> KeyEvent.KEYCODE_RIGHT_BRACKET
|
||||
"-" -> KeyEvent.KEYCODE_MINUS
|
||||
"=" -> KeyEvent.KEYCODE_EQUALS
|
||||
" ", "space" -> KeyEvent.KEYCODE_SPACE
|
||||
else -> when {
|
||||
input.length == 1 && input[0].lowercaseChar() in 'a'..'z' -> KeyEvent.KEYCODE_A + (input[0].lowercaseChar() - 'a')
|
||||
input.length == 1 && input[0] in '0'..'9' -> KeyEvent.KEYCODE_0 + (input[0] - '0')
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private const val MASK = KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON or KeyEvent.META_ALT_ON
|
||||
|
||||
/** The command a key press stands for, if any. Meta counts as Ctrl. */
|
||||
fun match(keyCode: Int, metaState: Int): Command? {
|
||||
var state = metaState
|
||||
if (state and KeyEvent.META_META_ON != 0) state = state or KeyEvent.META_CTRL_ON
|
||||
val pressed = state and MASK
|
||||
return current.firstOrNull { it.keyCode == keyCode && it.modifiers == pressed }
|
||||
}
|
||||
|
||||
/** Runs the matching command for a key going down. True when one took it. */
|
||||
fun dispatch(event: KeyEvent): Boolean {
|
||||
if (event.action != KeyEvent.ACTION_DOWN || event.repeatCount > 0) return false
|
||||
val command = match(event.keyCode, event.metaState) ?: return false
|
||||
// A plain key (no modifier) is left to a text field that has the focus.
|
||||
if (command.modifiers == 0 && event.keyCode != KeyEvent.KEYCODE_ESCAPE) return false
|
||||
val press = onPress ?: return false
|
||||
press(command.id)
|
||||
return true
|
||||
}
|
||||
|
||||
/** The list the system shows for Meta + /. */
|
||||
fun shortcutGroup(label: CharSequence): KeyboardShortcutGroup? {
|
||||
val items = current.map { KeyboardShortcutInfo(it.title, it.keyCode, it.modifiers) }
|
||||
return if (items.isEmpty()) null else KeyboardShortcutGroup(label, items)
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.liketrek.trek.screen
|
||||
|
||||
import android.app.Activity
|
||||
import android.graphics.Rect
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.window.layout.FoldingFeature
|
||||
import androidx.window.layout.WindowInfoTracker
|
||||
import androidx.window.layout.WindowLayoutInfo
|
||||
import androidx.window.layout.WindowMetricsCalculator
|
||||
import com.getcapacitor.JSObject
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* The window's shape for the UI (TrekShell.getWindowLayout and the
|
||||
* "windowLayout" event, feature windowLayout): its size class by Android's
|
||||
* breakpoints, and a foldable's posture and hinge through Jetpack WindowManager.
|
||||
*
|
||||
* The layouts themselves follow the CSS size classes (hooks/sizeClass.ts), which
|
||||
* the WebView answers from the window like any browser; this adds what CSS cannot
|
||||
* see: that a Galaxy Z Fold or Pixel Fold is half open like a laptop or a book,
|
||||
* and where the hinge runs, so a layout can keep content off the fold. Lengths
|
||||
* are in CSS pixels, relative to the window.
|
||||
*/
|
||||
object TrekWindowLayout {
|
||||
/** The last WindowLayoutInfo WindowManager reported, with the fold in it. */
|
||||
@Volatile private var lastInfo: WindowLayoutInfo? = null
|
||||
|
||||
/** The window now, with the posture last reported: what getWindowLayout answers. */
|
||||
fun current(activity: Activity): JSObject = describe(activity, lastInfo)
|
||||
|
||||
fun observe(activity: ComponentActivity, emit: (JSObject) -> Unit) {
|
||||
activity.lifecycleScope.launch {
|
||||
activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
WindowInfoTracker.getOrCreate(activity).windowLayoutInfo(activity).collect { info ->
|
||||
lastInfo = info
|
||||
emit(describe(activity, info))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun describe(activity: Activity, info: WindowLayoutInfo?): JSObject {
|
||||
val density = activity.resources.displayMetrics.density
|
||||
val bounds = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(activity).bounds
|
||||
val widthDp = bounds.width() / density
|
||||
val heightDp = bounds.height() / density
|
||||
val result = JSObject()
|
||||
.put("width", widthDp.toInt())
|
||||
.put("height", heightDp.toInt())
|
||||
.put("widthClass", sizeClass(widthDp, 600f, 840f))
|
||||
.put("heightClass", sizeClass(heightDp, 480f, 900f))
|
||||
val fold = info?.displayFeatures?.filterIsInstance<FoldingFeature>()?.firstOrNull()
|
||||
if (fold == null) {
|
||||
result.put("posture", "none")
|
||||
} else {
|
||||
val r: Rect = fold.bounds
|
||||
result.put("posture", if (fold.state == FoldingFeature.State.HALF_OPENED) "halfOpened" else "flat")
|
||||
.put("orientation", if (fold.orientation == FoldingFeature.Orientation.VERTICAL) "vertical" else "horizontal")
|
||||
.put("separating", fold.isSeparating)
|
||||
.put("occluding", fold.occlusionType == FoldingFeature.OcclusionType.FULL)
|
||||
.put(
|
||||
"hinge",
|
||||
JSObject()
|
||||
.put("left", ((r.left - bounds.left) / density).toInt())
|
||||
.put("top", ((r.top - bounds.top) / density).toInt())
|
||||
.put("right", ((r.right - bounds.left) / density).toInt())
|
||||
.put("bottom", ((r.bottom - bounds.top) / density).toInt()),
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** Android's window size classes: compact, medium, expanded. */
|
||||
fun sizeClass(dp: Float, medium: Float, expanded: Float): String = when {
|
||||
dp < medium -> "compact"
|
||||
dp < expanded -> "medium"
|
||||
else -> "expanded"
|
||||
}
|
||||
}
|
||||
@@ -1,431 +0,0 @@
|
||||
package com.liketrek.trek.share
|
||||
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Bundle
|
||||
import android.text.format.Formatter
|
||||
import android.view.HapticFeedbackConstants
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.CalendarMonth
|
||||
import androidx.compose.material.icons.rounded.Check
|
||||
import androidx.compose.material.icons.rounded.Description
|
||||
import androidx.compose.material.icons.rounded.Email
|
||||
import androidx.compose.material.icons.rounded.Image
|
||||
import androidx.compose.material.icons.rounded.Language
|
||||
import androidx.compose.material.icons.rounded.PictureAsPdf
|
||||
import androidx.compose.material.icons.rounded.Schedule
|
||||
import androidx.compose.material.icons.rounded.ShortText
|
||||
import androidx.compose.material.icons.rounded.Wallet
|
||||
import androidx.compose.material.icons.rounded.ErrorOutline
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.pm.ShortcutManagerCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.liketrek.trek.MainActivity
|
||||
import com.liketrek.trek.R
|
||||
import com.liketrek.trek.ui.TrekMaterialTheme
|
||||
import com.liketrek.trek.widget.WidgetArt
|
||||
import java.time.LocalDate
|
||||
import java.time.temporal.ChronoUnit
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* "TREK" in the system share sheet (and "Open with TREK"): a Material bottom
|
||||
* sheet over the app that shared, showing what came in, the trip it goes to and
|
||||
* one button, the counterpart of the iOS share extension (ShareView.swift). The
|
||||
* item and the trip are left for the app (ShareHandoff) and TREK opens, where
|
||||
* the booking import takes over. A direct-share shortcut of a trip
|
||||
* (TrekShortcuts) arrives with that trip already picked.
|
||||
*/
|
||||
class ShareActivity : ComponentActivity() {
|
||||
private sealed interface Phase {
|
||||
data object Loading : Phase
|
||||
data object Ready : Phase
|
||||
data object Saving : Phase
|
||||
data object Done : Phase
|
||||
data class Failed(val message: Int) : Phase
|
||||
}
|
||||
|
||||
private var phase by mutableStateOf<Phase>(Phase.Loading)
|
||||
private var item by mutableStateOf<ShareItem?>(null)
|
||||
private var trips by mutableStateOf<List<ShareHandoff.Trip>>(emptyList())
|
||||
private var selected by mutableStateOf<Long?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
trips = ShareHandoff.trips(this)
|
||||
val shortcutTrip = intent.getStringExtra(ShortcutManagerCompat.EXTRA_SHORTCUT_ID)?.removePrefix("trip.")?.toLongOrNull()
|
||||
selected = if (savedInstanceState?.containsKey(SELECTED) == true) {
|
||||
// The trip picked before the system recreated the sheet; -1 is "choose later".
|
||||
savedInstanceState.getLong(SELECTED).takeIf { it >= 0 }
|
||||
} else {
|
||||
shortcutTrip?.takeIf { id -> trips.any { it.id == id } } ?: trips.firstOrNull()?.id
|
||||
}
|
||||
val incoming = intent
|
||||
lifecycleScope.launch {
|
||||
phase = try {
|
||||
item = withContext(Dispatchers.IO) { ShareLoader.load(incoming, contentResolver) }
|
||||
Phase.Ready
|
||||
} catch (e: ShareLoadException) {
|
||||
Phase.Failed(if (e.reason == ShareLoadException.Reason.TOO_LARGE) R.string.share_too_large else R.string.share_unsupported)
|
||||
} catch (e: Exception) {
|
||||
Phase.Failed(R.string.share_unsupported)
|
||||
}
|
||||
}
|
||||
setContent {
|
||||
TrekMaterialTheme {
|
||||
Sheet()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
outState.putLong(SELECTED, selected ?: -1L)
|
||||
}
|
||||
|
||||
private fun add() {
|
||||
val current = item ?: return
|
||||
if (phase != Phase.Ready) return
|
||||
phase = Phase.Saving
|
||||
lifecycleScope.launch {
|
||||
val stored = withContext(Dispatchers.IO) { ShareHandoff.store(this@ShareActivity, current, selected) }
|
||||
if (!stored) {
|
||||
window.decorView.performHapticFeedback(HapticFeedbackConstants.REJECT)
|
||||
phase = Phase.Failed(R.string.share_failed)
|
||||
return@launch
|
||||
}
|
||||
window.decorView.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
|
||||
phase = Phase.Done
|
||||
delay(850)
|
||||
startActivity(
|
||||
Intent(this@ShareActivity, MainActivity::class.java)
|
||||
.setAction(MainActivity.ACTION_SHARE_HANDOFF)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),
|
||||
)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun Sheet() {
|
||||
val state = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||
val scope = rememberCoroutineScope()
|
||||
val dismiss: () -> Unit = {
|
||||
scope.launch { state.hide() }.invokeOnCompletion { finish() }
|
||||
}
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = { finish() },
|
||||
sheetState = state,
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 12.dp)) {
|
||||
Header(onClose = dismiss)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
when (val now = phase) {
|
||||
is Phase.Failed -> Failure(stringResource(now.message), onClose = dismiss)
|
||||
else -> Content(now)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Header(onClose: () -> Unit) {
|
||||
Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(12.dp)).background(MaterialTheme.colorScheme.primary),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("T", color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Black, fontSize = 21.sp)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("TREK", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, letterSpacing = 2.4.sp)
|
||||
Text(stringResource(R.string.share_title), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
TextButton(onClick = onClose) { Text(stringResource(R.string.share_cancel)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Content(now: Phase) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(18.dp)) {
|
||||
ItemCard(item, Modifier.padding(horizontal = 20.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.share_trip).uppercase(),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 1.2.sp,
|
||||
modifier = Modifier.padding(horizontal = 22.dp),
|
||||
)
|
||||
if (trips.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.share_no_trips),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 22.dp),
|
||||
)
|
||||
} else {
|
||||
TripRail()
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.share_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 22.dp),
|
||||
)
|
||||
AddButton(now)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ItemCard(item: ShareItem?, modifier: Modifier) {
|
||||
val context = LocalContext.current
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(modifier = Modifier.padding(14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier.size(46.dp).clip(RoundedCornerShape(14.dp)).background(MaterialTheme.colorScheme.secondaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (item == null) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Icon(kindIcon(item.kind), null, tint = MaterialTheme.colorScheme.onSecondaryContainer)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
item?.title ?: stringResource(R.string.share_reading),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (item != null) {
|
||||
val parts = listOfNotNull(stringResource(kindLabel(item.kind)), Formatter.formatShortFileSize(context, item.data.size.toLong()), item.source)
|
||||
Text(parts.joinToString(", "), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TripRail() {
|
||||
LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
items(trips, key = { it.id }) { trip ->
|
||||
TripCard(trip, selected == trip.id) { selected = trip.id }
|
||||
}
|
||||
item {
|
||||
FilterChip(
|
||||
selected = selected == null,
|
||||
onClick = { selected = null },
|
||||
label = { Text(stringResource(R.string.share_later)) },
|
||||
leadingIcon = { Icon(Icons.Rounded.Schedule, null, modifier = Modifier.size(18.dp)) },
|
||||
modifier = Modifier.height(132.dp).padding(vertical = 44.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TripCard(trip: ShareHandoff.Trip, isSelected: Boolean, onClick: () -> Unit) {
|
||||
val view = LocalView.current
|
||||
val cover: Bitmap? = remember(trip.id) { WidgetArt.cover(trip.cover, 360) ?: WidgetArt.sky(trip.title, 300, 200) }
|
||||
val border = if (isSelected) BorderStroke(3.dp, MaterialTheme.colorScheme.primary) else BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant)
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
border = border,
|
||||
modifier = Modifier.width(168.dp).height(132.dp).clip(RoundedCornerShape(20.dp)).clickable {
|
||||
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
|
||||
onClick()
|
||||
},
|
||||
) {
|
||||
Box {
|
||||
if (cover != null) {
|
||||
Image(cover.asImageBitmap(), null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize().background(
|
||||
Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.1f), Color.Black.copy(alpha = 0.68f))),
|
||||
),
|
||||
)
|
||||
if (isSelected) {
|
||||
Box(
|
||||
modifier = Modifier.padding(8.dp).size(24.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primary).align(Alignment.TopEnd),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Rounded.Check, null, tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
}
|
||||
Column(modifier = Modifier.align(Alignment.BottomStart).padding(12.dp)) {
|
||||
Text(when_(trip), color = Color.White.copy(alpha = 0.82f), style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)
|
||||
Text(trip.title, color = Color.White, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun when_(trip: ShareHandoff.Trip): String {
|
||||
val today = LocalDate.now()
|
||||
val start = trip.start
|
||||
val end = trip.end
|
||||
return when {
|
||||
end != null && end < today -> stringResource(R.string.share_past)
|
||||
start == null || start <= today -> stringResource(R.string.share_now)
|
||||
ChronoUnit.DAYS.between(today, start) == 1L -> stringResource(R.string.share_tomorrow)
|
||||
else -> stringResource(R.string.share_in_days, ChronoUnit.DAYS.between(today, start).toInt())
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddButton(now: Phase) {
|
||||
val title = trips.firstOrNull { it.id == selected }?.title
|
||||
Button(
|
||||
onClick = ::add,
|
||||
enabled = now == Phase.Ready,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = if (now == Phase.Done) {
|
||||
ButtonDefaults.buttonColors(containerColor = Color(0xFF2FA37A), disabledContainerColor = Color(0xFF2FA37A), disabledContentColor = Color.White)
|
||||
} else {
|
||||
ButtonDefaults.buttonColors()
|
||||
},
|
||||
contentPadding = PaddingValues(vertical = 16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp),
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = now,
|
||||
transitionSpec = { (fadeIn() + scaleIn(spring(dampingRatio = 0.6f))) togetherWith fadeOut() },
|
||||
label = "add",
|
||||
) { target ->
|
||||
when (target) {
|
||||
Phase.Saving, Phase.Loading -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp, color = MaterialTheme.colorScheme.onPrimary)
|
||||
Phase.Done -> Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Check, null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.share_added), fontWeight = FontWeight.Bold)
|
||||
}
|
||||
else -> Text(
|
||||
if (title != null) stringResource(R.string.share_add_to, title) else stringResource(R.string.share_add),
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Failure(message: String, onClose: () -> Unit) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(Icons.Rounded.ErrorOutline, null, tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(40.dp))
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(message, style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Button(onClick = onClose, shape = RoundedCornerShape(18.dp)) { Text(stringResource(R.string.share_close)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun kindIcon(kind: ShareItem.Kind): ImageVector = when (kind) {
|
||||
ShareItem.Kind.PASS -> Icons.Rounded.Wallet
|
||||
ShareItem.Kind.PDF -> Icons.Rounded.PictureAsPdf
|
||||
ShareItem.Kind.MAIL -> Icons.Rounded.Email
|
||||
ShareItem.Kind.CALENDAR -> Icons.Rounded.CalendarMonth
|
||||
ShareItem.Kind.PAGE -> Icons.Rounded.Language
|
||||
ShareItem.Kind.TEXT -> Icons.Rounded.ShortText
|
||||
ShareItem.Kind.IMAGE -> Icons.Rounded.Image
|
||||
ShareItem.Kind.FILE -> Icons.Rounded.Description
|
||||
}
|
||||
|
||||
private fun kindLabel(kind: ShareItem.Kind): Int = when (kind) {
|
||||
ShareItem.Kind.PASS -> R.string.share_kind_pass
|
||||
ShareItem.Kind.PDF -> R.string.share_kind_pdf
|
||||
ShareItem.Kind.MAIL -> R.string.share_kind_mail
|
||||
ShareItem.Kind.CALENDAR -> R.string.share_kind_file
|
||||
ShareItem.Kind.PAGE -> R.string.share_kind_page
|
||||
ShareItem.Kind.TEXT -> R.string.share_kind_text
|
||||
ShareItem.Kind.IMAGE -> R.string.share_kind_image
|
||||
ShareItem.Kind.FILE -> R.string.share_kind_file
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SELECTED = "trek.share.selected"
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.liketrek.trek.share
|
||||
|
||||
import android.content.Context
|
||||
import com.liketrek.trek.widget.WidgetSnapshot
|
||||
import com.liketrek.trek.widget.WidgetStore
|
||||
import java.io.File
|
||||
import java.time.LocalDate
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The trips the share sheet offers, and the hand-over of the shared item to the
|
||||
* app. The trip list is the one the app keeps for the widgets (WidgetStore, key
|
||||
* "trips"); the item waits in the app's cache until MainActivity hands it to the
|
||||
* UI (TrekSharedFiles.receiveHandoff), the way ShareHandoff.swift does through
|
||||
* the keychain on iOS.
|
||||
*/
|
||||
object ShareHandoff {
|
||||
data class Trip(
|
||||
val id: Long,
|
||||
val title: String,
|
||||
val start: LocalDate?,
|
||||
val end: LocalDate?,
|
||||
val place: String?,
|
||||
/** The small cover from the trip's widget snapshot, base64, when the app wrote one. */
|
||||
val cover: String?,
|
||||
)
|
||||
|
||||
/** The trips that have not ended yet, soonest first, then the six most recent past ones. */
|
||||
fun trips(context: Context, today: LocalDate = LocalDate.now()): List<Trip> {
|
||||
val all = WidgetStore.trips(context).map { ref ->
|
||||
val snapshot = WidgetStore.read(context, "trip.${ref.id}")?.let(WidgetSnapshot::parse)
|
||||
Trip(ref.id, ref.title, WidgetSnapshot.day(ref.start), WidgetSnapshot.day(ref.end), snapshot?.trip?.place, snapshot?.trip?.cover)
|
||||
}
|
||||
return order(all, today)
|
||||
}
|
||||
|
||||
internal fun order(all: List<Trip>, today: LocalDate): List<Trip> {
|
||||
val ahead = all.filter { (it.end ?: LocalDate.MAX) >= today }.sortedBy { it.start ?: LocalDate.MAX }
|
||||
val past = all.filter { (it.end ?: LocalDate.MAX) < today }.sortedByDescending { it.end ?: LocalDate.MIN }
|
||||
return ahead + past.take(6)
|
||||
}
|
||||
|
||||
private fun dir(context: Context) = File(context.cacheDir, "share").apply { mkdirs() }
|
||||
|
||||
/** Leaves the item for the app, with the trip it goes to (null: the app asks). */
|
||||
fun store(context: Context, item: ShareItem, tripId: Long?): Boolean = runCatching {
|
||||
val meta = JSONObject().put("name", item.name).put("mimeType", item.mimeType)
|
||||
if (tripId != null) meta.put("tripId", tripId)
|
||||
File(dir(context), "pending.data").writeBytes(item.data)
|
||||
File(dir(context), "pending.json").writeText(meta.toString())
|
||||
true
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** The item left by [store], taken once. */
|
||||
fun take(context: Context): Pair<JSONObject, ByteArray>? {
|
||||
val metaFile = File(dir(context), "pending.json")
|
||||
val dataFile = File(dir(context), "pending.data")
|
||||
if (!metaFile.exists() || !dataFile.exists()) return null
|
||||
return try {
|
||||
JSONObject(metaFile.readText()) to dataFile.readBytes()
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} finally {
|
||||
metaFile.delete()
|
||||
dataFile.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
package com.liketrek.trek.share
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.OpenableColumns
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* What was shared to TREK, read into a file the booking import takes: a wallet
|
||||
* pass, a PDF, a mail, a calendar entry, a web page, a piece of text or a photo.
|
||||
* The import in the app (BookingImportModal) decides what it can read; this only
|
||||
* carries the bytes over with a name and a type, like ShareItem.swift on iOS.
|
||||
*/
|
||||
data class ShareItem(
|
||||
val kind: Kind,
|
||||
/** The file name the import sees. */
|
||||
val name: String,
|
||||
val mimeType: String,
|
||||
val data: ByteArray,
|
||||
/** What the sheet shows: a page title, a file name, the first line of a text. */
|
||||
val title: String,
|
||||
/** A host, for a page. */
|
||||
val source: String? = null,
|
||||
) {
|
||||
enum class Kind { PASS, PDF, MAIL, CALENDAR, PAGE, TEXT, IMAGE, FILE }
|
||||
|
||||
override fun equals(other: Any?): Boolean = other is ShareItem && other.name == name && other.data.contentEquals(data)
|
||||
|
||||
override fun hashCode(): Int = name.hashCode() * 31 + data.contentHashCode()
|
||||
}
|
||||
|
||||
class ShareLoadException(val reason: Reason) : Exception(reason.name) {
|
||||
enum class Reason { UNSUPPORTED, TOO_LARGE }
|
||||
}
|
||||
|
||||
object ShareLoader {
|
||||
/** The same ceiling as the app's import of an opened file (TrekSharedFiles). */
|
||||
const val MAX_BYTES = 15 * 1024 * 1024
|
||||
private const val PAGE_TIMEOUT_MS = 10_000
|
||||
|
||||
/** Reads what [intent] carries. Runs on a background thread: it may read a file or fetch a page. */
|
||||
fun load(intent: Intent, resolver: ContentResolver): ShareItem {
|
||||
val stream = streamOf(intent)
|
||||
if (stream != null) return fromUri(stream, intent.type, resolver)
|
||||
val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.trim()
|
||||
if (!text.isNullOrEmpty()) return fromText(text, intent.getStringExtra(Intent.EXTRA_SUBJECT))
|
||||
throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED)
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared document, content:// only. The share target is open to every app,
|
||||
* and a file:// path would be read with TREK's rights, its own private files
|
||||
* included; every sender today shares through a content provider anyway.
|
||||
*/
|
||||
private fun streamOf(intent: Intent): Uri? = when (intent.action) {
|
||||
Intent.ACTION_VIEW -> intent.data
|
||||
Intent.ACTION_SEND -> parcelable(intent, Intent.EXTRA_STREAM)
|
||||
Intent.ACTION_SEND_MULTIPLE -> parcelableList(intent)?.firstOrNull()
|
||||
else -> null
|
||||
}?.takeIf(::isShareable)
|
||||
|
||||
internal fun isShareable(uri: Uri): Boolean = uri.scheme == ContentResolver.SCHEME_CONTENT
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun parcelable(intent: Intent, key: String): Uri? =
|
||||
if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(key, Uri::class.java) else intent.getParcelableExtra(key)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun parcelableList(intent: Intent): List<Uri>? =
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java)
|
||||
} else {
|
||||
intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)
|
||||
}
|
||||
|
||||
private fun fromUri(uri: Uri, intentType: String?, resolver: ContentResolver): ShareItem {
|
||||
val name = displayName(uri, resolver)
|
||||
val size = runCatching {
|
||||
resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { if (it.moveToFirst() && !it.isNull(0)) it.getLong(0) else null }
|
||||
}.getOrNull()
|
||||
if (size != null && size > MAX_BYTES) throw ShareLoadException(ShareLoadException.Reason.TOO_LARGE)
|
||||
val data = resolver.openInputStream(uri)?.use { readCapped(it) } ?: throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED)
|
||||
val mime = resolver.getType(uri) ?: intentType ?: "application/octet-stream"
|
||||
val (kind, normalized) = classify(name, mime)
|
||||
return checked(ShareItem(kind, withExtension(name, kind), normalized, data, name.substringBeforeLast('.').ifBlank { name }))
|
||||
}
|
||||
|
||||
/** A link becomes the page it points at; anything else, a text file the import reads. */
|
||||
internal fun fromText(text: String, subject: String?): ShareItem {
|
||||
val link = firstLink(text)
|
||||
if (link != null) {
|
||||
runCatching { return page(link, subject) }
|
||||
}
|
||||
val firstLine = text.lineSequence().firstOrNull { it.isNotBlank() }?.trim() ?: text
|
||||
return checked(ShareItem(ShareItem.Kind.TEXT, "shared-text.txt", "text/plain", text.toByteArray(), (subject ?: firstLine).take(80)))
|
||||
}
|
||||
|
||||
/** The first http(s) link in a text, when the text is not much more than that link. */
|
||||
internal fun firstLink(text: String): String? {
|
||||
val match = Regex("https?://[^\\s<>\"]+").find(text) ?: return null
|
||||
// A long mail body with a link in it is the booking itself, not a pointer to one.
|
||||
return if (text.length - match.value.length <= 200) match.value.trimEnd('.', ',', ')', ']') else null
|
||||
}
|
||||
|
||||
private fun page(link: String, subject: String?): ShareItem {
|
||||
val connection = URL(link).openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = PAGE_TIMEOUT_MS
|
||||
connection.readTimeout = PAGE_TIMEOUT_MS
|
||||
connection.instanceFollowRedirects = true
|
||||
connection.setRequestProperty("Accept", "text/html")
|
||||
try {
|
||||
val code = connection.responseCode
|
||||
val type = connection.contentType.orEmpty()
|
||||
if (code !in 200..299 || !type.contains("html")) throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED)
|
||||
val data = connection.inputStream.use { readCapped(it) }
|
||||
val html = String(data, Charsets.UTF_8)
|
||||
val host = runCatching { Uri.parse(link).host }.getOrNull()
|
||||
val title = pageTitle(html) ?: subject ?: host ?: "Page"
|
||||
return checked(ShareItem(ShareItem.Kind.PAGE, "${slug(title)}.html", "text/html", data, title, host))
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/** The kind and the MIME type the import should see, from the name when the type is vague. */
|
||||
internal fun classify(name: String, mime: String): Pair<ShareItem.Kind, String> {
|
||||
val ext = name.substringAfterLast('.', "").lowercase()
|
||||
return when {
|
||||
ext == "pkpass" || mime == "application/vnd.apple.pkpass" -> ShareItem.Kind.PASS to "application/vnd.apple.pkpass"
|
||||
ext == "pdf" || mime == "application/pdf" -> ShareItem.Kind.PDF to "application/pdf"
|
||||
ext == "eml" || mime == "message/rfc822" -> ShareItem.Kind.MAIL to "message/rfc822"
|
||||
ext == "ics" || mime == "text/calendar" -> ShareItem.Kind.CALENDAR to "text/calendar"
|
||||
ext == "html" || ext == "htm" || mime == "text/html" -> ShareItem.Kind.PAGE to "text/html"
|
||||
mime.startsWith("image/") -> ShareItem.Kind.IMAGE to mime
|
||||
ext == "txt" || mime == "text/plain" -> ShareItem.Kind.TEXT to "text/plain"
|
||||
else -> ShareItem.Kind.FILE to mime
|
||||
}
|
||||
}
|
||||
|
||||
private fun withExtension(name: String, kind: ShareItem.Kind): String {
|
||||
val ext = when (kind) {
|
||||
ShareItem.Kind.PASS -> "pkpass"
|
||||
ShareItem.Kind.PDF -> "pdf"
|
||||
ShareItem.Kind.MAIL -> "eml"
|
||||
ShareItem.Kind.CALENDAR -> "ics"
|
||||
ShareItem.Kind.PAGE -> "html"
|
||||
else -> return name
|
||||
}
|
||||
return if (name.lowercase().endsWith(".$ext")) name else "$name.$ext"
|
||||
}
|
||||
|
||||
private fun displayName(uri: Uri, resolver: ContentResolver): String {
|
||||
runCatching {
|
||||
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
|
||||
if (it.moveToFirst() && !it.isNull(0)) return it.getString(0)
|
||||
}
|
||||
}
|
||||
return uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { null } ?: "booking"
|
||||
}
|
||||
|
||||
private fun readCapped(input: InputStream): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
if (out.size() > MAX_BYTES) throw ShareLoadException(ShareLoadException.Reason.TOO_LARGE)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun checked(item: ShareItem): ShareItem {
|
||||
if (item.data.isEmpty()) throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED)
|
||||
if (item.data.size > MAX_BYTES) throw ShareLoadException(ShareLoadException.Reason.TOO_LARGE)
|
||||
return item
|
||||
}
|
||||
|
||||
internal fun pageTitle(html: String): String? {
|
||||
val match = Regex("<title[^>]*>(.*?)</title>", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)).find(html) ?: return null
|
||||
return match.groupValues[1].trim().take(120).ifBlank { null }
|
||||
}
|
||||
|
||||
internal fun slug(title: String): String {
|
||||
val words = title.lowercase().split(Regex("[^\\p{L}\\p{N}]+")).filter { it.isNotEmpty() }
|
||||
return words.take(8).joinToString("-").ifBlank { "page" }
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.liketrek.trek.share
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Rect
|
||||
import android.net.Uri
|
||||
import androidx.core.content.pm.ShortcutInfoCompat
|
||||
import androidx.core.content.pm.ShortcutManagerCompat
|
||||
import androidx.core.graphics.drawable.IconCompat
|
||||
import com.liketrek.trek.MainActivity
|
||||
import com.liketrek.trek.widget.WidgetArt
|
||||
import com.liketrek.trek.widget.WidgetSnapshot
|
||||
import com.liketrek.trek.widget.WidgetStore
|
||||
|
||||
/**
|
||||
* The trips as shortcuts: a long press on TREK's icon lists the coming ones and
|
||||
* opens a trip straight away, and the system share sheet offers them as direct
|
||||
* share targets, so a booking goes into its trip in one tap (ShareActivity
|
||||
* reads the shortcut's id). Rebuilt whenever the app writes its trip list.
|
||||
*/
|
||||
object TrekShortcuts {
|
||||
/** The category res/xml/shortcuts.xml's share-target names. */
|
||||
const val SHARE_CATEGORY = "com.liketrek.trek.category.TRIP_SHARE"
|
||||
private const val MAX = 4
|
||||
|
||||
fun publish(context: Context) {
|
||||
val trips = ShareHandoff.trips(context).take(MAX)
|
||||
val limit = ShortcutManagerCompat.getMaxShortcutCountPerActivity(context).coerceAtLeast(1)
|
||||
val shortcuts = trips.take(limit).mapIndexed { rank, trip ->
|
||||
val open = Intent(Intent.ACTION_VIEW, Uri.parse(WidgetSnapshot.link("/trips/${trip.id}")), context, MainActivity::class.java)
|
||||
ShortcutInfoCompat.Builder(context, "trip.${trip.id}")
|
||||
.setShortLabel(trip.title.take(24))
|
||||
.setLongLabel(trip.title)
|
||||
.setIcon(IconCompat.createWithAdaptiveBitmap(icon(trip)))
|
||||
.setIntent(open)
|
||||
.setCategories(setOf(SHARE_CATEGORY))
|
||||
.setLongLived(true)
|
||||
.setRank(rank)
|
||||
.build()
|
||||
}
|
||||
runCatching {
|
||||
// Trips no longer listed lose their shortcut; pinned ones stay but are disabled by the system.
|
||||
val keep = shortcuts.map { it.id }.toSet()
|
||||
val stale = ShortcutManagerCompat.getDynamicShortcuts(context).map { it.id }.filter { it !in keep }
|
||||
if (stale.isNotEmpty()) ShortcutManagerCompat.removeLongLivedShortcuts(context, stale)
|
||||
ShortcutManagerCompat.setDynamicShortcuts(context, shortcuts)
|
||||
}
|
||||
}
|
||||
|
||||
/** The trip's cover, else its own sky, cropped for an adaptive icon (108dp with a 72dp safe zone). */
|
||||
private fun icon(trip: ShareHandoff.Trip): Bitmap {
|
||||
val size = 216
|
||||
val source = WidgetArt.cover(trip.cover, 432) ?: WidgetArt.sky(trip.title, size, size)
|
||||
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
||||
val side = minOf(source.width, source.height)
|
||||
val from = Rect((source.width - side) / 2, (source.height - side) / 2, (source.width + side) / 2, (source.height + side) / 2)
|
||||
Canvas(out).drawBitmap(source, from, Rect(0, 0, size, size), Paint(Paint.FILTER_BITMAP_FLAG))
|
||||
return out
|
||||
}
|
||||
|
||||
/** Whether there is anything to publish: the app wrote a trip list. */
|
||||
fun hasTrips(context: Context): Boolean = WidgetStore.trips(context).isNotEmpty()
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package com.liketrek.trek.tiles
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* The app's own store of Mapbox map resources, the counterpart of the iOS
|
||||
* TrekTileStore (TrekBridgeViewController.swift).
|
||||
*
|
||||
* Android's WebView runs the server's service worker, which keeps every raster
|
||||
* tile the user looked at. Mapbox's vector tiles, styles, sprites and glyphs it
|
||||
* may not keep, but a device cache of what was viewed is allowed for 30 days,
|
||||
* so the WebView client hands those requests here (TrekWebViewClient), and a
|
||||
* Mapbox map keeps working offline for the places already seen. Nothing is
|
||||
* prefetched; the store is pruned to [MAX_BYTES], least recently used first.
|
||||
*/
|
||||
object TrekTileStore {
|
||||
const val MAX_AGE_MS = 30L * 24 * 60 * 60 * 1000
|
||||
const val MAX_BYTES = 250L * 1024 * 1024
|
||||
private const val PRUNE_TARGET = 0.8
|
||||
private const val TIMEOUT_MS = 15_000
|
||||
/** One resource is a tile, a style or a sprite sheet: far below this. */
|
||||
private const val MAX_RESOURCE_BYTES = 8 * 1024 * 1024
|
||||
|
||||
private val HOST = Regex("^(api\\.mapbox\\.com|[a-z0-9-]+\\.tiles\\.mapbox\\.com)$", RegexOption.IGNORE_CASE)
|
||||
/** What a map draws; telemetry, sessions and anything else go straight out. */
|
||||
private val PATHS = listOf("/v4/", "/styles/", "/fonts/", "/models/", "/rasterarrays/", "/raster/")
|
||||
private val DROPPED = setOf("access_token", "sku", "key", "api_key", "apikey")
|
||||
|
||||
@Volatile private var dir: File? = null
|
||||
private var writesSincePrune = 0
|
||||
|
||||
fun init(context: Context) {
|
||||
if (dir == null) dir = File(context.cacheDir, "tiles").apply { mkdirs() }
|
||||
}
|
||||
|
||||
fun handles(request: WebResourceRequest): Boolean = request.method == "GET" && handles(request.url)
|
||||
|
||||
fun handles(url: Uri): Boolean = url.scheme == "https" && HOST.matches(url.host.orEmpty()) && PATHS.any { url.path.orEmpty().startsWith(it) }
|
||||
|
||||
/** The key of a resource: its URL without the credentials and the billing session, which change. */
|
||||
fun key(url: Uri): String {
|
||||
val builder = url.buildUpon().clearQuery()
|
||||
url.queryParameterNames.filter { it.lowercase() !in DROPPED }.sorted().forEach { name ->
|
||||
url.getQueryParameters(name).forEach { builder.appendQueryParameter(name, it) }
|
||||
}
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(builder.build().toString().toByteArray())
|
||||
return digest.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a Mapbox request from the store when it is younger than 30 days,
|
||||
* else from the network, keeping what came back. Null lets the WebView load
|
||||
* it itself (no store, or the network failed).
|
||||
*/
|
||||
fun serve(request: WebResourceRequest): WebResourceResponse? {
|
||||
val root = dir ?: return null
|
||||
val url = request.url
|
||||
val key = key(url)
|
||||
val body = File(root, "$key.bin")
|
||||
val meta = File(root, "$key.type")
|
||||
val now = System.currentTimeMillis()
|
||||
if (body.exists() && now - created(meta) < MAX_AGE_MS) {
|
||||
body.setLastModified(now)
|
||||
val type = runCatching { meta.readLines().getOrNull(1) }.getOrNull() ?: "application/octet-stream"
|
||||
return runCatching { response(body.readBytes(), type) }.getOrNull()
|
||||
}
|
||||
try {
|
||||
val connection = URL(url.toString()).openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = TIMEOUT_MS
|
||||
connection.readTimeout = TIMEOUT_MS
|
||||
// The WebView's own headers go along: Mapbox checks a URL-restricted token
|
||||
// against the Referer, and the server's origin is what the token allows.
|
||||
for ((name, value) in forwardedHeaders(request.requestHeaders)) connection.setRequestProperty(name, value)
|
||||
try {
|
||||
val code = connection.responseCode
|
||||
if (code == 200) {
|
||||
val bytes = connection.inputStream.use { it.readBytes() }
|
||||
if (bytes.size <= MAX_RESOURCE_BYTES) {
|
||||
val type = connection.contentType ?: "application/octet-stream"
|
||||
store(body, meta, bytes, type, now)
|
||||
return response(bytes, type)
|
||||
}
|
||||
}
|
||||
// Anything but a tile (401/403 for a token, 404, a 5xx) the WebView asks for
|
||||
// itself, with everything a browser sends, and the map reports what it gets.
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Offline and never seen: the map shows the gap as it would in a browser.
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** HttpURLConnection has already undone any gzip, so no Content-Encoding goes along. */
|
||||
/** Headers that are the request's own; the connection sets the hop-by-hop ones itself. */
|
||||
private val HOP_BY_HOP = setOf("connection", "keep-alive", "transfer-encoding", "te", "upgrade", "host", "content-length", "accept-encoding")
|
||||
|
||||
internal fun forwardedHeaders(headers: Map<String, String>?): Map<String, String> =
|
||||
headers.orEmpty().filterKeys { it.lowercase() !in HOP_BY_HOP }
|
||||
|
||||
private fun response(bytes: ByteArray, type: String): WebResourceResponse {
|
||||
val mime = type.substringBefore(';').trim()
|
||||
val charset = Regex("charset=([^;]+)").find(type)?.groupValues?.get(1)
|
||||
return WebResourceResponse(mime, charset, 200, "OK", cors(), ByteArrayInputStream(bytes))
|
||||
}
|
||||
|
||||
/** The map fetches from the server's origin; the store's answer has to allow it as Mapbox's own does. */
|
||||
private fun cors(): MutableMap<String, String> = mutableMapOf("Access-Control-Allow-Origin" to "*", "Cache-Control" to "no-store")
|
||||
|
||||
private fun created(meta: File): Long = runCatching { meta.readLines().first().toLong() }.getOrDefault(0L)
|
||||
|
||||
@Synchronized
|
||||
private fun store(body: File, meta: File, bytes: ByteArray, type: String, now: Long) {
|
||||
runCatching {
|
||||
body.writeBytes(bytes)
|
||||
meta.writeText("$now\n$type")
|
||||
}
|
||||
if (++writesSincePrune >= 200) {
|
||||
writesSincePrune = 0
|
||||
prune()
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops what is past 30 days, then the least recently used while the store is over its limit. */
|
||||
@Synchronized
|
||||
fun prune() {
|
||||
val root = dir ?: return
|
||||
val now = System.currentTimeMillis()
|
||||
val bodies = root.listFiles { f -> f.name.endsWith(".bin") }?.toMutableList() ?: return
|
||||
bodies.filter { now - created(File(root, it.name.removeSuffix(".bin") + ".type")) > MAX_AGE_MS }.forEach {
|
||||
remove(root, it)
|
||||
bodies.remove(it)
|
||||
}
|
||||
var total = bodies.sumOf { it.length() }
|
||||
if (total <= MAX_BYTES) return
|
||||
val target = (MAX_BYTES * PRUNE_TARGET).toLong()
|
||||
for (file in bodies.sortedBy { it.lastModified() }) {
|
||||
if (total <= target) break
|
||||
total -= file.length()
|
||||
remove(root, file)
|
||||
}
|
||||
}
|
||||
|
||||
private fun remove(root: File, body: File) {
|
||||
body.delete()
|
||||
File(root, body.name.removeSuffix(".bin") + ".type").delete()
|
||||
}
|
||||
|
||||
fun usage(): Long = dir?.listFiles()?.sumOf { it.length() } ?: 0L
|
||||
|
||||
@Synchronized
|
||||
fun clear() {
|
||||
dir?.listFiles()?.forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
package com.liketrek.trek.tripday
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.drawable.IconCompat
|
||||
import com.liketrek.trek.MainActivity
|
||||
import com.liketrek.trek.R
|
||||
import com.liketrek.trek.widget.TrekIcons
|
||||
import com.liketrek.trek.widget.WidgetSnapshot
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
|
||||
/**
|
||||
* The travel day as a Live Update, the Android counterpart of the iOS Live
|
||||
* Activity (TripDayLiveActivity.swift): an ongoing notification with the next
|
||||
* stop, its time as the status-bar chip and a countdown, and the day's stops as
|
||||
* a segmented progress bar. Android 16 promotes it to the top of the shade and
|
||||
* the lock screen (ProgressStyle, POST_PROMOTED_NOTIFICATIONS); older versions
|
||||
* show the same content as a quiet ongoing notification with a plain bar.
|
||||
*
|
||||
* The UI starts, updates and ends it (TrekShell.syncTripDay / endTripDay), and
|
||||
* it lapses on its own at midnight, so a forgotten one never lingers.
|
||||
*/
|
||||
object TripDayNotification {
|
||||
const val CHANNEL = "tripday"
|
||||
private const val ID = 0x7d1
|
||||
|
||||
data class State(
|
||||
val tripTitle: String,
|
||||
val path: String,
|
||||
val dayLabel: String,
|
||||
val nextName: String,
|
||||
val nextTime: String?,
|
||||
/** Minutes after midnight of the next stop, for the countdown. */
|
||||
val nextMinutes: Int?,
|
||||
val done: Int,
|
||||
val total: Int,
|
||||
/** #rrggbb of each stop, for the segments; may be empty. */
|
||||
val colors: List<String?> = emptyList(),
|
||||
)
|
||||
|
||||
fun ensureChannel(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val manager = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
if (manager.getNotificationChannel(CHANNEL) != null) return
|
||||
// Default importance: low would keep it out of the status bar chip and promotion.
|
||||
val channel = NotificationChannel(CHANNEL, context.getString(R.string.push_channel_tripday), NotificationManager.IMPORTANCE_DEFAULT).apply {
|
||||
description = context.getString(R.string.push_channel_tripday_description)
|
||||
setSound(null, null)
|
||||
enableVibration(false)
|
||||
setShowBadge(false)
|
||||
}
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
/** Whether it can be shown at all: notifications allowed, and the channel not switched off. */
|
||||
fun allowed(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= 33 &&
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return false
|
||||
}
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
if (!manager.areNotificationsEnabled()) return false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val channel = context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL)
|
||||
if (channel != null && channel.importance == NotificationManager.IMPORTANCE_NONE) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Shows the day, or updates the one showing. False when notifications are off. */
|
||||
fun show(context: Context, state: State): Boolean {
|
||||
ensureChannel(context)
|
||||
if (!allowed(context)) return false
|
||||
try {
|
||||
NotificationManagerCompat.from(context).notify(ID, build(context, state))
|
||||
} catch (e: SecurityException) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun end(context: Context) {
|
||||
NotificationManagerCompat.from(context).cancel(ID)
|
||||
}
|
||||
|
||||
fun build(context: Context, state: State, today: LocalDate = LocalDate.now()): android.app.Notification {
|
||||
val open = Intent(Intent.ACTION_VIEW, Uri.parse(WidgetSnapshot.link(state.path)), context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
val tap = PendingIntent.getActivity(context, ID, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
val zone = ZoneId.systemDefault()
|
||||
val midnight = today.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val remaining = (midnight - System.currentTimeMillis()).coerceAtLeast(60_000L)
|
||||
|
||||
val builder = NotificationCompat.Builder(context, CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_trek)
|
||||
.setContentTitle(state.nextName)
|
||||
.setContentText(listOfNotNull(state.nextTime, state.tripTitle).joinToString(" "))
|
||||
.setSubText(state.dayLabel)
|
||||
.setContentIntent(tap)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setSilent(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setTimeoutAfter(remaining)
|
||||
.setRequestPromotedOngoing(true)
|
||||
|
||||
state.nextTime?.let { builder.setShortCriticalText(it) }
|
||||
state.nextMinutes?.let { minutes ->
|
||||
val at = today.atTime(LocalTime.of((minutes / 60).coerceIn(0, 23), minutes % 60)).atZone(zone).toInstant().toEpochMilli()
|
||||
if (at > System.currentTimeMillis()) {
|
||||
builder.setWhen(at).setShowWhen(true).setUsesChronometer(true).setChronometerCountDown(true)
|
||||
}
|
||||
}
|
||||
|
||||
val total = state.total.coerceAtLeast(1)
|
||||
val done = state.done.coerceIn(0, total)
|
||||
val style = NotificationCompat.ProgressStyle()
|
||||
.setStyledByProgress(true)
|
||||
.setProgressTrackerIcon(IconCompat.createWithBitmap(TrekIcons.bitmap(TrekIcons.vector("figure.walk"), 72, ContextCompat.getColor(context, R.color.notification_accent))))
|
||||
for (i in 0 until total) {
|
||||
val color = state.colors.getOrNull(i)?.let(::parseColor) ?: ContextCompat.getColor(context, R.color.tripday_segment)
|
||||
style.addProgressSegment(NotificationCompat.ProgressStyle.Segment(1).setColor(color))
|
||||
}
|
||||
style.setProgress(done)
|
||||
builder.setStyle(style)
|
||||
// Before Android 16 the style falls back to nothing: the plain bar carries the progress.
|
||||
if (Build.VERSION.SDK_INT < 36) builder.setProgress(total, done, false)
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
private fun parseColor(css: String): Int? = runCatching { android.graphics.Color.parseColor(css) }.getOrNull()
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.liketrek.trek.ui
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/**
|
||||
* The theme of the app's own native screens (the share sheet, the widget's trip
|
||||
* picker): Material You's wallpaper colours on Android 12 and later, TREK's
|
||||
* neutral palette before that, light and dark with the system.
|
||||
*/
|
||||
@Composable
|
||||
fun TrekMaterialTheme(content: @Composable () -> Unit) {
|
||||
val dark = isSystemInDarkTheme()
|
||||
val context = LocalContext.current
|
||||
val colors = when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> if (dark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
dark -> darkColorScheme(
|
||||
primary = Color(0xFFE4E4E7),
|
||||
onPrimary = Color(0xFF101013),
|
||||
secondary = Color(0xFF8AAEF0),
|
||||
secondaryContainer = Color(0xFF233250),
|
||||
onSecondaryContainer = Color(0xFFDCE6FA),
|
||||
surface = Color(0xFF0C0C0F),
|
||||
surfaceContainerLow = Color(0xFF16161A),
|
||||
surfaceContainer = Color(0xFF1B1B21),
|
||||
surfaceContainerHigh = Color(0xFF232329),
|
||||
onSurface = Color(0xFFF5F5F7),
|
||||
onSurfaceVariant = Color(0xFF9C9CA3),
|
||||
)
|
||||
else -> lightColorScheme(
|
||||
primary = Color(0xFF111827),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
secondary = Color(0xFF4A7DDB),
|
||||
secondaryContainer = Color(0xFFE4EAF7),
|
||||
onSecondaryContainer = Color(0xFF1B2F57),
|
||||
surface = Color(0xFFFDFCF9),
|
||||
surfaceContainerLow = Color(0xFFF4F2EE),
|
||||
surfaceContainer = Color(0xFFEFEDE8),
|
||||
surfaceContainerHigh = Color(0xFFE9E7E1),
|
||||
onSurface = Color(0xFF101013),
|
||||
onSurfaceVariant = Color(0xFF68686F),
|
||||
)
|
||||
}
|
||||
MaterialTheme(colorScheme = colors, content = content)
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.AcUnit
|
||||
import androidx.compose.material.icons.rounded.AccountBalance
|
||||
import androidx.compose.material.icons.rounded.Backpack
|
||||
import androidx.compose.material.icons.rounded.BeachAccess
|
||||
import androidx.compose.material.icons.rounded.Bed
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material.icons.rounded.Bookmark
|
||||
import androidx.compose.material.icons.rounded.CalendarMonth
|
||||
import androidx.compose.material.icons.rounded.CameraAlt
|
||||
import androidx.compose.material.icons.rounded.Chat
|
||||
import androidx.compose.material.icons.rounded.CheckCircle
|
||||
import androidx.compose.material.icons.rounded.Checklist
|
||||
import androidx.compose.material.icons.rounded.Cloud
|
||||
import androidx.compose.material.icons.rounded.CreditCard
|
||||
import androidx.compose.material.icons.rounded.DirectionsBoat
|
||||
import androidx.compose.material.icons.rounded.DirectionsBus
|
||||
import androidx.compose.material.icons.rounded.DirectionsCar
|
||||
import androidx.compose.material.icons.rounded.DirectionsRun
|
||||
import androidx.compose.material.icons.rounded.DirectionsWalk
|
||||
import androidx.compose.material.icons.rounded.Event
|
||||
import androidx.compose.material.icons.rounded.Favorite
|
||||
import androidx.compose.material.icons.rounded.FitnessCenter
|
||||
import androidx.compose.material.icons.rounded.Flag
|
||||
import androidx.compose.material.icons.rounded.Flight
|
||||
import androidx.compose.material.icons.rounded.FlightTakeoff
|
||||
import androidx.compose.material.icons.rounded.Dehaze
|
||||
import androidx.compose.material.icons.rounded.Forest
|
||||
import androidx.compose.material.icons.rounded.Grain
|
||||
import androidx.compose.material.icons.rounded.Group
|
||||
import androidx.compose.material.icons.rounded.Hiking
|
||||
import androidx.compose.material.icons.rounded.Home
|
||||
import androidx.compose.material.icons.rounded.Hotel
|
||||
import androidx.compose.material.icons.rounded.Landscape
|
||||
import androidx.compose.material.icons.rounded.LocalBar
|
||||
import androidx.compose.material.icons.rounded.LocalCafe
|
||||
import androidx.compose.material.icons.rounded.LocalHospital
|
||||
import androidx.compose.material.icons.rounded.LocalLibrary
|
||||
import androidx.compose.material.icons.rounded.Luggage
|
||||
import androidx.compose.material.icons.rounded.Map
|
||||
import androidx.compose.material.icons.rounded.MusicNote
|
||||
import androidx.compose.material.icons.rounded.Navigation
|
||||
import androidx.compose.material.icons.rounded.Park
|
||||
import androidx.compose.material.icons.rounded.Place
|
||||
import androidx.compose.material.icons.rounded.Poll
|
||||
import androidx.compose.material.icons.rounded.Public
|
||||
import androidx.compose.material.icons.rounded.Restaurant
|
||||
import androidx.compose.material.icons.rounded.Sailing
|
||||
import androidx.compose.material.icons.rounded.Schedule
|
||||
import androidx.compose.material.icons.rounded.ShoppingBag
|
||||
import androidx.compose.material.icons.rounded.Star
|
||||
import androidx.compose.material.icons.rounded.Storefront
|
||||
import androidx.compose.material.icons.rounded.Thunderstorm
|
||||
import androidx.compose.material.icons.rounded.TheaterComedy
|
||||
import androidx.compose.material.icons.rounded.ConfirmationNumber
|
||||
import androidx.compose.material.icons.rounded.Train
|
||||
import androidx.compose.material.icons.rounded.Water
|
||||
import androidx.compose.material.icons.rounded.WbCloudy
|
||||
import androidx.compose.material.icons.rounded.WbSunny
|
||||
import androidx.compose.material.icons.rounded.Cabin
|
||||
import androidx.compose.ui.graphics.asAndroidPath
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.VectorGroup
|
||||
import androidx.compose.ui.graphics.vector.VectorNode
|
||||
import androidx.compose.ui.graphics.vector.VectorPath
|
||||
import androidx.compose.ui.graphics.vector.PathParser
|
||||
import androidx.glance.ImageProvider
|
||||
|
||||
/**
|
||||
* The widgets' icons: the Material Symbols (rounded) counterparts of the SF
|
||||
* Symbols the snapshot names, so one snapshot draws on both platforms. A widget
|
||||
* is RemoteViews, which cannot draw a Compose vector, so each icon is drawn
|
||||
* once into a small white bitmap and tinted by the widget's theme colour.
|
||||
*/
|
||||
object TrekIcons {
|
||||
/** The SF Symbol names client/src/native/widgetExtras.ts and widgets.ts use, and a few of the widgets' own. */
|
||||
private val SYMBOLS: Map<String, ImageVector> = mapOf(
|
||||
"airplane" to Icons.Rounded.Flight,
|
||||
"airplane.departure" to Icons.Rounded.FlightTakeoff,
|
||||
"tram.fill" to Icons.Rounded.Train,
|
||||
"bus.fill" to Icons.Rounded.DirectionsBus,
|
||||
"car.fill" to Icons.Rounded.DirectionsCar,
|
||||
"ferry.fill" to Icons.Rounded.DirectionsBoat,
|
||||
"sailboat.fill" to Icons.Rounded.Sailing,
|
||||
"bed.double.fill" to Icons.Rounded.Hotel,
|
||||
"house.fill" to Icons.Rounded.Home,
|
||||
"tent.fill" to Icons.Rounded.Cabin,
|
||||
"fork.knife" to Icons.Rounded.Restaurant,
|
||||
"cup.and.saucer.fill" to Icons.Rounded.LocalCafe,
|
||||
"mug.fill" to Icons.Rounded.LocalCafe,
|
||||
"wineglass.fill" to Icons.Rounded.LocalBar,
|
||||
"ticket.fill" to Icons.Rounded.ConfirmationNumber,
|
||||
"theatermasks.fill" to Icons.Rounded.TheaterComedy,
|
||||
"music.note" to Icons.Rounded.MusicNote,
|
||||
"figure.hiking" to Icons.Rounded.Hiking,
|
||||
"figure.walk" to Icons.Rounded.DirectionsWalk,
|
||||
"figure.run" to Icons.Rounded.DirectionsRun,
|
||||
"dumbbell.fill" to Icons.Rounded.FitnessCenter,
|
||||
"bookmark.fill" to Icons.Rounded.Bookmark,
|
||||
"building.columns.fill" to Icons.Rounded.AccountBalance,
|
||||
"building.2.fill" to Icons.Rounded.AccountBalance,
|
||||
"books.vertical.fill" to Icons.Rounded.LocalLibrary,
|
||||
"storefront.fill" to Icons.Rounded.Storefront,
|
||||
"bag.fill" to Icons.Rounded.ShoppingBag,
|
||||
"backpack.fill" to Icons.Rounded.Backpack,
|
||||
"suitcase.rolling.fill" to Icons.Rounded.Luggage,
|
||||
"creditcard.fill" to Icons.Rounded.CreditCard,
|
||||
"cross.case.fill" to Icons.Rounded.LocalHospital,
|
||||
"camera.fill" to Icons.Rounded.CameraAlt,
|
||||
"camera.macro" to Icons.Rounded.Park,
|
||||
"leaf.fill" to Icons.Rounded.Park,
|
||||
"tree.fill" to Icons.Rounded.Forest,
|
||||
"mountain.2.fill" to Icons.Rounded.Landscape,
|
||||
"water.waves" to Icons.Rounded.Water,
|
||||
"beach.umbrella.fill" to Icons.Rounded.BeachAccess,
|
||||
"sun.max.fill" to Icons.Rounded.WbSunny,
|
||||
"bolt.fill" to Icons.Rounded.Bolt,
|
||||
"heart.fill" to Icons.Rounded.Favorite,
|
||||
"star.fill" to Icons.Rounded.Star,
|
||||
"flag.fill" to Icons.Rounded.Flag,
|
||||
"map.fill" to Icons.Rounded.Map,
|
||||
"safari.fill" to Icons.Rounded.Navigation,
|
||||
"location.north.fill" to Icons.Rounded.Navigation,
|
||||
"location.fill" to Icons.Rounded.Place,
|
||||
"globe.europe.africa.fill" to Icons.Rounded.Public,
|
||||
"calendar" to Icons.Rounded.CalendarMonth,
|
||||
"clock" to Icons.Rounded.Schedule,
|
||||
"checklist" to Icons.Rounded.Checklist,
|
||||
"checkmark.circle.fill" to Icons.Rounded.CheckCircle,
|
||||
"person.2.fill" to Icons.Rounded.Group,
|
||||
"bubble.left.fill" to Icons.Rounded.Chat,
|
||||
"chart.bar.fill" to Icons.Rounded.Poll,
|
||||
"event" to Icons.Rounded.Event,
|
||||
)
|
||||
|
||||
/** A booking kind's symbol and colour, the same pairs as TrekStyle.swift. */
|
||||
fun booking(kind: String): Pair<String, Int> = when (kind) {
|
||||
"flight" -> "airplane" to 0xFF4A7DDB.toInt()
|
||||
"train" -> "tram.fill" to 0xFF2FA37A.toInt()
|
||||
"bus" -> "bus.fill" to 0xFF2BA6A6.toInt()
|
||||
"car" -> "car.fill" to 0xFFD6673B.toInt()
|
||||
"cruise", "ferry", "boat" -> "ferry.fill" to 0xFF2E8BC0.toInt()
|
||||
"hotel" -> "bed.double.fill" to 0xFF8E6CD9.toInt()
|
||||
"restaurant" -> "fork.knife" to 0xFFE8A13A.toInt()
|
||||
"event" -> "ticket.fill" to 0xFFD6408B.toInt()
|
||||
"tour" -> "figure.hiking" to 0xFF4E9F3D.toInt()
|
||||
else -> "bookmark.fill" to 0xFF7A7A85.toInt()
|
||||
}
|
||||
|
||||
/** The provider's main weather condition as an icon. */
|
||||
fun weather(main: String): ImageVector = when (main.lowercase()) {
|
||||
"clear" -> Icons.Rounded.WbSunny
|
||||
"clouds" -> Icons.Rounded.WbCloudy
|
||||
"rain", "drizzle" -> Icons.Rounded.Grain
|
||||
"thunderstorm" -> Icons.Rounded.Thunderstorm
|
||||
"snow" -> Icons.Rounded.AcUnit
|
||||
"mist", "fog", "haze" -> Icons.Rounded.Dehaze
|
||||
else -> Icons.Rounded.Cloud
|
||||
}
|
||||
|
||||
fun vector(symbol: String?): ImageVector = symbol?.let { SYMBOLS[it] } ?: Icons.Rounded.Place
|
||||
|
||||
private val cache = HashMap<Pair<ImageVector, Int>, Bitmap>()
|
||||
|
||||
/** The icon as a white bitmap of [sizePx], tinted where it is drawn. */
|
||||
@Synchronized
|
||||
fun bitmap(vector: ImageVector, sizePx: Int = 48): Bitmap = cache.getOrPut(vector to sizePx) { render(vector, sizePx) }
|
||||
|
||||
fun provider(symbol: String?, sizePx: Int = 48): ImageProvider = ImageProvider(bitmap(vector(symbol), sizePx))
|
||||
|
||||
fun provider(vector: ImageVector, sizePx: Int = 48): ImageProvider = ImageProvider(bitmap(vector, sizePx))
|
||||
|
||||
/** The icon in [color], for places that draw it as it is (a notification's progress tracker). */
|
||||
fun bitmap(vector: ImageVector, sizePx: Int, color: Int): Bitmap = render(vector, sizePx, color)
|
||||
|
||||
private fun render(vector: ImageVector, sizePx: Int, color: Int = android.graphics.Color.WHITE): Bitmap {
|
||||
val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val scale = Matrix().apply { setScale(sizePx / vector.viewportWidth, sizePx / vector.viewportHeight) }
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
this.color = color
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
fun draw(node: VectorNode) {
|
||||
when (node) {
|
||||
is VectorGroup -> node.forEach { draw(it) }
|
||||
is VectorPath -> {
|
||||
val path: Path = PathParser().addPathNodes(node.pathData).toPath().asAndroidPath()
|
||||
path.fillType = if (node.pathFillType == androidx.compose.ui.graphics.PathFillType.EvenOdd) {
|
||||
Path.FillType.EVEN_ODD
|
||||
} else {
|
||||
Path.FillType.WINDING
|
||||
}
|
||||
path.transform(scale)
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
}
|
||||
}
|
||||
draw(vector.root)
|
||||
return bitmap
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import androidx.glance.appwidget.GlanceAppWidget
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import androidx.glance.appwidget.GlanceAppWidgetReceiver
|
||||
import androidx.glance.appwidget.updateAll
|
||||
import kotlin.reflect.KClass
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** The widget providers the manifest lists, one per widget in the picker. */
|
||||
abstract class TrekWidgetReceiver : GlanceAppWidgetReceiver() {
|
||||
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
|
||||
super.onDeleted(context, appWidgetIds)
|
||||
WidgetStore.forget(context, appWidgetIds)
|
||||
}
|
||||
}
|
||||
|
||||
class TripWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = TripWidget()
|
||||
}
|
||||
|
||||
class TodayWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = TodayWidget()
|
||||
}
|
||||
|
||||
class BookingsWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = BookingsWidget()
|
||||
}
|
||||
|
||||
class TodosWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = TodosWidget()
|
||||
}
|
||||
|
||||
class PackingWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = PackingWidget()
|
||||
}
|
||||
|
||||
class AtlasWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = AtlasWidget()
|
||||
}
|
||||
|
||||
class CollabWidgetReceiver : TrekWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = CollabWidget()
|
||||
}
|
||||
|
||||
/** Redraws every placed TREK widget after the app wrote a new snapshot. */
|
||||
object TrekWidgetUpdater {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
val receivers: List<KClass<out GlanceAppWidgetReceiver>> = listOf(
|
||||
TripWidgetReceiver::class,
|
||||
TodayWidgetReceiver::class,
|
||||
BookingsWidgetReceiver::class,
|
||||
TodosWidgetReceiver::class,
|
||||
PackingWidgetReceiver::class,
|
||||
AtlasWidgetReceiver::class,
|
||||
CollabWidgetReceiver::class,
|
||||
)
|
||||
|
||||
/** The widget a placed widget id belongs to, by its provider. */
|
||||
fun widgetFor(context: Context, appWidgetId: Int): GlanceAppWidget? {
|
||||
val provider = android.appwidget.AppWidgetManager.getInstance(context).getAppWidgetInfo(appWidgetId)?.provider?.className
|
||||
?: return null
|
||||
val receiver = receivers.firstOrNull { it.java.name == provider } ?: return null
|
||||
return receiver.java.getDeclaredConstructor().newInstance().glanceAppWidget
|
||||
}
|
||||
|
||||
fun widgets(): List<GlanceAppWidget> =
|
||||
listOf(TripWidget(), TodayWidget(), BookingsWidget(), TodosWidget(), PackingWidget(), AtlasWidget(), CollabWidget())
|
||||
|
||||
@JvmStatic
|
||||
fun refreshAll(context: Context) {
|
||||
val app = context.applicationContext
|
||||
scope.launch { for (widget in widgets()) runCatching { widget.updateAll(app) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 15's widget picker shows a live preview drawn by the widget itself
|
||||
* (providePreview) instead of a static image. The system rate-limits the
|
||||
* call, so it runs once per app version.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun publishPreviews(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < 35) return
|
||||
val app = context.applicationContext
|
||||
val prefs = app.getSharedPreferences("trek.widgets", Context.MODE_PRIVATE)
|
||||
val version = runCatching { app.packageManager.getPackageInfo(app.packageName, 0).lastUpdateTime }.getOrDefault(0L)
|
||||
if (prefs.getLong("previews", -1L) == version) return
|
||||
scope.launch {
|
||||
val manager = GlanceAppWidgetManager(app)
|
||||
val all = receivers.all { runCatching { manager.setWidgetPreviews(it); true }.getOrDefault(false) }
|
||||
if (all) prefs.edit().putLong("previews", version).apply()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,815 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.CalendarMonth
|
||||
import androidx.compose.material.icons.rounded.CheckCircle
|
||||
import androidx.compose.material.icons.rounded.Flight
|
||||
import androidx.compose.material.icons.rounded.Group
|
||||
import androidx.compose.material.icons.rounded.Luggage
|
||||
import androidx.compose.material.icons.rounded.Place
|
||||
import androidx.compose.material.icons.rounded.Public
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.glance.ColorFilter
|
||||
import androidx.glance.GlanceId
|
||||
import androidx.glance.GlanceModifier
|
||||
import androidx.glance.GlanceTheme
|
||||
import androidx.glance.Image
|
||||
import androidx.glance.ImageProvider
|
||||
import androidx.glance.LocalContext
|
||||
import androidx.glance.LocalSize
|
||||
import androidx.glance.action.clickable
|
||||
import androidx.glance.appwidget.GlanceAppWidget
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import androidx.glance.appwidget.SizeMode
|
||||
import androidx.glance.appwidget.cornerRadius
|
||||
import androidx.glance.appwidget.provideContent
|
||||
import androidx.glance.background
|
||||
import androidx.glance.layout.Alignment
|
||||
import androidx.glance.layout.Box
|
||||
import androidx.glance.layout.Column
|
||||
import androidx.glance.layout.ColumnScope
|
||||
import androidx.glance.layout.ContentScale
|
||||
import androidx.glance.layout.Row
|
||||
import androidx.glance.layout.Spacer
|
||||
import androidx.glance.layout.fillMaxHeight
|
||||
import androidx.glance.layout.fillMaxSize
|
||||
import androidx.glance.layout.fillMaxWidth
|
||||
import androidx.glance.layout.height
|
||||
import androidx.glance.layout.padding
|
||||
import androidx.glance.layout.size
|
||||
import androidx.glance.layout.width
|
||||
import androidx.glance.text.FontWeight
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextAlign
|
||||
import androidx.glance.text.TextStyle
|
||||
import androidx.glance.unit.ColorProvider
|
||||
import java.time.LocalDate
|
||||
|
||||
/** The sizes every TREK widget lays itself out for (a 2x2, a 4x2 and a 4x4 cell block). */
|
||||
object TrekSizes {
|
||||
val SMALL = DpSize(120.dp, 120.dp)
|
||||
val WIDE = DpSize(250.dp, 120.dp)
|
||||
val LARGE = DpSize(250.dp, 260.dp)
|
||||
val all = setOf(SMALL, WIDE, LARGE)
|
||||
}
|
||||
|
||||
private val DpSize.isWide get() = width >= 220.dp
|
||||
private val DpSize.isTall get() = height >= 220.dp
|
||||
|
||||
/**
|
||||
* A TREK widget: reads the snapshot of the trip it is set to (WidgetStore) and
|
||||
* draws [Content]. The app writes the snapshot and refreshes the widgets
|
||||
* (TrekWidgetUpdater); [preview] draws the same views from a sample trip for
|
||||
* the widget picker and the screenshot tests.
|
||||
*/
|
||||
abstract class TrekWidget : GlanceAppWidget() {
|
||||
override val sizeMode: SizeMode = SizeMode.Responsive(TrekSizes.all)
|
||||
override val previewSizeMode = SizeMode.Responsive(TrekSizes.all)
|
||||
|
||||
/** Whether the widget shows one trip, so the trip picker applies to it. */
|
||||
open val perTrip: Boolean = true
|
||||
|
||||
override suspend fun provideGlance(context: Context, id: GlanceId) {
|
||||
val appWidgetId = runCatching { GlanceAppWidgetManager(context).getAppWidgetId(id) }.getOrDefault(-1)
|
||||
provideContent {
|
||||
// Read inside the composition: a session outlives one update, and every
|
||||
// write (the dashboard's, then each trip's) must reach it.
|
||||
val version by WidgetStore.version.collectAsState()
|
||||
val snapshot = remember(version) {
|
||||
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
|
||||
WidgetStore.load(context, tripId)
|
||||
}
|
||||
TrekWidgetTheme.Themed { Content(snapshot) }
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun providePreview(context: Context, widgetCategory: Int) {
|
||||
provideContent { TrekWidgetTheme.Themed { Content(WidgetSamples.snapshot(running = false)) } }
|
||||
}
|
||||
|
||||
@Composable
|
||||
abstract fun Content(snapshot: WidgetSnapshot?)
|
||||
}
|
||||
|
||||
// ---- Trip ----
|
||||
|
||||
/** The trip: a countdown on its own cover before it starts, the day and what comes next while it runs. */
|
||||
class TripWidget : TrekWidget() {
|
||||
@Composable
|
||||
override fun Content(snapshot: WidgetSnapshot?) {
|
||||
val context = LocalContext.current
|
||||
val trip = snapshot?.trip
|
||||
if (snapshot == null || trip == null) {
|
||||
EmptyWidget(snapshot?.labels?.noTrip ?: WidgetSamples.emptyText(context))
|
||||
return
|
||||
}
|
||||
val size = LocalSize.current
|
||||
WidgetFrame(onClick = openPath(context, trip.path), background = TrekStatus.scrim, padding = 0.dp) {
|
||||
Box(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.cover(trip.cover) ?: WidgetArt.sky(trip.title)),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
)
|
||||
Image(
|
||||
provider = ImageProvider(com.liketrek.trek.R.drawable.widget_scrim),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.FillBounds,
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
)
|
||||
Column(modifier = GlanceModifier.fillMaxSize().padding(14.dp)) {
|
||||
val today = snapshot.today
|
||||
if (today != null) Running(snapshot, trip, today, size) else Upcoming(snapshot, trip, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Upcoming(snapshot: WidgetSnapshot, trip: WidgetSnapshot.Trip, size: DpSize) {
|
||||
val context = LocalContext.current
|
||||
val labels = snapshot.labels
|
||||
val days = (snapshot.daysUntilStart() ?: 0L).coerceAtLeast(0L)
|
||||
if (!size.isWide) {
|
||||
// Small: the number carries it, with the trip's name under it.
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Flight, TrekStatus.white, 16.dp)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
snapshot.weather?.let { WeatherChip(it, onPhoto = true) }
|
||||
}
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Countdown(days, labels, ring = false)
|
||||
Line(trip.title, 14.sp, TrekStatus.white, FontWeight.Bold, maxLines = 1)
|
||||
return
|
||||
}
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
Eyebrow(labels.nextTrip, TrekStatus.whiteMuted)
|
||||
Spacer(GlanceModifier.height(2.dp))
|
||||
Line(trip.title, if (size.isTall) 22.sp else 18.sp, TrekStatus.white, FontWeight.Bold, maxLines = 2)
|
||||
trip.place?.let {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Place, TrekStatus.whiteMuted, 12.dp)
|
||||
Spacer(GlanceModifier.width(3.dp))
|
||||
Line(it, 12.sp, TrekStatus.whiteMuted, FontWeight.Medium)
|
||||
}
|
||||
}
|
||||
if (size.isTall) {
|
||||
RelativeDay.range(context, trip.start, trip.end)?.let {
|
||||
Spacer(GlanceModifier.height(6.dp))
|
||||
Chip(it, TrekStatus.glass, TrekStatus.white, TrekIcons.provider(Icons.Rounded.CalendarMonth), TrekStatus.white)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(GlanceModifier.width(10.dp))
|
||||
Countdown(days, labels, ring = true)
|
||||
}
|
||||
if (size.isTall) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
TripFacts(snapshot, onPhoto = true)
|
||||
snapshot.bookings.firstOrNull()?.let {
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
BookingRow(it, labels, onPhoto = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The days to go: a big number, or today and tomorrow in words; around a ring of the last 60 days on the wide sizes. */
|
||||
@Composable
|
||||
private fun Countdown(days: Long, labels: WidgetSnapshot.Labels, ring: Boolean) {
|
||||
val number: @Composable () -> Unit = {
|
||||
when (days) {
|
||||
0L -> Line(labels.todayShort, 26.sp, TrekStatus.white, FontWeight.Bold)
|
||||
1L -> Line(labels.tomorrow, 20.sp, TrekStatus.white, FontWeight.Bold)
|
||||
else -> if (ring) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(
|
||||
text = days.toString(),
|
||||
style = TextStyle(color = TrekStatus.white, fontSize = if (days > 99) 22.sp else 28.sp, fontWeight = FontWeight.Bold),
|
||||
maxLines = 1,
|
||||
)
|
||||
Eyebrow(labels.days, TrekStatus.whiteMuted)
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(days.toString(), style = TextStyle(color = TrekStatus.white, fontSize = 34.sp, fontWeight = FontWeight.Bold), maxLines = 1)
|
||||
Spacer(GlanceModifier.width(4.dp))
|
||||
Line(labels.days, 13.sp, TrekStatus.whiteMuted, FontWeight.Bold, modifier = GlanceModifier.padding(bottom = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!ring) {
|
||||
number()
|
||||
return
|
||||
}
|
||||
val progress = 1f - (days.coerceAtMost(60L).toFloat() / 60f)
|
||||
Box(modifier = GlanceModifier.size(84.dp), contentAlignment = Alignment.Center) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.ring(progress)),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(TrekStatus.white),
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
)
|
||||
number()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Running(snapshot: WidgetSnapshot, trip: WidgetSnapshot.Trip, today: WidgetSnapshot.Today, size: DpSize) {
|
||||
val labels = snapshot.labels
|
||||
val now = nowMinutes()
|
||||
val next = today.stops.firstOrNull { (it.minutes ?: -1) >= now } ?: today.stops.lastOrNull()
|
||||
val index = today.index ?: 1
|
||||
val total = today.total ?: snapshot.tripLength ?: 1
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Eyebrow(if (size.isWide) trip.title else today.dayLabel, TrekStatus.whiteMuted, GlanceModifier.defaultWeight())
|
||||
snapshot.weather?.let { WeatherChip(it, onPhoto = true) }
|
||||
}
|
||||
if (size.isWide) Line(today.dayLabel, 20.sp, TrekStatus.white, FontWeight.Bold, modifier = GlanceModifier.padding(top = 2.dp))
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
DaySegments(index, total, TrekStatus.white)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
if (size.isWide) {
|
||||
Column(modifier = GlanceModifier.fillMaxWidth().background(TrekStatus.glass).cornerRadius(16.dp).padding(10.dp)) {
|
||||
StopList(today.stops, now, limit = if (size.isTall) 5 else 1, onPhoto = true, nothing = labels.nothingPlanned, nowLabel = labels.now)
|
||||
}
|
||||
} else if (next != null) {
|
||||
Line(next.time ?: labels.today, 26.sp, TrekStatus.white, FontWeight.Bold)
|
||||
Line(next.name, 14.sp, TrekStatus.white, FontWeight.Bold, maxLines = 2)
|
||||
} else {
|
||||
Line(labels.nothingPlanned, 14.sp, TrekStatus.white, FontWeight.Bold, maxLines = 3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The trip's numbers: days, places, travellers. */
|
||||
@Composable
|
||||
private fun TripFacts(snapshot: WidgetSnapshot, onPhoto: Boolean) {
|
||||
val labels = snapshot.labels
|
||||
val facts = listOfNotNull(
|
||||
snapshot.tripLength?.let { it to labels.days },
|
||||
snapshot.trip?.placeCount?.let { it to labels.places },
|
||||
snapshot.trip?.memberCount?.let { it to labels.travellers },
|
||||
)
|
||||
Row(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
facts.forEachIndexed { i, (value, label) ->
|
||||
Column(
|
||||
modifier = GlanceModifier.defaultWeight().background(if (onPhoto) TrekStatus.glass else GlanceTheme.colors.secondaryContainer)
|
||||
.cornerRadius(14.dp).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
Line(value.toString(), 18.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer, FontWeight.Bold)
|
||||
Line(label, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSecondaryContainer)
|
||||
}
|
||||
if (i < facts.size - 1) Spacer(GlanceModifier.width(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Today ----
|
||||
|
||||
/** Today's plan as a timeline, with the weather and what is next. */
|
||||
class TodayWidget : TrekWidget() {
|
||||
@Composable
|
||||
override fun Content(snapshot: WidgetSnapshot?) {
|
||||
val context = LocalContext.current
|
||||
val size = LocalSize.current
|
||||
val labels = snapshot?.labels
|
||||
val today = snapshot?.today
|
||||
val trip = snapshot?.trip
|
||||
if (snapshot == null || labels == null || trip == null) {
|
||||
EmptyWidget(labels?.noTrip ?: WidgetSamples.emptyText(context))
|
||||
return
|
||||
}
|
||||
WidgetFrame(onClick = openPath(context, trip.path)) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
if (size.isTall) Eyebrow(if (today != null) labels.today else labels.nextTrip, GlanceTheme.colors.primary)
|
||||
Line(today?.dayLabel ?: trip.title, if (size.isWide) 17.sp else 14.sp, weight = FontWeight.Bold)
|
||||
}
|
||||
snapshot.weather?.let { WeatherChip(it, onPhoto = false) }
|
||||
}
|
||||
Spacer(GlanceModifier.height(if (size.isTall) 10.dp else 6.dp))
|
||||
if (today == null || today.stops.isEmpty()) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
val days = snapshot.daysUntilStart()
|
||||
val text = if (today == null && days != null && days > 0) labels.inDays.replace("{n}", days.toString()) else labels.nothingPlanned
|
||||
Line(text, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 3)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
} else {
|
||||
val limit = when {
|
||||
size.isTall -> 6
|
||||
size.isWide -> 2
|
||||
else -> 1
|
||||
}
|
||||
StopList(today.stops, nowMinutes(), limit, onPhoto = false, nothing = labels.nothingPlanned, nowLabel = labels.now, compact = !size.isWide)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The stops from the next one on, at most [limit], the next one marked. */
|
||||
@Composable
|
||||
fun StopList(
|
||||
stops: List<WidgetSnapshot.Stop>,
|
||||
nowMinutes: Int,
|
||||
limit: Int,
|
||||
onPhoto: Boolean,
|
||||
nothing: String,
|
||||
nowLabel: String,
|
||||
compact: Boolean = false,
|
||||
) {
|
||||
if (stops.isEmpty()) {
|
||||
Line(nothing, 13.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSurfaceVariant)
|
||||
return
|
||||
}
|
||||
val nextIndex = stops.indexOfFirst { (it.minutes ?: -1) >= nowMinutes }.let { if (it < 0) stops.size - 1 else it }
|
||||
// Keep the last done stop in view when there is room, so the day reads as a line.
|
||||
val from = (nextIndex - if (limit > 3) 1 else 0).coerceIn(0, (stops.size - limit).coerceAtLeast(0))
|
||||
val shown = stops.drop(from).take(limit)
|
||||
shown.forEachIndexed { i, stop ->
|
||||
val index = from + i
|
||||
val isNext = index == nextIndex
|
||||
val done = index < nextIndex
|
||||
val ink = when {
|
||||
onPhoto -> if (done) TrekStatus.whiteFaint else TrekStatus.white
|
||||
done -> GlanceTheme.colors.onSurfaceVariant
|
||||
else -> GlanceTheme.colors.onSurface
|
||||
}
|
||||
Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
val accent = cssColor(stop.color) ?: if (onPhoto) TrekStatus.white else GlanceTheme.colors.primary
|
||||
if (compact) {
|
||||
Box(modifier = GlanceModifier.size(8.dp).cornerRadius(4.dp).background(accent)) {}
|
||||
} else {
|
||||
IconBadge(
|
||||
stop.symbol,
|
||||
tint = if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer,
|
||||
background = if (onPhoto) TrekStatus.glass else GlanceTheme.colors.secondaryContainer,
|
||||
size = 26.dp,
|
||||
)
|
||||
}
|
||||
Spacer(GlanceModifier.width(8.dp))
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
Line(stop.name, 13.sp, ink, if (isNext) FontWeight.Bold else FontWeight.Medium)
|
||||
if (compact && stop.time != null) Line(stop.time, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSurfaceVariant)
|
||||
}
|
||||
if (!compact) {
|
||||
if (isNext && !onPhoto) {
|
||||
Chip(stop.time ?: nowLabel, GlanceTheme.colors.primary, GlanceTheme.colors.onPrimary)
|
||||
} else {
|
||||
Line(stop.time ?: "", 12.sp, ink, if (isNext) FontWeight.Bold else FontWeight.Normal)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Bookings ----
|
||||
|
||||
/** The next flights, trains, hotels and tables, and when they are due. */
|
||||
class BookingsWidget : 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 bookings = snapshot.bookings
|
||||
WidgetFrame(onClick = openPath(context, bookings.firstOrNull()?.path ?: snapshot.trip?.path ?: "/")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 14.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
Eyebrow(labels.bookings, GlanceTheme.colors.primary)
|
||||
}
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
if (bookings.isEmpty()) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Line(labels.noBookings, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
} else if (!size.isWide) {
|
||||
val first = bookings.first()
|
||||
val (symbol, color) = TrekIcons.booking(first.kind)
|
||||
IconBadge(symbol, TrekStatus.white, ColorProvider(androidx.compose.ui.graphics.Color(color)), 30.dp)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Line(first.title, 14.sp, weight = FontWeight.Bold, maxLines = 1)
|
||||
Line(
|
||||
listOfNotNull(RelativeDay.label(first.date, labels), first.time).joinToString(", "),
|
||||
12.sp,
|
||||
GlanceTheme.colors.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
val limit = if (size.isTall) 4 else 1
|
||||
bookings.take(limit).forEach { booking ->
|
||||
BookingRow(booking, labels, onPhoto = false)
|
||||
Spacer(GlanceModifier.height(5.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BookingRow(booking: WidgetSnapshot.Booking, labels: WidgetSnapshot.Labels, onPhoto: Boolean) {
|
||||
val context = LocalContext.current
|
||||
val (symbol, color) = TrekIcons.booking(booking.kind)
|
||||
Row(
|
||||
modifier = GlanceModifier.fillMaxWidth()
|
||||
.background(if (onPhoto) TrekStatus.glass else GlanceTheme.colors.surfaceVariant)
|
||||
.cornerRadius(14.dp).padding(horizontal = 8.dp, vertical = 6.dp)
|
||||
.clickable(openPath(context, booking.path)),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
IconBadge(symbol, TrekStatus.white, ColorProvider(androidx.compose.ui.graphics.Color(color)), 30.dp)
|
||||
Spacer(GlanceModifier.width(10.dp))
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
Line(booking.title, 13.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSurface, FontWeight.Bold)
|
||||
booking.detail?.let { Line(it, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSurfaceVariant) }
|
||||
}
|
||||
Spacer(GlanceModifier.width(6.dp))
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
RelativeDay.label(booking.date, labels)?.let { Line(it, 12.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSurface, FontWeight.Bold) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(modifier = GlanceModifier.size(6.dp).cornerRadius(3.dp).background(if (booking.confirmed) TrekStatus.confirmed else TrekStatus.pending)) {}
|
||||
Spacer(GlanceModifier.width(4.dp))
|
||||
Line(booking.time ?: if (booking.confirmed) labels.confirmed else labels.pending, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- To-dos ----
|
||||
|
||||
/** What is still open for the trip, and how far the packing has come. */
|
||||
class TodosWidget : 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 todos = snapshot.todos
|
||||
WidgetFrame(onClick = openPath(context, todos?.path ?: snapshot.trip?.path ?: "/")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.CheckCircle, GlanceTheme.colors.primary, 14.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
Eyebrow(labels.todos, GlanceTheme.colors.primary, GlanceModifier.defaultWeight())
|
||||
if (todos != null && todos.total > 0) Line("${todos.total - todos.open}/${todos.total}", 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold)
|
||||
}
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
if (todos == null || todos.open == 0) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Line(labels.noTodos, 16.sp, weight = FontWeight.Bold)
|
||||
snapshot.trip?.title?.let { Line(it, 12.sp, GlanceTheme.colors.onSurfaceVariant) }
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
} else {
|
||||
if (!size.isWide) {
|
||||
Line(todos.open.toString(), 34.sp, GlanceTheme.colors.primary, FontWeight.Bold)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
}
|
||||
val limit = when {
|
||||
size.isTall -> 6
|
||||
size.isWide -> 3
|
||||
else -> 1
|
||||
}
|
||||
Column(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
todos.items.take(limit).forEach { todo ->
|
||||
Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = GlanceModifier.size(14.dp).cornerRadius(7.dp).background(priorityColor(todo.priority) ?: GlanceTheme.colors.outline),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Box(modifier = GlanceModifier.size(10.dp).cornerRadius(5.dp).background(GlanceTheme.colors.widgetBackground)) {}
|
||||
}
|
||||
Spacer(GlanceModifier.width(8.dp))
|
||||
Line(todo.name, 13.sp, modifier = GlanceModifier.defaultWeight())
|
||||
if (size.isWide) RelativeDay.label(todo.due, labels)?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (size.isWide) Spacer(GlanceModifier.defaultWeight())
|
||||
}
|
||||
val packing = snapshot.packing
|
||||
if (size.isTall && packing != null && packing.total > 0) {
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Luggage, GlanceTheme.colors.onSurfaceVariant, 13.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
Line("${labels.packing}: ${packing.packed}/${packing.total}", 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium)
|
||||
}
|
||||
Spacer(GlanceModifier.height(5.dp))
|
||||
Bar(packing.packed.toFloat() / packing.total, GlanceTheme.colors.primary, GlanceTheme.colors.surfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun priorityColor(priority: Int): ColorProvider? = when (priority) {
|
||||
3 -> TrekStatus.danger
|
||||
2 -> TrekStatus.pending
|
||||
1 -> ColorProvider(androidx.compose.ui.graphics.Color(0xFF4A7DDB))
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Packing ----
|
||||
|
||||
/** How full the bags are, their weight, and what is still missing. */
|
||||
class PackingWidget : 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 packing = snapshot.packing
|
||||
WidgetFrame(onClick = openPath(context, packing?.path ?: snapshot.trip?.path ?: "/")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Luggage, GlanceTheme.colors.primary, 14.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
Eyebrow(labels.packing, GlanceTheme.colors.primary)
|
||||
}
|
||||
if (packing == null || packing.total == 0) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Line(snapshot.trip?.title ?: labels.noTrip, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 3)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
return@Column
|
||||
}
|
||||
val progress = packing.packed.toFloat() / packing.total
|
||||
Spacer(GlanceModifier.height(if (size.isWide) 8.dp else 4.dp))
|
||||
if (!size.isWide) {
|
||||
// Small: the ring is the widget.
|
||||
Box(modifier = GlanceModifier.fillMaxWidth().defaultWeight(), contentAlignment = Alignment.Center) {
|
||||
PackRing(progress, 64.dp)
|
||||
}
|
||||
Line("${packing.packed}/${packing.total} ${labels.packed}", 11.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium)
|
||||
return@Column
|
||||
}
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
PackRing(progress, 64.dp)
|
||||
Spacer(GlanceModifier.width(12.dp))
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
Line("${packing.packed}/${packing.total}", 18.sp, weight = FontWeight.Bold)
|
||||
Line(labels.packed, 12.sp, GlanceTheme.colors.onSurfaceVariant)
|
||||
if (!size.isTall && packing.missing.isNotEmpty()) {
|
||||
Line("${packing.missing.size} ${labels.missing}", 12.sp, GlanceTheme.colors.primary, FontWeight.Medium)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (size.isTall) {
|
||||
Spacer(GlanceModifier.height(10.dp))
|
||||
// Each group in a column of its own: a Glance column takes ten children at most.
|
||||
Column(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
packing.bags.take(2).forEach { bag -> BagRow(bag) }
|
||||
}
|
||||
if (packing.missing.isNotEmpty()) {
|
||||
Spacer(GlanceModifier.height(4.dp))
|
||||
Column(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
Eyebrow(labels.missing)
|
||||
Spacer(GlanceModifier.height(2.dp))
|
||||
packing.missing.take(2).forEach { item ->
|
||||
Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(modifier = GlanceModifier.size(6.dp).cornerRadius(3.dp).background(cssColor(item.color) ?: GlanceTheme.colors.outline)) {}
|
||||
Spacer(GlanceModifier.width(8.dp))
|
||||
Line(item.name, 12.sp, modifier = GlanceModifier.defaultWeight())
|
||||
item.category?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PackRing(progress: Float, size: androidx.compose.ui.unit.Dp) {
|
||||
Box(modifier = GlanceModifier.size(size), contentAlignment = Alignment.Center) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.ring(progress, stroke = 16f)),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(GlanceTheme.colors.primary),
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
)
|
||||
Line("${(progress * 100).toInt()}%", 13.sp, weight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BagRow(bag: WidgetSnapshot.Bag) {
|
||||
val bagColor = cssColor(bag.color) ?: GlanceTheme.colors.primary
|
||||
Column(modifier = GlanceModifier.fillMaxWidth().padding(bottom = 6.dp)) {
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(modifier = GlanceModifier.size(8.dp).cornerRadius(4.dp).background(bagColor)) {}
|
||||
Spacer(GlanceModifier.width(6.dp))
|
||||
Line(bag.name, 12.sp, weight = FontWeight.Medium, modifier = GlanceModifier.defaultWeight())
|
||||
Line(weight(bag.grams) + (bag.limit?.let { " / ${weight(it)}" } ?: ""), 11.sp, GlanceTheme.colors.onSurfaceVariant)
|
||||
}
|
||||
Spacer(GlanceModifier.height(4.dp))
|
||||
Bar(if (bag.limit != null && bag.limit > 0) bag.grams.toFloat() / bag.limit else bag.packed.toFloat() / bag.total.coerceAtLeast(1), bagColor, GlanceTheme.colors.surfaceVariant, 5.dp)
|
||||
}
|
||||
}
|
||||
|
||||
private fun weight(grams: Int): String = if (grams >= 1000) "%.1f kg".format(grams / 1000f) else "$grams g"
|
||||
}
|
||||
|
||||
// ---- Atlas ----
|
||||
|
||||
/** The countries the user has been to, glowing on the world map. Not tied to a trip. */
|
||||
class AtlasWidget : TrekWidget() {
|
||||
override val perTrip = false
|
||||
|
||||
@Composable
|
||||
override fun Content(snapshot: WidgetSnapshot?) {
|
||||
val context = LocalContext.current
|
||||
val size = LocalSize.current
|
||||
val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context))
|
||||
val atlas = snapshot.atlas
|
||||
val codes = atlas?.codes?.toSet() ?: emptySet()
|
||||
WidgetFrame(onClick = openPath(context, "/atlas")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Public, GlanceTheme.colors.primary, 14.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
Eyebrow(context.getString(com.liketrek.trek.R.string.widget_atlas_name), GlanceTheme.colors.primary)
|
||||
}
|
||||
Spacer(GlanceModifier.height(4.dp))
|
||||
val count: @Composable () -> Unit = {
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Line((atlas?.count ?: 0).toString(), if (size.isWide) 34.sp else 30.sp, GlanceTheme.colors.onSurface, FontWeight.Bold)
|
||||
Spacer(GlanceModifier.width(6.dp))
|
||||
Column(modifier = GlanceModifier.padding(bottom = 4.dp)) {
|
||||
Line(labels.countries, 12.sp, GlanceTheme.colors.onSurface, FontWeight.Bold)
|
||||
// 195 countries make the world, as on the Atlas page.
|
||||
if (size.isWide) Line("${((atlas?.count ?: 0) * 100 / 195)}% ${labels.world}", 11.sp, GlanceTheme.colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (size.isWide && !size.isTall) {
|
||||
// Wide: the count beside the map, which gets the height.
|
||||
Row(modifier = GlanceModifier.fillMaxWidth().defaultWeight(), verticalAlignment = Alignment.CenterVertically) {
|
||||
count()
|
||||
Spacer(GlanceModifier.width(10.dp))
|
||||
WorldMap(codes, GlanceModifier.defaultWeight().fillMaxHeight())
|
||||
}
|
||||
} else {
|
||||
count()
|
||||
Spacer(GlanceModifier.height(6.dp))
|
||||
WorldMap(codes, GlanceModifier.fillMaxWidth().defaultWeight())
|
||||
}
|
||||
if (size.isTall && atlas != null) {
|
||||
Spacer(GlanceModifier.height(10.dp))
|
||||
Row(modifier = GlanceModifier.fillMaxWidth()) {
|
||||
atlas.recent.take(4).forEach { country ->
|
||||
Column(modifier = GlanceModifier.defaultWeight(), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(flag(country.code), style = TextStyle(fontSize = 20.sp, textAlign = TextAlign.Center))
|
||||
Line(country.name, 10.sp, GlanceTheme.colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WorldMap(codes: Set<String>, modifier: GlanceModifier) {
|
||||
Box(modifier = modifier) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.worldDots(codes, visited = false)),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(GlanceTheme.colors.outline),
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
)
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.worldDots(codes, visited = true)),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(GlanceTheme.colors.primary),
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The flag emoji of an ISO 3166-1 alpha-2 code. */
|
||||
private fun flag(code: String): String {
|
||||
if (code.length != 2) return ""
|
||||
val first = Character.toChars(0x1F1E6 + (code[0].uppercaseChar() - 'A'))
|
||||
val second = Character.toChars(0x1F1E6 + (code[1].uppercaseChar() - 'A'))
|
||||
return String(first) + String(second)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Travel group ----
|
||||
|
||||
/** Who comes along, the latest messages and the open poll. */
|
||||
class CollabWidget : 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 collab = snapshot.collab
|
||||
WidgetFrame(onClick = openPath(context, collab?.path ?: snapshot.trip?.path ?: "/")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Rounded.Group, GlanceTheme.colors.primary, 14.dp)
|
||||
Spacer(GlanceModifier.width(5.dp))
|
||||
if (size.isWide) Eyebrow(labels.group, GlanceTheme.colors.primary, GlanceModifier.defaultWeight()) else Spacer(GlanceModifier.defaultWeight())
|
||||
collab?.members?.take(if (size.isWide) 4 else 3)?.forEach { member ->
|
||||
Spacer(GlanceModifier.width(2.dp))
|
||||
Initials(member.initials, 22.dp)
|
||||
}
|
||||
}
|
||||
Spacer(GlanceModifier.height(8.dp))
|
||||
val messages = collab?.messages.orEmpty()
|
||||
if (messages.isEmpty() && collab?.poll == null) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Line(labels.noMessages, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2)
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
return@Column
|
||||
}
|
||||
messages.takeLast(if (size.isTall) (if (collab?.poll != null) 2 else 4) else 1).forEach { message ->
|
||||
Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.Top) {
|
||||
if (!message.mine) {
|
||||
Initials(message.initials, 24.dp)
|
||||
Spacer(GlanceModifier.width(6.dp))
|
||||
} else {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
}
|
||||
Column(
|
||||
modifier = GlanceModifier
|
||||
.background(if (message.mine) GlanceTheme.colors.primary else GlanceTheme.colors.surfaceVariant)
|
||||
.cornerRadius(14.dp).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
if (!message.mine && size.isWide) Line(message.author, 10.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold)
|
||||
Line(
|
||||
message.text,
|
||||
12.sp,
|
||||
if (message.mine) GlanceTheme.colors.onPrimary else GlanceTheme.colors.onSurface,
|
||||
maxLines = if (size.isWide) 2 else 3,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
val poll = collab?.poll
|
||||
if (size.isTall && poll != null) {
|
||||
Spacer(GlanceModifier.defaultWeight())
|
||||
Column(modifier = GlanceModifier.fillMaxWidth().background(GlanceTheme.colors.secondaryContainer).cornerRadius(14.dp).padding(10.dp)) {
|
||||
Eyebrow("${labels.poll}: ${poll.voters} ${labels.votes}", GlanceTheme.colors.onSecondaryContainer)
|
||||
Line(poll.question, 13.sp, GlanceTheme.colors.onSecondaryContainer, FontWeight.Bold)
|
||||
Spacer(GlanceModifier.height(4.dp))
|
||||
val most = poll.options.maxOfOrNull { it.votes }?.coerceAtLeast(1) ?: 1
|
||||
poll.options.take(3).forEach { option ->
|
||||
Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Line(option.label, 12.sp, GlanceTheme.colors.onSecondaryContainer, modifier = GlanceModifier.width(70.dp))
|
||||
Bar(option.votes.toFloat() / most, GlanceTheme.colors.primary, GlanceTheme.colors.surface, 5.dp, GlanceModifier.defaultWeight())
|
||||
Spacer(GlanceModifier.width(6.dp))
|
||||
Line(option.votes.toString(), 11.sp, GlanceTheme.colors.onSecondaryContainer, FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Initials(text: String, size: androidx.compose.ui.unit.Dp) {
|
||||
Box(
|
||||
modifier = GlanceModifier.size(size).cornerRadius(size / 2).background(GlanceTheme.colors.tertiaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(text, style = TextStyle(color = GlanceTheme.colors.onTertiaryContainer, fontSize = 9.sp, fontWeight = FontWeight.Bold), maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A widget with nothing to show yet: TREK's mark and what to do. */
|
||||
@Composable
|
||||
fun EmptyWidget(text: String) {
|
||||
val context = LocalContext.current
|
||||
WidgetFrame(onClick = openPath(context, "/")) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = GlanceModifier.size(34.dp).cornerRadius(11.dp).background(GlanceTheme.colors.primary),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("T", style = TextStyle(color = GlanceTheme.colors.onPrimary, fontSize = 18.sp, fontWeight = FontWeight.Bold))
|
||||
}
|
||||
Spacer(GlanceModifier.height(10.dp))
|
||||
Line(text, 13.sp, GlanceTheme.colors.onSurface, FontWeight.Medium, maxLines = 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.Shader
|
||||
import android.util.Base64
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sin
|
||||
|
||||
/**
|
||||
* The pictures a widget shows that RemoteViews cannot draw: the trip's cover,
|
||||
* its own sky when it has none, and the world map's dots. Drawn once per
|
||||
* update into bitmaps, kept small (a widget's RemoteViews have a size budget).
|
||||
*/
|
||||
object WidgetArt {
|
||||
/** A stable number for a text (FNV-1a), the same as TrekStyle.swift's seed. */
|
||||
fun seed(text: String): Long {
|
||||
var hash = 1469598103934665603L
|
||||
for (byte in text.toByteArray(Charsets.UTF_8)) {
|
||||
hash = (hash xor (byte.toLong() and 0xff)) * 1099511628211L
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
/** The trip's two colours, from its title: the same trip always gets the same sky. */
|
||||
fun tripHues(title: String): Pair<Int, Int> {
|
||||
val base = (java.lang.Long.remainderUnsigned(seed(title), 360)).toFloat()
|
||||
val first = Color.HSVToColor(floatArrayOf(base, 0.62f, 0.78f))
|
||||
val second = Color.HSVToColor(floatArrayOf((base + 40f) % 360f, 0.7f, 0.42f))
|
||||
return first to second
|
||||
}
|
||||
|
||||
/** The cover the app sent, base64 JPEG, decoded down to at most [maxSide] pixels. */
|
||||
fun cover(base64: String?, maxSide: Int = 720): Bitmap? {
|
||||
if (base64.isNullOrBlank()) return null
|
||||
return try {
|
||||
val bytes = Base64.decode(base64, Base64.DEFAULT)
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
var sample = 1
|
||||
while (bounds.outWidth / (sample * 2) >= maxSide || bounds.outHeight / (sample * 2) >= maxSide) sample *= 2
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
} catch (e: IllegalArgumentException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** A trip without a cover: its two colours as a sky, with contour lines over it. */
|
||||
fun sky(title: String, width: Int = 480, height: Int = 480): Bitmap {
|
||||
val (first, second) = tripHues(title)
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
paint.shader = LinearGradient(0f, 0f, width.toFloat(), height.toFloat(), first, second, Shader.TileMode.CLAMP)
|
||||
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
|
||||
paint.shader = RadialGradient(width * 0.85f, height * 0.05f, width * 0.6f, Color.argb(70, 255, 255, 255), Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
||||
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
|
||||
paint.shader = null
|
||||
drawContours(canvas, width, height, java.lang.Long.remainderUnsigned(seed(title), 997).toInt(), Color.argb(36, 255, 255, 255))
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/** Concentric wobbly rings, the topographic lines that stand for travel in TREK. */
|
||||
private fun drawContours(canvas: Canvas, width: Int, height: Int, seed: Int, color: Int) {
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = 2f
|
||||
this.color = color
|
||||
}
|
||||
val cx = width * (0.25f + (seed % 50) / 100f)
|
||||
val cy = height * (0.35f + (seed % 30) / 100f)
|
||||
val maxR = min(width, height) * 1.1f
|
||||
val rings = 11
|
||||
for (ring in 1..rings) {
|
||||
val r = maxR * ring / rings
|
||||
val path = Path()
|
||||
val steps = 72
|
||||
for (i in 0..steps) {
|
||||
val a = 2 * PI * i / steps
|
||||
val wobble = 1 + 0.08 * sin(a * 3 + seed + ring) + 0.05 * cos(a * 5 + seed * 0.7)
|
||||
val x = cx + (r * wobble * cos(a)).toFloat()
|
||||
val y = cy + (r * wobble * sin(a) * 0.8).toFloat()
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The world map as dots, white so the widget tints it: [visited] true draws
|
||||
* only the countries in [codes], false only the others.
|
||||
*/
|
||||
fun worldDots(codes: Set<String>, visited: Boolean, dot: Int = 8): Bitmap {
|
||||
val rows = WorldGrid.ROWS.size
|
||||
val bitmap = Bitmap.createBitmap(WorldGrid.COLUMNS * dot, rows * dot, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE }
|
||||
val radius = dot * 0.36f
|
||||
for (row in 0 until rows) {
|
||||
for (column in 0 until WorldGrid.COLUMNS) {
|
||||
val code = WorldGrid.code(row, column) ?: continue
|
||||
if ((code in codes) != visited) continue
|
||||
canvas.drawCircle(column * dot + dot / 2f, row * dot + dot / 2f, radius, paint)
|
||||
}
|
||||
}
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/** A ring of [progress] (0..1), white on a faint track, for the countdown and the packing. */
|
||||
fun ring(progress: Float, sizePx: Int = 160, stroke: Float = 14f, track: Int = Color.argb(60, 255, 255, 255)): Bitmap {
|
||||
val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = stroke
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
}
|
||||
val inset = stroke / 2 + 1
|
||||
val oval = android.graphics.RectF(inset, inset, sizePx - inset, sizePx - inset)
|
||||
paint.color = track
|
||||
canvas.drawArc(oval, 0f, 360f, false, paint)
|
||||
paint.color = Color.WHITE
|
||||
val sweep = 360f * progress.coerceIn(0f, 1f)
|
||||
if (sweep > 0) canvas.drawArc(oval, -90f, sweep, false, paint)
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/** A trip's days as segments, filled up to [index]: white, the widget tints it. Track at a third. */
|
||||
fun segments(index: Int, total: Int, width: Int = 600, height: Int = 10): Bitmap {
|
||||
val count = total.coerceIn(1, 31)
|
||||
val filled = if (total > 31) (index * 31f / total).toInt().coerceAtLeast(1) else index
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
val gap = if (count > 14) 4f else 8f
|
||||
val w = (width - gap * (count - 1)) / count
|
||||
for (i in 0 until count) {
|
||||
paint.color = if (i < filled) Color.WHITE else Color.argb(85, 255, 255, 255)
|
||||
val left = i * (w + gap)
|
||||
canvas.drawRoundRect(android.graphics.RectF(left, 0f, left + w, height.toFloat()), height / 2f, height / 2f, paint)
|
||||
}
|
||||
return bitmap
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.AutoAwesome
|
||||
import androidx.compose.material.icons.rounded.Luggage
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LargeTopAppBar
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.rememberTopAppBarState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.liketrek.trek.R
|
||||
import com.liketrek.trek.ui.TrekMaterialTheme
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* "Choose trip" for a placed widget, the counterpart of the iOS widget's Edit
|
||||
* Widget (TripIntent.swift): Automatic follows the dashboard's trip, or one of
|
||||
* the trips the app listed (key "trips"). Shown when the widget is placed
|
||||
* (optional, it starts on Automatic) and again from the widget's long press.
|
||||
*/
|
||||
class WidgetConfigActivity : ComponentActivity() {
|
||||
private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
appWidgetId = intent?.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
|
||||
?: AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
// Backing out keeps the widget on what it had (Automatic for a new one).
|
||||
setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId))
|
||||
val trips = WidgetStore.trips(this)
|
||||
val current = WidgetStore.tripFor(this, appWidgetId)
|
||||
setContent {
|
||||
TrekMaterialTheme {
|
||||
TripPicker(trips, current, onPick = ::pick)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun pick(tripId: String) {
|
||||
WidgetStore.setTripFor(this, appWidgetId, tripId)
|
||||
lifecycleScope.launch {
|
||||
val manager = GlanceAppWidgetManager(this@WidgetConfigActivity)
|
||||
val glanceId = runCatching { manager.getGlanceIdBy(appWidgetId) }.getOrNull()
|
||||
// Only the widget this id belongs to: Glance keys a session by the id alone,
|
||||
// so another class updating it would draw its own layout there.
|
||||
val widget = TrekWidgetUpdater.widgetFor(this@WidgetConfigActivity, appWidgetId)
|
||||
if (glanceId != null && widget != null) runCatching { widget.update(this@WidgetConfigActivity, glanceId) }
|
||||
setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId))
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun TripPicker(trips: List<TripRef>, current: String, onPick: (String) -> Unit) {
|
||||
var selected by remember { mutableStateOf(current) }
|
||||
val scroll = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState())
|
||||
Scaffold(
|
||||
modifier = Modifier.fillMaxSize().nestedScroll(scroll.nestedScrollConnection),
|
||||
topBar = {
|
||||
LargeTopAppBar(
|
||||
title = { Text(stringResource(R.string.widget_intent_title)) },
|
||||
scrollBehavior = scroll,
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding() + 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.widget_intent_description),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 4.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
item {
|
||||
PickRow(
|
||||
title = stringResource(R.string.widget_intent_auto),
|
||||
subtitle = stringResource(R.string.widget_intent_auto_hint),
|
||||
leading = { Icon(Icons.Rounded.AutoAwesome, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
checked = selected == WidgetStore.AUTO,
|
||||
) {
|
||||
selected = WidgetStore.AUTO
|
||||
onPick(WidgetStore.AUTO)
|
||||
}
|
||||
}
|
||||
items(trips, key = { it.id }) { trip ->
|
||||
PickRow(
|
||||
title = trip.title,
|
||||
subtitle = RelativeDayRange(trip),
|
||||
leading = { Icon(Icons.Rounded.Luggage, null, tint = MaterialTheme.colorScheme.secondary) },
|
||||
checked = selected == trip.id.toString(),
|
||||
) {
|
||||
selected = trip.id.toString()
|
||||
onPick(trip.id.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RelativeDayRange(trip: TripRef): String? {
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
return RelativeDay.range(context, trip.start, trip.end)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PickRow(title: String, subtitle: String?, leading: @Composable () -> Unit, checked: Boolean, onClick: () -> Unit) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = if (checked) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainerLow,
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
|
||||
) {
|
||||
Row(modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(shape = RoundedCornerShape(12.dp), color = MaterialTheme.colorScheme.surface, modifier = Modifier.size(40.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) { leading() }
|
||||
}
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (subtitle != null) {
|
||||
Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
RadioButton(selected = checked, onClick = onClick)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.content.Context
|
||||
import com.liketrek.trek.R
|
||||
import java.time.LocalDate
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The sample trip the widget picker shows before the app ever wrote a snapshot,
|
||||
* and what the screenshot tests draw: the same trip to Kyoto as the iOS gallery
|
||||
* (WidgetSnapshot.sample in TrekFamily.swift).
|
||||
*/
|
||||
object WidgetSamples {
|
||||
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)))
|
||||
|
||||
fun json(running: Boolean, now: LocalDate = LocalDate.now()): String {
|
||||
fun iso(offset: Long) = now.plusDays(offset).toString()
|
||||
val start = if (running) -2L else 12L
|
||||
val today = if (running) {
|
||||
"""
|
||||
"today": {"dayLabel": "Day 3 of 9", "index": 3, "total": 9, "stops": [
|
||||
{"time": "08:30", "name": "Fushimi Inari Taisha", "minutes": 510, "color": "#D6273B", "symbol": "building.columns.fill"},
|
||||
{"time": "11:00", "name": "Nishiki Market", "minutes": 660, "color": "#E8A13A", "symbol": "storefront.fill"},
|
||||
{"time": "13:30", "name": "Kiyomizu-dera", "minutes": 810, "color": "#2FA37A", "symbol": "leaf.fill"},
|
||||
{"time": "16:00", "name": "Gion walk", "minutes": 960, "color": "#4A7DDB", "symbol": "figure.walk"},
|
||||
{"time": "19:30", "name": "Dinner at Pontocho", "minutes": 1170, "color": "#8E6CD9", "symbol": "fork.knife"}
|
||||
]},
|
||||
"""
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return """
|
||||
{
|
||||
"trip": {"title": "Autumn in Kyoto", "start": "${iso(start)}", "end": "${iso(start + 8)}", "path": "/trips/1",
|
||||
"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},
|
||||
"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"},
|
||||
{"title": "Hotel Kanra Kyoto", "kind": "hotel", "date": "${iso(if (running) 0 else 13)}", "time": "15:00", "detail": "6 nights", "confirmed": true, "path": "/trips/1"},
|
||||
{"title": "Kaiseki at Kikunoi", "kind": "restaurant", "date": "${iso(if (running) 1 else 15)}", "time": "19:00", "detail": "Higashiyama", "confirmed": false, "path": "/trips/1"},
|
||||
{"title": "Tea ceremony", "kind": "event", "date": "${iso(if (running) 2 else 16)}", "time": "10:30", "detail": "Camellia Flower", "confirmed": true, "path": "/trips/1"}
|
||||
],
|
||||
"todos": {"open": 4, "total": 11, "path": "/trips/1/todos", "items": [
|
||||
{"name": "Order JR Pass", "due": "${iso(if (running) 0 else 3)}", "priority": 3},
|
||||
{"name": "Book Ghibli Museum tickets", "due": "${iso(if (running) 1 else 5)}", "priority": 2},
|
||||
{"name": "Get yen in cash", "priority": 1},
|
||||
{"name": "Download offline maps", "priority": 0}
|
||||
]},
|
||||
"packing": {"packed": 23, "total": 31, "path": "/trips/1/packing",
|
||||
"bags": [
|
||||
{"name": "Suitcase", "color": "#4A7DDB", "grams": 14200, "limit": 23000, "packed": 15, "total": 19},
|
||||
{"name": "Daypack", "color": "#2FA37A", "grams": 4100, "limit": 8000, "packed": 8, "total": 12}
|
||||
],
|
||||
"missing": [
|
||||
{"name": "Rain jacket", "category": "Clothes", "color": "#4A7DDB"},
|
||||
{"name": "Power bank", "category": "Tech", "color": "#2FA37A"},
|
||||
{"name": "Passport", "category": "Documents", "color": "#2FA37A"},
|
||||
{"name": "Sandals", "category": "Shoes", "color": "#4A7DDB"}
|
||||
]},
|
||||
"atlas": {"count": 23, "trips": 41, "days": 318,
|
||||
"codes": ["DE","AT","CH","FR","IT","ES","PT","NL","BE","DK","NO","SE","GB","IE","GR","HR","JP","TH","VN","US","CA","MA","AU"],
|
||||
"recent": [{"code": "JP", "name": "Japan"}, {"code": "NO", "name": "Norway"}, {"code": "PT", "name": "Portugal"}, {"code": "MA", "name": "Morocco"}],
|
||||
"continents": [{"name": "Europe", "count": 16}, {"name": "Asia", "count": 3}, {"name": "North America", "count": 2}, {"name": "Africa", "count": 1}, {"name": "Oceania", "count": 1}]},
|
||||
"collab": {"path": "/trips/1?tab=collab",
|
||||
"members": [{"name": "Maurice", "initials": "MA"}, {"name": "Julien", "initials": "JU"}, {"name": "Elmo", "initials": "EL"}, {"name": "Sara", "initials": "SA"}],
|
||||
"messages": [
|
||||
{"author": "Julien", "initials": "JU", "text": "Got the JR Pass vouchers, all four of us", "mine": false},
|
||||
{"author": "Sara", "initials": "SA", "text": "Can we push dinner to 20:00? Train is late", "mine": false},
|
||||
{"author": "Maurice", "initials": "MA", "text": "Sure, I moved the table at Pontocho", "mine": true}
|
||||
],
|
||||
"poll": {"question": "Day trip on Saturday?", "voters": 4, "options": [{"label": "Nara", "votes": 3}, {"label": "Uji", "votes": 1}, {"label": "Kurama", "votes": 0}]}},
|
||||
"labels": {
|
||||
"nextTrip": "Next trip", "today": "Today", "noTrip": "No trip coming up. Plan the next one in TREK.",
|
||||
"inDays": "in {n} days", "tomorrow": "Tomorrow", "nothingPlanned": "Nothing planned today",
|
||||
"days": "days", "bookings": "Coming up", "noBookings": "No bookings ahead",
|
||||
"todos": "To-dos", "noTodos": "All done", "packing": "Packing", "packed": "packed",
|
||||
"confirmed": "Confirmed", "pending": "Pending", "todayShort": "Today", "tomorrowShort": "Tomorrow",
|
||||
"now": "Now", "places": "places", "travellers": "travellers", "allDone": "Day done",
|
||||
"missing": "still to pack", "countries": "countries", "world": "of the world", "group": "Travel group",
|
||||
"poll": "Poll", "votes": "votes", "noMessages": "No messages yet", "departure": "Departure"
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -1,286 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeParseException
|
||||
import java.time.temporal.ChronoUnit
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* What the app last told the widgets: client/src/native/widgets.ts builds it and
|
||||
* hands it over through TrekShell.setWidgetSnapshot, the same JSON the iOS
|
||||
* widgets read (client/ios/App/TREKWidgets/WidgetSnapshot.swift). Texts arrive
|
||||
* already translated, so a widget always speaks the language the app does.
|
||||
*
|
||||
* Everything past trip, today and labels is optional: a binary newer than the
|
||||
* server's UI shows what it gets, and unknown fields are ignored.
|
||||
*/
|
||||
data class WidgetSnapshot(
|
||||
val trip: Trip?,
|
||||
val today: Today?,
|
||||
val weather: Weather?,
|
||||
val bookings: List<Booking>,
|
||||
val todos: Todos?,
|
||||
val packing: Packing?,
|
||||
val atlas: Atlas?,
|
||||
val collab: Collab?,
|
||||
val labels: Labels,
|
||||
) {
|
||||
data class Trip(
|
||||
val title: String,
|
||||
val start: String,
|
||||
val end: String,
|
||||
val path: String,
|
||||
val place: String?,
|
||||
/** A small JPEG of the cover, base64. */
|
||||
val cover: String?,
|
||||
val dayCount: Int?,
|
||||
val placeCount: Int?,
|
||||
val memberCount: Int?,
|
||||
)
|
||||
|
||||
data class Stop(
|
||||
val time: String?,
|
||||
val name: String,
|
||||
/** Minutes after midnight. */
|
||||
val minutes: Int?,
|
||||
/** #rrggbb */
|
||||
val color: String?,
|
||||
/** The SF Symbol name the iOS widget uses; [TrekIcons] maps it. */
|
||||
val symbol: String?,
|
||||
)
|
||||
|
||||
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
|
||||
|
||||
data class Weather(
|
||||
val temp: Int,
|
||||
val high: Int?,
|
||||
val low: Int?,
|
||||
val main: String,
|
||||
val label: String,
|
||||
val place: String?,
|
||||
val rain: Int?,
|
||||
)
|
||||
|
||||
data class Booking(
|
||||
val title: String,
|
||||
val kind: String,
|
||||
val date: String?,
|
||||
val time: String?,
|
||||
val detail: String?,
|
||||
val confirmed: Boolean,
|
||||
val path: String,
|
||||
)
|
||||
|
||||
data class Todo(val name: String, val due: String?, val priority: Int)
|
||||
|
||||
data class Todos(val open: Int, val total: Int, val items: List<Todo>, val path: String)
|
||||
|
||||
data class Bag(val name: String, val color: String, val grams: Int, val limit: Int?, val packed: Int, val total: Int)
|
||||
|
||||
data class PackItem(val name: String, val category: String?, val color: String?)
|
||||
|
||||
data class Packing(val packed: Int, val total: Int, val path: String, val bags: List<Bag>, val missing: List<PackItem>)
|
||||
|
||||
data class Country(val code: String, val name: String)
|
||||
|
||||
data class Continent(val name: String, val count: Int)
|
||||
|
||||
data class Atlas(
|
||||
val count: Int,
|
||||
val codes: List<String>,
|
||||
val recent: List<Country>,
|
||||
val continents: List<Continent>,
|
||||
val trips: Int?,
|
||||
val days: Int?,
|
||||
)
|
||||
|
||||
data class Member(val name: String, val initials: String)
|
||||
|
||||
data class Message(val author: String, val initials: String, val text: String, val at: String?, val mine: Boolean)
|
||||
|
||||
data class PollOption(val label: String, val votes: Int)
|
||||
|
||||
data class Poll(val question: String, val options: List<PollOption>, val voters: Int)
|
||||
|
||||
data class Collab(val members: List<Member>, val messages: List<Message>, val poll: Poll?, 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")
|
||||
val today get() = text("today", "Today")
|
||||
val noTrip get() = text("noTrip", "No trip coming up. Plan the next one in TREK.")
|
||||
val inDays get() = text("inDays", "in {n} days")
|
||||
val tomorrow get() = text("tomorrow", "Tomorrow")
|
||||
val nothingPlanned get() = text("nothingPlanned", "Nothing planned today")
|
||||
val days get() = text("days", "days")
|
||||
val bookings get() = text("bookings", "Coming up")
|
||||
val noBookings get() = text("noBookings", "No bookings ahead")
|
||||
val todos get() = text("todos", "To-dos")
|
||||
val noTodos get() = text("noTodos", "All done")
|
||||
val packing get() = text("packing", "Packing")
|
||||
val packed get() = text("packed", "packed")
|
||||
val confirmed get() = text("confirmed", "Confirmed")
|
||||
val pending get() = text("pending", "Pending")
|
||||
val todayShort get() = text("todayShort", today)
|
||||
val tomorrowShort get() = text("tomorrowShort", tomorrow)
|
||||
val now get() = text("now", "Now")
|
||||
val places get() = text("places", "places")
|
||||
val travellers get() = text("travellers", "travellers")
|
||||
val allDone get() = text("allDone", "Day done")
|
||||
val openTrek get() = text("openTrek", "Open TREK")
|
||||
val missing get() = text("missing", "still to pack")
|
||||
val countries get() = text("countries", "countries")
|
||||
val world get() = text("world", "of the world")
|
||||
val group get() = text("group", "Travel group")
|
||||
val poll get() = text("poll", "Poll")
|
||||
val votes get() = text("votes", "votes")
|
||||
val noMessages get() = text("noMessages", "No messages yet")
|
||||
val departure get() = text("departure", "Departure")
|
||||
|
||||
private fun text(key: String, fallback: String): String = raw.optString(key).ifBlank { fallback }
|
||||
}
|
||||
|
||||
/** Whole days from [now] to the trip's start. */
|
||||
fun daysUntilStart(now: LocalDate = LocalDate.now()): Long? = trip?.let { day(it.start) }?.let { ChronoUnit.DAYS.between(now, it) }
|
||||
|
||||
/** The trip's length in days, from its dates when the app sent no count. */
|
||||
val tripLength: Int?
|
||||
get() {
|
||||
trip?.dayCount?.takeIf { it > 0 }?.let { return it }
|
||||
val start = trip?.let { day(it.start) } ?: return null
|
||||
val end = day(trip.end) ?: return null
|
||||
return ChronoUnit.DAYS.between(start, end).toInt() + 1
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun parse(json: String): WidgetSnapshot? = try {
|
||||
fromJson(JSONObject(json))
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
|
||||
trip = o.optJSONObject("trip")?.let {
|
||||
Trip(
|
||||
title = it.optString("title"),
|
||||
start = it.optString("start"),
|
||||
end = it.optString("end"),
|
||||
path = it.optString("path", "/"),
|
||||
place = it.str("place"),
|
||||
cover = it.str("cover"),
|
||||
dayCount = it.int("dayCount"),
|
||||
placeCount = it.int("placeCount"),
|
||||
memberCount = it.int("memberCount"),
|
||||
)
|
||||
},
|
||||
today = o.optJSONObject("today")?.let { t ->
|
||||
Today(
|
||||
dayLabel = t.optString("dayLabel"),
|
||||
stops = t.optJSONArray("stops").objects().map {
|
||||
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
|
||||
},
|
||||
index = t.int("index"),
|
||||
total = t.int("total"),
|
||||
)
|
||||
},
|
||||
weather = o.optJSONObject("weather")?.let {
|
||||
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
|
||||
},
|
||||
bookings = o.optJSONArray("bookings").objects().map {
|
||||
Booking(
|
||||
title = it.optString("title"),
|
||||
kind = it.optString("kind", "other"),
|
||||
date = it.str("date"),
|
||||
time = it.str("time"),
|
||||
detail = it.str("detail"),
|
||||
confirmed = it.optBoolean("confirmed"),
|
||||
path = it.optString("path", "/"),
|
||||
)
|
||||
},
|
||||
todos = o.optJSONObject("todos")?.let { t ->
|
||||
Todos(
|
||||
open = t.optInt("open"),
|
||||
total = t.optInt("total"),
|
||||
items = t.optJSONArray("items").objects().map { Todo(it.optString("name"), it.str("due"), it.optInt("priority")) },
|
||||
path = t.optString("path", "/"),
|
||||
)
|
||||
},
|
||||
packing = o.optJSONObject("packing")?.let { p ->
|
||||
Packing(
|
||||
packed = p.optInt("packed"),
|
||||
total = p.optInt("total"),
|
||||
path = p.optString("path", "/"),
|
||||
bags = p.optJSONArray("bags").objects().map {
|
||||
Bag(it.optString("name"), it.optString("color", "#4A7DDB"), it.optInt("grams"), it.int("limit"), it.optInt("packed"), it.optInt("total"))
|
||||
},
|
||||
missing = p.optJSONArray("missing").objects().map { PackItem(it.optString("name"), it.str("category"), it.str("color")) },
|
||||
)
|
||||
},
|
||||
atlas = o.optJSONObject("atlas")?.let { a ->
|
||||
Atlas(
|
||||
count = a.optInt("count"),
|
||||
codes = a.optJSONArray("codes").strings(),
|
||||
recent = a.optJSONArray("recent").objects().map { Country(it.optString("code"), it.optString("name")) },
|
||||
continents = a.optJSONArray("continents").objects().map { Continent(it.optString("name"), it.optInt("count")) },
|
||||
trips = a.int("trips"),
|
||||
days = a.int("days"),
|
||||
)
|
||||
},
|
||||
collab = o.optJSONObject("collab")?.let { c ->
|
||||
Collab(
|
||||
members = c.optJSONArray("members").objects().map { Member(it.optString("name"), it.optString("initials")) },
|
||||
messages = c.optJSONArray("messages").objects().map {
|
||||
Message(it.optString("author"), it.optString("initials"), it.optString("text"), it.str("at"), it.optBoolean("mine"))
|
||||
},
|
||||
poll = c.optJSONObject("poll")?.let { p ->
|
||||
Poll(p.optString("question"), p.optJSONArray("options").objects().map { PollOption(it.optString("label"), it.optInt("votes")) }, p.optInt("voters"))
|
||||
},
|
||||
path = c.optString("path", "/"),
|
||||
)
|
||||
},
|
||||
labels = Labels(o.optJSONObject("labels") ?: JSONObject()),
|
||||
)
|
||||
|
||||
fun day(iso: String?): LocalDate? {
|
||||
if (iso.isNullOrBlank() || iso.length < 10) return null
|
||||
return try {
|
||||
LocalDate.parse(iso.substring(0, 10))
|
||||
} catch (e: DateTimeParseException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** The app link a tap opens: com.liketrek.trek://navigate<path>, which the UI routes (nativeApp.ts). */
|
||||
fun link(path: String): String = "com.liketrek.trek://navigate" + if (path.startsWith("/")) path else "/$path"
|
||||
|
||||
private fun JSONObject.str(key: String): String? = if (isNull(key)) null else optString(key).ifEmpty { null }
|
||||
|
||||
private fun JSONObject.int(key: String): Int? = if (has(key) && !isNull(key)) optInt(key) else null
|
||||
|
||||
private fun JSONArray?.objects(): List<JSONObject> =
|
||||
if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
|
||||
|
||||
private fun JSONArray?.strings(): List<String> =
|
||||
if (this == null) emptyList() else (0 until length()).mapNotNull { optString(it).ifEmpty { null } }
|
||||
}
|
||||
}
|
||||
|
||||
/** A trip a widget can be set to, as the app lists them (key "trips"). */
|
||||
data class TripRef(val id: Long, val title: String, val start: String, val end: String) {
|
||||
companion object {
|
||||
fun parseList(json: String?): List<TripRef> {
|
||||
if (json.isNullOrBlank()) return emptyList()
|
||||
return try {
|
||||
val array = JSONArray(json)
|
||||
(0 until array.length()).mapNotNull { i ->
|
||||
val o = array.optJSONObject(i) ?: return@mapNotNull null
|
||||
if (!o.has("id")) return@mapNotNull null
|
||||
TripRef(o.optLong("id"), o.optString("title"), o.optString("start"), o.optString("end"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
/**
|
||||
* Where the widgets' snapshots live: one JSON file per key in the app's own
|
||||
* storage. The widgets run in the app's process, so no shared container is
|
||||
* needed as on iOS; the keys are the same ones the UI writes there
|
||||
* ("snapshot", "trips", "trip.<id>").
|
||||
*/
|
||||
object WidgetStore {
|
||||
private val KEY = Regex("^(snapshot|trips|trip\\.[0-9]{1,12})$")
|
||||
private const val PREFS = "trek.widgets"
|
||||
const val AUTO = "auto"
|
||||
|
||||
private val changes = MutableStateFlow(0L)
|
||||
|
||||
/**
|
||||
* Counts every write and every trip picked for a widget. A widget reads its
|
||||
* data inside its composition, keyed on this, so a write that lands while its
|
||||
* Glance session still runs is drawn too, not only the first one.
|
||||
*/
|
||||
val version: StateFlow<Long> = changes
|
||||
|
||||
fun isValidKey(key: String): Boolean = KEY.matches(key)
|
||||
|
||||
private fun dir(context: Context): File = File(context.filesDir, "widgets").apply { mkdirs() }
|
||||
|
||||
fun write(context: Context, key: String, json: String) {
|
||||
require(isValidKey(key)) { "key must be snapshot, trips or trip.<id>" }
|
||||
val target = File(dir(context), "$key.json")
|
||||
val temp = File(dir(context), "$key.json.tmp")
|
||||
temp.writeText(json)
|
||||
if (!temp.renameTo(target)) {
|
||||
target.delete()
|
||||
temp.renameTo(target)
|
||||
}
|
||||
changes.value++
|
||||
}
|
||||
|
||||
fun read(context: Context, key: String): String? {
|
||||
if (!isValidKey(key)) return null
|
||||
val file = File(dir(context), "$key.json")
|
||||
return if (file.exists()) runCatching { file.readText() }.getOrNull() else null
|
||||
}
|
||||
|
||||
/** The dashboard's snapshot. */
|
||||
fun load(context: Context): WidgetSnapshot? = read(context, "snapshot")?.let(WidgetSnapshot::parse)
|
||||
|
||||
/**
|
||||
* The snapshot of the trip a widget is set to; the dashboard's for none or
|
||||
* "auto", and the dashboard's too while the app has not written that trip.
|
||||
* A trip's snapshot carries no Atlas, so it borrows the dashboard's.
|
||||
*/
|
||||
fun load(context: Context, tripId: String?): WidgetSnapshot? {
|
||||
if (tripId == null || tripId == AUTO) return load(context)
|
||||
val own = read(context, "trip.$tripId")?.let(WidgetSnapshot::parse) ?: return load(context)
|
||||
return if (own.atlas == null) own.copy(atlas = load(context)?.atlas) else own
|
||||
}
|
||||
|
||||
fun trips(context: Context): List<TripRef> = TripRef.parseList(read(context, "trips"))
|
||||
|
||||
/** The trip picked for one placed widget, "auto" when none was. */
|
||||
fun tripFor(context: Context, appWidgetId: Int): String =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("trip.$appWidgetId", AUTO) ?: AUTO
|
||||
|
||||
fun setTripFor(context: Context, appWidgetId: Int, tripId: String) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("trip.$appWidgetId", tripId).commit()
|
||||
changes.value++
|
||||
}
|
||||
|
||||
fun forget(context: Context, appWidgetIds: IntArray) {
|
||||
val editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
for (id in appWidgetIds) editor.remove("trip.$id")
|
||||
editor.apply()
|
||||
}
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.text.format.DateFormat
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.glance.ColorFilter
|
||||
import androidx.glance.GlanceComposable
|
||||
import androidx.glance.GlanceModifier
|
||||
import androidx.glance.GlanceTheme
|
||||
import androidx.glance.Image
|
||||
import androidx.glance.ImageProvider
|
||||
import androidx.glance.action.Action
|
||||
import androidx.glance.action.clickable
|
||||
import androidx.glance.appwidget.action.actionStartActivity
|
||||
import androidx.glance.appwidget.appWidgetBackground
|
||||
import androidx.glance.appwidget.cornerRadius
|
||||
import androidx.glance.background
|
||||
import androidx.glance.layout.Alignment
|
||||
import androidx.glance.layout.Box
|
||||
import androidx.glance.layout.Column
|
||||
import androidx.glance.layout.Row
|
||||
import androidx.glance.layout.Spacer
|
||||
import androidx.glance.layout.fillMaxSize
|
||||
import androidx.glance.layout.fillMaxWidth
|
||||
import androidx.glance.layout.height
|
||||
import androidx.glance.layout.padding
|
||||
import androidx.glance.layout.size
|
||||
import androidx.glance.layout.width
|
||||
import androidx.glance.material3.ColorProviders
|
||||
import androidx.glance.text.FontWeight
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextStyle
|
||||
import androidx.glance.unit.ColorProvider
|
||||
import com.liketrek.trek.MainActivity
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* What every TREK widget shares: Material You's colours on Android 12 and later
|
||||
* (the wallpaper's), TREK's own before that, the system's corner radius, the
|
||||
* tap that opens a place in the app, and the small pieces (eyebrow, chip, icon
|
||||
* badge) the widgets are built from.
|
||||
*/
|
||||
object TrekWidgetTheme {
|
||||
/** TREK's palette (client/src/mobile/mobile.css) for systems without dynamic colour. */
|
||||
val fallback = ColorProviders(
|
||||
light = lightColorScheme(
|
||||
primary = Color(0xFF101013),
|
||||
onPrimary = Color(0xFFF5F5F7),
|
||||
primaryContainer = Color(0xFFE7E5DF),
|
||||
onPrimaryContainer = Color(0xFF101013),
|
||||
secondary = Color(0xFF4A7DDB),
|
||||
secondaryContainer = Color(0xFFE4EAF7),
|
||||
onSecondaryContainer = Color(0xFF1B2F57),
|
||||
tertiary = Color(0xFF2FA37A),
|
||||
surface = Color(0xFFF7F6F2),
|
||||
onSurface = Color(0xFF101013),
|
||||
onSurfaceVariant = Color(0xFF68686F),
|
||||
surfaceVariant = Color(0xFFECEAE4),
|
||||
outline = Color(0xFF9A9AA1),
|
||||
background = Color(0xFFF1EFEA),
|
||||
error = Color(0xFFD6273B),
|
||||
),
|
||||
dark = darkColorScheme(
|
||||
primary = Color(0xFFF5F5F7),
|
||||
onPrimary = Color(0xFF101013),
|
||||
primaryContainer = Color(0xFF26262C),
|
||||
onPrimaryContainer = Color(0xFFF5F5F7),
|
||||
secondary = Color(0xFF8AAEF0),
|
||||
secondaryContainer = Color(0xFF233250),
|
||||
onSecondaryContainer = Color(0xFFDCE6FA),
|
||||
tertiary = Color(0xFF5CC79E),
|
||||
surface = Color(0xFF121216),
|
||||
onSurface = Color(0xFFF5F5F7),
|
||||
onSurfaceVariant = Color(0xFF9C9CA3),
|
||||
surfaceVariant = Color(0xFF1E1E24),
|
||||
outline = Color(0xFF6E6E76),
|
||||
background = Color(0xFF0C0C0F),
|
||||
error = Color(0xFFFF6B7A),
|
||||
),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun Themed(content: @Composable () -> Unit) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) GlanceTheme(content = content) else GlanceTheme(colors = fallback, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
/** The status colours, the same on every wallpaper so they keep their meaning. */
|
||||
object TrekStatus {
|
||||
val confirmed = ColorProvider(Color(0xFF2FA37A))
|
||||
val pending = ColorProvider(Color(0xFFE8A13A))
|
||||
val danger = ColorProvider(Color(0xFFD6273B))
|
||||
val white = ColorProvider(Color.White)
|
||||
val whiteMuted = ColorProvider(Color(0xCCFFFFFF))
|
||||
val whiteFaint = ColorProvider(Color(0x99FFFFFF))
|
||||
val scrim = ColorProvider(Color(0x66000000))
|
||||
val glass = ColorProvider(Color(0x33000000))
|
||||
}
|
||||
|
||||
/** Opens [path] of the user's server in the app (nativeApp.ts routes com.liketrek.trek://navigate). */
|
||||
fun openPath(context: Context, path: String): Action = actionStartActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(WidgetSnapshot.link(path)), context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),
|
||||
)
|
||||
|
||||
/** The ground of a widget: the system's widget shape and the theme's widget background. */
|
||||
@Composable
|
||||
fun WidgetFrame(
|
||||
onClick: Action?,
|
||||
background: ColorProvider = GlanceTheme.colors.widgetBackground,
|
||||
padding: Dp = 14.dp,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
var modifier = GlanceModifier.fillMaxSize().appWidgetBackground().background(background).padding(padding)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) modifier = modifier.cornerRadius(android.R.dimen.system_app_widget_background_radius)
|
||||
if (onClick != null) modifier = modifier.clickable(onClick)
|
||||
Box(modifier = modifier) { content() }
|
||||
}
|
||||
|
||||
/** A small, bold, upper-case line above a widget's content. */
|
||||
@Composable
|
||||
@GlanceComposable
|
||||
fun Eyebrow(text: String, color: ColorProvider = GlanceTheme.colors.onSurfaceVariant, modifier: GlanceModifier = GlanceModifier) {
|
||||
Text(
|
||||
text = text.uppercase(Locale.getDefault()),
|
||||
style = TextStyle(color = color, fontSize = 11.sp, fontWeight = FontWeight.Bold),
|
||||
maxLines = 1,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun Line(
|
||||
text: String,
|
||||
size: TextUnit = 13.sp,
|
||||
color: ColorProvider = GlanceTheme.colors.onSurface,
|
||||
weight: FontWeight = FontWeight.Normal,
|
||||
maxLines: Int = 1,
|
||||
modifier: GlanceModifier = GlanceModifier,
|
||||
) {
|
||||
Text(text = text, style = TextStyle(color = color, fontSize = size, fontWeight = weight), maxLines = maxLines, modifier = modifier)
|
||||
}
|
||||
|
||||
/** An icon in a tinted circle: a booking's kind, a stop's category. */
|
||||
@Composable
|
||||
fun IconBadge(symbol: String?, tint: ColorProvider, background: ColorProvider, size: Dp = 28.dp) {
|
||||
Box(
|
||||
modifier = GlanceModifier.size(size).background(background).cornerRadius(size / 2),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
provider = TrekIcons.provider(symbol),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(tint),
|
||||
modifier = GlanceModifier.size(size * 0.58f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun Icon(vector: ImageVector, tint: ColorProvider, size: Dp = 14.dp) {
|
||||
Image(provider = TrekIcons.provider(vector), contentDescription = null, colorFilter = ColorFilter.tint(tint), modifier = GlanceModifier.size(size))
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SymbolIcon(symbol: String, tint: ColorProvider, size: Dp = 14.dp) {
|
||||
Image(provider = TrekIcons.provider(symbol), contentDescription = null, colorFilter = ColorFilter.tint(tint), modifier = GlanceModifier.size(size))
|
||||
}
|
||||
|
||||
/** A rounded pill with a short text: a date range, a weather reading, a status. */
|
||||
@Composable
|
||||
fun Chip(
|
||||
text: String,
|
||||
background: ColorProvider,
|
||||
color: ColorProvider,
|
||||
leading: ImageProvider? = null,
|
||||
leadingTint: ColorProvider? = null,
|
||||
) {
|
||||
Row(
|
||||
modifier = GlanceModifier.background(background).cornerRadius(100.dp).padding(horizontal = 8.dp, vertical = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (leading != null) {
|
||||
Image(
|
||||
provider = leading,
|
||||
contentDescription = null,
|
||||
colorFilter = leadingTint?.let { ColorFilter.tint(it) },
|
||||
modifier = GlanceModifier.size(12.dp),
|
||||
)
|
||||
Spacer(GlanceModifier.width(4.dp))
|
||||
}
|
||||
Text(text = text, style = TextStyle(color = color, fontSize = 11.sp, fontWeight = FontWeight.Medium), maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun WeatherChip(weather: WidgetSnapshot.Weather, onPhoto: Boolean) {
|
||||
Chip(
|
||||
text = "${weather.temp}°",
|
||||
background = if (onPhoto) TrekStatus.glass else GlanceTheme.colors.secondaryContainer,
|
||||
color = if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer,
|
||||
leading = TrekIcons.provider(TrekIcons.weather(weather.main)),
|
||||
leadingTint = if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer,
|
||||
)
|
||||
}
|
||||
|
||||
/** A horizontal bar of [value] (0..1): Glance's progress indicator, rounded. */
|
||||
@Composable
|
||||
fun Bar(value: Float, color: ColorProvider, track: ColorProvider, height: Dp = 6.dp, modifier: GlanceModifier = GlanceModifier.fillMaxWidth()) {
|
||||
androidx.glance.appwidget.LinearProgressIndicator(
|
||||
progress = value.coerceIn(0f, 1f),
|
||||
color = color,
|
||||
backgroundColor = track,
|
||||
modifier = modifier.height(height).cornerRadius(height / 2),
|
||||
)
|
||||
}
|
||||
|
||||
/** The day segments of a trip: one bar per day, filled up to today. Drawn as one image (a Row takes ten children at most). */
|
||||
@Composable
|
||||
fun DaySegments(index: Int, total: Int, color: ColorProvider) {
|
||||
Image(
|
||||
provider = ImageProvider(WidgetArt.segments(index, total)),
|
||||
contentDescription = "$index / $total",
|
||||
colorFilter = ColorFilter.tint(color),
|
||||
contentScale = androidx.glance.layout.ContentScale.FillBounds,
|
||||
modifier = GlanceModifier.fillMaxWidth().height(4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** Relative days and ranges in the device's language. */
|
||||
object RelativeDay {
|
||||
fun label(iso: String?, labels: WidgetSnapshot.Labels, today: LocalDate = LocalDate.now(), locale: Locale = Locale.getDefault()): String? {
|
||||
val date = WidgetSnapshot.day(iso) ?: return null
|
||||
val days = ChronoUnit.DAYS.between(today, date)
|
||||
if (days == 0L) return labels.todayShort
|
||||
if (days == 1L) return labels.tomorrowShort
|
||||
val skeleton = if (days in 2..6) "EEE" else "EEEdMMM"
|
||||
return DateTimeFormatter.ofPattern(DateFormat.getBestDateTimePattern(locale, skeleton), locale).format(date)
|
||||
}
|
||||
|
||||
/** "1-9 Oct" in the device's own way of writing a range. */
|
||||
fun range(context: Context, start: String, end: String): String? {
|
||||
val from = WidgetSnapshot.day(start) ?: return null
|
||||
val to = WidgetSnapshot.day(end) ?: return null
|
||||
val zone = java.time.ZoneId.systemDefault()
|
||||
val startMs = from.atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
// formatDateRange's end is exclusive: noon of the last day keeps it in the range.
|
||||
val endMs = to.atTime(12, 0).atZone(zone).toInstant().toEpochMilli()
|
||||
val flags = android.text.format.DateUtils.FORMAT_SHOW_DATE or android.text.format.DateUtils.FORMAT_ABBREV_MONTH or
|
||||
android.text.format.DateUtils.FORMAT_NO_YEAR
|
||||
return android.text.format.DateUtils.formatDateRange(context, startMs, endMs, flags)
|
||||
}
|
||||
}
|
||||
|
||||
/** Minutes after midnight, now. */
|
||||
fun nowMinutes(): Int = java.time.LocalTime.now().let { it.hour * 60 + it.minute }
|
||||
|
||||
/** "#rrggbb" as a colour, null for anything else. */
|
||||
fun cssColor(css: String?): ColorProvider? {
|
||||
val hex = css?.removePrefix("#") ?: return null
|
||||
if (hex.length != 6) return null
|
||||
val value = hex.toLongOrNull(16) ?: return null
|
||||
return ColorProvider(Color(0xFF000000 or value))
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.liketrek.trek.widget
|
||||
|
||||
/**
|
||||
* The world as 76 by 34 dots from 80 degrees north to 58 south, each the ISO
|
||||
* code of the country under it, ".." for sea. The same grid as the iOS widget
|
||||
* (client/ios/App/TREKWidgets/WorldGrid.swift, generated from
|
||||
* server/assets/atlas/admin0.geojson.gz); copy it over when that one changes.
|
||||
*/
|
||||
object WorldGrid {
|
||||
const val COLUMNS = 76
|
||||
val ROWS: List<String> = listOf(
|
||||
"........................CACACA..CACACACACACA..GLGLGLGLGLGLGLGLGLGLGL............NONONO..................RU..........RURURU..............................",
|
||||
"......................CACACACACA..CACACACACA........GLGLGLGLGLGLGLGL..............................RURU....RURURURURURURURURURURURURU..RURURU............",
|
||||
"......USUSUSUSUSCACACACACACACACACACACACACACACACA....GLGLGLGLGLGLGL................NONONORURU....RURU..RURURURURURURURURURURURURURURURURURURURURURURURURU",
|
||||
"RURU..USUSUSUSUSCACACACACACACACACACACACACACACACACA....GLGLGLGL....ISIS..........NOSESEFIRURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURU",
|
||||
"......USUSUSUSUSCACACACACACACACACACACA....CACACACA....GLGL....................NONOSEFIFIRURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURU",
|
||||
"........USUS......USCACACACACACACACACACA..CACACACA........................GB..NOSESELVLVRURURURURURURURURURURURURURURURURURURURURURURURU......RURU......",
|
||||
"......US............CACACACACACACACACACACACACACACACA....................IEGBGBNLDEPLPLBYBYRURURURURURUKZKZRURURURURURURURURURURURURURURURU....RU........",
|
||||
"......................CACACACACACACACACACACACACACACACA....................FRFRDEDECZPLUAUAUARURUKZKZKZKZKZKZKZKZRUMNMNMNMNRUMNCNCNRURURURU..............",
|
||||
"........................USUSUSUSUSUSUSUSCACACAUSCA........................FRFRITITHRROROMDUARURURUKZKZKZKZKZKZCNCNMNMNMNMNMNCNCNCNCNRU..................",
|
||||
"......................USUSUSUSUSUSUSUSUSUSUSUS..........................ESESES..ITITALBGTRTRTRGEAZTMTMUZKZKGKGCNCNCNCNCNCNCNCNCNCNCN..JPJP..............",
|
||||
"........................USUSUSUSUSUSUSUSUSUS............................ESESDZDZ....GRTRTRTRTRIRIRIRIRTMTJTJCNCNCNCNCNCNCNCNCNCNKPKR..JP................",
|
||||
"..........................USUSUSUSUSUSUSUSUS............................MAMADZDZTN..LY....LBIQIQIRIRIRAFAFPKINCNCNCNCNCNCNCNCNCNKRJPJP..................",
|
||||
"..........................MXMXMXMXUSUS..US............................MADZDZDZDZLYLYLYEGEGSASAIQIRIRIRPKPKININNPCNCNCNCNCNCNCNCN........................",
|
||||
"............................MXMXMXUS....US..........................EHEHMRDZDZDZLYLYLYEGEGSASASASAAEIRPKPKINININININMMCNCNCNCNCN........................",
|
||||
"..............................MXMXMX..MXCUCUBS......................MRMRMRMLDZDZNETDLYSDSDSDSASASASAOM..INININININMMMMLAVNCN............................",
|
||||
"................................MXMXMXMX..JM........................MRMRMRMLMLNENETDTDSDSDSDERYEYEOM......INININ....MMTHVN....PH........................",
|
||||
"....................................GTSVNI....VE....................SNSNMLBFNENENGTDTDSDSDSDETYEYE........ININ......MMTHKH....PH........................",
|
||||
"........................................CRPACOVEVEVE..................SLCIGHBJNGNGTDCFSSSSETETSOSO..........IN....IN....VN......PH......................",
|
||||
"..........................................COCOCOVEGYSR..................CICI..NGCMCFCFCDSSKEETSOSO..................IDMY....MY..ID......................",
|
||||
"..........................................ECCOBRBRBRBRBR........................GACGCDCDUGKEKESO......................ID..IDIDID........................",
|
||||
"..........................................ECPEBRBRBRBRBRBRBR....................CGCDCDCDBITZKE........................IDIDIDIDID..IDIDIDPG..PG..........",
|
||||
"..........................................PEBRBRBRBRBRBRBRBRBR..................AOAOCDCDTZTZTZ..........................IDIDID........IDPGPGPG..........",
|
||||
"..........................................PEPEBOBRBRBRBRBRBRBR....................AOAOCDZMTZMZKM..................................AUAU....PG............",
|
||||
"............................................PEBOBOBRBRBRBRBR....................AOAOAOZMMZMZMZMGMG..............................AUAUAU..AU..............",
|
||||
"..............................................CLBOPYBRBRBRBR....................NANABWBWZWMZ..MGMG............................AUAUAUAUAUAUAU....FR......",
|
||||
"..............................................CLARPYBRBRBR........................NABWBWZAMZ..MG............................AUAUAUAUAUAUAUAU............",
|
||||
"..............................................ARARARBRBR..........................NAZAZAZA..................................AUAUAUAUAUAUAUAUAU..........",
|
||||
"..............................................ARARARUY............................ZAZAZAZA..................................AUAUAUAUAUAUAUAUAU..........",
|
||||
"............................................CLARARARUY..............................ZA......................................AU........AUAUAU............",
|
||||
"............................................CLARARAR....................................................................................AU............NZ",
|
||||
"............................................CLARAR......................................................................................AU........NZNZ..",
|
||||
"............................................CLAR........................................................................................................",
|
||||
"............................................CLAR........................................................................................................",
|
||||
"..............................................CL........................................................................................................",
|
||||
)
|
||||
|
||||
/** The country code of a dot, null for sea. */
|
||||
fun code(row: Int, column: Int): String? {
|
||||
val code = ROWS[row].substring(column * 2, column * 2 + 2)
|
||||
return if (code == "..") null else code
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 8.3 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 8.3 KiB |
|
Before Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 48 KiB |