first commit

This commit is contained in:
2024-08-23 19:17:13 +00:00
commit d6df9f205a
23 changed files with 6009 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
import React from "react";
const index = () => {
return (
<div>
<div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4">
<div className="shrink-0">
<img className="size-12" src="/img/logo.svg" alt="ChitChat Logo" />
</div>
<div>
<div className="text-xl font-medium text-black">ChitChat</div>
<p className="text-slate-500">You have a new message!</p>
</div>
</div>
</div>
);
};
export default index;

View File

@@ -0,0 +1,7 @@
"use client";
export default function Logo() {
return (
<div>Logo</div>
);
}

View File

@@ -0,0 +1,10 @@
"use client";
export default function Menu({name} : any) {
return (
<div>
{name}
<div>Menu</div>
</div>
);
}

View File

@@ -0,0 +1,17 @@
"use client";
import Logo from '@/components/Header/Logo';
import Menu from '@/components/Header/Menu';
export default function Header(props: any) {
return (
<header>
{props.name} {props.age} {props.isMan ? 'is a man' : 'is a woman'}
<Logo />
<div>Header item</div>
<Menu {...props} />
</header>
);
}

View File

@@ -0,0 +1,173 @@
"use client";
import React, { useEffect, useState, useRef } from "react";
import Stats from "./stats";
const Console = () => {
const [url, setUrl] = useState("");
const [token, setToken] = useState("");
const [output, setOutput] = useState<string[]>([]);
const [input, setInput] = useState<string>("");
const [cpuStat, setCpuStat] = useState<number>(0);
const [ramStat, setRamStat] = useState<number>(0);
const [ramTotal, setRamTotal] = useState<number>(0);
const [diskUsage, setDiskUsage] = useState<number>(0);
const [diskTotal, setDiskTotal] = useState<number>(0);
const [network, setNetwork] = useState({ inbound: 0, outbound: 0 });
const [uptime, setUptime] = useState<number>(0);
const websocketRef = useRef<WebSocket | null>(null); // Dodajemy ref do WebSocket
const textareaRef = useRef<HTMLTextAreaElement>(null); // Dodajemy referencję do textarea
const fetchData = async () => {
try {
const response = await fetch(
"https://ptero.przeqpiciel.com/api/client/servers/0bf192ab/websocket",
{
method: "GET",
headers: {
Authorization:
"Bearer ptlc_aDGU4VHNQuN5t6dyxNzVon3UZLR5ehuySmdR7xsUbMm",
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setUrl(data.data.socket);
setToken(data.data.token);
} catch (error) {
console.error("Error fetching data:", error);
}
};
const fetchStats = async () => {
setDiskTotal(5);
};
useEffect(() => {
fetchData();
fetchStats();
}, []);
useEffect(() => {
if (url && token) {
const websocket = new WebSocket(url);
websocketRef.current = websocket;
websocket.onopen = () => {
console.log("WebSocket connection established.");
websocket.send(`{"event":"auth","args":["${token}"]}`);
};
websocket.onmessage = (event) => {
const message = JSON.parse(event.data);
// console.log("Received message:", message.event);
if (message.event === "token expiring") {
fetchData();
websocket.send(`{"event":"auth","args":["${token}"]}`);
console.log("New token fetched");
}
if (message.event === "stats") {
let data = JSON.parse(JSON.parse(event.data).args[0]);
setCpuStat(data.cpu_absolute.toFixed(2));
setRamStat(
Number((data.memory_bytes / (1024 * 1024 * 1024)).toFixed(2))
);
setRamTotal(
Number((data.memory_limit_bytes / (1024 * 1024 * 1024)).toFixed(2))
);
setDiskUsage(
Number((data.disk_bytes / (1024 * 1024 * 1024)).toFixed(2))
);
setNetwork({
inbound: data.network.rx_bytes,
outbound: data.network.tx_bytes,
});
setUptime(data.uptime);
}
if (message.event === "console output") {
setOutput((prevOutput) => {
let tmpMessage = JSON.parse(event.data).args[0];
tmpMessage = tmpMessage.replace(/\u001b\[[0-9;]*m/g, "");
const newOutput = [...prevOutput, tmpMessage];
if (newOutput.length > 1000) {
return newOutput.slice(-1000);
}
return newOutput;
});
}
};
websocket.onclose = () => {
console.log("WebSocket connection closed.");
};
websocket.onerror = (error) => {
console.error("WebSocket error:", error);
};
return () => {
websocket.close();
};
}
}, [url, token]);
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.scrollTop = textareaRef.current.scrollHeight;
}
}, [output]);
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && websocketRef.current) {
console.log("Sending message:", input);
websocketRef.current.send(`{"event":"send command","args":["${input}"]}`);
setInput("");
}
};
return (
<div className="flex gap-4">
<div className="w-3/5">
<div>
<textarea
className="textarea textarea-bordered text-yellow-200 w-full"
ref={textareaRef}
cols={110}
rows={20}
value={output.join("\n")}
readOnly
/>
</div>
<div>
<input
className="input input-bordered w-full text-yellow-200"
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={handleKeyPress}
/>
</div>
</div>
<div className="w-2/5">
<Stats
cpu={cpuStat}
ramUsage={ramStat}
ramTotal={ramTotal}
diskUsage={diskUsage}
diskTotal={diskTotal}
network={network}
uptime={uptime}
/>
</div>
</div>
);
};
export default Console;

View File

@@ -0,0 +1,116 @@
import React, { useEffect, useState, useRef } from "react";
interface Stats {
cpu: number;
ramUsage: number;
ramTotal: number;
diskUsage: number;
diskTotal: number;
network: NetworkStats;
uptime: number;
}
interface NetworkStats {
inbound: number;
outbound: number;
}
const StatsComponent = ({
cpu,
ramUsage,
ramTotal,
diskUsage,
diskTotal,
network,
uptime,
}: Stats) => {
const [inboundSpeed, setInboundSpeed] = useState(0);
const [outboundSpeed, setOutboundSpeed] = useState(0);
const [uptimeStat, setUptime] = useState(uptime);
// useRef to przechowywanie poprzednich wartości bez powodowania ponownego renderowania komponentu
const previousInbound = useRef(network.inbound);
const previousOutbound = useRef(network.outbound);
useEffect(() => {
const intervalId = setInterval(() => {
const currentInbound = network.inbound;
const currentOutbound = network.outbound;
const inboundDifference = currentInbound - previousInbound.current;
const outboundDifference = currentOutbound - previousOutbound.current;
setInboundSpeed(inboundDifference);
setOutboundSpeed(outboundDifference);
// Aktualizacja poprzednich wartości
previousInbound.current = currentInbound;
previousOutbound.current = currentOutbound;
}, 1000); // Prędkość będzie aktualizowana co 1 sekundę
return () => clearInterval(intervalId); // Czyszczenie interwału po odmontowaniu komponentu
}, [network.inbound, network.outbound]);
// substract current tiimestamp with the timestamp from timestamp variable and convert it to days hours minutes and seconds
const formatUptime = (timestamp: number) => {
// convert miliseconds to string formatted days hours minutes and seconds
const days = Math.floor(timestamp / (1000 * 60 * 60 * 24));
const hours = Math.floor(
(timestamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((timestamp % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timestamp % (1000 * 60)) / 1000);
return `${days}d ${hours}h ${minutes}m ${seconds}s`;
};
return (
<div>
<div className="stats stats-vertical shadow w-full">
<div className="stat">
<div className="stat-title">Uptime</div>
<div className="stat-value">{formatUptime(uptime)}</div>
</div>
<div className="stat">
<div className="stat-title">CPU</div>
<div className="stat-value">{cpu} %</div>
</div>
<div className="stat">
<div className="stat-title">RAM</div>
<div className="stat-value">{ramUsage} GB</div>
<div className="stat-desc">{ramTotal} GB</div>
</div>
<div className="stat">
<div className="stat-title">Storage</div>
<div className="stat-value">{diskUsage} GB</div>
<div className="stat-desc">{diskTotal} GB</div>
</div>
<div className="stat">
<div className="stat-title">Network (Inbound)</div>
<div className="stat-value">
{Math.round(inboundSpeed / 1024)} kB/s
</div>
<div className="stat-desc">
{Math.round(network.inbound / (1024 * 1024))} MB
</div>
</div>
<div className="stat">
<div className="stat-title">Network (Outbound)</div>
<div className="stat-value">
{Math.round(outboundSpeed / 1024)} kB/s
</div>
<div className="stat-desc">
{Math.round(network.outbound / (1024 * 1024))} MB
</div>
</div>
</div>
</div>
);
};
export default StatsComponent;