Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be0f893f67 | ||
|
|
694e180855 | ||
|
|
65bf540ea0 | ||
| 81632a4275 | |||
| c48212bfff | |||
| adb8905ebf | |||
| 1a65736fb8 | |||
| 24561bbc88 | |||
| 0ed7ec0624 | |||
| 08b9579839 | |||
| 21f431441e |
70
.gitea/workflows/release.yml
Normal file
@@ -0,0 +1,70 @@
|
||||
name: Build & Release APK
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
# Builds on Marcus's MacBook: runner label `macos`, host mode (no container),
|
||||
# using the Node, JDK 21 and Android SDK set in the runner's config.yaml.
|
||||
# Jobs queue while the laptop is asleep or offline.
|
||||
# (Was `desktop` + a Linux container until 2026-11-24.)
|
||||
runs-on: macos
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
git init -q .
|
||||
git fetch -q --depth 1 "https://git.rehbock.xyz/${{ github.repository }}.git" "${{ github.sha }}"
|
||||
git checkout -q FETCH_HEAD
|
||||
|
||||
- name: Toolchain
|
||||
run: |
|
||||
node --version
|
||||
java -version 2>&1 | head -1
|
||||
test -d "$ANDROID_HOME/platforms" && echo "Android SDK: $ANDROID_HOME"
|
||||
|
||||
- name: npm ci
|
||||
run: npm ci --no-audit --no-fund
|
||||
|
||||
- name: Decode signing keystore
|
||||
env:
|
||||
KEYSTORE_B64: ${{ secrets.KEYSTORE_B64 }}
|
||||
run: echo "$KEYSTORE_B64" | base64 -d > "$PWD/.release.jks"
|
||||
|
||||
- name: Prebuild android project
|
||||
env:
|
||||
VERSION_CODE: ${{ github.run_number }}
|
||||
VERSION_NAME: 1.0.${{ github.run_number }}
|
||||
run: npx expo prebuild --platform android --no-install
|
||||
|
||||
- name: Build signed release APK (arm64)
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
KEY_ALIAS: health
|
||||
VERSION_CODE: ${{ github.run_number }}
|
||||
VERSION_NAME: 1.0.${{ github.run_number }}
|
||||
run: |
|
||||
export HEALTH_KEYSTORE="$PWD/.release.jks"
|
||||
echo "sdk.dir=$ANDROID_HOME" > android/local.properties
|
||||
cd android && ./gradlew assembleRelease -PreactNativeArchitectures=arm64-v8a \
|
||||
--no-daemon --console=plain
|
||||
|
||||
- name: Publish Gitea release with APK
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
API="https://git.rehbock.xyz/api/v1/repos/${{ github.repository }}"
|
||||
TAG="v1.0.${{ github.run_number }}"
|
||||
APK=android/app/build/outputs/apk/release/app-release.apk
|
||||
test -f "$APK"
|
||||
curl -sf -X POST "$API/releases" \
|
||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":\"Automated build of commit ${{ github.sha }}\",\"target_commitish\":\"${{ github.sha }}\"}" \
|
||||
> "$PWD/.release.json"
|
||||
RID=$(grep -o '"id":[0-9]*' "$PWD/.release.json" | head -1 | cut -d: -f2)
|
||||
echo "release id: $RID"
|
||||
curl -sf -X POST "$API/releases/$RID/assets?name=health-app-$TAG-arm64.apk" \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$APK;type=application/vnd.android.package-archive" >/dev/null
|
||||
echo "published $TAG"
|
||||
19
README.md
@@ -4,7 +4,7 @@ Cross-platform (iOS + Android) Expo app — native front end for the private
|
||||
health dashboard at **https://health.rehbock.xyz**.
|
||||
|
||||
The app is a pure client: all data lives on the server and is fetched live over
|
||||
HTTPS with HTTP Basic auth. Nothing is stored on the device except the auth
|
||||
HTTPS with a bearer API token. Nothing is stored on the device except the auth
|
||||
token (in the platform keychain via `expo-secure-store`).
|
||||
|
||||
## Screens
|
||||
@@ -30,7 +30,10 @@ npm install
|
||||
npx expo start # scan the QR with Expo Go (iOS or Android)
|
||||
```
|
||||
|
||||
Log in with the same Basic-auth credentials as the website.
|
||||
There is no login screen. Open **Settings** (⚙️ on the Today screen) and paste the API token;
|
||||
without one the app has no data. The server accepts it via `HEALTH_APP_TOKEN` in
|
||||
`health-auth` (`~/personal/health-auth/.env` on the VPS, passed through `docker-compose.yml`).
|
||||
Rotate it by changing that value and running `docker compose up -d`.
|
||||
|
||||
## Android release APK
|
||||
|
||||
@@ -47,8 +50,16 @@ cd android && ./gradlew assembleRelease
|
||||
# → android/app/build/outputs/apk/release/app-release.apk
|
||||
```
|
||||
|
||||
Install on GrapheneOS by copying the APK over (or via Obtainium once a
|
||||
Gitea release exists).
|
||||
Install on GrapheneOS by copying the APK over, or via Obtainium.
|
||||
|
||||
## CI (Gitea Actions)
|
||||
|
||||
Every push to `main` runs `.gitea/workflows/release.yml`: prebuild →
|
||||
signed arm64 APK → Gitea release tagged `v1.0.<run_number>`, APK attached.
|
||||
`app.config.js` stamps `VERSION_CODE`/`VERSION_NAME` from the run number so
|
||||
each release installs as an upgrade (Obtainium-friendly).
|
||||
|
||||
Repo secrets: `KEYSTORE_B64` (base64 of the jks), `KEYSTORE_PASSWORD`.
|
||||
|
||||
## iOS
|
||||
|
||||
|
||||
10
app.config.js
Normal file
@@ -0,0 +1,10 @@
|
||||
/* Wraps app.json so CI can stamp versions: VERSION_NAME → expo.version,
|
||||
VERSION_CODE → android.versionCode (Obtainium needs it to increase). */
|
||||
module.exports = ({ config }) => {
|
||||
const versionCode = parseInt(process.env.VERSION_CODE || '', 10);
|
||||
if (process.env.VERSION_NAME) config.version = process.env.VERSION_NAME;
|
||||
if (Number.isFinite(versionCode)) {
|
||||
config.android = { ...config.android, versionCode };
|
||||
}
|
||||
return config;
|
||||
};
|
||||
24
app.json
@@ -9,12 +9,25 @@
|
||||
"userInterfaceStyle": "dark",
|
||||
"backgroundColor": "#0d0d0f",
|
||||
"ios": {
|
||||
"icon": "./assets/expo.icon",
|
||||
"icon": "./assets/images/icon.png",
|
||||
"bundleIdentifier": "xyz.rehbock.health",
|
||||
"supportsTablet": true
|
||||
},
|
||||
"android": {
|
||||
"package": "xyz.rehbock.health",
|
||||
"permissions": [
|
||||
"android.permission.health.READ_HEART_RATE",
|
||||
"android.permission.health.READ_RESTING_HEART_RATE",
|
||||
"android.permission.health.READ_HEART_RATE_VARIABILITY",
|
||||
"android.permission.health.READ_OXYGEN_SATURATION",
|
||||
"android.permission.health.READ_SLEEP",
|
||||
"android.permission.health.READ_STEPS",
|
||||
"android.permission.health.READ_RESPIRATORY_RATE",
|
||||
"android.permission.health.READ_DISTANCE",
|
||||
"android.permission.health.READ_ACTIVE_CALORIES_BURNED",
|
||||
"android.permission.health.READ_TOTAL_CALORIES_BURNED",
|
||||
"android.permission.health.READ_FLOORS_CLIMBED"
|
||||
],
|
||||
"adaptiveIcon": {
|
||||
"backgroundColor": "#0d0d0f",
|
||||
"foregroundImage": "./assets/images/android-icon-foreground.png",
|
||||
@@ -30,6 +43,15 @@
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
"expo-secure-store",
|
||||
"react-native-health-connect",
|
||||
[
|
||||
"expo-build-properties",
|
||||
{
|
||||
"android": {
|
||||
"minSdkVersion": 26
|
||||
}
|
||||
}
|
||||
],
|
||||
"./plugins/with-release-signing.js",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg width="652" height="606" viewBox="0 0 652 606" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M353.554 0H298.446C273.006 0 249.684 14.6347 237.962 37.9539L4.37994 502.646C-1.04325 513.435 -1.45067 526.178 3.2716 537.313L22.6123 582.918C34.6475 611.297 72.5404 614.156 88.4414 587.885L309.863 222.063C313.34 216.317 319.439 212.826 326 212.826C332.561 212.826 338.659 216.317 342.137 222.063L563.559 587.885C579.46 614.156 617.352 611.297 629.388 582.918L648.728 537.313C653.451 526.178 653.043 513.435 647.62 502.646L414.038 37.9539C402.316 14.6347 378.994 0 353.554 0Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 608 B |
|
Before Width: | Height: | Size: 52 KiB |
@@ -1,40 +0,0 @@
|
||||
{
|
||||
"fill" : {
|
||||
"automatic-gradient" : "extended-srgb:0.00000,0.47843,1.00000,1.00000"
|
||||
},
|
||||
"groups" : [
|
||||
{
|
||||
"layers" : [
|
||||
{
|
||||
"image-name" : "expo-symbol 2.svg",
|
||||
"name" : "expo-symbol 2",
|
||||
"position" : {
|
||||
"scale" : 1,
|
||||
"translation-in-points" : [
|
||||
1.1008400065293245e-05,
|
||||
-16.046875
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"image-name" : "grid.png",
|
||||
"name" : "grid"
|
||||
}
|
||||
],
|
||||
"shadow" : {
|
||||
"kind" : "neutral",
|
||||
"opacity" : 0.5
|
||||
},
|
||||
"translucency" : {
|
||||
"enabled" : true,
|
||||
"value" : 0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"supported-platforms" : {
|
||||
"circles" : [
|
||||
"watchOS"
|
||||
],
|
||||
"squares" : "shared"
|
||||
}
|
||||
}
|
||||
1
assets/icon-src/background.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs><radialGradient id="hb" cx="50%" cy="44%" r="72%"><stop offset="0" stop-color="#1d1a33"/><stop offset="1" stop-color="#0b0b0e"/></radialGradient></defs><rect width="1024" height="1024" fill="url(#hb)"/></svg>
|
||||
|
After Width: | Height: | Size: 306 B |
1
assets/icon-src/foreground.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs><linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="205.1" y1="0" x2="711.9" y2="0"><stop offset="0" stop-color="#3fc8f2"/><stop offset="0.5" stop-color="#7c6cf7"/><stop offset="1" stop-color="#f06bc0"/></linearGradient><linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="205.1" y1="0" x2="329.0" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient><mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="1024" height="1024"><rect width="1024" height="1024" fill="url(#fadeg)"/></mask><filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="32.5"/></filter><filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="53.2"/></filter><radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/><stop offset="1" stop-color="#f06bc0"/></radialGradient></defs><g mask="url(#fm)" filter="url(#bl)" opacity="0.75"><path d="M205.1 530.9 L329.0 530.9 L368.4 490.7 L402.2 530.9 L430.3 530.9 L481.0 294.4 L537.3 724.9 L582.4 483.6 L610.6 530.9 L711.9 530.9" fill="none" stroke="url(#pl)" stroke-width="59.1" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="711.9" cy="530.9" r="112.4" fill="#f06bc0" opacity="0.55" filter="url(#bl2)"/><g mask="url(#fm)"><path d="M205.1 530.9 L329.0 530.9 L368.4 490.7 L402.2 530.9 L430.3 530.9 L481.0 294.4 L537.3 724.9 L582.4 483.6 L610.6 530.9 L711.9 530.9" fill="none" stroke="url(#pl)" stroke-width="59.1" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="711.9" cy="530.9" r="79.8" fill="none" stroke="#f06bc0" stroke-opacity="0.35" stroke-width="13.0"/><circle cx="711.9" cy="530.9" r="54.4" fill="url(#dot)"/></svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
1
assets/icon-src/icon.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs><radialGradient id="hb" cx="50%" cy="44%" r="72%"><stop offset="0" stop-color="#1d1a33"/><stop offset="1" stop-color="#0b0b0e"/></radialGradient><linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="122.9" y1="0" x2="823.3" y2="0"><stop offset="0" stop-color="#3fc8f2"/><stop offset="0.5" stop-color="#7c6cf7"/><stop offset="1" stop-color="#f06bc0"/></linearGradient><linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="122.9" y1="0" x2="294.1" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient><mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="1024" height="1024"><rect width="1024" height="1024" fill="url(#fadeg)"/></mask><filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="44.9"/></filter><filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="73.5"/></filter><radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/><stop offset="1" stop-color="#f06bc0"/></radialGradient></defs><rect width="1024" height="1024" fill="url(#hb)"/><g mask="url(#fm)" filter="url(#bl)" opacity="0.75"><path d="M122.9 538.1 L294.1 538.1 L348.6 482.6 L395.3 538.1 L434.2 538.1 L504.2 211.3 L582.0 806.2 L644.3 472.8 L683.2 538.1 L823.3 538.1" fill="none" stroke="url(#pl)" stroke-width="81.7" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="823.3" cy="538.1" r="155.3" fill="#f06bc0" opacity="0.55" filter="url(#bl2)"/><g mask="url(#fm)"><path d="M122.9 538.1 L294.1 538.1 L348.6 482.6 L395.3 538.1 L434.2 538.1 L504.2 211.3 L582.0 806.2 L644.3 472.8 L683.2 538.1 L823.3 538.1" fill="none" stroke="url(#pl)" stroke-width="81.7" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="823.3" cy="538.1" r="126.7" fill="none" stroke="#f06bc0" stroke-opacity="0.35" stroke-width="18.0"/><circle cx="823.3" cy="538.1" r="75.2" fill="url(#dot)"/></svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
116
assets/icon-src/make.py
Normal file
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the Health app icon set from one mark: a live heartbeat trace.
|
||||
|
||||
python3 assets/icon-src/make.py # needs `resvg` and `magick` (Homebrew)
|
||||
|
||||
The mark is a bold ECG trace in the dashboard's blue → violet → pink gradient
|
||||
that fades in from the left and ends in a glowing "now" dot, like the live
|
||||
point on a chart. The background is the app's near-black (#0d0d0f) with a
|
||||
violet glow.
|
||||
|
||||
Writes the SVG sources next to this file and the PNGs into assets/images/:
|
||||
icon.png 1024 opaque (iOS + fallback)
|
||||
android-icon-background.png 1024 opaque (adaptive background)
|
||||
android-icon-foreground.png 1024 alpha (adaptive foreground, inside the 66dp safe zone)
|
||||
android-icon-monochrome.png 1024 alpha (themed icon, white glyph)
|
||||
splash-icon.png 512 alpha (splash, glyph only)
|
||||
favicon.png 64 opaque (web)
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
IMAGES = os.path.join(HERE, '..', 'images')
|
||||
|
||||
BG_CENTER, BG_EDGE = '#1d1a33', '#0b0b0e'
|
||||
TRACE = [(0, '#3fc8f2'), (0.5, '#7c6cf7'), (1, '#f06bc0')] # blue → accent violet → pink
|
||||
|
||||
# x in 0..1 across the glyph, y in -1..1 (negative = up)
|
||||
PULSE = [(0.00, 0), (0.22, 0), (0.29, -0.17), (0.35, 0.0), (0.40, 0),
|
||||
(0.49, -1.0), (0.59, 0.82), (0.67, -0.20), (0.72, 0), (0.90, 0)]
|
||||
|
||||
|
||||
def svg(size, body, defs=''):
|
||||
return (f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" '
|
||||
f'viewBox="0 0 {size} {size}"><defs>{defs}</defs>{body}</svg>\n')
|
||||
|
||||
|
||||
def background(size):
|
||||
defs = (f'<radialGradient id="hb" cx="50%" cy="44%" r="72%">'
|
||||
f'<stop offset="0" stop-color="{BG_CENTER}"/><stop offset="1" stop-color="{BG_EDGE}"/></radialGradient>')
|
||||
return defs, f'<rect width="{size}" height="{size}" fill="url(#hb)"/>'
|
||||
|
||||
|
||||
def pulse(size, scale, mono=False, glow=True, shift=0.0, halo=1.55):
|
||||
"""scale = glyph width as a fraction of the canvas."""
|
||||
w = size * scale
|
||||
amp, stroke = w * 0.42, w * 0.105
|
||||
c = size / 2
|
||||
left = c - shift * w - w / 2
|
||||
pts = [(left + x * w, c + amp * 0.08 + y * amp) for x, y in PULSE]
|
||||
if mono: # no fade in a single colour: start the trace later instead
|
||||
pts = [(left + 0.12 * w, pts[0][1])] + pts[2:]
|
||||
d = 'M' + ' L'.join(f'{x:.1f} {y:.1f}' for x, y in pts)
|
||||
ex, ey = pts[-1]
|
||||
line = (f'<path d="{d}" fill="none" stroke="{{s}}" stroke-width="{stroke:.1f}" '
|
||||
f'stroke-linecap="round" stroke-linejoin="round"/>')
|
||||
if mono:
|
||||
return '', line.format(s='#fff') + f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * 0.95:.1f}" fill="#fff"/>'
|
||||
|
||||
stops = ''.join(f'<stop offset="{p}" stop-color="{col}"/>' for p, col in TRACE)
|
||||
defs = (f'<linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="{left:.1f}" y1="0" x2="{ex:.1f}" y2="0">{stops}</linearGradient>'
|
||||
f'<linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="{left:.1f}" y1="0" x2="{left + w * 0.22:.1f}" y2="0">'
|
||||
f'<stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient>'
|
||||
f'<mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="{size}" height="{size}">'
|
||||
f'<rect width="{size}" height="{size}" fill="url(#fadeg)"/></mask>'
|
||||
f'<filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="{stroke * 0.55:.1f}"/></filter>'
|
||||
f'<filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="{stroke * 0.9:.1f}"/></filter>'
|
||||
f'<radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/>'
|
||||
f'<stop offset="1" stop-color="{TRACE[-1][1]}"/></radialGradient>')
|
||||
trace = line.format(s='url(#pl)')
|
||||
body = ''
|
||||
if glow:
|
||||
body += f'<g mask="url(#fm)" filter="url(#bl)" opacity="0.75">{trace}</g>'
|
||||
body += f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * 1.9:.1f}" fill="{TRACE[-1][1]}" opacity="0.55" filter="url(#bl2)"/>'
|
||||
body += f'<g mask="url(#fm)">{trace}</g>'
|
||||
body += (f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * halo:.1f}" fill="none" stroke="{TRACE[-1][1]}" '
|
||||
f'stroke-opacity="0.35" stroke-width="{stroke * 0.22:.1f}"/>')
|
||||
body += f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * 0.92:.1f}" fill="url(#dot)"/>'
|
||||
return defs, body
|
||||
|
||||
|
||||
def main():
|
||||
bd, bb = background(1024)
|
||||
# iOS: full-bleed, glyph spans 76% (Apple rounds the corners itself)
|
||||
gd, gb = pulse(1024, 0.76)
|
||||
sources = {
|
||||
'icon': (1024, svg(1024, bb + gb, bd + gd)),
|
||||
'background': (1024, svg(1024, bb, bd)),
|
||||
# Android adaptive: shifted left (the trace fades in) so the dot + halo clear the 66dp safe circle
|
||||
'foreground': (1024, svg(1024, *reversed(pulse(1024, 0.55, shift=0.045, halo=1.35)))),
|
||||
# themed icons read best a little smaller than the colour glyph
|
||||
'monochrome': (1024, svg(1024, *reversed(pulse(1024, 0.46, mono=True, glow=False, shift=0.045)))),
|
||||
'splash': (512, svg(512, *reversed(pulse(512, 0.94, glow=False)))),
|
||||
}
|
||||
out = {
|
||||
'icon': 'icon.png', 'background': 'android-icon-background.png',
|
||||
'foreground': 'android-icon-foreground.png', 'monochrome': 'android-icon-monochrome.png',
|
||||
'splash': 'splash-icon.png',
|
||||
}
|
||||
for name, (size, text) in sources.items():
|
||||
src = os.path.join(HERE, f'{name}.svg')
|
||||
with open(src, 'w') as f:
|
||||
f.write(text)
|
||||
png = os.path.join(IMAGES, out[name])
|
||||
subprocess.run(['resvg', '-w', str(size), '-h', str(size), src, png], check=True)
|
||||
# iOS rejects icons with an alpha channel; the web favicon is the icon at 64px
|
||||
icon = os.path.join(IMAGES, 'icon.png')
|
||||
subprocess.run(['magick', icon, '-background', BG_EDGE, '-alpha', 'remove', '-alpha', 'off', icon], check=True)
|
||||
bgp = os.path.join(IMAGES, 'android-icon-background.png')
|
||||
subprocess.run(['magick', bgp, '-alpha', 'off', bgp], check=True)
|
||||
subprocess.run(['magick', icon, '-resize', '64x64', os.path.join(IMAGES, 'favicon.png')], check=True)
|
||||
print('wrote', ', '.join(out.values()), 'favicon.png')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
1
assets/icon-src/monochrome.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs></defs><path d="M311.8 527.8 L391.9 494.2 L420.1 527.8 L443.7 527.8 L486.1 330.0 L533.2 690.1 L570.9 488.3 L594.4 527.8 L679.2 527.8" fill="none" stroke="#fff" stroke-width="49.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="679.2" cy="527.8" r="47.0" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 384 B |
1
assets/icon-src/splash.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><defs><linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="15.4" y1="0" x2="448.5" y2="0"><stop offset="0" stop-color="#3fc8f2"/><stop offset="0.5" stop-color="#7c6cf7"/><stop offset="1" stop-color="#f06bc0"/></linearGradient><linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="15.4" y1="0" x2="121.2" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient><mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512"><rect width="512" height="512" fill="url(#fadeg)"/></mask><filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="27.8"/></filter><filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="45.5"/></filter><radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/><stop offset="1" stop-color="#f06bc0"/></radialGradient></defs><g mask="url(#fm)"><path d="M15.4 272.2 L121.2 272.2 L154.9 237.8 L183.8 272.2 L207.9 272.2 L251.2 70.0 L299.3 437.9 L337.8 231.7 L361.9 272.2 L448.5 272.2" fill="none" stroke="url(#pl)" stroke-width="50.5" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="448.5" cy="272.2" r="78.3" fill="none" stroke="#f06bc0" stroke-opacity="0.35" stroke-width="11.1"/><circle cx="448.5" cy="272.2" r="46.5" fill="url(#dot)"/></svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 249 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 4.8 KiB |
|
Before Width: | Height: | Size: 780 KiB After Width: | Height: | Size: 245 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 21 KiB |
47
package-lock.json
generated
@@ -27,6 +27,7 @@
|
||||
"react-dom": "19.2.3",
|
||||
"react-native": "0.86.2",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-health-connect": "^4.1.3",
|
||||
"react-native-reanimated": "4.5.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "~4.26.0",
|
||||
@@ -36,6 +37,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.2",
|
||||
"expo-build-properties": "^57.0.9",
|
||||
"typescript": "~6.0.3"
|
||||
}
|
||||
},
|
||||
@@ -3811,6 +3813,21 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-build-properties": {
|
||||
"version": "57.0.9",
|
||||
"resolved": "https://registry.npmjs.org/expo-build-properties/-/expo-build-properties-57.0.9.tgz",
|
||||
"integrity": "sha512-IX8Nz85yNDZyqBK7zbLEfn4ijMGaF6TmLjCY2KE0UKltUoV78DhgN6ksPZbDbPDvqLpU2fMY/5OD4CbYB7hHwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/schema-utils": "^57.0.2",
|
||||
"resolve-from": "^5.0.0",
|
||||
"semver": "^7.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-constants": {
|
||||
"version": "57.0.9",
|
||||
"resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-57.0.9.tgz",
|
||||
@@ -6575,6 +6592,36 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/react-native-health-connect": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/react-native-health-connect/-/react-native-health-connect-4.1.3.tgz",
|
||||
"integrity": "sha512-osiWh4RD4tNHdHeggzOeGZFeEVaLQQr0+Yezq61WsPRvN1Yb6eA10rMfSU0+dqcfm6ZvIXSr2tYns+Yg1s37nw==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"example",
|
||||
"docs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/matinzd/react-native-health-connect?sponsor=1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@expo/config-plugins": ">= 6.0.2",
|
||||
"expo": "*",
|
||||
"react": "*",
|
||||
"react-native": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@expo/config-plugins": {
|
||||
"optional": true
|
||||
},
|
||||
"expo": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-native-is-edge-to-edge": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-native-is-edge-to-edge/-/react-native-is-edge-to-edge-1.3.1.tgz",
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
"react-dom": "19.2.3",
|
||||
"react-native": "0.86.2",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-health-connect": "^4.1.3",
|
||||
"react-native-reanimated": "4.5.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "~4.26.0",
|
||||
@@ -31,6 +32,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.2",
|
||||
"expo-build-properties": "^57.0.9",
|
||||
"typescript": "~6.0.3"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -40,6 +40,17 @@ module.exports = function withReleaseSigning(config) {
|
||||
if (jdk && !cfg.modResults.some((p) => p.key === 'org.gradle.java.home')) {
|
||||
cfg.modResults.push({ type: 'property', key: 'org.gradle.java.home', value: jdk });
|
||||
}
|
||||
/* use every core: parallel module builds + build cache */
|
||||
const set = (key, value) => {
|
||||
const hit = cfg.modResults.find((p) => p.key === key);
|
||||
if (hit) hit.value = value;
|
||||
else cfg.modResults.push({ type: 'property', key, value });
|
||||
};
|
||||
set('org.gradle.parallel', 'true');
|
||||
set('org.gradle.caching', 'true');
|
||||
set('org.gradle.configuration-cache', 'false');
|
||||
set('org.gradle.workers.max', String(os.cpus().length));
|
||||
set('org.gradle.jvmargs', '-Xmx6g -XX:MaxMetaspaceSize=1g');
|
||||
return cfg;
|
||||
});
|
||||
return withAppBuildGradle(config, (cfg) => {
|
||||
|
||||
@@ -4,12 +4,10 @@ import React from 'react';
|
||||
import { View } from 'react-native';
|
||||
import { AuthProvider, useAuth } from '../lib/api';
|
||||
import { C } from '../lib/theme';
|
||||
import { LoginScreen } from '../components/login';
|
||||
|
||||
function Gate() {
|
||||
const { ready, authed } = useAuth();
|
||||
const { ready } = useAuth();
|
||||
if (!ready) return <View style={{ flex: 1, backgroundColor: C.bg }} />;
|
||||
if (!authed) return <LoginScreen />;
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
@@ -22,10 +20,12 @@ function Gate() {
|
||||
<Stack.Screen name="index" options={{ title: 'Health' }} />
|
||||
<Stack.Screen name="blood" options={{ title: 'Bloodwork' }} />
|
||||
<Stack.Screen name="sleep" options={{ title: 'Sleep' }} />
|
||||
<Stack.Screen name="fitbit" options={{ title: 'Fitbit Air' }} />
|
||||
<Stack.Screen name="train" options={{ title: 'Training' }} />
|
||||
<Stack.Screen name="body" options={{ title: 'Body Composition' }} />
|
||||
<Stack.Screen name="mind" options={{ title: 'Meditation' }} />
|
||||
<Stack.Screen name="dna" options={{ title: 'Genetic Traits' }} />
|
||||
<Stack.Screen name="settings" options={{ title: 'Settings' }} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
237
src/app/fitbit.tsx
Normal file
@@ -0,0 +1,237 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Platform, Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
|
||||
import { DailyBars, DailyLine } from '../components/charts';
|
||||
import { ErrBox, Loading, Panel, Screen, Sec, SrcNote, Tile, TileGrid } from '../components/ui';
|
||||
import { load } from '../lib/api';
|
||||
import { fmtDY, hm, num } from '../lib/format';
|
||||
import { healthConnectStatus, healthConnectSupported, syncFitbit } from '../lib/fitbit';
|
||||
import { C } from '../lib/theme';
|
||||
import { useLoad } from '../lib/use-load';
|
||||
|
||||
interface DayVal { day: string; value: number }
|
||||
interface DayAvg { day: string; avg: number; n: number }
|
||||
|
||||
interface Summary {
|
||||
days: number;
|
||||
steps: DayVal[];
|
||||
hr_daily: { day: string; min: number; max: number; avg: number; n: number }[];
|
||||
resting_hr: DayAvg[];
|
||||
hrv: DayAvg[];
|
||||
spo2: DayAvg[];
|
||||
respiratory_rate: DayAvg[];
|
||||
sleep: {
|
||||
id: string; started_at: string; ended_at: string; total_seconds: number;
|
||||
sleep_seconds: number; deep_seconds: number; rem_seconds: number;
|
||||
light_seconds: number; awake_seconds: number;
|
||||
}[];
|
||||
sample_counts: Record<string, number>;
|
||||
}
|
||||
|
||||
export default function Fitbit() {
|
||||
const { width } = useWindowDimensions();
|
||||
const chartW = Math.min(608, width - 32) - 28;
|
||||
const { data, err, loading, refresh } = useLoad(() => load<Summary>('fitbitSummary'));
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [syncMsg, setSyncMsg] = useState('');
|
||||
const [hcStatus, setHcStatus] = useState<string>('');
|
||||
const autoSynced = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
healthConnectStatus().then(setHcStatus);
|
||||
}, []);
|
||||
|
||||
const runSync = async () => {
|
||||
if (syncing) return;
|
||||
setSyncing(true);
|
||||
try {
|
||||
const res = await syncFitbit(setSyncMsg);
|
||||
setSyncMsg(res.message);
|
||||
if (res.ok && (res.samples || res.daily || res.sleep)) refresh();
|
||||
} catch (e) {
|
||||
setSyncMsg(`Sync failed: ${e instanceof Error ? e.message : e}`);
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// auto-sync once per screen visit on Android
|
||||
useEffect(() => {
|
||||
if (hcStatus === 'available' && !autoSynced.current) {
|
||||
autoSynced.current = true;
|
||||
runSync();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hcStatus]);
|
||||
|
||||
let body: React.ReactNode = null;
|
||||
if (loading && !data) body = <Loading />;
|
||||
else if (err) body = <ErrBox msg={err} />;
|
||||
else if (data) {
|
||||
const lastVal = (arr: DayAvg[]) => (arr.length ? arr[arr.length - 1] : null);
|
||||
const stepsToday = data.steps.length ? data.steps[data.steps.length - 1] : null;
|
||||
const rhr = lastVal(data.resting_hr);
|
||||
const hrv = lastVal(data.hrv);
|
||||
const spo2 = lastVal(data.spo2);
|
||||
const lastSleep = data.sleep.length ? data.sleep[data.sleep.length - 1] : null;
|
||||
const empty = !data.steps.length && !data.hr_daily.length && !data.sleep.length;
|
||||
|
||||
body = (
|
||||
<>
|
||||
{empty ? (
|
||||
<View style={s.emptyBox}>
|
||||
<Text style={{ color: C.text, fontSize: 14, fontWeight: '600', marginBottom: 6 }}>
|
||||
No Fitbit data yet
|
||||
</Text>
|
||||
<Text style={{ color: C.muted, fontSize: 12.5, lineHeight: 18 }}>
|
||||
Make sure the Google Health app is installed, the Fitbit Air is paired, and
|
||||
Google Health is sharing to Health Connect (Profile → Privacy → Health Connect).
|
||||
Then tap Sync below.
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<TileGrid>
|
||||
<Tile label="Steps" value={stepsToday ? num(Math.round(stepsToday.value)) : '—'}
|
||||
sub={stepsToday ? fmtDY(stepsToday.day) : undefined} />
|
||||
<Tile label="Resting HR" value={rhr ? String(Math.round(rhr.avg)) : '—'} unit="bpm"
|
||||
sub={rhr ? fmtDY(rhr.day) : undefined} />
|
||||
<Tile label="HRV (RMSSD)" value={hrv ? String(Math.round(hrv.avg)) : '—'} unit="ms"
|
||||
sub={hrv ? fmtDY(hrv.day) : undefined} />
|
||||
<Tile label="SpO2" value={spo2 ? spo2.avg.toFixed(1) : '—'} unit="%"
|
||||
sub={spo2 ? fmtDY(spo2.day) : undefined} />
|
||||
{lastSleep ? (
|
||||
<Tile label="Last sleep" value={hm(lastSleep.sleep_seconds)}
|
||||
sub={fmtDY(lastSleep.started_at)} />
|
||||
) : null}
|
||||
</TileGrid>
|
||||
)}
|
||||
|
||||
{data.steps.length ? (
|
||||
<>
|
||||
<Sec title={`Steps · ${data.days} days`} />
|
||||
<Panel title="Daily steps" sub="tap a bar">
|
||||
<DailyBars data={data.steps} width={chartW} unit="Steps" />
|
||||
</Panel>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{data.resting_hr.length > 1 ? (
|
||||
<>
|
||||
<Sec title="Resting heart rate" />
|
||||
<Panel title="Daily resting HR (bpm)" sub="tap a point">
|
||||
<DailyLine data={data.resting_hr} width={chartW} unit="bpm" color={C.s2} />
|
||||
</Panel>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{data.hrv.length > 1 ? (
|
||||
<>
|
||||
<Sec title="Heart rate variability" />
|
||||
<Panel title="Nightly HRV RMSSD (ms)" sub="tap a point">
|
||||
<DailyLine data={data.hrv} width={chartW} unit="ms" color={C.s3} />
|
||||
</Panel>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{data.spo2.length > 1 ? (
|
||||
<>
|
||||
<Sec title="Blood oxygen" />
|
||||
<Panel title="Nightly SpO2 (%)" sub="tap a point">
|
||||
<DailyLine data={data.spo2} width={chartW} unit="%" color={C.s1} decimals={1} />
|
||||
</Panel>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{data.sleep.length ? (
|
||||
<>
|
||||
<Sec title="Sleep sessions" count={data.sleep.length} />
|
||||
{[...data.sleep].reverse().slice(0, 14).map((sl) => (
|
||||
<View key={sl.id} style={s.row}>
|
||||
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
|
||||
<Text style={{ color: C.text, fontSize: 13.5, fontWeight: '500' }}>
|
||||
{hm(sl.sleep_seconds)}
|
||||
</Text>
|
||||
<Text style={{ color: C.muted, fontSize: 11 }}>{fmtDY(sl.started_at)}</Text>
|
||||
</View>
|
||||
<Text style={{ color: C.muted, fontSize: 12, marginTop: 3 }}>
|
||||
{sl.deep_seconds ? `deep ${hm(sl.deep_seconds)} · ` : ''}
|
||||
{sl.rem_seconds ? `REM ${hm(sl.rem_seconds)} · ` : ''}
|
||||
{sl.light_seconds ? `light ${hm(sl.light_seconds)} · ` : ''}
|
||||
awake {hm(sl.awake_seconds)}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Sec title="Data on record" />
|
||||
<View style={s.debugBox}>
|
||||
{Object.entries(data.sample_counts).map(([k, v]) => (
|
||||
<Text key={k} style={{ color: v ? C.muted : C.dim, fontSize: 12, marginVertical: 1 }}>
|
||||
{k.replace(/_/g, ' ')}: {num(v)}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
<SrcNote>
|
||||
Fitbit Air → Google Health → Health Connect → health.rehbock.xyz. Data syncs from
|
||||
this phone when you open this screen; the server is the system of record.
|
||||
</SrcNote>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Screen onRefresh={refresh}>
|
||||
{/* sync bar */}
|
||||
<View style={s.syncBar}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={{ color: C.text, fontSize: 13, fontWeight: '600' }}>
|
||||
{Platform.OS === 'android' ? 'Health Connect' : 'Sync (Android phone only)'}
|
||||
</Text>
|
||||
<Text style={{ color: C.muted, fontSize: 11.5, marginTop: 2 }}>
|
||||
{healthConnectSupported()
|
||||
? hcStatus === 'available'
|
||||
? syncMsg || 'Ready'
|
||||
: hcStatus === 'needs-update'
|
||||
? 'Health Connect needs an update'
|
||||
: hcStatus || 'Checking…'
|
||||
: 'Viewing server data — sync runs on the Android phone'}
|
||||
</Text>
|
||||
</View>
|
||||
{healthConnectSupported() && (
|
||||
<Pressable
|
||||
style={[s.syncBtn, (syncing || hcStatus !== 'available') && { opacity: 0.5 }]}
|
||||
disabled={syncing || hcStatus !== 'available'}
|
||||
onPress={runSync}>
|
||||
<Text style={{ color: '#fff', fontWeight: '600', fontSize: 13 }}>
|
||||
{syncing ? 'Syncing…' : 'Sync'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</View>
|
||||
{body}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const s = StyleSheet.create({
|
||||
syncBar: {
|
||||
flexDirection: 'row', alignItems: 'center', gap: 12,
|
||||
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border,
|
||||
borderRadius: 12, padding: 12, marginBottom: 14,
|
||||
},
|
||||
syncBtn: {
|
||||
backgroundColor: C.accent, borderRadius: 10, paddingVertical: 9, paddingHorizontal: 18,
|
||||
},
|
||||
emptyBox: {
|
||||
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border,
|
||||
borderRadius: 12, padding: 16, marginBottom: 4,
|
||||
},
|
||||
row: {
|
||||
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border, borderRadius: 12,
|
||||
paddingVertical: 12, paddingHorizontal: 14, marginBottom: 8,
|
||||
},
|
||||
debugBox: {
|
||||
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border,
|
||||
borderRadius: 12, padding: 12,
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Stack } from 'expo-router';
|
||||
import { Link, Stack } from 'expo-router';
|
||||
import React from 'react';
|
||||
import { Alert, Pressable, Text, View } from 'react-native';
|
||||
import { Text, View } from 'react-native';
|
||||
import { NavCard, PriorityCard, Screen, Sec } from '../components/ui';
|
||||
import { useAuth } from '../lib/api';
|
||||
import { agoTxt, fmtD, fmtDY, hm, num, cap } from '../lib/format';
|
||||
@@ -13,11 +13,11 @@ import type {
|
||||
import { loadAll, useLoad } from '../lib/use-load';
|
||||
|
||||
export default function Today() {
|
||||
const { logout } = useAuth();
|
||||
const { hasToken } = useAuth();
|
||||
const { data, loading, refresh } = useLoad(() =>
|
||||
loadAll({
|
||||
meta: 'meta', bio: 'biomarkers', wo: 'workouts', sApi: 'sleepApi',
|
||||
sc: 'sleepCycle', dexa: 'dexa', med: 'medStats',
|
||||
sc: 'sleepCycle', dexa: 'dexa', med: 'medStats', fitbit: 'fitbitSummary',
|
||||
} as const),
|
||||
);
|
||||
|
||||
@@ -30,6 +30,11 @@ export default function Today() {
|
||||
sc: SleepCycleExport | null;
|
||||
dexa: DexaResponse | null;
|
||||
med: MeditationStats | null;
|
||||
fitbit: {
|
||||
steps: { day: string; value: number }[];
|
||||
resting_hr: { day: string; avg: number }[];
|
||||
hrv: { day: string; avg: number }[];
|
||||
} | null;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
@@ -89,6 +94,21 @@ export default function Today() {
|
||||
);
|
||||
} else cards.push(<NavCard key="mind" title="Mind" big="—" note="Couldn’t load" href="/mind" />);
|
||||
|
||||
{
|
||||
const fb = r.fitbit;
|
||||
const steps = fb?.steps?.length ? fb.steps[fb.steps.length - 1] : null;
|
||||
const hrv = fb?.hrv?.length ? fb.hrv[fb.hrv.length - 1] : null;
|
||||
cards.push(
|
||||
<NavCard key="fitbit" title="Fitbit" href="/fitbit"
|
||||
big={steps ? num(Math.round(steps.value)) : '—'} unit={steps ? 'steps' : undefined}
|
||||
note={
|
||||
steps
|
||||
? `${fmtD(steps.day)}${hrv ? ` · HRV ${Math.round(hrv.avg)} ms` : ''}`
|
||||
: 'Open to sync from Health Connect'
|
||||
} />,
|
||||
);
|
||||
}
|
||||
|
||||
cards.push(
|
||||
<NavCard key="dna" title="DNA" big="99" unit="traits" href="/dna"
|
||||
note="AncestryDNA trait report" />,
|
||||
@@ -100,16 +120,9 @@ export default function Today() {
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
hitSlop={10}
|
||||
onPress={() =>
|
||||
Alert.alert('Lock the dashboard?', 'You will need the password to get back in.', [
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{ text: 'Lock', style: 'destructive', onPress: logout },
|
||||
])
|
||||
}>
|
||||
<Text style={{ fontSize: 16 }}>🔒</Text>
|
||||
</Pressable>
|
||||
<Link href="/settings">
|
||||
<Text style={{ fontSize: 18, padding: 6 }}>⚙️</Text>
|
||||
</Link>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
@@ -119,7 +132,11 @@ export default function Today() {
|
||||
weekday: 'long', month: 'long', day: 'numeric',
|
||||
})}
|
||||
/>
|
||||
{loading && !r ? (
|
||||
{!hasToken ? (
|
||||
<Link href="/settings" style={{ padding: 24, textAlign: 'center', color: C.accent, fontSize: 15 }}>
|
||||
Add your API token in Settings to load your data →
|
||||
</Link>
|
||||
) : loading && !r ? (
|
||||
<Text style={{ color: C.muted, fontSize: 13, textAlign: 'center', padding: 24 }}>
|
||||
Loading…
|
||||
</Text>
|
||||
|
||||
74
src/app/settings.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import { Screen } from '../components/ui';
|
||||
import { BASE, useAuth } from '../lib/api';
|
||||
import { C } from '../lib/theme';
|
||||
|
||||
export default function Settings() {
|
||||
const { hasToken, saveToken, clearToken } = useAuth();
|
||||
const [value, setValue] = useState('');
|
||||
const [msg, setMsg] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
setMsg('');
|
||||
try {
|
||||
if (await saveToken(value)) {
|
||||
setValue('');
|
||||
setMsg('Saved.');
|
||||
} else setMsg('The server rejected that token.');
|
||||
} catch {
|
||||
setMsg('Network error — are you online?');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen>
|
||||
<Text style={s.lbl}>SERVER</Text>
|
||||
<Text style={s.val}>{BASE}</Text>
|
||||
<Text style={s.lbl}>API TOKEN {hasToken ? '· saved' : '· not set'}</Text>
|
||||
<TextInput
|
||||
style={s.input}
|
||||
value={value}
|
||||
onChangeText={setValue}
|
||||
placeholder={hasToken ? '•••••••• (enter a new one to replace)' : 'Paste your API token'}
|
||||
placeholderTextColor={C.dim}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
secureTextEntry
|
||||
onSubmitEditing={save}
|
||||
returnKeyType="done"
|
||||
/>
|
||||
<Pressable
|
||||
style={[s.go, (busy || !value.trim()) && { opacity: 0.5 }]}
|
||||
disabled={busy || !value.trim()}
|
||||
onPress={save}>
|
||||
<Text style={s.goTxt}>Save token</Text>
|
||||
</Pressable>
|
||||
{hasToken ? (
|
||||
<Pressable style={s.clear} onPress={clearToken}>
|
||||
<Text style={{ color: C.red, fontSize: 14 }}>Remove token from this device</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<View style={{ minHeight: 24 }}>
|
||||
<Text style={s.msg}>{msg}</Text>
|
||||
</View>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const s = StyleSheet.create({
|
||||
lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 16, marginBottom: 6 },
|
||||
val: { fontSize: 15, color: C.text },
|
||||
input: {
|
||||
paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
|
||||
borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
|
||||
},
|
||||
go: { marginTop: 16, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center' },
|
||||
goTxt: { color: '#fff', fontWeight: '600', fontSize: 15 },
|
||||
clear: { marginTop: 20, alignItems: 'center', padding: 8 },
|
||||
msg: { marginTop: 12, fontSize: 12.5, color: C.muted },
|
||||
});
|
||||
@@ -13,15 +13,19 @@ export default function Sleep() {
|
||||
const { width } = useWindowDimensions();
|
||||
const chartW = Math.min(608, width - 32) - 28;
|
||||
const { data, err, loading, refresh } = useLoad(() =>
|
||||
Promise.all([load<SleepApiResponse>('sleepApi'), load<SleepCycleExport>('sleepCycle')]),
|
||||
Promise.all([
|
||||
load<SleepApiResponse>('sleepApi'),
|
||||
load<SleepCycleExport>('sleepCycle'),
|
||||
load<{ sleep: import('../lib/shape').HcSleepRow[] }>('fitbitSummary').catch(() => null),
|
||||
]),
|
||||
);
|
||||
|
||||
let body: React.ReactNode = null;
|
||||
if (loading && !data) body = <Loading />;
|
||||
else if (err) body = <ErrBox msg={err} />;
|
||||
else if (data) {
|
||||
const [api, sc] = data;
|
||||
const nights = shapeSleep(api, sc);
|
||||
const [api, sc, fb] = data;
|
||||
const nights = shapeSleep(api, sc, fb?.sleep ?? []);
|
||||
const recent = nights.slice(-30);
|
||||
const last7 = nights.slice(-7);
|
||||
const avg = (arr: typeof nights, f: (t: (typeof nights)[0]) => number) =>
|
||||
@@ -56,8 +60,9 @@ export default function Sleep() {
|
||||
/>
|
||||
</Panel>
|
||||
<SrcNote>
|
||||
Sources: Eight Sleep pod (through Feb 2026, incl. HRV/HR) and Sleep Cycle app export
|
||||
(through {sc.exported_at}). {num(nights.length)} nights total on record.
|
||||
Sources: Fitbit Air (via Health Connect), Eight Sleep pod (through Feb 2026, incl.
|
||||
HRV/HR), Sleep Cycle export (through {sc.exported_at}). {num(nights.length)} nights
|
||||
total on record.
|
||||
</SrcNote>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -157,6 +157,108 @@ export function VolumeChart({ weeks, width }: { weeks: Week[]; width: number })
|
||||
);
|
||||
}
|
||||
|
||||
/* generic daily bars (steps, kcal…) — tap for value */
|
||||
export function DailyBars({
|
||||
data, width, unit, color = C.s1, fmt = (v: number) => kfmt(v),
|
||||
}: {
|
||||
data: { day: string; value: number }[];
|
||||
width: number;
|
||||
unit: string;
|
||||
color?: string;
|
||||
fmt?: (v: number) => string;
|
||||
}) {
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
if (!data.length) return null;
|
||||
const H = 130, padL = 34, padB = 16, W = width;
|
||||
const iw = W - padL, n = data.length, bw = Math.max(3, iw / n - 2);
|
||||
const maxV = Math.max(...data.map((d) => d.value), 1);
|
||||
const y = (v: number) => H - padB - (v / maxV) * (H - padB - 8);
|
||||
const selD = sel != null ? data[sel] : null;
|
||||
return (
|
||||
<View>
|
||||
<Svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
|
||||
{[0, 0.5, 1].map((f) => (
|
||||
<G key={f}>
|
||||
<Line x1={padL} y1={y(maxV * f)} x2={W} y2={y(maxV * f)} stroke={C.gridline} strokeWidth={1} />
|
||||
<SvgText x={padL - 5} y={y(maxV * f) + 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
|
||||
{fmt(maxV * f)}
|
||||
</SvgText>
|
||||
</G>
|
||||
))}
|
||||
{data.map((d, i) => {
|
||||
const x = padL + (i + 0.5) * (iw / n) - bw / 2;
|
||||
return (
|
||||
<G key={d.day} onPress={() => setSel(i === sel ? null : i)}>
|
||||
<Rect x={x - 1} y={8} width={bw + 2} height={H - padB - 8} fill="transparent" />
|
||||
<Rect x={x} y={y(d.value)} width={bw} height={Math.max(1, H - padB - y(d.value))}
|
||||
rx={1.5} fill={color} opacity={sel == null || sel === i ? 1 : 0.35} />
|
||||
</G>
|
||||
);
|
||||
})}
|
||||
<SvgText x={padL} y={H - 3} fill={C.muted} fontSize={9.5}>{fmtD(data[0].day)}</SvgText>
|
||||
<SvgText x={W} y={H - 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
|
||||
{fmtD(data[n - 1].day)}
|
||||
</SvgText>
|
||||
</Svg>
|
||||
{selD && (
|
||||
<DetailCard title={fmtDY(selD.day)} rows={[[unit, `${num(Math.round(selD.value))}`]]} />
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/* daily line with dots (resting HR, HRV, SpO2…) — tap a point for value */
|
||||
export function DailyLine({
|
||||
data, width, unit, color = C.s3, decimals = 0,
|
||||
}: {
|
||||
data: { day: string; avg: number }[];
|
||||
width: number;
|
||||
unit: string;
|
||||
color?: string;
|
||||
decimals?: number;
|
||||
}) {
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
if (data.length < 2) return null;
|
||||
const H = 110, padL = 34, padB = 16, padT = 8, W = width;
|
||||
const iw = W - padL, n = data.length;
|
||||
const vs = data.map((d) => d.avg);
|
||||
const min = Math.min(...vs), max = Math.max(...vs);
|
||||
const span = max - min || 1;
|
||||
const x = (i: number) => padL + (i + 0.5) * (iw / n);
|
||||
const y = (v: number) => H - padB - ((v - min) / span) * (H - padB - padT);
|
||||
const path = data.map((d, i) => (i ? 'L' : 'M') + x(i).toFixed(1) + ' ' + y(d.avg).toFixed(1)).join(' ');
|
||||
const selD = sel != null ? data[sel] : null;
|
||||
return (
|
||||
<View>
|
||||
<Svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
|
||||
{[min, max].map((v) => (
|
||||
<G key={v}>
|
||||
<Line x1={padL} y1={y(v)} x2={W} y2={y(v)} stroke={C.gridline} strokeWidth={1} />
|
||||
<SvgText x={padL - 5} y={y(v) + 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
|
||||
{v.toFixed(decimals)}
|
||||
</SvgText>
|
||||
</G>
|
||||
))}
|
||||
<Path d={path} fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" opacity={0.85} />
|
||||
{data.map((d, i) => (
|
||||
<G key={d.day} onPress={() => setSel(i === sel ? null : i)}>
|
||||
<Rect x={x(i) - iw / n / 2} y={0} width={iw / n} height={H - padB} fill="transparent" />
|
||||
<Circle cx={x(i)} cy={y(d.avg)} r={sel === i ? 4.5 : 2.5} fill={color}
|
||||
stroke={C.surface} strokeWidth={1} />
|
||||
</G>
|
||||
))}
|
||||
<SvgText x={padL} y={H - 3} fill={C.muted} fontSize={9.5}>{fmtD(data[0].day)}</SvgText>
|
||||
<SvgText x={W} y={H - 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
|
||||
{fmtD(data[n - 1].day)}
|
||||
</SvgText>
|
||||
</Svg>
|
||||
{selD && (
|
||||
<DetailCard title={fmtDY(selD.day)} rows={[[unit, selD.avg.toFixed(decimals)]]} />
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/* biomarker sparkline */
|
||||
export function Sparkline({
|
||||
pts, flagged, width,
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View,
|
||||
} from 'react-native';
|
||||
import { useAuth } from '../lib/api';
|
||||
import { C } from '../lib/theme';
|
||||
|
||||
export function LoginScreen() {
|
||||
const { login } = useAuth();
|
||||
const [user, setUser] = useState('admin');
|
||||
const [pass, setPass] = useState('');
|
||||
const [err, setErr] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const go = async () => {
|
||||
setBusy(true);
|
||||
setErr('');
|
||||
try {
|
||||
const ok = await login(user.trim(), pass);
|
||||
if (!ok) setErr('Wrong password.');
|
||||
else setPass('');
|
||||
} catch {
|
||||
setErr('Network error — are you online?');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
style={s.wrap}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
|
||||
<View style={s.card}>
|
||||
<Text style={{ fontSize: 34, marginBottom: 10 }}>⚕️</Text>
|
||||
<Text style={s.h1}>Health Dashboard</Text>
|
||||
<Text style={s.sub}>health.rehbock.xyz — private</Text>
|
||||
<Text style={s.lbl}>USER</Text>
|
||||
<TextInput
|
||||
style={s.input}
|
||||
value={user}
|
||||
onChangeText={setUser}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="username"
|
||||
/>
|
||||
<Text style={s.lbl}>PASSWORD</Text>
|
||||
<TextInput
|
||||
style={s.input}
|
||||
value={pass}
|
||||
onChangeText={setPass}
|
||||
secureTextEntry
|
||||
textContentType="password"
|
||||
onSubmitEditing={go}
|
||||
returnKeyType="go"
|
||||
/>
|
||||
<Pressable style={[s.go, busy && { opacity: 0.5 }]} disabled={busy} onPress={go}>
|
||||
<Text style={{ color: '#fff', fontWeight: '600', fontSize: 15 }}>Unlock</Text>
|
||||
</Pressable>
|
||||
<Text style={s.err}>{err}</Text>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
const s = StyleSheet.create({
|
||||
wrap: {
|
||||
flex: 1, backgroundColor: C.bg, alignItems: 'center', justifyContent: 'center', padding: 24,
|
||||
},
|
||||
card: {
|
||||
width: '100%', maxWidth: 340, backgroundColor: C.surface, borderWidth: 1,
|
||||
borderColor: C.border, borderRadius: 16, paddingVertical: 28, paddingHorizontal: 24,
|
||||
},
|
||||
h1: { fontSize: 18, fontWeight: '600', color: C.text, marginBottom: 4 },
|
||||
sub: { fontSize: 12, color: C.muted, marginBottom: 20 },
|
||||
lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 12, marginBottom: 5 },
|
||||
input: {
|
||||
paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
|
||||
borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
|
||||
},
|
||||
go: {
|
||||
marginTop: 20, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center',
|
||||
},
|
||||
err: { marginTop: 12, fontSize: 12.5, color: C.red, minHeight: 18 },
|
||||
});
|
||||
107
src/lib/api.tsx
@@ -14,51 +14,41 @@ export const EP = {
|
||||
medStats: `${BASE}/api/meditation/v1/stats`,
|
||||
medSessions: `${BASE}/api/meditation/v1/sessions?limit=1000`,
|
||||
traits: `${BASE}/ancestry-traits.json`,
|
||||
fitbitSummary: `${BASE}/api/health/v1/fitbit/summary?days=30`,
|
||||
fitbitLatest: `${BASE}/api/health/v1/fitbit/latest`,
|
||||
} as const;
|
||||
|
||||
export const FITBIT_SYNC_URL = `${BASE}/api/health/v1/fitbit/sync`;
|
||||
|
||||
/* authenticated POST (fitbit sync) */
|
||||
export async function postJson<T>(url: string, body: unknown): Promise<T> {
|
||||
if (!token) throw new Error(NO_TOKEN);
|
||||
const r = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
|
||||
if (!r.ok) throw new Error(`${url} → ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export type EpKey = keyof typeof EP;
|
||||
|
||||
const AUTH_KEY = 'hd.auth';
|
||||
const AUTH_KEY = 'hd.token';
|
||||
|
||||
export const NO_TOKEN = 'No API token — add one in Settings.';
|
||||
export const BAD_TOKEN = 'API token rejected — check it in Settings.';
|
||||
|
||||
let token: string | null = null;
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
|
||||
/* base64 without Buffer/btoa dependency quirks across Hermes versions */
|
||||
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||
export function b64(str: string): string {
|
||||
const bytes: number[] = [];
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const code = str.codePointAt(i)!;
|
||||
if (code > 0xffff) i++;
|
||||
if (code < 0x80) bytes.push(code);
|
||||
else if (code < 0x800) bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
|
||||
else if (code < 0x10000)
|
||||
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
else
|
||||
bytes.push(
|
||||
0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63),
|
||||
0x80 | ((code >> 6) & 63), 0x80 | (code & 63),
|
||||
);
|
||||
}
|
||||
let out = '';
|
||||
for (let i = 0; i < bytes.length; i += 3) {
|
||||
const [a, b, c] = [bytes[i], bytes[i + 1], bytes[i + 2]];
|
||||
out += B64[a >> 2] + B64[((a & 3) << 4) | (b ?? 0) >> 4];
|
||||
out += b === undefined ? '=' : B64[((b & 15) << 2) | (c ?? 0) >> 6];
|
||||
out += c === undefined ? '=' : B64[c & 63];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function authFetch<T>(url: string): Promise<T> {
|
||||
if (!token) throw new Error(NO_TOKEN);
|
||||
const r = await fetch(url, {
|
||||
headers: { Authorization: 'Basic ' + token },
|
||||
headers: { Authorization: 'Bearer ' + token },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (r.status === 401 || r.status === 403) {
|
||||
onUnauthorized?.();
|
||||
throw new Error('unauthorized');
|
||||
}
|
||||
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
|
||||
if (!r.ok) throw new Error(`${url} → ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
@@ -79,66 +69,67 @@ export function clearCache() {
|
||||
cache = {};
|
||||
}
|
||||
|
||||
/* drop specific endpoints from the cache so the next load() refetches */
|
||||
export function invalidate(...keys: EpKey[]) {
|
||||
for (const k of keys) delete cache[k];
|
||||
}
|
||||
|
||||
/* ---- auth context ---- */
|
||||
|
||||
interface AuthCtx {
|
||||
ready: boolean;
|
||||
authed: boolean;
|
||||
login: (user: string, pass: string) => Promise<boolean>;
|
||||
logout: () => void;
|
||||
/** an API token is stored (it may still be rejected by the server) */
|
||||
hasToken: boolean;
|
||||
/** verify against the server, then store; false = server rejected it */
|
||||
saveToken: (t: string) => Promise<boolean>;
|
||||
clearToken: () => void;
|
||||
}
|
||||
|
||||
const Ctx = createContext<AuthCtx>({
|
||||
ready: false,
|
||||
authed: false,
|
||||
login: async () => false,
|
||||
logout: () => {},
|
||||
hasToken: false,
|
||||
saveToken: async () => false,
|
||||
clearToken: () => {},
|
||||
});
|
||||
|
||||
export const useAuth = () => useContext(Ctx);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [hasToken, setHasToken] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
SecureStore.getItemAsync(AUTH_KEY)
|
||||
.then((t) => {
|
||||
if (t) {
|
||||
token = t;
|
||||
setAuthed(true);
|
||||
setHasToken(true);
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
const clearToken = useCallback(() => {
|
||||
token = null;
|
||||
clearCache();
|
||||
SecureStore.deleteItemAsync(AUTH_KEY).catch(() => {});
|
||||
setAuthed(false);
|
||||
setHasToken(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
onUnauthorized = logout;
|
||||
return () => {
|
||||
onUnauthorized = null;
|
||||
};
|
||||
}, [logout]);
|
||||
|
||||
const login = useCallback(async (user: string, pass: string) => {
|
||||
const tok = b64(`${user}:${pass}`);
|
||||
const saveToken = useCallback(async (raw: string) => {
|
||||
const t = raw.trim();
|
||||
const r = await fetch(EP.meta, {
|
||||
headers: { Authorization: 'Basic ' + tok },
|
||||
headers: { Authorization: 'Bearer ' + t },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!r.ok) return false;
|
||||
token = tok;
|
||||
token = t;
|
||||
clearCache();
|
||||
await SecureStore.setItemAsync(AUTH_KEY, tok);
|
||||
setAuthed(true);
|
||||
await SecureStore.setItemAsync(AUTH_KEY, t);
|
||||
setHasToken(true);
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
return <Ctx.Provider value={{ ready, authed, login, logout }}>{children}</Ctx.Provider>;
|
||||
return <Ctx.Provider value={{ ready, hasToken, saveToken, clearToken }}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
193
src/lib/fitbit.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
/* Fitbit Air → Health Connect → health.rehbock.xyz sync.
|
||||
Android-only: react-native-health-connect is loaded lazily so the module's
|
||||
absence (iOS, Expo Go) never crashes the app. */
|
||||
import { Platform } from 'react-native';
|
||||
import { FITBIT_SYNC_URL, invalidate, load, postJson } from './api';
|
||||
|
||||
export interface SyncResult {
|
||||
ok: boolean;
|
||||
samples: number;
|
||||
daily: number;
|
||||
sleep: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface Sample { type: string; t: string; value: number }
|
||||
interface DailyRow { type: string; day: string; value: number }
|
||||
interface SleepRow {
|
||||
id: string; started_at: string; ended_at: string;
|
||||
total_seconds: number; sleep_seconds: number;
|
||||
deep_seconds: number; rem_seconds: number; light_seconds: number; awake_seconds: number;
|
||||
}
|
||||
|
||||
const READ_PERMISSIONS = [
|
||||
'HeartRate', 'RestingHeartRate', 'HeartRateVariabilityRmssd', 'OxygenSaturation',
|
||||
'SleepSession', 'Steps', 'RespiratoryRate', 'Distance',
|
||||
'ActiveCaloriesBurned', 'TotalCaloriesBurned', 'FloorsClimbed',
|
||||
] as const;
|
||||
|
||||
const FIRST_SYNC_LOOKBACK_DAYS = 60;
|
||||
const OVERLAP_MS = 6 * 3600 * 1000; // re-read a little so late-arriving records land
|
||||
|
||||
function hc() {
|
||||
// require at call time — the native module only exists in the Android build
|
||||
return require('react-native-health-connect');
|
||||
}
|
||||
|
||||
export function healthConnectSupported(): boolean {
|
||||
return Platform.OS === 'android';
|
||||
}
|
||||
|
||||
export async function healthConnectStatus(): Promise<'available' | 'needs-update' | 'unavailable' | 'unsupported'> {
|
||||
if (!healthConnectSupported()) return 'unsupported';
|
||||
try {
|
||||
const { getSdkStatus, SdkAvailabilityStatus } = hc();
|
||||
const s = await getSdkStatus();
|
||||
if (s === SdkAvailabilityStatus.SDK_AVAILABLE) return 'available';
|
||||
if (s === SdkAvailabilityStatus.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED) return 'needs-update';
|
||||
return 'unavailable';
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
async function readAll(recordType: string, startTime: string, endTime: string): Promise<any[]> {
|
||||
const { readRecords } = hc();
|
||||
const out: any[] = [];
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const res = await readRecords(recordType, {
|
||||
timeRangeFilter: { operator: 'between', startTime, endTime },
|
||||
pageSize: 1000,
|
||||
...(pageToken ? { pageToken } : {}),
|
||||
});
|
||||
out.push(...(res.records || []));
|
||||
pageToken = res.pageToken || undefined;
|
||||
} while (pageToken && out.length < 200000);
|
||||
return out;
|
||||
}
|
||||
|
||||
const localDay = (iso: string) => {
|
||||
const d = new Date(iso);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
/* HC sleep stage constants (androidx.health.connect SleepStageType) */
|
||||
const STAGE = { AWAKE: 1, SLEEPING: 2, OUT_OF_BED: 3, LIGHT: 4, DEEP: 5, REM: 6, AWAKE_IN_BED: 7 };
|
||||
|
||||
export async function syncFitbit(onProgress?: (msg: string) => void): Promise<SyncResult> {
|
||||
if (!healthConnectSupported())
|
||||
return { ok: false, samples: 0, daily: 0, sleep: 0, message: 'Health Connect is Android-only' };
|
||||
|
||||
const { initialize, requestPermission } = hc();
|
||||
const say = (m: string) => onProgress?.(m);
|
||||
|
||||
say('Initializing Health Connect…');
|
||||
const ok = await initialize();
|
||||
if (!ok) return { ok: false, samples: 0, daily: 0, sleep: 0, message: 'Health Connect init failed' };
|
||||
|
||||
say('Requesting permissions…');
|
||||
await requestPermission(READ_PERMISSIONS.map((r) => ({ accessType: 'read', recordType: r })));
|
||||
|
||||
say('Checking server watermark…');
|
||||
invalidate('fitbitLatest'); // watermark must be fresh, never the session-cached copy
|
||||
const latest = await load<{
|
||||
samples: Record<string, string | null>;
|
||||
daily: Record<string, string | null>;
|
||||
sleep: string | null;
|
||||
}>('fitbitLatest');
|
||||
|
||||
const now = new Date();
|
||||
const endTime = now.toISOString();
|
||||
const fallback = new Date(now.getTime() - FIRST_SYNC_LOOKBACK_DAYS * 86400000).toISOString();
|
||||
const sinceFor = (watermark: string | null) =>
|
||||
watermark ? new Date(new Date(watermark).getTime() - OVERLAP_MS).toISOString() : fallback;
|
||||
|
||||
const samples: Sample[] = [];
|
||||
const daily = new Map<string, DailyRow>();
|
||||
const sleep: SleepRow[] = [];
|
||||
|
||||
// continuous heart rate (records carry arrays of samples)
|
||||
say('Reading heart rate…');
|
||||
for (const rec of await readAll('HeartRate', sinceFor(latest.samples.heart_rate), endTime))
|
||||
for (const s of rec.samples || [])
|
||||
samples.push({ type: 'heart_rate', t: s.time, value: s.beatsPerMinute });
|
||||
|
||||
say('Reading vitals…');
|
||||
for (const rec of await readAll('RestingHeartRate', sinceFor(latest.samples.resting_hr), endTime))
|
||||
samples.push({ type: 'resting_hr', t: rec.time, value: rec.beatsPerMinute });
|
||||
for (const rec of await readAll('HeartRateVariabilityRmssd', sinceFor(latest.samples.hrv_rmssd), endTime))
|
||||
samples.push({ type: 'hrv_rmssd', t: rec.time, value: rec.heartRateVariabilityMillis });
|
||||
for (const rec of await readAll('OxygenSaturation', sinceFor(latest.samples.spo2), endTime))
|
||||
samples.push({ type: 'spo2', t: rec.time, value: rec.percentage });
|
||||
for (const rec of await readAll('RespiratoryRate', sinceFor(latest.samples.respiratory_rate), endTime))
|
||||
samples.push({ type: 'respiratory_rate', t: rec.time, value: rec.rate });
|
||||
|
||||
// interval records → per-local-day sums
|
||||
say('Reading activity…');
|
||||
const addDaily = (type: string, day: string, value: number) => {
|
||||
const k = `${type}|${day}`;
|
||||
const cur = daily.get(k);
|
||||
if (cur) cur.value += value;
|
||||
else daily.set(k, { type, day, value });
|
||||
};
|
||||
const dailyStart = (t: string | null) => sinceFor(t);
|
||||
for (const rec of await readAll('Steps', dailyStart(latest.daily.steps ? latest.daily.steps + 'T00:00:00Z' : null), endTime))
|
||||
addDaily('steps', localDay(rec.startTime), rec.count || 0);
|
||||
for (const rec of await readAll('Distance', dailyStart(latest.daily.distance_m ? latest.daily.distance_m + 'T00:00:00Z' : null), endTime))
|
||||
addDaily('distance_m', localDay(rec.startTime), rec.distance?.inMeters ?? 0);
|
||||
for (const rec of await readAll('ActiveCaloriesBurned', dailyStart(latest.daily.active_kcal ? latest.daily.active_kcal + 'T00:00:00Z' : null), endTime))
|
||||
addDaily('active_kcal', localDay(rec.startTime), rec.energy?.inKilocalories ?? 0);
|
||||
for (const rec of await readAll('TotalCaloriesBurned', dailyStart(latest.daily.total_kcal ? latest.daily.total_kcal + 'T00:00:00Z' : null), endTime))
|
||||
addDaily('total_kcal', localDay(rec.startTime), rec.energy?.inKilocalories ?? 0);
|
||||
for (const rec of await readAll('FloorsClimbed', dailyStart(latest.daily.floors ? latest.daily.floors + 'T00:00:00Z' : null), endTime))
|
||||
addDaily('floors', localDay(rec.startTime), rec.floors || 0);
|
||||
|
||||
say('Reading sleep…');
|
||||
for (const rec of await readAll('SleepSession', sinceFor(latest.sleep), endTime)) {
|
||||
const startMs = new Date(rec.startTime).getTime();
|
||||
const endMs = new Date(rec.endTime).getTime();
|
||||
let deep = 0, rem = 0, light = 0, awake = 0, asleep = 0;
|
||||
for (const st of rec.stages || []) {
|
||||
const sec = (new Date(st.endTime).getTime() - new Date(st.startTime).getTime()) / 1000;
|
||||
if (st.stage === STAGE.DEEP) deep += sec;
|
||||
else if (st.stage === STAGE.REM) rem += sec;
|
||||
else if (st.stage === STAGE.LIGHT || st.stage === STAGE.SLEEPING) light += sec;
|
||||
else if (st.stage === STAGE.AWAKE || st.stage === STAGE.AWAKE_IN_BED || st.stage === STAGE.OUT_OF_BED) awake += sec;
|
||||
}
|
||||
asleep = deep + rem + light;
|
||||
const total = (endMs - startMs) / 1000;
|
||||
if (asleep === 0) asleep = Math.max(0, total - awake); // unstaged session
|
||||
sleep.push({
|
||||
id: rec.metadata?.id || `${rec.startTime}-${rec.endTime}`,
|
||||
started_at: rec.startTime, ended_at: rec.endTime,
|
||||
total_seconds: Math.round(total), sleep_seconds: Math.round(asleep),
|
||||
deep_seconds: Math.round(deep), rem_seconds: Math.round(rem),
|
||||
light_seconds: Math.round(light), awake_seconds: Math.round(awake),
|
||||
});
|
||||
}
|
||||
|
||||
say('Uploading…');
|
||||
let ns = 0, nd = 0, nl = 0;
|
||||
const dailyRows = [...daily.values()];
|
||||
const CHUNK = 4000;
|
||||
for (let i = 0; i < Math.max(1, Math.ceil(samples.length / CHUNK)); i++) {
|
||||
const chunk = samples.slice(i * CHUNK, (i + 1) * CHUNK);
|
||||
const body = {
|
||||
samples: chunk,
|
||||
daily: i === 0 ? dailyRows : [],
|
||||
sleep: i === 0 ? sleep : [],
|
||||
};
|
||||
if (!chunk.length && i > 0) break;
|
||||
const res = await postJson<{ samples: number; daily: number; sleep: number }>(FITBIT_SYNC_URL, body);
|
||||
ns += res.samples; nd += res.daily; nl += res.sleep;
|
||||
}
|
||||
|
||||
// new rows exist server-side — cached copies of these are now stale
|
||||
invalidate('fitbitSummary', 'fitbitLatest');
|
||||
|
||||
return {
|
||||
ok: true, samples: ns, daily: nd, sleep: nl,
|
||||
message: `Synced ${ns} samples, ${nd} daily rows, ${nl} sleep sessions`,
|
||||
};
|
||||
}
|
||||
@@ -3,7 +3,17 @@ import type {
|
||||
Week, Workout,
|
||||
} from './types';
|
||||
|
||||
export function shapeSleep(api: SleepApiResponse, sc: SleepCycleExport): Night[] {
|
||||
export interface HcSleepRow {
|
||||
id: string; started_at: string; ended_at: string;
|
||||
total_seconds: number; sleep_seconds: number;
|
||||
deep_seconds: number; rem_seconds: number; light_seconds: number; awake_seconds: number;
|
||||
}
|
||||
|
||||
export function shapeSleep(
|
||||
api: SleepApiResponse,
|
||||
sc: SleepCycleExport,
|
||||
fitbit: HcSleepRow[] = [],
|
||||
): Night[] {
|
||||
const byDate = new Map<string, Night>();
|
||||
(sc.sessions || []).forEach((r) => {
|
||||
const o: Record<string, any> = Object.fromEntries(sc.fields.map((f, i) => [f, r[i]]));
|
||||
@@ -39,6 +49,23 @@ export function shapeSleep(api: SleepApiResponse, sc: SleepCycleExport): Night[]
|
||||
src: 'Eight Sleep',
|
||||
});
|
||||
});
|
||||
// Fitbit Air wins where sources overlap — it's the current device.
|
||||
fitbit.forEach((f) => {
|
||||
const date = f.ended_at.slice(0, 10);
|
||||
byDate.set(date, {
|
||||
date,
|
||||
total: f.total_seconds,
|
||||
asleep: f.sleep_seconds,
|
||||
deep: f.deep_seconds,
|
||||
rem: f.rem_seconds,
|
||||
light: f.light_seconds,
|
||||
awake: f.awake_seconds,
|
||||
quality: null,
|
||||
hrv: null,
|
||||
hr: null,
|
||||
src: 'Fitbit Air',
|
||||
});
|
||||
});
|
||||
return [...byDate.values()].sort((a, b) => (a.date < b.date ? -1 : 1));
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +19,7 @@ export function useLoad<T>(fn: () => Promise<T>): LoadState<T> & { refresh: () =
|
||||
.then((data) => live && setState({ data, loading: false }))
|
||||
.catch((e) => {
|
||||
if (!live) return;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (msg !== 'unauthorized') setState({ err: msg, loading: false });
|
||||
setState({ err: e instanceof Error ? e.message : String(e), loading: false });
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
|
||||