Patch: Tidy up of style code and fix to authentication logic

Feat: Added ability to access user's username through AuthContext
This commit is contained in:
Chris-1010
2025-01-27 16:11:42 +00:00
parent 4e9fa011fa
commit 93b3ffbc0b
16 changed files with 97 additions and 119 deletions

View File

@@ -15,7 +15,7 @@ services:
build:
context: ./web_server
ports:
- "5000"
- "5000:5000"
networks:
- app_network
env_file:

View File

@@ -2,18 +2,20 @@ import { useState, useEffect } from "react";
import { AuthContext } from "./context/AuthContext";
import { StreamsProvider } from "./context/StreamsContext";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import HomePage, { PersonalisedHomePage } from "./pages/HomePage";
import HomePage from "./pages/HomePage";
import StreamerRoute from "./components/Stream/StreamerRoute";
import NotFoundPage from "./pages/NotFoundPage";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [username, setUsername] = useState<string | null>(null);
useEffect(() => {
fetch("/api/get_login_status")
.then((response) => response.json())
.then((loggedIn) => {
setIsLoggedIn(loggedIn);
.then((data) => {
setIsLoggedIn(data.status);
setUsername(data.username);
})
.catch((error) => {
console.error("Error fetching login status:", error);
@@ -22,13 +24,13 @@ function App() {
}, []);
return (
<AuthContext.Provider value={{ isLoggedIn, setIsLoggedIn }}>
<AuthContext.Provider value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}>
<StreamsProvider>
<BrowserRouter>
<Routes>
<Route
path="/"
element={isLoggedIn ? <PersonalisedHomePage /> : <HomePage />}
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />}
/>
<Route path="/:streamerName" element={<StreamerRoute />} />

View File

@@ -20,25 +20,6 @@
background: #555;
}
.bg-repeat {
animation: moving_bg 200s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.bg-repeat {
animation: none;
}
}
@keyframes moving_bg {
0% {
background-position: 0% 0%;
}
100% {
background-position: 100% 0%;
}
}
/*
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;

View File

@@ -7,14 +7,14 @@ interface LogoProps {
const Logo: React.FC<LogoProps> = ({ variant = "default" }) => {
const gradient =
"bg-gradient-to-br from-yellow-400 via-red-500 to-indigo-500 text-transparent bg-clip-text group-hover:mx-1 transition-all";
"text-transparent group-hover:mx-1 transition-all";
return (
<Link to="/" className="cursor-pointer">
<div id="logo" className={`group py-3 text-center font-bold hover:scale-110 transition-all ${variant === "home" ? "text-[12vh]" : "text-[4vh]"}`}>
<h6 className="text-sm bg-gradient-to-br from-blue-400 via-green-500 to-indigo-500 font-black text-transparent bg-clip-text">
Go on, have a...
</h6>
<div className="flex w-fit min-w-[30vw] justify-center leading-none transition-all">
<div className="flex w-fit min-w-[30vw] bg-logo bg-clip-text animate-moving_text_colour bg-[length:300%_300%] justify-center leading-none transition-all">
<span className={gradient}>G</span>
<span className={gradient}>A</span>
<span className={gradient}>N</span>

View File

@@ -1,11 +0,0 @@
const Name = () => {
return (
<div id="logo" className="text-center">
<span className="text-7xl font-bold italic bg-agog bg-clip-text text-transparent leading-none p-1 hover:scale-110 transition-all hover:animate-agog bg-[length:300%_300%]">
AGOG
</span>
</div>
);
};
export default Name;

View File

@@ -26,7 +26,7 @@ const StreamerRoute: React.FC = () => {
checkStreamStatus();
// Poll for live status changes
const interval = setInterval(checkStreamStatus, 90000); // Check every 90 seconds
const interval = setInterval(checkStreamStatus, 1000); // Check every 90 seconds
return () => clearInterval(interval);
}, [streamerName]);

View File

@@ -1,6 +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";
interface ChatMessage {
chatter_id: string;
@@ -10,21 +11,21 @@ interface ChatMessage {
interface ChatPanelProps {
streamId: number;
chatterId?: string; // Optional as user might not be logged in
}
const ChatPanel: React.FC<ChatPanelProps> = ({ streamId, chatterId }) => {
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();
// Initialize socket connection
useEffect(() => {
const newSocket = io("/", {
path: "/api/socket.io",
withCredentials: true
}); // Make sure this matches your backend URL
});
setSocket(newSocket);
newSocket.on("connect", () => {
@@ -37,6 +38,14 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId, chatterId }) => {
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);
});
@@ -74,10 +83,12 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId, chatterId }) => {
}, [messages]);
const sendChat = () => {
if (!inputMessage.trim() || !chatterId || !socket) return;
if (!inputMessage.trim() || !socket) {
console.log("No message to send or socket not initialized!");
return;
};
socket.emit("send_message", {
chatter_id: chatterId,
stream_id: streamId,
message: inputMessage.trim()
});
@@ -106,7 +117,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId, chatterId }) => {
<span className="text-gray-400 text-sm">
{new Date(msg.time_sent).toLocaleTimeString()}
</span>
<span className={`font-bold ${msg.chatter_id === chatterId ? "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>
))}
@@ -118,13 +129,13 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId, chatterId }) => {
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyDown={handleKeyPress}
placeholder={chatterId ? "Type a message..." : "Login to chat"}
disabled={!chatterId}
placeholder={isLoggedIn ? "Type a message..." : "Login to chat"}
disabled={!isLoggedIn}
extraClasses="flex-grow disabled:cursor-not-allowed"
/>
<button
onClick={sendChat}
disabled={!chatterId}
disabled={!isLoggedIn}
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
Send

View File

@@ -2,7 +2,9 @@ import { createContext, useContext } from "react";
interface AuthContextType {
isLoggedIn: boolean;
username: string | null;
setIsLoggedIn: (value: boolean) => void;
setUsername: (value: string | null) => void;
}
export const AuthContext = createContext<AuthContextType | undefined>(

View File

@@ -3,9 +3,12 @@ import Navbar from "../components/Layout/Navbar";
import StreamListRow from "../components/Layout/StreamListRow";
import { useNavigate } from "react-router-dom";
import { useStreams } from "../context/StreamsContext";
import Name from "../components/Layout/Name";
const HomePage: React.FC = () => {
interface HomePageProps {
variant?: "default" | "personalised";
}
const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
const { featuredStreams, featuredCategories } = useStreams();
const navigate = useNavigate();
@@ -17,54 +20,22 @@ const HomePage: React.FC = () => {
return (
<div
id="home-page"
className="bg-repeat"
className="animate-moving_bg"
style={{ backgroundImage: "url(/images/background-pattern.svg)" }}
>
<Navbar variant="home" />
<Name></Name>
{/*//TODO Extract StreamListRow away, to ListRow so that it makes sense for categories to be there also */}
<StreamListRow
title="Live Now"
description="Streamers that are currently live"
title={"Live Now" + (variant === "personalised" ? " - Recommended" : "")}
description={variant === "personalised" ? "We think you might like these streams - Streamers recommended for you" : "Streamers that are currently live"}
streams={featuredStreams}
onStreamClick={handleStreamClick}
/>
<StreamListRow
title="Trending Categories"
description="Categories that have been 'popping off' lately"
streams={featuredCategories}
onStreamClick={() => {}} //TODO
/>
</div>
);
};
export const PersonalisedHomePage: React.FC = () => {
const { featuredStreams, featuredCategories } = useStreams();
const navigate = useNavigate();
const handleStreamClick = (streamId: number, streamerName: string) => {
console.log(`Navigating to ${streamId}`);
navigate(`/${streamerName}`);
};
return (
<div
id="personalised-home-page"
className="bg-repeat"
style={{ backgroundImage: "url(/images/background-pattern.svg)" }}
>
<Navbar variant="home" />
{/*//TODO Extract StreamListRow away to ListRow so that it makes sense for categories to be there also */}
<StreamListRow
title="Live Now - Recommended"
description="We think you might like these streams - Streamers recommended for you"
streams={featuredStreams}
onStreamClick={handleStreamClick}
/>
<StreamListRow
title="Followed Categories"
description="Current streams from your followed categories"
title={variant === "personalised" ? "Followed Categories" : "Trending Categories"}
description={variant === "personalised" ? "Current streams from your followed categories" : "Categories that have been 'popping off' lately"}
streams={featuredCategories}
onStreamClick={() => {}} //TODO
/>

View File

@@ -45,7 +45,7 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamId }) => {
<VideoPlayer streamId={streamId} />
{isLoggedIn ? (
<ChatPanel streamId={streamId} chatterId="chatter-man" />
<ChatPanel streamId={streamId} />
) : (
<ChatPanel streamId={streamId} />
)}

View File

@@ -6,20 +6,27 @@ export default {
],
theme: {
extend: {
animation: {
moving_text_colour: "moving_text_colour 6s ease-in-out infinite alternate",
moving_bg: 'moving_bg 200s linear infinite'
},
backgroundImage: {
logo: "linear-gradient(45deg, #60A5FA, #8B5CF6, #EC4899, #FACC15,#60A5FA, #8B5CF6, #EC4899, #FACC15)",
},
keyframes: {
agog: {
moving_text_colour: {
"0%": { backgroundPosition: "0% 50%" },
"100%": { backgroundPosition: "100% 50%" },
},
},
animation: {
agog: "agog 6s linear infinite",
},
backgroundImage: {
agog: "linear-gradient(to right, #60A5FA, #8B5CF6, #EC4899, #FACC15,#60A5FA, #8B5CF6, #EC4899, #FACC15)",
},
moving_bg: {
'0%': { backgroundPosition: '0% 0%' },
'100%': { backgroundPosition: '100% 0%' }
}
}
},
},
plugins: [

View File

@@ -25,13 +25,10 @@ def signup():
# Validation - ensure all fields exist, users cannot have an empty field
if not all([username, email, password]):
fields = ["username", "email", "password"]
for x in fields:
if not [username, email, password][fields.index(x)]:
fields.remove(x)
error_fields = get_error_fields([username, email, password]), #!←← find the error_fields, to highlight them in red to the user on the frontend
return jsonify({
"account_created": False,
"error_fields": fields,
"error_fields": error_fields,
"message": "Missing required fields"
}), 400
@@ -41,9 +38,10 @@ def signup():
email = sanitizer(email, "email")
password = sanitizer(password, "password")
except ValueError as e:
error_fields = get_error_fields([username, email, password])
return jsonify({
"account_created": False,
"error_fields": fields,
"error_fields": error_fields,
"message": "Invalid input received"
}), 400
@@ -204,3 +202,10 @@ def logout() -> dict:
"""
session.clear()
return {"logged_in": False}
def get_error_fields(values: list):
fields = ["username", "email", "password"]
for x in fields:
if not values[fields.index(x)]:
fields.remove(x)
return fields

View File

@@ -9,6 +9,7 @@ socketio = SocketIO()
# <---------------------- ROUTES NEEDS TO BE CHANGED TO VIDEO OR DELETED AS DEEMED APPROPRIATE ---------------------->
# TODO: Add a route that deletes all chat logs when the stream is finished
@socketio.on("connect")
def handle_connection() -> None:
"""
@@ -16,6 +17,7 @@ def handle_connection() -> None:
"""
print("Client Connected") # Confirmation connect has been made
@socketio.on("join")
def handle_join(data) -> None:
"""
@@ -26,6 +28,7 @@ def handle_join(data) -> None:
join_room(stream_id)
emit("status", {"message": f"Welcome to the chat, stream_id: {stream_id}"}, room=stream_id)
@socketio.on("leave")
def handle_leave(data) -> None:
"""
@@ -36,6 +39,7 @@ def handle_leave(data) -> None:
leave_room(stream_id)
emit("status", {"message": f"user left room {stream_id}"}, room=stream_id)
@chat_bp.route("/chat/<int:stream_id>")
def get_past_chat(stream_id: int):
"""
@@ -64,11 +68,13 @@ def get_past_chat(stream_id: int):
db.close_connection()
# Create JSON output of chat_history to pass through NGINX proxy
chat_history = [{"chatter_id": chat[0], "message": chat[1], "time_sent": chat[2]} for chat in all_chats]
chat_history = [{"chatter_id": chat[0], "message": chat[1],
"time_sent": chat[2]} for chat in all_chats]
# Pass the chat history to the proxy
return jsonify({"chat_history": chat_history}), 200
@socketio.on("send_message")
def send_chat(data) -> None:
"""
@@ -96,7 +102,7 @@ def send_chat(data) -> None:
# Send the chat message to the client so it can be displayed
emit("new_message", {
"chatter_id":chatter_id,
"message":message,
"chatter_id": chatter_id,
"message": message,
"time_sent": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}, room=stream_id)
}, room=stream_id)

View File

@@ -3,6 +3,7 @@ from utils.user_utils import is_subscribed, is_following, subscription_expiratio
user_bp = Blueprint("user", __name__)
@user_bp.route('/is_subscribed/<int:user_id>/<int:streamer_id>')
def user_subscribed(user_id: int, streamer_id: int):
"""
@@ -36,7 +37,9 @@ def get_login_status():
"""
Returns whether the user is logged in or not
"""
return jsonify(session.get("username") is not None)
username = session.get("username")
return jsonify({'status': username is not None, 'username': username})
@user_bp.route('/authenticate_user')
def authenticate_user() -> dict:
@@ -45,6 +48,7 @@ def authenticate_user() -> dict:
"""
return {"authenticated": True}
@user_bp.route('/forgot_password', methods=['POST'])
def forgot_password():
"""

View File

@@ -8,6 +8,7 @@ Flask==3.1.0
Flask-Session==0.8.0
Flask-WTF==1.2.2
Flask_CORS==5.0.0
flask-socketio==5.5.1
python-dotenv==1.0.1
idna==3.10
itsdangerous==2.2.0
@@ -21,4 +22,3 @@ urllib3==2.3.0
Werkzeug==3.1.3
WTForms==3.2.1
Gunicorn==20.1.0
flask-socketio==5.5.1