fej/src/ivago/controller/pickup_times.rs

57 lines
1.7 KiB
Rust
Raw Normal View History

use super::structs::{BasicDate, PickupTime, Street};
use crate::errors::FejError;
use chrono::DateTime;
use chrono_tz::Tz;
2021-04-04 11:39:40 +02:00
use reqwest::blocking as reqwest;
use std::collections::HashMap;
2021-04-04 12:06:33 +02:00
use std::convert::{From, TryFrom};
2021-03-15 14:48:20 +01:00
2021-03-21 16:18:53 +01:00
const BASE_URL: &str = "https://www.ivago.be/nl/particulier/afval/ophaling";
2021-04-04 11:39:40 +02:00
const CAL_URL: &str = "https://www.ivago.be/nl/particulier/garbage/pick-up/pickups";
2021-03-21 16:18:53 +01:00
pub fn get_pickup_times(
street: &Street,
number: &u32,
start_date: &DateTime<Tz>,
end_date: &DateTime<Tz>,
) -> Result<Vec<PickupTime>, FejError> {
2021-04-04 11:39:40 +02:00
let client = reqwest::Client::builder().cookie_store(true).build()?;
// This populates the cookies with the necessary values
client
.post(BASE_URL)
.form(&[
("garbage_type", ""),
("ivago_street", &String::from(street)),
("number", &number.to_string()),
("form_id", "garbage_address_form"),
])
.send()?;
let response = client
.get(CAL_URL)
.query(&[
("_format", "json"),
("type", ""),
("start", &start_date.timestamp().to_string()),
("end", &end_date.timestamp().to_string()),
2021-04-04 11:39:40 +02:00
])
.send()?;
let data: Vec<HashMap<String, String>> = response.json()?;
let mut output: Vec<PickupTime> = Vec::new();
for map in data
.iter()
.filter(|m| m.contains_key("date") && m.contains_key("label"))
{
2021-04-08 23:00:54 +02:00
// Because we filtered the maps in the loop, we can safely use unwrap
// here
if let Ok(date) = BasicDate::try_from(map.get("date").unwrap().as_str()) {
output.push(PickupTime::new(date, map.get("label").unwrap().to_string()))
}
2021-04-04 11:39:40 +02:00
}
2021-04-04 12:06:33 +02:00
Ok(output)
2021-03-21 16:18:53 +01:00
}