summaryrefslogtreecommitdiff
path: root/src/routes/device.rs
blob: 49361f2d05020f521c09178e90bb133346ef71fd (plain) (blame)
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
use crate::error::Error;
use crate::storage::Device;
use axum::extract::Path;
use axum::Json;
use ipnetwork::IpNetwork;
use mac_address::MacAddress;
use serde::Deserialize;
use serde_json::{json, Value};
use std::str::FromStr;
use tracing::{debug, info};
use utoipa::ToSchema;

#[utoipa::path(
    get,
    path = "/device/{id}",
    responses(
        (status = 200, description = "Get `Device` information", body = [Device])
    ),
    params(
        ("id" = String, Path, description = "device id")
    ),
    security((), ("api_key" = []))
)]
pub async fn get(Path(id): Path<String>) -> Result<Json<Value>, Error> {
    info!("get device from path {}", id);

    let device = Device::read(&id)?;

    debug!("got device {:?}", device);

    Ok(Json(json!(device)))
}

#[derive(Deserialize, ToSchema)]
pub struct DPayload {
    id: String,
    mac: String,
    broadcast_addr: String,
    ip: String,
}

#[utoipa::path(
    put,
    path = "/device",
    request_body = DPayload,
    responses(
        (status = 200, description = "add device to storage", body = [DeviceSchema])
    ),
    security((), ("api_key" = []))
)]
pub async fn put(
    Json(payload): Json<DPayload>,
) -> Result<Json<Value>, Error> {
    info!(
        "add device {} ({}, {}, {})",
        payload.id, payload.mac, payload.broadcast_addr, payload.ip
    );

    let ip = IpNetwork::from_str(&payload.ip)?;
    let mac = MacAddress::from_str(&payload.mac)?;
    let device = Device {
        id: payload.id,
        mac,
        broadcast_addr: payload.broadcast_addr,
        ip,
        times: None,
    };
    device.write()?;

    Ok(Json(json!(device)))
}

#[utoipa::path(
    post,
    path = "/device",
    request_body = DPayload,
    responses(
        (status = 200, description = "update device in storage", body = [DeviceSchema])
    ),
    security((), ("api_key" = []))
)]
pub async fn post(
    Json(payload): Json<DPayload>,
) -> Result<Json<Value>, Error> {
    info!(
        "edit device {} ({}, {}, {})",
        payload.id, payload.mac, payload.broadcast_addr, payload.ip
    );
    let ip = IpNetwork::from_str(&payload.ip)?;
    let mac = MacAddress::from_str(&payload.mac)?;
    let times = Device::read(&payload.id)?.times;

    let device = Device {
        id: payload.id,
        mac,
        broadcast_addr: payload.broadcast_addr,
        ip,
        times,
    };
    device.write()?;

    Ok(Json(json!(device)))
}