UPDATE: Fix to stream/userpage routing, Added UserPage and Tidy to code;

Added ability to visit a user's profile page from their stream;
Cleaned up code formatting, primarily changing from single quotes to double quotes;
Removed unused SignupForm component;
This commit is contained in:
Chris-1010
2025-02-04 14:59:18 +00:00
parent f31834bc1d
commit 60c19b3052
24 changed files with 325 additions and 150 deletions

View File

@@ -32,7 +32,7 @@
"tailwindcss": "^3.4.17", "tailwindcss": "^3.4.17",
"typescript": "~5.6.2", "typescript": "~5.6.2",
"typescript-eslint": "^8.18.2", "typescript-eslint": "^8.18.2",
"vite": "^6.0.5" "vite": "latest"
} }
}, },
"node_modules/@alloc/quick-lru": { "node_modules/@alloc/quick-lru": {

View File

@@ -5,6 +5,7 @@ import { BrowserRouter, Routes, Route } from "react-router-dom";
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";
import UserPage from "./pages/UserPage";
function App() { function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false); const [isLoggedIn, setIsLoggedIn] = useState(false);
@@ -24,15 +25,22 @@ function App() {
}, []); }, []);
return ( return (
<AuthContext.Provider value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}> <AuthContext.Provider
value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}
>
<StreamsProvider> <StreamsProvider>
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
<Route <Route
path="/" path="/"
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />} element={
isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />
}
/> />
<Route path="/:streamerName" element={<StreamerRoute />} /> <Route path="/:streamerName" element={<StreamerRoute />} />
<Route path="/user/:username" element={<UserPage />} />
<Route path="*" element={<NotFoundPage />} /> <Route path="*" element={<NotFoundPage />} />
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>

View File

@@ -5,14 +5,13 @@ import LoginForm from "./LoginForm";
import RegisterForm from "./RegisterForm"; import RegisterForm from "./RegisterForm";
import "../../assets/styles/auth.css"; import "../../assets/styles/auth.css";
interface AuthModalProps { interface AuthModalProps {
onClose: () => void; onClose: () => void;
} }
const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => { const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => {
const [selectedTab, setSelectedTab] = useState<string>("Login"); const [selectedTab, setSelectedTab] = useState<string>("Login");
const [spinDuration, setSpinDuration] = useState("7s") const [spinDuration, setSpinDuration] = useState("7s");
const handleSubmit = () => { const handleSubmit = () => {
setSpinDuration("1s"); setSpinDuration("1s");
@@ -25,21 +24,26 @@ const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => {
return ( return (
<> <>
{/*Background Blur*/} {/*Background Blur*/}
<div id="blurring-layer" className="fixed z-50 inset-0 w-screen h-screen backdrop-blur-sm group-has-[input:focus]:backdrop-blur-[5px]"></div> <div
id="blurring-layer"
className="fixed z-50 inset-0 w-screen h-screen backdrop-blur-sm group-has-[input:focus]:backdrop-blur-[5px]"
></div>
{/*Container*/} {/*Container*/}
<div <div
className="container fixed inset-0 flex flex-col items-center justify-around z-[9999] className="container fixed inset-0 flex flex-col items-center justify-around z-[9999]
h-[75vh] m-auto min-w-[45vw] w-fit py-[50px] rounded-[5rem] transition-all animate-floating" h-[75vh] m-auto min-w-[45vw] w-fit py-[50px] rounded-[5rem] transition-all animate-floating"
style={{ "--spin-duration": spinDuration } as React.CSSProperties} style={{ "--spin-duration": spinDuration } as React.CSSProperties}
> >
{/*Border Container*/} {/*Border Container*/}
<div <div
id="border-container" id="border-container"
className="front-content fixed inset-0 bg-gradient-to-br from-blue-950 via-purple-500 to-violet-800 flex flex-col justify-center className="front-content fixed inset-0 bg-gradient-to-br from-blue-950 via-purple-500 to-violet-800 flex flex-col justify-center
z-50 h-[70vh] mr-0.5 mb-0.5 m-auto min-w-[40vw] w-fit py-[50px] rounded-[2rem] transition-all" z-50 h-[70vh] mr-0.5 mb-0.5 m-auto min-w-[40vw] w-fit py-[50px] rounded-[2rem] transition-all"
> >
<div id="login-methods" className=" w-full flex flex-row items-center justify-evenly"> <div
id="login-methods"
className=" w-full flex flex-row items-center justify-evenly"
>
<button <button
onClick={onClose} onClick={onClose}
className="absolute top-[1rem] right-[2rem] text-[2rem] text-white hover:text-red-500 font-black hover:text-[2.5rem] transition-all" className="absolute top-[1rem] right-[2rem] text-[2rem] text-white hover:text-red-500 font-black hover:text-[2.5rem] transition-all"
@@ -63,7 +67,11 @@ const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => {
Register Register
</ToggleButton> </ToggleButton>
</div> </div>
{selectedTab === "Login" ? <LoginForm onSubmit={handleSubmit} /> : <RegisterForm onSubmit={handleSubmit}/>} {selectedTab === "Login" ? (
<LoginForm onSubmit={handleSubmit} />
) : (
<RegisterForm onSubmit={handleSubmit} />
)}
</div> </div>
</div> </div>
</> </>

View File

@@ -126,6 +126,7 @@ const RegisterForm: React.FC<SubmitProps> = ({ onSubmit }) => {
onChange={handleInputChange} onChange={handleInputChange}
extraClasses={`${errors.username ? "border-red-500" : ""}`} extraClasses={`${errors.username ? "border-red-500" : ""}`}
/> />
{errors.email && ( {errors.email && (
<p className="text-red-500 mt-3 text-sm">{errors.email}</p> <p className="text-red-500 mt-3 text-sm">{errors.email}</p>
)} )}
@@ -137,6 +138,7 @@ const RegisterForm: React.FC<SubmitProps> = ({ onSubmit }) => {
onChange={handleInputChange} onChange={handleInputChange}
extraClasses={`${errors.email ? "border-red-500" : ""}`} extraClasses={`${errors.email ? "border-red-500" : ""}`}
/> />
{errors.password && ( {errors.password && (
<p className="text-red-500 mt-3 text-sm">{errors.password}</p> <p className="text-red-500 mt-3 text-sm">{errors.password}</p>
)} )}
@@ -148,6 +150,7 @@ const RegisterForm: React.FC<SubmitProps> = ({ onSubmit }) => {
onChange={handleInputChange} onChange={handleInputChange}
extraClasses={`${errors.password ? "border-red-500" : ""}`} extraClasses={`${errors.password ? "border-red-500" : ""}`}
/> />
{errors.confirmPassword && ( {errors.confirmPassword && (
<p className="text-red-500 mt-3 text-sm">{errors.confirmPassword}</p> <p className="text-red-500 mt-3 text-sm">{errors.confirmPassword}</p>
)} )}
@@ -159,6 +162,7 @@ const RegisterForm: React.FC<SubmitProps> = ({ onSubmit }) => {
onChange={handleInputChange} onChange={handleInputChange}
extraClasses={`${errors.confirmPassword ? "border-red-500" : ""}`} extraClasses={`${errors.confirmPassword ? "border-red-500" : ""}`}
/> />
<Button type="submit">Register</Button> <Button type="submit">Register</Button>
</form> </form>
); );

View File

@@ -1 +0,0 @@
// signup.html

View File

@@ -67,8 +67,14 @@ const CheckoutForm: React.FC<CheckoutFormProps> = ({ onClose }) => {
return ( return (
<> <>
<div id="blurring-layer" className="fixed z-10 inset-0 w-screen h-screen backdrop-blur-sm"></div> <div
<div id="modal-container" className="fixed inset-0 bg-black/30 flex items-center justify-center z-50 h-[70vh] m-auto w-fit py-[50px] px-[100px] rounded-[2rem]"> id="blurring-layer"
className="fixed z-10 inset-0 w-screen h-screen backdrop-blur-sm"
></div>
<div
id="modal-container"
className="fixed inset-0 bg-black/30 flex items-center justify-center z-50 h-[70vh] m-auto w-fit py-[50px] px-[100px] rounded-[2rem]"
>
<button <button
onClick={onClose} onClick={onClose}
className="absolute top-[1rem] right-[3rem] text-[2rem] text-white hover:text-red-500 font-black hover:text-[2.5rem] transition-all" className="absolute top-[1rem] right-[3rem] text-[2rem] text-white hover:text-red-500 font-black hover:text-[2.5rem] transition-all"

View File

@@ -72,12 +72,10 @@ const ListRow: React.FC<ListRowProps> = ({
id={item.id} id={item.id}
type={item.type} type={item.type}
title={item.title} title={item.title}
streamer={item.type === "stream" ? (item.streamer) : undefined} streamer={item.type === "stream" ? item.streamer : undefined}
viewers={item.viewers} viewers={item.viewers}
thumbnail={item.thumbnail} thumbnail={item.thumbnail}
onItemClick={() => onItemClick={() => onClick?.(item.id, item.streamer || item.title)}
onClick?.(item.id, item.streamer || item.title)
}
/> />
))} ))}
</div> </div>

View File

@@ -6,11 +6,13 @@ interface LogoProps {
} }
const Logo: React.FC<LogoProps> = ({ variant = "default" }) => { const Logo: React.FC<LogoProps> = ({ variant = "default" }) => {
const gradient = const gradient = "text-transparent group-hover:mx-1 transition-all";
"text-transparent group-hover:mx-1 transition-all";
return ( return (
<Link to="/" className="cursor-pointer"> <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]"}`}> <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"> <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... Go on, have a...
</h6> </h6>

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import Logo from "./Logo"; import Logo from "./Logo";
import Button, {ToggleButton} from "./Button"; import Button, { ToggleButton } from "./Button";
import Sidebar from "./Sidebar"; import Sidebar from "./Sidebar";
import { Sidebar as SidebarIcon } from "lucide-react"; import { Sidebar as SidebarIcon } from "lucide-react";
import { import {
@@ -13,14 +13,17 @@ import Input from "./Input";
import AuthModal from "../Auth/AuthModal"; import AuthModal from "../Auth/AuthModal";
import { useAuth } from "../../context/AuthContext"; import { useAuth } from "../../context/AuthContext";
interface NavbarProps { interface NavbarProps {
variant?: "home" | "default"; variant?: "home" | "default";
isChatOpen: boolean; isChatOpen?: boolean;
toggleChat: () => void; toggleChat?: () => void;
} }
const Navbar: React.FC<NavbarProps> = ({ variant = "default", isChatOpen, toggleChat }) => { const Navbar: React.FC<NavbarProps> = ({
variant = "default",
isChatOpen,
toggleChat,
}) => {
const [showAuthModal, setShowAuthModal] = useState(false); const [showAuthModal, setShowAuthModal] = useState(false);
const { isLoggedIn } = useAuth(); const { isLoggedIn } = useAuth();
const isVideoPage = location.pathname.includes("/EduGuru"); const isVideoPage = location.pathname.includes("/EduGuru");
@@ -47,7 +50,10 @@ const Navbar: React.FC<NavbarProps> = ({ variant = "default", isChatOpen, toggle
}; };
return ( return (
<div id="navbar" className={`flex justify-center items-center ${variant === "home" ? "h-[45vh] flex-col" : "h-[15vh] col-span-2 flex-row"}`}> <div
id="navbar"
className={`flex justify-center items-center ${variant === "home" ? "h-[45vh] flex-col" : "h-[15vh] col-span-2 flex-row"}`}
>
<Logo variant={variant} /> <Logo variant={variant} />
<Button <Button
extraClasses="absolute top-[20px] left-[20px] text-[1rem] flex items-center flex-nowrap" extraClasses="absolute top-[20px] left-[20px] text-[1rem] flex items-center flex-nowrap"
@@ -83,7 +89,9 @@ const Navbar: React.FC<NavbarProps> = ({ variant = "default", isChatOpen, toggle
Quick Settings Quick Settings
</Button> </Button>
{isVideoPage && ( {isVideoPage && (
<ToggleButton onClick={toggleChat} toggled={isChatOpen} <ToggleButton
onClick={toggleChat}
toggled={isChatOpen}
extraClasses="absolute top-[80px] right-[20px] text-[1rem] flex items-center flex-nowrap" extraClasses="absolute top-[80px] right-[20px] text-[1rem] flex items-center flex-nowrap"
> >
{isChatOpen ? "Hide Chat" : "Show Chat"} {isChatOpen ? "Hide Chat" : "Show Chat"}
@@ -96,10 +104,10 @@ const Navbar: React.FC<NavbarProps> = ({ variant = "default", isChatOpen, toggle
placeholder="Search..." placeholder="Search..."
extraClasses="pr-[30px] focus:outline-none focus:border-purple-500 focus:w-[30vw]" extraClasses="pr-[30px] focus:outline-none focus:border-purple-500 focus:w-[30vw]"
/> />
<SearchIcon className="-translate-x-[28px] top-1/2 h-6 w-6 text-white" /> <SearchIcon className="-translate-x-[28px] top-1/2 h-6 w-6 text-white" />
</div> </div>
{showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />} {showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />}
</div> </div>
); );

View File

@@ -7,13 +7,14 @@ const StreamerRoute: React.FC = () => {
const { streamerName } = useParams<{ streamerName: string }>(); const { streamerName } = useParams<{ streamerName: string }>();
const [isLive, setIsLive] = useState<boolean>(false); const [isLive, setIsLive] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(true); const [isLoading, setIsLoading] = useState<boolean>(true);
let streamId: number = 0;
useEffect(() => { useEffect(() => {
const checkStreamStatus = async () => { const checkStreamStatus = async () => {
try { try {
const response = await fetch(`/api/streamer/${streamerName}/status`); const response = await fetch(`/api/streamer/${streamerName}/status`);
const data = await response.json(); const data = await response.json();
setIsLive(data.is_live); setIsLive(Boolean(data.is_live));
} catch (error) { } catch (error) {
console.error("Error checking stream status:", error); console.error("Error checking stream status:", error);
setIsLive(false); setIsLive(false);
@@ -31,11 +32,23 @@ const StreamerRoute: React.FC = () => {
}, [streamerName]); }, [streamerName]);
if (isLoading) { if (isLoading) {
return <div className="h-screen w-screen flex text-6xl items-center justify-center" >Loading...</div>; // Or your loading component return (
<div className="h-screen w-screen flex text-6xl items-center justify-center">
Loading...
</div>
);
// Or your loading component
} }
// streamId=0 is a special case for the streamer's latest stream // streamId=0 is a special case for the streamer's latest stream
return isLive ? <VideoPage streamId={1} /> : (streamerName ? <UserPage username={streamerName} /> : <div>Error: Streamer not found</div>); return isLive ? (
<VideoPage streamId={streamId} />
) : streamerName ? (
<UserPage />
) : (
<div>Error: Streamer not found</div>
);
}; };
export default StreamerRoute; export default StreamerRoute;

View File

@@ -1,4 +1,4 @@
import React from 'react' import React from "react";
interface ThumbnailProps { interface ThumbnailProps {
path: string; path: string;
@@ -7,15 +7,10 @@ interface ThumbnailProps {
const Thumbnail = ({ path, alt }: ThumbnailProps) => { const Thumbnail = ({ path, alt }: ThumbnailProps) => {
return ( return (
<div id='stream-thumbnail'> <div id="stream-thumbnail">
<img <img width={300} src={path} alt={alt} className="rounded-md" />
width={300}
src={path}
alt={alt}
className="rounded-md"
/>
</div> </div>
) );
} };
export default Thumbnail export default Thumbnail;

View File

@@ -121,7 +121,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
<div <div
ref={chatContainerRef} ref={chatContainerRef}
id="chat-message-list" id="chat-message-list"
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 rounded-[67px]"
> >
{messages.map((msg, index) => ( {messages.map((msg, index) => (
<div <div
@@ -129,7 +129,8 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
className="grid grid-cols-[minmax(15%,_100px)_1fr] group h-fit items-center bg-gray-700 rounded p-2 text-white" className="grid grid-cols-[minmax(15%,_100px)_1fr] group h-fit items-center bg-gray-700 rounded p-2 text-white"
> >
<span <span
className={`font-bold ${msg.chatter_username === username className={`font-bold ${
msg.chatter_username === username
? "text-blue-400" ? "text-blue-400"
: "text-green-400" : "text-green-400"
}`} }`}
@@ -137,7 +138,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
{" "} {" "}
{msg.chatter_username}:{" "} {msg.chatter_username}:{" "}
</span> </span>
<span className="text-center" >{msg.message}</span> <span className="text-center">{msg.message}</span>
<span className="text-gray-400 text-sm scale-0 group-hover:scale-100 h-[0px] group-hover:h-[10px] transition-all delay-1000 group-hover:delay-200"> <span className="text-gray-400 text-sm scale-0 group-hover:scale-100 h-[0px] group-hover:h-[10px] transition-all delay-1000 group-hover:delay-200">
{new Date(msg.time_sent).toLocaleTimeString()} {new Date(msg.time_sent).toLocaleTimeString()}
</span> </span>
@@ -153,13 +154,12 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
value={inputMessage} value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)} onChange={(e) => setInputMessage(e.target.value)}
onKeyDown={handleKeyPress} onKeyDown={handleKeyPress}
placeholder={ placeholder={isLoggedIn ? "Type a message..." : "Login to chat"}
isLoggedIn ? "Type a message..." : "Login to chat"
}
disabled={!isLoggedIn} disabled={!isLoggedIn}
extraClasses="flex-grow" extraClasses="flex-grow"
onClick={() => !isLoggedIn && setShowAuthModal(true)} onClick={() => !isLoggedIn && setShowAuthModal(true)}
/> />
<button <button
onClick={sendChat} onClick={sendChat}
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700" className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"

View File

@@ -19,7 +19,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({ streamId }) => {
"video-js", "video-js",
"vjs-big-play-centered", "vjs-big-play-centered",
"w-full", "w-full",
"h-full" "h-full",
); );
videoRef.current.appendChild(videoElement); videoRef.current.appendChild(videoElement);
@@ -34,7 +34,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({ streamId }) => {
{ {
src: `/images/sample_game_video.mp4`, src: `/images/sample_game_video.mp4`,
// type: "application/x-mpegURL", // type: "application/x-mpegURL",
type: 'video/mp4' type: "video/mp4",
}, },
], ],
}); });

View File

@@ -8,7 +8,7 @@ interface AuthContextType {
} }
export const AuthContext = createContext<AuthContextType | undefined>( export const AuthContext = createContext<AuthContextType | undefined>(
undefined undefined,
); );
export function useAuth() { export function useAuth() {

View File

@@ -29,7 +29,7 @@ const StreamsContext = createContext<StreamsContextType | undefined>(undefined);
export function StreamsProvider({ children }: { children: React.ReactNode }) { export function StreamsProvider({ children }: { children: React.ReactNode }) {
const [featuredStreams, setFeaturedStreams] = useState<StreamItem[]>([]); const [featuredStreams, setFeaturedStreams] = useState<StreamItem[]>([]);
const [featuredCategories, setFeaturedCategories] = useState<CategoryItem[]>( const [featuredCategories, setFeaturedCategories] = useState<CategoryItem[]>(
[] [],
); );
const { isLoggedIn } = useAuth(); const { isLoggedIn } = useAuth();

View File

@@ -1,10 +1,10 @@
import { StrictMode } from 'react' import { StrictMode } from "react";
import { createRoot } from 'react-dom/client' import { createRoot } from "react-dom/client";
import './assets/styles/index.css' import "./assets/styles/index.css";
import App from './App.tsx' import App from "./App.tsx";
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById("root")!).render(
// <StrictMode> // <StrictMode>
<App /> <App />,
// </StrictMode>, // </StrictMode>,
) );

View File

@@ -13,7 +13,7 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
const navigate = useNavigate(); const navigate = useNavigate();
const handleStreamClick = (streamId: number, streamerName: string) => { const handleStreamClick = (streamId: number, streamerName: string) => {
console.log(`Navigating to ${streamId}`); console.log(`Navigating to stream ${streamId}`);
navigate(`/${streamerName}`); navigate(`/${streamerName}`);
}; };
@@ -28,20 +28,34 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
{/* If Personalised_HomePage, display Streams recommended for the logged-in user. Else, live streams with the most viewers. */} {/* If Personalised_HomePage, display Streams recommended for the logged-in user. Else, live streams with the most viewers. */}
<ListRow <ListRow
type="stream" type="stream"
title={"Live Now" + (variant === "personalised" ? " - Recommended" : "")} title={
description={variant === "personalised" ? "We think you might like these streams - Streamers recommended for you" : "Streamers that are currently live"} "Live Now" + (variant === "personalised" ? " - Recommended" : "")
}
description={
variant === "personalised"
? "We think you might like these streams - Streamers recommended for you"
: "Streamers that are currently live"
}
items={featuredStreams} items={featuredStreams}
onClick={handleStreamClick} onClick={handleStreamClick}
/> />
{/* If Personalised_HomePage, display Categories the logged-in user follows. Else, trending categories. */} {/* If Personalised_HomePage, display Categories the logged-in user follows. Else, trending categories. */}
<ListRow <ListRow
type="category" type="category"
title={variant === "personalised" ? "Followed Categories" : "Trending Categories"} title={
description={variant === "personalised" ? "Current streams from your followed categories" : "Categories that have been 'popping off' lately"} variant === "personalised"
? "Followed Categories"
: "Trending Categories"
}
description={
variant === "personalised"
? "Current streams from your followed categories"
: "Categories that have been 'popping off' lately"
}
items={featuredCategories} items={featuredCategories}
onClick={() => {}} //TODO onClick={() => {}} //TODO
/> />
</div> </div>
); );
}; };

View File

@@ -1,10 +1,7 @@
import React from 'react'; import React from "react";
const NotFoundPage: React.FC = () => { const NotFoundPage: React.FC = () => {
return ( return <div></div>;
<div>
</div>
);
}; };
export default NotFoundPage; export default NotFoundPage;

View File

@@ -1,14 +1,124 @@
import React from "react"; import React, { useState, useEffect } from "react";
import Navbar from "../components/Layout/Navbar";
import { useParams } from "react-router-dom";
interface UserPageProps { interface UserProfileData {
username: string; username: string;
bio: string;
followerCount: number;
isPartnered: boolean;
} }
const UserPage: React.FC<UserPageProps> = ({ username }) => { const UserPage: React.FC = () => {
const [profileData, setProfileData] = useState<UserProfileData | null>(null);
const { username } = useParams();
useEffect(() => {
// Fetch user profile data
fetch(`/api/get_streamer_data/${username}`)
.then((res) => res.json())
.then((data) => {
setProfileData({
username: data.username,
bio: data.bio || "This user hasn't written a bio yet.",
followerCount: data.num_followering || 0,
isPartnered: data.isPartnered || false,
});
})
.catch((err) => console.error("Error fetching profile data:", err));
}, [username]);
if (!profileData) {
return ( return (
<div className="bg-[#808080] h-screen w-screen flex flex-col items-center justify-center"> <div className="h-screen w-screen flex items-center justify-center text-white">
<h1>{username}</h1> Loading...
<p>Profile page for {username}</p> </div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white">
<Navbar />
<div className="mx-auto px-4 py-8">
<div className="grid grid-cols-3 gap-8">
{/* Profile Section - Left Third */}
<div className="col-span-1 bg-gray-800 rounded-lg p-6 shadow-lg">
{/* Profile Picture */}
<div className="flex flex-col items-center">
<div className="relative w-48 h-48 rounded-full overflow-hidden mb-6">
<img
src="/images/monkey.png"
alt={`${profileData.username}'s profile`}
className="w-full h-full object-cover"
/>
{profileData.isPartnered && (
<div className="absolute bottom-2 right-2 bg-purple-600 rounded-full p-2">
<svg
className="w-6 h-6 text-white"
fill="currentColor"
viewBox="0 0 20 20"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
</div>
)}
</div>
<h1 className="text-3xl font-bold mb-2">
{profileData.username}
</h1>
<div className="flex items-center space-x-2 mb-6">
<span className="text-gray-400">
{profileData.followerCount.toLocaleString()} followers
</span>
{profileData.isPartnered && (
<span className="bg-purple-600 text-white text-sm px-2 py-1 rounded">
Partner
</span>
)}
</div>
<button className="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg mb-4 transition-colors">
Follow
</button>
</div>
{/* Bio Section */}
<div className="mt-6">
<h2 className="text-xl font-semibold mb-3">
About {profileData.username}
</h2>
<p className="text-gray-300 whitespace-pre-wrap">
{profileData.bio}
</p>
</div>
{/* Additional Stats */}
<div className="mt-6 pt-6 border-t border-gray-700">
<div className="grid grid-cols-2 gap-4 text-center">
<div>
<div className="text-2xl font-bold text-purple-400">0</div>
<div className="text-sm text-gray-400">Total Views</div>
</div>
<div>
<div className="text-2xl font-bold text-purple-400">0</div>
<div className="text-sm text-gray-400">Following</div>
</div>
</div>
</div>
</div>
{/* Content Section */}
<div className="col-span-2 bg-gray-800 rounded-lg p-6 flex flex-col">
<h2 className="text-2xl font-bold mb-4">Past Broadcasts</h2>
<div className="text-gray-400 flex h-full rounded-none">
No past broadcasts found
</div>
</div>
</div>
</div>
</div> </div>
); );
}; };

View File

@@ -1,8 +1,8 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import Navbar from "../components/Layout/Navbar"; import Navbar from "../components/Layout/Navbar";
import Button, { ToggleButton } from "../components/Layout/Button"; import Button from "../components/Layout/Button";
import ChatPanel from "../components/Video/ChatPanel"; import ChatPanel from "../components/Video/ChatPanel";
import { useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { useAuth } from "../context/AuthContext"; import { useAuth } from "../context/AuthContext";
import VideoPlayer from "../components/Video/VideoPlayer"; import VideoPlayer from "../components/Video/VideoPlayer";
import { SocketProvider } from "../context/SocketContext"; import { SocketProvider } from "../context/SocketContext";
@@ -28,7 +28,7 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamId }) => {
const [isChatOpen, setIsChatOpen] = useState(true); const [isChatOpen, setIsChatOpen] = useState(true);
// const [showCheckout, setShowCheckout] = useState(false); // const [showCheckout, setShowCheckout] = useState(false);
// const showReturn = window.location.search.includes("session_id"); // const showReturn = window.location.search.includes("session_id");
// const navigate = useNavigate(); const navigate = useNavigate();
// useEffect(() => { // useEffect(() => {
// // Prevent scrolling when checkout is open // // Prevent scrolling when checkout is open
@@ -45,8 +45,7 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamId }) => {
useEffect(() => { useEffect(() => {
// Fetch stream data for this streamer // Fetch stream data for this streamer
fetch( fetch(
`/api/get_stream_data/${streamerName}${streamId == 0 ? "" : `/${streamId}` `/api/get_stream_data/${streamerName}${streamId == 0 ? "" : `/${streamId}`}`,
}`
).then((res) => { ).then((res) => {
if (!res.ok) { if (!res.ok) {
console.error("Failed to load stream data:", res.statusText); console.error("Failed to load stream data:", res.statusText);
@@ -80,7 +79,10 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamId }) => {
<SocketProvider> <SocketProvider>
<div id="videoPage" className="w-full"> <div id="videoPage" className="w-full">
<Navbar isChatOpen={isChatOpen} toggleChat={toggleChat} /> <Navbar isChatOpen={isChatOpen} toggleChat={toggleChat} />
<div id="container" className={`grid grid-rows-[auto_1fr] bg-gray-900 h-full ${isChatOpen ? "grid-cols-[3fr_1fr]" : "grid-cols-1"}`}
<div
id="container"
className={`grid grid-rows-[auto_1fr] bg-gray-900 h-full ${isChatOpen ? "grid-cols-[3fr_1fr]" : "grid-cols-1"}`}
> >
<div className="relative"> <div className="relative">
<VideoPlayer streamId={streamId} /> <VideoPlayer streamId={streamId} />
@@ -103,8 +105,8 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamId }) => {
{streamData ? streamData.streamTitle : "Loading..."} {streamData ? streamData.streamTitle : "Loading..."}
</h1> </h1>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<div className="flex items-center gap-2"> <div id="streamer" className="flex items-center gap-2 cursor-pointer" onClick={() => navigate(`/user/${streamerName}`)} >
<span className="font-semibold">Streamer:</span> <img src="/images/monkey.png" alt="streamer" className="w-10 h-10 bg-indigo-500 rounded-full" />
<span> <span>
{streamData ? streamData.streamerName : "Loading..."} {streamData ? streamData.streamerName : "Loading..."}
</span> </span>

View File

@@ -92,22 +92,22 @@ def get_streamer_data(streamer_username):
@stream_bp.route('/streamer/<string:streamer_username>/status') @stream_bp.route('/streamer/<string:streamer_username>/status')
def get_streamer_status(streamer_username): def get_streamer_status(streamer_username):
""" """
Returns a streamer's status, if they are live or not and their most recent stream Returns a streamer's status, if they are live or not and their most recent stream (their current stream if live)
""" """
user_id = get_user_id(streamer_username) user_id = get_user_id(streamer_username)
if not user_id: if not user_id:
abort(404) abort(404)
is_live = streamer_live_status(user_id) is_live = True if streamer_live_status(user_id)['isLive'] else False
most_recent_stream = streamer_most_recent_stream(user_id) most_recent_stream = streamer_most_recent_stream(user_id)['stream_id']
if not most_recent_stream: if not most_recent_stream:
most_recent_stream = {'stream_id': None} most_recent_stream = None
return jsonify({ return jsonify({
"is_live": is_live, "is_live": is_live,
"most_recent_stream": most_recent_stream['stream_id'] "most_recent_stream": most_recent_stream
}) })
@@ -122,6 +122,20 @@ def get_stream(streamer_username):
return jsonify(streamer_most_recent_stream(user_id)) return jsonify(streamer_most_recent_stream(user_id))
@stream_bp.route('/get_stream_data/<string:streamer_username>/<int:stream_id>')
def get_specific_stream(streamer_username, stream_id):
"""
Returns a streamer's stream data given stream_id
"""
user_id = get_user_id(streamer_username)
stream = user_stream(user_id, stream_id)
if stream:
return jsonify(stream)
return jsonify({'error': 'Stream not found'}), 404
@login_required @login_required
@stream_bp.route('/get_followed_category_streams') @stream_bp.route('/get_followed_category_streams')
def get_following_categories_streams(): def get_following_categories_streams():
@@ -136,18 +150,6 @@ def get_following_categories_streams():
return jsonify(streams) return jsonify(streams)
@stream_bp.route('/get_stream_data/<string:streamer_username>/<int:stream_id>')
def get_specific_stream(streamer_username, stream_id):
"""
Returns a streamer's stream data given stream_id
"""
user_id = get_user_id(streamer_username)
stream = user_stream(user_id, stream_id)
if stream:
return jsonify(stream)
return jsonify({'error': 'Stream not found'}), 404
@login_required @login_required
@stream_bp.route('/get_followed_streamers') @stream_bp.route('/get_followed_streamers')
def get_followed_streamers(): def get_followed_streamers():

View File

@@ -1,6 +1,7 @@
from database.database import Database from database.database import Database
from typing import Optional, List from typing import Optional, List
def user_recommendation_category(user_id: int) -> Optional[int]: def user_recommendation_category(user_id: int) -> Optional[int]:
""" """
Queries user_preferences database to find users favourite streaming category and returns the category Queries user_preferences database to find users favourite streaming category and returns the category
@@ -15,7 +16,8 @@ def user_recommendation_category(user_id: int) -> Optional[int]:
""", (user_id,)) """, (user_id,))
return category["category_id"] if category else None return category["category_id"] if category else None
def followed_categories_recommendations(user_id : int) -> Optional[List[dict]]:
def followed_categories_recommendations(user_id: int) -> Optional[List[dict]]:
""" """
Returns top 25 streams given a users category following Returns top 25 streams given a users category following
""" """
@@ -31,6 +33,7 @@ def followed_categories_recommendations(user_id : int) -> Optional[List[dict]]:
""", (user_id,)) """, (user_id,))
return streams return streams
def recommendations_based_on_category(category_id: int) -> Optional[List[dict]]: def recommendations_based_on_category(category_id: int) -> Optional[List[dict]]:
""" """
Queries stream database to get top 25 most viewed streams based on given category Queries stream database to get top 25 most viewed streams based on given category
@@ -58,11 +61,13 @@ def default_recommendations() -> Optional[List[dict]]:
FROM streams FROM streams
JOIN users ON users.user_id = streams.user_id JOIN users ON users.user_id = streams.user_id
JOIN categories ON streams.category_id = categories.category_id JOIN categories ON streams.category_id = categories.category_id
WHERE isLive = 1
ORDER BY num_viewers DESC ORDER BY num_viewers DESC
LIMIT 25; LIMIT 25;
""") """)
return data return data
def category_recommendations() -> Optional[List[dict]]: def category_recommendations() -> Optional[List[dict]]:
""" """
Returns a list of the top 5 most popular live categories Returns a list of the top 5 most popular live categories
@@ -79,6 +84,7 @@ def category_recommendations() -> Optional[List[dict]]:
""") """)
return categories return categories
def user_category_recommendations(user_id: int) -> Optional[List[dict]]: def user_category_recommendations(user_id: int) -> Optional[List[dict]]:
""" """
Queries user_preferences database to find users top 5 favourite streaming category and returns the category Queries user_preferences database to find users top 5 favourite streaming category and returns the category

View File

@@ -45,29 +45,6 @@ def followed_streamers(user_id: int) -> Optional[List[dict]]:
""", (user_id,)) """, (user_id,))
return followed_streamers return followed_streamers
def streamer_most_recent_stream(user_id: int) -> Optional[dict]:
"""
Returns data of the most recent stream by a streamer
"""
with Database() as db:
most_recent_stream = db.fetchone("""
SELECT * FROM streams
WHERE user_id = ?
AND stream_id = (SELECT MAX(stream_id) FROM streams WHERE user_id = ?)
""", (user_id, user_id))
return most_recent_stream
def streamer_data(streamer_id: int) -> Optional[dict]:
"""
Returns information about the streamer
"""
with Database() as db:
data = db.fetchone("""
SELECT username, num_followering, isPartnered FROM users
WHERE user_id = ?
""", (streamer_id))
return data
def user_stream(user_id: int, stream_id: int) -> dict: def user_stream(user_id: int, stream_id: int) -> dict:
""" """
Returns data of a streamers selected stream Returns data of a streamers selected stream
@@ -83,6 +60,32 @@ def user_stream(user_id: int, stream_id: int) -> dict:
""", (user_id, stream_id)) """, (user_id, stream_id))
return stream return stream
def streamer_most_recent_stream(user_id: int) -> Optional[dict]:
"""
Returns data of the most recent stream by a streamer
"""
with Database() as db:
most_recent_stream = db.fetchone("""
SELECT s.stream_id, u.username, s.user_id, s.title, s.start_time, s.num_viewers, c.category_name
FROM streams AS s
JOIN categories AS c ON s.category_id = c.category_id
JOIN users AS u ON s.user_id = u.user_id
WHERE u.user_id = ?
AND s.stream_id = (SELECT MAX(stream_id) FROM streams WHERE user_id = ?)
""", (user_id, user_id))
return most_recent_stream
def streamer_data(streamer_id: int) -> Optional[dict]:
"""
Returns information about the streamer
"""
with Database() as db:
data = db.fetchone("""
SELECT username, bio, num_followers, is_partnered FROM users
WHERE user_id = ?
""", (streamer_id,))
return data
def generate_thumbnail(user_id: int) -> None: def generate_thumbnail(user_id: int) -> None:
""" """
Returns the thumbnail of a stream Returns the thumbnail of a stream