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",
"typescript": "~5.6.2",
"typescript-eslint": "^8.18.2",
"vite": "^6.0.5"
"vite": "latest"
}
},
"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 StreamerRoute from "./components/Stream/StreamerRoute";
import NotFoundPage from "./pages/NotFoundPage";
import UserPage from "./pages/UserPage";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
@@ -24,15 +25,22 @@ function App() {
}, []);
return (
<AuthContext.Provider value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}>
<AuthContext.Provider
value={{ isLoggedIn, username, setIsLoggedIn, setUsername }}
>
<StreamsProvider>
<BrowserRouter>
<Routes>
<Route
path="/"
element={isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />}
element={
isLoggedIn ? <HomePage variant="personalised" /> : <HomePage />
}
/>
<Route path="/:streamerName" element={<StreamerRoute />} />
<Route path="/user/:username" element={<UserPage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</BrowserRouter>

View File

@@ -5,14 +5,13 @@ import LoginForm from "./LoginForm";
import RegisterForm from "./RegisterForm";
import "../../assets/styles/auth.css";
interface AuthModalProps {
onClose: () => void;
}
const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => {
const [selectedTab, setSelectedTab] = useState<string>("Login");
const [spinDuration, setSpinDuration] = useState("7s")
const [spinDuration, setSpinDuration] = useState("7s");
const handleSubmit = () => {
setSpinDuration("1s");
@@ -25,21 +24,26 @@ const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => {
return (
<>
{/*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*/}
<div
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"
style={{ "--spin-duration": spinDuration } as React.CSSProperties}
>
{/*Border Container*/}
<div
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
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
onClick={onClose}
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
</ToggleButton>
</div>
{selectedTab === "Login" ? <LoginForm onSubmit={handleSubmit} /> : <RegisterForm onSubmit={handleSubmit}/>}
{selectedTab === "Login" ? (
<LoginForm onSubmit={handleSubmit} />
) : (
<RegisterForm onSubmit={handleSubmit} />
)}
</div>
</div>
</>

View File

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

View File

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

View File

@@ -67,8 +67,14 @@ const CheckoutForm: React.FC<CheckoutFormProps> = ({ onClose }) => {
return (
<>
<div 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]">
<div
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
onClick={onClose}
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}
type={item.type}
title={item.title}
streamer={item.type === "stream" ? (item.streamer) : undefined}
streamer={item.type === "stream" ? item.streamer : undefined}
viewers={item.viewers}
thumbnail={item.thumbnail}
onItemClick={() =>
onClick?.(item.id, item.streamer || item.title)
}
onItemClick={() => onClick?.(item.id, item.streamer || item.title)}
/>
))}
</div>

View File

@@ -6,11 +6,13 @@ interface LogoProps {
}
const Logo: React.FC<LogoProps> = ({ variant = "default" }) => {
const gradient =
"text-transparent group-hover:mx-1 transition-all";
const gradient = "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]"}`}>
<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>

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react";
import Logo from "./Logo";
import Button, {ToggleButton} from "./Button";
import Button, { ToggleButton } from "./Button";
import Sidebar from "./Sidebar";
import { Sidebar as SidebarIcon } from "lucide-react";
import {
@@ -13,14 +13,17 @@ import Input from "./Input";
import AuthModal from "../Auth/AuthModal";
import { useAuth } from "../../context/AuthContext";
interface NavbarProps {
variant?: "home" | "default";
isChatOpen: boolean;
toggleChat: () => void;
isChatOpen?: boolean;
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 { isLoggedIn } = useAuth();
const isVideoPage = location.pathname.includes("/EduGuru");
@@ -47,7 +50,10 @@ const Navbar: React.FC<NavbarProps> = ({ variant = "default", isChatOpen, toggle
};
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} />
<Button
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
</Button>
{isVideoPage && (
<ToggleButton onClick={toggleChat} toggled={isChatOpen}
<ToggleButton
onClick={toggleChat}
toggled={isChatOpen}
extraClasses="absolute top-[80px] right-[20px] text-[1rem] flex items-center flex-nowrap"
>
{isChatOpen ? "Hide Chat" : "Show Chat"}
@@ -96,10 +104,10 @@ const Navbar: React.FC<NavbarProps> = ({ variant = "default", isChatOpen, toggle
placeholder="Search..."
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" />
</div>
{showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />}
</div>
);

View File

@@ -7,13 +7,14 @@ const StreamerRoute: React.FC = () => {
const { streamerName } = useParams<{ streamerName: string }>();
const [isLive, setIsLive] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(true);
let streamId: number = 0;
useEffect(() => {
const checkStreamStatus = async () => {
try {
const response = await fetch(`/api/streamer/${streamerName}/status`);
const data = await response.json();
setIsLive(data.is_live);
setIsLive(Boolean(data.is_live));
} catch (error) {
console.error("Error checking stream status:", error);
setIsLive(false);
@@ -31,11 +32,23 @@ const StreamerRoute: React.FC = () => {
}, [streamerName]);
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
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;

View File

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

View File

@@ -121,7 +121,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
<div
ref={chatContainerRef}
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) => (
<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"
>
<span
className={`font-bold ${msg.chatter_username === username
className={`font-bold ${
msg.chatter_username === username
? "text-blue-400"
: "text-green-400"
}`}
@@ -137,7 +138,7 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
{" "}
{msg.chatter_username}:{" "}
</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">
{new Date(msg.time_sent).toLocaleTimeString()}
</span>
@@ -153,13 +154,12 @@ const ChatPanel: React.FC<ChatPanelProps> = ({ streamId }) => {
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyDown={handleKeyPress}
placeholder={
isLoggedIn ? "Type a message..." : "Login to chat"
}
placeholder={isLoggedIn ? "Type a message..." : "Login to chat"}
disabled={!isLoggedIn}
extraClasses="flex-grow"
onClick={() => !isLoggedIn && setShowAuthModal(true)}
/>
<button
onClick={sendChat}
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",
"vjs-big-play-centered",
"w-full",
"h-full"
"h-full",
);
videoRef.current.appendChild(videoElement);
@@ -34,7 +34,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({ streamId }) => {
{
src: `/images/sample_game_video.mp4`,
// type: "application/x-mpegURL",
type: 'video/mp4'
type: "video/mp4",
},
],
});

View File

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

View File

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

View File

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

View File

@@ -13,7 +13,7 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
const navigate = useNavigate();
const handleStreamClick = (streamId: number, streamerName: string) => {
console.log(`Navigating to ${streamId}`);
console.log(`Navigating to stream ${streamId}`);
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. */}
<ListRow
type="stream"
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"}
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"
}
items={featuredStreams}
onClick={handleStreamClick}
/>
{/* If Personalised_HomePage, display Categories the logged-in user follows. Else, trending categories. */}
<ListRow
type="category"
title={variant === "personalised" ? "Followed Categories" : "Trending Categories"}
description={variant === "personalised" ? "Current streams from your followed categories" : "Categories that have been 'popping off' lately"}
title={
variant === "personalised"
? "Followed Categories"
: "Trending Categories"
}
description={
variant === "personalised"
? "Current streams from your followed categories"
: "Categories that have been 'popping off' lately"
}
items={featuredCategories}
onClick={() => {}} //TODO
/>
</div>
);
};

View File

@@ -1,10 +1,7 @@
import React from 'react';
import React from "react";
const NotFoundPage: React.FC = () => {
return (
<div>
</div>
);
return <div></div>;
};
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;
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 (
<div className="bg-[#808080] h-screen w-screen flex flex-col items-center justify-center">
<h1>{username}</h1>
<p>Profile page for {username}</p>
<div className="h-screen w-screen flex items-center justify-center text-white">
Loading...
</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>
);
};

View File

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

View File

@@ -92,22 +92,22 @@ def get_streamer_data(streamer_username):
@stream_bp.route('/streamer/<string:streamer_username>/status')
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)
if not user_id:
abort(404)
is_live = streamer_live_status(user_id)
most_recent_stream = streamer_most_recent_stream(user_id)
is_live = True if streamer_live_status(user_id)['isLive'] else False
most_recent_stream = streamer_most_recent_stream(user_id)['stream_id']
if not most_recent_stream:
most_recent_stream = {'stream_id': None}
most_recent_stream = None
return jsonify({
"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))
@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
@stream_bp.route('/get_followed_category_streams')
def get_following_categories_streams():
@@ -136,18 +150,6 @@ def get_following_categories_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
@stream_bp.route('/get_followed_streamers')
def get_followed_streamers():

View File

@@ -1,6 +1,7 @@
from database.database import Database
from typing import Optional, List
def user_recommendation_category(user_id: int) -> Optional[int]:
"""
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,))
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
"""
@@ -31,6 +33,7 @@ def followed_categories_recommendations(user_id : int) -> Optional[List[dict]]:
""", (user_id,))
return streams
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
@@ -58,11 +61,13 @@ def default_recommendations() -> Optional[List[dict]]:
FROM streams
JOIN users ON users.user_id = streams.user_id
JOIN categories ON streams.category_id = categories.category_id
WHERE isLive = 1
ORDER BY num_viewers DESC
LIMIT 25;
""")
return data
def category_recommendations() -> Optional[List[dict]]:
"""
Returns a list of the top 5 most popular live categories
@@ -79,6 +84,7 @@ def category_recommendations() -> Optional[List[dict]]:
""")
return categories
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

View File

@@ -45,29 +45,6 @@ def followed_streamers(user_id: int) -> Optional[List[dict]]:
""", (user_id,))
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:
"""
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))
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:
"""
Returns the thumbnail of a stream