summaryrefslogtreecommitdiff
path: root/src/strava.rs
blob: ff59c66123f7ca7ecb4280e91f54637bf23b7d23 (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
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
use crate::error;
use crate::error::Error;
use crate::models;
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;

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

impl Token {
    pub fn update_model(&self, out: &mut models::StravaToken) {
        out.expires_at = self.expires_at.clone();
        out.refresh_token = self.refresh_token.clone();
        out.access_token = self.access_token.clone();
    }
}

impl From<&models::StravaToken> for Token {
    fn from(t: &models::StravaToken) -> Token {
        Token {
            expires_at: t.expires_at,
            refresh_token: t.refresh_token.clone(),
            access_token: t.access_token.clone(),
        }
    }
}

pub trait StravaApi: Sync + Send {
    fn get(
        &self,
        method: &str,
        access_token: &str,
        params: &[(&str, &str)],
    ) -> Result<Value, Error>;

    fn refresh_token(
        &self,
        token: &Token) -> Result<Token, Error>;
}

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

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

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

        if !status.is_success() {
            return Err(From::from(error::StravaApiError::new(status, json)));
        }
        Ok(json)
    }

    fn refresh_token(
        &self,
        token: &Token) -> Result<Token, Error> {
        let uri = format!("{}{}{}", self.base_url, self.api_url, "/oauth/token");
        let params = [
            ("client_id", self.client_id.as_str()),
            ("client_secret", self.client_secret.as_str()),
            ("grant_type", "refresh_token"),
            ("refresh_token", token.refresh_token.as_str()),
        ];
        let response = self
            .client
            .post(&uri)
            .form(&params)
            .send()?;
        info!("StravaApi::refresh_token returned {:?}", response);
        let status = response.status();
        let json: Value = response.json()?;

        if !status.is_success() {
            return Err(From::from(error::StravaApiError::new(status, json)));
        }
        from_value(json).map_err(From::from)
    }
}

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)
}