Skip to content

Commit

Permalink
fix(demo): Websocket error in demo mode
Browse files Browse the repository at this point in the history
  • Loading branch information
NriotHrreion committed Aug 9, 2024
1 parent ee7a43d commit 88b9a5b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
8 changes: 6 additions & 2 deletions app/(pages)/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import GPUWidget from "@/components/dashboard/gpu-widget";
import BatteryWidget from "@/components/dashboard/battery-widget";
import OSWidget from "@/components/dashboard/os-widget";
import { WebSocketContext } from "@/hooks/useOS";
import { isDemo } from "@/lib/global";

export default function Page() {
const [mounted, setMounted] = useState<boolean>(false);
Expand All @@ -22,8 +23,11 @@ export default function Page() {

document.title = "Ferrum - 仪表盘";

const _ws = new WebSocket(`ws://${window.location.host}/api/os`);
setWebSocket(_ws);
var _ws: WebSocket;
if(!isDemo) {
_ws = new WebSocket(`ws://${window.location.host}/api/os`);
setWebSocket(_ws);
}

return () => _ws?.close();
}, []);
Expand Down
10 changes: 2 additions & 8 deletions app/api/os/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import cookie from "cookie";
import { error } from "@/lib/packet";
import { isDemo, tokenStorageKey } from "@/lib/global";
import { validateToken } from "@/lib/token";
// Demo
import demoOS from "@/lib/demo/os.json";

export function GET() {
return error(400);
Expand All @@ -24,6 +22,8 @@ export function SOCKET(
req: IncomingMessage,
_server: WebSocketServer,
) {
if(isDemo) return;

const token = cookie.parse(req.headers.cookie ?? "")[tokenStorageKey];

if(!token) {
Expand All @@ -40,12 +40,6 @@ export function SOCKET(
console.log("[Server: /api/os] Socket client connected.");

const handleRequest = async () => {
if(isDemo) {
client.send(JSON.stringify(demoOS));

return;
}

const cpu = await si.cpu();
const cpuTemp = await si.cpuTemperature();
const mem = await si.mem();
Expand Down
12 changes: 11 additions & 1 deletion hooks/useOS.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import React, { useContext, useEffect } from "react";

import { isDemo } from "@/lib/global";
// Demo
import demoOS from "@/lib/demo/os.json";

interface WebSocketContextType {
ws: WebSocket | null;
ws: WebSocket | null
}

export const WebSocketContext = React.createContext<WebSocketContextType>({ ws: null });
Expand Down Expand Up @@ -65,6 +69,12 @@ export function useOS(listener: (msg: OSWebSocketMessage) => void) {
const { ws } = useContext(WebSocketContext);

useEffect(() => {
if(isDemo) {
listener(demoOS as OSWebSocketMessage);

return;
}

const controller = new AbortController();

ws?.addEventListener("message", (e) => {
Expand Down

0 comments on commit 88b9a5b

Please sign in to comment.