1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Trip-related types and methods
use crate::{PaginatedResponse, Photo, Polyline, Result, RideWithGpsClient, Visibility};
use serde::{Deserialize, Serialize};
/// Track point on a trip with telemetry data
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TripTrackPoint {
/// Longitude
pub x: Option<f64>,
/// Latitude
pub y: Option<f64>,
/// Distance in meters
pub d: Option<f64>,
/// Elevation in meters
pub e: Option<f64>,
/// Unix timestamp
pub t: Option<i64>,
/// Speed in km/h
pub s: Option<f64>,
/// Temperature in Celsius
#[serde(rename = "T")]
pub temp: Option<f64>,
/// Heart rate in BPM
pub h: Option<f64>,
/// Cadence in RPM
pub c: Option<f64>,
/// Power in watts
pub p: Option<f64>,
/// Power balance (L/R percentage)
pub pb: Option<f64>,
/// Lap marker
pub lap: Option<bool>,
/// Exclude from metrics
pub k: Option<bool>,
/// User modified point
pub m: Option<bool>,
}
/// Gear/equipment used for a trip
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Gear {
/// Gear ID
pub id: u64,
/// Make/brand
pub make: Option<String>,
/// Model
pub model: Option<String>,
/// Description
pub description: Option<String>,
/// Whether to exclude from totals
pub exclude_from_totals: Option<bool>,
/// Created timestamp
pub created_at: Option<String>,
}
/// A trip (recorded ride)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Trip {
/// Trip ID
pub id: u64,
/// Trip name
pub name: Option<String>,
/// Trip description
pub description: Option<String>,
/// Distance in meters
pub distance: Option<f64>,
/// Elevation gain in meters
pub elevation_gain: Option<f64>,
/// Elevation loss in meters
pub elevation_loss: Option<f64>,
/// Trip visibility
pub visibility: Option<Visibility>,
/// User ID of the trip owner
pub user_id: Option<u64>,
/// API URL
pub url: Option<String>,
/// HTML/web URL
pub web_url: Option<String>,
/// Departed at timestamp
pub departed_at: Option<String>,
/// Time zone
pub time_zone: Option<String>,
/// Created timestamp
pub created_at: Option<String>,
/// Updated timestamp
pub updated_at: Option<String>,
/// Duration in seconds
pub duration: Option<f64>,
/// Moving time in seconds
pub moving_time: Option<f64>,
/// Average speed in m/s
pub avg_speed: Option<f64>,
/// Maximum speed in m/s
pub max_speed: Option<f64>,
/// Average cadence (RPM)
pub avg_cad: Option<f64>,
/// Minimum cadence (RPM)
pub min_cad: Option<f64>,
/// Maximum cadence (RPM)
pub max_cad: Option<f64>,
/// Average heart rate (BPM)
pub avg_hr: Option<f64>,
/// Minimum heart rate (BPM)
pub min_hr: Option<f64>,
/// Maximum heart rate (BPM)
pub max_hr: Option<f64>,
/// Average power (watts)
pub avg_watts: Option<f64>,
/// Minimum power (watts)
pub min_watts: Option<f64>,
/// Maximum power (watts)
pub max_watts: Option<f64>,
/// Calories burned
pub calories: Option<f64>,
/// Recording device name
pub device: Option<String>,
/// Locality/location
pub locality: Option<String>,
/// Administrative area
pub administrative_area: Option<String>,
/// Country code
pub country_code: Option<String>,
/// Activity type
pub activity_type: Option<String>,
/// FIT file sport type
pub fit_sport: Option<i32>,
/// FIT file sub-sport type
pub fit_sub_sport: Option<i32>,
/// Whether the trip is stationary
pub stationary: Option<bool>,
/// Track type
pub track_type: Option<String>,
/// Terrain rating
pub terrain: Option<i32>,
/// Difficulty rating
pub difficulty: Option<i32>,
/// First point latitude
pub first_lat: Option<f64>,
/// First point longitude
pub first_lng: Option<f64>,
/// Last point latitude
pub last_lat: Option<f64>,
/// Last point longitude
pub last_lng: Option<f64>,
/// Southwest corner latitude (bounding box)
pub sw_lat: Option<f64>,
/// Southwest corner longitude (bounding box)
pub sw_lng: Option<f64>,
/// Northeast corner latitude (bounding box)
pub ne_lat: Option<f64>,
/// Northeast corner longitude (bounding box)
pub ne_lng: Option<f64>,
/// Track points with telemetry (included when fetching a specific trip)
pub track_points: Option<Vec<TripTrackPoint>>,
/// Gear/equipment used (included when fetching a specific trip)
pub gear: Option<Gear>,
/// Photos (included when fetching a specific trip)
pub photos: Option<Vec<Photo>>,
}
/// Parameters for listing trips
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListTripsParams {
/// Filter by trip name
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Filter by visibility
#[serde(skip_serializing_if = "Option::is_none")]
pub visibility: Option<Visibility>,
/// Filter by minimum distance (meters)
#[serde(skip_serializing_if = "Option::is_none")]
pub min_distance: Option<f64>,
/// Filter by maximum distance (meters)
#[serde(skip_serializing_if = "Option::is_none")]
pub max_distance: Option<f64>,
/// Filter by minimum elevation gain (meters)
#[serde(skip_serializing_if = "Option::is_none")]
pub min_elevation_gain: Option<f64>,
/// Filter by maximum elevation gain (meters)
#[serde(skip_serializing_if = "Option::is_none")]
pub max_elevation_gain: Option<f64>,
/// Page number
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
/// Page size
#[serde(skip_serializing_if = "Option::is_none")]
pub page_size: Option<u32>,
}
impl RideWithGpsClient {
/// List trips for the authenticated user
///
/// # Arguments
///
/// * `params` - Optional parameters for filtering and pagination
///
/// # Example
///
/// ```rust,no_run
/// use ridewithgps_client::{RideWithGpsClient, ListTripsParams};
///
/// let client = RideWithGpsClient::new(
/// "https://ridewithgps.com",
/// "your-api-key",
/// Some("your-auth-token")
/// );
///
/// let params = ListTripsParams {
/// min_distance: Some(20000.0), // 20km
/// ..Default::default()
/// };
///
/// let trips = client.list_trips(Some(¶ms)).unwrap();
/// println!("Found {} trips", trips.results.len());
/// ```
pub fn list_trips(&self, params: Option<&ListTripsParams>) -> Result<PaginatedResponse<Trip>> {
let mut url = "/api/v1/trips.json".to_string();
if let Some(params) = params {
let query = serde_json::to_value(params)?;
if let Some(obj) = query.as_object() {
if !obj.is_empty() {
let query_str = serde_urlencoded::to_string(obj).map_err(|e| {
crate::Error::ApiError(format!("Failed to encode query: {}", e))
})?;
url.push('?');
url.push_str(&query_str);
}
}
}
self.get(&url)
}
/// Get a specific trip by ID
///
/// # Arguments
///
/// * `id` - The trip ID
///
/// # Example
///
/// ```rust,no_run
/// use ridewithgps_client::RideWithGpsClient;
///
/// let client = RideWithGpsClient::new(
/// "https://ridewithgps.com",
/// "your-api-key",
/// Some("your-auth-token")
/// );
///
/// let trip = client.get_trip(12345).unwrap();
/// println!("Trip: {:?}", trip);
/// ```
pub fn get_trip(&self, id: u64) -> Result<Trip> {
#[derive(Deserialize)]
struct TripWrapper {
trip: Trip,
}
let wrapper: TripWrapper = self.get(&format!("/api/v1/trips/{}.json", id))?;
Ok(wrapper.trip)
}
/// Get the polyline for a specific trip
///
/// # Arguments
///
/// * `id` - The trip ID
///
/// # Example
///
/// ```rust,no_run
/// use ridewithgps_client::RideWithGpsClient;
///
/// let client = RideWithGpsClient::new(
/// "https://ridewithgps.com",
/// "your-api-key",
/// None
/// );
///
/// let polyline = client.get_trip_polyline(12345).unwrap();
/// println!("Polyline: {}", polyline.polyline);
/// ```
pub fn get_trip_polyline(&self, id: u64) -> Result<Polyline> {
self.get(&format!("/api/v1/trips/{}/polyline.json", id))
}
/// Delete a trip
///
/// # Arguments
///
/// * `id` - The trip ID
///
/// # Example
///
/// ```rust,no_run
/// use ridewithgps_client::RideWithGpsClient;
///
/// let client = RideWithGpsClient::new(
/// "https://ridewithgps.com",
/// "your-api-key",
/// Some("your-auth-token")
/// );
///
/// client.delete_trip(12345).unwrap();
/// ```
pub fn delete_trip(&self, id: u64) -> Result<()> {
self.delete(&format!("/api/v1/trips/{}.json", id))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trip_deserialization() {
let json = r#"{
"id": 456,
"name": "Morning Ride",
"distance": 25000.0,
"elevation_gain": 300.0,
"visibility": "private",
"duration": 3600.0,
"avg_speed": 6.94
}"#;
let trip: Trip = serde_json::from_str(json).unwrap();
assert_eq!(trip.id, 456);
assert_eq!(trip.name.as_deref(), Some("Morning Ride"));
assert_eq!(trip.distance, Some(25000.0));
assert_eq!(trip.visibility, Some(Visibility::Private));
assert_eq!(trip.duration, Some(3600.0));
}
#[test]
fn test_list_trips_params() {
let params = ListTripsParams {
name: Some("ride".to_string()),
visibility: Some(Visibility::Public),
min_distance: Some(10000.0),
page: Some(2),
..Default::default()
};
let json = serde_json::to_value(¶ms).unwrap();
assert!(json.get("name").is_some());
assert!(json.get("visibility").is_some());
assert!(json.get("min_distance").is_some());
assert!(json.get("page").is_some());
}
#[test]
fn test_trip_wrapper_deserialization() {
let json = r#"{
"trip": {
"id": 789,
"name": "Wrapped Trip",
"distance": 30000.0,
"avg_hr": 145.5
}
}"#;
#[derive(Deserialize)]
struct TripWrapper {
trip: Trip,
}
let wrapper: TripWrapper = serde_json::from_str(json).unwrap();
assert_eq!(wrapper.trip.id, 789);
assert_eq!(wrapper.trip.name.as_deref(), Some("Wrapped Trip"));
assert_eq!(wrapper.trip.avg_hr, Some(145.5));
}
#[test]
fn test_trip_track_point_deserialization() {
let json = r#"{
"x": -122.4,
"y": 37.7,
"t": 1609459200,
"s": 5.5,
"h": 150.0,
"c": 90.0,
"p": 200.0,
"lap": true
}"#;
let track_point: TripTrackPoint = serde_json::from_str(json).unwrap();
assert_eq!(track_point.x, Some(-122.4));
assert_eq!(track_point.y, Some(37.7));
assert_eq!(track_point.t, Some(1609459200));
assert_eq!(track_point.s, Some(5.5));
assert_eq!(track_point.h, Some(150.0));
assert_eq!(track_point.c, Some(90.0));
assert_eq!(track_point.p, Some(200.0));
assert_eq!(track_point.lap, Some(true));
}
#[test]
fn test_gear_deserialization() {
let json = r#"{
"id": 42,
"make": "Trek",
"model": "Domane SL5",
"description": "Road Bike"
}"#;
let gear: Gear = serde_json::from_str(json).unwrap();
assert_eq!(gear.id, 42);
assert_eq!(gear.make.as_deref(), Some("Trek"));
assert_eq!(gear.model.as_deref(), Some("Domane SL5"));
assert_eq!(gear.description.as_deref(), Some("Road Bike"));
}
#[test]
fn test_trip_with_telemetry() {
let json = r#"{
"id": 555,
"name": "Power Training",
"avg_cad": 85.5,
"max_cad": 120.0,
"avg_hr": 155.0,
"max_hr": 180.0,
"avg_watts": 220.0,
"max_watts": 450.0,
"calories": 850.0,
"fit_sport": 2,
"fit_sub_sport": 10
}"#;
let trip: Trip = serde_json::from_str(json).unwrap();
assert_eq!(trip.id, 555);
assert_eq!(trip.avg_cad, Some(85.5));
assert_eq!(trip.max_cad, Some(120.0));
assert_eq!(trip.avg_hr, Some(155.0));
assert_eq!(trip.max_hr, Some(180.0));
assert_eq!(trip.avg_watts, Some(220.0));
assert_eq!(trip.calories, Some(850.0));
assert_eq!(trip.fit_sport, Some(2));
assert_eq!(trip.fit_sub_sport, Some(10));
}
}