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
extern crate chrono;
extern crate hyper;
extern crate hyper_tls;
extern crate serde;
extern crate serde_json;
pub mod errors;
pub mod model;
use crate::errors::Error;
use crate::model::{APIResponse, Shipment};
use hyper::{header, Body, Client, Request};
use hyper_tls::HttpsConnector;
fn extract_access_token(set_cookie_value: &str) -> Option<&str> {
let end = set_cookie_value.find(';')?;
Some(&set_cookie_value[..end])
}
pub async fn get_tracking_info(shipment_id: &str) -> Result<Shipment, Error> {
if !shipment_id.chars().all(char::is_alphanumeric) {
return Result::Err(Error::IllegalParcelId);
}
let https = HttpsConnector::new();
let client = Client::builder().build::<_, hyper::Body>(https);
let first_request = Request::builder()
.uri(format!(
"https://www.laposte.fr/outils/suivre-vos-envois?code={}",
shipment_id,
))
.body(Body::default())
.map_err(|_| Error::IllegalParcelId)?;
let first_response = client
.request(first_request)
.await
.map_err(|_| Error::Request)?;
let cookie_header = first_response
.headers()
.get(header::SET_COOKIE)
.ok_or(Error::Response)?;
let cookie_header = cookie_header.to_str().map_err(|_| Error::Response)?;
let access_token = extract_access_token(cookie_header).ok_or(Error::Response)?;
let api_request = Request::builder()
.uri(format!(
"https://api.laposte.fr/ssu/v1/suivi-unifie/idship/{}?lang=fr_FR",
shipment_id,
))
.header(header::ACCEPT, "application/json")
.header(header::COOKIE, access_token)
.body(Body::default())
.map_err(|_| Error::Response)?;
let api_response = client
.request(api_request)
.await
.map_err(|_| Error::Request)?;
let body = hyper::body::to_bytes(api_response.into_body())
.await
.map_err(|_| Error::Response)?;
let body = String::from_utf8(body.to_vec()).map_err(|_| Error::Response)?;
println!("{:?}", body);
let api_response: APIResponse = serde_json::from_str(&body).unwrap();
api_response.into()
}