diff --git a/HANDOFF.md b/HANDOFF.md index 32796f9..30dac15 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -26,6 +26,7 @@ It started on 2026-10-13 as "WinterMiles" (an icTrainer alternative for riding G | **Herne Hill Velodrome** | Built-in track. The route is in `crates/core/src/velodrome.rs`; the banked track, its paint and the buildings are in `world/venue.rs`. Tested in code, and I've checked a live preview in demo mode on both renderers, each way round (`VP_SMOKE_ROUTE=herne-hill` or `herne-hill-clockwise`). Nobody has ridden it with a trainer yet. | | **Laps on loop routes** | Lap engine, bests, segments and renderers unit-tested in `crates/core`; smoke-run across the line on Linux with three.js, not yet with the native renderer (macOS). Group standings don't show who is a lap up. | | **Strava** (OAuth, upload, segments, activities as ghosts) | Never run against the live API. Users must create their own API key (open source can't ship a secret). Scope is `read,activity:read_all,activity:write`. | +| **Dreeve** (API key, upload, rides as ghosts, rides imported as routes) | Request shapes and error mapping are tested against an in-process fake server (`connectors/dreeve.rs` tests). Connecting, listing rides, fetching a track and finding the rides that fit a route were run against a real Dreeve v5.8.2 with about 190 rides on 2026-11-10 (`live_dreeve_lists_rides_and_tracks`, ignored by default, takes `DREEVE_URL`, `DREEVE_API_KEY` and optionally `DREEVE_ROUTE_RIDE`). The upload was tested by hand against a real instance. | | **Windows and Linux** | Built and packaged by CI on every push (and Arch's package is installed in a container and its libraries checked), but **never run by a person**. | | **Native renderer** (macOS, opt-in) | wgpu/Metal in an NSView under a transparent webview. Matches three.js in screenshots; HUD-over-native never checked in a real window; no clean release-build performance comparison. | | **Dense woods and tree sprites** | Checked in both renderers with the smoke harness, and their cost measured only on Apple silicon (about 0.6 M triangles a frame on a wooded climb). Not tried on weaker graphics (Windows/Linux integrated GPUs). | @@ -65,7 +66,8 @@ src-tauri/ The app (Tauri 2) diag.rs Diagnostics log + reports; issues.rs: GitHub new-issue links; snapshot.rs: window PNGs (macOS) connectors/ Services a ride is uploaded to, and whose past rides can be raced as ghosts: mod.rs (Connector trait, registry, descriptor types the settings card is built from), - strava.rs (OAuth, upload, recent rides, segments). + strava.rs (OAuth, upload, recent rides, segments), + dreeve.rs (API key, upload, recent rides, ride GPX for route import; a self-hosted Dreeve). docs/ADDING_A_CONNECTOR.md explains adding one. geo, photos, smart, group, library, terrain, secrets, store web/ React + three.js (Vite). ui/ screens, world/ the 3D scene (scene.ts, terrain.ts, trees.ts (tree models, sprite atlas), rider.ts, @@ -159,7 +161,7 @@ CI also builds every push to `main`; installers can be downloaded from the run's - **Laps are `distance` on the loop plus `ridden` for totals.** `RideEngine` keeps `distance` as the position on the loop, in `[0, route.total]`, and adds `lap` (from 1) and `ridden` (metres across all laps). Everything meaning "where on the road" uses `distance`; everything meaning "how far ridden" (FIT, summary, progress, goal) uses `ridden`. Without laps `ridden == distance`, so ordinary rides are unchanged by construction. The choice is only accepted when the route is a loop (`Route.closed`, offered to the page by `route_is_loop`) and is kept on the ride as `laps`. Agreed with the maintainer (#67): ghosts off on lap rides, climbs and segments timed on each lap and kept fastest, and a lap ride never sets the route's best time. - **Commits are under the maintainer's name only.** -- **Connectors are a trait plus a registry** (`src-tauri/src/connectors/`), not a Strava module with ifs, because Dreeve (self-hosted, API key, no activity page) is the next target and differs from Strava in how it links, what an upload returns and what else it offers. The page draws each service's settings card from the connector's own description, so a new service is one Rust file. Listing past rides (for ghosts) and finding segments along a route are optional parts of the trait whose defaults say the service can't, because services offer different subsets: Strava has both, Dreeve's public API has rides but no segments. `SegmentSource::Strava` became `Remote` plus a `connector` field on the segment; stored segments that still say "strava" are read as Remote from Strava. +- **Connectors are a trait plus a registry** (`src-tauri/src/connectors/`), not a Strava module with ifs, because Dreeve (self-hosted, API key, no activity page) differs from Strava in how it links, what an upload returns and what else it offers. The page draws each service's settings card from the connector's own description, so a new service is one Rust file. Listing past rides (for ghosts) and finding segments along a route are optional parts of the trait whose defaults say the service can't, because services offer different subsets: Strava has both, Dreeve's public API has rides but no segments. Two more optional parts both end in a GPX file but start from different things: `lists_routes` (`saved_routes`, `route_gpx`) lists routes the rider *planned or starred* and feeds Find a route (Strava); `imports_routes` (`ride_gpx`) turns a ride the rider *has ridden* into a route from the routes page (Dreeve). Dreeve has no saved routes, so it doesn't set `lists_routes`. `SegmentSource::Strava` became `Remote` plus a `connector` field on the segment; stored segments that still say "strava" are read as Remote from Strava. ## 10. Known traps diff --git a/README.md b/README.md index 5b539c9..8c14082 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,11 @@ Free and open source ([GPLv3](LICENSE)) for **Windows, macOS and Linux**. Writte - **Fitness tracking.** Power curve (5 s to 1 h), an FTP estimate you can apply in one click, power zones on the HUD, and a training-load chart of fitness, fatigue and form. - **Sensors.** Power meters, heart-rate straps, speed and cadence sensors over Bluetooth and ANT+. When several devices report the same metric the most direct one wins (crank power meter over trainer estimate, strap over relayed HR). Basic trainers with only a speed sensor can use estimated power. - **Handlebar controllers.** Buttons that speak [OpenBikeControl](https://openbikecontrol.org), an open protocol, shift virtual gears, change the ERG target or workout intensity, skip a workout step, pause and switch camera without letting go of the bars. See [Handlebar controllers](#handlebar-controllers-openbikecontrol). -- **Gamification.** Race the ghost of your best time on each route, chase pace riders at fixed W/kg, and get timed on every auto-detected climb (categorised 4 → HC) and on the Strava segments along the route, with a live "ahead of / behind your best" gap. Race other people's rides as ghosts (GPX, FIT or from your Strava). A season goal (1,000 km by spring by default), week and day streaks, XP, levels and 23 badges. +- **Gamification.** Race the ghost of your best time on each route, chase pace riders at fixed W/kg, and get timed on every auto-detected climb (categorised 4 → HC) and on the Strava segments along the route, with a live "ahead of / behind your best" gap. Race other people's rides as ghosts (GPX, FIT, or from your Strava or Dreeve). A season goal (1,000 km by spring by default), week and day streaks, XP, levels and 23 badges. - **Group rides.** Ride a route together with friends: share a room code, everyone's rider appears in everyone's world. Goes through a tiny relay server anyone can run (`crates/relay`). - **Living world.** Village and town signs, summit boards named after the place at the top, and roadside cafés, fountains, bike shops and viewpoints from OpenStreetMap. Dawn, day, evening, dusk or night (with a lamp on the bike), and clear, cloudy, rain, fog or snow — or the weather at the real place right now. Optional street-level photos of the road from Mapillary (bring your own free token). - **Fan and lights.** A fan that speeds up with your speed, power or heart rate, and a light coloured by power zone, through Home Assistant, a Shelly or Tasmota plug, or any webhook. -- **Recording and sharing.** Every ride is saved as a standard `.FIT` file (GPS, power, heart rate, cadence, laps, normalised power) and can be uploaded to Strava as a Virtual Ride in one click or automatically. Set a second folder under **Settings → Ride files** (iCloud Drive or Dropbox, say) and each ride is copied there too. +- **Recording and sharing.** Every ride is saved as a standard `.FIT` file (GPS, power, heart rate, cadence, laps, normalised power) and can be uploaded in one click or automatically: to Strava as a Virtual Ride, or to your own [Dreeve](https://github.com/dreeveapp/dreeve) server. Set a second folder under **Settings → Ride files** (iCloud Drive or Dropbox, say) and each ride is copied there too. - **Demo rider.** A simulated rider and trainer so you can try everything with no hardware. ### On the road diff --git a/docs/ADDING_A_CONNECTOR.md b/docs/ADDING_A_CONNECTOR.md index 19deb41..98f70d9 100644 --- a/docs/ADDING_A_CONNECTOR.md +++ b/docs/ADDING_A_CONNECTOR.md @@ -1,7 +1,7 @@ # Adding a connector -A *connector* is a service a finished ride can be sent to. Strava is one; Dreeve -is next. Each is one Rust file in `src-tauri/src/connectors/`, registered in one +A *connector* is a service a finished ride can be sent to. Strava (OAuth) and +Dreeve (API key) are the two there are. Each is one Rust file in `src-tauri/src/connectors/`, registered in one place. The page (settings card, upload buttons, auto-upload toggle, the record of where a ride went) is generic and needs no change for a new service. @@ -11,10 +11,12 @@ where a ride went) is generic and needs no change for a new service. |---|---| | `src-tauri/src/connectors/mod.rs` | The `Connector` trait, the descriptor types the page draws from, the `ALL` registry, `Ctx` (credential storage + HTTP client) | | `src-tauri/src/connectors/.rs` | One file per service: a unit struct implementing `Connector` | -| `src-tauri/src/commands.rs`, *Connectors* section | Generic commands routed by connector id: `connectors_list`, `connector_status`, `connector_configure`, `connector_connect`, `connector_disconnect`, `connector_upload`, `connector_rides`, `ghost_import_connector`, `segments_fetch` | +| `src-tauri/src/commands.rs`, *Connectors* section | Generic commands routed by connector id: `connectors_list`, `connector_status`, `connector_configure`, `connector_connect`, `connector_disconnect`, `connector_upload`, `connector_rides`, `ghost_import_connector`, `segments_fetch`; for the optional route features `connector_routes`, `connector_route` (saved routes) and `connector_ride_list`, `route_import_connector` (ride as route) | | `crates/core/src/types.rs` | `UploadRecord` (what a connector returns, kept per ride under `RideSummary.uploads[id]`), `Settings.auto_upload` (ids to send every ride to) | | `web/src/ui/Settings.tsx` `ConnectorCard` | Builds the card from `ConnectorInfo`: setup steps, one input per field, connect/disconnect, the auto-upload toggle | | `web/src/ui/Summary.tsx` `UploadButtons` | One button per connected connector on the summary and history screens | +| `web/src/ui/Explore.tsx` | "Your routes" in Find a route, for connectors with `lists_routes` | +| `web/src/ui/Home.tsx`, `web/src/ui/RemoteImport.tsx` | "Import from …" on the routes page and its dialog, for connectors with `imports_routes` | | `web/src/ui/RideSetup.tsx` | "From …" ghost import and "Find segments" for every connected connector that offers them | ## Steps @@ -100,6 +102,7 @@ where a ride went) is generic and needs no change for a new service. } ``` + `dreeve.rs` is this shape, with tests against a fake HTTP server to copy. `AuthKind::OAuth` connectors (see `strava.rs`) get `open_browser` to show the consent page and listen on a loopback port for the redirect. The page shows "Connect to X" / "Waiting for X in your browser…" for OAuth and "Save and @@ -115,7 +118,9 @@ where a ride went) is generic and needs no change for a new service. That is the only place the app enumerates connectors. 3. **Optional CSS.** Upload buttons get the classes `upload `; add a - `button.` rule in `web/src/styles.css` for a branded colour (Strava has one). + `button.` rule in `web/src/styles.css` for a branded colour: define + `--` next to `--strava` and `--dreeve` in `:root` and use it for the + background and border (Strava and Dreeve have one each). ## Rules of the road @@ -143,7 +148,23 @@ where a ride went) is generic and needs no change for a new service. the listing's summary polyline: `connectors::find_rides` uses it to mark the rides that ride the chosen route from its start, and pages back until a few do (at most five pages). The ride setup then shows "From …" with the - fitting rides first. The defaults say the service can't list rides. + fitting rides first. The defaults say the service can't list rides. Set each + ride's `sport` to the service's sport type in Strava's vocabulary ("Ride", + "GravelRide", …) so the rider can filter by bike. +- **Saved routes are optional.** Override `lists_routes` to return `true` and + implement `saved_routes` (the routes the rider planned or starred, starred + first) and `route_gpx` (one of them as GPX, by the id `saved_routes` gave; + keep ids as text). Find a route then shows "Your routes". Strava does + this; a service that only holds finished rides does not. +- **Importing a ride as a route is optional** and builds on listing rides. + Override `imports_routes` to return `true` and implement `ride_gpx`, which + returns one ride as GPX text with elevation. The routes page then shows + "Import from …": a dialog listing every ride (`connectors::list_rides`, + up to twenty pages) with search, a bike filter and a distance range. + Don't confuse the two: `lists_routes` offers routes the rider *planned* + (Find a route); `imports_routes` turns a ride the rider *has ridden* into a + route (the routes page). Both end in a GPX file in the library. Dreeve sets + only `imports_routes`, Strava only `lists_routes`. - **Finding segments is optional too.** Override `finds_segments` to return `true` and implement `segments_near`, which gets `[south, west, north, east]` boxes along the route and returns each segment's shape as `(lat, lon)` points diff --git a/docs/wiki/Architecture.md b/docs/wiki/Architecture.md index 45aa035..1e30cab 100644 --- a/docs/wiki/Architecture.md +++ b/docs/wiki/Architecture.md @@ -25,7 +25,7 @@ src-tauri/ The app (Tauri 2) mapdata Downloading and caching map data (vector tiles, Overpass) diag The diagnostics log and reports group, smart Group-ride client; fan and light control - connectors/ Services rides upload to (one file per service, Strava today) + connectors/ Services rides upload to (one file per service: Strava, Dreeve) geo place search and route planning web/ React screens and the three.js world ``` @@ -35,7 +35,7 @@ web/ React screens and the three.js world 1. **Start:** the route is built (resampled every few metres, smoothed, climbs found). Map data for the route is loaded from the cache or downloaded: vector tiles for scenery, Overpass for building detail and the route's road tags (surface, width, lanes, trail grades). The `World` combines it: a height field pinned to the road, the scene (forests, water, other roads), structures, the route road and barriers. 2. **Loop (50 Hz, Rust):** sensor readings are merged (most direct source wins), the physics advances the rider, rivals and ghosts move, and once a second the trainer gets a command (gradient or ERG target) and the diagnostics log gets a line. State goes to the page 20 times a second. 3. **Drawing:** the page asks for meshes in compact binary form (terrain chunks streamed around the rider with their trees, the road ribbon, structures, barriers, the tree models) and draws them with three.js; trees beyond about 200 m become camera-facing sprites rendered from the same models — or the native renderer draws the same meshes with Metal beneath a transparent page that shows only the HUD. -4. **End:** the ride is saved as FIT, personal bests, XP and badges are updated, and it can be uploaded to any connected service (Strava today). +4. **End:** the ride is saved as FIT, personal bests, XP and badges are updated, and it can be uploaded to any connected service (Strava, Dreeve). ## Design choices diff --git a/docs/wiki/Dreeve.md b/docs/wiki/Dreeve.md new file mode 100644 index 0000000..44c6c82 --- /dev/null +++ b/docs/wiki/Dreeve.md @@ -0,0 +1,19 @@ +# Dreeve + +[Dreeve](https://github.com/dreeveapp/dreeve) (formerly *Statistics for Strava*) is a self-hosted dashboard for your sports data. VeloPopuli can send every ride's `.FIT` file straight to your own instance. + +1. In Dreeve's admin panel open **Settings → Security → API access** and generate a key (it looks like `drv_…`). +2. Set it as `DREEVE_API_KEY` in Dreeve's `.env` and recreate the containers. Dreeve must run with `IMPORT_MODE=files`. +3. In VeloPopuli → **Settings → Dreeve**, enter your instance's address and the key and press **Save and test**. The test tells you if the key is wrong or uploads are switched off. + + The address must start with `https://`: VeloPopuli refuses plain `http://` so your key isn't sent unencrypted. Only `localhost` and `127.0.0.1` are allowed without it. If your Dreeve runs on your home network over plain http, put a reverse proxy with a certificate in front of it. + +Then: + +- Rides upload with one click on the summary or history screen, or automatically (toggle on the Dreeve card). +- Dreeve queues the file and imports it within a few minutes; the button shows what the server said. There is no page to open, so look in Dreeve's activity list. +- Dreeve reads everything from the FIT file (power, heart rate, cadence, the route), so nothing else is sent. +- **Your Dreeve rides** with a GPS track can be raced as ghosts: *From Dreeve…* when setting up a ride. +- **Ride one of them again** as a route: *Import from Dreeve…* on the routes page lists your rides, searchable by name or date and filtered by bike and distance. This needs Dreeve 5.4 or later, which exports a ride as GPX. + +The key is kept in the system keychain (macOS, Windows) or a file only you can read (Linux). diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 1a735a1..5f6b7c5 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -20,6 +20,7 @@ VeloPopuli turns any GPX route into a 3D world built from OpenStreetMap and open - [[Virtual gears]] — shift with keys or a remote instead of your bike's gears (optional) - [[Progress and goals]] — power curve, FTP, training load, streaks, badges and the season goal - [[Strava]] — connect, upload, segments and friends' rides as ghosts +- [[Dreeve]] — upload rides to your own Dreeve server - [[Group rides and self-hosting]] — ride together; run your own relay - [[Fan and lights]] — Home Assistant, Shelly, Tasmota and webhooks diff --git a/docs/wiki/Riding.md b/docs/wiki/Riding.md index e939fd9..968fd1d 100644 --- a/docs/wiki/Riding.md +++ b/docs/wiki/Riding.md @@ -34,7 +34,7 @@ Not yet: laps in the FIT file, ending the ride on the workout instead of the lap - **Pace riders** hold a steady W/kg to chase or drop (set them in Settings). - **Your ghost** — your best ride on the route. -- **Other people's rides** as ghosts — from a GPX or FIT file, or from your Strava. +- **Other people's rides** as ghosts — from a GPX or FIT file, or from your Strava or Dreeve. - **Climbs** are detected and categorised (4 → HC) and timed; **Strava segments** along the route are timed too. ## Time of day and weather diff --git a/docs/wiki/Routes-and-the-map.md b/docs/wiki/Routes-and-the-map.md index 1e70a4a..7b60905 100644 --- a/docs/wiki/Routes-and-the-map.md +++ b/docs/wiki/Routes-and-the-map.md @@ -6,6 +6,8 @@ - **Import GPX** from anywhere. Routes without elevation (planner exports) get it filled in from open terrain data. - **Find a route** — search for a place, click waypoints and get a route along bike-friendly roads with real elevation (via [BRouter](https://brouter.de)), or pick one of the famous climbs (Alpe d'Huez, Mont Ventoux, Stelvio, Galibier, Tourmalet, Mortirolo, Zoncolan, Box Hill). **Prefer: Mountain bike (trails)** plans along tracks and singletrack instead of roads. +- **Your Strava routes** — with [[Strava]] connected, **Find a route** lists the routes you made or starred on Strava, starred first. Pick one to preview it and save it to your library. Strava asks for extra permission to read private routes: if you linked before this existed, only public routes are listed and the page asks you to connect again. +- **Import from Dreeve…** — with [[Dreeve]] connected, the routes page lists your finished rides there (search by name or date, filter by bike and distance, needs Dreeve 5.4 or later). Pick one to ride it again as a route. This is not the same as the Strava item above: that lists routes you planned, this turns a ride you already did into a route. - **Mountain-bike routes** — on **Find a route**, move the map to an area and press **Find MTB routes here** to list the waymarked mountain-bike routes mapped there (OpenStreetMap `route=mtb`), longest first. Pick one to see it on the map with its distance, climbing and elevation profile, then save it. Its mapped pieces are joined end to end; if some don't meet, you're told how many gaps there are, and you ride straight across them. The area can be up to about 60 km across. ![Route finder](https://raw.githubusercontent.com/pepperstm/velopopuli/main/docs/images/screen-explore.jpg) diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index f145d67..edfa633 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -12,6 +12,7 @@ - [[Virtual gears]] - [[Progress and goals]] - [[Strava]] +- [[Dreeve]] - [[Group rides and self-hosting]] - [[Fan and lights]] diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 28311ba..86d534f 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -521,6 +521,8 @@ pub struct ConnectorEntry { finds_segments: bool, /// Find a route can list the rider's saved routes on this service. lists_routes: bool, + /// The routes page can import one of the rider's rides on this service as a route. + imports_routes: bool, } /// Every connector with its description and current state, for the settings and upload UI. @@ -529,10 +531,32 @@ pub fn connectors_list(state: State) -> Vec { let ctx = state.connector_ctx(); connectors::ALL .iter() - .map(|c| ConnectorEntry { info: c.info(), status: c.status(&ctx), lists_rides: c.lists_rides(), finds_segments: c.finds_segments(), lists_routes: c.lists_routes() }) + .map(|c| ConnectorEntry { + info: c.info(), + status: c.status(&ctx), + lists_rides: c.lists_rides(), + finds_segments: c.finds_segments(), + lists_routes: c.lists_routes(), + imports_routes: c.imports_routes(), + }) .collect() } +/// Every ride the rider has on a connector, for picking one to import as a route. +#[tauri::command] +pub async fn connector_ride_list(state: State<'_, AppState>, id: String) -> Res { + let ctx = state.connector_ctx(); + connectors::list_rides(connectors::get(&id)?, &ctx).await +} + +/// Imports one of the rider's rides on a connector as a route; `name` is used when the GPX has none. +#[tauri::command] +pub async fn route_import_connector(state: State<'_, AppState>, id: String, ride_id: String, name: String) -> Res { + let ctx = state.connector_ctx(); + let gpx = connectors::get(&id)?.ride_gpx(&ctx, &ride_id).await?; + import_gpx(&state, &name, &gpx) +} + /// The rider's rides on a connector, each marked whether it follows the route, for racing one /// as a ghost. Pages back through older rides until a few follow the route. #[tauri::command] diff --git a/src-tauri/src/connectors/dreeve.rs b/src-tauri/src/connectors/dreeve.rs new file mode 100644 index 0000000..b863934 --- /dev/null +++ b/src-tauri/src/connectors/dreeve.rs @@ -0,0 +1,555 @@ +//! Dreeve (formerly "Statistics for Strava"), a self-hosted sports dashboard: +//! https://github.com/dreeveapp/dreeve +//! +//! API: bearer token `drv_<64 hex>` (generated in the admin panel and set as +//! `DREEVE_API_KEY` on the server), `GET /api/v1/status` to verify the URL and key, +//! `POST /api/v1/activity/upload` with a multipart `file` part. Uploads are queued +//! and answered with `202 Accepted`; the server imports them within minutes, so +//! there is no activity page to link to. `GET /api/v1/activities` lists rides and +//! `GET /api/v1/activities/{id}/streams` gives a ride's GPS track for racing it as a ghost. + +use std::collections::BTreeMap; +use std::time::Duration; + +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; +use velopopuli_core::types::UploadRecord; + +use super::{field, AuthKind, ConfigField, Connector, ConnectorInfo, ConnectorStatus, Ctx, FieldKind, OpenBrowser, RemoteRide, RidePage, RideTrack, SetupStep, UploadRequest}; +use crate::now_ms; +use velopopuli_core::segments::decode_polyline; + +pub const ID: &str = "dreeve"; +const STATUS_PATH: &str = "/api/v1/status"; +const UPLOAD_PATH: &str = "/api/v1/activity/upload"; +const ACTIVITIES_PATH: &str = "/api/v1/activities"; +/// Dreeve's cycling sport types (Strava's vocabulary); the others are runs, swims, gym sessions. +const RIDE_TYPES: &[&str] = &["Ride", "MountainBikeRide", "GravelRide", "EBikeRide", "EMountainBikeRide", "VirtualRide", "Velomobile", "Handcycle"]; + +pub struct Dreeve; + +#[derive(Default, Serialize, Deserialize)] +struct Creds { + url: String, + api_key: String, + /// The status call succeeded with these credentials. + #[serde(default)] + verified: bool, + /// "Dreeve 1.2.3", from the status call. + #[serde(default)] + server: String, +} + +fn load(ctx: &Ctx) -> Creds { + ctx.load_creds(ID) +} + +fn to_status(c: &Creds) -> ConnectorStatus { + ConnectorStatus { id: ID, configured: !c.url.is_empty() && !c.api_key.is_empty(), connected: c.verified, account: c.server.clone(), fields: BTreeMap::from([("url", c.url.clone())]) } +} + +/// The instance URL without a trailing slash, or why it can't be used. +fn normalise_url(url: &str) -> Result { + if url.trim().is_empty() { + return Err("Enter your Dreeve URL.".into()); + } + // https only (this machine excepted), so the API key isn't sent unencrypted. + super::secure_server_url(url).map_err(|e| e.replace("server address", "Dreeve URL")) +} + +/// A Dreeve API key is "drv_" followed by 64 hex characters. +fn key_ok(key: &str) -> bool { + key.len() == 68 && key.starts_with("drv_") && key[4..].bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Turns an error reply into a sentence: the server's own message when it sends one. +fn error_message(status: u16, json: &serde_json::Value) -> String { + if let Some(message) = json["message"].as_str() { + return match json["error"].as_str() { + Some(code) => format!("{message} ({code}, HTTP {status})"), + None => format!("{message} (HTTP {status})"), + }; + } + match status { + 401 | 403 => format!("Dreeve refused the API key (HTTP {status}). Check the key and that DREEVE_API_KEY is set on the server."), + 404 => format!("Nothing at that address (HTTP {status}). Check the Dreeve URL."), + 409 => format!("Dreeve is not accepting uploads (HTTP {status}). It must run with IMPORT_MODE=files."), + 413 => format!("The file is too large for the server (HTTP {status})."), + _ => format!("Unexpected reply from Dreeve (HTTP {status})."), + } +} + +fn reach_error(e: reqwest::Error) -> String { + if e.is_timeout() { + "Dreeve did not respond in time.".into() + } else { + format!("Could not reach Dreeve: {e}") + } +} + +/// A GET against the instance with the saved key; errors become sentences. +async fn get_json(ctx: &Ctx, creds: &Creds, path_and_query: &str) -> Result { + if !creds.verified { + return Err("Not connected to Dreeve.".into()); + } + let res = ctx.http.get(format!("{}{path_and_query}", creds.url)).bearer_auth(&creds.api_key).timeout(Duration::from_secs(15)).send().await.map_err(reach_error)?; + let status = res.status().as_u16(); + let json: serde_json::Value = res.json().await.unwrap_or_default(); + if status != 200 { + return Err(error_message(status, &json)); + } + Ok(json) +} + +/// Activity ids go into the URL path; only letters, digits, `-` and `_` are let through. +fn check_id(id: &str) -> Result<(), String> { + if id.is_empty() || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') { + return Err("Not a Dreeve activity id.".into()); + } + Ok(()) +} + +#[async_trait] +impl Connector for Dreeve { + fn info(&self) -> ConnectorInfo { + ConnectorInfo { + id: ID, + name: "Dreeve", + description: "Rides are queued on your own Dreeve server and imported within a few minutes.", + auth: AuthKind::Token, + fields: vec![ + ConfigField { key: "url", label: "Dreeve URL", hint: "https://dreeve.example.com", kind: FieldKind::Url }, + ConfigField { key: "apiKey", label: "API key", hint: "drv_…", kind: FieldKind::Secret }, + ], + setup: vec![ + SetupStep { text: "In Dreeve's admin panel open Settings → Security → API access and generate a key.", link: None }, + SetupStep { text: "Set it as DREEVE_API_KEY in Dreeve's .env and recreate the containers. Dreeve must run with IMPORT_MODE=files.", link: None }, + SetupStep { text: "Enter your instance's address and the key below, then save and test.", link: None }, + ], + } + } + + fn status(&self, ctx: &Ctx) -> ConnectorStatus { + to_status(&load(ctx)) + } + + fn configure(&self, ctx: &Ctx, fields: &BTreeMap) -> Result { + let prev = load(ctx); + let url = normalise_url(&field(fields, "url"))?; + let typed = field(fields, "apiKey"); + let api_key = if typed.is_empty() { prev.api_key } else { typed }; + if api_key.is_empty() { + return Err("Enter your Dreeve API key.".into()); + } + if !key_ok(&api_key) { + return Err("A Dreeve API key is \"drv_\" followed by 64 hex characters.".into()); + } + // New credentials are unverified until `connect` checks them. + let next = Creds { url, api_key, ..Default::default() }; + ctx.save_creds(ID, &next)?; + Ok(to_status(&next)) + } + + async fn connect(&self, ctx: &Ctx, _open_browser: OpenBrowser) -> Result { + let mut creds = load(ctx); + if creds.url.is_empty() || creds.api_key.is_empty() { + return Err("Enter your Dreeve URL and API key first.".into()); + } + let res = ctx.http.get(format!("{}{STATUS_PATH}", creds.url)).bearer_auth(&creds.api_key).timeout(Duration::from_secs(15)).send().await.map_err(reach_error)?; + let status = res.status().as_u16(); + let json: serde_json::Value = res.json().await.unwrap_or_default(); + if status != 200 { + return Err(error_message(status, &json)); + } + if json["app"].as_str() != Some("dreeve") { + return Err("That address answered, but not like a Dreeve instance.".into()); + } + let version = json["version"].as_str().unwrap_or("unknown version"); + if json["canUpload"].as_bool() != Some(true) { + return Err(format!("Connected to Dreeve {version}, but uploads are disabled: it must run with IMPORT_MODE=files.")); + } + creds.verified = true; + creds.server = format!("Dreeve {version}"); + ctx.save_creds(ID, &creds)?; + Ok(to_status(&creds)) + } + + async fn disconnect(&self, ctx: &Ctx) -> Result { + // Keep the URL and key so connecting again is one click. + let next = Creds { verified: false, server: String::new(), ..load(ctx) }; + ctx.save_creds(ID, &next)?; + Ok(to_status(&next)) + } + + async fn upload(&self, ctx: &Ctx, req: &UploadRequest) -> Result { + let creds = load(ctx); + if !creds.verified { + return Err("Not connected to Dreeve.".into()); + } + // Dreeve reads everything from the FIT file; the title and description have nowhere to go. + let file_name = req.file.file_name().and_then(|n| n.to_str()).unwrap_or("ride.fit").to_string(); + let bytes = tokio::task::spawn_blocking({ + let file = req.file.clone(); + move || std::fs::read(file) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| format!("Could not read the ride file: {e}"))?; + let form = reqwest::multipart::Form::new().part("file", reqwest::multipart::Part::bytes(bytes).file_name(file_name)); + let res = ctx.http.post(format!("{}{UPLOAD_PATH}", creds.url)).bearer_auth(&creds.api_key).multipart(form).timeout(Duration::from_secs(120)).send().await.map_err(reach_error)?; + let status = res.status().as_u16(); + let json: serde_json::Value = res.json().await.unwrap_or_default(); + if !matches!(status, 200 | 202) { + return Err(error_message(status, &json)); + } + let message = json["message"].as_str().unwrap_or("File queued for import.").to_string(); + Ok(UploadRecord { uploaded_at: now_ms(), reference: None, url: None, message: Some(message) }) + } + + fn lists_rides(&self) -> bool { + true + } + + /// One page of cycling activities with a GPS track; the server filters by sport type and `hasGpx`. + async fn recent_rides(&self, ctx: &Ctx, page: u32) -> Result { + let creds = load(ctx); + let json = get_json(ctx, &creds, &format!("{ACTIVITIES_PATH}?filters[sportType]={}&filters[hasGpx]=true&pagination[size]=100&pagination[page]={page}", RIDE_TYPES.join(","))).await?; + let rides = json["activities"] + .as_array() + .into_iter() + .flatten() + .filter(|a| a["sportType"].as_str().is_some_and(|t| RIDE_TYPES.contains(&t)) && a["hasGpx"].as_bool() != Some(false)) + .filter_map(|a| { + Some(RemoteRide { + id: a["id"].as_str()?.to_string(), + name: a["name"].as_str().unwrap_or("Ride").to_string(), + start: a["startDateLocal"].as_str().unwrap_or("").to_string(), + distance: a["distanceInMeter"].as_f64().unwrap_or(0.0), + moving_time: a["movingTimeInSeconds"].as_f64().unwrap_or(0.0), + sport: a["sportType"].as_str().unwrap_or("").to_string(), + outline: decode_polyline(a["encodedPolyline"].as_str().unwrap_or("")), + ..Default::default() + }) + }) + .collect(); + let pagination = &json["pagination"]; + let more = pagination["page"].as_u64().zip(pagination["totalPages"].as_u64()).is_some_and(|(page, total)| page < total); + Ok(RidePage { rides, more }) + } + + fn imports_routes(&self) -> bool { + true + } + + /// Dreeve's own GPX export of the ride (Dreeve 5.4 and later), with elevation where it has it. + async fn ride_gpx(&self, ctx: &Ctx, id: &str) -> Result { + check_id(id)?; + let creds = load(ctx); + if !creds.verified { + return Err("Not connected to Dreeve.".into()); + } + let res = ctx.http.get(format!("{}{ACTIVITIES_PATH}/{id}/gpx", creds.url)).bearer_auth(&creds.api_key).timeout(Duration::from_secs(30)).send().await.map_err(reach_error)?; + let status = res.status().as_u16(); + let text = res.text().await.map_err(|e| format!("Could not read the GPX from Dreeve: {e}"))?; + if status != 200 { + return Err(error_message(status, &serde_json::from_str(&text).unwrap_or_default())); + } + Ok(text) + } + + /// The ride's `latLng` and `timeInSeconds` streams, lined up by index; points without a fix are skipped. + async fn ride_track(&self, ctx: &Ctx, id: &str) -> Result { + check_id(id)?; + let creds = load(ctx); + let info = get_json(ctx, &creds, &format!("{ACTIVITIES_PATH}/{id}")).await?; + // Local time without a zone; ghosts only use the differences between timestamps. + let start = info["startDateLocal"].as_str().and_then(velopopuli_core::gpx::parse_iso_time).unwrap_or(0.0); + let streams = get_json(ctx, &creds, &format!("{ACTIVITIES_PATH}/{id}/streams")).await?; + let (Some(ll), Some(tt)) = (streams["latLng"].as_array(), streams["timeInSeconds"].as_array()) else { + return Err("That ride has no GPS track.".into()); + }; + let points: Vec<(f64, f64, f64)> = ll.iter().zip(tt).filter_map(|(p, t)| Some((start + t.as_f64()?, p[0].as_f64()?, p[1].as_f64()?))).collect(); + if points.is_empty() { + return Err("That ride has no GPS track.".into()); + } + Ok(RideTrack { name: info["name"].as_str().unwrap_or("Dreeve ride").to_string(), points }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: &str = "drv_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + #[test] + fn url_is_normalised_and_checked() { + assert_eq!(normalise_url(" https://dreeve.example.com/ ").unwrap(), "https://dreeve.example.com"); + assert_eq!(normalise_url("http://localhost:8080//").unwrap(), "http://localhost:8080"); + assert!(normalise_url("http://10.0.0.5:8080").unwrap_err().contains("https://")); + assert!(normalise_url("dreeve.example.com").is_err()); + assert!(normalise_url("ftp://dreeve.example.com").is_err()); + assert!(normalise_url("").is_err()); + } + + #[test] + fn key_format() { + assert!(key_ok(KEY)); + assert!(!key_ok("not-a-key")); + assert!(!key_ok(&KEY[..67])); + assert!(!key_ok(&format!("{}g", &KEY[..67]))); + } + + #[test] + fn error_messages_prefer_the_servers_words() { + let body = serde_json::json!({ "error": "import_mode_not_files", "message": "Import mode is not files." }); + assert_eq!(error_message(409, &body), "Import mode is not files. (import_mode_not_files, HTTP 409)"); + assert!(error_message(401, &serde_json::Value::Null).contains("API key")); + assert!(error_message(404, &serde_json::Value::Null).contains("URL")); + assert!(error_message(413, &serde_json::Value::Null).contains("too large")); + } + + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + #[test] + fn configure_validates_keeps_the_saved_key_and_never_echoes_it() { + let dir = std::env::temp_dir().join(format!("vp-dreeve-{}", std::process::id())); + let ctx = Ctx::new(&dir, &reqwest::Client::new()); + let fields = |url: &str, key: &str| BTreeMap::from([("url".to_string(), url.to_string()), ("apiKey".to_string(), key.to_string())]); + + assert!(Dreeve.configure(&ctx, &fields("https://d.example.com", "bad")).is_err()); + assert!(Dreeve.configure(&ctx, &fields("d.example.com", KEY)).is_err()); + assert!(Dreeve.configure(&ctx, &fields("https://d.example.com", "")).is_err(), "no key saved yet"); + + let s = Dreeve.configure(&ctx, &fields("https://d.example.com/", KEY)).unwrap(); + assert!(s.configured && !s.connected); + assert_eq!(s.fields["url"], "https://d.example.com"); + assert!(!serde_json::to_string(&s).unwrap().contains(KEY)); + + // A blank key keeps the saved one; a changed URL drops the verified state. + let s = Dreeve.configure(&ctx, &fields("https://other.example.com", "")).unwrap(); + assert!(s.configured); + assert_eq!(load(&ctx).api_key, KEY); + assert_eq!(Dreeve.status(&ctx).fields["url"], "https://other.example.com"); + std::fs::remove_dir_all(dir).ok(); + } + + /// An HTTP server that takes one connection per reply, records each request and answers + /// the reply's status with its JSON body. + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + async fn fake_server(replies: &[(&'static str, &'static str)]) -> (String, tokio::task::JoinHandle>) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let replies: Vec = + replies.iter().map(|(status, body)| format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len())).collect(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let handle = tokio::spawn(async move { + let mut requests = Vec::new(); + for reply in replies { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut got = Vec::new(); + let mut buf = [0u8; 4096]; + loop { + let n = socket.read(&mut buf).await.unwrap(); + got.extend_from_slice(&buf[..n]); + let text = String::from_utf8_lossy(&got); + let Some(head_end) = text.find("\r\n\r\n") else { continue }; + let length = text[..head_end].lines().find_map(|l| l.strip_prefix("content-length: ")).and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + if got.len() >= head_end + 4 + length || n == 0 { + break; + } + } + socket.write_all(reply.as_bytes()).await.unwrap(); + socket.shutdown().await.ok(); + requests.push(String::from_utf8_lossy(&got).into_owned()); + } + requests + }); + (url, handle) + } + + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + #[tokio::test] + async fn connect_and_upload_speak_the_dreeve_api() { + let dir = std::env::temp_dir().join(format!("vp-dreeve-http-{}", std::process::id())); + let ctx = Ctx::new(&dir, &reqwest::Client::new()); + let fit = dir.join("ride.fit"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(&fit, b"FITBYTES").unwrap(); + let no_browser: OpenBrowser = Box::new(|_| {}); + + // Status: wrong import mode is a clear error and leaves the connector unlinked. + let (url, server) = fake_server(&[("200 OK", "{\"app\":\"dreeve\",\"version\":\"2.1.0\",\"canUpload\":false}")]).await; + Dreeve.configure(&ctx, &BTreeMap::from([("url".to_string(), url), ("apiKey".to_string(), KEY.to_string())])).unwrap(); + let err = Dreeve.connect(&ctx, Box::new(|_| {})).await.unwrap_err(); + assert!(err.contains("IMPORT_MODE=files"), "{err}"); + let request = server.await.unwrap().remove(0); + assert!(request.starts_with("GET /api/v1/status HTTP/1.1"), "{request}"); + assert!(request.to_lowercase().contains(&format!("authorization: bearer {KEY}")), "{request}"); + assert!(!Dreeve.status(&ctx).connected); + + // Status: a healthy instance links the connector and names the server. + let (url, server) = fake_server(&[("200 OK", "{\"app\":\"dreeve\",\"version\":\"2.1.0\",\"canUpload\":true}")]).await; + Dreeve.configure(&ctx, &BTreeMap::from([("url".to_string(), url), ("apiKey".to_string(), String::new())])).unwrap(); + let status = Dreeve.connect(&ctx, no_browser).await.unwrap(); + server.await.unwrap(); + assert!(status.connected); + assert_eq!(status.account, "Dreeve 2.1.0"); + + // Upload: multipart "file" part with the file's name and bytes; 202 is success with the server's message. + let (url, server) = fake_server(&[("202 Accepted", "{\"status\":\"queued\",\"message\":\"Queued, five minutes.\"}")]).await; + let mut creds = load(&ctx); + creds.url = url; + ctx.save_creds(ID, &creds).unwrap(); + let record = Dreeve.upload(&ctx, &UploadRequest { file: fit.clone(), name: "Alpe".into(), description: String::new() }).await.unwrap(); + let request = server.await.unwrap().remove(0); + assert!(request.starts_with("POST /api/v1/activity/upload HTTP/1.1"), "{request}"); + assert!(request.contains("name=\"file\"") && request.contains("filename=\"ride.fit\"") && request.contains("FITBYTES"), "{request}"); + assert_eq!(record.message.as_deref(), Some("Queued, five minutes.")); + assert!(record.url.is_none()); + + // Upload: an error reply becomes the server's own words. + let (url, server) = fake_server(&[("401 Unauthorized", "{\"error\":\"invalid_token\",\"message\":\"A valid token is required.\"}")]).await; + creds.url = url; + ctx.save_creds(ID, &creds).unwrap(); + let err = Dreeve.upload(&ctx, &UploadRequest { file: fit, name: String::new(), description: String::new() }).await.unwrap_err(); + server.await.unwrap(); + assert_eq!(err, "A valid token is required. (invalid_token, HTTP 401)"); + std::fs::remove_dir_all(dir).ok(); + } + + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + #[tokio::test] + async fn rides_and_tracks_speak_the_dreeve_api() { + let dir = std::env::temp_dir().join(format!("vp-dreeve-rides-{}", std::process::id())); + let ctx = Ctx::new(&dir, &reqwest::Client::new()); + let page = concat!( + "{\"activities\":[", + "{\"id\":\"activity-1\",\"name\":\"Evening Ride\",\"sportType\":\"GravelRide\",\"startDateLocal\":\"2026-11-09T18:05:38\",\"distanceInMeter\":42000,\"movingTimeInSeconds\":5400,\"hasGpx\":true,\"encodedPolyline\":\"_p~iF~ps|U_ulLnnqC_mqNvxq`@\"},", + "{\"id\":\"activity-2\",\"name\":\"Lunch Run\",\"sportType\":\"Run\",\"startDateLocal\":\"2026-11-08T12:00:00\",\"distanceInMeter\":8000,\"movingTimeInSeconds\":2400,\"hasGpx\":true},", + "{\"id\":\"activity-3\",\"name\":\"Trainer\",\"sportType\":\"VirtualRide\",\"startDateLocal\":\"2026-11-07T07:00:00\",\"distanceInMeter\":30000,\"movingTimeInSeconds\":3600,\"hasGpx\":false}", + "],\"pagination\":{\"page\":1,\"size\":100,\"total\":250,\"totalPages\":3}}" + ); + let detail = "{\"id\":\"activity-1\",\"name\":\"Evening Ride\",\"startDateLocal\":\"2026-11-09T18:05:38\",\"hasGpx\":true}"; + let streams = "{\"timeInSeconds\":[0,1,2,3],\"latLng\":[[51.2,3.18],null,[51.2001,3.1802],[51.2002,3.1804]]}"; + let gpx = "Evening Ride12"; + let (url, server) = fake_server(&[ + ("200 OK", page), + ("200 OK", detail), + ("200 OK", streams), + ("200 OK", gpx), + ("404 Not Found", "{\"error\":\"FILE_NOT_AVAILABLE\",\"message\":\"Activity \\\"activity-3\\\" has no GPS data to export as GPX.\"}"), + ]) + .await; + ctx.save_creds(ID, &Creds { url, api_key: KEY.into(), verified: true, server: "Dreeve 2.1.0".into() }).unwrap(); + + let page = Dreeve.recent_rides(&ctx, 1).await.unwrap(); + assert!(page.more, "page 1 of 3"); + let rides = page.rides; + assert_eq!(rides[0].outline.len(), 3, "the encoded polyline is the outline"); + assert!((rides[0].outline[0].0 - 38.5).abs() < 1e-6 && (rides[0].outline[0].1 + 120.2).abs() < 1e-6); + assert_eq!(rides.iter().map(|r| r.id.as_str()).collect::>(), ["activity-1"], "runs and rides without GPS are left out"); + assert_eq!(rides[0].name, "Evening Ride"); + assert_eq!(rides[0].start, "2026-11-09T18:05:38"); + assert_eq!((rides[0].distance, rides[0].moving_time), (42000.0, 5400.0)); + assert_eq!(rides[0].sport, "GravelRide"); + + let track = Dreeve.ride_track(&ctx, "activity-1").await.unwrap(); + assert_eq!(track.name, "Evening Ride"); + assert_eq!(track.points.len(), 3, "the point without a fix is skipped"); + assert_eq!(track.points[1].0 - track.points[0].0, 2.0); + assert_eq!((track.points[2].1, track.points[2].2), (51.2002, 3.1804)); + assert!(track.points[0].0 > 1.7e9, "absolute start from startDateLocal"); + + assert_eq!(Dreeve.ride_gpx(&ctx, "activity-1").await.unwrap(), gpx); + assert!(Dreeve.ride_gpx(&ctx, "activity-3").await.unwrap_err().contains("no GPS data")); + + let requests = server.await.unwrap(); + assert!(requests[0].starts_with("GET /api/v1/activities?filters[sportType]=Ride,MountainBikeRide,GravelRide,EBikeRide,EMountainBikeRide,VirtualRide,Velomobile,Handcycle&filters[hasGpx]=true&pagination[size]=100&pagination[page]=1 HTTP/1.1"), "{}", requests[0]); + assert!(requests[0].to_lowercase().contains(&format!("authorization: bearer {KEY}"))); + assert!(requests[1].starts_with("GET /api/v1/activities/activity-1 HTTP/1.1"), "{}", requests[1]); + assert!(requests[2].starts_with("GET /api/v1/activities/activity-1/streams HTTP/1.1"), "{}", requests[2]); + assert!(requests[3].starts_with("GET /api/v1/activities/activity-1/gpx HTTP/1.1"), "{}", requests[3]); + assert!(requests[3].to_lowercase().contains(&format!("authorization: bearer {KEY}"))); + + assert!(Dreeve.ride_track(&ctx, "../etc").await.unwrap_err().contains("activity id")); + assert!(Dreeve.ride_gpx(&ctx, "../etc").await.unwrap_err().contains("activity id")); + std::fs::remove_dir_all(dir).ok(); + } + + /// Needs a real instance: `DREEVE_URL=https://… DREEVE_API_KEY=drv_… cargo test -p velopopuli live_dreeve -- --ignored --nocapture`, + /// optionally `DREEVE_ROUTE_RIDE=` for the ride the test route is made of. + /// Read-only: links, lists rides, fetches one track and its GPX; uploads nothing. + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + #[tokio::test] + #[ignore] + async fn live_dreeve_lists_rides_and_tracks() { + let (Ok(url), Ok(key)) = (std::env::var("DREEVE_URL"), std::env::var("DREEVE_API_KEY")) else { + eprintln!("skipped: set DREEVE_URL and DREEVE_API_KEY"); + return; + }; + let dir = std::env::temp_dir().join(format!("vp-dreeve-live-{}", std::process::id())); + let http = reqwest::Client::builder().user_agent("VeloPopuli/0.3 (open-source indoor cycling app)").connect_timeout(Duration::from_secs(8)).build().unwrap(); + let ctx = Ctx::new(&dir, &http); + let fields = BTreeMap::from([("url".to_string(), url), ("apiKey".to_string(), key)]); + let status = Dreeve.configure(&ctx, &fields).unwrap(); + assert!(status.configured && !status.connected); + let status = Dreeve.connect(&ctx, Box::new(|_| {})).await.unwrap(); + assert!(status.connected); + eprintln!("connected: {}", status.account); + + let page = Dreeve.recent_rides(&ctx, 1).await.unwrap(); + let rides = page.rides; + eprintln!("page 1: {} rides with GPS, more: {}, with outline: {}", rides.len(), page.more, rides.iter().filter(|r| !r.outline.is_empty()).count()); + for r in rides.iter().take(5) { + eprintln!(" {} | {} | {} | {:.1} km | {:.0} min", r.id, r.start, r.name, r.distance / 1000.0, r.moving_time / 60.0); + } + // An outdoor ride (a virtual one's GPS is a made-up world): make a route of its track and + // the ride search must find that ride as one that rides it. + // DREEVE_ROUTE_RIDE= picks the ride to make the route of. + let pick = std::env::var("DREEVE_ROUTE_RIDE").ok(); + if let Some(outdoor) = rides.iter().find(|r| pick.as_deref().map_or(!r.name.contains("Virtual") && r.distance > 5000.0, |id| r.id == id)) { + let track = Dreeve.ride_track(&ctx, &outdoor.id).await.unwrap(); + let (t0, tn) = (track.points[0].0, track.points[track.points.len() - 1].0); + eprintln!("track of {:?}: {} points over {:.0} min", track.name, track.points.len(), (tn - t0) / 60.0); + assert!(track.points.len() > 10 && tn > t0); + let pts: Vec = track.points.iter().map(|p| velopopuli_core::gpx::RawPoint { lat: p.1, lon: p.2, ele: None }).collect(); + let route = velopopuli_core::gpx::build_route("live", &pts).unwrap(); + let found = super::super::find_rides(&Dreeve, &ctx, &route).await.unwrap(); + let fitting: Vec = found + .rides + .iter() + .filter(|r| r.follows_route) + .map(|r| format!("{} {} ({:.0}/{:.0} km)", r.start.get(..10).unwrap_or(""), r.name, r.followed_m / 1000.0, route.total / 1000.0)) + .collect(); + let partial = found.rides.iter().filter(|r| !r.follows_route && r.followed_m > 0.0).count(); + eprintln!( + "route from {:?}, {:.0} km: searched {} rides (more: {}), {} fit, {} share only its start", + outdoor.name, + route.total / 1000.0, + found.rides.len(), + found.more, + fitting.len(), + partial + ); + for f in &fitting { + eprintln!(" fits: {f}"); + } + assert!(found.rides.iter().any(|r| r.id == outdoor.id && r.follows_route), "the ride the route was made from fits it"); + + // The same ride as a route: Dreeve's GPX export must build one with elevation. + let gpx = Dreeve.ride_gpx(&ctx, &outdoor.id).await.unwrap(); + let (name, pts) = velopopuli_core::gpx::parse_gpx(&gpx).unwrap(); + let route = velopopuli_core::gpx::build_route(&name, &pts).unwrap(); + eprintln!("GPX of {name:?}: {} points, {:.0} km, {:.0} m up", pts.len(), route.total / 1000.0, route.ascent); + assert!(pts.iter().any(|p| p.ele.is_some()), "the export carries elevation"); + } + + let all = super::super::list_rides(&Dreeve, &ctx).await.unwrap(); + let mut sports: Vec<&str> = all.rides.iter().map(|r| r.sport.as_str()).collect(); + sports.sort_unstable(); + sports.dedup(); + eprintln!("listed {} rides (more: {}), sports {sports:?}, with preview: {}", all.rides.len(), all.more, all.rides.iter().filter(|r| !r.preview.is_empty()).count()); + assert!(all.rides.len() >= rides.len()); + std::fs::remove_dir_all(dir).ok(); + } +} diff --git a/src-tauri/src/connectors/mod.rs b/src-tauri/src/connectors/mod.rs index 0209f8f..c42791b 100644 --- a/src-tauri/src/connectors/mod.rs +++ b/src-tauri/src/connectors/mod.rs @@ -10,6 +10,7 @@ //! Linux) under its id — see `secrets.rs` — and never in the settings document, //! which goes into diagnostics reports. +pub mod dreeve; pub mod strava; use std::collections::BTreeMap; @@ -25,7 +26,7 @@ use velopopuli_core::types::UploadRecord; use crate::secrets; /// Every connector there is. Adding a service means adding it here. -pub static ALL: &[&(dyn Connector + Sync)] = &[&strava::Strava]; +pub static ALL: &[&(dyn Connector + Sync)] = &[&strava::Strava, &dreeve::Dreeve]; pub fn get(id: &str) -> Result<&'static (dyn Connector + Sync), String> { ALL.iter().copied().find(|c| c.info().id == id).ok_or_else(|| format!("Unknown connector: {id}")) @@ -57,7 +58,6 @@ impl Ctx { /// pasting a key that is checked with a test request. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] -#[allow(dead_code)] // `Token` is for key-based services such as Dreeve. pub enum AuthKind { OAuth, Token, @@ -66,7 +66,6 @@ pub enum AuthKind { /// What kind of input a configuration field wants. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] -#[allow(dead_code)] // `Url` is for self-hosted services such as Dreeve. pub enum FieldKind { Text, Url, @@ -134,6 +133,8 @@ pub struct RemoteRide { pub start: String, pub distance: f64, pub moving_time: f64, + /// The service's sport type, in Strava's vocabulary ("Ride", "GravelRide", …); empty if unknown. + pub sport: String, /// The service's simplified outline of the ride as `(lat, lon)`, empty if it gives none. #[serde(skip)] pub outline: Vec<(f64, f64)>, @@ -141,6 +142,9 @@ pub struct RemoteRide { pub follows_route: bool, /// Set by `find_rides`: how far along the route the outline follows it, in metres. pub followed_m: f64, + /// Set by `list_rides`: a few points of the outline as `(lat, lon)`, for drawing it small. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub preview: Vec<(f64, f64)>, } /// One page of `recent_rides`. @@ -261,6 +265,19 @@ pub trait Connector: Send + Sync { Err(format!("{} can't fetch a ride.", self.info().name)) } + // ── Optional: turning one of those rides into a route ──────────────────── + + /// True when `ride_gpx` works; the routes page then offers "Import from …". + /// Needs `lists_rides` too, which is where the rider picks the ride. + fn imports_routes(&self) -> bool { + false + } + + /// One ride as a GPX file with elevation, by the id `recent_rides` gave. + async fn ride_gpx(&self, _ctx: &Ctx, _id: &str) -> Result { + Err(format!("{} can't export a ride as a route.", self.info().name)) + } + // ── Optional: segments the service knows along a route ─────────────────── /// True when `segments_near` works; the ride setup then offers "Find segments". @@ -318,6 +335,36 @@ pub async fn find_rides(connector: &(dyn Connector + Sync), ctx: &Ctx, route: &R Ok(found) } +/// Pages to read at most when listing every ride to import one as a route. +const MAX_LIST_PAGES: u32 = 20; +/// Points kept of an outline for the small preview drawing. +const PREVIEW_POINTS: usize = 60; + +/// Every ride the connector lists, newest first, up to `MAX_LIST_PAGES` pages, each with a preview. +pub async fn list_rides(connector: &(dyn Connector + Sync), ctx: &Ctx) -> Result { + let mut found = RideSearch::default(); + for page in 1..=MAX_LIST_PAGES { + let mut got = connector.recent_rides(ctx, page).await?; + for ride in &mut got.rides { + ride.preview = thin(&ride.outline, PREVIEW_POINTS); + } + found.rides.append(&mut got.rides); + found.more = got.more; + if !got.more { + break; + } + } + Ok(found) +} + +/// At most `n` points of `points`, evenly spaced, keeping the first and the last. +fn thin(points: &[(f64, f64)], n: usize) -> Vec<(f64, f64)> { + if points.len() <= n || n < 2 { + return points.to_vec(); + } + (0..n).map(|i| points[i * (points.len() - 1) / (n - 1)]).collect() +} + /// Reads a field, trimmed; missing is the empty string. pub fn field(fields: &BTreeMap, key: &str) -> String { fields.get(key).map(|v| v.trim().to_string()).unwrap_or_default() @@ -326,7 +373,6 @@ pub fn field(fields: &BTreeMap, key: &str) -> String { /// Checks a server URL typed by the user before an API key is sent to it: https only, so the key /// isn't sent unencrypted. Plain http is allowed for this machine (`localhost`, `127.0.0.1`, `::1`), /// which is where a service under development runs. Returns the URL without a trailing slash. -#[allow(dead_code)] // For key-based services such as Dreeve. pub fn secure_server_url(raw: &str) -> Result { let url = reqwest::Url::parse(raw.trim()).map_err(|_| "That server address isn't a valid URL. Use the form https://example.org.".to_string())?; let local = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")); @@ -381,6 +427,13 @@ mod tests { assert!(err.contains(c.info().name), "{err}"); assert!(c.ride_track(&ctx, "1").await.is_err()); } + for c in ALL.iter().filter(|c| !c.imports_routes()) { + let err = c.ride_gpx(&ctx, "1").await.unwrap_err(); + assert!(err.contains(c.info().name), "{err}"); + } + for c in ALL.iter().filter(|c| c.imports_routes()) { + assert!(c.lists_rides(), "{}: importing a route needs the ride list", c.info().id); + } for c in ALL.iter().filter(|c| !c.finds_segments()) { let err = c.segments_near(&ctx, &[[0.0, 0.0, 1.0, 1.0]]).await.unwrap_err(); assert!(err.contains(c.info().name), "{err}"); @@ -463,6 +516,23 @@ mod tests { assert!(found.more); } + #[tokio::test] + async fn list_rides_reads_every_page_and_thins_the_outline() { + let ctx = Ctx::new(Path::new("/nonexistent"), &reqwest::Client::new()); + let route = straight_route(); + let fake = FakeRides { pages: vec![vec![true, false], vec![true], vec![false]], route, asked: Default::default() }; + let found = list_rides(&fake, &ctx).await.unwrap(); + assert_eq!(*fake.asked.lock().unwrap(), [1, 2, 3]); + assert_eq!(found.rides.len(), 4); + assert!(!found.more); + assert_eq!(found.rides[0].preview.len(), 4, "short outlines are kept whole"); + + let long: Vec<(f64, f64)> = (0..1000).map(|i| (i as f64, 0.0)).collect(); + let thinned = thin(&long, PREVIEW_POINTS); + assert_eq!(thinned.len(), PREVIEW_POINTS); + assert_eq!((thinned[0], thinned[PREVIEW_POINTS - 1]), (long[0], long[999])); + } + #[test] fn every_connector_describes_its_fields() { for c in ALL { diff --git a/src-tauri/src/connectors/strava.rs b/src-tauri/src/connectors/strava.rs index d25d601..0298e4f 100644 --- a/src-tauri/src/connectors/strava.rs +++ b/src-tauri/src/connectors/strava.rs @@ -369,6 +369,7 @@ async fn recent_rides(ctx: &Ctx, page: u32) -> Result { start: a["start_date_local"].as_str().unwrap_or("").to_string(), distance: a["distance"].as_f64().unwrap_or(0.0), moving_time: a["moving_time"].as_f64().unwrap_or(0.0), + sport: a["sport_type"].as_str().or(a["type"].as_str()).unwrap_or("").to_string(), outline: decode_polyline(a["map"]["summary_polyline"].as_str().unwrap_or("")), ..Default::default() }) diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 3d4baab..3eb24f2 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -184,6 +184,8 @@ fn main() { commands::connector_rides, commands::connector_routes, commands::connector_route, + commands::connector_ride_list, + commands::route_import_connector, commands::smoke_config, commands::smoke_done, commands::smoke_frame, diff --git a/web/src/bridge.ts b/web/src/bridge.ts index aa6ab66..9a9a146 100644 --- a/web/src/bridge.ts +++ b/web/src/bridge.ts @@ -41,6 +41,7 @@ export const api = { routes: { importDialog: () => invoke<{ added: RouteMeta[]; problems: string[] }>('routes_import_dialog'), importText: (name: string, text: string) => invoke('routes_import_text', { name, text }), + importRemote: (id: string, rideId: string, name: string) => invoke('route_import_connector', { id, rideId, name }), demoMeta: () => invoke('demo_meta'), /** The built-in velodromes, each as ridden anticlockwise (its ID with `-clockwise` the other way). */ tracksMeta: () => invoke('tracks_meta'), @@ -110,7 +111,9 @@ export const api = { name: string | null gaps: number clipped: boolean - }>('connector_route', { id, routeId }) + }>('connector_route', { id, routeId }), + /** Every ride the rider has on the service, newest first, with a preview of each. */ + rideList: (id: string) => invoke('connector_ride_list', { id }) }, workouts: { list: () => invoke('workouts_list'), diff --git a/web/src/styles.css b/web/src/styles.css index b1da065..952d5e8 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -27,6 +27,7 @@ --ok: #4ddb8a; --warn: #ffd24a; --strava: #fc4c02; + --dreeve: #428f7e; color-scheme: dark; } @@ -135,6 +136,12 @@ button.strava { color: #fff; font-weight: 600; } +button.dreeve { + background: var(--dreeve); + border-color: var(--dreeve); + color: #fff; + font-weight: 600; +} input, select, @@ -428,6 +435,84 @@ textarea:focus { .modal .row { margin-top: 6px; } +/* Importing a ride from a connected service as a route: 80 % of the window. */ +.modal.remote-import { + width: 80vw; + height: 80vh; + max-width: none; + display: flex; + flex-direction: column; + gap: 10px; +} +.remote-import-head { + display: flex; + align-items: center; + justify-content: space-between; +} +.remote-import-head h2 { + margin: 0; +} +.remote-import-filters { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; +} +.remote-import-filters input[type='search'] { + flex: 1 1 240px; +} +.range-filter { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 220px; +} +/* Two handles on one track (DualRange in RemoteImport.tsx). */ +.dual-range { + position: relative; + height: 22px; + margin: 0 9px; + cursor: pointer; + touch-action: none; +} +.dual-range-rail, +.dual-range-fill { + position: absolute; + top: 9px; + height: 4px; + border-radius: 2px; +} +.dual-range-rail { + left: 0; + right: 0; + background: var(--line); +} +.dual-range-fill { + background: var(--accent); +} +.dual-range-thumb { + position: absolute; + top: 2px; + width: 18px; + height: 18px; + margin-left: -9px; + border-radius: 50%; + background: var(--accent); + border: 2px solid var(--panel); + box-shadow: 0 0 0 1px var(--line); +} +.dual-range-thumb:focus-visible { + outline: 2px solid var(--text); + outline-offset: 2px; +} +.remote-import-list { + flex: 1; + overflow-y: auto; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); + align-content: start; + gap: 14px; +} .picker { display: flex; flex-direction: column; diff --git a/web/src/types.ts b/web/src/types.ts index 12e47f1..5566ba9 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -225,6 +225,10 @@ export interface RemoteRide { start: string distance: number movingTime: number + /** The service's sport type in Strava's vocabulary ("Ride", "GravelRide", …); empty if unknown. */ + sport: string + /** A few `[lat, lon]` points of its outline, when listed for importing as a route. */ + preview?: [number, number][] /** Its outline rides the route from its start for most of it. */ followsRoute: boolean /** How far along the route it follows it, in metres. */ @@ -327,6 +331,8 @@ export interface ConnectorEntry { findsSegments: boolean /** The service can list the rider's saved routes (Find a route). */ listsRoutes: boolean + /** One of the rider's rides on the service can be imported as a route. */ + importsRoutes: boolean } /** One of the rider's saved routes on a service. */ diff --git a/web/src/ui/Home.tsx b/web/src/ui/Home.tsx index adeb8eb..4e742f5 100644 --- a/web/src/ui/Home.tsx +++ b/web/src/ui/Home.tsx @@ -2,7 +2,8 @@ import { useEffect, useMemo, useState } from 'react' import { errorText } from '../bridge' import { fmtDist, fmtEle, fmtTime } from '../core/fmt' import { api, useSettings, useStored } from '../state' -import type { RideRequest, RouteMeta } from '../types' +import type { ConnectorEntry, RideRequest, RouteMeta } from '../types' +import { RemoteImport } from './RemoteImport' import { RideSetup } from './RideSetup' export function RoutePreview({ outline }: { outline: [number, number][] }): React.JSX.Element { @@ -37,8 +38,12 @@ export function Home({ onRide }: { onRide: (request: RideRequest) => void }): Re const [setup, setSetup] = useState<{ route: RouteMeta; room?: string } | null>(null) const [joining, setJoining] = useState(false) const [room, setRoom] = useState('') + /** Connected services whose rides can be imported as routes. */ + const [sources, setSources] = useState([]) + const [importing, setImporting] = useState(null) useEffect(() => void api.routes.demoMeta().then(setDemo), []) useEffect(() => void api.routes.tracksMeta().then(setTracks), []) + useEffect(() => void api.connectors.list().then((all) => setSources(all.filter((c) => c.importsRoutes && c.listsRides && c.status.connected))), []) const add = (added: RouteMeta[], problems: string[]): void => { if (added.length) saveRoutes([...added, ...(routes ?? [])]) @@ -124,6 +129,11 @@ export function Home({ onRide }: { onRide: (request: RideRequest) => void }): Re
+ {sources.map((c) => ( + + ))}
)} + {importing && add([route], [])} onClose={() => setImporting(null)} />} {setup && setSetup(null)} onStart={(r) => (setSetup(null), onRide(r))} />} {error &&
{error}
}
diff --git a/web/src/ui/RemoteImport.tsx b/web/src/ui/RemoteImport.tsx new file mode 100644 index 0000000..6bd86fe --- /dev/null +++ b/web/src/ui/RemoteImport.tsx @@ -0,0 +1,244 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { errorText } from '../bridge' +import { distUnit, distValue, fmtDist, fmtTime } from '../core/fmt' +import { api, useSettings } from '../state' +import type { ConnectorEntry, RemoteRide, RouteMeta } from '../types' +import { RoutePreview } from './Home' + +/** Strava's sport types, which Dreeve uses too, as the bike they were ridden on. */ +const BIKES: Record = { + Ride: 'Road', + GravelRide: 'Gravel', + MountainBikeRide: 'Mountain bike', + EBikeRide: 'E-bike', + EMountainBikeRide: 'E-mountain bike', + VirtualRide: 'Virtual', + Velomobile: 'Velomobile', + Handcycle: 'Handcycle' +} +const bikeName = (sport: string): string => BIKES[sport] ?? (sport || 'Other') + +const fmtDate = (start: string): string => { + const d = new Date(start) + return Number.isNaN(d.getTime()) ? start : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) +} + +/** + * Two handles on one track for a whole-number range from 0 to `max`. Drawn from plain elements + * because two overlapping native range inputs can't share the pointer in WebKitGTK. + */ +function DualRange(props: { max: number; value: [number, number]; unit: string; onChange: (v: [number, number]) => void }): React.JSX.Element { + const { max, value, unit, onChange } = props + const [lo, hi] = value + const track = useRef(null) + /** The handle being dragged: 0 for the shortest, 1 for the longest, 'either' until a stacked pair is moved. */ + const dragging = useRef<0 | 1 | 'either' | null>(null) + + const at = (clientX: number): number => { + const box = track.current?.getBoundingClientRect() + if (!box || box.width === 0) return 0 + return Math.round(Math.min(1, Math.max(0, (clientX - box.left) / box.width)) * max) + } + const set = (handle: 0 | 1, v: number): void => onChange(handle === 0 ? [Math.min(Math.max(0, v), hi), hi] : [lo, Math.max(Math.min(max, v), lo)]) + + const onDown = (e: React.PointerEvent): void => { + const v = at(e.clientX) + track.current?.setPointerCapture(e.pointerId) + // Both handles on the spot pressed: the direction of the drag picks one. + if (lo === hi && v === lo) { + dragging.current = 'either' + return + } + // Otherwise the nearer handle jumps there; between two stacked ones, the side pressed decides. + const handle: 0 | 1 = Math.abs(v - lo) < Math.abs(v - hi) || (lo === hi && v < lo) ? 0 : 1 + dragging.current = handle + set(handle, v) + } + const onMove = (e: React.PointerEvent): void => { + if (dragging.current === null) return + const v = at(e.clientX) + if (dragging.current === 'either') { + if (v === lo) return + dragging.current = v < lo ? 0 : 1 + } + set(dragging.current, v) + } + const onUp = (e: React.PointerEvent): void => { + dragging.current = null + track.current?.releasePointerCapture(e.pointerId) + } + const onKey = (handle: 0 | 1) => (e: React.KeyboardEvent) => { + const now = handle === 0 ? lo : hi + const step = e.shiftKey ? 10 : 1 + const next = { ArrowLeft: now - step, ArrowDown: now - step, ArrowRight: now + step, ArrowUp: now + step, Home: 0, End: max }[e.key] + if (next === undefined) return + e.preventDefault() + set(handle, next) + } + + const pct = (v: number): string => `${(v / max) * 100}%` + const handle = (h: 0 | 1, v: number, label: string): React.JSX.Element => ( +
+ ) + + return ( +
+
+
+ {handle(0, lo, 'Shortest')} + {handle(1, hi, 'Longest')} +
+ ) +} + +/** A near-fullscreen list of the rider's rides on a service, to import one or more as routes. */ +export function RemoteImport(props: { connector: ConnectorEntry; onAdded: (route: RouteMeta) => void; onClose: () => void }): React.JSX.Element { + const { connector, onAdded, onClose } = props + const name = connector.info.name + const { settings } = useSettings() + const u = settings.units + const [rides, setRides] = useState(null) + const [more, setMore] = useState(false) + const [error, setError] = useState('') + const [query, setQuery] = useState('') + const [bike, setBike] = useState('') + /** The distance range in the rider's unit; `null` until the rides are in and set its bounds. */ + const [range, setRange] = useState<[number, number] | null>(null) + const [busy, setBusy] = useState(null) + const [imported, setImported] = useState([]) + + useEffect(() => { + api.connectors.rideList(connector.info.id).then( + (found) => { + setRides(found.rides) + setMore(found.more) + }, + (err) => setError(errorText(err)) + ) + }, [connector.info.id]) + + useEffect(() => { + const onKey = (e: KeyboardEvent): void => { + if (e.key === 'Escape') onClose() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [onClose]) + + const maxDist = useMemo(() => Math.max(1, Math.ceil(Math.max(0, ...(rides ?? []).map((r) => distValue(r.distance, u))))), [rides, u]) + const [lo, hi] = range ?? [0, maxDist] + const bikes = useMemo(() => [...new Set((rides ?? []).map((r) => r.sport))].sort((a, b) => bikeName(a).localeCompare(bikeName(b))), [rides]) + + const shown = useMemo(() => { + const words = query.toLowerCase().split(/\s+/).filter(Boolean) + return (rides ?? []).filter((r) => { + const d = distValue(r.distance, u) + const text = `${r.name} ${fmtDate(r.start)}`.toLowerCase() + return (!bike || r.sport === bike) && d >= lo && d <= hi && words.every((w) => text.includes(w)) + }) + }, [rides, query, bike, lo, hi, u]) + + const take = (ride: RemoteRide): void => { + setBusy(ride.id) + setError('') + api.routes.importRemote(connector.info.id, ride.id, ride.name).then( + (route) => { + onAdded(route) + setImported((ids) => [...ids, ride.id]) + setBusy(null) + }, + (err) => { + setError(`${ride.name}: ${errorText(err)}`) + setBusy(null) + } + ) + } + + const unit = distUnit(u) + const filtered = Boolean(query || bike || range) + + return ( +
e.target === e.currentTarget && onClose()}> +
+
+

Import from {name}

+ +
+ +
+ setQuery(e.target.value)} /> + +
+ + {lo}–{hi} {unit} + + +
+ {filtered && ( + + )} +
+ + {error &&
{error}
} + {!rides && !error &&

Loading your {name} rides…

} + {rides && ( +

+ {shown.length} of {rides.length} rides{more ? ` (the newest ${rides.length}; older ones aren't listed)` : ''} +

+ )} + +
+ {shown.map((r) => { + const done = imported.includes(r.id) + return ( +
+ +

{r.name}

+
+ {fmtDist(r.distance, u)} + {fmtTime(r.movingTime)} + {bikeName(r.sport)} +
+
{fmtDate(r.start)}
+
+ +
+
+ ) + })} + {rides && !shown.length &&

No ride matches these filters.

} +
+
+
+ ) +}