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 { AuthContext } from "./context/AuthContext";
|
||||||
import { StreamsProvider } from "./context/StreamsContext";
|
import { StreamsProvider } from "./context/StreamsContext";
|
||||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||||
|
import { SocketProvider } from "./context/SocketContext";
|
||||||
import HomePage from "./pages/HomePage";
|
import HomePage from "./pages/HomePage";
|
||||||
import StreamerRoute from "./components/Stream/StreamerRoute";
|
import StreamerRoute from "./components/Stream/StreamerRoute";
|
||||||
import NotFoundPage from "./pages/NotFoundPage";
|
import NotFoundPage from "./pages/NotFoundPage";
|
||||||
@@ -25,19 +26,20 @@ function App() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}>
|
<AuthContext.Provider value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}>
|
||||||
<StreamsProvider>
|
<SocketProvider>
|
||||||
<BrowserRouter>
|
<StreamsProvider>
|
||||||
<Routes>
|
<BrowserRouter>
|
||||||
<Route
|
<Routes>
|
||||||
path="/"
|
<Route
|
||||||
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />}
|
path="/"
|
||||||
/>
|
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />}
|
||||||
<Route path="/:streamerName" element={<StreamerRoute />} />
|
/>
|
||||||
|
<Route path="/:streamerName" element={<StreamerRoute />} />
|
||||||
<Route path="*" element={<NotFoundPage />} />
|
<Route path="*" element={<NotFoundPage />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</StreamsProvider>
|
</StreamsProvider>
|
||||||
|
</SocketProvider>
|
||||||
</AuthContext.Provider>
|
</AuthContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ const ListItem: React.FC<ListItemProps> = ({
|
|||||||
thumbnail,
|
thumbnail,
|
||||||
onItemClick,
|
onItemClick,
|
||||||
}) => {
|
}) => {
|
||||||
console.log(title, "thumbnail", thumbnail);
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="flex flex-col bg-gray-800 rounded-lg overflow-hidden cursor-pointer hover:bg-gray-700 transition-colors"
|
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 React, { useState, useEffect, useRef } from "react";
|
||||||
import { io, Socket } from "socket.io-client";
|
|
||||||
import Input from "../Layout/Input";
|
import Input from "../Layout/Input";
|
||||||
import { useAuth } from "../../context/AuthContext";
|
import { useAuth } from "../../context/AuthContext";
|
||||||
|
import { useSocket } from "../../context/SocketContext";
|
||||||
|
|
||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
chatter_id: string;
|
chatter_id: string;
|
||||||
@@ -16,81 +16,60 @@ interface ChatPanelProps {
|
|||||||
const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
const [inputMessage, setInputMessage] = useState("");
|
const [inputMessage, setInputMessage] = useState("");
|
||||||
const [socket, setSocket] = useState<Socket | null>(null);
|
|
||||||
const chatContainerRef = useRef<HTMLDivElement>(null);
|
const chatContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const { isLoggedIn, username } = useAuth();
|
const { isLoggedIn, username } = useAuth();
|
||||||
|
const { socket, isConnected } = useSocket();
|
||||||
|
|
||||||
// Initialize socket connection
|
// Join chat room when component mounts
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const newSocket = io("/", {
|
if (socket && isConnected) {
|
||||||
path: "/api/socket.io",
|
socket.emit("join", { stream_id: streamId });
|
||||||
withCredentials: true
|
|
||||||
});
|
|
||||||
setSocket(newSocket);
|
|
||||||
|
|
||||||
newSocket.on("connect", () => {
|
// Load initial chat history
|
||||||
console.log("Socket Connection established!");
|
fetch(`/api/chat/${streamId}`)
|
||||||
// Join the stream's chat room
|
.then((response) => {
|
||||||
newSocket.emit("join", { stream_id: streamId });
|
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) => {
|
// Handle incoming messages
|
||||||
setMessages(prev => [...prev, data]);
|
socket.on("new_message", (data: ChatMessage) => {
|
||||||
});
|
setMessages((prev) => [...prev, data]);
|
||||||
|
});
|
||||||
|
|
||||||
newSocket.on("connect_error", (error) => {
|
// Cleanup
|
||||||
console.error("Socket connection error:", error);
|
return () => {
|
||||||
});
|
socket.emit("leave", { stream_id: streamId });
|
||||||
|
socket.off("new_message");
|
||||||
newSocket.on("connect_timeout", () => {
|
};
|
||||||
console.error("Socket connection timeout");
|
}
|
||||||
});
|
}, [socket, isConnected, streamId]);
|
||||||
|
|
||||||
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]);
|
|
||||||
|
|
||||||
// Auto-scroll to bottom when new messages arrive
|
// Auto-scroll to bottom when new messages arrive
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (chatContainerRef.current) {
|
if (chatContainerRef.current) {
|
||||||
chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
|
chatContainerRef.current.scrollTop =
|
||||||
|
chatContainerRef.current.scrollHeight;
|
||||||
}
|
}
|
||||||
}, [messages]);
|
}, [messages]);
|
||||||
|
|
||||||
const sendChat = () => {
|
const sendChat = () => {
|
||||||
if (!inputMessage.trim() || !socket) {
|
if (!inputMessage.trim() || !socket || !isConnected) {
|
||||||
console.log("No message to send or socket not initialized!");
|
console.log("Invalid message or socket not connected");
|
||||||
return;
|
return;
|
||||||
};
|
}
|
||||||
|
|
||||||
socket.emit("send_message", {
|
socket.emit("send_message", {
|
||||||
stream_id: streamId,
|
stream_id: streamId,
|
||||||
message: inputMessage.trim()
|
message: inputMessage.trim(),
|
||||||
});
|
});
|
||||||
|
|
||||||
setInputMessage("");
|
setInputMessage("");
|
||||||
@@ -102,7 +81,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
|
|||||||
sendChat();
|
sendChat();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div id="chat-panel" className="h-full flex flex-col rounded-lg p-4">
|
<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>
|
<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"
|
className="flex-grow w-full max-h-[50vh] overflow-y-auto mb-4 space-y-2"
|
||||||
>
|
>
|
||||||
{messages.map((msg, index) => (
|
{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">
|
<span className="text-gray-400 text-sm">
|
||||||
{new Date(msg.time_sent).toLocaleTimeString()}
|
{new Date(msg.time_sent).toLocaleTimeString()}
|
||||||
</span>
|
</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>
|
<span>{msg.message}</span>
|
||||||
</div>
|
</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 {
|
http {
|
||||||
|
access_log off;
|
||||||
# Enable HLS
|
# Enable HLS
|
||||||
server {
|
server {
|
||||||
listen 8080;
|
listen 8080;
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ def get_specific_stream(streamer_username, stream_id):
|
|||||||
if stream:
|
if stream:
|
||||||
return jsonify(stream)
|
return jsonify(stream)
|
||||||
|
|
||||||
abort(404)
|
return jsonify({'error': 'Stream not found'}), 404
|
||||||
|
|
||||||
@login_required
|
@login_required
|
||||||
@stream_bp.route('/get_followed_streamers')
|
@stream_bp.route('/get_followed_streamers')
|
||||||
|
|||||||
Reference in New Issue
Block a user