Can delete a pending device

This commit is contained in:
Pierre HUBERT 2024-07-03 21:10:15 +02:00
parent 716af6219a
commit 2502ed6bcf
6 changed files with 120 additions and 9 deletions

View File

@ -95,4 +95,27 @@ impl DevicesList {
pub fn full_list(&self) -> Vec<Device> { pub fn full_list(&self) -> Vec<Device> {
self.0.clone().into_values().collect() self.0.clone().into_values().collect()
} }
/// Delete a device
pub fn delete(&mut self, id: &DeviceId) -> anyhow::Result<()> {
let crt_path = AppConfig::get().device_cert_path(id);
if crt_path.is_file() {
// TODO : implement
unimplemented!("Certificate revocation not implemented yet!");
}
let csr_path = AppConfig::get().device_csr_path(id);
if csr_path.is_file() {
std::fs::remove_file(&csr_path)?;
}
let conf_path = AppConfig::get().device_config_path(id);
if conf_path.is_file() {
std::fs::remove_file(&conf_path)?;
}
self.0.remove(id);
Ok(())
}
} }

View File

@ -94,6 +94,22 @@ impl Handler<EnrollDevice> for EnergyActor {
} }
} }
/// Delete a device
#[derive(Message)]
#[rtype(result = "anyhow::Result<()>")]
pub struct DeleteDevice(pub DeviceId);
impl Handler<DeleteDevice> for EnergyActor {
type Result = anyhow::Result<()>;
fn handle(&mut self, msg: DeleteDevice, _ctx: &mut Context<Self>) -> Self::Result {
log::info!("Requested to delete device {:?}...", &msg.0);
self.devices.delete(&msg.0)?;
// TODO : delete energy related information
Ok(())
}
}
/// Get the list of devices /// Get the list of devices
#[derive(Message)] #[derive(Message)]
#[rtype(result = "Vec<Device>")] #[rtype(result = "Vec<Device>")]

View File

@ -139,6 +139,10 @@ pub async fn secure_server(energy_actor: EnergyActorAddr) -> anyhow::Result<()>
"/web_api/devices/list_validated", "/web_api/devices/list_validated",
web::get().to(devices_controller::list_validated), web::get().to(devices_controller::list_validated),
) )
.route(
"/web_api/device/{id}",
web::delete().to(devices_controller::delete_device),
)
// Devices API // Devices API
.route( .route(
"/devices_api/utils/time", "/devices_api/utils/time",

View File

@ -1,7 +1,8 @@
use crate::devices::device::DeviceId;
use crate::energy::energy_actor; use crate::energy::energy_actor;
use crate::server::custom_error::HttpResult; use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor; use crate::server::WebEnergyActor;
use actix_web::HttpResponse; use actix_web::{web, HttpResponse};
/// Get the list of pending (not accepted yet) devices /// Get the list of pending (not accepted yet) devices
pub async fn list_pending(actor: WebEnergyActor) -> HttpResult { pub async fn list_pending(actor: WebEnergyActor) -> HttpResult {
@ -26,3 +27,17 @@ pub async fn list_validated(actor: WebEnergyActor) -> HttpResult {
Ok(HttpResponse::Ok().json(list)) Ok(HttpResponse::Ok().json(list))
} }
#[derive(serde::Deserialize)]
pub struct DeviceInPath {
id: DeviceId,
}
/// Delete a device
pub async fn delete_device(actor: WebEnergyActor, id: web::Path<DeviceInPath>) -> HttpResult {
actor
.send(energy_actor::DeleteDevice(id.id.clone()))
.await??;
Ok(HttpResponse::Accepted().finish())
}

View File

@ -49,4 +49,14 @@ export class DeviceApi {
}) })
).data; ).data;
} }
/**
* Delete a device
*/
static async Delete(d: Device): Promise<void> {
await APIClient.exec({
uri: `/device/${encodeURIComponent(d.id)}`,
method: "DELETE",
});
}
} }

View File

@ -1,16 +1,22 @@
import React from "react"; import DeleteIcon from "@mui/icons-material/Delete";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
import { Device, DeviceApi } from "../api/DeviceApi";
import { import {
TableContainer, IconButton,
Paper, Paper,
Table, Table,
TableBody,
TableCell,
TableContainer,
TableHead, TableHead,
TableRow, TableRow,
TableCell,
TableBody,
} from "@mui/material"; } from "@mui/material";
import React from "react";
import { Device, DeviceApi } from "../api/DeviceApi";
import { useAlert } from "../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../hooks/context_providers/ConfirmDialogProvider";
import { useLoadingMessage } from "../hooks/context_providers/LoadingMessageProvider";
import { useSnackbar } from "../hooks/context_providers/SnackbarProvider";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
import { TimeWidget } from "../widgets/TimeWidget"; import { TimeWidget } from "../widgets/TimeWidget";
export function PendingDevicesRoute(): React.ReactElement { export function PendingDevicesRoute(): React.ReactElement {
@ -46,6 +52,37 @@ function PendingDevicesList(p: {
pending: Device[]; pending: Device[];
onReload: () => void; onReload: () => void;
}): React.ReactElement { }): React.ReactElement {
const alert = useAlert();
const confirm = useConfirm();
const snackbar = useSnackbar();
const loadingMessage = useLoadingMessage();
const deleteDevice = async (d: Device) => {
try {
if (
!(await confirm(
`Do you really want to delete the device ${d.id}? The operation cannot be reverted!`
))
)
return;
loadingMessage.show("Deleting device...");
await DeviceApi.Delete(d);
snackbar("The device has been successfully deleted!");
p.onReload();
} catch (e) {
console.error(`Failed to delete device! ${e})`);
alert("Failed to delete device!");
} finally {
loadingMessage.hide();
}
};
if (p.pending.length === 0) {
return <p>There is no device awaiting confirmation right now.</p>;
}
return ( return (
<TableContainer component={Paper}> <TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table"> <Table sx={{ minWidth: 650 }} aria-label="simple table">
@ -54,8 +91,9 @@ function PendingDevicesList(p: {
<TableCell>#</TableCell> <TableCell>#</TableCell>
<TableCell>Model</TableCell> <TableCell>Model</TableCell>
<TableCell>Version</TableCell> <TableCell>Version</TableCell>
<TableCell>Maximum number of relays</TableCell> <TableCell>Max number of relays</TableCell>
<TableCell>Created</TableCell> <TableCell>Created</TableCell>
<TableCell></TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
@ -70,6 +108,11 @@ function PendingDevicesList(p: {
<TableCell> <TableCell>
<TimeWidget time={dev.time_create} /> <TimeWidget time={dev.time_create} />
</TableCell> </TableCell>
<TableCell>
<IconButton onClick={() => deleteDevice(dev)}>
<DeleteIcon />
</IconButton>
</TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>