aboutsummaryrefslogtreecommitdiff
path: root/src/routes/start.rs
blob: 0b6b38ba11399b59c8a81704e6fa9f9473631171 (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
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
use crate::storage::Device;
use crate::error::Error;
use crate::services::ping::Value as PingValue;
use crate::wol::{create_buffer, send_packet};
use axum::extract::{Path, State};
use axum::Json;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
use tracing::{debug, info};
use utoipa::ToSchema;
use uuid::Uuid;

#[utoipa::path(
    post,
    path = "/start/{id}",
    request_body = Option<SPayload>,
    responses(
        (status = 200, description = "start the device with the given id", body = [Response])
    ),
    params(
        ("id" = String, Path, description = "device id")
    ),
    security((), ("api_key" = []))
)]
pub async fn post(
    State(state): State<Arc<crate::AppState>>,
    Path(id): Path<String>,
    payload: Option<Json<SPayload>>,
) -> Result<Json<Value>, Error> {
    send_wol(state, &id, payload)
}

#[utoipa::path(
    get,
    path = "/start/{id}",
    responses(
        (status = 200, description = "start the device with the given id", body = [Response])
    ),
    params(
        ("id" = String, Path, description = "device id")
    ),
    security((), ("api_key" = []))
)]
pub async fn get(
    State(state): State<Arc<crate::AppState>>,
    Path(id): Path<String>,
) -> Result<Json<Value>, Error> {
    send_wol(state, &id, None)
}

fn send_wol(
    state: Arc<crate::AppState>,
    id: &str,
    payload: Option<Json<SPayload>>,
) -> Result<Json<Value>, Error> {
    info!("start request for {id}");
    let device = Device::read(id)?;

    info!("starting {}", device.id);

    let bind_addr = "0.0.0.0:0";

    send_packet(
        bind_addr,
        &device.broadcast_addr.to_string(),
        &create_buffer(&device.mac.to_string())?
    )?;
    let dev_id = device.id.clone();
    let uuid = if let Some(pl) = payload {
        if pl.ping.is_some_and(|ping| ping) {
            if device.ip.is_none() {
                return Err(Error::NoIpOnPing);
            }
            Some(setup_ping(state, device))
        } else {
            None
        }
    } else {
        None
    };

    Ok(Json(json!(Response {
        id: dev_id,
        boot: true,
        uuid
    })))
}

fn setup_ping(state: Arc<crate::AppState>, device: Device) -> String {
    let mut uuid: Option<String> = None;
    // Safe: Only called when ip is set
    let ip = device.ip.unwrap();
    for (key, value) in state.ping_map.clone() {
        if value.ip == ip {
            debug!("service already exists");
            uuid = Some(key);
            break;
        }
    }
    let uuid_gen = match uuid {
        Some(u) => u,
        None => Uuid::new_v4().to_string(),
    };
    let uuid_ret = uuid_gen.clone();

    debug!("init ping service");
    state.ping_map.insert(
        uuid_gen.clone(),
        PingValue {
            ip,
            eta: get_eta(device.clone().times),
            online: false,
        },
    );

    tokio::spawn(async move {
        crate::services::ping::spawn(
            state.ping_send.clone(),
            &state.config,
            device,
            uuid_gen,
            &state.ping_map,
        )
        .await;
    });

    uuid_ret
}

fn get_eta(times: Option<Vec<u64>>) -> u64 {
    let times = if let Some(times) = times {
        times
    } else {
        vec![0]
    };

    times.iter().sum::<u64>() / u64::try_from(times.len()).unwrap()
}

#[derive(Deserialize, ToSchema)]
pub struct SPayload {
    ping: Option<bool>,
}

#[derive(Serialize, ToSchema)]
pub struct Response {
    id: String,
    boot: bool,
    uuid: Option<String>,
}