ridewithgps-client 0.1.0

API client for the RideWithGPS routing and trip planning service
Documentation
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
//! Route-related types and methods

use crate::{PaginatedResponse, PointOfInterest, Result, RideWithGpsClient};
use serde::{Deserialize, Serialize};

/// Visibility setting for a route
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Visibility {
    /// Public route
    Public,

    /// Private route
    Private,

    /// Unlisted route
    Unlisted,
}

/// Track point on a route
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TrackPoint {
    /// Longitude
    pub x: Option<f64>,

    /// Latitude
    pub y: Option<f64>,

    /// Distance in meters
    pub d: Option<f64>,

    /// Elevation in meters
    pub e: Option<f64>,

    /// Surface type
    #[serde(rename = "S")]
    pub surface: Option<i32>,

    /// Highway tag
    #[serde(rename = "R")]
    pub highway: Option<i32>,
}

/// Course point (turn-by-turn cue) on a route
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CoursePoint {
    /// Longitude
    pub x: Option<f64>,

    /// Latitude
    pub y: Option<f64>,

    /// Distance in meters
    pub d: Option<f64>,

    /// Cue type
    pub t: Option<String>,

    /// Cue text/description
    pub n: Option<String>,
}

/// Photo attached to a route or trip
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Photo {
    /// Photo ID
    pub id: u64,

    /// Photo URL
    pub url: Option<String>,

    /// Whether the photo is highlighted
    pub highlighted: Option<bool>,

    /// Photo caption
    pub caption: Option<String>,

    /// Created timestamp
    pub created_at: Option<String>,
}

/// A route
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Route {
    /// Route ID
    pub id: u64,

    /// Route name
    pub name: Option<String>,

    /// Route 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>,

    /// Route visibility
    pub visibility: Option<Visibility>,

    /// User ID of the route owner
    pub user_id: Option<u64>,

    /// API URL
    pub url: Option<String>,

    /// HTML/web URL
    pub html_url: Option<String>,

    /// Created timestamp
    pub created_at: Option<String>,

    /// Updated timestamp
    pub updated_at: Option<String>,

    /// Locality/location
    pub locality: Option<String>,

    /// Administrative area
    pub administrative_area: Option<String>,

    /// Country code
    pub country_code: Option<String>,

    /// Track type
    pub track_type: Option<String>,

    /// Whether the route has course points
    pub has_course_points: Option<bool>,

    /// Terrain rating
    pub terrain: Option<String>,

    /// Difficulty rating
    pub difficulty: Option<String>,

    /// 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>,

    /// Percentage of unpaved surface
    pub unpaved_pct: Option<f64>,

    /// Surface type
    pub surface: Option<String>,

    /// Whether the route is archived
    pub archived: Option<bool>,

    /// Activity types
    pub activity_types: Option<Vec<String>>,

    /// Track points (included when fetching a specific route)
    pub track_points: Option<Vec<TrackPoint>>,

    /// Course points/cues (included when fetching a specific route)
    pub course_points: Option<Vec<CoursePoint>>,

    /// Points of interest along the route (included when fetching a specific route)
    pub points_of_interest: Option<Vec<PointOfInterest>>,

    /// Photos (included when fetching a specific route)
    pub photos: Option<Vec<Photo>>,
}

/// Polyline data for a route
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Polyline {
    /// Encoded polyline string
    pub polyline: String,

    /// Parent type (e.g., "route")
    pub parent_type: Option<String>,

    /// Parent ID
    pub parent_id: Option<u64>,
}

/// Parameters for listing routes
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListRoutesParams {
    /// Filter by route 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 routes for the authenticated user
    ///
    /// # Arguments
    ///
    /// * `params` - Optional parameters for filtering and pagination
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::{RideWithGpsClient, ListRoutesParams};
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     Some("your-auth-token")
    /// );
    ///
    /// let params = ListRoutesParams {
    ///     min_distance: Some(10000.0), // 10km
    ///     ..Default::default()
    /// };
    ///
    /// let routes = client.list_routes(Some(&params)).unwrap();
    /// println!("Found {} routes", routes.results.len());
    /// ```
    pub fn list_routes(
        &self,
        params: Option<&ListRoutesParams>,
    ) -> Result<PaginatedResponse<Route>> {
        let mut url = "/api/v1/routes.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 route by ID
    ///
    /// # Arguments
    ///
    /// * `id` - The route ID
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::RideWithGpsClient;
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     Some("your-auth-token")
    /// );
    ///
    /// let route = client.get_route(12345).unwrap();
    /// println!("Route: {:?}", route);
    /// ```
    pub fn get_route(&self, id: u64) -> Result<Route> {
        #[derive(Deserialize)]
        struct RouteWrapper {
            route: Route,
        }

        let wrapper: RouteWrapper = self.get(&format!("/api/v1/routes/{}.json", id))?;
        Ok(wrapper.route)
    }

    /// Get the polyline for a specific route
    ///
    /// # Arguments
    ///
    /// * `id` - The route ID
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::RideWithGpsClient;
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     None
    /// );
    ///
    /// let polyline = client.get_route_polyline(12345).unwrap();
    /// println!("Polyline: {}", polyline.polyline);
    /// ```
    pub fn get_route_polyline(&self, id: u64) -> Result<Polyline> {
        self.get(&format!("/api/v1/routes/{}/polyline.json", id))
    }

    /// Delete a route
    ///
    /// # Arguments
    ///
    /// * `id` - The route 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_route(12345).unwrap();
    /// ```
    pub fn delete_route(&self, id: u64) -> Result<()> {
        self.delete(&format!("/api/v1/routes/{}.json", id))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_route_deserialization() {
        let json = r#"{
            "id": 123,
            "name": "Test Route",
            "distance": 10000.0,
            "elevation_gain": 500.0,
            "visibility": "public"
        }"#;

        let route: Route = serde_json::from_str(json).unwrap();
        assert_eq!(route.id, 123);
        assert_eq!(route.name.as_deref(), Some("Test Route"));
        assert_eq!(route.distance, Some(10000.0));
        assert_eq!(route.visibility, Some(Visibility::Public));
    }

    #[test]
    fn test_polyline_deserialization() {
        let json = r#"{
            "polyline": "encoded_string_here",
            "parent_type": "route",
            "parent_id": 123
        }"#;

        let polyline: Polyline = serde_json::from_str(json).unwrap();
        assert_eq!(polyline.polyline, "encoded_string_here");
        assert_eq!(polyline.parent_type.as_deref(), Some("route"));
        assert_eq!(polyline.parent_id, Some(123));
    }

    #[test]
    fn test_list_routes_params() {
        let params = ListRoutesParams {
            name: Some("test".to_string()),
            visibility: Some(Visibility::Public),
            min_distance: Some(5000.0),
            ..Default::default()
        };

        let json = serde_json::to_value(&params).unwrap();
        assert!(json.get("name").is_some());
        assert!(json.get("visibility").is_some());
        assert!(json.get("min_distance").is_some());
    }

    #[test]
    fn test_route_wrapper_deserialization() {
        let json = r#"{
            "route": {
                "id": 456,
                "name": "Wrapped Route",
                "distance": 15000.0
            }
        }"#;

        #[derive(Deserialize)]
        struct RouteWrapper {
            route: Route,
        }

        let wrapper: RouteWrapper = serde_json::from_str(json).unwrap();
        assert_eq!(wrapper.route.id, 456);
        assert_eq!(wrapper.route.name.as_deref(), Some("Wrapped Route"));
        assert_eq!(wrapper.route.distance, Some(15000.0));
    }

    #[test]
    fn test_track_point_deserialization() {
        let json = r#"{
            "x": -122.4194,
            "y": 37.7749,
            "d": 1234.5,
            "e": 100.0,
            "S": 2,
            "R": 3
        }"#;

        let track_point: TrackPoint = serde_json::from_str(json).unwrap();
        assert_eq!(track_point.x, Some(-122.4194));
        assert_eq!(track_point.y, Some(37.7749));
        assert_eq!(track_point.d, Some(1234.5));
        assert_eq!(track_point.e, Some(100.0));
        assert_eq!(track_point.surface, Some(2));
        assert_eq!(track_point.highway, Some(3));
    }

    #[test]
    fn test_course_point_deserialization() {
        let json = r#"{
            "x": -122.5,
            "y": 37.8,
            "d": 5000.0,
            "n": "Water Stop",
            "t": "water"
        }"#;

        let course_point: CoursePoint = serde_json::from_str(json).unwrap();
        assert_eq!(course_point.x, Some(-122.5));
        assert_eq!(course_point.y, Some(37.8));
        assert_eq!(course_point.d, Some(5000.0));
        assert_eq!(course_point.n.as_deref(), Some("Water Stop"));
        assert_eq!(course_point.t.as_deref(), Some("water"));
    }

    #[test]
    fn test_route_with_nested_structures() {
        let json = r#"{
            "id": 999,
            "name": "Complex Route",
            "track_points": [
                {"x": -122.0, "y": 37.0, "d": 0.0},
                {"x": -122.1, "y": 37.1, "d": 100.0}
            ],
            "course_points": [
                {"id": 1, "n": "Start", "t": "generic"}
            ]
        }"#;

        let route: Route = serde_json::from_str(json).unwrap();
        assert_eq!(route.id, 999);
        assert!(route.track_points.is_some());
        assert_eq!(route.track_points.as_ref().unwrap().len(), 2);
        assert!(route.course_points.is_some());
        assert_eq!(route.course_points.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_photo_deserialization() {
        let json = r#"{
            "id": 111,
            "url": "https://example.com/photo.jpg",
            "thumbnail_url": "https://example.com/thumb.jpg",
            "caption": "Great view"
        }"#;

        let photo: Photo = serde_json::from_str(json).unwrap();
        assert_eq!(photo.id, 111);
        assert_eq!(photo.url.as_deref(), Some("https://example.com/photo.jpg"));
        assert_eq!(photo.caption.as_deref(), Some("Great view"));
    }
}