Skip to content

Commit

Permalink
refactor: update WebSocket handling and configuration
Browse files Browse the repository at this point in the history
- Removed the deprecated useWebSocket hook and replaced it with a new implementation in the websocket directory.
- Updated the Dockerfile to streamline the server command execution.
- Modified the docker-compose.yml to remove the default WebSocket URL environment variable.
- Changed the default theme color in next.config.mjs from "mint" to "ocean".
- Enhanced sidebar component to improve online user display logic.
- Added WS_URL to the server configuration for better WebSocket management.
  • Loading branch information
kiritoko1029 committed Dec 28, 2024
1 parent c738294 commit b2e1a3e
Show file tree
Hide file tree
Showing 13 changed files with 321 additions and 147 deletions.
5 changes: 2 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ ENV PROXY_URL=""
ENV OPENAI_API_KEY=""
ENV GOOGLE_API_KEY=""
ENV CODE=""

COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
Expand All @@ -57,7 +56,7 @@ CMD if [ -n "$PROXY_URL" ]; then \
echo "localnet ::1/128" >> $conf; \
echo "[ProxyList]" >> $conf; \
echo "$protocol $host $port" >> $conf; \
node proxychains -f $conf node server.js; \
proxychains -f $conf node server.js; \
else \
node node server.js; \
node server.js; \
fi
7 changes: 7 additions & 0 deletions app/api/ws-config/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";

export async function GET() {
return NextResponse.json({
wsUrl: process.env.WS_URL ?? "",
});
}
40 changes: 21 additions & 19 deletions app/components/sidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useMemo, useState, Fragment } from "react";
import { useWebSocket } from "../hooks/useWebSocket";
import { useWebSocket } from "../websocket/useWebSocket";
import styles from "./home.module.scss";

import { IconButton } from "./button";
Expand Down Expand Up @@ -383,27 +383,29 @@ const SubTitle = function SubTitle(props: {}) {

return (
<div className={styles["sidebar-sub-title"]}>
<div
style={{
fontSize: "12px",
color: "#888",
display: "flex",
alignItems: "center",
gap: "4px",
marginBottom: "4px",
}}
>
{onlineUsers > 0 && (
<div
style={{
width: "6px",
height: "6px",
borderRadius: "50%",
backgroundColor: onlineUsers > 0 ? "#4CAF50" : "#ccc",
marginRight: "2px",
fontSize: "12px",
color: "#888",
display: "flex",
alignItems: "center",
gap: "4px",
marginBottom: "4px",
}}
/>
{Locale.Hitokoto.OnlineCount(onlineUsers)}
</div>
>
<div
style={{
width: "6px",
height: "6px",
borderRadius: "50%",
backgroundColor: "#4CAF50",
marginRight: "2px",
}}
/>
{Locale.Hitokoto.OnlineCount(onlineUsers)}
</div>
)}
<HitokotoTooltip
showCopied={showCopied}
onRefresh={fetchHitokoto}
Expand Down
6 changes: 5 additions & 1 deletion app/config/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ declare global {
SIDEBAR_TITLE?: string;
HEADER_LOGO_URL?: string;
ANNOUNCEMENT_PATH?: string;
WS_URL?: string;
}
}
}
Expand Down Expand Up @@ -122,6 +123,7 @@ export const getSidebarConfig = () => {
title: process.env.SIDEBAR_TITLE ?? "Next Web",
hitokotoUrl: process.env.HITOKOTO_URL ?? "https://v1.hitokoto.cn",
headerLogoUrl: process.env.HEADER_LOGO_URL ?? "",
wsUrl: process.env.WS_URL ?? "",
};
};
export const getServerSideConfig = () => {
Expand All @@ -139,7 +141,9 @@ export const getServerSideConfig = () => {
if (customModels) customModels += ",";
customModels += DEFAULT_MODELS.filter(
(m) =>
(m.name.startsWith("gpt-4") || m.name.startsWith("chatgpt-4o") || m.name.startsWith("o1")) &&
(m.name.startsWith("gpt-4") ||
m.name.startsWith("chatgpt-4o") ||
m.name.startsWith("o1")) &&
!m.name.startsWith("gpt-4o-mini"),
)
.map((m) => "-" + m.name)
Expand Down
121 changes: 0 additions & 121 deletions app/hooks/useWebSocket.ts

This file was deleted.

6 changes: 6 additions & 0 deletions app/websocket/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// WebSocket 配置相关
export const getWebSocketConfig = () => {
return {
wsUrl: process.env.WS_URL || undefined,
};
};
6 changes: 6 additions & 0 deletions app/websocket/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { NextResponse } from "next/server";
import { getWebSocketConfig } from "./config";

export async function GET() {
return NextResponse.json(getWebSocketConfig());
}
63 changes: 63 additions & 0 deletions app/websocket/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { WebSocketServer, WebSocket } from "ws";
import { Server } from "http";

let onlineUsers = 0;
export let wss: WebSocketServer | null = null;

function broadcastOnlineUsers() {
if (!wss) return;
const message = JSON.stringify({ type: "online", count: onlineUsers });
wss.clients.forEach((client) => {
try {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
} catch (error) {
console.error("Error broadcasting to client:", error);
}
});
}

export function setupWebSocket(server: Server) {
if (wss) return;

wss = new WebSocketServer({
server,
path: "/ws",
perMessageDeflate: false,
});

console.log("WebSocket server is set up");

wss.on("connection", (ws: WebSocket) => {
onlineUsers++;
console.log("New connection established. Online users:", onlineUsers);

ws.send(JSON.stringify({ type: "online", count: onlineUsers }));
broadcastOnlineUsers();

ws.on("message", (message: string) => {
try {
const data = JSON.parse(message.toString());
if (data.type === "getOnline") {
ws.send(JSON.stringify({ type: "online", count: onlineUsers }));
}
} catch (e) {
console.error("Failed to parse message:", e);
}
});

ws.on("close", () => {
onlineUsers = Math.max(0, onlineUsers - 1);
console.log("Connection closed. Online users:", onlineUsers);
broadcastOnlineUsers();
});

ws.on("error", (error) => {
console.error("WebSocket error:", error);
if (ws.readyState === WebSocket.OPEN) {
ws.close();
}
});
});
}
11 changes: 11 additions & 0 deletions app/websocket/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { create } from "zustand";

interface WebSocketStore {
onlineUsers: number;
setOnlineUsers: (count: number) => void;
}

export const useWebSocketStore = create<WebSocketStore>((set) => ({
onlineUsers: 0,
setOnlineUsers: (count) => set({ onlineUsers: count }),
}));
Loading

0 comments on commit b2e1a3e

Please sign in to comment.