MAJOR FIX: Chat Latency Fixed
This commit is contained in:
@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";
|
||||
import { AuthContext } from "./context/AuthContext";
|
||||
import { StreamsProvider } from "./context/StreamsContext";
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import { SocketProvider } from "./context/SocketContext";
|
||||
import HomePage from "./pages/HomePage";
|
||||
import StreamerRoute from "./components/Stream/StreamerRoute";
|
||||
import NotFoundPage from "./pages/NotFoundPage";
|
||||
@@ -25,19 +26,20 @@ function App() {
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}>
|
||||
<StreamsProvider>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />}
|
||||
/>
|
||||
<Route path="/:streamerName" element={<StreamerRoute />} />
|
||||
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</StreamsProvider>
|
||||
<SocketProvider>
|
||||
<StreamsProvider>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />}
|
||||
/>
|
||||
<Route path="/:streamerName" element={<StreamerRoute />} />
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</StreamsProvider>
|
||||
</SocketProvider>
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ const ListItem: React.FC<ListItemProps> = ({
|
||||
thumbnail,
|
||||
onItemClick,
|
||||
}) => {
|
||||
console.log(title, "thumbnail", thumbnail);
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col bg-gray-800 rounded-lg overflow-hidden cursor-pointer hover:bg-gray-700 transition-colors"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import { io, Socket } from "socket.io-client";
|
||||
import Input from "../Layout/Input";
|
||||
import { useAuth } from "../../context/AuthContext";
|
||||
import { useSocket } from "../../context/SocketContext";
|
||||
|
||||
interface ChatMessage {
|
||||
chatter_id: string;
|
||||
@@ -16,81 +16,60 @@ interface ChatPanelProps {
|
||||
const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [inputMessage, setInputMessage] = useState("");
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
const chatContainerRef = useRef<HTMLDivElement>(null);
|
||||
const { isLoggedIn, username } = useAuth();
|
||||
const { socket, isConnected } = useSocket();
|
||||
|
||||
// Initialize socket connection
|
||||
// Join chat room when component mounts
|
||||
useEffect(() => {
|
||||
const newSocket = io("/", {
|
||||
path: "/api/socket.io",
|
||||
withCredentials: true
|
||||
});
|
||||
setSocket(newSocket);
|
||||
if (socket && isConnected) {
|
||||
socket.emit("join", { stream_id: streamId });
|
||||
|
||||
newSocket.on("connect", () => {
|
||||
console.log("Socket Connection established!");
|
||||
// Join the stream's chat room
|
||||
newSocket.emit("join", { stream_id: streamId });
|
||||
});
|
||||
// Load initial chat history
|
||||
fetch(`/api/chat/${streamId}`)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error("Failed to fetch chat history");
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
if (data.chat_history) {
|
||||
setMessages(data.chat_history);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading chat history:", error);
|
||||
});
|
||||
|
||||
newSocket.on("new_message", (data: ChatMessage) => {
|
||||
setMessages(prev => [...prev, data]);
|
||||
});
|
||||
// Handle incoming messages
|
||||
socket.on("new_message", (data: ChatMessage) => {
|
||||
setMessages((prev) => [...prev, data]);
|
||||
});
|
||||
|
||||
newSocket.on("connect_error", (error) => {
|
||||
console.error("Socket connection error:", error);
|
||||
});
|
||||
|
||||
newSocket.on("connect_timeout", () => {
|
||||
console.error("Socket connection timeout");
|
||||
});
|
||||
|
||||
newSocket.on("error", (error) => {
|
||||
console.error("Socket error:", error);
|
||||
});
|
||||
|
||||
// Cleanup on unmount
|
||||
return () => {
|
||||
newSocket.emit("leave", { stream_id: streamId });
|
||||
newSocket.close();
|
||||
};
|
||||
}, [streamId]);
|
||||
|
||||
// Load initial chat history
|
||||
useEffect(() => {
|
||||
const loadPastChat = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/chat/${streamId}`);
|
||||
if (!response.ok) throw new Error("Failed to fetch chat history");
|
||||
const data = await response.json();
|
||||
if (data.chat_history) {
|
||||
setMessages(data.chat_history);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading chat history:", error);
|
||||
}
|
||||
};
|
||||
|
||||
loadPastChat();
|
||||
}, [streamId]);
|
||||
// Cleanup
|
||||
return () => {
|
||||
socket.emit("leave", { stream_id: streamId });
|
||||
socket.off("new_message");
|
||||
};
|
||||
}
|
||||
}, [socket, isConnected, streamId]);
|
||||
|
||||
// Auto-scroll to bottom when new messages arrive
|
||||
useEffect(() => {
|
||||
if (chatContainerRef.current) {
|
||||
chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
|
||||
chatContainerRef.current.scrollTop =
|
||||
chatContainerRef.current.scrollHeight;
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
const sendChat = () => {
|
||||
if (!inputMessage.trim() || !socket) {
|
||||
console.log("No message to send or socket not initialized!");
|
||||
if (!inputMessage.trim() || !socket || !isConnected) {
|
||||
console.log("Invalid message or socket not connected");
|
||||
return;
|
||||
};
|
||||
}
|
||||
|
||||
socket.emit("send_message", {
|
||||
stream_id: streamId,
|
||||
message: inputMessage.trim()
|
||||
message: inputMessage.trim(),
|
||||
});
|
||||
|
||||
setInputMessage("");
|
||||
@@ -102,7 +81,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
sendChat();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div id="chat-panel" className="h-full flex flex-col rounded-lg p-4">
|
||||
<h2 className="text-xl font-bold mb-4 text-white">Stream Chat</h2>
|
||||
@@ -113,11 +92,21 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
className="flex-grow w-full max-h-[50vh] overflow-y-auto mb-4 space-y-2"
|
||||
>
|
||||
{messages.map((msg, index) => (
|
||||
<div key={index} className="grid grid-cols-[8%_minmax(15%,_100px)_1fr] items-center bg-gray-700 rounded p-2 text-white">
|
||||
<div
|
||||
key={index}
|
||||
className="grid grid-cols-[8%_minmax(15%,_100px)_1fr] items-center bg-gray-700 rounded p-2 text-white"
|
||||
>
|
||||
<span className="text-gray-400 text-sm">
|
||||
{new Date(msg.time_sent).toLocaleTimeString()}
|
||||
</span>
|
||||
<span className={`font-bold ${msg.chatter_id === username ? "text-blue-400" : "text-green-400"}`}> {msg.chatter_id}: </span>
|
||||
<span
|
||||
className={`font-bold ${
|
||||
msg.chatter_id === username ? "text-blue-400" : "text-green-400"
|
||||
}`}
|
||||
>
|
||||
{" "}
|
||||
{msg.chatter_id}:{" "}
|
||||
</span>
|
||||
<span>{msg.message}</span>
|
||||
</div>
|
||||
))}
|
||||
@@ -145,4 +134,4 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default ChatPanel;
|
||||
export default ChatPanel;
|
||||
|
||||
57
frontend/src/context/SocketContext.tsx
Normal file
57
frontend/src/context/SocketContext.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
|
||||
interface SocketContextType {
|
||||
socket: Socket | null;
|
||||
isConnected: boolean;
|
||||
}
|
||||
|
||||
const SocketContext = createContext<SocketContextType | undefined>(undefined);
|
||||
|
||||
export const SocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const newSocket = io("http://localhost:8080", {
|
||||
path: "/socket.io/",
|
||||
withCredentials: true,
|
||||
transports: ['websocket'],
|
||||
upgrade: false
|
||||
});
|
||||
|
||||
newSocket.on('connect', () => {
|
||||
console.log('Socket connected!');
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
newSocket.on('connect_error', (error) => {
|
||||
console.error('Socket connection error:', error);
|
||||
});
|
||||
|
||||
newSocket.on('disconnect', () => {
|
||||
console.log('Socket disconnected!');
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
setSocket(newSocket);
|
||||
|
||||
return () => {
|
||||
newSocket.close();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SocketContext.Provider value={{ socket, isConnected }}>
|
||||
{children}
|
||||
</SocketContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useSocket = () => {
|
||||
const context = useContext(SocketContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useSocket must be used within a SocketProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -37,6 +37,7 @@ rtmp {
|
||||
}
|
||||
|
||||
http {
|
||||
access_log off;
|
||||
# Enable HLS
|
||||
server {
|
||||
listen 8080;
|
||||
|
||||
@@ -134,7 +134,7 @@ def get_specific_stream(streamer_username, stream_id):
|
||||
if stream:
|
||||
return jsonify(stream)
|
||||
|
||||
abort(404)
|
||||
return jsonify({'error': 'Stream not found'}), 404
|
||||
|
||||
@login_required
|
||||
@stream_bp.route('/get_followed_streamers')
|
||||
|
||||
Reference in New Issue
Block a user