-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.rs
198 lines (178 loc) · 6.12 KB
/
client.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
use std::{cell::LazyCell, str::FromStr, sync::Arc};
use crate::{error::Error, shapes::GetAccessTokenResponse, UserDetailResponse};
use reqwest::Client as ReqwestClient;
use tokio::runtime::{Builder as RuntimeBuilder, Runtime};
use url::Url;
pub const BASE_URL: LazyCell<Url> = LazyCell::new(|| Url::from_str("https://github.com").unwrap());
pub const API_BASE_URL: LazyCell<Url> =
LazyCell::new(|| Url::from_str("https://api.github.com").unwrap());
/// A client for interacting with Github programmatically.
#[derive(Clone)]
pub struct GithubClient {
http_client: ReqwestClient,
/// The github client id. This one gets exposed publicly.
client_id: String,
/// The secret key that is known only to us and Github. Keep this
/// one private!
client_secret: String,
/// The base url that authorization urls are based on.
base_url: Url,
/// The base url that the client uses to communicate with Github.
api_base_url: Url,
}
#[derive(Debug, Clone)]
pub struct GithubSyncClient {
client: GithubClient,
rt: Arc<Runtime>,
}
impl GithubClient {
/// Create a new Github client configured to use the public Github
/// API.
pub fn new(client_id: &str, client_secret: &str) -> Result<Self, Error> {
Self::new_with_urls(
client_id,
client_secret,
BASE_URL.clone(),
API_BASE_URL.clone(),
)
}
/// Create a new Github client configured to use arbitrary API
/// endpoints.
///
/// See also [`crate::fakehub::Fakehub::add_client`].
pub fn new_with_urls(
client_id: &str,
client_secret: &str,
base_url: Url,
api_base_url: Url,
) -> Result<Self, Error> {
Ok(Self {
http_client: reqwest::ClientBuilder::new()
.user_agent("Rust/request/ghoauth")
.build()?,
client_id: client_id.to_owned(),
client_secret: client_secret.to_owned(),
base_url,
api_base_url,
})
}
/// The URL to send a user to in order to start the OAuth workflow.
pub fn authorization_url(&self) -> String {
format!(
"{}/#/oauth/authorize?client_id={}",
self.base_url, self.client_id
)
}
/// Exchange a login code for an access token.
pub async fn get_access_token(&self, code: &str) -> Result<GetAccessTokenResponse, Error> {
let params = [
("client_id", self.client_id.as_str()),
("client_secret", self.client_secret.as_str()),
("code", code),
];
Ok(self
.http_client
.post(self.base_url.join("login/oauth/access_token")?)
.form(¶ms)
.header("Accept", "application/json")
.send()
.await?
.json()
.await?)
}
/// Use an access token to query the user this token is associated with.
pub async fn get_user_detail(&self, access_token: &str) -> Result<UserDetailResponse, Error> {
Ok(self
.http_client
.get(self.api_base_url.join("user")?)
.header("Authorization", format!("token {}", access_token))
.header("Accept", "application/json")
.send()
.await?
.json()
.await?)
}
/// Get a user's public profile.
pub async fn get_user_detail_public(
&self,
username: &str,
) -> Result<UserDetailResponse, Error> {
Ok(self
.http_client
.get(self.api_base_url.join(&format!("user/{}", username))?)
.header("Accept", "application/json")
.send()
.await?
.json()
.await?)
}
}
impl std::fmt::Debug for GithubClient {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"GithubClient {{ http_client: {:?}, client_id: {}, \
client_secret: REDACTED }}",
self.http_client, self.client_id,
)
}
}
impl GithubSyncClient {
/// Create a new Github client configured to use the public Github
/// API.
pub fn new(client_id: &str, client_secret: &str) -> Result<Self, Error> {
Ok(Self {
client: GithubClient::new(client_id, client_secret)?,
rt: create_current_thread_rt(),
})
}
/// Create a new Github client configured to use arbitrary API
/// endpoints.
///
/// See also [`crate::fakehub::Fakehub::add_client`].
pub fn new_with_urls(
client_id: &str,
client_secret: &str,
base_url: Url,
api_base_url: Url,
) -> Result<Self, Error> {
Ok(Self {
client: GithubClient::new_with_urls(client_id, client_secret, base_url, api_base_url)?,
rt: create_current_thread_rt(),
})
}
/// Create a new synchronous client by wrapping an existing
/// asynchronous client.
pub fn new_from_async_client(client: GithubClient) -> Self {
Self {
client,
rt: create_current_thread_rt(),
}
}
/// The URL to send a user to in order to start the OAuth workflow.
pub fn authorization_url(&self) -> String {
self.client.authorization_url()
}
/// Exchange a login code for an access token.
pub fn get_access_token(&self, code: &str) -> Result<GetAccessTokenResponse, Error> {
self.rt.block_on(self.client.get_access_token(code))
}
/// Use an access token to query the user this token is associated with.
pub fn get_user_detail(&self, access_token: &str) -> Result<UserDetailResponse, Error> {
self.rt.block_on(self.client.get_user_detail(access_token))
}
/// Get a user's public profile.
pub fn get_user_detail_public(&self, username: &str) -> Result<UserDetailResponse, Error> {
self.rt
.block_on(self.client.get_user_detail_public(username))
}
}
fn create_current_thread_rt() -> Arc<Runtime> {
Arc::new(
RuntimeBuilder::new_current_thread()
.enable_io()
.enable_time()
.build()
.expect("Cannot construct current-thread runtime"),
)
}