MAJOR UPDATE/FEAT: Overhaul of DashboardPage to include VODs;
REFACTOR: General formatting; UPDATE: Shrink Logo upon opening sidebar on certain pages
This commit is contained in:
@@ -11,101 +11,77 @@ import CategoriesPage from "./pages/AllCategoriesPage";
|
|||||||
import ResultsPage from "./pages/ResultsPage";
|
import ResultsPage from "./pages/ResultsPage";
|
||||||
import { SidebarProvider } from "./context/SidebarContext";
|
import { SidebarProvider } from "./context/SidebarContext";
|
||||||
import { QuickSettingsProvider } from "./context/QuickSettingsContext";
|
import { QuickSettingsProvider } from "./context/QuickSettingsContext";
|
||||||
import StreamDashboardPage from "./pages/StreamDashboardPage";
|
import DashboardPage from "./pages/DashboardPage";
|
||||||
import { Brightness } from "./context/BrightnessContext";
|
import { Brightness } from "./context/BrightnessContext";
|
||||||
import LoadingScreen from "./components/Layout/LoadingScreen";
|
import LoadingScreen from "./components/Layout/LoadingScreen";
|
||||||
import Following from "./pages/Following";
|
import Following from "./pages/Following";
|
||||||
import FollowedCategories from "./pages/FollowedCategories";
|
import FollowedCategories from "./pages/FollowedCategories";
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||||
const [userId, setUserId] = useState<number | null>(null);
|
const [username, setUsername] = useState<string | null>(null);
|
||||||
const [username, setUsername] = useState<string | null>(null);
|
const [userId, setUserId] = useState<number | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLive, setIsLive] = useState(false);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch("/api/user/login_status")
|
fetch("/api/user/login_status")
|
||||||
.then((response) => response.json())
|
.then((response) => response.json())
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
setUserId(data.user_id);
|
setUserId(data.user_id);
|
||||||
setIsLoggedIn(data.status);
|
setIsLoggedIn(data.status);
|
||||||
setUsername(data.username);
|
setUsername(data.username);
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error("Error fetching login status:", error);
|
console.error("Error fetching login status:", error);
|
||||||
setIsLoggedIn(false);
|
setIsLoggedIn(false);
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return <LoadingScreen />;
|
return <LoadingScreen />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Brightness>
|
<Brightness>
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
value={{
|
value={{
|
||||||
isLoggedIn,
|
isLoggedIn,
|
||||||
username,
|
username,
|
||||||
userId,
|
userId,
|
||||||
setIsLoggedIn,
|
isLive,
|
||||||
setUsername,
|
setIsLoggedIn,
|
||||||
setUserId,
|
setUsername,
|
||||||
}}
|
setUserId,
|
||||||
>
|
setIsLive,
|
||||||
<SidebarProvider>
|
}}
|
||||||
<QuickSettingsProvider>
|
>
|
||||||
<BrowserRouter>
|
<SidebarProvider>
|
||||||
<Routes>
|
<QuickSettingsProvider>
|
||||||
<Route
|
<BrowserRouter>
|
||||||
path="/"
|
<Routes>
|
||||||
element={
|
<Route path="/" element={<HomePage />} />
|
||||||
isLoggedIn ? (
|
<Route path="/dashboard" element={isLoggedIn ? <DashboardPage /> : <Navigate to="/" replace />} />
|
||||||
<HomePage variant="personalised" />
|
<Route path="/:streamerName" element={<StreamerRoute />} />
|
||||||
) : (
|
<Route path="/user/:username" element={<UserPage />} />
|
||||||
<HomePage />
|
<Route path="/reset_password/:token" element={<ResetPasswordPage />}></Route>
|
||||||
)
|
<Route path="/category/:categoryName" element={<CategoryPage />}></Route>
|
||||||
}
|
<Route path="/categories" element={<CategoriesPage />}></Route>
|
||||||
/>
|
<Route path="/results" element={<ResultsPage />}></Route>
|
||||||
<Route
|
<Route path="/404" element={<NotFoundPage />} />
|
||||||
path="/go-live"
|
<Route path="/user/:username/following" element={<Following />} />
|
||||||
element={
|
<Route path="/user/:username/yourCategories" element={<FollowedCategories />} />
|
||||||
isLoggedIn ? (
|
<Route path="*" element={<Navigate to="/404" replace />} />
|
||||||
<StreamDashboardPage />
|
</Routes>
|
||||||
) : (
|
</BrowserRouter>
|
||||||
<Navigate to="/" replace />
|
</QuickSettingsProvider>
|
||||||
)
|
</SidebarProvider>
|
||||||
}
|
</AuthContext.Provider>
|
||||||
/>
|
</Brightness>
|
||||||
<Route path="/:streamerName" element={<StreamerRoute />} />
|
);
|
||||||
<Route path="/user/:username" element={<UserPage />} />
|
|
||||||
<Route
|
|
||||||
path="/reset_password/:token"
|
|
||||||
element={<ResetPasswordPage />}
|
|
||||||
></Route>
|
|
||||||
<Route
|
|
||||||
path="/category/:categoryName"
|
|
||||||
element={<CategoryPage />}
|
|
||||||
></Route>
|
|
||||||
<Route
|
|
||||||
path="/categories"
|
|
||||||
element={<CategoriesPage />}
|
|
||||||
></Route>
|
|
||||||
<Route path="/results" element={<ResultsPage />}></Route>
|
|
||||||
<Route path="/404" element={<NotFoundPage />} />
|
|
||||||
<Route path="/user/:username/following" element={<Following />} />
|
|
||||||
<Route path="/user/:username/yourCategories" element={<FollowedCategories />} />
|
|
||||||
<Route path="*" element={<Navigate to="/404" replace />} />
|
|
||||||
</Routes>
|
|
||||||
</BrowserRouter>
|
|
||||||
</QuickSettingsProvider>
|
|
||||||
</SidebarProvider>
|
|
||||||
</AuthContext.Provider>
|
|
||||||
</Brightness>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default App;
|
export default App;
|
||||||
|
|||||||
@@ -78,7 +78,6 @@ const RegisterForm: React.FC<SubmitProps> = ({ onSubmit }) => {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.account_created) {
|
if (data.account_created) {
|
||||||
//TODO Handle successful registration (e.g., redirect or show success message)
|
|
||||||
console.log("Registration Successful! Account created successfully");
|
console.log("Registration Successful! Account created successfully");
|
||||||
setIsLoggedIn(true);
|
setIsLoggedIn(true);
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import Navbar from "../Navigation/Navbar";
|
import Navbar from "../Navigation/Navbar";
|
||||||
import { useSidebar } from "../../context/SidebarContext";
|
import { useSidebar } from "../../context/SidebarContext";
|
||||||
import Footer from "./Footer";
|
|
||||||
|
|
||||||
interface DynamicPageContentProps extends React.HTMLProps<HTMLDivElement> {
|
interface DynamicPageContentProps extends React.HTMLProps<HTMLDivElement> {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
@@ -28,7 +27,7 @@ const DynamicPageContent: React.FC<DynamicPageContentProps> = ({
|
|||||||
<Navbar variant={navbarVariant} />
|
<Navbar variant={navbarVariant} />
|
||||||
<div
|
<div
|
||||||
id="content"
|
id="content"
|
||||||
className={`min-w-[850px] ${
|
className={`flex-grow min-w-[850px] ${
|
||||||
showSideBar ? "w-[85vw] translate-x-[15vw]" : "w-[100vw]"
|
showSideBar ? "w-[85vw] translate-x-[15vw]" : "w-[100vw]"
|
||||||
} items-start transition-all duration-[500ms] ease-in-out ${contentClassName}`}
|
} items-start transition-all duration-[500ms] ease-in-out ${contentClassName}`}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -3,186 +3,164 @@ import { StreamType } from "../../types/StreamType";
|
|||||||
import { CategoryType } from "../../types/CategoryType";
|
import { CategoryType } from "../../types/CategoryType";
|
||||||
import { UserType } from "../../types/UserType";
|
import { UserType } from "../../types/UserType";
|
||||||
import { VodType } from "../../types/VodType";
|
import { VodType } from "../../types/VodType";
|
||||||
|
import { DownloadIcon, UploadIcon } from "lucide-react";
|
||||||
|
|
||||||
// Base props that all item types share
|
// Base props that all item types share
|
||||||
interface BaseListItemProps {
|
interface BaseListItemProps {
|
||||||
onItemClick?: () => void;
|
onItemClick?: () => void;
|
||||||
extraClasses?: string;
|
extraClasses?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stream item component
|
// Stream item component
|
||||||
interface StreamListItemProps extends BaseListItemProps, Omit<StreamType, 'type'> {}
|
interface StreamListItemProps extends BaseListItemProps, Omit<StreamType, "type"> {}
|
||||||
|
|
||||||
const StreamListItem: React.FC<StreamListItemProps> = ({
|
const StreamListItem: React.FC<StreamListItemProps> = ({
|
||||||
title,
|
title,
|
||||||
username,
|
username,
|
||||||
streamCategory,
|
streamCategory,
|
||||||
viewers,
|
viewers,
|
||||||
thumbnail,
|
thumbnail,
|
||||||
onItemClick,
|
onItemClick,
|
||||||
extraClasses = "",
|
extraClasses = "",
|
||||||
}) => {
|
}) => {
|
||||||
return (
|
return (
|
||||||
<div className="p-4">
|
<div className="p-4">
|
||||||
<div
|
<div
|
||||||
className={`${extraClasses} overflow-hidden flex-shrink-0 flex flex-col bg-purple-900 rounded-lg cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 transition-all`}
|
className={`${extraClasses} overflow-hidden flex-shrink-0 flex flex-col bg-purple-900 rounded-lg cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 transition-all`}
|
||||||
onClick={onItemClick}
|
onClick={onItemClick}
|
||||||
>
|
>
|
||||||
<div className="relative w-full aspect-video overflow-hidden rounded-t-lg">
|
<div className="relative w-full aspect-video overflow-hidden rounded-t-lg">
|
||||||
{thumbnail ? (
|
{thumbnail ? (
|
||||||
<img
|
<img src={thumbnail} alt={title} className="absolute top-0 left-0 w-full h-full object-cover" />
|
||||||
src={thumbnail}
|
) : (
|
||||||
alt={title}
|
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
|
||||||
className="absolute top-0 left-0 w-full h-full object-cover"
|
)}
|
||||||
/>
|
</div>
|
||||||
) : (
|
<div className="p-3">
|
||||||
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
|
<h3 className="font-semibold text-lg text-center truncate max-w-full">{title}</h3>
|
||||||
)}
|
<p className="font-bold">{username}</p>
|
||||||
</div>
|
<p className="text-sm text-gray-300">{streamCategory}</p>
|
||||||
<div className="p-3">
|
<p className="text-sm text-gray-300">{viewers} viewers</p>
|
||||||
<h3 className="font-semibold text-lg text-center truncate max-w-full">
|
</div>
|
||||||
{title}
|
</div>
|
||||||
</h3>
|
</div>
|
||||||
<p className="font-bold">{username}</p>
|
);
|
||||||
<p className="text-sm text-gray-300">{streamCategory}</p>
|
|
||||||
<p className="text-sm text-gray-300">{viewers} viewers</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Category item component
|
// Category item component
|
||||||
interface CategoryListItemProps extends BaseListItemProps, Omit<CategoryType, 'type'> {}
|
interface CategoryListItemProps extends BaseListItemProps, Omit<CategoryType, "type"> {}
|
||||||
|
|
||||||
const CategoryListItem: React.FC<CategoryListItemProps> = ({
|
const CategoryListItem: React.FC<CategoryListItemProps> = ({ title, viewers, thumbnail, onItemClick, extraClasses = "" }) => {
|
||||||
title,
|
return (
|
||||||
viewers,
|
<div className="p-4">
|
||||||
thumbnail,
|
<div
|
||||||
onItemClick,
|
className={`${extraClasses} overflow-hidden flex-shrink-0 flex flex-col bg-purple-900 rounded-lg cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 transition-all`}
|
||||||
extraClasses = "",
|
onClick={onItemClick}
|
||||||
}) => {
|
>
|
||||||
return (
|
<div className="relative w-full aspect-video overflow-hidden rounded-t-lg">
|
||||||
<div className="p-4">
|
{thumbnail ? (
|
||||||
<div
|
<img src={thumbnail} alt={title} className="absolute top-0 left-0 w-full h-full object-cover" />
|
||||||
className={`${extraClasses} overflow-hidden flex-shrink-0 flex flex-col bg-purple-900 rounded-lg cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 transition-all`}
|
) : (
|
||||||
onClick={onItemClick}
|
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
|
||||||
>
|
)}
|
||||||
<div className="relative w-full aspect-video overflow-hidden rounded-t-lg">
|
</div>
|
||||||
{thumbnail ? (
|
<div className="p-3">
|
||||||
<img
|
<h3 className="font-semibold text-lg text-center truncate max-w-full">{title}</h3>
|
||||||
src={thumbnail}
|
<p className="text-sm text-gray-300">{viewers} viewers</p>
|
||||||
alt={title}
|
</div>
|
||||||
className="absolute top-0 left-0 w-full h-full object-cover"
|
</div>
|
||||||
/>
|
</div>
|
||||||
) : (
|
);
|
||||||
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="p-3">
|
|
||||||
<h3 className="font-semibold text-lg text-center truncate max-w-full">
|
|
||||||
{title}
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-gray-300">{viewers} viewers</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// User item component
|
// User item component
|
||||||
interface UserListItemProps extends BaseListItemProps, Omit<UserType, 'type'> {}
|
interface UserListItemProps extends BaseListItemProps, Omit<UserType, "type"> {}
|
||||||
|
|
||||||
const UserListItem: React.FC<UserListItemProps> = ({
|
const UserListItem: React.FC<UserListItemProps> = ({ title, username, isLive, onItemClick, extraClasses = "" }) => {
|
||||||
title,
|
return (
|
||||||
username,
|
<div className="p-4 pb-10">
|
||||||
isLive,
|
<div
|
||||||
onItemClick,
|
className={`group relative w-fit flex flex-col bg-purple-900 rounded-tl-xl rounded-xl min-h-[calc((20vw+20vh)/3)] max-w-[calc((27vw+27vh)/2)] justify-end items-center cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 z-50 transition-all ${extraClasses}`}
|
||||||
extraClasses = "",
|
onClick={onItemClick}
|
||||||
}) => {
|
>
|
||||||
return (
|
<img
|
||||||
<div className="p-4 pb-10">
|
|
||||||
<div
|
|
||||||
className={`group relative w-fit flex flex-col bg-purple-900 rounded-tl-xl rounded-xl min-h-[calc((20vw+20vh)/3)] max-w-[calc((27vw+27vh)/2)] justify-end items-center cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 z-50 transition-all ${extraClasses}`}
|
|
||||||
onClick={onItemClick}
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src="/images/monkey.png"
|
src="/images/monkey.png"
|
||||||
alt={`user ${username}`}
|
alt={`user ${username}`}
|
||||||
className="rounded-xl border-[0.15em] border-[var(--bg-color)] cursor-pointer"
|
className="rounded-xl border-[0.15em] border-[var(--bg-color)] cursor-pointer"
|
||||||
/>
|
/>
|
||||||
<button className="text-[calc((2vw+2vh)/2)] font-bold hover:underline w-full py-2">
|
<button className="text-[calc((2vw+2vh)/2)] font-bold hover:underline w-full py-2">{title}</button>
|
||||||
{title}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{isLive && (
|
{isLive && (
|
||||||
<p className="absolute font-black bottom-5 opacity-0 group-hover:translate-y-full group-hover:opacity-100 group-hover:-bottom-1 transition-all">
|
<p className="absolute font-black bottom-5 opacity-0 group-hover:translate-y-full group-hover:opacity-100 group-hover:-bottom-1 transition-all">
|
||||||
Currently Live!
|
Currently Live!
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// VODs item component
|
// VODs item component
|
||||||
interface VodListItemProps extends BaseListItemProps, Omit<VodType, "type"> {}
|
interface VodListItemProps extends BaseListItemProps, Omit<VodType, "type"> {
|
||||||
|
variant?: string;
|
||||||
const VodListItem: React.FC<VodListItemProps> = ({
|
|
||||||
title,
|
|
||||||
streamer,
|
|
||||||
datetime,
|
|
||||||
category,
|
|
||||||
length,
|
|
||||||
views,
|
|
||||||
thumbnail,
|
|
||||||
url,
|
|
||||||
onItemClick,
|
|
||||||
extraClasses = "",
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<div className="p-4">
|
|
||||||
<div
|
|
||||||
className={`${extraClasses} overflow-hidden flex-shrink-0 flex flex-col bg-purple-900 rounded-lg cursor-pointer mx-auto hover:bg-purple-600 hover:scale-105 transition-all`}
|
|
||||||
onClick={() => window.open(url, "_blank")}
|
|
||||||
>
|
|
||||||
<div className="relative w-full aspect-video overflow-hidden rounded-t-lg">
|
|
||||||
{thumbnail ? (
|
|
||||||
<img
|
|
||||||
src={thumbnail}
|
|
||||||
alt={title}
|
|
||||||
className="absolute top-0 left-0 w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="p-3">
|
|
||||||
<h3 className="font-semibold text-lg text-center truncate max-w-full">
|
|
||||||
{title}
|
|
||||||
</h3>
|
|
||||||
<p className="font-bold">{streamer}</p>
|
|
||||||
<p className="text-sm text-gray-300">{category}</p>
|
|
||||||
<p className="text-sm text-gray-300">{new Date(datetime).toLocaleDateString()} | {length} mins</p>
|
|
||||||
<p className="text-sm text-gray-300">{views} views</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Legacy wrapper component for backward compatibility
|
|
||||||
export interface ListItemProps {
|
|
||||||
type: "stream" | "category" | "user";
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
username?: string;
|
|
||||||
streamCategory?: string;
|
|
||||||
viewers: number;
|
|
||||||
thumbnail?: string;
|
|
||||||
onItemClick?: () => void;
|
|
||||||
extraClasses?: string;
|
|
||||||
isLive?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { StreamListItem, CategoryListItem, UserListItem, VodListItem };
|
const VodListItem: React.FC<VodListItemProps> = ({
|
||||||
|
title,
|
||||||
|
username,
|
||||||
|
category_name,
|
||||||
|
views,
|
||||||
|
length,
|
||||||
|
datetime,
|
||||||
|
thumbnail,
|
||||||
|
onItemClick,
|
||||||
|
extraClasses = "",
|
||||||
|
variant,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<div className="p-4">
|
||||||
|
<div
|
||||||
|
className={`${extraClasses} overflow-hidden flex-shrink-0 flex flex-col bg-gray-900 rounded-lg cursor-pointer mx-auto hover:bg-gray-800 hover:scale-105 transition-all`}
|
||||||
|
onClick={onItemClick}
|
||||||
|
>
|
||||||
|
<div className="relative w-full aspect-video overflow-hidden rounded-t-lg">
|
||||||
|
{/* Thumbnail */}
|
||||||
|
<img src={thumbnail} alt={title} className="absolute top-0 left-0 w-full h-full object-cover" />
|
||||||
|
|
||||||
|
{/* Duration badge */}
|
||||||
|
<div className="absolute bottom-2 right-2 bg-black/80 text-white px-2 py-1 text-xs rounded">{length}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-3">
|
||||||
|
<h3 className="font-semibold text-lg text-white truncate max-w-full">{title}</h3>
|
||||||
|
<p className="text-sm text-gray-300">{username}</p>
|
||||||
|
<p className="text-sm text-gray-400">{category_name}</p>
|
||||||
|
<div className="flex justify-between items-center mt-2">
|
||||||
|
<p className="text-xs text-gray-500">{datetime}</p>
|
||||||
|
<p className="text-xs text-gray-500">{views} views</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{variant === "vodDashboard" && (
|
||||||
|
<div className="flex justify-evenly items-stretch rounded-b-lg">
|
||||||
|
<button
|
||||||
|
className="flex justify-around w-full h-full bg-black/50 hover:bg-black/80 p-2 mx-1 font-semibold rounded-full border border-transparent hover:border-white"
|
||||||
|
onClick={() => console.log("Publish")}
|
||||||
|
>
|
||||||
|
<UploadIcon />
|
||||||
|
Publish
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="flex justify-around w-full h-full bg-black/50 hover:bg-black/80 p-2 mx-1 font-semibold rounded-full border border-transparent hover:border-white"
|
||||||
|
onClick={() => console.log("Download")}
|
||||||
|
>
|
||||||
|
<DownloadIcon />
|
||||||
|
Download
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { StreamListItem, CategoryListItem, UserListItem, VodListItem };
|
||||||
|
|||||||
@@ -1,232 +1,201 @@
|
|||||||
import {
|
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
|
||||||
ArrowLeftIcon,
|
import React, { forwardRef, useImperativeHandle, useRef, useState } from "react";
|
||||||
ArrowRightIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
import React, {
|
|
||||||
forwardRef,
|
|
||||||
useImperativeHandle,
|
|
||||||
useRef,
|
|
||||||
useState,
|
|
||||||
} from "react";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import "../../assets/styles/listRow.css";
|
import "../../assets/styles/listRow.css";
|
||||||
import { StreamListItem, CategoryListItem, UserListItem, VodListItem } from "./ListItem";
|
import { StreamListItem, CategoryListItem, UserListItem, VodListItem } from "./ListItem";
|
||||||
import { StreamType } from "../../types/StreamType";
|
import { StreamType } from "../../types/StreamType";
|
||||||
import { CategoryType } from "../../types/CategoryType";
|
import { CategoryType } from "../../types/CategoryType";
|
||||||
import { UserType } from "../../types/UserType";
|
import { UserType } from "../../types/UserType";
|
||||||
import { VodType } from "../../types/VodType"
|
import { VodType } from "../../types/VodType";
|
||||||
|
|
||||||
type ItemType = StreamType | CategoryType | UserType | VodType;
|
type ItemType = StreamType | CategoryType | UserType | VodType;
|
||||||
|
|
||||||
interface ListRowProps {
|
interface ListRowProps {
|
||||||
variant?: "default" | "search";
|
variant?: "default" | "search" | "vodDashboard";
|
||||||
type: "stream" | "category" | "user" | "vod";
|
type: "stream" | "category" | "user" | "vod";
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
items: ItemType[];
|
items: ItemType[];
|
||||||
wrap?: boolean;
|
wrap?: boolean;
|
||||||
onItemClick: (itemName: string) => void;
|
onItemClick: (itemName: string) => void;
|
||||||
titleClickable?: boolean;
|
titleClickable?: boolean;
|
||||||
extraClasses?: string;
|
extraClasses?: string;
|
||||||
itemExtraClasses?: string;
|
itemExtraClasses?: string;
|
||||||
amountForScroll?: number;
|
amountForScroll?: number;
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ListRowRef {
|
interface ListRowRef {
|
||||||
addMoreItems: (newItems: ItemType[]) => void;
|
addMoreItems: (newItems: ItemType[]) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ListRow = forwardRef<ListRowRef, ListRowProps>((props, ref) => {
|
const ListRow = forwardRef<ListRowRef, ListRowProps>((props, ref) => {
|
||||||
const {
|
const {
|
||||||
variant = "default",
|
variant = "default",
|
||||||
type,
|
type,
|
||||||
title = "",
|
title = "",
|
||||||
description = "",
|
description = "",
|
||||||
items,
|
items,
|
||||||
onItemClick,
|
onItemClick,
|
||||||
titleClickable = false,
|
titleClickable = false,
|
||||||
wrap = false,
|
wrap = false,
|
||||||
extraClasses = "",
|
extraClasses = "",
|
||||||
itemExtraClasses = "",
|
itemExtraClasses = "",
|
||||||
amountForScroll = 4,
|
amountForScroll = 4,
|
||||||
children,
|
children,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const [currentItems, setCurrentItems] = useState<ItemType[]>(items);
|
|
||||||
const slider = useRef<HTMLDivElement>(null);
|
|
||||||
const scrollAmount = window.innerWidth * 0.3;
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const addMoreItems = (newItems: ItemType[]) => {
|
const [currentItems, setCurrentItems] = useState<ItemType[]>(items);
|
||||||
setCurrentItems((prevItems) => [...prevItems, ...newItems]);
|
const slider = useRef<HTMLDivElement>(null);
|
||||||
};
|
const scrollAmount = window.innerWidth * 0.3;
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
const addMoreItems = (newItems: ItemType[]) => {
|
||||||
addMoreItems,
|
setCurrentItems((prevItems) => [...prevItems, ...newItems]);
|
||||||
}));
|
};
|
||||||
|
|
||||||
const slideRight = () => {
|
useImperativeHandle(ref, () => ({
|
||||||
if (!wrap && slider.current) {
|
addMoreItems,
|
||||||
slider.current.scrollBy({ left: +scrollAmount, behavior: "smooth" });
|
}));
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const slideLeft = () => {
|
const slideRight = () => {
|
||||||
if (!wrap && slider.current) {
|
if (!wrap && slider.current) {
|
||||||
slider.current.scrollBy({ left: -scrollAmount, behavior: "smooth" });
|
slider.current.scrollBy({ left: +scrollAmount, behavior: "smooth" });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleTitleClick = () => {
|
const slideLeft = () => {
|
||||||
switch (type) {
|
if (!wrap && slider.current) {
|
||||||
case "stream":
|
slider.current.scrollBy({ left: -scrollAmount, behavior: "smooth" });
|
||||||
break;
|
}
|
||||||
case "category":
|
};
|
||||||
navigate("/categories");
|
|
||||||
break;
|
|
||||||
case "user":
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const isStreamType = (item: ItemType): item is StreamType =>
|
const handleTitleClick = () => {
|
||||||
item.type === "stream";
|
switch (type) {
|
||||||
|
case "stream":
|
||||||
const isCategoryType = (item: ItemType): item is CategoryType =>
|
break;
|
||||||
item.type === "category";
|
case "category":
|
||||||
|
navigate("/categories");
|
||||||
const isUserType = (item: ItemType): item is UserType =>
|
break;
|
||||||
item.type === "user";
|
case "user":
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const isVodType = (item: ItemType): item is VodType =>
|
const isStreamType = (item: ItemType): item is StreamType => item.type === "stream";
|
||||||
item.type === "vod";
|
|
||||||
|
|
||||||
return (
|
const isCategoryType = (item: ItemType): item is CategoryType => item.type === "category";
|
||||||
<div
|
|
||||||
className={`${extraClasses} flex relative rounded-[1.5rem] text-white transition-all ${
|
|
||||||
variant === "search"
|
|
||||||
? "items-center"
|
|
||||||
: "flex-col space-y-4 py-6 px-5 mx-2 mt-5"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{/* List Details */}
|
|
||||||
<div
|
|
||||||
className={`text-center ${
|
|
||||||
variant === "search" ? "min-w-fit px-auto w-[15vw]" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<h2
|
|
||||||
className={`${
|
|
||||||
titleClickable
|
|
||||||
? "cursor-pointer hover:underline"
|
|
||||||
: "cursor-default"
|
|
||||||
} text-2xl font-bold`}
|
|
||||||
onClick={titleClickable ? handleTitleClick : undefined}
|
|
||||||
>
|
|
||||||
{title}
|
|
||||||
</h2>
|
|
||||||
<p>{description}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* List Items */}
|
const isUserType = (item: ItemType): item is UserType => item.type === "user";
|
||||||
<div className="relative overflow-hidden flex flex-grow items-center z-0">
|
|
||||||
{!wrap && currentItems.length > amountForScroll && (
|
|
||||||
<>
|
|
||||||
<ArrowLeftIcon
|
|
||||||
onClick={slideLeft}
|
|
||||||
size={30}
|
|
||||||
className="absolute left-0 cursor-pointer z-[999]"
|
|
||||||
/>
|
|
||||||
<ArrowRightIcon
|
|
||||||
onClick={slideRight}
|
|
||||||
size={30}
|
|
||||||
className="absolute right-0 cursor-pointer z-[999]"
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div
|
const isVodType = (item: ItemType): item is VodType => item.type === "vod";
|
||||||
ref={slider}
|
|
||||||
className={`flex ${
|
return (
|
||||||
wrap ? "flex-wrap justify-between" : "overflow-x-scroll whitespace-nowrap"
|
<div
|
||||||
} max-w-[95%] items-center w-full mx-auto scroll-smooth scrollbar-hide`}
|
className={`${extraClasses} flex relative rounded-[1.5rem] text-white transition-all ${
|
||||||
>
|
variant === "search" ? "items-center" : "flex-col space-y-4 py-6 px-5 mx-2 mt-5"
|
||||||
{currentItems.length === 0 ? (
|
}`}
|
||||||
<h1 className="mx-auto">Nothing Found</h1>
|
>
|
||||||
) : (
|
{/* List Details */}
|
||||||
<>
|
<div className={`text-center ${variant === "search" ? "min-w-fit px-auto w-[15vw]" : ""}`}>
|
||||||
{currentItems.map((item) => {
|
<h2
|
||||||
if (type === "stream" && isStreamType(item)) {
|
className={`${titleClickable ? "cursor-pointer hover:underline" : "cursor-default"} text-2xl font-bold`}
|
||||||
return (
|
onClick={titleClickable ? handleTitleClick : undefined}
|
||||||
<StreamListItem
|
>
|
||||||
key={`stream-${item.id}`}
|
{title}
|
||||||
id={item.id}
|
</h2>
|
||||||
title={item.title}
|
<p>{description}</p>
|
||||||
username={item.username}
|
</div>
|
||||||
streamCategory={item.streamCategory}
|
|
||||||
viewers={item.viewers}
|
{/* List Items */}
|
||||||
thumbnail={item.thumbnail}
|
<div className="relative overflow-hidden flex flex-grow items-center z-0">
|
||||||
onItemClick={() => onItemClick(item.username)}
|
{!wrap && currentItems.length > amountForScroll && (
|
||||||
extraClasses={itemExtraClasses}
|
<>
|
||||||
/>
|
<ArrowLeftIcon onClick={slideLeft} size={30} className="absolute left-0 cursor-pointer z-[999]" />
|
||||||
);
|
<ArrowRightIcon onClick={slideRight} size={30} className="absolute right-0 cursor-pointer z-[999]" />
|
||||||
} else if (type === "category" && isCategoryType(item)) {
|
</>
|
||||||
return (
|
)}
|
||||||
<CategoryListItem
|
|
||||||
key={`category-${item.id}`}
|
<div
|
||||||
id={item.id}
|
ref={slider}
|
||||||
title={item.title}
|
className={`flex ${
|
||||||
viewers={item.viewers}
|
wrap ? "flex-wrap justify-between" : "overflow-x-scroll whitespace-nowrap"
|
||||||
thumbnail={item.thumbnail}
|
} max-w-[95%] items-center w-full mx-auto scroll-smooth scrollbar-hide`}
|
||||||
onItemClick={() => onItemClick(item.title)}
|
>
|
||||||
extraClasses={itemExtraClasses}
|
{currentItems.length === 0 ? (
|
||||||
/>
|
<h1 className="mx-auto">Nothing Found</h1>
|
||||||
);
|
) : (
|
||||||
} else if (type === "user" && isUserType(item)) {
|
<>
|
||||||
return (
|
{currentItems.map((item) => {
|
||||||
<UserListItem
|
if (type === "stream" && isStreamType(item)) {
|
||||||
key={`user-${item.id}`}
|
return (
|
||||||
id={item.id}
|
<StreamListItem
|
||||||
title={item.title}
|
key={`stream-${item.id}`}
|
||||||
username={item.username}
|
id={item.id}
|
||||||
isLive={item.isLive}
|
title={item.title}
|
||||||
viewers={item.viewers}
|
username={item.username}
|
||||||
thumbnail={item.thumbnail}
|
streamCategory={item.streamCategory}
|
||||||
onItemClick={() => onItemClick(item.username)}
|
viewers={item.viewers}
|
||||||
extraClasses={itemExtraClasses}
|
thumbnail={item.thumbnail}
|
||||||
/>
|
onItemClick={() => onItemClick(item.username)}
|
||||||
);
|
extraClasses={itemExtraClasses}
|
||||||
}
|
/>
|
||||||
else if (type === "vod" && isVodType(item)) {
|
);
|
||||||
return (
|
} else if (type === "category" && isCategoryType(item)) {
|
||||||
<VodListItem
|
return (
|
||||||
key={`vod-${item.id}`}
|
<CategoryListItem
|
||||||
id={item.id}
|
key={`category-${item.id}`}
|
||||||
title={item.title}
|
id={item.id}
|
||||||
streamer={item.streamer}
|
title={item.title}
|
||||||
datetime={item.datetime}
|
viewers={item.viewers}
|
||||||
category={item.category}
|
thumbnail={item.thumbnail}
|
||||||
length={item.length}
|
onItemClick={() => onItemClick(item.title)}
|
||||||
views={item.views}
|
extraClasses={itemExtraClasses}
|
||||||
url={item.url}
|
/>
|
||||||
thumbnail={item.thumbnail}
|
);
|
||||||
onItemClick={() => window.open(item.url, "_blank")}
|
} else if (type === "user" && isUserType(item)) {
|
||||||
extraClasses={itemExtraClasses}
|
return (
|
||||||
/>
|
<UserListItem
|
||||||
);
|
key={`user-${item.id}`}
|
||||||
}
|
id={item.id}
|
||||||
return null;
|
title={item.title}
|
||||||
})}
|
username={item.username}
|
||||||
</>
|
isLive={item.isLive}
|
||||||
)}
|
viewers={item.viewers}
|
||||||
</div>
|
thumbnail={item.thumbnail}
|
||||||
</div>
|
onItemClick={() => onItemClick(item.username)}
|
||||||
{children}
|
extraClasses={itemExtraClasses}
|
||||||
</div>
|
/>
|
||||||
);
|
);
|
||||||
|
} else if (type === "vod" && isVodType(item)) {
|
||||||
|
return (
|
||||||
|
<VodListItem
|
||||||
|
key={`vod-${item.vod_id}`}
|
||||||
|
vod_id={item.vod_id}
|
||||||
|
title={item.title}
|
||||||
|
username={item.username}
|
||||||
|
datetime={item.datetime}
|
||||||
|
category_name={item.category_name}
|
||||||
|
length={item.length}
|
||||||
|
views={item.views}
|
||||||
|
thumbnail={item.thumbnail}
|
||||||
|
onItemClick={() => onItemClick(item.vod_id.toString())}
|
||||||
|
extraClasses={itemExtraClasses}
|
||||||
|
variant={variant}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
export default ListRow;
|
export default ListRow;
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
import React, { useEffect } from "react";
|
import React, { useEffect } from "react";
|
||||||
import Logo from "../Layout/Logo";
|
import Logo from "../Layout/Logo";
|
||||||
import Button, { ToggleButton } from "../Input/Button";
|
import Button, { ToggleButton } from "../Input/Button";
|
||||||
import {
|
import { LogInIcon, LogOutIcon, SettingsIcon, Radio as LiveIcon } from "lucide-react";
|
||||||
LogInIcon,
|
|
||||||
LogOutIcon,
|
|
||||||
SettingsIcon,
|
|
||||||
Radio as LiveIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
import SearchBar from "../Input/SearchBar";
|
import SearchBar from "../Input/SearchBar";
|
||||||
import AuthModal from "../Auth/AuthModal";
|
import AuthModal from "../Auth/AuthModal";
|
||||||
import { useAuthModal } from "../../hooks/useAuthModal";
|
import { useAuthModal } from "../../hooks/useAuthModal";
|
||||||
@@ -17,113 +12,102 @@ import { useQuickSettings } from "../../context/QuickSettingsContext";
|
|||||||
import Sidebar from "./Sidebar";
|
import Sidebar from "./Sidebar";
|
||||||
|
|
||||||
interface NavbarProps {
|
interface NavbarProps {
|
||||||
variant?: "home" | "no-searchbar" | "default";
|
variant?: "home" | "no-searchbar" | "default";
|
||||||
}
|
}
|
||||||
|
|
||||||
const Navbar: React.FC<NavbarProps> = ({ variant = "default" }) => {
|
const Navbar: React.FC<NavbarProps> = ({ variant = "default" }) => {
|
||||||
const { isLoggedIn } = useAuth();
|
const { isLoggedIn } = useAuth();
|
||||||
const { showAuthModal, setShowAuthModal } = useAuthModal();
|
const { showAuthModal, setShowAuthModal } = useAuthModal();
|
||||||
const { showSideBar } = useSidebar();
|
const { showSideBar } = useSidebar();
|
||||||
const { showQuickSettings, setShowQuickSettings } = useQuickSettings();
|
const { showQuickSettings, setShowQuickSettings } = useQuickSettings();
|
||||||
const [justToggled, setJustToggled] = React.useState(false);
|
const [justToggled, setJustToggled] = React.useState(false);
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
console.log("Logging out...");
|
console.log("Logging out...");
|
||||||
fetch("/api/logout")
|
fetch("/api/logout")
|
||||||
.then((response) => response.json())
|
.then((response) => response.json())
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
console.log(data);
|
console.log(data);
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleQuickSettings = () => {
|
const handleQuickSettings = () => {
|
||||||
setShowQuickSettings(!showQuickSettings);
|
setShowQuickSettings(!showQuickSettings);
|
||||||
setJustToggled(true);
|
setJustToggled(true);
|
||||||
setTimeout(() => setJustToggled(false), 200);
|
setTimeout(() => setJustToggled(false), 200);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Keyboard shortcut to toggle sidebar
|
// Keyboard shortcut to toggle sidebar
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleKeyPress = (e: KeyboardEvent) => {
|
const handleKeyPress = (e: KeyboardEvent) => {
|
||||||
if (e.key === "q" && document.activeElement == document.body)
|
if (e.key === "q" && document.activeElement == document.body) handleQuickSettings();
|
||||||
handleQuickSettings();
|
};
|
||||||
};
|
|
||||||
|
|
||||||
document.addEventListener("keydown", handleKeyPress);
|
document.addEventListener("keydown", handleKeyPress);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener("keydown", handleKeyPress);
|
document.removeEventListener("keydown", handleKeyPress);
|
||||||
};
|
};
|
||||||
}, [showQuickSettings]);
|
}, [showQuickSettings]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
id="navbar"
|
id="navbar"
|
||||||
className={`relative flex justify-evenly items-center ${
|
className={`relative flex justify-evenly items-center ${variant === "home" ? "h-[45vh] flex-col" : "h-[15vh] col-span-2 flex-row"}`}
|
||||||
variant === "home"
|
>
|
||||||
? "h-[45vh] flex-col"
|
{isLoggedIn && window.innerWidth > 900 && <Sidebar />}
|
||||||
: "h-[15vh] col-span-2 flex-row"
|
<Logo extraClasses={variant != "home" && showSideBar && !window.location.pathname.includes("dashboard") ? "scale-0" : "duration-[3s]"} variant={variant} />
|
||||||
}`}
|
{/* Login / Logout Button */}
|
||||||
>
|
<Button
|
||||||
{isLoggedIn && window.innerWidth > 900 && <Sidebar />}
|
extraClasses={`absolute top-[2vh] ${
|
||||||
<Logo variant={variant} />
|
showSideBar ? "left-[16vw] duration-[0.5s]" : "left-[20px] duration-[1s]"
|
||||||
{/* Login / Logout Button */}
|
} text-[1rem] flex items-center flex-nowrap z-[99]`}
|
||||||
<Button
|
onClick={() => (isLoggedIn ? handleLogout() : setShowAuthModal(true))}
|
||||||
extraClasses={`absolute top-[2vh] ${
|
>
|
||||||
showSideBar
|
{isLoggedIn ? (
|
||||||
? "left-[16vw] duration-[0.5s]"
|
<>
|
||||||
: "left-[20px] duration-[1s]"
|
<LogOutIcon className="h-15 w-15 mr-1" />
|
||||||
} text-[1rem] flex items-center flex-nowrap z-[99]`}
|
Logout
|
||||||
onClick={() => (isLoggedIn ? handleLogout() : setShowAuthModal(true))}
|
</>
|
||||||
>
|
) : (
|
||||||
{isLoggedIn ? (
|
<>
|
||||||
<>
|
<LogInIcon className="h-15 w-15 mr-1" />
|
||||||
<LogOutIcon className="h-15 w-15 mr-1" />
|
Login / Register
|
||||||
Logout
|
</>
|
||||||
</>
|
)}
|
||||||
) : (
|
</Button>
|
||||||
<>
|
{/* Quick Settings Sidebar */}
|
||||||
<LogInIcon className="h-15 w-15 mr-1" />
|
<ToggleButton
|
||||||
Login / Register
|
extraClasses={`absolute group text-[1rem] top-[2vh] ${showQuickSettings ? "right-[21vw]" : "right-[20px]"} cursor-pointer z-[20]`}
|
||||||
</>
|
onClick={() => handleQuickSettings()}
|
||||||
)}
|
toggled={showQuickSettings}
|
||||||
</Button>
|
>
|
||||||
{/* Quick Settings Sidebar */}
|
<SettingsIcon className="h-[2vw] w-[2vw]" />
|
||||||
<ToggleButton
|
{!showQuickSettings && !justToggled && (
|
||||||
extraClasses={`absolute group text-[1rem] top-[2vh] ${
|
<small className="absolute flex items-center top-0 mr-2 right-0 h-full w-fit text-nowrap font-bold my-auto group-hover:right-full opacity-0 group-hover:opacity-100 group-hover:bg-black/30 p-1 rounded-md text-white transition-all">
|
||||||
showQuickSettings ? "right-[21vw]" : "right-[20px]"
|
Press Q
|
||||||
} cursor-pointer z-[20]`}
|
</small>
|
||||||
onClick={() => handleQuickSettings()}
|
)}
|
||||||
toggled={showQuickSettings}
|
</ToggleButton>
|
||||||
>
|
<QuickSettings />
|
||||||
<SettingsIcon className="h-[2vw] w-[2vw]" />
|
|
||||||
{!showQuickSettings && !justToggled && (
|
|
||||||
<small className="absolute flex items-center top-0 mr-2 right-0 h-full w-fit text-nowrap font-bold my-auto group-hover:right-full opacity-0 group-hover:opacity-100 group-hover:bg-black/30 p-1 rounded-md text-white transition-all">
|
|
||||||
Press Q
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
</ToggleButton>
|
|
||||||
<QuickSettings />
|
|
||||||
|
|
||||||
{variant != "no-searchbar" && <SearchBar />}
|
{variant != "no-searchbar" && <SearchBar />}
|
||||||
|
|
||||||
{/* Stream Button */}
|
{/* Stream Button */}
|
||||||
{isLoggedIn && !window.location.pathname.includes("go-live") && (
|
{isLoggedIn && !window.location.pathname.includes("dashboard") && (
|
||||||
<Button
|
<Button
|
||||||
extraClasses={`${
|
extraClasses={`${variant === "home" ? "absolute top-[2vh] right-[10vw]" : ""} flex flex-row items-center`}
|
||||||
variant === "home" ? "absolute top-[2vh] right-[10vw]" : ""
|
onClick={() => (window.location.href = "/dashboard")}
|
||||||
} flex flex-row items-center`}
|
>
|
||||||
onClick={() => (window.location.href = "/go-live")}
|
<LiveIcon className="h-15 w-15 mr-2" />
|
||||||
>
|
Stream Dashboard
|
||||||
<LiveIcon className="h-15 w-15 mr-2" />
|
</Button>
|
||||||
Go Live
|
)}
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />}
|
{showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Navbar;
|
export default Navbar;
|
||||||
|
|||||||
@@ -6,282 +6,247 @@ import { useAuthModal } from "../../hooks/useAuthModal";
|
|||||||
import { useAuth } from "../../context/AuthContext";
|
import { useAuth } from "../../context/AuthContext";
|
||||||
import { useSocket } from "../../context/SocketContext";
|
import { useSocket } from "../../context/SocketContext";
|
||||||
import { useChat } from "../../context/ChatContext";
|
import { useChat } from "../../context/ChatContext";
|
||||||
import {
|
import { ArrowLeftFromLineIcon, ArrowRightFromLineIcon, CrownIcon } from "lucide-react";
|
||||||
ArrowLeftFromLineIcon,
|
|
||||||
ArrowRightFromLineIcon,
|
|
||||||
CrownIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
chatter_username: string;
|
chatter_username: string;
|
||||||
message: string;
|
message: string;
|
||||||
time_sent: string;
|
time_sent: string;
|
||||||
is_subscribed: boolean;
|
is_subscribed: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ChatPanelProps {
|
interface ChatPanelProps {
|
||||||
streamId: number;
|
streamId: number;
|
||||||
onViewerCountChange?: (count: number) => void;
|
onViewerCountChange?: (count: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ChatPanel: React.FC<ChatPanelProps> = ({
|
const ChatPanel: React.FC<ChatPanelProps> = ({ streamId, onViewerCountChange }) => {
|
||||||
streamId,
|
const { isLoggedIn, username, userId } = useAuth();
|
||||||
onViewerCountChange,
|
const { showChat, setShowChat } = useChat();
|
||||||
}) => {
|
const { showAuthModal, setShowAuthModal } = useAuthModal();
|
||||||
const { isLoggedIn, username, userId } = useAuth();
|
const { socket, isConnected } = useSocket();
|
||||||
const { showChat, setShowChat } = useChat();
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
const { showAuthModal, setShowAuthModal } = useAuthModal();
|
const [inputMessage, setInputMessage] = useState("");
|
||||||
const { socket, isConnected } = useSocket();
|
const chatContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
const [justToggled, setJustToggled] = useState(false);
|
||||||
const [inputMessage, setInputMessage] = useState("");
|
|
||||||
const chatContainerRef = useRef<HTMLDivElement>(null);
|
|
||||||
const [justToggled, setJustToggled] = useState(false);
|
|
||||||
|
|
||||||
// Join chat room when component mounts
|
// Join chat room when component mounts
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (socket && isConnected) {
|
if (socket && isConnected) {
|
||||||
// Add username check
|
// Add username check
|
||||||
socket.emit("join", {
|
socket.emit("join", {
|
||||||
userId: userId ? userId : null,
|
userId: userId ? userId : null,
|
||||||
username: username ? username : "Guest",
|
username: username ? username : "Guest",
|
||||||
stream_id: streamId,
|
stream_id: streamId,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle beforeunload event
|
// Handle beforeunload event
|
||||||
const handleBeforeUnload = () => {
|
const handleBeforeUnload = () => {
|
||||||
socket.emit("leave", {
|
socket.emit("leave", {
|
||||||
userId: userId ? userId : null,
|
userId: userId ? userId : null,
|
||||||
username: username ? username : "Guest",
|
username: username ? username : "Guest",
|
||||||
stream_id: streamId,
|
stream_id: streamId,
|
||||||
});
|
});
|
||||||
socket.disconnect();
|
socket.disconnect();
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||||
|
|
||||||
// Load initial chat history
|
// Load initial chat history
|
||||||
fetch(`/api/chat/${streamId}`)
|
fetch(`/api/chat/${streamId}`)
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (!response.ok) throw new Error("Failed to fetch chat history");
|
if (!response.ok) throw new Error("Failed to fetch chat history");
|
||||||
return response.json();
|
return response.json();
|
||||||
})
|
})
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
if (data.chat_history) {
|
if (data.chat_history) {
|
||||||
setMessages(data.chat_history);
|
setMessages(data.chat_history);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error("Error loading chat history:", error);
|
console.error("Error loading chat history:", error);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle incoming messages
|
// Handle incoming messages
|
||||||
socket.on("new_message", (data: ChatMessage) => {
|
socket.on("new_message", (data: ChatMessage) => {
|
||||||
setMessages((prev) => [...prev, data]);
|
setMessages((prev) => [...prev, data]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle live viewership
|
// Handle live viewership
|
||||||
socket.on("status", (data: any) => {
|
socket.on("status", (data: any) => {
|
||||||
if (onViewerCountChange && data.num_viewers) {
|
if (onViewerCountChange && data.num_viewers) {
|
||||||
onViewerCountChange(data.num_viewers);
|
onViewerCountChange(data.num_viewers);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cleanup function
|
// Cleanup function
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener("beforeunload", handleBeforeUnload);
|
window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||||
socket.emit("leave", { stream_id: streamId });
|
socket.emit("leave", { stream_id: streamId });
|
||||||
socket.disconnect();
|
socket.disconnect();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}, [socket, isConnected, userId, username, streamId]);
|
}, [socket, isConnected, userId, username, 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.scrollTop = chatContainerRef.current.scrollHeight;
|
||||||
chatContainerRef.current.scrollHeight;
|
}
|
||||||
}
|
}, [messages]);
|
||||||
}, [messages]);
|
|
||||||
|
|
||||||
// Keyboard shortcut to toggle chat
|
// Keyboard shortcut to toggle chat
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleKeyPress = (e: KeyboardEvent) => {
|
const handleKeyPress = (e: KeyboardEvent) => {
|
||||||
if (e.key === "c" && document.activeElement == document.body) {
|
if (e.key === "c" && document.activeElement == document.body) {
|
||||||
toggleChat();
|
toggleChat();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
document.addEventListener("keydown", handleKeyPress);
|
document.addEventListener("keydown", handleKeyPress);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener("keydown", handleKeyPress);
|
document.removeEventListener("keydown", handleKeyPress);
|
||||||
};
|
};
|
||||||
}, [showChat]);
|
}, [showChat]);
|
||||||
|
|
||||||
const toggleChat = () => {
|
const toggleChat = () => {
|
||||||
setShowChat(!showChat);
|
setShowChat(!showChat);
|
||||||
setJustToggled(true);
|
setJustToggled(true);
|
||||||
setTimeout(() => setJustToggled(false), 200);
|
setTimeout(() => setJustToggled(false), 200);
|
||||||
};
|
};
|
||||||
|
|
||||||
const sendChat = () => {
|
const sendChat = () => {
|
||||||
if (!inputMessage.trim() || !socket || !isConnected) {
|
if (!inputMessage.trim() || !socket || !isConnected) {
|
||||||
console.log("Invalid message or socket not connected");
|
console.log("Invalid message or socket not connected");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.emit("send_message", {
|
socket.emit("send_message", {
|
||||||
username: username,
|
username: username,
|
||||||
stream_id: streamId,
|
stream_id: streamId,
|
||||||
message: inputMessage.trim(),
|
message: inputMessage.trim(),
|
||||||
});
|
});
|
||||||
|
|
||||||
setInputMessage("");
|
setInputMessage("");
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||||
if (e.key === "Enter" && !e.shiftKey) {
|
if (e.key === "Enter" && !e.shiftKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
sendChat();
|
sendChat();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
id="chat-panel"
|
id="chat-panel"
|
||||||
className="relative max-w-[30vw] max-h-[83vh] flex flex-col rounded-lg p-[2vh] justify-between"
|
className="relative max-w-[30vw] max-h-[83vh] flex flex-col rounded-lg p-[2vh] justify-between"
|
||||||
style={{ gridArea: "1 / 2 / 3 / 3" }}
|
style={{ gridArea: "1 / 2 / 3 / 3" }}
|
||||||
>
|
>
|
||||||
{/* Toggle Button for Chat */}
|
{/* Toggle Button for Chat */}
|
||||||
<button
|
<button
|
||||||
onClick={toggleChat}
|
onClick={toggleChat}
|
||||||
className={`group cursor-pointer p-2 hover:bg-gray-800 rounded-md absolute top-[1vh] left-[1vw] ${
|
className={`group cursor-pointer p-2 hover:bg-gray-800 rounded-md absolute top-[1vh] left-[1vw] ${
|
||||||
showChat ? "" : "delay-[0.75s] -translate-x-[4vw]"
|
showChat ? "" : "delay-[0.75s] -translate-x-[4vw]"
|
||||||
} text-[1rem] text-purple-500 flex items-center flex-nowrap z-[20] duration-[0.3s] transition-all`}
|
} text-[1rem] text-purple-500 flex items-center flex-nowrap z-[20] duration-[0.3s] transition-all`}
|
||||||
>
|
>
|
||||||
{showChat ? <ArrowRightFromLineIcon /> : <ArrowLeftFromLineIcon />}
|
{showChat ? <ArrowRightFromLineIcon /> : <ArrowLeftFromLineIcon />}
|
||||||
|
|
||||||
<small
|
<small
|
||||||
className={`absolute ${
|
className={`absolute ${
|
||||||
showChat
|
showChat
|
||||||
? justToggled
|
? justToggled
|
||||||
? "left-0 group-hover:-left-[5vw] group-hover:bg-white/10"
|
? "left-0 group-hover:-left-[5vw] group-hover:bg-white/10"
|
||||||
: "right-0 group-hover:-right-[5vw] group-hover:bg-red-500/80"
|
: "right-0 group-hover:-right-[5vw] group-hover:bg-red-500/80"
|
||||||
: justToggled
|
: justToggled
|
||||||
? "right-0 group-hover:-right-[5vw] group-hover:bg-red-500/80"
|
? "right-0 group-hover:-right-[5vw] group-hover:bg-red-500/80"
|
||||||
: "left-0 group-hover:-left-[5vw] group-hover:bg-white/10"
|
: "left-0 group-hover:-left-[5vw] group-hover:bg-white/10"
|
||||||
} p-1 rounded-md w-fit text-nowrap font-bold opacity-0 group-hover:opacity-100 text-white transition-all`}
|
} p-1 rounded-md w-fit text-nowrap font-bold opacity-0 group-hover:opacity-100 text-white transition-all`}
|
||||||
>
|
>
|
||||||
Press C
|
Press C
|
||||||
</small>
|
</small>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Chat Header */}
|
{/* Chat Header */}
|
||||||
<h2 className="cursor-default text-xl font-bold mb-4 text-white text-center flex-none">
|
<h2 className="cursor-default text-xl font-bold mb-4 text-white text-center flex-none">Stream Chat</h2>
|
||||||
Stream Chat
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
{/* Message List */}
|
{/* Message List */}
|
||||||
<div
|
<div ref={chatContainerRef} id="chat-message-list" className="w-full h-full overflow-y-auto mb-4 space-y-2 rounded-md">
|
||||||
ref={chatContainerRef}
|
{messages.map((msg, index) => (
|
||||||
id="chat-message-list"
|
<div key={index} className="flex items-start space-x-2 bg-gray-800 rounded p-2 text-white relative">
|
||||||
className="w-full h-full overflow-y-auto mb-4 space-y-2 rounded-md"
|
{/* User avatar with image */}
|
||||||
>
|
<div
|
||||||
{messages.map((msg, index) => (
|
className={`w-2em h-2em rounded-full overflow-hidden flex-shrink-0 ${
|
||||||
<div
|
msg.chatter_username === username ? "" : "cursor-pointer"
|
||||||
key={index}
|
}`}
|
||||||
className="flex items-start space-x-2 bg-gray-800 rounded p-2 text-white relative"
|
onClick={() => (msg.chatter_username === username ? null : (window.location.href = `/user/${msg.chatter_username}`))}
|
||||||
>
|
>
|
||||||
{/* User avatar with image */}
|
<img
|
||||||
<div
|
|
||||||
className={`w-2em h-2em rounded-full overflow-hidden flex-shrink-0 ${
|
|
||||||
msg.chatter_username === username ? "" : "cursor-pointer"
|
|
||||||
}`}
|
|
||||||
onClick={() =>
|
|
||||||
msg.chatter_username === username
|
|
||||||
? null
|
|
||||||
: (window.location.href = `/user/${msg.chatter_username}`)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src="/images/monkey.png"
|
src="/images/monkey.png"
|
||||||
alt="User Avatar"
|
alt="User Avatar"
|
||||||
className="w-full h-full object-cover"
|
className="w-full h-full object-cover"
|
||||||
style={{ width: "2.5em", height: "2.5em" }}
|
style={{ width: "2.5em", height: "2.5em" }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex-grow overflow-hidden">
|
<div className="flex-grow overflow-hidden">
|
||||||
<div className="flex items-center space-x-0.5em">
|
<div className="flex items-center space-x-0.5em">
|
||||||
{/* Username */}
|
{/* Username */}
|
||||||
<span
|
<span
|
||||||
className={`flex items-center gap-2 font-bold text-[1em] ${
|
className={`flex items-center gap-2 font-bold text-[1em] ${
|
||||||
msg.chatter_username === username
|
msg.chatter_username === username ? "text-purple-600" : "text-green-400 cursor-pointer"
|
||||||
? "text-purple-600"
|
}`}
|
||||||
: "text-green-400 cursor-pointer"
|
onClick={() => (msg.chatter_username === username ? null : (window.location.href = `/user/${msg.chatter_username}`))}
|
||||||
}`}
|
>
|
||||||
onClick={() =>
|
{msg.chatter_username}
|
||||||
msg.chatter_username === username
|
{msg.is_subscribed && <CrownIcon size={20} color="gold" />}
|
||||||
? null
|
</span>
|
||||||
: (window.location.href = `/user/${msg.chatter_username}`)
|
</div>
|
||||||
}
|
{/* Message content */}
|
||||||
>
|
<div className="message w-full text-[0.9em] mt-0.5em flex flex-col overflow-hidden">{msg.message}</div>
|
||||||
{msg.chatter_username}
|
</div>
|
||||||
{msg.is_subscribed && <CrownIcon size={20} color="gold" />}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
{/* Message content */}
|
|
||||||
<div className="message w-full text-[0.9em] mt-0.5em flex flex-col overflow-hidden">
|
|
||||||
{msg.message}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Time sent */}
|
{/* Time sent */}
|
||||||
<div className="text-gray-500 text-[0.8em] absolute top-0 right-0 p-2">
|
<div className="text-gray-500 text-[0.8em] absolute top-0 right-0 p-2">
|
||||||
{new Date(msg.time_sent).toLocaleTimeString("en-GB", {
|
{new Date(msg.time_sent).toLocaleTimeString("en-GB", {
|
||||||
hour12: false,
|
hour12: false,
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Input area */}
|
{/* Input area */}
|
||||||
<div className="flex-none flex justify-center gap-2">
|
<div className="flex-none flex justify-center gap-2">
|
||||||
{isLoggedIn ? (
|
{isLoggedIn ? (
|
||||||
<>
|
<>
|
||||||
<Input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
value={inputMessage}
|
value={inputMessage}
|
||||||
onChange={(e) => setInputMessage(e.target.value)}
|
onChange={(e) => setInputMessage(e.target.value)}
|
||||||
onKeyDown={handleKeyPress}
|
onKeyDown={handleKeyPress}
|
||||||
placeholder="Type a message..."
|
placeholder="Type a message..."
|
||||||
extraClasses="flex-grow w-full focus:w-full"
|
extraClasses="flex-grow w-full focus:w-full"
|
||||||
maxLength={200}
|
maxLength={200}
|
||||||
onClick={() => !isLoggedIn && setShowAuthModal(true)}
|
onClick={() => !isLoggedIn && setShowAuthModal(true)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<button
|
<button onClick={sendChat} className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
|
||||||
onClick={sendChat}
|
Send
|
||||||
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
|
</button>
|
||||||
>
|
</>
|
||||||
Send
|
) : (
|
||||||
</button>
|
<Button extraClasses="text-[1rem] flex items-center flex-nowrap" onClick={() => setShowAuthModal(true)}>
|
||||||
</>
|
Login to Chat
|
||||||
) : (
|
</Button>
|
||||||
<Button
|
)}
|
||||||
extraClasses="text-[1rem] flex items-center flex-nowrap"
|
</div>
|
||||||
onClick={() => setShowAuthModal(true)}
|
{showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />}
|
||||||
>
|
</div>
|
||||||
Login to Chat
|
);
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{showAuthModal && <AuthModal onClose={() => setShowAuthModal(false)} />}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ChatPanel;
|
export default ChatPanel;
|
||||||
|
|||||||
389
frontend/src/components/Stream/StreamDashboard.tsx
Normal file
389
frontend/src/components/Stream/StreamDashboard.tsx
Normal file
@@ -0,0 +1,389 @@
|
|||||||
|
import React, { useState, useEffect } from "react";
|
||||||
|
import Button from "../../components/Input/Button";
|
||||||
|
import Input from "../../components/Input/Input";
|
||||||
|
import { useCategories } from "../../hooks/useContent";
|
||||||
|
import { X as CloseIcon, Eye as ShowIcon, EyeOff as HideIcon } from "lucide-react";
|
||||||
|
import { debounce } from "lodash";
|
||||||
|
import VideoPlayer from "../../components/Stream/VideoPlayer";
|
||||||
|
import { CategoryType } from "../../types/CategoryType";
|
||||||
|
import { StreamListItem } from "../../components/Layout/ListItem";
|
||||||
|
import { getCategoryThumbnail } from "../../utils/thumbnailUtils";
|
||||||
|
|
||||||
|
interface StreamData {
|
||||||
|
title: string;
|
||||||
|
category_name: string;
|
||||||
|
viewer_count: number;
|
||||||
|
start_time: string;
|
||||||
|
stream_key: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StreamDashboardProps {
|
||||||
|
username: string;
|
||||||
|
userId: number;
|
||||||
|
isLive: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const StreamDashboard: React.FC<StreamDashboardProps> = ({ username, userId, isLive }) => {
|
||||||
|
const [streamData, setStreamData] = useState<StreamData>({
|
||||||
|
title: "",
|
||||||
|
category_name: "",
|
||||||
|
viewer_count: 0,
|
||||||
|
start_time: "",
|
||||||
|
stream_key: "",
|
||||||
|
});
|
||||||
|
const [timeStarted, setTimeStarted] = useState("");
|
||||||
|
const [streamDetected, setStreamDetected] = useState(false);
|
||||||
|
const [isCategoryFocused, setIsCategoryFocused] = useState(false);
|
||||||
|
const [filteredCategories, setFilteredCategories] = useState<CategoryType[]>([]);
|
||||||
|
const [thumbnail, setThumbnail] = useState<File | null>(null);
|
||||||
|
const [thumbnailPreview, setThumbnailPreview] = useState<{
|
||||||
|
url: string;
|
||||||
|
isCustom: boolean;
|
||||||
|
}>({ url: "", isCustom: false });
|
||||||
|
const [debouncedCheck, setDebouncedCheck] = useState<Function | null>(null);
|
||||||
|
const [showKey, setShowKey] = useState(false);
|
||||||
|
|
||||||
|
const { categories } = useCategories("/api/categories/popular/100");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Set filtered categories when categories load
|
||||||
|
if (categories.length > 0) {
|
||||||
|
setFilteredCategories(categories);
|
||||||
|
}
|
||||||
|
}, [categories]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const categoryCheck = debounce((categoryName: string) => {
|
||||||
|
const isValidCategory = categories.some((cat: CategoryType) => cat.title.toLowerCase() === categoryName.toLowerCase());
|
||||||
|
|
||||||
|
if (isValidCategory && !thumbnailPreview.isCustom) {
|
||||||
|
const defaultThumbnail = getCategoryThumbnail(categoryName);
|
||||||
|
setThumbnailPreview({ url: defaultThumbnail, isCustom: false });
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
setDebouncedCheck(() => categoryCheck);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
categoryCheck.cancel();
|
||||||
|
};
|
||||||
|
}, [categories, thumbnailPreview.isCustom]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (username) {
|
||||||
|
checkStreamStatus();
|
||||||
|
}
|
||||||
|
}, [username]);
|
||||||
|
|
||||||
|
const checkStreamStatus = async () => {
|
||||||
|
try {
|
||||||
|
if (isLive) {
|
||||||
|
const streamResponse = await fetch(`/api/streams/${userId}/data`, { credentials: "include" });
|
||||||
|
const streamData = await streamResponse.json();
|
||||||
|
setStreamData({
|
||||||
|
title: streamData.title,
|
||||||
|
category_name: streamData.category_name,
|
||||||
|
viewer_count: streamData.num_viewers,
|
||||||
|
start_time: streamData.start_time,
|
||||||
|
stream_key: streamData.stream_key,
|
||||||
|
});
|
||||||
|
|
||||||
|
const time = Math.floor(
|
||||||
|
(Date.now() - new Date(streamData.start_time).getTime()) / 60000 // Convert to minutes
|
||||||
|
);
|
||||||
|
|
||||||
|
if (time < 60) setTimeStarted(`${time}m ago`);
|
||||||
|
else if (time < 1440) setTimeStarted(`${Math.floor(time / 60)}h ${time % 60}m ago`);
|
||||||
|
else setTimeStarted(`${Math.floor(time / 1440)}d ${Math.floor((time % 1440) / 60)}h ${time % 60}m ago`);
|
||||||
|
} else {
|
||||||
|
// Just need the stream key if not streaming
|
||||||
|
const response = await fetch(`/api/user/${username}/stream_key`, { credentials: "include" });
|
||||||
|
const keyData = await response.json();
|
||||||
|
setStreamData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
stream_key: keyData.stream_key,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error checking stream status:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setStreamData((prev) => ({ ...prev, [name]: value }));
|
||||||
|
|
||||||
|
if (name === "category_name") {
|
||||||
|
const filtered = categories.filter((cat: CategoryType) => cat.title.toLowerCase().includes(value.toLowerCase()));
|
||||||
|
setFilteredCategories(filtered);
|
||||||
|
if (debouncedCheck) {
|
||||||
|
debouncedCheck(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCategorySelect = (categoryName: string) => {
|
||||||
|
console.log("Selected category:", categoryName);
|
||||||
|
setStreamData((prev) => ({ ...prev, category_name: categoryName }));
|
||||||
|
setFilteredCategories([]);
|
||||||
|
if (debouncedCheck) {
|
||||||
|
debouncedCheck(categoryName);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleThumbnailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
if (e.target.files && e.target.files[0]) {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
setThumbnail(file);
|
||||||
|
setThumbnailPreview({
|
||||||
|
url: URL.createObjectURL(file),
|
||||||
|
isCustom: true,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setThumbnail(null);
|
||||||
|
if (streamData.category_name && debouncedCheck) {
|
||||||
|
debouncedCheck(streamData.category_name);
|
||||||
|
} else {
|
||||||
|
setThumbnailPreview({ url: "", isCustom: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearThumbnail = () => {
|
||||||
|
setThumbnail(null);
|
||||||
|
if (streamData.category_name) {
|
||||||
|
console.log("Clearing thumbnail as category is set and default category thumbnail will be used");
|
||||||
|
const defaultThumbnail = getCategoryThumbnail(streamData.category_name);
|
||||||
|
setThumbnailPreview({ url: defaultThumbnail, isCustom: false });
|
||||||
|
} else {
|
||||||
|
setThumbnailPreview({ url: "", isCustom: false });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isFormValid = () => {
|
||||||
|
return (
|
||||||
|
streamData.title.trim() !== "" &&
|
||||||
|
streamData.category_name.trim() !== "" &&
|
||||||
|
categories.some((cat: CategoryType) => cat.title.toLowerCase() === streamData.category_name.toLowerCase()) &&
|
||||||
|
streamDetected
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePublishStream = async () => {
|
||||||
|
console.log("Starting stream with data:", streamData);
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("data", JSON.stringify(streamData));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/publish_stream", {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
console.log("Stream published successfully");
|
||||||
|
window.location.reload();
|
||||||
|
} else if (response.status === 403) {
|
||||||
|
console.error("Unauthorized - Invalid stream key or already streaming");
|
||||||
|
} else {
|
||||||
|
console.error("Failed to publish stream");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error publishing stream:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUpdateStream = async () => {
|
||||||
|
console.log("Updating stream with data:", streamData);
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("key", streamData.stream_key);
|
||||||
|
formData.append("title", streamData.title);
|
||||||
|
formData.append("category_name", streamData.category_name);
|
||||||
|
if (thumbnail) {
|
||||||
|
formData.append("thumbnail", thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/update_stream", {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
console.log("Stream updated successfully");
|
||||||
|
window.location.reload();
|
||||||
|
} else {
|
||||||
|
console.error("Failed to update stream");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating stream:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEndStream = async () => {
|
||||||
|
console.log("Ending stream...");
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("key", streamData.stream_key);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/end_stream", {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
console.log("Stream ended successfully");
|
||||||
|
window.location.reload();
|
||||||
|
} else {
|
||||||
|
console.error("Failed to end stream");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error ending stream:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col flex-grow mx-auto px-4">
|
||||||
|
<div className="flex flex-grow gap-8 items-stretch pb-4">
|
||||||
|
{/* Left side - Stream Settings */}
|
||||||
|
<div className="flex flex-col flex-grow">
|
||||||
|
<h2 className="text-center text-2xl font-bold text-white mb-4">Stream Settings</h2>
|
||||||
|
<div className="flex flex-col flex-grow justify-evenly space-y-6 bg-gray-800 rounded-lg p-6 shadow-xl">
|
||||||
|
<div>
|
||||||
|
<label className="block text-white mb-2">Stream Title</label>
|
||||||
|
<Input
|
||||||
|
name="title"
|
||||||
|
value={streamData.title}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
placeholder="Enter your stream title"
|
||||||
|
extraClasses="w-[70%] focus:w-[70%]"
|
||||||
|
maxLength={50}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<label className="block text-white mb-2">Category</label>
|
||||||
|
<Input
|
||||||
|
name="category_name"
|
||||||
|
value={streamData.category_name}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
onFocus={() => setIsCategoryFocused(true)}
|
||||||
|
onBlur={() => setTimeout(() => setIsCategoryFocused(false), 200)}
|
||||||
|
placeholder="Select or type a category"
|
||||||
|
extraClasses="w-[70%] focus:w-[70%]"
|
||||||
|
maxLength={50}
|
||||||
|
autoComplete="off"
|
||||||
|
type="search"
|
||||||
|
/>
|
||||||
|
{isCategoryFocused && filteredCategories.length > 0 && (
|
||||||
|
<div className="absolute z-10 w-full bg-gray-700 mt-1 rounded-md shadow-lg max-h-48 overflow-y-auto">
|
||||||
|
{filteredCategories.map((category) => (
|
||||||
|
<div
|
||||||
|
key={category.title}
|
||||||
|
className="px-4 py-2 hover:bg-gray-600 cursor-pointer text-white"
|
||||||
|
onClick={() => handleCategorySelect(category.title)}
|
||||||
|
>
|
||||||
|
{category.title}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-white mb-2">Stream Thumbnail</label>
|
||||||
|
<div className="relative flex flex-row items-center justify-center">
|
||||||
|
<input type="file" accept="image/*" onChange={handleThumbnailChange} className="hidden" id="thumbnail-upload" />
|
||||||
|
<label
|
||||||
|
htmlFor="thumbnail-upload"
|
||||||
|
className="cursor-pointer inline-block bg-gray-700 hover:bg-gray-600 text-white py-2 px-4 rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
{thumbnail ? "Change Thumbnail" : "Choose Thumbnail"}
|
||||||
|
</label>
|
||||||
|
<span className="ml-3 text-gray-400">{thumbnail ? thumbnail.name : "No file selected"}</span>
|
||||||
|
{thumbnailPreview.isCustom && (
|
||||||
|
<button
|
||||||
|
onClick={clearThumbnail}
|
||||||
|
className="absolute right-0 top-0 p-1 bg-red-500 rounded-full hover:bg-red-600 transition-colors"
|
||||||
|
>
|
||||||
|
<CloseIcon size={16} className="text-white" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{!thumbnailPreview.isCustom && (
|
||||||
|
<p className="text-gray-400 mt-2 text-sm text-center">No thumbnail selected - the default category image will be used</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLive && (
|
||||||
|
<div className="bg-gray-700 p-4 rounded-lg">
|
||||||
|
<h3 className="text-white font-semibold mb-2">Stream Info</h3>
|
||||||
|
<p className="text-gray-300">Viewers: {streamData.viewer_count}</p>
|
||||||
|
<p className="text-gray-300">
|
||||||
|
Started: {new Date(streamData.start_time!).toLocaleTimeString()}
|
||||||
|
{` (${timeStarted})`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center mx-auto p-10 bg-gray-900 w-fit rounded-xl py-4">
|
||||||
|
<label className="block text-white mr-8">Stream Key</label>
|
||||||
|
<Input type={showKey ? "text" : "password"} value={streamData.stream_key} readOnly extraClasses="w-fit pr-[30px]" disabled />
|
||||||
|
<button type="button" onClick={() => setShowKey(!showKey)} className="-translate-x-[30px] top-1/2 h-6 w-6 text-white">
|
||||||
|
{showKey ? <HideIcon className="h-6 w-6" /> : <ShowIcon className="h-6 w-6" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col w-fit mx-auto items-center justify-center pt-6 gap-6">
|
||||||
|
<div className="flex gap-8">
|
||||||
|
<Button
|
||||||
|
onClick={isLive ? handleUpdateStream : handlePublishStream}
|
||||||
|
disabled={!isFormValid()}
|
||||||
|
extraClasses="text-2xl px-8 py-4 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{isLive ? "Update Stream" : "Start Streaming"}
|
||||||
|
</Button>
|
||||||
|
{isLive && (
|
||||||
|
<Button onClick={handleEndStream} extraClasses="text-2xl px-8 py-4 hover:text-red-500 hover:border-red-500">
|
||||||
|
End Stream
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{!streamDetected && (
|
||||||
|
<p className="text-red-500 text-sm">No stream input detected. Please start streaming using your broadcast software.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right side - Preview */}
|
||||||
|
<div className="w-[25vw] flex flex-col">
|
||||||
|
<h2 className="text-center text-2xl font-bold text-white mb-4">Stream Preview</h2>
|
||||||
|
<div className="flex flex-col gap-4 bg-gray-800 rounded-lg p-4 w-full h-fit flex-grow justify-around">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<p className="text-white text-center pb-4">Video</p>
|
||||||
|
<VideoPlayer streamer={username ?? undefined} extraClasses="border border-white" onStreamDetected={setStreamDetected} />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<p className="text-white text-center">List Item</p>
|
||||||
|
<StreamListItem
|
||||||
|
id={1}
|
||||||
|
title={streamData.title || "Stream Title"}
|
||||||
|
username={username || ""}
|
||||||
|
streamCategory={streamData.category_name || "Category"}
|
||||||
|
viewers={streamData.viewer_count}
|
||||||
|
thumbnail={thumbnailPreview.url || ""}
|
||||||
|
onItemClick={() => {}}
|
||||||
|
extraClasses="max-w-[20vw]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default StreamDashboard;
|
||||||
37
frontend/src/components/Stream/VodsDashboard.tsx
Normal file
37
frontend/src/components/Stream/VodsDashboard.tsx
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import React from "react";
|
||||||
|
import ListRow from "../Layout/ListRow";
|
||||||
|
import { VodType } from "../../types/VodType";
|
||||||
|
|
||||||
|
interface VodsDashboardProps {
|
||||||
|
vods: VodType[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const VodsDashboard: React.FC<VodsDashboardProps> = ({ vods }) => {
|
||||||
|
const handleVodClick = (vodUrl: string) => {
|
||||||
|
window.open(vodUrl, "_blank");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="w-full">
|
||||||
|
<h2 className="text-3xl font-bold text-white mb-6">Past Broadcasts</h2>
|
||||||
|
|
||||||
|
{vods.length === 0 ? (
|
||||||
|
<div className="text-center text-gray-400 py-8">
|
||||||
|
<p>No past broadcasts found</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ListRow
|
||||||
|
type="vod"
|
||||||
|
variant="vodDashboard"
|
||||||
|
items={vods}
|
||||||
|
wrap={false}
|
||||||
|
onItemClick={handleVodClick}
|
||||||
|
extraClasses="bg-black/50"
|
||||||
|
itemExtraClasses="w-[20vw]"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default VodsDashboard;
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
import { createContext, useContext } from "react";
|
import { createContext, useContext } from "react";
|
||||||
|
|
||||||
interface AuthContextType {
|
interface AuthContextType {
|
||||||
isLoggedIn: boolean;
|
isLoggedIn: boolean;
|
||||||
username: string | null;
|
username: string | null;
|
||||||
userId: number | null;
|
userId: number | null;
|
||||||
setIsLoggedIn: (value: boolean) => void;
|
isLive: boolean;
|
||||||
setUsername: (value: string | null) => void;
|
setIsLoggedIn: (value: boolean) => void;
|
||||||
setUserId: (value: number | null) => void;
|
setUsername: (value: string | null) => void;
|
||||||
|
setUserId: (value: number | null) => void;
|
||||||
|
setIsLive: (value: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AuthContext = createContext<AuthContextType | undefined>(
|
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||||
undefined
|
|
||||||
);
|
|
||||||
|
|
||||||
export function useAuth() {
|
export function useAuth() {
|
||||||
const context = useContext(AuthContext);
|
const context = useContext(AuthContext);
|
||||||
if (context === undefined) {
|
if (context === undefined) {
|
||||||
throw new Error("useAuth must be used within an AuthProvider");
|
throw new Error("useAuth must be used within an AuthProvider");
|
||||||
}
|
}
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,173 +4,160 @@ import { useAuth } from "../context/AuthContext";
|
|||||||
import { StreamType } from "../types/StreamType";
|
import { StreamType } from "../types/StreamType";
|
||||||
import { CategoryType } from "../types/CategoryType";
|
import { CategoryType } from "../types/CategoryType";
|
||||||
import { UserType } from "../types/UserType";
|
import { UserType } from "../types/UserType";
|
||||||
import { VodType } from "../types/VodType"
|
import { VodType } from "../types/VodType";
|
||||||
import { getCategoryThumbnail } from "../utils/thumbnailUtils";
|
import { getCategoryThumbnail } from "../utils/thumbnailUtils";
|
||||||
|
|
||||||
// Process API data into our VodType structure
|
|
||||||
const processVodData = (data: any[]): VodType[] => {
|
const processVodData = (data: any[]): VodType[] => {
|
||||||
|
return data.map((vod) => ({
|
||||||
return data.map((vod) => ({
|
type: "vod",
|
||||||
type: "vod",
|
vod_id: vod.vod_id,
|
||||||
id: vod.id, // Ensure this matches API response
|
title: vod.title,
|
||||||
title: vod.title,
|
username: vod.username,
|
||||||
streamer: vod.streamer, // Ensure backend sends streamer name or ID
|
datetime: formatDate(vod.datetime),
|
||||||
datetime: new Date(vod.datetime).toLocaleString(),
|
category_name: vod.category_name,
|
||||||
category: vod.category,
|
length: formatDuration(vod.length),
|
||||||
length: vod.length,
|
views: vod.views,
|
||||||
views: vod.views,
|
thumbnail: vod.thumbnail, //TODO
|
||||||
url: vod.url,
|
}));
|
||||||
thumbnail: "../../images/category_thumbnails/abstract.webp",
|
|
||||||
}));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Helper function to process API data into our consistent types
|
// Helper function to process API data into our consistent types
|
||||||
const processStreamData = (data: any[]): StreamType[] => {
|
const processStreamData = (data: any[]): StreamType[] => {
|
||||||
return data.map((stream) => ({
|
return data.map((stream) => ({
|
||||||
type: "stream",
|
type: "stream",
|
||||||
id: stream.user_id,
|
id: stream.user_id,
|
||||||
title: stream.title,
|
title: stream.title,
|
||||||
username: stream.username,
|
username: stream.username,
|
||||||
streamCategory: stream.category_name,
|
streamCategory: stream.category_name,
|
||||||
viewers: stream.num_viewers,
|
viewers: stream.num_viewers,
|
||||||
thumbnail: getCategoryThumbnail(stream.category_name, stream.thumbnail),
|
thumbnail: getCategoryThumbnail(stream.category_name, stream.thumbnail),
|
||||||
}))
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
const processCategoryData = (data: any[]): CategoryType[] => {
|
const processCategoryData = (data: any[]): CategoryType[] => {
|
||||||
console.log("Raw API VOD Data:", data); // Debugging
|
return data.map((category) => ({
|
||||||
return data.map((category) => ({
|
type: "category",
|
||||||
type: "category",
|
id: category.category_id,
|
||||||
id: category.category_id,
|
title: category.category_name,
|
||||||
title: category.category_name,
|
viewers: category.num_viewers,
|
||||||
viewers: category.num_viewers,
|
thumbnail: getCategoryThumbnail(category.category_name),
|
||||||
thumbnail: getCategoryThumbnail(category.category_name)
|
}));
|
||||||
}));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const processUserData = (data: any[]): UserType[] => {
|
const processUserData = (data: any[]): UserType[] => {
|
||||||
return data.map((user) => ({
|
return data.map((user) => ({
|
||||||
type: "user",
|
type: "user",
|
||||||
id: user.user_id,
|
id: user.user_id,
|
||||||
title: user.username,
|
title: user.username,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
isLive: user.is_live,
|
isLive: user.is_live,
|
||||||
viewers: 0, // This may need to be updated based on your API
|
viewers: 0, // This may need to be updated based on your API
|
||||||
thumbnail: user.thumbnail || "/images/pfps/default.webp",
|
thumbnail: user.thumbnail || "/images/pfps/default.webp",
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
// Generic fetch hook that can be used for any content type
|
// Generic fetch hook that can be used for any content type
|
||||||
export function useFetchContent<T>(
|
export function useFetchContent<T>(
|
||||||
url: string,
|
url: string,
|
||||||
processor: (data: any[]) => T[],
|
processor: (data: any[]) => T[],
|
||||||
dependencies: any[] = []
|
dependencies: any[] = []
|
||||||
): { data: T[]; isLoading: boolean; error: string | null } {
|
): { data: T[]; isLoading: boolean; error: string | null } {
|
||||||
const [data, setData] = useState<T[]>([]);
|
const [data, setData] = useState<T[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Error fetching data: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawData = await response.json();
|
|
||||||
const processedData = processor(rawData);
|
|
||||||
setData(processedData);
|
|
||||||
setError(null);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Error fetching content:", err);
|
|
||||||
setError(err instanceof Error ? err.message : "Unknown error");
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchData();
|
if (!response.ok) {
|
||||||
}, dependencies);
|
throw new Error(`Error fetching data: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
return { data, isLoading, error };
|
const rawData = await response.json();
|
||||||
|
const processedData = processor(rawData);
|
||||||
|
setData(processedData);
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching content:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Unknown error");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchData();
|
||||||
|
}, dependencies);
|
||||||
|
|
||||||
|
return { data, isLoading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Specific hooks for each content type
|
// Specific hooks for each content type
|
||||||
export function useStreams(customUrl?: string): {
|
export function useStreams(customUrl?: string): {
|
||||||
streams: StreamType[];
|
streams: StreamType[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
error: string | null
|
error: string | null;
|
||||||
} {
|
} {
|
||||||
const { isLoggedIn } = useAuth();
|
const { isLoggedIn } = useAuth();
|
||||||
const url = customUrl || (isLoggedIn
|
const url = customUrl || (isLoggedIn ? "/api/streams/recommended" : "/api/streams/popular/4");
|
||||||
? "/api/streams/recommended"
|
|
||||||
: "/api/streams/popular/4");
|
|
||||||
|
|
||||||
const { data, isLoading, error } = useFetchContent<StreamType>(
|
|
||||||
url,
|
|
||||||
processStreamData,
|
|
||||||
[isLoggedIn, customUrl]
|
|
||||||
);
|
|
||||||
|
|
||||||
return { streams: data, isLoading, error };
|
const { data, isLoading, error } = useFetchContent<StreamType>(url, processStreamData, [isLoggedIn, customUrl]);
|
||||||
|
|
||||||
|
return { streams: data, isLoading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCategories(customUrl?: string): {
|
export function useCategories(customUrl?: string): {
|
||||||
categories: CategoryType[];
|
categories: CategoryType[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
error: string | null
|
error: string | null;
|
||||||
} {
|
} {
|
||||||
const { isLoggedIn } = useAuth();
|
const { isLoggedIn } = useAuth();
|
||||||
const url = customUrl || (isLoggedIn
|
const url = customUrl || (isLoggedIn ? "/api/categories/recommended" : "/api/categories/popular/4");
|
||||||
? "/api/categories/recommended"
|
|
||||||
: "/api/categories/popular/4");
|
|
||||||
|
|
||||||
const { data, isLoading, error } = useFetchContent<CategoryType>(
|
|
||||||
url,
|
|
||||||
processCategoryData,
|
|
||||||
[isLoggedIn, customUrl]
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log("Fetched Cat Data:", data); // Debugging
|
const { data, isLoading, error } = useFetchContent<CategoryType>(url, processCategoryData, [isLoggedIn, customUrl]);
|
||||||
|
|
||||||
|
return { categories: data, isLoading, error };
|
||||||
return { categories: data, isLoading, error };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useVods(customUrl?: string): {
|
export function useVods(customUrl?: string): {
|
||||||
vods: VodType[];
|
vods: VodType[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
error: string | null
|
error: string | null;
|
||||||
} {
|
} {
|
||||||
const url = customUrl || "api/vods/all";
|
const url = customUrl || "api/vods/all"; //TODO: Change this to the correct URL or implement it
|
||||||
const { data, isLoading, error } = useFetchContent<VodType>(
|
const { data, isLoading, error } = useFetchContent<VodType>(url, processVodData, [customUrl]);
|
||||||
url,
|
|
||||||
processVodData,
|
|
||||||
[customUrl]
|
|
||||||
);
|
|
||||||
|
|
||||||
|
return { vods: data, isLoading, error };
|
||||||
return { vods: data, isLoading, error };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useUsers(customUrl?: string): {
|
||||||
export function useUsers(customUrl?: string): {
|
users: UserType[];
|
||||||
users: UserType[];
|
isLoading: boolean;
|
||||||
isLoading: boolean;
|
error: string | null;
|
||||||
error: string | null
|
|
||||||
} {
|
} {
|
||||||
const url = customUrl || "/api/users/popular";
|
const url = customUrl || "/api/users/popular";
|
||||||
|
|
||||||
const { data, isLoading, error } = useFetchContent<UserType>(
|
|
||||||
url,
|
|
||||||
processUserData,
|
|
||||||
[customUrl]
|
|
||||||
);
|
|
||||||
|
|
||||||
return { users: data, isLoading, error };
|
const { data, isLoading, error } = useFetchContent<UserType>(url, processUserData, [customUrl]);
|
||||||
}
|
|
||||||
|
return { users: data, isLoading, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format duration from seconds to HH:MM:SS
|
||||||
|
const formatDuration = (seconds: number): string => {
|
||||||
|
const hours = Math.floor(seconds / 3600);
|
||||||
|
const minutes = Math.floor((seconds % 3600) / 60);
|
||||||
|
const remainingSeconds = seconds % 60;
|
||||||
|
|
||||||
|
if (hours > 0) {
|
||||||
|
return `${hours}:${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Format date to a more readable format
|
||||||
|
const formatDate = (dateString: string): string => {
|
||||||
|
const date = new Date(dateString);
|
||||||
|
return date.toLocaleDateString() + " " + date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||||
|
};
|
||||||
|
|||||||
100
frontend/src/pages/DashboardPage.tsx
Normal file
100
frontend/src/pages/DashboardPage.tsx
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import React, { useState, useEffect } from "react";
|
||||||
|
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
||||||
|
import { useAuth } from "../context/AuthContext";
|
||||||
|
import StreamDashboard from "../components/Stream/StreamDashboard";
|
||||||
|
import { CircleDotIcon as RecordIcon, SquarePlayIcon as PlaybackIcon, Undo2Icon } from "lucide-react";
|
||||||
|
import VodsDashboard from "../components/Stream/VodsDashboard";
|
||||||
|
import { useVods } from "../hooks/useContent";
|
||||||
|
|
||||||
|
interface DashboardPageProps {
|
||||||
|
tab?: "dashboard" | "stream" | "vod";
|
||||||
|
}
|
||||||
|
|
||||||
|
const DashboardPage: React.FC<DashboardPageProps> = ({ tab = "dashboard" }) => {
|
||||||
|
const { username, isLive, userId, setIsLive } = useAuth();
|
||||||
|
const { vods } = useVods(`/api/vods/${username}`);
|
||||||
|
const [selectedTab, setSelectedTab] = useState<"dashboard" | "stream" | "vod">(tab);
|
||||||
|
|
||||||
|
const colors = {
|
||||||
|
stream: "red-500",
|
||||||
|
vod: "green-500",
|
||||||
|
dashboard: "white",
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (username) {
|
||||||
|
checkUserStatus();
|
||||||
|
}
|
||||||
|
}, [username]);
|
||||||
|
|
||||||
|
const checkUserStatus = async () => {
|
||||||
|
if (!username) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/user/${username}/status`);
|
||||||
|
const data = await response.json();
|
||||||
|
setIsLive(data.is_live);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error checking user status:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DynamicPageContent className="flex flex-col min-h-screen bg-gradient-radial from-purple-600 via-blue-900 to-black">
|
||||||
|
<div id="dashboard" className="flex flex-col justify-evenly items-center h-full text-white">
|
||||||
|
<div className="flex w-full px-[10vw]">
|
||||||
|
{selectedTab != "dashboard" && (
|
||||||
|
<Undo2Icon
|
||||||
|
size={50}
|
||||||
|
className={`absolute cursor-pointer hover:text-${colors[selectedTab]} transition-all`}
|
||||||
|
onClick={() => setSelectedTab("dashboard")}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<h1 className="text-5xl w-full cursor-default text-center">
|
||||||
|
Welcome <em className="text-[--bg-color] font-black">{username}</em>
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
<h2 className={`text-${colors[selectedTab]} cursor-default text-4xl text-center font-bold bg-black/30 rounded-full px-4 py-2 my-4`}>
|
||||||
|
{selectedTab === "stream" ? "Streaming" : selectedTab === "vod" ? "VODs" : "Dashboard"}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
{selectedTab == "dashboard" ? (
|
||||||
|
<div id="tab-select" className="flex justify-evenly items-center h-full w-full text-[calc((4vh+4vw)/2)] font-bold">
|
||||||
|
<div
|
||||||
|
id="stream-tab"
|
||||||
|
className={`relative ${
|
||||||
|
isLive ? "bg-[#ff0000] hover:bg-[#ff0000]/80" : "bg-black/30 hover:bg-black/40"
|
||||||
|
} flex flex-col justify-evenly items-center text-center w-[50vh] h-[50vh] rounded-xl cursor-pointer hover:scale-105 transition-all bg-`}
|
||||||
|
onClick={() => setSelectedTab("stream")}
|
||||||
|
>
|
||||||
|
{isLive && (
|
||||||
|
<div className="absolute -bottom-5 left-1/2 transform -translate-x-1/2 bg-white text-[#ff0000] text-[2rem] font-black tracking-widest py-1 sm:px-5 px-4 z-30 flex items-center justify-center rounded-tr-xl rounded-bl-xl rounded-tl-xl rounded-br-xl">
|
||||||
|
LIVE
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<RecordIcon color={isLive ? "white" : "red"} size={100} />
|
||||||
|
<h1>Streaming</h1>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="vod-tab"
|
||||||
|
className="relative flex flex-col justify-evenly items-center bg-black/30 hover:bg-black/40 text-white w-[50vh] h-[50vh] rounded-xl cursor-pointer hover:scale-105 transition-all"
|
||||||
|
onClick={() => vods.length > 0 && setSelectedTab("vod")}
|
||||||
|
>
|
||||||
|
<PlaybackIcon size={100} />
|
||||||
|
<h1 className="text-white">VODs</h1>
|
||||||
|
<h3 className={`${vods.length > 0 ? "text-white" : "text-gray-600"} absolute bottom-5 text-sm`}>
|
||||||
|
{vods.length} VOD{vods.length != 1 && "s"} available
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : selectedTab === "stream" && username && userId ? (
|
||||||
|
<StreamDashboard username={username} userId={userId} isLive={isLive} />
|
||||||
|
) : (
|
||||||
|
<VodsDashboard vods={vods} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DynamicPageContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DashboardPage;
|
||||||
@@ -1,480 +0,0 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
|
||||||
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
|
||||||
import Button from "../components/Input/Button";
|
|
||||||
import Input from "../components/Input/Input";
|
|
||||||
import { useCategories } from "../hooks/useContent";
|
|
||||||
import {
|
|
||||||
X as CloseIcon,
|
|
||||||
Eye as ShowIcon,
|
|
||||||
EyeOff as HideIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { useAuth } from "../context/AuthContext";
|
|
||||||
import { debounce } from "lodash";
|
|
||||||
import VideoPlayer from "../components/Stream/VideoPlayer";
|
|
||||||
import { CategoryType } from "../types/CategoryType";
|
|
||||||
import { StreamListItem } from "../components/Layout/ListItem";
|
|
||||||
import { getCategoryThumbnail } from "../utils/thumbnailUtils";
|
|
||||||
|
|
||||||
interface StreamData {
|
|
||||||
title: string;
|
|
||||||
category_name: string;
|
|
||||||
viewer_count: number;
|
|
||||||
start_time: string;
|
|
||||||
stream_key: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const StreamDashboardPage: React.FC = () => {
|
|
||||||
const { username } = useAuth();
|
|
||||||
const [isStreaming, setIsStreaming] = useState(false);
|
|
||||||
const [streamData, setStreamData] = useState<StreamData>({
|
|
||||||
title: "",
|
|
||||||
category_name: "",
|
|
||||||
viewer_count: 0,
|
|
||||||
start_time: "",
|
|
||||||
stream_key: "",
|
|
||||||
});
|
|
||||||
const [streamDetected, setStreamDetected] = useState(false);
|
|
||||||
const [timeStarted, setTimeStarted] = useState("");
|
|
||||||
const [isCategoryFocused, setIsCategoryFocused] = useState(false);
|
|
||||||
const [filteredCategories, setFilteredCategories] = useState<CategoryType[]>(
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
const [thumbnail, setThumbnail] = useState<File | null>(null);
|
|
||||||
const [thumbnailPreview, setThumbnailPreview] = useState<{
|
|
||||||
url: string;
|
|
||||||
isCustom: boolean;
|
|
||||||
}>({ url: "", isCustom: false });
|
|
||||||
const [debouncedCheck, setDebouncedCheck] = useState<Function | null>(null);
|
|
||||||
const [showKey, setShowKey] = useState(false);
|
|
||||||
|
|
||||||
const {
|
|
||||||
categories,
|
|
||||||
isLoading: categoriesLoading,
|
|
||||||
error: categoriesError,
|
|
||||||
} = useCategories("/api/categories/popular/100");
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Set filtered categories when categories load
|
|
||||||
if (categories.length > 0) {
|
|
||||||
setFilteredCategories(categories);
|
|
||||||
}
|
|
||||||
}, [categories]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const categoryCheck = debounce((categoryName: string) => {
|
|
||||||
const isValidCategory = categories.some(
|
|
||||||
(cat) => cat.title.toLowerCase() === categoryName.toLowerCase()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isValidCategory && !thumbnailPreview.isCustom) {
|
|
||||||
const defaultThumbnail = getCategoryThumbnail(categoryName);
|
|
||||||
setThumbnailPreview({ url: defaultThumbnail, isCustom: false });
|
|
||||||
}
|
|
||||||
}, 300);
|
|
||||||
|
|
||||||
setDebouncedCheck(() => categoryCheck);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
categoryCheck.cancel();
|
|
||||||
};
|
|
||||||
}, [categories, thumbnailPreview.isCustom]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (username) {
|
|
||||||
checkStreamStatus();
|
|
||||||
}
|
|
||||||
}, [username]);
|
|
||||||
|
|
||||||
const checkStreamStatus = async () => {
|
|
||||||
if (!username) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/api/user/${username}/status`);
|
|
||||||
const data = await response.json();
|
|
||||||
setIsStreaming(data.is_live);
|
|
||||||
|
|
||||||
if (data.is_live) {
|
|
||||||
const streamResponse = await fetch(
|
|
||||||
`/api/streams/${data.user_id}/data`,
|
|
||||||
{ credentials: "include" }
|
|
||||||
);
|
|
||||||
const streamData = await streamResponse.json();
|
|
||||||
setStreamData({
|
|
||||||
title: streamData.title,
|
|
||||||
category_name: streamData.category_name,
|
|
||||||
viewer_count: streamData.num_viewers,
|
|
||||||
start_time: streamData.start_time,
|
|
||||||
stream_key: streamData.stream_key,
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log("Stream data:", streamData);
|
|
||||||
|
|
||||||
const time = Math.floor(
|
|
||||||
(Date.now() - new Date(streamData.start_time).getTime()) / 60000 // Convert to minutes
|
|
||||||
);
|
|
||||||
|
|
||||||
if (time < 60) setTimeStarted(`${time}m ago`);
|
|
||||||
else if (time < 1440)
|
|
||||||
setTimeStarted(`${Math.floor(time / 60)}h ${time % 60}m ago`);
|
|
||||||
else
|
|
||||||
setTimeStarted(
|
|
||||||
`${Math.floor(time / 1440)}d ${Math.floor((time % 1440) / 60)}h ${
|
|
||||||
time % 60
|
|
||||||
}m ago`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Just need the stream key if not streaming
|
|
||||||
const response = await fetch(`/api/user/${username}/stream_key`);
|
|
||||||
const keyData = await response.json();
|
|
||||||
setStreamData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
stream_key: keyData.stream_key,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error checking stream status:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setStreamData((prev) => ({ ...prev, [name]: value }));
|
|
||||||
|
|
||||||
if (name === "category_name") {
|
|
||||||
const filtered = categories.filter((cat) =>
|
|
||||||
cat.title.toLowerCase().includes(value.toLowerCase())
|
|
||||||
);
|
|
||||||
setFilteredCategories(filtered);
|
|
||||||
if (debouncedCheck) {
|
|
||||||
debouncedCheck(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCategorySelect = (categoryName: string) => {
|
|
||||||
console.log("Selected category:", categoryName);
|
|
||||||
setStreamData((prev) => ({ ...prev, category_name: categoryName }));
|
|
||||||
setFilteredCategories([]);
|
|
||||||
if (debouncedCheck) {
|
|
||||||
debouncedCheck(categoryName);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleThumbnailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
if (e.target.files && e.target.files[0]) {
|
|
||||||
const file = e.target.files[0];
|
|
||||||
setThumbnail(file);
|
|
||||||
setThumbnailPreview({
|
|
||||||
url: URL.createObjectURL(file),
|
|
||||||
isCustom: true,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
setThumbnail(null);
|
|
||||||
if (streamData.category_name && debouncedCheck) {
|
|
||||||
debouncedCheck(streamData.category_name);
|
|
||||||
} else {
|
|
||||||
setThumbnailPreview({ url: "", isCustom: false });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearThumbnail = () => {
|
|
||||||
setThumbnail(null);
|
|
||||||
if (streamData.category_name) {
|
|
||||||
console.log(
|
|
||||||
"Clearing thumbnail as category is set and default category thumbnail will be used"
|
|
||||||
);
|
|
||||||
const defaultThumbnail = getCategoryThumbnail(streamData.category_name);
|
|
||||||
setThumbnailPreview({ url: defaultThumbnail, isCustom: false });
|
|
||||||
} else {
|
|
||||||
setThumbnailPreview({ url: "", isCustom: false });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const isFormValid = () => {
|
|
||||||
return (
|
|
||||||
streamData.title.trim() !== "" &&
|
|
||||||
streamData.category_name.trim() !== "" &&
|
|
||||||
categories.some(
|
|
||||||
(cat) =>
|
|
||||||
cat.title.toLowerCase() === streamData.category_name.toLowerCase()
|
|
||||||
) &&
|
|
||||||
streamDetected
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePublishStream = async () => {
|
|
||||||
console.log("Starting stream with data:", streamData);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/publish_stream", {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(streamData),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
console.log("Stream published successfully");
|
|
||||||
window.location.reload();
|
|
||||||
} else if (response.status === 403) {
|
|
||||||
console.error("Unauthorized - Invalid stream key or already streaming");
|
|
||||||
} else {
|
|
||||||
console.error("Failed to publish stream");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error publishing stream:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleUpdateStream = async () => {
|
|
||||||
console.log("Updating stream with data:", streamData);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/update_stream", {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
key: streamData.stream_key,
|
|
||||||
title: streamData.title,
|
|
||||||
category_name: streamData.category_name,
|
|
||||||
thumbnail: thumbnail,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
console.log("Stream updated successfully");
|
|
||||||
window.location.reload();
|
|
||||||
} else {
|
|
||||||
console.error("Failed to update stream");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating stream:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleEndStream = async () => {
|
|
||||||
console.log("Ending stream...");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/end_stream", {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ key: streamData.stream_key }),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
console.log("Stream ended successfully");
|
|
||||||
window.location.reload();
|
|
||||||
} else {
|
|
||||||
console.error("Failed to end stream");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error ending stream:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DynamicPageContent className="flex flex-col min-h-screen bg-gradient-radial from-purple-600 via-blue-900 to-black">
|
|
||||||
<div
|
|
||||||
id="streamer-dashboard"
|
|
||||||
className="flex flex-col flex-grow mx-auto px-4"
|
|
||||||
>
|
|
||||||
<h1 className="text-4xl font-bold text-white text-center">
|
|
||||||
{isStreaming ? "Stream Dashboard" : "Start Streaming"}
|
|
||||||
</h1>
|
|
||||||
|
|
||||||
<div className="flex flex-grow gap-8 items-stretch pb-4">
|
|
||||||
{/* Left side - Stream Settings */}
|
|
||||||
<div className="flex flex-col flex-grow">
|
|
||||||
<h2 className="text-center text-2xl font-bold text-white mb-4">
|
|
||||||
Stream Settings
|
|
||||||
</h2>
|
|
||||||
<div className="flex flex-col flex-grow justify-evenly space-y-6 bg-gray-800 rounded-lg p-6 shadow-xl">
|
|
||||||
<div>
|
|
||||||
<label className="block text-white mb-2">Stream Title</label>
|
|
||||||
<Input
|
|
||||||
name="title"
|
|
||||||
value={streamData.title}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
placeholder="Enter your stream title"
|
|
||||||
extraClasses="w-[70%] focus:w-[70%]"
|
|
||||||
maxLength={50}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="relative">
|
|
||||||
<label className="block text-white mb-2">Category</label>
|
|
||||||
<Input
|
|
||||||
name="category_name"
|
|
||||||
value={streamData.category_name}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
onFocus={() => setIsCategoryFocused(true)}
|
|
||||||
onBlur={() =>
|
|
||||||
setTimeout(() => setIsCategoryFocused(false), 200)
|
|
||||||
}
|
|
||||||
placeholder="Select or type a category"
|
|
||||||
extraClasses="w-[70%] focus:w-[70%]"
|
|
||||||
maxLength={50}
|
|
||||||
autoComplete="off"
|
|
||||||
type="search"
|
|
||||||
/>
|
|
||||||
{isCategoryFocused && filteredCategories.length > 0 && (
|
|
||||||
<div className="absolute z-10 w-full bg-gray-700 mt-1 rounded-md shadow-lg max-h-48 overflow-y-auto">
|
|
||||||
{filteredCategories.map((category) => (
|
|
||||||
<div
|
|
||||||
key={category.title}
|
|
||||||
className="px-4 py-2 hover:bg-gray-600 cursor-pointer text-white"
|
|
||||||
onClick={() => handleCategorySelect(category.title)}
|
|
||||||
>
|
|
||||||
{category.title}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-white mb-2">
|
|
||||||
Stream Thumbnail
|
|
||||||
</label>
|
|
||||||
<div className="relative flex flex-row items-center justify-center">
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept="image/*"
|
|
||||||
onChange={handleThumbnailChange}
|
|
||||||
className="hidden"
|
|
||||||
id="thumbnail-upload"
|
|
||||||
/>
|
|
||||||
<label
|
|
||||||
htmlFor="thumbnail-upload"
|
|
||||||
className="cursor-pointer inline-block bg-gray-700 hover:bg-gray-600 text-white py-2 px-4 rounded-lg transition-colors"
|
|
||||||
>
|
|
||||||
{thumbnail ? "Change Thumbnail" : "Choose Thumbnail"}
|
|
||||||
</label>
|
|
||||||
<span className="ml-3 text-gray-400">
|
|
||||||
{thumbnail ? thumbnail.name : "No file selected"}
|
|
||||||
</span>
|
|
||||||
{thumbnailPreview.isCustom && (
|
|
||||||
<button
|
|
||||||
onClick={clearThumbnail}
|
|
||||||
className="absolute right-0 top-0 p-1 bg-red-500 rounded-full hover:bg-red-600 transition-colors"
|
|
||||||
>
|
|
||||||
<CloseIcon size={16} className="text-white" />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{!thumbnailPreview.isCustom && (
|
|
||||||
<p className="text-gray-400 mt-2 text-sm text-center">
|
|
||||||
No thumbnail selected - the default category image will be
|
|
||||||
used
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isStreaming && (
|
|
||||||
<div className="bg-gray-700 p-4 rounded-lg">
|
|
||||||
<h3 className="text-white font-semibold mb-2">Stream Info</h3>
|
|
||||||
<p className="text-gray-300">
|
|
||||||
Viewers: {streamData.viewer_count}
|
|
||||||
</p>
|
|
||||||
<p className="text-gray-300">
|
|
||||||
Started:{" "}
|
|
||||||
{new Date(streamData.start_time!).toLocaleTimeString()}
|
|
||||||
{` (${timeStarted})`}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex items-center mx-auto p-10 bg-gray-900 w-fit rounded-xl py-4">
|
|
||||||
<label className="block text-white mr-8">Stream Key</label>
|
|
||||||
<Input
|
|
||||||
type={showKey ? "text" : "password"}
|
|
||||||
value={streamData.stream_key}
|
|
||||||
readOnly
|
|
||||||
extraClasses="w-fit pr-[30px]"
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowKey(!showKey)}
|
|
||||||
className="-translate-x-[30px] top-1/2 h-6 w-6 text-white"
|
|
||||||
>
|
|
||||||
{showKey ? (
|
|
||||||
<HideIcon className="h-6 w-6" />
|
|
||||||
) : (
|
|
||||||
<ShowIcon className="h-6 w-6" />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col w-fit mx-auto items-center justify-center pt-6 gap-6">
|
|
||||||
<div className="flex gap-8">
|
|
||||||
<Button
|
|
||||||
onClick={
|
|
||||||
isStreaming ? handleUpdateStream : handlePublishStream
|
|
||||||
}
|
|
||||||
disabled={!isFormValid()}
|
|
||||||
extraClasses="text-2xl px-8 py-4 disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{isStreaming ? "Update Stream" : "Start Streaming"}
|
|
||||||
</Button>
|
|
||||||
{isStreaming && (
|
|
||||||
<Button
|
|
||||||
onClick={handleEndStream}
|
|
||||||
extraClasses="text-2xl px-8 py-4 hover:text-red-500 hover:border-red-500"
|
|
||||||
>
|
|
||||||
End Stream
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{!streamDetected && (
|
|
||||||
<p className="text-red-500 text-sm">
|
|
||||||
No stream input detected. Please start streaming using your
|
|
||||||
broadcast software.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right side - Preview */}
|
|
||||||
<div className="w-[25vw] flex flex-col">
|
|
||||||
<h2 className="text-center text-2xl font-bold text-white mb-4">
|
|
||||||
Stream Preview
|
|
||||||
</h2>
|
|
||||||
<div className="flex flex-col gap-4 bg-gray-800 rounded-lg p-4 w-full h-fit flex-grow justify-around">
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<p className="text-white text-center pb-4">Video</p>
|
|
||||||
<VideoPlayer
|
|
||||||
streamer={username ?? undefined}
|
|
||||||
extraClasses="border border-white"
|
|
||||||
onStreamDetected={setStreamDetected}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<p className="text-white text-center">List Item</p>
|
|
||||||
<StreamListItem
|
|
||||||
id={1}
|
|
||||||
title={streamData.title || "Stream Title"}
|
|
||||||
username={username || ""}
|
|
||||||
streamCategory={streamData.category_name || "Category"}
|
|
||||||
viewers={streamData.viewer_count}
|
|
||||||
thumbnail={thumbnailPreview.url || ""}
|
|
||||||
onItemClick={() => {}}
|
|
||||||
extraClasses="max-w-[20vw]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</DynamicPageContent>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default StreamDashboardPage;
|
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
export interface VodType {
|
export interface VodType {
|
||||||
type: "vod";
|
type: "vod";
|
||||||
id: number;
|
vod_id: number;
|
||||||
title: string;
|
title: string;
|
||||||
streamer: string;
|
username: string;
|
||||||
datetime: string;
|
datetime: string;
|
||||||
category: string;
|
category_name: string;
|
||||||
length: number;
|
length: string;
|
||||||
views: number;
|
views: number;
|
||||||
url: string;
|
|
||||||
thumbnail: string;
|
thumbnail: string;
|
||||||
}
|
}
|
||||||
@@ -85,7 +85,7 @@ def get_latest_vod(user_id: int):
|
|||||||
Returns data of the most recent stream by a streamer
|
Returns data of the most recent stream by a streamer
|
||||||
"""
|
"""
|
||||||
with Database() as db:
|
with Database() as db:
|
||||||
latest_vod = db.fetchone("""SELECT * FROM vods WHERE user_id = ? ORDER BY vod_id DESC;""", (user_id,))
|
latest_vod = db.fetchone("""SELECT vods.*, category_name FROM vods JOIN categories ON vods.category_id = categories.category_id WHERE user_id = ? ORDER BY vod_id DESC;""", (user_id,))
|
||||||
return latest_vod
|
return latest_vod
|
||||||
|
|
||||||
def get_user_vods(user_id: int):
|
def get_user_vods(user_id: int):
|
||||||
@@ -93,7 +93,7 @@ def get_user_vods(user_id: int):
|
|||||||
Returns data of all vods by a streamer
|
Returns data of all vods by a streamer
|
||||||
"""
|
"""
|
||||||
with Database() as db:
|
with Database() as db:
|
||||||
vods = db.fetchall("""SELECT * FROM vods WHERE user_id = ?;""", (user_id,))
|
vods = db.fetchall("""SELECT vods.*, category_name FROM vods JOIN categories ON vods.category_id = categories.category_id WHERE user_id = ? ORDER BY vod_id DESC;""", (user_id,))
|
||||||
return vods
|
return vods
|
||||||
|
|
||||||
def get_all_vods():
|
def get_all_vods():
|
||||||
|
|||||||
Reference in New Issue
Block a user