summaryrefslogtreecommitdiff
path: root/src/strava.rs
blob: 6be54660c15699c90971c04bfb262b4b5d1f70ff (plain)
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
use crate::error::Error;
use chrono::serde::ts_seconds;
use chrono::DateTime;
use chrono::Utc;
use reqwest;
use serde::Deserialize;
use serde::Serialize;
use serde_json::from_value;
use serde_json::Value;

pub trait StravaApi {
    fn get<T: Serialize + ?Sized>(&self, method: &str, access_token: &str, parasm: &T) -> Result<Value, Error>;
}

pub struct StravaImpl {
    client: reqwest::blocking::Client,
    base_url: String,
}

impl StravaImpl {
    pub fn new() -> StravaImpl {
        StravaImpl {
            client: reqwest::blocking::Client::new(),
            base_url: "https://www.strava.com/api/v3".to_string(),
        }
    }
}

impl StravaApi for StravaImpl {
    fn get<T: Serialize + ?Sized>(&self, method: &str, access_token: &str,
                                  params: &T) -> Result<Value, Error> {
        let uri = format!("{}{}", self.base_url, method);
        let response = self.client.get(&uri)
            .bearer_auth(access_token)
            .query(params)
            .send()?;
        info!("StravaApi::get({}) returned {:?}", method, response);
        let json = response.json()?;
        Ok(json)
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct AthleteSummary {
    id: i64,
    username: String,
    firstname: String,
    lastname: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Token {
    #[serde(with = "ts_seconds")]
    pub expires_at: DateTime<Utc>,
    pub refresh_token: String,
    pub access_token: String,
    pub athlete: AthleteSummary,
}

pub fn exchange_token(client_id: &str, client_secret: &str, code: &str) -> Result<Token, Error> {
    let client = reqwest::blocking::Client::new();
    let params = [
        ("client_id", client_id),
        ("client_secret", client_secret),
        ("code", code),
    ];
    let uri = "https://www.strava.com/oauth/token";
    let req = client.post(uri).form(&params);
    let json: Value = req.send().map(|r| r.json())??;
    from_value(json).map_err(From::from)
}