From 732c487d3dab4af9fc561527591d3d56299e39f2 Mon Sep 17 00:00:00 2001 From: fx Date: Mon, 9 Oct 2023 16:06:08 +0200 Subject: added db for devices --- src/routes/start.rs | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) (limited to 'src/routes') diff --git a/src/routes/start.rs b/src/routes/start.rs index e7d7e0e..2d505fc 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -4,28 +4,40 @@ use axum::Json; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use std::error::Error; +use std::sync::Arc; +use axum::extract::State; use serde_json::{json, Value}; -use tracing::error; +use tracing::{error, info}; use crate::auth::{auth, AuthError}; use crate::config::SETTINGS; use crate::wol::{create_buffer, send_packet}; +use crate::db::Device; -pub async fn start(headers: HeaderMap, Json(payload): Json) -> Result, StartError> { +pub async fn start(State(state): State>, headers: HeaderMap, Json(payload): Json) -> Result, StartError> { let secret = headers.get("authorization"); if auth(secret).map_err(StartError::Auth)? { + let device = sqlx::query_as!( + Device, + r#" + SELECT id, mac, broadcast_addr + FROM devices + WHERE id = ?1; + "#, + payload.id + ).fetch_one(&state.db).await.map_err(|err| StartError::Server(Box::new(err)))?; + + info!("starting {}", device.id); + let bind_addr = SETTINGS .get_string("bindaddr") .map_err(|err| StartError::Server(Box::new(err)))?; - let broadcast_addr = SETTINGS - .get_string("broadcastaddr") - .map_err(|err| StartError::Server(Box::new(err)))?; + let _ = send_packet( &bind_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?, - &broadcast_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?, - // TODO: MAC saved in DB - create_buffer(std::env::var("MAC").unwrap().as_str()).map_err(|err| StartError::Server(Box::new(err)))? + &device.broadcast_addr.parse().map_err(|err| StartError::Server(Box::new(err)))?, + create_buffer(&device.mac).map_err(|err| StartError::Server(Box::new(err)))? ).map_err(|err| StartError::Server(Box::new(err))); - Ok(Json(json!(StartResponse { id: payload.id, boot: true }))) + Ok(Json(json!(StartResponse { id: device.id, boot: true }))) } else { Err(StartError::Generic) } -- cgit v1.2.3