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
use serde::{Deserialize, Serialize};
use std::{convert::TryInto, io, sync::Arc};
use tokio::sync;
use twitch_oauth2::TwitchToken;
pub mod channel;
pub mod clips;
pub mod moderation;
pub mod streams;
pub mod users;
pub use twitch_oauth2::Scope;
#[derive(Clone)]
pub struct HelixClient {
token: Arc<sync::RwLock<Box<dyn TwitchToken + Send + Sync>>>,
client: reqwest::Client,
}
impl HelixClient {
pub fn new<T>(token: Box<T>) -> HelixClient
where T: TwitchToken + Sized + Send + Sync + 'static {
let client = reqwest::Client::new();
HelixClient {
token: Arc::new(sync::RwLock::new(token)),
client,
}
}
pub fn clone_client(&self) -> reqwest::Client { self.client.clone() }
pub async fn monitor_expire(&self) -> Option<tokio::time::Delay> {
self.token()
.await
.as_ref()
.expires()
.map(tokio::time::Instant::from_std)
.map(tokio::time::delay_until)
}
pub async fn token(&self) -> sync::RwLockReadGuard<'_, Box<dyn TwitchToken + Send + Sync>> {
self.token.read().await
}
pub async fn validate_token(
&self,
) -> Result<twitch_oauth2::ValidatedToken, twitch_oauth2::ValidationError> {
let t = self.token().await;
t.validate_token().await
}
pub async fn refresh_token(&self) -> Result<(), twitch_oauth2::RefreshTokenError> {
let mut token = self.token.write().await;
token.as_mut().refresh_token().await?;
Ok(())
}
#[allow(clippy::needless_doctest_main)]
pub async fn req_get<R, D>(&self, request: R) -> Result<Response<R, D>, RequestError>
where
R: Request<Response = D> + Request + RequestGet,
D: serde::de::DeserializeOwned, {
#[derive(PartialEq, Deserialize, Debug)]
struct InnerResponse<D> {
data: Vec<D>,
#[serde(default)]
pagination: Pagination,
}
#[derive(Deserialize, Clone, Debug)]
pub struct HelixRequestError {
error: String,
status: u16,
message: String,
}
let url = url::Url::parse(&format!(
"{}{}?{}",
crate::TWITCH_HELIX_URL,
<R as Request>::PATH,
request.query()?
))?;
let token = self.token().await;
let req = self
.client
.get(url.clone())
.header("Client-ID", token.client_id().as_str())
.bearer_auth(token.token().secret())
.send()
.await?;
let text = req.text().await?;
if let Ok(HelixRequestError {
error,
status,
message,
}) = serde_json::from_str::<HelixRequestError>(&text)
{
return Err(RequestError::HelixRequestError {
error,
status: status
.try_into()
.unwrap_or_else(|_| reqwest::StatusCode::BAD_REQUEST),
message,
url,
});
}
let response: InnerResponse<D> = serde_json::from_str(&text)?;
Ok(Response {
data: response.data,
pagination: response.pagination,
request,
})
}
}
#[async_trait::async_trait]
pub trait Request: serde::Serialize {
const PATH: &'static str;
const SCOPE: &'static [twitch_oauth2::Scope];
const OPT_SCOPE: &'static [twitch_oauth2::Scope] = &[];
type Response;
fn query(&self) -> Result<String, serde_urlencoded::ser::Error> {
serde_urlencoded::to_string(&self)
}
}
pub trait RequestPut: Request {}
pub trait RequestGet: Request {}
#[derive(PartialEq, Debug)]
pub struct Response<R, D>
where R: Request<Response = D> {
pub data: Vec<D>,
pub pagination: Pagination,
pub request: R,
}
impl<R, D> Response<R, D>
where
R: Request<Response = D> + Clone + Paginated + RequestGet,
D: serde::de::DeserializeOwned,
{
pub async fn get_next(
self,
client: &HelixClient,
) -> Result<Option<Response<R, D>>, RequestError>
{
let mut req = self.request.clone();
if let Some(ref cursor) = self.pagination.cursor {
req.set_pagination(cursor.clone());
client.req_get(req).await.map(Some)
} else {
Ok(None)
}
}
}
pub trait Paginated {
fn set_pagination(&mut self, cursor: Cursor);
}
#[derive(PartialEq, Deserialize, Serialize, Debug, Clone, Default)]
pub struct Pagination {
#[serde(default)]
cursor: Option<Cursor>,
}
pub type Cursor = String;
#[allow(missing_docs)]
#[derive(thiserror::Error, Debug)]
pub enum RequestError {
#[error("url could not be parsed")]
UrlParseError(#[from] url::ParseError),
#[error("io error")]
IOError(#[from] io::Error),
#[error("deserialization failed")]
DeserializeError(#[from] serde_json::Error),
#[error("Could not serialize request to query")]
QuerySerializeError(#[from] serde_urlencoded::ser::Error),
#[error("request failed from reqwests side")]
RequestError(#[from] reqwest::Error),
#[error("no pagination found")]
NoPage,
#[error("something happened")]
Other,
#[error(
"helix returned error {status:?} - {error} when calling `{url}` with message: {message}"
)]
HelixRequestError {
error: String,
status: reqwest::StatusCode,
message: String,
url: url::Url,
},
}
pub fn repeat_query(name: &str, items: &[String]) -> String {
let mut s = String::new();
for (idx, item) in items.iter().enumerate() {
s.push_str(&format!("{}={}", name, item));
if idx + 1 != items.len() {
s.push_str("&")
}
}
s
}