40 Commits

Author SHA1 Message Date
f403c85f0a Add release configuration
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2025-04-07 12:31:42 +02:00
db25c7e426 Update Rust crate sysinfo to 0.34.2
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-04-02 00:39:29 +00:00
98b67534cb Update Rust crate rust-embed to 8.6.0
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-03-31 20:54:10 +00:00
09d3cf08f3 Update Rust crate quick-xml to 0.37.3
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-03-31 00:38:34 +00:00
9b3d32811f Update Rust crate num to 0.4.3
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-03-30 02:24:42 +00:00
26d391ea96 Update Rust crate log to 0.4.27
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-03-29 23:01:14 +00:00
c044996014 Update Rust crate image to 0.25.6
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-03-29 18:17:12 +00:00
34b04968b2 Update renovate.json
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-29 17:30:56 +00:00
c44a3f2673 Merge pull request 'Update Rust crate sysinfo to v0.34.1' (#305) from renovate/sysinfo-0.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #305
2025-03-29 12:52:01 +00:00
e46adcd1da Merge pull request 'Update Rust crate basic-jwt to 0.3.0' (#306) from renovate/basic-jwt-0.x into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #306
2025-03-29 12:51:53 +00:00
d1506f26ab Update renovate.json
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-29 09:04:05 +00:00
23194d13d2 Update Rust crate basic-jwt to 0.3.0
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-29 00:34:32 +00:00
131dec892d Update Rust crate sysinfo to v0.34.1
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-29 00:34:22 +00:00
c2e6105aff Reload page when signedIn state change
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 13:10:47 +01:00
f5202f596d Fix all ESLint errors
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 12:25:04 +01:00
3bf8859ff9 WIP ESLint
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 12:12:11 +01:00
9a905e83f7 WIP ESLint fixes 2025-03-28 11:35:51 +01:00
4b9df95721 Remove deprecated code 2025-03-28 11:29:31 +01:00
e14f51ef7e Upgrade vite project
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 11:26:51 +01:00
5d49ce17a6 fix CI
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 11:07:16 +01:00
e5753d2b26 WIP update 2025-03-28 11:06:30 +01:00
e9e3103938 Format all code following migration to Rust edition 2024
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 10:23:37 +01:00
44188975ca Update backend to edition 2024
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-28 10:17:19 +01:00
3f8d4e78d8 Update backend dependencies 2025-03-28 10:14:33 +01:00
1c01a3b1ac Merge pull request 'Update Rust crate log to v0.4.27' (#300) from renovate/log-0.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #300
2025-03-28 08:33:19 +00:00
a5c40255c7 Merge pull request 'Update dependency @types/react to v18.3.20' (#301) from renovate/react-18.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #301
2025-03-28 08:32:55 +00:00
6080bd83b5 Merge pull request 'Update Rust crate image to v0.25.6' (#302) from renovate/image-0.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #302
2025-03-28 08:31:01 +00:00
8cb9d8bb32 Merge pull request 'Update Rust crate quick-xml to v0.37.3' (#303) from renovate/quick-xml-0.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #303
2025-03-28 08:30:47 +00:00
3c613e40bf Update Rust crate quick-xml to v0.37.3
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-26 00:28:52 +00:00
7fed9e2324 Update Rust crate image to v0.25.6
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-03-26 00:28:47 +00:00
afe7aab751 Update dependency @types/react to v18.3.20
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-25 00:29:00 +00:00
accd4776cb Update Rust crate log to v0.4.27
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-25 00:28:58 +00:00
6aabab866c Merge pull request 'Update dependency @types/react to v18.3.19' (#296) from renovate/react-18.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #296
2025-03-24 14:51:14 +00:00
4981a41a0a Merge pull request 'Update dependency xml-formatter to v3.6.5' (#299) from renovate/xml-formatter-3.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #299
2025-03-24 14:51:04 +00:00
9daced06e4 Update dependency xml-formatter to v3.6.5
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-22 00:27:04 +00:00
8299065eb2 Update dependency @types/react to v18.3.19
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-03-21 00:27:17 +00:00
67549d54a3 Migrate from actix-web-actor to actix-ws
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-20 22:08:02 +01:00
c0690d888e Update frontend dependencies
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-20 21:39:09 +01:00
ed9fd097e9 Updated backend dependencies
All checks were successful
continuous-integration/drone/push Build is passing
2025-03-20 21:33:18 +01:00
3c8de8279b Merge pull request 'Update dependency @mui/icons-material to v6.4.7' (#290) from renovate/mui-icons-material-6.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #290
2025-03-20 20:16:29 +00:00
96 changed files with 2746 additions and 19675 deletions

View File

@ -11,7 +11,8 @@ steps:
path: /tmp/web_build
commands:
- cd virtweb_frontend
- npm install
- npm install --legacy-peer-deps # TODO : remove when mui-file-input is updated
- npm run lint
- npm run build
- mv dist /tmp/web_build
@ -25,6 +26,7 @@ steps:
- rustup component add clippy
- cd virtweb_backend
- cargo clippy -- -D warnings
- cargo clippy --examples -- -D warnings
- cargo test
- name: backend_compile
@ -34,6 +36,8 @@ steps:
path: /usr/local/cargo/registry
- name: web_app
path: /tmp/web_build
- name: release
path: /tmp/release
depends_on:
- backend_check
- web_build
@ -43,10 +47,30 @@ steps:
- mv /tmp/web_build/dist static
- cargo build --release
- ls -lah target/release/virtweb_backend
- cp target/release/virtweb_backend /tmp/release
- name: gitea_release
image: plugins/gitea-release
depends_on:
- backend_compile
when:
event:
- tag
volumes:
- name: release
path: /tmp/release
environment:
PLUGIN_API_KEY:
from_secret: API_KEY
settings:
base_url: https://gitea.communiquons.org
files: /tmp/release/*
checksum: sha512
volumes:
- name: rust_registry
temp: {}
- name: web_app
temp: {}
- name: release
temp: {}

View File

@ -1,9 +1,3 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"packageRules": [
{
"matchUpdateTypes": ["major", "minor", "patch"],
"automerge": true
}
]
"extends": ["local>renovate/presets"]
}

File diff suppressed because it is too large Load Diff

View File

@ -1,48 +1,48 @@
[package]
name = "virtweb_backend"
version = "0.1.0"
edition = "2021"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.21"
env_logger = "0.11.3"
clap = { version = "4.5.20", features = ["derive", "env"] }
light-openid = { version = "1.0.2", features = ["crypto-wrapper"] }
log = "0.4.27"
env_logger = "0.11.7"
clap = { version = "4.5.34", features = ["derive", "env"] }
light-openid = { version = "1.0.4", features = ["crypto-wrapper"] }
lazy_static = "1.5.0"
actix = "0.13.3"
actix-web = "4.9.0"
actix = "0.13.5"
actix-web = "4.10.2"
actix-remote-ip = "0.1.0"
actix-session = { version = "0.10.0", features = ["cookie-session"] }
actix-session = { version = "0.10.1", features = ["cookie-session"] }
actix-identity = "0.8.0"
actix-cors = "0.7.0"
actix-files = "0.6.5"
actix-web-actors = "4.3.0"
actix-http = "3.9.0"
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.132"
quick-xml = { version = "0.37.1", features = ["serialize", "overlapped-lists"] }
actix-cors = "0.7.1"
actix-files = "0.6.6"
actix-ws = "0.3.0"
actix-http = "3.10.0"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
quick-xml = { version = "0.37.3", features = ["serialize", "overlapped-lists"] }
futures-util = "0.3.31"
anyhow = "1.0.93"
actix-multipart = "0.7.0"
tempfile = "3.14.0"
reqwest = { version = "0.12.9", features = ["stream"] }
url = "2.5.0"
virt = "0.4.1"
sysinfo = { version = "0.32.0", features = ["serde"] }
uuid = { version = "1.11.0", features = ["v4", "serde"] }
lazy-regex = "3.3.0"
thiserror = "2.0.0"
image = "0.25.4"
anyhow = "1.0.97"
actix-multipart = "0.7.2"
tempfile = "3.19.1"
reqwest = { version = "0.12.15", features = ["stream"] }
url = "2.5.4"
virt = "0.4.2"
sysinfo = { version = "0.34.2", features = ["serde"] }
uuid = { version = "1.16.0", features = ["v4", "serde"] }
lazy-regex = "3.4.1"
thiserror = "2.0.12"
image = "0.25.6"
rand = "0.9.0"
bytes = "1.8.0"
tokio = "1.41.1"
bytes = "1.10.1"
tokio = { version = "1.44.1", features = ["rt", "time", "macros"] }
futures = "0.3.31"
ipnetwork = "0.20.0"
num = "0.4.2"
rust-embed = { version = "8.5.0" }
mime_guess = "2.0.4"
ipnetwork = { version = "0.21.1", features = ["serde"] }
num = "0.4.3"
rust-embed = { version = "8.6.0" }
mime_guess = "2.0.5"
dotenvy = "0.15.7"
nix = { version = "0.29.0", features = ["net"] }
basic-jwt = "0.2.0"
basic-jwt = "0.3.0"

View File

@ -55,12 +55,13 @@ fn main() {
let jwt = key.sign_jwt(&claims).expect("Failed to sign JWT!");
Command::new("curl")
let err = Command::new("curl")
.args(["-X", &args.verb])
.args(["-H", &format!("x-token-id: {}", args.token_id)])
.args(["-H", &format!("x-token-content: {jwt}")])
.args(args.run)
.arg(full_url)
.exec();
panic!("Failed to run curl!")
panic!("Failed to run cURL! {err}")
}

View File

@ -1,3 +1,3 @@
pub mod libvirt_actor;
pub mod vnc_actor;
pub mod vnc_handler;
pub mod vnc_tokens_actor;

View File

@ -1,209 +0,0 @@
use actix::{Actor, ActorContext, AsyncContext, Handler, StreamHandler};
use actix_http::ws::Item;
use actix_web_actors::ws;
use actix_web_actors::ws::Message;
use bytes::Bytes;
use image::EncodableLayout;
use std::path::Path;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::UnixStream;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
#[derive(thiserror::Error, Debug)]
enum VNCError {
#[error("Socket file does not exists!")]
SocketDoesNotExists,
}
pub struct VNCActor {
/// Qemu -> WS
read_half: Option<OwnedReadHalf>,
/// WS -> Qemu
write_half: OwnedWriteHalf,
// Client must respond to ping at a specific interval, otherwise we drop connection
hb: Instant,
}
impl VNCActor {
pub async fn new(socket_path: &str) -> anyhow::Result<Self> {
let socket_path = Path::new(socket_path);
if !socket_path.exists() {
return Err(VNCError::SocketDoesNotExists.into());
}
let socket = UnixStream::connect(socket_path).await?;
let (read_half, write_half) = socket.into_split();
Ok(Self {
read_half: Some(read_half),
write_half,
hb: Instant::now(),
})
}
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
log::warn!("WebSocket Client heartbeat failed, disconnecting!");
ctx.stop();
return;
}
ctx.ping(b"");
});
}
fn send_to_socket(&mut self, bytes: Bytes, ctx: &mut ws::WebsocketContext<Self>) {
log::trace!("Received {} bytes for VNC socket", bytes.len());
if let Err(e) = futures::executor::block_on(self.write_half.write(bytes.as_bytes())) {
log::error!("Failed to relay bytes to VNC socket {e}");
ctx.close(None);
}
}
fn start_qemu_to_ws_end(&mut self, ctx: &mut ws::WebsocketContext<Self>) {
let mut read_half = self.read_half.take().unwrap();
let addr = ctx.address();
let future = async move {
let mut buff: [u8; 5000] = [0; 5000];
loop {
match read_half.read(&mut buff).await {
Ok(mut l) => {
if l == 0 {
log::warn!("Got empty read!");
// Ugly hack made to wait for next byte
let mut one_byte_buff: [u8; 1] = [0; 1];
match read_half.read_exact(&mut one_byte_buff).await {
Ok(b) => {
if b == 0 {
log::error!("Did not get a byte !");
let _ = addr.send(CloseWebSocketReq).await;
break;
}
buff[0] = one_byte_buff[0];
l = 1;
}
Err(e) => {
log::error!("Failed to read 1 BYTE from remote socket. Stopping now... {:?}", e);
break;
}
}
}
let to_send = SendBytesReq(Vec::from(&buff[0..l]));
if let Err(e) = addr.send(to_send).await {
log::error!("Failed to send to websocket. Stopping now... {:?}", e);
return;
}
}
Err(e) => {
log::error!("Failed to read from remote socket. Stopping now... {:?}", e);
break;
}
};
}
log::info!("Exited read loop");
};
tokio::spawn(future);
}
}
impl Actor for VNCActor {
type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.hb(ctx);
self.start_qemu_to_ws_end(ctx);
}
}
impl StreamHandler<Result<Message, ws::ProtocolError>> for VNCActor {
fn handle(&mut self, msg: Result<Message, ws::ProtocolError>, ctx: &mut Self::Context) {
match msg {
Ok(Message::Ping(msg)) => ctx.pong(&msg),
Ok(Message::Text(_text)) => {
log::error!("Received unexpected text on VNC WebSocket!");
}
Ok(Message::Binary(bin)) => {
log::info!("Forward {} bytes to VNC server", bin.len());
self.send_to_socket(bin, ctx);
}
Ok(Message::Continuation(msg)) => match msg {
Item::FirstText(_) => {
log::error!("Received unexpected split text!");
ctx.close(None);
}
Item::FirstBinary(bin) | Item::Continue(bin) | Item::Last(bin) => {
self.send_to_socket(bin, ctx);
}
},
Ok(Message::Pong(_)) => {
log::trace!("Received PONG message");
self.hb = Instant::now();
}
Ok(Message::Close(r)) => {
log::info!("WebSocket closed. Reason={r:?}");
ctx.close(r);
}
Ok(Message::Nop) => {
log::debug!("Received Nop message")
}
Err(e) => {
log::error!("WebSocket protocol error! {e}");
ctx.close(None)
}
}
}
}
#[derive(actix::Message)]
#[rtype(result = "()")]
pub struct SendBytesReq(Vec<u8>);
impl Handler<SendBytesReq> for VNCActor {
type Result = ();
fn handle(&mut self, msg: SendBytesReq, ctx: &mut Self::Context) -> Self::Result {
log::trace!("Send {} bytes to WS", msg.0.len());
ctx.binary(msg.0);
}
}
#[derive(actix::Message)]
#[rtype(result = "()")]
pub struct CloseWebSocketReq;
impl Handler<CloseWebSocketReq> for VNCActor {
type Result = ();
fn handle(&mut self, _msg: CloseWebSocketReq, ctx: &mut Self::Context) -> Self::Result {
log::trace!("Close websocket, because VNC socket has terminated");
ctx.close(None);
}
}

View File

@ -0,0 +1,129 @@
use actix_http::ws::Message;
use futures_util::StreamExt as _;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::select;
use tokio::time::interval;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
/// Broadcast text & binary messages received from a client, respond to ping messages, and monitor
/// connection health to detect network issues and free up resources.
pub async fn handle(
mut session: actix_ws::Session,
mut msg_stream: actix_ws::MessageStream,
mut socket: UnixStream,
) {
log::info!("Connected to websocket");
let mut last_heartbeat = Instant::now();
let mut interval = interval(HEARTBEAT_INTERVAL);
let mut buf_socket = [0u8; 1024];
let reason = loop {
// waits for either `msg_stream` to receive a message from the client, the broadcast channel
// to send a message, or the heartbeat interval timer to tick, yielding the value of
// whichever one is ready first
select! {
// heartbeat interval ticked
_tick = interval.tick() => {
// if no heartbeat ping/pong received recently, close the connection
if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT {
log::info!(
"client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting"
);
break None;
}
// send heartbeat ping
let _ = session.ping(b"").await;
}
msg = msg_stream.next() => {
let msg = match msg {
// received message from WebSocket client
Some(Ok(msg)) => msg,
// client WebSocket stream error
Some(Err(err)) => {
log::error!("{err}");
break None;
}
// client WebSocket stream ended
None => break None
};
log::debug!("msg: {msg:?}");
match msg {
Message::Text(_) => {
log::error!("Received unexpected text on VNC WebSocket!");
}
Message::Binary(bin) => {
log::info!("Forward {} bytes to VNC server", bin.len());
if let Err(e) = socket.write(&bin).await {
log::error!("Failed to relay bytes to VNC socket {e}");
break None;
}
}
Message::Close(reason) => {
break reason;
}
Message::Ping(bytes) => {
last_heartbeat = Instant::now();
let _ = session.pong(&bytes).await;
}
Message::Pong(_) => {
last_heartbeat = Instant::now();
}
Message::Continuation(_) => {
log::warn!("no support for continuation frames");
}
// no-op; ignore
Message::Nop => {}
};
}
// Forward socket packet to WS client
count = socket.read(&mut buf_socket) => {
let count = match count {
Ok(count) => count,
Err(e) => {
log::error!("[VNC] Failed to read from upstream! {e}");
break None;
}
};
if count == 0 {
log::warn!("[VNC] infinite loop (upstream), closing connection");
break None;
}
if let Err(e)=session.binary(buf_socket[0..count].to_vec()).await{
log::error!("[VNC] Failed to forward messages to upstream, will close connection! {e}");
break None
}
}
}
};
// attempt to close connection gracefully
let _ = session.close(reason).await;
log::info!("Disconnected from websocket");
}

View File

@ -2,9 +2,9 @@
use crate::api_tokens;
use crate::api_tokens::{NewToken, TokenID, TokenRights};
use crate::controllers::api_tokens_controller::rest_token::RestToken;
use crate::controllers::HttpResult;
use actix_web::{web, HttpResponse};
use crate::controllers::api_tokens_controller::rest_token::RestToken;
use actix_web::{HttpResponse, web};
use basic_jwt::JWTPrivateKey;
/// Create a special module for REST token to enforce usage of constructor function

View File

@ -1,6 +1,6 @@
use actix_remote_ip::RemoteIP;
use actix_web::web::Data;
use actix_web::{web, HttpResponse, Responder};
use actix_web::{HttpResponse, Responder, web};
use light_openid::basic_state_manager::BasicStateManager;
use crate::app_config::AppConfig;

View File

@ -3,9 +3,9 @@ use crate::constants;
use crate::controllers::HttpResult;
use crate::utils::files_utils;
use actix_files::NamedFile;
use actix_multipart::form::tempfile::TempFile;
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use actix_multipart::form::tempfile::TempFile;
use actix_web::{HttpRequest, HttpResponse, web};
use futures_util::StreamExt;
use std::fs::File;
use std::io::Write;

View File

@ -1,7 +1,7 @@
use crate::libvirt_client::LibVirtClient;
use actix_http::StatusCode;
use actix_web::body::BoxBody;
use actix_web::{web, HttpResponse};
use actix_web::{HttpResponse, web};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io::ErrorKind;

View File

@ -1,7 +1,7 @@
use crate::controllers::{HttpResult, LibVirtReq};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::net::NetworkInfo;
use actix_web::{web, HttpResponse};
use actix_web::{HttpResponse, web};
#[derive(serde::Serialize, serde::Deserialize)]
pub struct NetworkID {

View File

@ -2,7 +2,7 @@ use crate::constants;
use crate::controllers::{HttpResult, LibVirtReq};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
use actix_web::{web, HttpResponse};
use actix_web::{HttpResponse, web};
#[derive(serde::Serialize, serde::Deserialize)]
pub struct NetworkFilterID {

View File

@ -136,16 +136,13 @@ pub async fn server_info(client: LibVirtReq) -> HttpResult {
system.refresh_all();
let mut components = Components::new();
components.refresh_list();
components.refresh();
components.refresh(true);
let mut disks = Disks::new();
disks.refresh_list();
disks.refresh();
disks.refresh(true);
let mut networks = Networks::new();
networks.refresh_list();
networks.refresh();
networks.refresh(true);
Ok(HttpResponse::Ok().json(ServerInfo {
hypervisor: client.get_info().await?,

View File

@ -18,7 +18,7 @@ mod serve_static_debug {
#[cfg(not(debug_assertions))]
mod serve_static_release {
use actix_web::{web, HttpResponse, Responder};
use actix_web::{HttpResponse, Responder, web};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]

View File

@ -1,11 +1,12 @@
use crate::actors::vnc_actor::VNCActor;
use crate::actors::vnc_handler;
use crate::actors::vnc_tokens_actor::VNCTokensManager;
use crate::controllers::{HttpResult, LibVirtReq};
use crate::libvirt_lib_structures::domain::DomainState;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::DomainState;
use crate::libvirt_rest_structures::vm::VMInfo;
use actix_web::{web, HttpRequest, HttpResponse};
use actix_web_actors::ws;
use actix_web::{HttpRequest, HttpResponse, rt, web};
use std::path::Path;
use tokio::net::UnixStream;
#[derive(serde::Serialize)]
struct VMInfoAndState {
@ -324,5 +325,19 @@ pub async fn vnc(
};
log::info!("Start VNC connection on socket {socket_path}");
Ok(ws::start(VNCActor::new(&socket_path).await?, &req, stream)?)
let socket_path = Path::new(&socket_path);
if !socket_path.exists() {
log::error!("VNC socket path {socket_path:?} does not exist!");
return Ok(HttpResponse::ServiceUnavailable().json("VNC socket path does not exists!"));
}
let socket = UnixStream::connect(socket_path).await?;
let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;
// spawn websocket handler (and don't await it) so that the response is returned immediately
rt::spawn(vnc_handler::handle(session, msg_stream, socket));
Ok(res)
}

View File

@ -1,7 +1,7 @@
use actix_identity::Identity;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
use futures_util::future::{ready, Ready};
use futures_util::future::{Ready, ready};
use std::fmt::Display;
pub struct AuthExtractor {

View File

@ -1,11 +1,11 @@
use crate::controllers::LibVirtReq;
use crate::libvirt_lib_structures::domain::DomainXML;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::DomainXML;
use crate::libvirt_rest_structures::vm::VMGroupId;
use actix_http::Payload;
use actix_web::error::ErrorBadRequest;
use actix_web::web::Query;
use actix_web::{web, Error, FromRequest, HttpRequest};
use actix_web::{Error, FromRequest, HttpRequest, web};
use std::future::Future;
use std::pin::Pin;

View File

@ -1,7 +1,7 @@
use crate::app_config::AppConfig;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpRequest};
use futures_util::future::{ready, Ready};
use futures_util::future::{Ready, ready};
use std::ops::Deref;
#[derive(Debug, Copy, Clone, PartialEq)]

View File

@ -1,9 +1,9 @@
use crate::actors::libvirt_actor;
use crate::actors::libvirt_actor::LibVirtActor;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::{DomainState, DomainXML};
use crate::libvirt_lib_structures::network::NetworkXML;
use crate::libvirt_lib_structures::nwfilter::NetworkFilterXML;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
use crate::libvirt_rest_structures::net::NetworkInfo;
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;

View File

@ -1,5 +1,5 @@
use crate::libvirt_lib_structures::network::*;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::network::*;
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
use crate::nat::nat_definition::Nat;
use crate::nat::nat_lib;

View File

@ -1,9 +1,9 @@
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::nwfilter::{
NetworkFilterRefXML, NetworkFilterRuleProtocolAllXML, NetworkFilterRuleProtocolArpXML,
NetworkFilterRuleProtocolIpvx, NetworkFilterRuleProtocolLayer4, NetworkFilterRuleProtocolMac,
NetworkFilterRuleXML, NetworkFilterXML,
};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::LibVirtStructError;
use crate::libvirt_rest_structures::LibVirtStructError::{
NetworkFilterExtraction, StructureExtraction,

View File

@ -1,7 +1,7 @@
use crate::app_config::AppConfig;
use crate::constants;
use crate::libvirt_lib_structures::domain::*;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::*;
use crate::libvirt_rest_structures::LibVirtStructError;
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
use crate::utils::disks_utils::Disk;

View File

@ -1,17 +1,17 @@
use actix::Actor;
use actix_cors::Cors;
use actix_identity::config::LogoutBehaviour;
use actix_identity::IdentityMiddleware;
use actix_multipart::form::tempfile::TempFileConfig;
use actix_identity::config::LogoutBehaviour;
use actix_multipart::form::MultipartFormConfig;
use actix_multipart::form::tempfile::TempFileConfig;
use actix_remote_ip::RemoteIPConfig;
use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware;
use actix_session::storage::CookieSessionStore;
use actix_web::cookie::{Key, SameSite};
use actix_web::http::header;
use actix_web::middleware::Logger;
use actix_web::web::Data;
use actix_web::{web, App, HttpServer};
use actix_web::{App, HttpServer, web};
use light_openid::basic_state_manager::BasicStateManager;
use std::time::Duration;
use virtweb_backend::actors::libvirt_actor::LibVirtActor;

View File

@ -1,4 +1,4 @@
use std::future::{ready, Ready};
use std::future::{Ready, ready};
use std::rc::Rc;
use crate::app_config::AppConfig;
@ -8,8 +8,8 @@ use crate::extractors::auth_extractor::AuthExtractor;
use actix_web::body::EitherBody;
use actix_web::dev::Payload;
use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error, FromRequest, HttpResponse,
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
};
use futures_util::future::LocalBoxFuture;
@ -68,7 +68,10 @@ where
.unwrap();
if !AppConfig::get().is_allowed_ip(remote_ip.0) {
log::error!("An attempt to access VirtWeb from an unauthorized network has been intercepted! {:?}", remote_ip);
log::error!(
"An attempt to access VirtWeb from an unauthorized network has been intercepted! {:?}",
remote_ip
);
return Ok(req
.into_response(
HttpResponse::MethodNotAllowed()
@ -86,8 +89,8 @@ where
Ok(auth) => auth,
Err(e) => {
log::error!(
"Failed to extract API authentication information from request! {e}"
);
"Failed to extract API authentication information from request! {e}"
);
return Ok(req
.into_response(HttpResponse::PreconditionFailed().finish())
.map_into_right_body());

View File

@ -49,7 +49,9 @@ pub async fn sub_main() -> anyhow::Result<()> {
let args = NatArgs::parse();
if !args.network_file().exists() {
log::warn!("Cannot do anything for the network, because the NAT configuration file does not exixsts!");
log::warn!(
"Cannot do anything for the network, because the NAT configuration file does not exixsts!"
);
return Ok(());
}
@ -184,7 +186,9 @@ fn toggle_port_forwarding(
false => "tcp",
};
log::info!("Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}");
log::info!(
"Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}"
);
// Rule 1
let cmd = Command::new(program)

View File

@ -57,7 +57,7 @@ pub fn is_net_interface_name_valid<D: AsRef<str>>(int: D) -> bool {
/// Get the list of available network interfaces
pub fn net_list() -> Vec<String> {
let mut networks = Networks::new();
networks.refresh_list();
networks.refresh(true);
networks
.list()

View File

@ -1,46 +1,12 @@
# Getting Started with Create React App
# Virtweb frontend
Built with Vite + React + TypeScript
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Get dependencies
```bash
npm install
```
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
# Run for developpment
```bash
npm run dev
```

View File

@ -0,0 +1,54 @@
import js from "@eslint/js";
import reactDom from "eslint-plugin-react-dom";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import reactX from "eslint-plugin-react-x";
import globals from "globals";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [
js.configs.recommended,
...tseslint.configs.strictTypeChecked,
...tseslint.configs.stylisticTypeChecked,
],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
"react-x": reactX,
"react-dom": reactDom,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
...reactX.configs["recommended-typescript"].rules,
...reactDom.configs.recommended.rules,
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/no-extraneous-class": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"react-refresh/only-export-components": "off",
},
}
);

File diff suppressed because it is too large Load Diff

View File

@ -3,63 +3,51 @@
"version": "0.1.0",
"type": "module",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.13.5",
"@emotion/styled": "^11.13.5",
"@fontsource/roboto": "^5.1.0",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@fontsource/roboto": "^5.2.5",
"@mdi/js": "^7.2.96",
"@mdi/react": "^1.6.1",
"@mui/icons-material": "^6.1.8",
"@mui/material": "^6.1.8",
"@mui/x-charts": "^7.22.3",
"@mui/x-data-grid": "^7.22.3",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
"@types/humanize-duration": "^3.27.1",
"@types/jest": "^29.5.14",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.3.3",
"@mui/icons-material": "^7.0.0",
"@mui/material": "^7.0.0",
"@mui/x-charts": "^7.28.0",
"@mui/x-data-grid": "^7.28.1",
"date-and-time": "^3.6.0",
"filesize": "^10.1.6",
"humanize-duration": "^3.29.0",
"mui-file-input": "^6.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^7.0.1",
"mui-file-input": "^7.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.4.0",
"react-syntax-highlighter": "^15.6.1",
"react-vnc": "^2.0.2",
"typescript": "^4.9.5",
"uuid": "^11.0.3",
"vite": "^6.0.0",
"vite-tsconfig-paths": "^5.1.3",
"web-vitals": "^3.5.2",
"react-vnc": "^3.0.7",
"uuid": "^11.1.0",
"xml-formatter": "^3.6.0"
},
"scripts": {
"start": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
"devDependencies": {
"@eslint/js": "^9.21.0",
"@types/humanize-duration": "^3.27.1",
"@types/jest": "^29.5.14",
"@types/react": "^19.0.12",
"@types/react-dom": "^19.0.4",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.21.0",
"eslint-plugin-react-dom": "^1.38.3",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.19",
"eslint-plugin-react-x": "^1.38.3",
"globals": "^15.15.0",
"typescript": "^5.8.2",
"typescript-eslint": "^8.24.1",
"vite": "^6.2.3"
}
}

View File

@ -51,7 +51,10 @@ export function App() {
const context: AuthContext = {
signedIn: signedIn,
setSignedIn: (s) => setSignedIn(s),
setSignedIn: (s) => {
setSignedIn(s);
location.reload();
},
};
const router = createBrowserRouter(
@ -97,12 +100,12 @@ export function App() {
);
return (
<AuthContextK.Provider value={context}>
<AuthContextK value={context}>
<RouterProvider router={router} />
</AuthContextK.Provider>
</AuthContextK>
);
}
export function useAuth(): AuthContext {
return React.useContext(AuthContextK)!;
return React.use(AuthContextK)!;
}

View File

@ -26,7 +26,7 @@ export class APIClient {
* Get backend URL
*/
static backendURL(): string {
const URL = import.meta.env.VITE_APP_BACKEND ?? "";
const URL = String(import.meta.env.VITE_APP_BACKEND ?? "");
if (URL.length === 0) throw new Error("Backend URL undefined!");
return URL;
}
@ -44,7 +44,7 @@ export class APIClient {
*/
static async exec(args: RequestParams): Promise<APIResponse> {
let body: string | undefined | FormData = undefined;
let headers: any = {};
const headers: any = {};
// JSON request
if (args.jsonData) {
@ -66,22 +66,25 @@ export class APIClient {
if (args.upProgress) {
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (e) =>
args.upProgress!(e.loaded / e.total)
);
xhr.addEventListener("load", () => resolve(xhr));
xhr.addEventListener("error", () =>
reject(new Error("File upload failed"))
);
xhr.addEventListener("abort", () =>
reject(new Error("File upload aborted"))
);
xhr.addEventListener("timeout", () =>
reject(new Error("File upload timeout"))
);
xhr.upload.addEventListener("progress", (e) => {
args.upProgress!(e.loaded / e.total);
});
xhr.addEventListener("load", () => {
resolve(xhr);
});
xhr.addEventListener("error", () => {
reject(new Error("File upload failed"));
});
xhr.addEventListener("abort", () => {
reject(new Error("File upload aborted"));
});
xhr.addEventListener("timeout", () => {
reject(new Error("File upload timeout"));
});
xhr.open(args.method, url, true);
xhr.withCredentials = true;
for (const key in headers) {
// eslint-disable-next-line no-prototype-builtins
if (headers.hasOwnProperty(key))
xhr.setRequestHeader(key, headers[key]);
}

View File

@ -140,7 +140,7 @@ export interface NWFilter {
rules: NWFilterRule[];
}
export function NWFilterURL(n: NWFilter, edit: boolean = false): string {
export function NWFilterURL(n: NWFilter, edit = false): string {
return `/nwfilter/${n.uuid}${edit ? "/edit" : ""}`;
}
@ -221,7 +221,7 @@ export class NWFilterApi {
static async Delete(n: NWFilter): Promise<void> {
await APIClient.exec({
method: "DELETE",
uri: `/nwfilter/${n.uuid}`,
uri: `/nwfilter/${n.uuid!}`,
});
}
}

View File

@ -53,7 +53,7 @@ export interface NetworkInfo {
export type NetworkStatus = "Started" | "Stopped";
export function NetworkURL(n: NetworkInfo, edit: boolean = false): string {
export function NetworkURL(n: NetworkInfo, edit = false): string {
return `/net/${n.uuid}${edit ? "/edit" : ""}`;
}

View File

@ -20,7 +20,7 @@ export interface APIToken {
max_inactivity?: number;
}
export function APITokenURL(t: APIToken, edit: boolean = false): string {
export function APITokenURL(t: APIToken, edit = false): string {
return `/token/${t.id}${edit ? "/edit" : ""}`;
}

View File

@ -39,7 +39,7 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
return (
<>
<AlertContextK.Provider value={hook}>{p.children}</AlertContextK.Provider>
<AlertContextK value={hook}>{p.children}</AlertContextK>
<Dialog
open={open}
@ -67,5 +67,5 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
}
export function useAlert(): AlertContext {
return React.useContext(AlertContextK)!;
return React.use(AlertContextK)!;
}

View File

@ -59,13 +59,13 @@ export function ConfirmDialogProvider(
return (
<>
<ConfirmContextK.Provider value={hook}>
<ConfirmContextK value={hook}>
{p.children}
</ConfirmContextK.Provider>
</ConfirmContextK>
<Dialog
open={open}
onClose={() => handleClose(false)}
onClose={() => { handleClose(false); }}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
@ -76,10 +76,10 @@ export function ConfirmDialogProvider(
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => handleClose(false)} autoFocus>
<Button onClick={() => { handleClose(false); }} autoFocus>
{cancelButton ?? "Cancel"}
</Button>
<Button onClick={() => handleClose(true)} color="error">
<Button onClick={() => { handleClose(true); }} color="error">
{confirmButton ?? "Confirm"}
</Button>
</DialogActions>
@ -89,5 +89,5 @@ export function ConfirmDialogProvider(
}
export function useConfirm(): ConfirmContext {
return React.useContext(ConfirmContextK)!;
return React.use(ConfirmContextK)!;
}

View File

@ -6,10 +6,10 @@ import {
} from "@mui/material";
import React, { PropsWithChildren } from "react";
type LoadingMessageContext = {
interface LoadingMessageContext {
show: (message: string) => void;
hide: () => void;
};
}
const LoadingMessageContextK =
React.createContext<LoadingMessageContext | null>(null);
@ -34,9 +34,9 @@ export function LoadingMessageProvider(
return (
<>
<LoadingMessageContextK.Provider value={hook}>
<LoadingMessageContextK value={hook}>
{p.children}
</LoadingMessageContextK.Provider>
</LoadingMessageContextK>
<Dialog open={open}>
<DialogContent>
@ -60,5 +60,5 @@ export function LoadingMessageProvider(
}
export function useLoadingMessage(): LoadingMessageContext {
return React.useContext(LoadingMessageContextK)!;
return React.use(LoadingMessageContextK)!;
}

View File

@ -24,9 +24,9 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
return (
<>
<SnackbarContextK.Provider value={hook}>
<SnackbarContextK value={hook}>
{p.children}
</SnackbarContextK.Provider>
</SnackbarContextK>
<Snackbar
open={open}
@ -39,5 +39,5 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
}
export function useSnackbar(): SnackbarContext {
return React.useContext(SnackbarContextK)!;
return React.use(SnackbarContextK)!;
}

View File

@ -7,7 +7,6 @@ import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./App";
import "./index.css";
import reportWebVitals from "./reportWebVitals";
import { LoadServerConfig } from "./widgets/LoadServerConfig";
import { ThemeProvider, createTheme } from "@mui/material";
import { LoadingMessageProvider } from "./hooks/providers/LoadingMessageProvider";
@ -22,7 +21,7 @@ const darkTheme = createTheme({
});
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
document.getElementById("root")!
);
root.render(
<React.StrictMode>
@ -41,8 +40,3 @@ root.render(
</ThemeProvider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -1,15 +0,0 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -116,7 +116,7 @@ function EditApiTokenRouteInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => updateState({}), []);
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
const valueChanged = () => {
setChanged(true);

View File

@ -99,7 +99,7 @@ function EditNetworkFilterRouteInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => updateState({}), []);
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
const valueChanged = () => {
setChanged(true);

View File

@ -97,7 +97,7 @@ function EditNetworkRouteInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => updateState({}), []);
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
const valueChanged = () => {
setChanged(true);

View File

@ -15,7 +15,7 @@ export function CreateVMRoute(): React.ReactElement {
const alert = useAlert();
const navigate = useNavigate();
const [vm, setVM] = React.useState(VMInfo.NewEmpty);
const [vm, setVM] = React.useState(VMInfo.NewEmpty());
const create = async (v: VMInfo) => {
try {
@ -103,7 +103,9 @@ function EditVMInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => updateState({}), []);
const forceUpdate = React.useCallback(() => {
updateState({});
}, []);
const valueChanged = () => {
setChanged(true);

View File

@ -96,7 +96,7 @@ function UploadIsoFileCard(p: {
p.onFileUploaded();
} catch (e) {
console.error(e);
await alert("Failed to perform file upload! " + e);
await alert(`Failed to perform file upload! ${e}`);
}
setUploadProgress(null);
@ -120,7 +120,9 @@ function UploadIsoFileCard(p: {
value={value}
onChange={handleChange}
style={{ flex: 1 }}
inputProps={{ accept: ServerApi.Config.iso_mimetypes.join(",") }}
slotProps={{
htmlInput: { accept: ServerApi.Config.iso_mimetypes.join(",") },
}}
/>
{value && <Button onClick={upload}>Upload file</Button>}
@ -147,6 +149,8 @@ function UploadIsoFileFromUrlCard(p: {
loadingMessage.show("Downloading file from URL...");
await IsoFilesApi.UploadFromURL(url, actualFileName);
p.onFileUploaded();
setURL("");
setFilename(null);
snackbar("Successfully downloaded file!");
@ -164,14 +168,18 @@ function UploadIsoFileFromUrlCard(p: {
label="URL"
value={url}
style={{ flex: 3 }}
onChange={(e) => setURL(e.target.value)}
onChange={(e) => {
setURL(e.target.value);
}}
/>
<span style={{ width: "10px" }}></span>
<TextField
label="Filename"
value={actualFileName}
style={{ flex: 2 }}
onChange={(e) => setFilename(e.target.value)}
onChange={(e) => {
setFilename(e.target.value);
}}
/>
{url !== "" && actualFileName !== "" && (
<Button onClick={upload}>Upload file</Button>
@ -198,7 +206,7 @@ function IsoFilesList(p: {
try {
const blob = await IsoFilesApi.Download(entry, setDlProgress);
await downloadBlob(blob, entry.filename);
downloadBlob(blob, entry.filename);
} catch (e) {
console.error(e);
alert("Failed to download iso file!");
@ -236,7 +244,7 @@ function IsoFilesList(p: {
</Typography>
);
const columns: GridColDef[] = [
const columns: GridColDef<IsoFile>[] = [
{ field: "filename", headerName: "File name", flex: 3 },
{
field: "size",
@ -301,7 +309,6 @@ function IsoFilesList(p: {
getRowId={(c) => c.filename}
rows={p.list}
columns={columns}
autoHeight={true}
/>
</VirtWebPaper>
</>

View File

@ -66,7 +66,7 @@ function NetworkFiltersListRouteInner(p: {
const onlyBuiltin = visibleFilters === VisibleFilters.Builtin;
return p.list.filter((f) => NWFilterIsBuiltin(f) === onlyBuiltin);
}, [visibleFilters]);
}, [visibleFilters, p.list]);
return (
<VirtWebRouteContainer
@ -78,7 +78,9 @@ function NetworkFiltersListRouteInner(p: {
size="small"
value={visibleFilters}
exclusive
onChange={(_ev, v) => setVisibleFilters(v)}
onChange={(_ev, v) => {
setVisibleFilters(v);
}}
aria-label="visible filters"
>
<ToggleButton value={VisibleFilters.All}>All</ToggleButton>
@ -130,8 +132,8 @@ function NetworkFiltersListRouteInner(p: {
</TableCell>
<TableCell>
<ul>
{t.join_filters.map((f, n) => (
<li key={n}>{f}</li>
{t.join_filters.map((f) => (
<li key={f}>{f}</li>
))}
</ul>
</TableCell>

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import {
mdiHarddisk,
mdiInformation,
@ -16,7 +17,7 @@ import {
TableRow,
Typography,
} from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import { PieChart } from "@mui/x-charts";
import { filesize } from "filesize";
import humanizeDuration from "humanize-duration";
@ -236,7 +237,7 @@ export function SysInfoRouteInner(p: {
function SysInfoDetailsTable(p: {
label: string;
icon: React.ReactElement;
entries: Array<{ label: string; value: string | number }>;
entries: { label: string; value: string | number }[];
}): React.ReactElement {
return (
<VirtWebPaper

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import VisibilityIcon from "@mui/icons-material/Visibility";
import {
Button,
@ -99,9 +100,9 @@ export function TokensListRouteInner(p: {
{t.max_inactivity && timeDiff(0, t.max_inactivity)}
</TableCell>
<TableCell>
{t.rights.map((r) => {
{t.rights.map((r, n) => {
return (
<div>
<div key={n}>
{r.verb} {r.path}
</div>
);

View File

@ -25,13 +25,13 @@ import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import { VMStatusWidget } from "../widgets/vms/VMStatusWidget";
export function VMListRoute(): React.ReactElement {
const [groups, setGroups] = React.useState<Array<string | undefined>>();
const [groups, setGroups] = React.useState<(string | undefined)[]>();
const [list, setList] = React.useState<VMInfo[] | undefined>();
const loadKey = React.useRef(1);
const load = async () => {
const groups: Array<string | undefined> = await GroupApi.GetList();
const groups: (string | undefined)[] = await GroupApi.GetList();
const list = await VMApi.GetList();
if (list.find((v) => !v.group) !== undefined) groups.push(undefined);
@ -70,7 +70,7 @@ export function VMListRoute(): React.ReactElement {
}
function VMListWidget(p: {
groups: Array<string | undefined>;
groups: (string | undefined)[];
list: VMInfo[];
onReload: () => void;
}): React.ReactElement {
@ -115,8 +115,8 @@ function VMListWidget(p: {
</TableRow>
</TableHead>
<TableBody>
{p.groups.map((g, num) => (
<React.Fragment key={num}>
{p.groups.map((g) => (
<React.Fragment key={g}>
{p.groups.length > 1 && (
<TableRow>
<TableCell
@ -125,9 +125,11 @@ function VMListWidget(p: {
>
<IconButton
size="small"
onClick={() => toggleHiddenGroup(g)}
onClick={() => {
toggleHiddenGroup(g);
}}
>
{!hiddenGroups?.has(g) ? (
{!hiddenGroups.has(g) ? (
<KeyboardArrowUpIcon />
) : (
<KeyboardArrowDownIcon />
@ -157,7 +159,9 @@ function VMListWidget(p: {
<TableCell>
<VMStatusWidget
vm={row}
onChange={(s) => updateVMState(row, s)}
onChange={(s) => {
updateVMState(row, s);
}}
/>
</TableCell>
<TableCell>

View File

@ -1,17 +1,16 @@
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import FullscreenIcon from "@mui/icons-material/Fullscreen";
import FullscreenExitIcon from "@mui/icons-material/FullscreenExit";
import KeyboardAltIcon from "@mui/icons-material/KeyboardAlt";
import { IconButton, Tooltip } from "@mui/material";
import React, { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { VncScreen } from "react-vnc";
import { VncScreen, VncScreenHandle } from "react-vnc";
import { ServerApi } from "../api/ServerApi";
import { VMApi, VMInfo } from "../api/VMApi";
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
import { time } from "../utils/DateUtils";
import { AsyncWidget } from "../widgets/AsyncWidget";
import RFB from "react-vnc/dist/types/noVNC/core/rfb";
import KeyboardAltIcon from "@mui/icons-material/KeyboardAlt";
interface VNCTokenInfo {
url: string;
@ -43,9 +42,10 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
const [token, setToken] = React.useState<VNCTokenInfo | undefined>();
const [counter, setCounter] = React.useState(1);
const [rfb, setRFB] = React.useState<RFB | undefined>();
const [connected, setConnected] = React.useState(false);
const vncRef = React.createRef<HTMLDivElement>();
const vncRef = React.useRef<HTMLDivElement>(null);
const vncScreenRef = React.useRef<VncScreenHandle>(null);
const connect = async (force: boolean) => {
try {
@ -71,7 +71,7 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
};
const disconnected = () => {
setRFB(undefined);
setConnected(false);
connect(true);
};
@ -91,7 +91,9 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
connect(false);
if (vncRef.current) {
vncRef.current.onfullscreenchange = () => setCounter(counter + 1);
vncRef.current.onfullscreenchange = () => {
setCounter(counter + 1);
};
}
});
@ -118,9 +120,9 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
)}
{/* Keystrokes */}
{rfb && (
{connected && (
<Tooltip title="Send Ctrl+Alt+Del">
<IconButton onClick={() => rfb?.sendCtrlAltDel()}>
<IconButton onClick={() => vncScreenRef.current?.sendCtrlAltDel()}>
<KeyboardAltIcon />
</IconButton>
</Tooltip>
@ -137,12 +139,15 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
}}
>
<VncScreen
ref={vncScreenRef}
url={token.url}
onDisconnect={() => {
console.info("VNC disconnected " + token?.url);
console.info("VNC disconnected " + token.url);
disconnected();
}}
onConnect={(rfb) => setRFB(rfb)}
onConnect={() => {
setConnected(true);
}}
/>
</div>
</div>

View File

@ -1,4 +1,5 @@
import { Visibility, VisibilityOff } from "@mui/icons-material";
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import {
Alert,
CircularProgress,
@ -35,7 +36,7 @@ export function LoginRoute(): React.ReactElement {
const canSubmit = username.length > 0 && password.length > 0;
const [showPassword, setShowPassword] = React.useState(false);
const handleClickShowPassword = () => setShowPassword((show) => !show);
const handleClickShowPassword = () => { setShowPassword((show) => !show); };
const handleMouseDownPassword = (
event: React.MouseEvent<HTMLButtonElement>
@ -104,7 +105,7 @@ export function LoginRoute(): React.ReactElement {
label="Username"
name="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
onChange={(e) => { setUsername(e.target.value); }}
autoComplete="username"
autoFocus
/>
@ -119,7 +120,7 @@ export function LoginRoute(): React.ReactElement {
type={showPassword ? "text" : "password"}
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onChange={(e) => { setPassword(e.target.value); }}
autoComplete="current-password"
endAdornment={
<InputAdornment position="end">
@ -130,7 +131,7 @@ export function LoginRoute(): React.ReactElement {
onMouseDown={handleMouseDownPassword}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
{showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
</IconButton>
</Tooltip>
</InputAdornment>

View File

@ -1,5 +0,0 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -1,4 +1,4 @@
export async function downloadBlob(blob: Blob, filename: string) {
export function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");

View File

@ -2,8 +2,9 @@
* Generate a random MAC address
*/
export function randomMacAddress(prefix: string | undefined): string {
prefix = prefix ?? "";
let mac = "XX:XX:XX:XX:XX:XX";
mac = prefix + mac.slice(prefix?.length);
mac = prefix + mac.slice(prefix.length);
return mac.replace(/X/g, () =>
"0123456789abcdef".charAt(Math.floor(Math.random() * 16))

View File

@ -19,7 +19,7 @@ export function AsyncWidget(p: {
}): React.ReactElement {
const [state, setState] = useState(State.Loading);
const counter = useRef<any | null>(null);
const counter = useRef<any>(null);
const load = async () => {
try {
@ -67,7 +67,7 @@ export function AsyncWidget(p: {
<Button onClick={load}>Try again</Button>
{p.errAdditionalElement && p.errAdditionalElement()}
{p.errAdditionalElement?.()}
</Box>
)
);

View File

@ -13,11 +13,9 @@ import {
List,
ListItemButton,
ListItemIcon,
ListItemSecondaryAction,
ListItemText,
ListItemText
} from "@mui/material";
import { Outlet, useLocation } from "react-router-dom";
import { isDebug } from "../utils/DebugUtils";
import { RouterLink } from "./RouterLink";
import { VirtWebAppBar } from "./VirtWebAppBar";
@ -96,7 +94,6 @@ function NavLink(p: {
icon: React.ReactElement;
uri: string;
label: string;
secondaryAction?: React.ReactElement;
}): React.ReactElement {
const location = useLocation();
return (
@ -104,9 +101,6 @@ function NavLink(p: {
<ListItemButton selected={p.uri === location.pathname}>
<ListItemIcon>{p.icon}</ListItemIcon>
<ListItemText primary={p.label} />
{p.secondaryAction && (
<ListItemSecondaryAction>{p.secondaryAction}</ListItemSecondaryAction>
)}
</ListItemButton>
</RouterLink>
);

View File

@ -3,7 +3,7 @@ import Icon from "@mdi/react";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import CssBaseline from "@mui/material/CssBaseline";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import Paper from "@mui/material/Paper";
import Typography from "@mui/material/Typography";
import { Link, Outlet } from "react-router-dom";

View File

@ -31,14 +31,16 @@ export function ConfigImportExportButtons(p: {
fileEl.click();
// Wait for a file to be chosen
await new Promise((res, _rej) =>
fileEl.addEventListener("change", () => res(null))
);
await new Promise((res) => {
fileEl.addEventListener("change", () => {
res(null);
});
});
if ((fileEl.files?.length ?? 0) === 0) return null;
// Import conf
let file = fileEl.files![0];
const file = fileEl.files![0];
const content = await file.text();
p.importConf?.(JSON.parse(content));
} catch (e) {

View File

@ -23,7 +23,7 @@ export function StateActionButton<S>(p: {
p.onExecuted();
} catch (e) {
console.error(e);
alert("Failed to perform action! " + e);
alert(`Failed to perform action! ${e}`);
}
};

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import { Box, Tab, Tabs } from "@mui/material";
export interface TabWidgetOption<E> {
@ -24,7 +25,9 @@ export function TabsWidget<E>(p: {
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<Tabs
value={currTabIndex}
onChange={(_ev, newVal) => updateActiveTab(newVal)}
onChange={(_ev, newVal) => {
updateActiveTab(newVal);
}}
>
{activeOptions.map((o, index) => (
<Tab key={index} label={o.label} style={{ color: o.color }} />

View File

@ -17,7 +17,7 @@ export function CheckboxInput(p: {
<Checkbox
disabled={!p.editable}
checked={p.checked}
onChange={(e) => p.onValueChange(e.target.checked)}
onChange={(e) => { p.onValueChange(e.target.checked); }}
/>
}
label={p.label}

View File

@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
import { Paper, Typography } from "@mui/material";
import React, { PropsWithChildren } from "react";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
export function EditSection(
p: {

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import React from "react";
import { TextInput } from "./TextInput";
@ -32,7 +33,7 @@ export function IPInputWithMask(p: {
const currValue =
p.ipAndMask ??
(p.ip ?? "") + (p.mask || showSlash.current ? "/" : "") + (p.mask ?? "");
`${p.ip ?? ""}${p.mask || showSlash.current ? "/" : ""}${p.mask ?? ""}`;
const { onValueChange, ...props } = p;
return (
@ -44,7 +45,7 @@ export function IPInputWithMask(p: {
return;
}
const split = v?.split("/");
const split = v.split("/");
const ip =
p.version === 4 ? sanitizeIpV4(split[0]) : sanitizeIpV6(split[0]);
let mask = undefined;
@ -69,7 +70,7 @@ export function IPInputWithMask(p: {
function sanitizeIpV4(s: string | undefined): string | undefined {
if (s === "" || s === undefined) return s;
let split = s.split(".");
const split = s.split(".");
if (split.length > 4) split.splice(4);
let needAnotherIteration = false;
@ -106,7 +107,7 @@ function sanitizeIpV6(s: string | undefined): string | undefined {
const num = parseInt(e, 16);
if (isNaN(num)) return "0";
let s = num.toString(16);
const s = num.toString(16);
if (num > 0xffff) {
needAnotherIteration = true;
return s.slice(0, 4) + ":" + s.slice(4);

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import { TextInput } from "./TextInput";
export function MACInput(p: {
@ -32,7 +33,7 @@ function sanitizeMacAddress(s: string | undefined): string | undefined {
const num = parseInt(e, 16);
if (isNaN(num)) return "0";
let s = num.toString(16).padStart(2, "0");
const s = num.toString(16).padStart(2, "0");
if (num > 0xff) {
needAnotherIteration = true;
return s.slice(0, 2) + ":" + s.slice(2);

View File

@ -12,7 +12,7 @@ export function NWFConnStateInput(p: {
label="Connection state"
value={p.value}
onValueChange={(s) => {
p.onChange?.(s as any);
p.onChange(s as any);
}}
options={[
{ label: "None", value: undefined },

View File

@ -1,3 +1,5 @@
/* eslint-disable react-x/no-array-index-key */
/* eslint-disable react-hooks/exhaustive-deps */
import React from "react";
import { useNavigate } from "react-router-dom";
import { NWFilter, NWFilterURL } from "../../api/NWFilterApi";

View File

@ -13,7 +13,7 @@ export function NWFilterPriorityInput(p: {
value={p.value?.toString()}
type="number"
onValueChange={(v) => {
p.onChange?.(v && v !== "" ? Number(v) : undefined);
p.onChange(v && v !== "" ? Number(v) : undefined);
}}
size={ServerApi.Config.constraints.nwfilter_priority}
helperText="A lower priority value is accessed before one with a higher value"

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import ArrowDownwardIcon from "@mui/icons-material/ArrowDownward";
import ArrowUpwardIcon from "@mui/icons-material/ArrowUpward";
import DeleteIcon from "@mui/icons-material/Delete";
@ -66,9 +67,19 @@ export function NWFilterRules(p: {
deleteRule(n);
}}
onGoDown={
n < p.rules.length - 1 ? () => swapRules(n, n + 1) : undefined
n < p.rules.length - 1
? () => {
swapRules(n, n + 1);
}
: undefined
}
onGoUp={
n > 0
? () => {
swapRules(n, n - 1);
}
: undefined
}
onGoUp={n > 0 ? () => swapRules(n, n - 1) : undefined}
{...p}
/>
))}
@ -153,7 +164,9 @@ function NWRuleEdit(p: {
editable={p.editable}
onChange={p.onChange}
selector={s}
onDelete={() => deleteSelector(n)}
onDelete={() => {
deleteSelector(n);
}}
/>
))}
</CardContent>

View File

@ -25,9 +25,7 @@ export function NWFilterSelectInput(p: {
value={selectedValue}
onDelete={p.editable ? () => p.onChange?.(undefined) : undefined}
onClick={
!p.editable && selectedValue
? () => navigate(NWFilterURL(selectedValue))
: undefined
!p.editable ? () => navigate(NWFilterURL(selectedValue)) : undefined
}
/>
);
@ -48,7 +46,7 @@ export function NWFilterSelectInput(p: {
renderInput={(params) => (
<TextField {...params} variant="standard" label={p.label} />
)}
renderOption={(_props, option, _state) => (
renderOption={(_props, option) => (
<NWFilterItem
dense
onClick={() => {

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import { mdiIp } from "@mdi/js";
import Icon from "@mdi/react";
import DeleteIcon from "@mui/icons-material/Delete";
@ -18,7 +19,7 @@ import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
import { IPInput } from "./IPInput";
import { MACInput } from "./MACInput";
import { TextInput } from "./TextInput";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
export function NetDHCPHostReservations(p: {
editable: boolean;
@ -130,7 +131,7 @@ function HostReservationWidget(p: {
value={p.host.mac}
onValueChange={(v) => {
p.host.mac = v!;
p.onChange?.();
p.onChange();
}}
/>
)}
@ -142,7 +143,7 @@ function HostReservationWidget(p: {
value={p.host.ip}
onValueChange={(v) => {
p.host.ip = v!;
p.onChange?.();
p.onChange();
}}
/>
</div>

View File

@ -9,7 +9,7 @@ import {
Tooltip,
Typography,
} from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import React, { PropsWithChildren } from "react";
import { NatEntry } from "../../api/NetworksApi";
import { ServerApi } from "../../api/ServerApi";
@ -54,6 +54,7 @@ export function NetNatConfiguration(p: {
<>
{p.nat.map((e, num) => (
<NatEntryForm
// eslint-disable-next-line react-x/no-array-index-key
key={num}
{...p}
entry={e}

View File

@ -12,7 +12,7 @@ export function PortInput(p: {
value={p.value?.toString() ?? ""}
type="number"
onValueChange={(v) => {
p.onChange?.(sanitizePort(v));
p.onChange(sanitizePort(v));
}}
checkValue={(v) => Number(v) <= 65535}
/>

View File

@ -24,10 +24,13 @@ export function RadioGroupInput(p: {
<RadioGroup
row
value={p.value}
onChange={(_ev, v) => p.onValueChange?.(v)}
onChange={(_ev, v) => {
p.onValueChange(v);
}}
>
{p.options.map((o) => (
<FormControlLabel
key={o.value}
disabled={!p.editable}
value={o.value}
control={<Radio />}

View File

@ -33,7 +33,7 @@ export function SelectInput(p: {
<Select
value={p.value ?? ""}
label={p.label}
onChange={(e) => p.onValueChange(e.target.value)}
onChange={(e) => { p.onValueChange(e.target.value); }}
>
{p.options.map((e) => (
<MenuItem

View File

@ -2,7 +2,7 @@ import { TextField } from "@mui/material";
import { LenConstraint } from "../../api/ServerApi";
/**
* Couple / Member property edition
* Text input property edition
*/
export function TextInput(p: {
label?: string;
@ -42,12 +42,14 @@ export function TextInput(p: {
e.target.value.length === 0 ? undefined : e.target.value
)
}
inputProps={{
maxLength: p.size?.max,
}}
InputProps={{
readOnly: !p.editable,
type: p.type,
slotProps={{
htmlInput: {
maxLength: p.size?.max,
},
input: {
readOnly: !p.editable,
type: p.type,
},
}}
variant={"standard"}
style={p.style ?? { width: "100%", marginBottom: "15px" }}

View File

@ -40,6 +40,7 @@ export function VMDisksList(p: {
{/* disks list */}
{p.vm.disks.map((d, num) => (
<DiskInfo
// eslint-disable-next-line react-x/no-array-index-key
key={num}
editable={p.editable}
disk={d}

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import DeleteIcon from "@mui/icons-material/Delete";
import {
Button,

View File

@ -1,3 +1,4 @@
/* eslint-disable react-x/no-array-index-key */
import { mdiNetworkOutline } from "@mdi/js";
import Icon from "@mdi/react";
import DeleteIcon from "@mui/icons-material/Delete";
@ -10,7 +11,7 @@ import {
ListItemText,
Tooltip,
} from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import { NWFilter } from "../../api/NWFilterApi";
import { NetworkInfo } from "../../api/NetworksApi";
import { ServerApi } from "../../api/ServerApi";
@ -51,7 +52,6 @@ export function VMNetworksList(p: {
{p.vm.networks.map((n, num) => (
<EditSection key={num}>
<NetworkInfoWidget
key={num}
network={n}
removeFromList={() => {
p.vm.networks.splice(num, 1);

View File

@ -19,7 +19,7 @@ export function VMSelectIsoInput(p: {
attachedISOs: string[];
onChange: (newVal: string[]) => void;
}): React.ReactElement {
if (!p.attachedISOs && !p.editable) return <></>;
if (p.attachedISOs.length === 0 && !p.editable) return <></>;
return (
<>
@ -27,7 +27,7 @@ export function VMSelectIsoInput(p: {
const iso = p.isoList.find((d) => d.filename === isoName);
return (
<ListItem
key={num}
key={isoName}
secondaryAction={
p.editable && (
<IconButton
@ -69,12 +69,11 @@ export function VMSelectIsoInput(p: {
}
}}
options={p.isoList.map((i) => {
return {
label: `${i.filename} ${filesize(i.size)}`,
value: i.filename,
};
})
}
return {
label: `${i.filename} ${filesize(i.size)}`,
value: i.filename,
};
})}
/>
</>
);

View File

@ -1,5 +1,5 @@
import { Button, Checkbox } from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import React from "react";
import { useNavigate } from "react-router-dom";
import { IpConfig, NetworkApi, NetworkInfo } from "../../api/NetworksApi";
@ -25,7 +25,7 @@ interface DetailsProps {
}
export function NetworkDetails(p: DetailsProps): React.ReactElement {
const [nicsList, setNicsList] = React.useState<string[] | any>();
const [nicsList, setNicsList] = React.useState<string[] | undefined>();
const load = async () => {
setNicsList(await ServerApi.GetNetworksList());
@ -36,7 +36,7 @@ export function NetworkDetails(p: DetailsProps): React.ReactElement {
loadKey={"1"}
load={load}
errMsg="Failed to load the list of host network cards!"
build={() => <NetworkDetailsInner nicsList={nicsList} {...p} />}
build={() => <NetworkDetailsInner nicsList={nicsList!} {...p} />}
/>
);
}
@ -260,7 +260,7 @@ function IPSection(p: {
const confirm = useConfirm();
const toggleNetwork = async () => {
if (!!p.config) {
if (p.config) {
if (
!(await confirm(
`Do you really want to disable IPv${p.version} on this network? Specific configuration will be deleted!`
@ -268,11 +268,11 @@ function IPSection(p: {
)
return;
p.onChange?.(undefined);
p.onChange(undefined);
return;
}
p.onChange?.({
p.onChange({
bridge_address: p.version === 4 ? "192.168.1.1" : "fd00::1",
prefix: p.version === 4 ? 24 : 8,
});
@ -298,7 +298,7 @@ function IPSection(p: {
p.config!.dhcp = undefined;
}
p.onChange?.(p.config);
p.onChange(p.config);
};
const toggleNAT = async (v: boolean) => {
@ -306,7 +306,7 @@ function IPSection(p: {
p.config!.nat = [];
} else {
if (
(p.config?.nat?.length ?? 0 > 0) &&
(p.config?.nat?.length ?? 0) > 0 &&
!(await confirm(
`Do you really want to disable IPv${p.version} NAT port forwarding on this network? Specific configuration will be deleted!`
))
@ -315,7 +315,7 @@ function IPSection(p: {
p.config!.nat = undefined;
}
p.onChange?.(p.config);
p.onChange(p.config);
};
if (!p.config && !p.editable) return <></>;
@ -338,10 +338,10 @@ function IPSection(p: {
editable={p.editable}
label="Bridge address"
version={p.version}
value={p.config?.bridge_address}
value={p.config.bridge_address}
onValueChange={(v) => {
p.config!.bridge_address = v ?? "";
p.onChange?.(p.config);
p.onChange(p.config);
}}
/>
@ -352,7 +352,7 @@ function IPSection(p: {
type="number"
onValueChange={(v) => {
p.config!.prefix = Number(v);
p.onChange?.(p.config);
p.onChange(p.config);
}}
size={
p.version === 4 ? { min: 0, max: 32 } : { min: 0, max: 128 }
@ -407,7 +407,7 @@ function IPSection(p: {
dhcp={p.config.dhcp}
onChange={(d) => {
p.config!.dhcp = d;
p.onChange?.(p.config);
p.onChange(p.config);
}}
/>
</EditSection>
@ -431,7 +431,7 @@ function IPSection(p: {
nat={p.config.nat}
onChange={(n) => {
p.config!.nat = n;
p.onChange?.(p.config);
p.onChange(p.config);
}}
/>
)}

View File

@ -29,13 +29,13 @@ export function NetworkStatusWidget(p: {
}
};
const changedAction = () => setState(undefined);
const changedAction = () => { setState(undefined); };
React.useEffect(() => {
refresh();
const i = setInterval(() => refresh(), 3000);
return () => clearInterval(i);
return () => { clearInterval(i); };
});
if (state === undefined)

View File

@ -1,5 +1,5 @@
import { Button } from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import React, { ReactElement } from "react";
import { useNavigate } from "react-router-dom";
import {
@ -28,7 +28,9 @@ interface DetailsProps {
}
export function NWFilterDetails(p: DetailsProps): ReactElement {
const [nwFiltersList, setNwFiltersList] = React.useState<NWFilter[] | any>();
const [nwFiltersList, setNwFiltersList] = React.useState<
NWFilter[] | undefined
>();
const load = async () => {
setNwFiltersList(await NWFilterApi.GetList());
@ -40,7 +42,7 @@ export function NWFilterDetails(p: DetailsProps): ReactElement {
load={load}
errMsg="Failed to load the list of network filters!"
build={() => (
<NetworkFilterDetailsInner nwFiltersList={nwFiltersList} {...p} />
<NetworkFilterDetailsInner nwFiltersList={nwFiltersList!} {...p} />
)}
/>
);
@ -116,7 +118,7 @@ function NetworkFilterDetailsTabGeneral(
p.nwfilter.name = v ?? "";
p.onChange?.();
}}
checkValue={(v) => /^[a-zA-Z0-9\_\-]+$/.test(v)}
checkValue={(v) => /^[a-zA-Z0-9_-]+$/.test(v)}
size={ServerApi.Config.constraints.nwfilter_name_size}
/>

View File

@ -1,5 +1,5 @@
import { Button } from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import React from "react";
import { useNavigate } from "react-router-dom";
import { GroupApi } from "../../api/GroupApi";
@ -161,14 +161,14 @@ function APITokenTabGeneral(p: DetailsInnerProps): React.ReactElement {
{p.status === TokenWidgetStatus.Create && (
<RadioGroupInput
{...p}
editable={p.status === TokenWidgetStatus.Create}
editable={true}
options={[
{ label: "IPv4", value: "4" },
{ label: "IPv6", value: "6" },
]}
value={ipVersion.toString()}
onValueChange={(v) => {
setIpVersion(Number(v) as any);
setIpVersion(Number(v) as 4 | 6);
}}
label="Token IP restriction version"
/>

View File

@ -63,6 +63,7 @@ export function TokenRawRightsEditor(p: {
</TableHead>
<TableBody>
{p.token.rights.map((r, num) => (
// eslint-disable-next-line react-x/no-array-index-key
<TableRow key={num} hover>
<TableCell style={{ width: "100px" }}>
<SelectInput
@ -95,7 +96,11 @@ export function TokenRawRightsEditor(p: {
</TableCell>
{p.editable && (
<TableCell style={{ width: "100px" }}>
<IconButton onClick={() => deleteRule(num)}>
<IconButton
onClick={() => {
deleteRule(num);
}}
>
<Tooltip title="Remove the rule">
<DeleteIcon />
</Tooltip>

View File

@ -85,8 +85,8 @@ export function TokenRightsEditor(p: {
</TableRow>
{/* Per VM operations */}
{p.vms.map((v, n) => (
<TableRow hover key={n}>
{p.vms.map((v) => (
<TableRow hover key={v.uuid}>
<TableCell>{v.name}</TableCell>
<CellRight
{...p}
@ -185,8 +185,8 @@ export function TokenRightsEditor(p: {
</TableRow>
{/* Per VM operations */}
{p.vms.map((v, n) => (
<TableRow hover key={n}>
{p.vms.map((v) => (
<TableRow hover key={v.uuid}>
<TableCell>{v.name}</TableCell>
<CellRight
{...p}
@ -306,8 +306,8 @@ export function TokenRightsEditor(p: {
</TableRow>
{/* Per VM operations */}
{p.groups.map((v, n) => (
<TableRow hover key={n}>
{p.groups.map((v) => (
<TableRow hover key={v}>
<TableCell>{v}</TableCell>
<CellRight
{...p}
@ -448,8 +448,8 @@ export function TokenRightsEditor(p: {
</TableRow>
{/* Per network operations */}
{p.networks.map((v, n) => (
<TableRow hover key={n}>
{p.networks.map((v) => (
<TableRow hover key={v.uuid}>
<TableCell>{v.name}</TableCell>
<CellRight
{...p}
@ -568,15 +568,15 @@ export function TokenRightsEditor(p: {
</TableRow>
{/* Per network filter operations */}
{p.nwFilters.map((v, n) => (
<TableRow hover key={n}>
{p.nwFilters.map((v) => (
<TableRow hover key={v.uuid}>
<TableCell>{v.name}</TableCell>
<CellRight
{...p}
right={{ verb: "GET", path: `/api/nwfilter/${v.uuid}` }}
parent={{ verb: "GET", path: "/api/nwfilter/*" }}
/>
{ServerApi.Config.builtin_nwfilter_rules.includes(v.name!) ? (
{ServerApi.Config.builtin_nwfilter_rules.includes(v.name) ? (
<TableCell></TableCell>
) : (
<CellRight
@ -585,7 +585,7 @@ export function TokenRightsEditor(p: {
parent={{ verb: "PUT", path: "/api/nwfilter/*" }}
/>
)}
{ServerApi.Config.builtin_nwfilter_rules.includes(v.name!) ? (
{ServerApi.Config.builtin_nwfilter_rules.includes(v.name) ? (
<TableCell></TableCell>
) : (
<CellRight
@ -645,8 +645,8 @@ export function TokenRightsEditor(p: {
</TableRow>
{/* Per API token operations */}
{p.tokens.map((v, n) => (
<TableRow hover key={n}>
{p.tokens.map((v) => (
<TableRow hover key={v.id}>
<TableCell>{v.name}</TableCell>
<CellRight
{...p}
@ -767,7 +767,7 @@ function RouteRight(p: RightOpts): React.ReactElement {
const parentActivated =
!!p.parent &&
p.token.rights.findIndex(
(r) => r.verb === p.parent?.verb && r.path === p.parent?.path
(r) => r.verb === p.parent?.verb && r.path === p.parent.path
) !== -1;
const toggle = (a: boolean) => {
@ -804,7 +804,9 @@ function RouteRight(p: RightOpts): React.ReactElement {
<Checkbox
checked={activated || parentActivated}
disabled={!p.editable || parentActivated}
onChange={(_e, a) => toggle(a)}
onChange={(_e, a) => {
toggle(a);
}}
/>
}
label={p.label}
@ -814,7 +816,9 @@ function RouteRight(p: RightOpts): React.ReactElement {
<Checkbox
checked={activated || parentActivated}
disabled={!p.editable || parentActivated}
onChange={(_e, a) => toggle(a)}
onChange={(_e, a) => {
toggle(a);
}}
/>
</span>
)}

View File

@ -1,7 +1,7 @@
import AddIcon from "@mui/icons-material/Add";
import ListIcon from "@mui/icons-material/List";
import { Button, IconButton, Tooltip } from "@mui/material";
import Grid from "@mui/material/Grid2";
import Grid from "@mui/material/Grid";
import React from "react";
import { useNavigate } from "react-router-dom";
import { validate as validateUUID } from "uuid";
@ -35,14 +35,16 @@ interface DetailsProps {
}
export function VMDetails(p: DetailsProps): React.ReactElement {
const [groupsList, setGroupsList] = React.useState<string[] | any>();
const [isoList, setIsoList] = React.useState<IsoFile[] | any>();
const [groupsList, setGroupsList] = React.useState<string[] | undefined>();
const [isoList, setIsoList] = React.useState<IsoFile[] | undefined>();
const [vcpuCombinations, setVCPUCombinations] = React.useState<
number[] | any
number[] | undefined
>();
const [networksList, setNetworksList] = React.useState<
NetworkInfo[] | undefined
>();
const [networksList, setNetworksList] = React.useState<NetworkInfo[] | any>();
const [networkFiltersList, setNetworkFiltersList] = React.useState<
NWFilter[] | any
NWFilter[] | undefined
>();
const load = async () => {
@ -60,11 +62,11 @@ export function VMDetails(p: DetailsProps): React.ReactElement {
errMsg="Failed to load the list of ISO files"
build={() => (
<VMDetailsInner
groupsList={groupsList}
isoList={isoList}
vcpuCombinations={vcpuCombinations}
networksList={networksList}
networkFiltersList={networkFiltersList}
groupsList={groupsList!}
isoList={isoList!}
vcpuCombinations={vcpuCombinations!}
networksList={networksList!}
networkFiltersList={networkFiltersList!}
{...p}
/>
)}
@ -202,7 +204,7 @@ function VMDetailsTabGeneral(p: DetailsInnerProps): React.ReactElement {
editable={p.editable}
label="Group"
onValueChange={(v) => {
p.vm.group = v! as any;
p.vm.group = v!;
p.onChange?.();
}}
value={p.vm.group}
@ -222,7 +224,11 @@ function VMDetailsTabGeneral(p: DetailsInnerProps): React.ReactElement {
: "Add a new group instead of using existing one"
}
>
<IconButton onClick={() => setAddGroup(!addGroup)}>
<IconButton
onClick={() => {
setAddGroup(!addGroup);
}}
>
{addGroup ? <ListIcon /> : <AddIcon />}
</IconButton>
</Tooltip>

View File

@ -9,7 +9,7 @@ export function VMScreenshot(p: { vm: VMInfo }): React.ReactElement {
string | undefined
>();
const int = React.useRef<number | undefined>();
const int = React.useRef<NodeJS.Timeout | undefined>(undefined);
React.useEffect(() => {
const refresh = async () => {
@ -25,7 +25,9 @@ export function VMScreenshot(p: { vm: VMInfo }): React.ReactElement {
if (int.current === undefined) {
refresh();
int.current = setInterval(() => refresh(), 5000);
int.current = setInterval(() => {
refresh();
}, 5000);
}
return () => {

View File

@ -31,13 +31,19 @@ export function VMStatusWidget(p: {
}
};
const changedAction = () => setState(undefined);
const changedAction = () => {
setState(undefined);
};
React.useEffect(() => {
refresh();
const i = setInterval(() => refresh(), 3000);
const i = setInterval(() => {
refresh();
}, 3000);
return () => clearInterval(i);
return () => {
clearInterval(i);
};
});
if (state === undefined)
@ -59,6 +65,7 @@ export function VMStatusWidget(p: {
icon={<PersonalVideoIcon />}
tooltip="Graphical remote control over the VM"
performAction={async () => navigate(p.vm.VNCURL)}
// eslint-disable-next-line @typescript-eslint/no-empty-function
onExecuted={() => {}}
/>
)

View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@ -1,27 +1,7 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"target": "ESNext",
"types": ["vite/client"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@ -1,15 +1,7 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import viteTsconfigPaths from "vite-tsconfig-paths";
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
// depending on your application, base can also be "/"
base: "/",
plugins: [react(), viteTsconfigPaths()],
server: {
// this ensures that the browser opens upon server start
open: true,
// this sets a default port to 3000
port: 3000,
},
});
plugins: [react()],
})