tribufu_api/
lib.rs

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
// Copyright (c) Tribufu. All Rights Reserved.

use alnilam_consts::TARGET_TRIPLE;
use mintaka_error::{Error, Result};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use reqwest::Client;
use std::env;
use tribufu_constants::VERSION;
use tribufu_types::games::Game;
use tribufu_types::oauth2::{OAuth2GrantType, OAuth2TokenRequest, OAuth2TokenResponse};
use tribufu_types::users::*;

pub enum Credentials {
    Anonymous,
    ApiKey {
        api_key: String,
    },
    Client {
        client_id: u64,
        client_secret: String,
    },
}

pub enum Token {
    ApiKey {
        api_key: String,
    },
    Basic {
        basic_token: String,
    },
    Bearer {
        access_token: String,
        refresh_token: Option<String>,
    },
}

pub struct TribufuApi {
    base_url: String,
    credentials: Credentials,
    token: Option<Token>,
    http: Client,
}

impl Default for TribufuApi {
    fn default() -> Self {
        Self::new(Credentials::Anonymous)
    }
}

impl TribufuApi {
    const TRIBUFU_API_URL: &'static str = "https://api.tribufu.com";

    pub fn new(credentials: Credentials) -> Self {
        let http = Client::builder()
            .user_agent(Self::user_agent())
            .default_headers(Self::default_headers())
            .build()
            .unwrap();

        Self {
            base_url: Self::get_base_url(),
            credentials,
            token: None,
            http,
        }
    }

    pub fn debug_enabled(&self) -> bool {
        return cfg!(debug_assertions);
    }

    #[inline]
    fn user_agent() -> String {
        format!(
            "Tribufu/{} (+https://api.tribufu.com; {})",
            VERSION, TARGET_TRIPLE
        )
    }

    #[inline]
    fn default_headers() -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert("X-Tribufu-Language", HeaderValue::from_static("rust"));
        headers.insert("X-Tribufu-Version", HeaderValue::from_static(VERSION));
        headers
    }

    fn get_base_url() -> String {
        if cfg!(debug_assertions) {
            return env::var("TRIBUFU_API_URL")
                .unwrap_or_else(|_| Self::TRIBUFU_API_URL.to_string());
        }

        Self::TRIBUFU_API_URL.to_string()
    }

    pub fn with_api_key(api_key: String) -> Self {
        Self::new(Credentials::ApiKey { api_key })
    }

    pub fn with_client(client_id: u64, client_secret: String) -> Self {
        Self::new(Credentials::Client {
            client_id,
            client_secret,
        })
    }

    pub fn with_api_key_from_env() -> Option<Self> {
        if let Ok(api_key) = env::var("TRIBUFU_API_KEY") {
            Some(Self::with_api_key(api_key))
        } else {
            None
        }
    }

    pub fn with_client_from_env() -> Option<Self> {
        let client_id = env::var("TRIBUFU_CLIENT_ID");
        let client_secret = env::var("TRIBUFU_CLIENT_SECRET");

        if let (Ok(client_id), Ok(client_secret)) = (client_id, client_secret) {
            Some(Self::with_client(client_id.parse().unwrap(), client_secret))
        } else {
            None
        }
    }

    pub fn set_anonymous(&mut self) {
        self.credentials = Credentials::Anonymous;
    }

    pub fn set_api_key(&mut self, api_key: String) {
        self.credentials = Credentials::ApiKey { api_key };
    }

    pub fn set_clients(&mut self, client_id: u64, client_secret: String) {
        self.credentials = Credentials::Client {
            client_id,
            client_secret,
        };
    }

    pub fn set_basic_token(&mut self, basic_token: String) {
        self.token = Some(Token::Basic { basic_token });
    }

    pub fn set_bearer_token(&mut self, access_token: String, refresh_token: Option<String>) {
        self.token = Some(Token::Bearer {
            access_token,
            refresh_token,
        });
    }

    #[inline]
    fn headers(&self) -> HeaderMap {
        let mut headers = Self::default_headers();

        match &self.token {
            Some(token) => match token {
                Token::ApiKey { api_key } => {
                    headers.insert(
                        AUTHORIZATION,
                        HeaderValue::from_str(&format!("ApiKey {}", api_key)).unwrap(),
                    );
                }
                Token::Basic { basic_token } => {
                    headers.insert(
                        AUTHORIZATION,
                        HeaderValue::from_str(&format!("Basic {}", basic_token)).unwrap(),
                    );
                }
                Token::Bearer { access_token, .. } => {
                    headers.insert(
                        AUTHORIZATION,
                        HeaderValue::from_str(&format!("Bearer {}", access_token)).unwrap(),
                    );
                }
            },
            None => {}
        }

        headers
    }

    pub async fn get_token_with_code(
        &mut self,
        code: String,
        client_id: u64,
        client_secret: String,
    ) -> Result<OAuth2TokenResponse> {
        self.get_oauth_token(
            OAuth2GrantType::AuthorizationCode,
            Some(code),
            client_id,
            client_secret,
            None,
            None,
        )
        .await
    }

    pub async fn get_token_from_password(
        &mut self,
        username: String,
        password: String,
        client_id: u64,
        client_secret: String,
    ) -> Result<OAuth2TokenResponse> {
        self.get_oauth_token(
            OAuth2GrantType::Password,
            Some(password),
            client_id,
            client_secret,
            None,
            Some(username),
        )
        .await
    }

    pub async fn get_token_from_passkey(
        &mut self,
        username: String,
        passkey: String,
        client_id: u64,
        client_secret: String,
    ) -> Result<OAuth2TokenResponse> {
        self.get_oauth_token(
            OAuth2GrantType::Passkey,
            Some(passkey),
            client_id,
            client_secret,
            None,
            Some(username),
        )
        .await
    }

    pub async fn refresh_token(
        &mut self,
        refresh_token: String,
        client_id: u64,
        client_secret: String,
    ) -> Result<OAuth2TokenResponse> {
        self.get_oauth_token(
            OAuth2GrantType::RefreshToken,
            Some(refresh_token),
            client_id,
            client_secret,
            None,
            None,
        )
        .await
    }

    pub async fn get_client_token(
        &mut self,
        client_id: u64,
        client_secret: String,
    ) -> Result<OAuth2TokenResponse> {
        self.get_oauth_token(
            OAuth2GrantType::ClientCredentials,
            None,
            client_id,
            client_secret,
            None,
            None,
        )
        .await
    }

    pub async fn get_server_token(
        &mut self,
        server_id: u64,
        client_id: u64,
        client_secret: String,
    ) -> Result<OAuth2TokenResponse> {
        self.get_oauth_token(
            OAuth2GrantType::ClientCredentials,
            None,
            client_id,
            client_secret,
            Some("server_id".to_string()),
            Some(server_id.to_string()),
        )
        .await
    }

    async fn get_oauth_token(
        &self,
        grant_type: OAuth2GrantType,
        grant_value: Option<String>,
        client_id: u64,
        client_secret: String,
        subject_key: Option<String>,
        subject_value: Option<String>,
    ) -> Result<OAuth2TokenResponse> {
        let code = if grant_type == OAuth2GrantType::AuthorizationCode {
            grant_value.clone()
        } else {
            None
        };

        let refresh_token = if grant_type == OAuth2GrantType::RefreshToken {
            grant_value.clone()
        } else {
            None
        };

        let mut require_username = false;

        let password = if grant_type == OAuth2GrantType::Password {
            require_username = true;
            grant_value.clone()
        } else {
            None
        };

        let passkey = if grant_type == OAuth2GrantType::Passkey {
            require_username = true;
            grant_value.clone()
        } else {
            None
        };

        let username = if require_username && subject_value.is_some() {
            subject_value.clone()
        } else {
            None
        };

        let request_body = OAuth2TokenRequest {
            grant_type,
            code,
            refresh_token,
            username,
            password,
            passkey,
            client_id: Some(client_id.to_string()),
            client_secret: Some(client_secret.clone()),
            redirect_uri: None,
        };

        let params = if subject_key.is_some() && subject_value.is_some() {
            format!("?{}={}", subject_key.unwrap(), subject_value.unwrap())
        } else {
            "".to_string()
        };

        let url = format!("{}/v1/oauth2/token{}", self.base_url, params);
        let headers = self.headers();
        let response = self
            .http
            .post(url)
            .headers(headers)
            .form(&request_body)
            .send()
            .await?;

        if response.status() != 200 {
            return Err(Error::msg(format!(
                "Failed to get token: {}",
                response.status()
            )));
        }

        Ok(response.json().await?)
    }

    pub async fn get_user_info(&self) -> Result<User> {
        let url = format!("{}/v1/oauth2/userinfo", self.base_url);
        let headers = self.headers();
        let response = self.http.get(url).headers(headers).send().await?;

        Ok(response.json().await?)
    }

    pub async fn get_games(&self, page: Option<u32>) -> Result<Vec<Game>> {
        let page = page.unwrap_or(1);
        let url = format!("{}/v1/packages?page={}", self.base_url, page);
        let headers = self.headers();
        let response = self.http.get(url).headers(headers).send().await?;

        Ok(response.json().await?)
    }

    pub async fn get_game(&self, id: u64) -> Result<Game> {
        let url = format!("{}/v1/packages/{}", self.base_url, id);
        let headers = self.headers();
        let response = self.http.get(url).headers(headers).send().await?;

        Ok(response.json().await?)
    }
}