classcharts 1.0.5

Unoffical classcharts library for rust.
Documentation
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::Deserialize;
use std::{borrow::Cow, string::FromUtf8Error};
use thiserror::Error;

use reqwest::{header::ToStrError, IntoUrl, RequestBuilder, Response};

use crate::{api::student::StudentInfoData, new_params};

#[derive(Debug)]
pub struct Client {
    pub session_id: String,
    pub student_id: String,
    reqwest_client: reqwest::Client,
    base_url: String,
    auth_cookies: String,
    last_session_id_updated: DateTime<Utc>,
}

#[derive(Deserialize, Debug)]
pub struct SessionCookie {
    session_id: String,
}

#[derive(Deserialize, Debug)]
pub struct CCStatusResponse {
    pub error: Option<String>,
    pub success: usize,
}

#[derive(Deserialize, Debug)]
pub struct SuccessResponse<Data, Meta> {
    pub data: Data,
    pub meta: Meta,
}

#[derive(Error, Debug)]
pub enum ClientCreationError {
    #[error(
        "Unauthenticated, either your code or date of birth is wrong. No cookies were provided."
    )]
    AuthenticationError,

    #[error("Failed to send the API request or create the reqwest client")]
    ClientError(#[from] reqwest::Error),

    #[error("Cookie cannot not be parsed")]
    CookieParsingError(#[from] serde_json::Error),

    #[error("Session cookie does not exist on server returned cookies")]
    MissingSesssionCookie(()),

    #[error("Could not parse header as a string")]
    StringParseError(#[from] ToStrError),

    #[error("Failed to get student info, error: {0}")]
    ApiRequestError(#[from] ErrorResponse),

    #[error("Failed to decode the cookie")]
    StringDecodingError(#[from] FromUtf8Error),
}

#[async_trait]
pub trait CCParser {
    async fn cc_parse(self) -> Result<String, ErrorResponse>;
}

#[derive(thiserror::Error, Debug)]
pub enum ErrorResponse {
    #[error("Failed to process the request")]
    GenericClientError(#[from] reqwest::Error),

    #[error("Failed to parse the text response")]
    TextParsingError(#[source] reqwest::Error),

    #[error("Could not parse the json response")]
    SerdeJsonParsingError(#[from] serde_json::Error),

    #[error("ClassCharts returned the error code: {0}")]
    ClassChartsStatusError(usize),

    #[error("ClassCharts returned the error code: {0} and message {1}")]
    ClassChartsError(usize, String),
}

#[derive(Deserialize, Debug)]
pub struct SessionMeta {
    pub session_id: String,
}

pub type Session = SuccessResponse<StudentInfoData, SessionMeta>;

#[async_trait]
impl CCParser for Response {
    /// Parses a reqwest::Response against ClassCharts API "spec".
    /// If ClassCharts does not return a `{ success: 1 }` then it will return:
    /// ErrorResponse::ClassChartsError or ErrorResponse::ClassChartsStatusError
    /// Returns the text so you can parse it with serde_json for the specific endpoint.
    ///
    /// Example:
    ///
    /// ```ignore
    /// let sample_request = reqwest::get("some classcharts endpoint").send().await?;
    /// let text = sample_reqest.cc_parse().await?;
    ///
    /// // json parsing logic using `text`
    /// let json = ...
    /// ```
    async fn cc_parse(mut self) -> Result<String, ErrorResponse> {
        let text = self
            .text()
            .await
            .map_err(ErrorResponse::TextParsingError)?;

        let json = serde_json::from_str::<CCStatusResponse>(&text)?;

        if json.success != 1 {
            if let Some(error) = json.error {
                return Err(ErrorResponse::ClassChartsError(json.success, error));
            } else {
                return Err(ErrorResponse::ClassChartsStatusError(json.success));
            }
        }

        return Ok(text);
    }
}

impl Client {
    /// Builds a get reqwest, injecting ClassCharts Authorization cookies and headers. 
    /// The url is formed by appending `/apiv2student` to the `base_url` set on the client and then
    /// appending the path you set onto that.
    /// 
    /// Example:
    /// ```ignore
    /// let request = client
    ///     .build_get("/endpoint")
    ///     .await?
    ///     .send()
    ///     .await?;
    /// ```
    ///
    /// For `POST` requests use `.build_post`.
    pub async fn build_get<P>(&mut self, path: P) -> Result<RequestBuilder, ErrorResponse>
    where
        P: IntoUrl + std::fmt::Display,
    {
        if (self.last_session_id_updated.time() - Utc::now().time()).num_minutes() > 3 {
            self.get_new_session_id().await?;
        }

        return Ok(self
            .reqwest_client
            .get(format!("{}/apiv2student{}", self.base_url, path))
            .header("Cookie", &self.auth_cookies)
            .header("Authorization", format!("Basic {}", self.session_id)));
    }

    /// Builds a post reqwest, injecting ClassCharts Authorization cookies and headers. 
    /// The url is formed by appending `/apiv2student` to the `base_url` set on the client and then
    /// appending the path you set onto that.
    /// 
    /// Example:
    /// ```ignore
    /// let request = client
    ///     .build_post("/endpoint")
    ///     .await?
    ///     .send()
    ///     .await?;
    /// ```
    ///
    /// For `GET` requests use `.build_post`.
    pub async fn build_post<P>(&mut self, path: P) -> Result<RequestBuilder, ErrorResponse>
    where
        P: IntoUrl + std::fmt::Display,
    {
        if (self.last_session_id_updated.time() - Utc::now().time()).num_minutes() > 3 {
            self.get_new_session_id().await?;
        }

        return Ok(self
            .reqwest_client
            .post(format!("{}/apiv2student{}", self.base_url, path))
            .header("Cookie", &self.auth_cookies)
            .header("Authorization", format!("Basic {}", self.session_id)));
    }

    /// Get's a new `session_id` from ClassCharts. It does two things:
    /// - Returns this id 
    /// - Sets the `session_id` and `last_session_id_updated` properties on self.
    pub async fn get_new_session_id(&mut self) -> Result<String, ErrorResponse> {
        let params = new_params!("include_data", "true");

        let request = self
            .reqwest_client
            .post(format!("{}/apiv2student/ping", self.base_url))
            .header("Cookie", &self.auth_cookies)
            .header("Authorization", format!("Basic {}", self.session_id))
            .header(
                reqwest::header::CONTENT_TYPE,
                "application/x-www-form-urlencoded",
            )
            .body(params)
            .send()
            .await?;

        let text = request.cc_parse().await?;
        let data: Session = serde_json::from_str(&text)?;

        let session_id = data.meta.session_id;

        self.session_id = session_id.clone();
        self.last_session_id_updated = Utc::now();

        return Ok(session_id);
    }

    /// This should be used **very** rarely and is only implimented for testing the library with
    /// custom fields.
    pub fn manual_creation(
        student_id: String,
        base_url: String,
        auth_cookies: String,
        session_id: String,
    ) -> Client {
        return Client {
            student_id,
            base_url,
            reqwest_client: reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .build()
                .unwrap(),
            last_session_id_updated: Utc::now(),
            auth_cookies,
            session_id,
        };
    }

    /// This creates a ClassCharts Student Client. It accepts a `code`, `dob` (Date of birth) and an
    /// optional `base_url`, which should **rarely** be used and is only implimented for testing.
    ///
    /// The `dob` parameter should be in the format of `DD/MM/YYYY`.
    ///
    /// Example:
    /// ```rust,no_run
    /// use classcharts::Client;
    /// # #[tokio::main]
    /// # async fn main() {
    /// let mut client = Client::create("your access code", "your date of birth
    /// (DD/MM/YYYY)", None).await.unwrap();
    /// # }
    /// ```
    pub async fn create<C, D>(
        code: C,
        dob: D,
        base_url: Option<String>,
    ) -> Result<Self, ClientCreationError>
    where
        C: ToString,
        D: Into<Cow<'static, str>>,
    {
        let reqwest_client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()?;
        let base_url = base_url.unwrap_or("https://www.classcharts.com".to_string());

        let login_form = reqwest::multipart::Form::new()
            .text("_method", "POST")
            .text("code", code.to_string().to_uppercase())
            .text("dob", dob)
            .text("remember_me", "1")
            .text("recaptcha-token", "no-token-available");

        let login_request = reqwest_client
            .post(format!("{}/student/login", base_url))
            .multipart(login_form)
            .send()
            .await?;

        let mut cookies = login_request.cookies();
        let headers = login_request.headers();
        let status = login_request.status();

        if status != 302 || headers.get("set-cookie").is_none() {
            return Err(ClientCreationError::AuthenticationError);
        }

        let session_cookie = cookies
            .find(|cookie| cookie.name() == "student_session_credentials")
            .ok_or(())
            .map_err(ClientCreationError::MissingSesssionCookie)?;

        // i don't think we actually need this
        let session_cookie = urlencoding::decode(session_cookie.value())?;

        let session_id = serde_json::from_str::<SessionCookie>(&session_cookie)?.session_id;

        let auth_cookies = headers
            .get("set-cookie")
            .unwrap()
            .to_str()?
            .split(",")
            .collect::<Vec<&str>>()
            .join(";");

        let mut client = Client {
            session_id,
            student_id: "".to_string(),
            reqwest_client,
            base_url,
            auth_cookies,
            last_session_id_updated: Utc::now(),
        };

        let cc_response = client
            .get_student_info()
            .await
            .map_err(ClientCreationError::ApiRequestError)?;

        client.student_id = cc_response.data.user.id.to_string();

        return Ok(client);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use httpmock::prelude::*;
    use serde_json::json;

    #[tokio::test]
    async fn cc_parser_test() {
        // Start a lightweight mock server.
        let server = MockServer::start();

        // Create a mock on the server.
        let error_mock = server.mock(|when, then| {
            when.method(GET).path("/error");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "success": 0,
                    "error": "test error"
                }));
        });

        let success_mock = server.mock(|when, then| {
            when.method(GET).path("/success");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "success": 1,
                    "data": "success",
                    "meta": [],
                }));
        });

        let client = reqwest::Client::new();

        let error_request = client
            .get(format!("{}/error", server.base_url()))
            .send()
            .await
            .unwrap();
        let success_request = client
            .get(format!("{}/success", server.base_url()))
            .send()
            .await
            .unwrap();

        error_request.cc_parse().await.unwrap_err();
        success_request.cc_parse().await.unwrap();

        success_mock.assert();
        error_mock.assert();
    }

    #[tokio::test]
    async fn create_client_test() {
        // Start a lightweight mock server.
        let server = MockServer::start();

        // Create a mock on the server.
        let student_login_response = server.mock(|when, then| {
            when.method(POST).path("/student/login");
            then.status(302)
                .header("content-type", "application/json")
                .header(
                    "set-cookie",
                    "student_session_credentials={\"session_id\":\"jf99rm23pdi29dj32fh23i\"}",
                );
        });

        let student_info_response = server.mock(|when, then| {
            when.method(POST).path("/apiv2student/ping");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "success": 1,
                    "data": {
                        "user": {
                            "id": 3949234,
                            "name": "Name",
                            "first_name": "first_name",
                            "last_name": "last_name",
                            "avatar_url": "https://example.com",
                            "display_behaviour": false,
                            "display_parent_behaviour": false,
                            "display_homework": false,
                            "display_rewards": false,
                            "display_detentions": false,
                            "display_report_cards": false,
                            "display_classes": false,
                            "display_announcements": true,
                            "display_academic_reports": false,
                            "display_attendance": true,
                            "display_attendance_type": "instance",
                            "display_attendance_percentage": false,
                            "display_activity": false,
                            "display_mental_health": false,
                            "display_mental_health_no_tracker": false,
                            "display_timetable": false,
                            "is_disabled": false,
                            "display_two_way_communications": true,
                            "display_absences": false,
                            "can_upload_attachments": false,
                            "display_event_badges": false,
                            "display_avatars": false,
                            "display_concern_submission": false,
                            "display_custom_fields": false,
                            "pupil_concerns_help_text": "",
                            "allow_pupils_add_timetable_notes": false,
                            "detention_alias_plural_uc": "Detentions",
                            "announcements_count": 0,
                            "messages_count": 0,
                            "pusher_channel_name": "pusher_channel_name",
                            "has_birthday": false,
                            "has_new_survey": false,
                            "survey_id": null
                        }
                    },
                    "meta": {
                        "session_id": "jf99rm23pdi29dj32fh23i",
                        "version": "27.16.2",
                    },
                }));
        });

        let client = Client::create("my_code", "my_dob", Some(server.base_url()))
            .await
            .unwrap();

        assert_eq!(client.student_id, "3949234");
        assert_eq!(client.session_id, "jf99rm23pdi29dj32fh23i");

        student_login_response.assert();
        student_info_response.assert();
    }
}