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
#[cfg(feature = "multi")]
use parking_lot::Mutex;
use std::time::Duration;
use reqwest::Client;
use serde_json::{json, Value};
use url::Url;
use crate::constants::*;
use crate::raw_types::RawTermListItem;
use crate::types::{Term, WrapperError};
use crate::wrapper::request_builder::WrapperTermRequestBuilder;
use crate::wrapper::request_data::{ReqType, ReqwestWebRegClientData, WebRegWrapperData};
use crate::wrapper::wrapper_builder::WebRegWrapperBuilder;
use crate::wrapper::ww_helper::{associate_term_helper, process_get_result};
use crate::{types, util};
pub mod input_types;
pub mod request_builder;
mod request_data;
pub mod requester_term;
pub mod wrapper_builder;
mod ww_helper;
/// A wrapper for [UCSD's WebReg](https://act.ucsd.edu/webreg2/start). For more information,
/// please see the README.
pub struct WebRegWrapper {
data: WebRegWrapperData,
}
impl<'a> WebRegWrapper {
/// Creates a new instance of the `WebRegWrapper` with the specified `Client` and session
/// cookies. A default timeout and user agent will be provided. To override these, use
/// [`WrapperBuilder`].
///
/// After providing your cookies, you should ensure that each term is "bound" to your cookies.
/// This can be done in several ways:
/// - Calling `associate_term` with the specified term you want to use.
/// - Calling `register_all_terms` to bind all terms to your cookie.
/// - Manually selecting a term from WebReg (this is effectively what `associate_term` does).
///
/// You are expected to provide a
/// [`reqwest::Client`](https://docs.rs/reqwest/latest/reqwest/struct.Client.html). This
/// can be as simple as the default client (`Client::new()`), or can be customized to suit
/// your needs. Note that the timeout set on the `Client` will be ignored in favor of the
/// `timeout` field here.
///
/// # Parameters
/// - `client`: The `reqwest` client. You are able to override this on a per-request basis.
/// - `cookies`: The cookies from your session of WebReg. You are able to override this on
/// a per-request basis.
///
/// # Returns
/// The new instance of the `WebRegWrapper`.
///
/// # Example
/// ```rust,no_run
/// use reqwest::Client;
/// use webweg::wrapper::WebRegWrapper;
///
/// let client = Client::new();
/// let wrapper = WebRegWrapper::new(client, "my cookies".to_string());
/// ```
pub fn new(client: Client, cookies: impl Into<String>) -> Self {
Self {
data: WebRegWrapperData {
#[cfg(feature = "multi")]
cookies: Mutex::new(cookies.into()),
#[cfg(not(feature = "multi"))]
cookies: cookies.into(),
client,
timeout: Duration::from_secs(30),
user_agent: MY_USER_AGENT.to_owned(),
close_after_request: false,
},
}
}
/// Creates a new builder that can be used to construct a `WebRegWrapper`. This is the
/// preferred method for creating a wrapper for more complex situations.
///
/// # Returns
/// The builder.
pub fn builder() -> WebRegWrapperBuilder {
WebRegWrapperBuilder::new()
}
/// Sets the cookies to the new, specified cookies.
///
/// This might be useful if you want to use the existing wrapper but need to change the
/// cookies.
///
/// # Parameters
/// - `new_cookies`: The new cookies.
#[cfg(not(feature = "multi"))]
pub fn set_cookies(&mut self, new_cookies: impl Into<String>) {
self.data.cookies = new_cookies.into();
}
/// Sets the cookies to the new, specified cookies.
///
/// This might be useful if you want to use the existing wrapper but need to change the
/// cookies.
///
/// Note that a mutex is internally used to store the cookies.
///
/// # Parameters
/// - `new_cookies`: The new cookies.
#[cfg(feature = "multi")]
pub fn set_cookies(&self, new_cookies: impl Into<String>) {
let mut cookies = self.data.cookies.lock();
*cookies = new_cookies.into();
}
/// Checks if the current WebReg instance is valid. Specifically, this will check if you
/// are logged in.
///
/// # Returns
/// `true` if the instance is valid and `false` otherwise.
///
/// # Example
/// ```rust,no_run
/// use reqwest::Client;
/// use webweg::wrapper::WebRegWrapper;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let wrapper = WebRegWrapper::new(Client::new(), "my cookies".to_string());
/// assert!(wrapper.is_valid().await);
/// # }
/// ```
pub async fn is_valid(&self) -> bool {
self.ping_server().await
}
/// Gets the name of the owner associated with this account.
///
/// # Returns
/// The name of the person, or an empty string if the cookies that were given were invalid.
///
/// # Example
/// ```rust,no_run
/// use reqwest::Client;
/// use webweg::wrapper::WebRegWrapper;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let wrapper = WebRegWrapper::new(Client::new(), "my cookies".to_string());
/// assert_eq!("Your name here", wrapper.get_account_name().await.unwrap());
/// # }
/// ```
pub async fn get_account_name(&self) -> types::Result<String> {
if !self.is_valid().await {
return Err(WrapperError::SessionNotValid);
}
Ok(self
.data
.req(ReqType::Get(ACC_NAME))
.send()
.await?
.text()
.await?)
}
/// Registers all terms to your current session so that you can freely
/// access any terms using this wrapper.
///
/// By default, when you provide brand new WebReg cookies, it won't be
/// associated with any terms. In order to actually use your cookies to
/// make requests, you need to tell WebReg that you want to "associate"
/// your cookies with a particular term.
///
/// # Returns
/// A result, where nothing is returned if everything went well and an
/// error is returned if something went wrong.
///
/// # Example
/// ```rust,no_run
/// use reqwest::Client;
/// use webweg::wrapper::WebRegWrapper;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let wrapper = WebRegWrapper::new(Client::new(), "my cookies".to_string());
/// assert!(wrapper.register_all_terms().await.is_ok());
/// # }
/// ```
pub async fn register_all_terms(&self) -> types::Result<()> {
let terms = self.get_all_terms().await?;
for term in terms {
self.associate_term(term.term_code).await?;
}
Ok(())
}
/// Gets all terms available on WebReg.
///
/// # Returns
/// A vector of term objects, with each object containing the term name and
/// term ID. If an error occurs, you will get that instead.
///
/// # Example
/// ```rust,no_run
/// use reqwest::Client;
/// use webweg::wrapper::WebRegWrapper;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let wrapper = WebRegWrapper::new(Client::new(), "my cookies".to_string());
/// assert!(wrapper.get_all_terms().await.unwrap().len() > 0);
/// # }
/// ```
pub async fn get_all_terms(&self) -> types::Result<Vec<Term>> {
let url = Url::parse_with_params(
TERM_LIST,
&[("_", util::get_epoch_time().to_string().as_str())],
)?;
process_get_result::<Vec<RawTermListItem>>(self.data.req(ReqType::Get(url)).send().await)
.await
.map(|raw_term_list| {
raw_term_list
.into_iter()
.map(
|RawTermListItem {
seq_id, term_code, ..
}| Term { seq_id, term_code },
)
.collect()
})
}
/// Associates a particular term to this current instance of the wrapper.
///
/// After calling this function, you should be able to make requests to
/// WebReg with the specified term.
///
/// Note that WebReg doesn't actually do any validation with your input,
/// so you should ensure that the term you want to use is actually valid.
///
/// # Parameters
/// - `term`: The term to associate with your session cookies.
///
/// # Returns
/// A result, where nothing is returned if everything went well and an
/// error is returned if something went wrong.
///
/// # Example
/// ```rust,no_run
/// use reqwest::Client;
/// use webweg::wrapper::WebRegWrapper;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let wrapper = WebRegWrapper::new(Client::new(), "my cookies".to_string());
/// // Associate this wrapper with S123, S223, FA23.
/// _ = wrapper.associate_term("S123").await;
/// _ = wrapper.associate_term("S223").await;
/// _ = wrapper.associate_term("FA23").await;
/// // We should now be able to use those three terms.
/// # }
/// ```
pub async fn associate_term(&self, term: impl AsRef<str>) -> types::Result<()> {
associate_term_helper(&self.data, term).await
}
/// Pings the WebReg server. Presumably, this is the endpoint that is used to ensure that
/// your (authenticated) session is still valid. In other words, if this isn't called, I
/// assume that you will be logged out, rendering your cookies invalid.
///
/// # Returns
/// `true` if the ping was successful and `false` otherwise.
pub async fn ping_server(&self) -> bool {
let res = self
.data
.req(ReqType::Get(format!(
"{}?_={}",
PING_SERVER,
util::get_epoch_time()
)))
.send()
.await;
if let Ok(r) = res {
let text = r.text().await.unwrap_or_else(|_| {
json!({
"SESSION_OK": false
})
.to_string()
});
let json: Value = serde_json::from_str(&text).unwrap_or_default();
// Use of unwrap here is safe since we know that there is a boolean value beforehand
json["SESSION_OK"].is_boolean() && json["SESSION_OK"].as_bool().unwrap()
} else {
false
}
}
/// Returns a request builder that can be used to customize any settings for a specific
/// request only.
///
/// # Parameters
/// - `term`: The term to use for this request.
///
/// # Returns
/// A builder allowing you to customize any settings for your request, like the cookies,
/// client, term, user agent, and timeout.
pub fn req(&'a self, term: &'a str) -> WrapperTermRequestBuilder {
WrapperTermRequestBuilder::new_request(&self.data, term)
}
}