Skip to main content

garmin_cli/client/
api.rs

1//! Garmin Connect API client for authenticated requests
2//!
3//! This module provides a high-level client for making authenticated requests
4//! to the Garmin Connect API using OAuth2 bearer tokens.
5
6use bytes::Bytes;
7use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT};
8use reqwest::{multipart, Client, Response, StatusCode};
9use serde::de::DeserializeOwned;
10use std::path::Path;
11
12use crate::client::tokens::OAuth2Token;
13use crate::error::{GarminError, Result};
14
15/// User agent for Connect API requests
16const API_USER_AGENT: &str = "GCM-iOS-5.7.2.1";
17
18/// Garmin Connect API client
19#[derive(Clone)]
20pub struct GarminClient {
21    client: Client,
22    base_url: String,
23}
24
25impl GarminClient {
26    /// Create a new API client for the given domain
27    pub fn new(domain: &str) -> Self {
28        Self {
29            client: Client::builder()
30                .timeout(std::time::Duration::from_secs(30))
31                .build()
32                .expect("Failed to create HTTP client"),
33            base_url: format!("https://connectapi.{}", domain),
34        }
35    }
36
37    /// Create a new API client with a custom base URL (for testing)
38    #[doc(hidden)]
39    pub fn new_with_base_url(base_url: &str) -> Self {
40        Self {
41            client: Client::builder()
42                .timeout(std::time::Duration::from_secs(30))
43                .build()
44                .expect("Failed to create HTTP client"),
45            base_url: base_url.to_string(),
46        }
47    }
48
49    /// Build the full URL for a given path
50    fn build_url(&self, path: &str) -> String {
51        format!("{}{}", self.base_url, path)
52    }
53
54    /// Build headers with authorization
55    fn build_headers(&self, token: &OAuth2Token) -> HeaderMap {
56        let mut headers = HeaderMap::new();
57        headers.insert(USER_AGENT, HeaderValue::from_static(API_USER_AGENT));
58        headers.insert(
59            AUTHORIZATION,
60            HeaderValue::from_str(&token.authorization_header()).unwrap(),
61        );
62        headers
63    }
64
65    /// Make an authenticated GET request and return the response
66    pub async fn get(&self, token: &OAuth2Token, path: &str) -> Result<Response> {
67        let url = self.build_url(path);
68        let headers = self.build_headers(token);
69
70        let response = self
71            .client
72            .get(&url)
73            .headers(headers)
74            .send()
75            .await
76            .map_err(GarminError::Http)?;
77
78        self.handle_response_status(response).await
79    }
80
81    /// Make an authenticated GET request and deserialize JSON response
82    pub async fn get_json<T: DeserializeOwned>(
83        &self,
84        token: &OAuth2Token,
85        path: &str,
86    ) -> Result<T> {
87        let response = self.get(token, path).await?;
88        response.json().await.map_err(|e| {
89            GarminError::invalid_response(format!("Failed to parse JSON response: {}", e))
90        })
91    }
92
93    /// Make an authenticated POST request with JSON body
94    pub async fn post_json(
95        &self,
96        token: &OAuth2Token,
97        path: &str,
98        body: &serde_json::Value,
99    ) -> Result<serde_json::Value> {
100        let url = self.build_url(path);
101        let headers = self.build_headers(token);
102
103        let response = self
104            .client
105            .post(&url)
106            .headers(headers)
107            .json(body)
108            .send()
109            .await
110            .map_err(GarminError::Http)?;
111
112        let response = self.handle_response_status(response).await?;
113        response.json().await.map_err(|e| {
114            GarminError::invalid_response(format!("Failed to parse JSON response: {}", e))
115        })
116    }
117
118    /// Make an authenticated GET request and return raw bytes (for file downloads)
119    pub async fn download(&self, token: &OAuth2Token, path: &str) -> Result<Bytes> {
120        let response = self.get(token, path).await?;
121        response.bytes().await.map_err(GarminError::Http)
122    }
123
124    /// Upload a file using multipart form data
125    pub async fn upload(
126        &self,
127        token: &OAuth2Token,
128        path: &str,
129        file_path: &Path,
130    ) -> Result<serde_json::Value> {
131        let url = self.build_url(path);
132        let headers = self.build_headers(token);
133
134        // Read the file
135        let file_name = file_path
136            .file_name()
137            .and_then(|n| n.to_str())
138            .unwrap_or("activity.fit")
139            .to_string();
140
141        let file_bytes = tokio::fs::read(file_path)
142            .await
143            .map_err(|e| GarminError::invalid_response(format!("Failed to read file: {}", e)))?;
144
145        // Create multipart form
146        let part = multipart::Part::bytes(file_bytes)
147            .file_name(file_name)
148            .mime_str("application/octet-stream")
149            .map_err(|e| GarminError::invalid_response(format!("Invalid MIME type: {}", e)))?;
150
151        let form = multipart::Form::new().part("file", part);
152
153        let response = self
154            .client
155            .post(&url)
156            .headers(headers)
157            .multipart(form)
158            .send()
159            .await
160            .map_err(GarminError::Http)?;
161
162        let response = self.handle_response_status(response).await?;
163        response.json().await.map_err(|e| {
164            GarminError::invalid_response(format!("Failed to parse upload response: {}", e))
165        })
166    }
167
168    /// Handle response status codes and convert to errors
169    async fn handle_response_status(&self, response: Response) -> Result<Response> {
170        let status = response.status();
171
172        match status {
173            StatusCode::OK
174            | StatusCode::CREATED
175            | StatusCode::ACCEPTED
176            | StatusCode::NO_CONTENT => Ok(response),
177            StatusCode::UNAUTHORIZED => Err(GarminError::NotAuthenticated),
178            StatusCode::TOO_MANY_REQUESTS => Err(GarminError::RateLimited),
179            StatusCode::NOT_FOUND => {
180                let url = response.url().to_string();
181                Err(GarminError::NotFound(url))
182            }
183            _ => {
184                let status_code = status.as_u16();
185                let body = response.text().await.unwrap_or_default();
186                Err(GarminError::Api {
187                    status: status_code,
188                    message: body,
189                })
190            }
191        }
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn test_build_url() {
201        let client = GarminClient::new("garmin.com");
202        assert_eq!(
203            client.build_url("/activity-service/activity/123"),
204            "https://connectapi.garmin.com/activity-service/activity/123"
205        );
206    }
207
208    #[test]
209    fn test_client_creation() {
210        let client = GarminClient::new("garmin.com");
211        assert_eq!(client.base_url, "https://connectapi.garmin.com");
212    }
213}