📦 Turbo87 / united-flarmnet

📄 weglide.rs · 67 lines
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
67use reqwest_middleware::ClientWithMiddleware;
use serde::{Deserialize, Serialize};
use time::serde::rfc3339;
use time::OffsetDateTime;

#[derive(Debug, Deserialize, Serialize)]
pub struct Device {
    pub id: String,
    pub name: Option<String>,
    pub competition_id: Option<String>,
    pub aircraft: Option<AircraftRef>,
    #[serde(with = "rfc3339::option")]
    pub until: Option<OffsetDateTime>,
    pub user: UserRef,
}

impl Device {
    pub fn is_current(&self) -> bool {
        self.until.is_none() || self.until.unwrap() >= OffsetDateTime::now_utc()
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct AircraftRef {
    pub id: u32,
    pub name: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct UserRef {
    pub id: u32,
    pub name: String,
}

impl Device {
    pub fn into_flarmnet_record(self) -> flarmnet::Record {
        flarmnet::Record {
            flarm_id: self.id,
            pilot_name: self.user.name,
            airfield: "".to_string(),
            plane_type: self.aircraft.map(|it| it.name).unwrap_or_default(),
            registration: self.name.unwrap_or_default(),
            call_sign: self.competition_id.unwrap_or_default(),
            frequency: "".to_string(),
        }
    }
}

#[instrument(skip(client))]
pub async fn get_devices(client: &ClientWithMiddleware) -> anyhow::Result<Vec<Device>> {
    info!("Downloading WeGlide device data…");
    let response = client
        .get("https://api.weglide.org/v1/device/connected")
        .send()
        .await?;

    let response = response.error_for_status()?;

    let devices: Vec<Device> = response.json().await?;
    debug!(devices = devices.len());

    let current_devices: Vec<_> = devices.into_iter().filter(|it| it.is_current()).collect();
    debug!(current_devices = current_devices.len());

    Ok(current_devices)
}