Merge branch 'main' of https://github.com/john-david3/cs3305-team11
This commit is contained in:
@@ -71,7 +71,7 @@ const ForgotPasswordForm: React.FC<SubmitProps> = ({ onSubmit }) => {
|
|||||||
return (
|
return (
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
<div className="flex flex-col items-center p-[2.5rem]">
|
<div className="flex flex-col items-center p-[2.5rem]">
|
||||||
<h1 className="text-white text-[1.5em] font-[800] md:text-[1.75em] lg:text-[2em]">
|
<h1 className="text-white text-[1.4em] font-[800] md:text-[1.5em] lg:text-[1.75em]">
|
||||||
Forgot Password
|
Forgot Password
|
||||||
</h1>
|
</h1>
|
||||||
<div className="mt-10 bg-white/10 backdrop-blur-md p-6 rounded-xl shadow-lg w-full max-w-[10em] min-w-[14em] border border-white/10 sm:max-w-[16em] md:max-w-[18em] lg:max-w-[20em]">
|
<div className="mt-10 bg-white/10 backdrop-blur-md p-6 rounded-xl shadow-lg w-full max-w-[10em] min-w-[14em] border border-white/10 sm:max-w-[16em] md:max-w-[18em] lg:max-w-[20em]">
|
||||||
|
|||||||
@@ -154,7 +154,7 @@ const LoginForm: React.FC<SubmitProps> = ({ onSubmit, onForgotPassword }) => {
|
|||||||
onClick={onForgotPassword}
|
onClick={onForgotPassword}
|
||||||
>
|
>
|
||||||
<ForgotIcon size={16} className="flex flex-row mr-1" />
|
<ForgotIcon size={16} className="flex flex-row mr-1" />
|
||||||
<span className="text-[calc((1.5vw+1vh)/2)]">
|
<span className="text-[0.6rem] 2lg:text-[0.75rem]">
|
||||||
Forgot Password
|
Forgot Password
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export default function GoogleLogin() {
|
|||||||
alt="Google logo"
|
alt="Google logo"
|
||||||
className="w-[2em] h-[2em] mr-2"
|
className="w-[2em] h-[2em] mr-2"
|
||||||
/>
|
/>
|
||||||
<span className="flex-grow text-[calc((1.5vw+1.5vh)/2)]">
|
<span className="flex-grow text-[0.75rem] 2lg:text-[1rem]">
|
||||||
Sign in with Google
|
Sign in with Google
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const Button: React.FC<ButtonProps> = ({
|
|||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type={type}
|
type={type}
|
||||||
className={`${extraClasses} p-2 text-[1.5vw] text-white hover:text-purple-600 bg-black/30 hover:bg-black/80 rounded-md border border-gray-300 hover:border-purple-500 hover:border-b-4 hover:border-l-4 active:border-b-2 active:border-l-2 transition-all`}
|
className={`${extraClasses} p-2 text-[clamp(1rem, 1.5vw, 1.25rem)] text-white hover:text-purple-600 bg-black/30 hover:bg-black/80 rounded-md border border-gray-300 hover:border-purple-500 hover:border-b-4 hover:border-l-4 active:border-b-2 active:border-l-2 transition-all`}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
54
frontend/src/components/Input/FollowUserButton.tsx
Normal file
54
frontend/src/components/Input/FollowUserButton.tsx
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import React, { useEffect, useState } from "react";
|
||||||
|
import { useFollow } from "../../hooks/useFollow";
|
||||||
|
|
||||||
|
interface FollowUserButtonProps {
|
||||||
|
user: {
|
||||||
|
user_id: number;
|
||||||
|
username: string;
|
||||||
|
isFollowing: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const FollowUserButton: React.FC<FollowUserButtonProps> = ({ user }) => {
|
||||||
|
const [isFollowing, setIsFollowing] = useState<boolean>(user.isFollowing);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
const { checkFollowStatus, followUser, unfollowUser } = useFollow();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsFollowing(user.isFollowing);
|
||||||
|
}, [user.isFollowing]);
|
||||||
|
|
||||||
|
const handleClick = async (e: React.MouseEvent<HTMLButtonElement>) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
if (isFollowing) {
|
||||||
|
await unfollowUser(user.user_id);
|
||||||
|
setIsFollowing(false);
|
||||||
|
} else {
|
||||||
|
await followUser(user.user_id);
|
||||||
|
setIsFollowing(true);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error toggling follow state:", error);
|
||||||
|
}
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={handleClick}
|
||||||
|
disabled={isLoading}
|
||||||
|
className={`px-4 py-2 text-sm rounded-md font-bold transition-all ${
|
||||||
|
isFollowing
|
||||||
|
? "bg-gray-700 hover:bg-red-600 text-white"
|
||||||
|
: "bg-purple-600 hover:bg-purple-700 text-white"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isFollowing ? "Unfollow" : "Follow"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default FollowUserButton;
|
||||||
@@ -2,6 +2,7 @@ import React from "react";
|
|||||||
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";
|
||||||
|
|
||||||
// Base props that all item types share
|
// Base props that all item types share
|
||||||
interface BaseListItemProps {
|
interface BaseListItemProps {
|
||||||
@@ -124,6 +125,52 @@ const UserListItem: React.FC<UserListItemProps> = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// VODs item component
|
||||||
|
interface VodListItemProps extends BaseListItemProps, Omit<VodType, "type"> {}
|
||||||
|
|
||||||
|
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
|
// Legacy wrapper component for backward compatibility
|
||||||
export interface ListItemProps {
|
export interface ListItemProps {
|
||||||
type: "stream" | "category" | "user";
|
type: "stream" | "category" | "user";
|
||||||
@@ -138,4 +185,4 @@ export interface ListItemProps {
|
|||||||
isLive?: boolean;
|
isLive?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { StreamListItem, CategoryListItem, UserListItem };
|
export { StreamListItem, CategoryListItem, UserListItem, VodListItem };
|
||||||
@@ -10,16 +10,17 @@ import React, {
|
|||||||
} from "react";
|
} 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 } 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"
|
||||||
|
|
||||||
type ItemType = StreamType | CategoryType | UserType;
|
type ItemType = StreamType | CategoryType | UserType | VodType;
|
||||||
|
|
||||||
interface ListRowProps {
|
interface ListRowProps {
|
||||||
variant?: "default" | "search";
|
variant?: "default" | "search";
|
||||||
type: "stream" | "category" | "user";
|
type: "stream" | "category" | "user" | "vod";
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
items: ItemType[];
|
items: ItemType[];
|
||||||
@@ -100,6 +101,9 @@ const ListRow = forwardRef<ListRowRef, ListRowProps>((props, ref) => {
|
|||||||
const isUserType = (item: ItemType): item is UserType =>
|
const isUserType = (item: ItemType): item is UserType =>
|
||||||
item.type === "user";
|
item.type === "user";
|
||||||
|
|
||||||
|
const isVodType = (item: ItemType): item is VodType =>
|
||||||
|
item.type === "vod";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`${extraClasses} flex relative rounded-[1.5rem] text-white transition-all ${
|
className={`${extraClasses} flex relative rounded-[1.5rem] text-white transition-all ${
|
||||||
@@ -196,6 +200,24 @@ const ListRow = forwardRef<ListRowRef, ListRowProps>((props, ref) => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
else if (type === "vod" && isVodType(item)) {
|
||||||
|
return (
|
||||||
|
<VodListItem
|
||||||
|
key={`vod-${item.id}`}
|
||||||
|
id={item.id}
|
||||||
|
title={item.title}
|
||||||
|
streamer={item.streamer}
|
||||||
|
datetime={item.datetime}
|
||||||
|
category={item.category}
|
||||||
|
length={item.length}
|
||||||
|
views={item.views}
|
||||||
|
url={item.url}
|
||||||
|
thumbnail={item.thumbnail}
|
||||||
|
onItemClick={() => window.open(item.url, "_blank")}
|
||||||
|
extraClasses={itemExtraClasses}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
})}
|
})}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -4,8 +4,28 @@ 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 { getCategoryThumbnail } from "../utils/thumbnailUtils";
|
import { getCategoryThumbnail } from "../utils/thumbnailUtils";
|
||||||
|
|
||||||
|
// Process API data into our VodType structure
|
||||||
|
const processVodData = (data: any[]): VodType[] => {
|
||||||
|
|
||||||
|
return data.map((vod) => ({
|
||||||
|
type: "vod",
|
||||||
|
id: vod.id, // Ensure this matches API response
|
||||||
|
title: vod.title,
|
||||||
|
streamer: vod.streamer, // Ensure backend sends streamer name or ID
|
||||||
|
datetime: new Date(vod.datetime).toLocaleString(),
|
||||||
|
category: vod.category,
|
||||||
|
length: vod.length,
|
||||||
|
views: vod.views,
|
||||||
|
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) => ({
|
||||||
@@ -20,6 +40,7 @@ const processStreamData = (data: any[]): StreamType[] => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
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,
|
||||||
@@ -115,9 +136,29 @@ export function useCategories(customUrl?: string): {
|
|||||||
[isLoggedIn, customUrl]
|
[isLoggedIn, customUrl]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
console.log("Fetched Cat Data:", data); // Debugging
|
||||||
|
|
||||||
|
|
||||||
return { categories: data, isLoading, error };
|
return { categories: data, isLoading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useVods(customUrl?: string): {
|
||||||
|
vods: VodType[];
|
||||||
|
isLoading: boolean;
|
||||||
|
error: string | null
|
||||||
|
} {
|
||||||
|
const url = customUrl || "api/vods/all";
|
||||||
|
const { data, isLoading, error } = useFetchContent<VodType>(
|
||||||
|
url,
|
||||||
|
processVodData,
|
||||||
|
[customUrl]
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
return { vods: data, isLoading, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export function useUsers(customUrl?: string): {
|
export function useUsers(customUrl?: string): {
|
||||||
users: UserType[];
|
users: UserType[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ const CategoryPage: React.FC = () => {
|
|||||||
<ListRow
|
<ListRow
|
||||||
ref={listRowRef}
|
ref={listRowRef}
|
||||||
type="stream"
|
type="stream"
|
||||||
title={`${categoryName} Streams`}
|
title={`${categoryName}`}
|
||||||
description={`Live streams in the ${categoryName} category`}
|
description={`Live streams in the ${categoryName} category`}
|
||||||
items={streams}
|
items={streams}
|
||||||
wrap={true}
|
wrap={true}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useNavigate, useParams } from "react-router-dom";
|
|||||||
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
||||||
import { useCategoryFollow } from "../hooks/useCategoryFollow";
|
import { useCategoryFollow } from "../hooks/useCategoryFollow";
|
||||||
import FollowButton from "../components/Input/FollowButton";
|
import FollowButton from "../components/Input/FollowButton";
|
||||||
|
import { useAuthModal } from "../hooks/useAuthModal";
|
||||||
|
|
||||||
|
|
||||||
interface Category {
|
interface Category {
|
||||||
@@ -23,6 +24,7 @@ const FollowedCategories: React.FC<FollowedCategoryProps> = ({ extraClasses = ""
|
|||||||
const { categoryName } = useParams<{ categoryName: string }>();
|
const { categoryName } = useParams<{ categoryName: string }>();
|
||||||
const { checkCategoryFollowStatus, followCategory, unfollowCategory } = useCategoryFollow();
|
const { checkCategoryFollowStatus, followCategory, unfollowCategory } = useCategoryFollow();
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (categoryName) checkCategoryFollowStatus(categoryName);
|
if (categoryName) checkCategoryFollowStatus(categoryName);
|
||||||
}, [categoryName]);
|
}, [categoryName]);
|
||||||
@@ -32,7 +34,7 @@ const FollowedCategories: React.FC<FollowedCategoryProps> = ({ extraClasses = ""
|
|||||||
|
|
||||||
const fetchFollowedCategories = async () => {
|
const fetchFollowedCategories = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/categories/following");
|
const response = await fetch("/api/categories/your_categories");
|
||||||
if (!response.ok) throw new Error("Failed to fetch followed categories");
|
if (!response.ok) throw new Error("Failed to fetch followed categories");
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setFollowedCategories(data);
|
setFollowedCategories(data);
|
||||||
@@ -52,7 +54,7 @@ const FollowedCategories: React.FC<FollowedCategoryProps> = ({ extraClasses = ""
|
|||||||
className={`top-0 left-0 w-screen h-screen overflow-x-hidden flex flex-col bg-[var(--sideBar-bg)] text-[var(--sideBar-text)] text-center overflow-y-auto scrollbar-hide transition-all duration-500 ease-in-out ${extraClasses}`}
|
className={`top-0 left-0 w-screen h-screen overflow-x-hidden flex flex-col bg-[var(--sideBar-bg)] text-[var(--sideBar-text)] text-center overflow-y-auto scrollbar-hide transition-all duration-500 ease-in-out ${extraClasses}`}
|
||||||
>
|
>
|
||||||
{/* Followed Categories */}
|
{/* Followed Categories */}
|
||||||
<div id="categories-followed" className="grid grid-cols-3 gap-4 p-4 w-full">
|
<div id="categories-followed" className="grid grid-cols-4 gap-4 p-4 w-full">
|
||||||
{followedCategories.map((category) => {
|
{followedCategories.map((category) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -1,35 +1,45 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { useSidebar } from "../context/SidebarContext";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { ToggleButton } from "../components/Input/Button";
|
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
||||||
import { Sidebar as SidebarIcon } from "lucide-react";
|
import { useFollow } from "../hooks/useFollow";
|
||||||
import { useNavigate } from "react-router-dom"; // Import useNavigate
|
import { useAuthModal } from "../hooks/useAuthModal";
|
||||||
import { CategoryType } from "../types/CategoryType";
|
import FollowUserButton from "../components/Input/FollowUserButton";
|
||||||
|
|
||||||
// Define TypeScript interfaces
|
|
||||||
interface Streamer {
|
interface Streamer {
|
||||||
user_id: number;
|
user_id: number;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FollowingProps {
|
interface FollowingStreamerProps {
|
||||||
extraClasses?: string;
|
extraClasses?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Following: React.FC<FollowingProps> = ({ extraClasses = "" }) => {
|
const Following: React.FC<FollowingStreamerProps> = ({ extraClasses = "" }) => {
|
||||||
const { showSideBar, setShowSideBar } = useSidebar();
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { username, isLoggedIn } = useAuth();
|
const { isLoggedIn } = useAuth();
|
||||||
const [followedStreamers, setFollowedStreamers] = useState<Streamer[]>([]);
|
const [followedStreamers, setFollowedStreamers] = useState<Streamer[]>([]);
|
||||||
|
const [followingStatus, setFollowingStatus] = useState<{ [key: number]: boolean }>({}); // Store follow status for each streamer
|
||||||
|
|
||||||
|
const { isFollowing, checkFollowStatus, followUser, unfollowUser } =
|
||||||
|
useFollow();
|
||||||
|
|
||||||
// Fetch followed streamers
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchFollowedStreamers = async () => {
|
const fetchFollowedStreamers = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/user/following");
|
const response = await fetch("/api/user/following");
|
||||||
if (!response.ok) throw new Error("Failed to fetch followed streamers");
|
if (!response.ok) throw new Error("Failed to fetch followed streamers");
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setFollowedStreamers(data.streamers || []);
|
setFollowedStreamers(data);
|
||||||
|
|
||||||
|
const updatedStatus: { [key: number]: boolean } = {};
|
||||||
|
for (const streamer of data || []) {
|
||||||
|
const status = await checkFollowStatus(streamer.username);
|
||||||
|
updatedStatus[streamer.user_id] = Boolean(status);
|
||||||
|
}
|
||||||
|
setFollowingStatus(updatedStatus);
|
||||||
|
|
||||||
|
console.log("Fetched Follow Status:", updatedStatus); // Log the status
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching followed streamers:", error);
|
console.error("Error fetching followed streamers:", error);
|
||||||
}
|
}
|
||||||
@@ -40,103 +50,51 @@ const Following: React.FC<FollowingProps> = ({ extraClasses = "" }) => {
|
|||||||
}
|
}
|
||||||
}, [isLoggedIn]);
|
}, [isLoggedIn]);
|
||||||
|
|
||||||
// Handle sidebar toggle
|
|
||||||
const handleSideBar = () => {
|
const handleFollowToggle = async (userId: number) => {
|
||||||
setShowSideBar(!showSideBar);
|
const isCurrentlyFollowing = followingStatus[userId];
|
||||||
|
|
||||||
|
if (isCurrentlyFollowing) {
|
||||||
|
await unfollowUser(userId);
|
||||||
|
} else {
|
||||||
|
await followUser(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update local state for this specific streamer
|
||||||
|
setFollowingStatus((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[userId]: !isCurrentlyFollowing, // Toggle based on previous state
|
||||||
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<DynamicPageContent>
|
||||||
{/* Sidebar Toggle Button */}
|
|
||||||
<ToggleButton
|
|
||||||
onClick={handleSideBar}
|
|
||||||
extraClasses={`absolute group text-[1rem] top-[9vh] ${
|
|
||||||
showSideBar
|
|
||||||
? "left-[16vw] duration-[0.5s]"
|
|
||||||
: "left-[20px] duration-[1s]"
|
|
||||||
} ease-in-out cursor-pointer z-[50]`}
|
|
||||||
toggled={showSideBar}
|
|
||||||
>
|
|
||||||
<SidebarIcon className="h-[2vw] w-[2vw]" />
|
|
||||||
|
|
||||||
{showSideBar && (
|
|
||||||
<small className="absolute flex items-center top-0 ml-4 left-0 h-full w-full my-auto group-hover:left-full opacity-0 group-hover:opacity-100 text-white transition-all delay-200">
|
|
||||||
Press S
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
</ToggleButton>
|
|
||||||
|
|
||||||
{/* Sidebar Container */}
|
|
||||||
<div
|
<div
|
||||||
id="sidebar"
|
id="sidebar"
|
||||||
className={`top-0 left-0 w-screen h-screen overflow-x-hidden flex flex-col bg-[var(--sideBar-bg)] text-[var(--sideBar-text)] text-center overflow-y-auto scrollbar-hide
|
className={`top-0 left-0 w-screen h-screen overflow-x-hidden flex flex-col bg-[var(--sideBar-bg)] text-[var(--sideBar-text)] text-center overflow-y-auto scrollbar-hide transition-all duration-500 ease-in-out ${extraClasses}`}
|
||||||
transition-all duration-500 ease-in-out ${
|
|
||||||
showSideBar ? "translate-x-0" : "-translate-x-full"
|
|
||||||
} ${extraClasses}`}
|
|
||||||
>
|
|
||||||
{/* Profile Info */}
|
|
||||||
<div className="flex flex-row items-center border-b-4 border-[var(--profile-border)] justify-evenly bg-[var(--sideBar-profile-bg)] py-[1em]">
|
|
||||||
<img
|
|
||||||
src="/images/monkey.png"
|
|
||||||
alt="profile picture"
|
|
||||||
className="w-[3em] h-[3em] rounded-full border-[0.15em] border-purple-500 cursor-pointer"
|
|
||||||
onClick={() => navigate(`/user/${username}`)}
|
|
||||||
/>
|
|
||||||
<div className="text-center flex flex-col items-center justify-center">
|
|
||||||
<h5 className="font-thin text-[0.85rem] cursor-default text-[var(--sideBar-profile-text)]">
|
|
||||||
Logged in as
|
|
||||||
</h5>
|
|
||||||
<button
|
|
||||||
className="font-black text-[1.4rem] hover:underline"
|
|
||||||
onClick={() => navigate(`/user/${username}`)}
|
|
||||||
>
|
|
||||||
<div className="text-[var(--sideBar-profile-text)]">
|
|
||||||
{username}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Following Section */}
|
|
||||||
<div
|
|
||||||
id="following"
|
|
||||||
className="flex flex-col flex-grow justify-evenly p-4 gap-4"
|
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="bg-[var(--follow-bg)] rounded-[1em] hover:scale-105 transition-all ease-in-out duration-300"
|
id="followed-users"
|
||||||
onMouseEnter={(e) =>
|
className={`grid grid-cols-2 gap-4 p-4 w-full`}>
|
||||||
(e.currentTarget.style.boxShadow = "var(--follow-shadow)")
|
{followedStreamers.map((streamer: any) => (
|
||||||
}
|
|
||||||
onMouseLeave={(e) => (e.currentTarget.style.boxShadow = "none")}
|
|
||||||
>
|
|
||||||
<h1 className="text-[2vw] font-bold text-2xl p-[0.75rem] cursor-default">
|
|
||||||
Following
|
|
||||||
</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Streamers Followed */}
|
|
||||||
<div
|
<div
|
||||||
id="streamers-followed"
|
|
||||||
className="flex flex-col flex-grow items-center"
|
|
||||||
>
|
|
||||||
<h2 className="border-b-4 border-t-4 w-[125%] text-2xl cursor-default">
|
|
||||||
Streamers
|
|
||||||
</h2>
|
|
||||||
<div className="flex flex-col flex-grow justify-evenly w-full">
|
|
||||||
{followedStreamers.map((streamer) => (
|
|
||||||
<button
|
|
||||||
key={`streamer-${streamer.username}`}
|
key={`streamer-${streamer.username}`}
|
||||||
className="cursor-pointer bg-black w-full py-2 border border-[--text-color] rounded-lg text-white hover:text-purple-500 transition-colors"
|
className="cursor-pointer bg-black w-full py-2 border border-[--text-color] rounded-lg text-white hover:text-purple-500 font-bold transition-colors"
|
||||||
onClick={() => navigate(`/user/${streamer.username}`)}
|
/*onClick={() => navigate(`/user/${streamer.username}`)}*/
|
||||||
>
|
>
|
||||||
{streamer.username}
|
{streamer.username}
|
||||||
</button>
|
<FollowUserButton
|
||||||
|
user={{
|
||||||
|
user_id: streamer.user_id,
|
||||||
|
username: streamer.username,
|
||||||
|
isFollowing: followingStatus[streamer.user_id] || true,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</DynamicPageContent>
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,30 +1,29 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import ListRow from "../components/Layout/ListRow";
|
import ListRow from "../components/Layout/ListRow";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useStreams, useCategories } from "../hooks/useContent";
|
import { useStreams, useCategories, useVods } from "../hooks/useContent";
|
||||||
import Button from "../components/Input/Button";
|
import Button from "../components/Input/Button";
|
||||||
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
import DynamicPageContent from "../components/Layout/DynamicPageContent";
|
||||||
import LoadingScreen from "../components/Layout/LoadingScreen";
|
import LoadingScreen from "../components/Layout/LoadingScreen";
|
||||||
import Footer from "../components/Layout/Footer";
|
import Footer from "../components/Layout/Footer";
|
||||||
|
|
||||||
|
|
||||||
interface HomePageProps {
|
interface HomePageProps {
|
||||||
variant?: "default" | "personalised";
|
variant?: "default" | "personalised";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
|
const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
|
||||||
const { streams, isLoading: isLoadingStreams } = useStreams();
|
const { streams, isLoading: isLoadingStreams } = useStreams();
|
||||||
const { categories, isLoading: isLoadingCategories } = useCategories();
|
const { categories, isLoading: isLoadingCategories } = useCategories();
|
||||||
|
const { vods, isLoading: isLoadingVods } = useVods(); // Fetch VODs
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const handleStreamClick = (streamerName: string) => {
|
const handleVodClick = (vodUrl: string) => {
|
||||||
window.location.href = `/${streamerName}`;
|
window.open(vodUrl, "_blank"); // Open VOD in new tab
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCategoryClick = (categoryName: string) => {
|
if (isLoadingStreams || isLoadingCategories || isLoadingVods)
|
||||||
navigate(`/category/${categoryName}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isLoadingStreams || isLoadingCategories)
|
|
||||||
return <LoadingScreen>Loading Content...</LoadingScreen>;
|
return <LoadingScreen>Loading Content...</LoadingScreen>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -33,51 +32,46 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
|
|||||||
className="relative min-h-screen animate-moving_bg"
|
className="relative min-h-screen animate-moving_bg"
|
||||||
contentClassName="pb-[12vh]"
|
contentClassName="pb-[12vh]"
|
||||||
>
|
>
|
||||||
|
{/* Streams Section */}
|
||||||
<ListRow
|
<ListRow
|
||||||
type="stream"
|
type="stream"
|
||||||
title={
|
title="Streams - Live Now"
|
||||||
"Streams - Live Now" +
|
description="Popular streamers that are currently live!"
|
||||||
(variant === "personalised" ? " - Recommended" : "")
|
|
||||||
}
|
|
||||||
description={
|
|
||||||
variant === "personalised"
|
|
||||||
? "We think you might like these streams - Streamers recommended for you"
|
|
||||||
: "Popular streamers that are currently live!"
|
|
||||||
}
|
|
||||||
items={streams}
|
items={streams}
|
||||||
wrap={false}
|
wrap={false}
|
||||||
onItemClick={handleStreamClick}
|
onItemClick={(streamerName) => navigate(`/${streamerName}`)}
|
||||||
extraClasses="bg-[var(--liveNow)]"
|
extraClasses="bg-[var(--liveNow)]"
|
||||||
itemExtraClasses="w-[20vw]"
|
itemExtraClasses="w-[20vw]"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* If Personalised_HomePage, display Categories the logged-in user follows. Else, trending categories. */}
|
{/* Categories Section */}
|
||||||
<ListRow
|
<ListRow
|
||||||
type="category"
|
type="category"
|
||||||
title={
|
title="Trending Categories"
|
||||||
variant === "personalised"
|
description="Recently popular categories lately!"
|
||||||
? "Followed Categories"
|
|
||||||
: "Trending Categories"
|
|
||||||
}
|
|
||||||
description={
|
|
||||||
variant === "personalised"
|
|
||||||
? "Current streams from your followed categories"
|
|
||||||
: "Recently popular categories lately!"
|
|
||||||
}
|
|
||||||
items={categories}
|
items={categories}
|
||||||
wrap={false}
|
wrap={false}
|
||||||
onItemClick={handleCategoryClick}
|
onItemClick={(categoryName) => navigate(`/category/${categoryName}`)}
|
||||||
titleClickable={true}
|
titleClickable={true}
|
||||||
extraClasses="bg-[var(--recommend)]"
|
extraClasses="bg-[var(--recommend)]"
|
||||||
itemExtraClasses="w-[20vw]"
|
itemExtraClasses="w-[20vw]"
|
||||||
>
|
>
|
||||||
<Button
|
<Button extraClasses="absolute right-10" onClick={() => navigate("/categories")}>
|
||||||
extraClasses="absolute right-10"
|
|
||||||
onClick={() => navigate("/categories")}
|
|
||||||
>
|
|
||||||
Show All
|
Show All
|
||||||
</Button>
|
</Button>
|
||||||
</ListRow>
|
</ListRow>
|
||||||
|
|
||||||
|
{/* VODs Section */}
|
||||||
|
<ListRow
|
||||||
|
type="vod"
|
||||||
|
title="Recent VODs"
|
||||||
|
description="Watch the latest recorded streams!"
|
||||||
|
items={vods}
|
||||||
|
wrap={false}
|
||||||
|
onItemClick={handleVodClick}
|
||||||
|
extraClasses="bg-black/50"
|
||||||
|
itemExtraClasses="w-[20vw]"
|
||||||
|
/>
|
||||||
<Footer />
|
<Footer />
|
||||||
</DynamicPageContent>
|
</DynamicPageContent>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ const UserPage: React.FC = () => {
|
|||||||
}, [username]);
|
}, [username]);
|
||||||
|
|
||||||
if (!profileData) return <LoadingScreen />;
|
if (!profileData) return <LoadingScreen />;
|
||||||
|
console.log(isUser)
|
||||||
return (
|
return (
|
||||||
<DynamicPageContent
|
<DynamicPageContent
|
||||||
className={`min-h-screen text-white flex flex-col`}
|
className={`min-h-screen text-white flex flex-col`}
|
||||||
|
|||||||
12
frontend/src/types/VodType.ts
Normal file
12
frontend/src/types/VodType.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export interface VodType {
|
||||||
|
type: "vod";
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
streamer: string;
|
||||||
|
datetime: string;
|
||||||
|
category: string;
|
||||||
|
length: number;
|
||||||
|
views: number;
|
||||||
|
url: string;
|
||||||
|
thumbnail: string;
|
||||||
|
}
|
||||||
@@ -93,23 +93,30 @@ http {
|
|||||||
expires -1d;
|
expires -1d;
|
||||||
}
|
}
|
||||||
|
|
||||||
#! Unused right now so the following are inaccurate locations
|
## The thumbnails location
|
||||||
# The thumbnails location
|
location ~ ^/stream/(.+)/thumbnails/(.+\.png)$ {
|
||||||
location ~ ^/stream/(.+)/thumbnails/(.+\.jpg)$ {
|
alias /stream_data/stream/$1/$2;
|
||||||
alias /stream_data/$1/thumbnails/$2;
|
|
||||||
|
|
||||||
# The thumbnails should not be cacheable
|
# The thumbnails should not be cacheable
|
||||||
expires -1d;
|
expires -1d;
|
||||||
}
|
}
|
||||||
|
|
||||||
# The vods location
|
## The vods location
|
||||||
location ~ ^/stream/(.+)/vods/(.+\.mp4)$ {
|
location ~ ^/stream/(.+)/vods/(.+\.mp4)$ {
|
||||||
alias /stream_data/$1/vods/$2;
|
alias /stream_data/vods/$1/$2;
|
||||||
|
|
||||||
# The vods should not be cacheable
|
# The vods should not be cacheable
|
||||||
expires -1d;
|
expires -1d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
## Profile pictures location
|
||||||
|
location ~ ^/user/(.+)/profile_picture$ {
|
||||||
|
alias /stream_data/profile_pictures/$1.png;
|
||||||
|
|
||||||
|
# The profile pictures should not be cacheable
|
||||||
|
expires -1d;
|
||||||
|
}
|
||||||
|
|
||||||
location ~ ^/\?token=.*$ {
|
location ~ ^/\?token=.*$ {
|
||||||
proxy_pass http://frontend:5173;
|
proxy_pass http://frontend:5173;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from utils.user_utils import get_user_id
|
|||||||
from blueprints.middleware import login_required
|
from blueprints.middleware import login_required
|
||||||
from database.database import Database
|
from database.database import Database
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from celery_tasks import update_thumbnail, combine_ts_stream
|
from celery_tasks.streaming import update_thumbnail, combine_ts_stream
|
||||||
from dateutil import parser
|
from dateutil import parser
|
||||||
from utils.path_manager import PathManager
|
from utils.path_manager import PathManager
|
||||||
import json
|
import json
|
||||||
@@ -60,7 +60,6 @@ def recommended_streams() -> list[dict]:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
user_id = session.get("user_id")
|
user_id = session.get("user_id")
|
||||||
|
|
||||||
# Get the user's most popular categories
|
# Get the user's most popular categories
|
||||||
category = get_user_preferred_category(user_id)
|
category = get_user_preferred_category(user_id)
|
||||||
streams = get_streams_based_on_category(category)
|
streams = get_streams_based_on_category(category)
|
||||||
@@ -112,7 +111,7 @@ def recommended_categories() -> list | list[dict]:
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
user_id = session.get("user_id")
|
user_id = session.get("user_id")
|
||||||
categories = get_user_category_recommendations(user_id)
|
categories = get_user_category_recommendations(1)
|
||||||
return jsonify(categories)
|
return jsonify(categories)
|
||||||
|
|
||||||
|
|
||||||
@@ -127,6 +126,18 @@ def following_categories_streams():
|
|||||||
return jsonify(streams)
|
return jsonify(streams)
|
||||||
|
|
||||||
|
|
||||||
|
@login_required
|
||||||
|
@stream_bp.route('/categories/your_categories')
|
||||||
|
def following_your_categories():
|
||||||
|
"""
|
||||||
|
Returns categories which the user followed
|
||||||
|
"""
|
||||||
|
|
||||||
|
streams = get_followed_your_categories(session.get('user_id'))
|
||||||
|
return jsonify(streams)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# User Routes
|
# User Routes
|
||||||
@stream_bp.route('/user/<string:username>/status')
|
@stream_bp.route('/user/<string:username>/status')
|
||||||
def user_live_status(username):
|
def user_live_status(username):
|
||||||
@@ -162,6 +173,17 @@ def vods(username):
|
|||||||
vods = get_user_vods(user_id)
|
vods = get_user_vods(user_id)
|
||||||
return jsonify(vods)
|
return jsonify(vods)
|
||||||
|
|
||||||
|
@stream_bp.route('/vods/all')
|
||||||
|
def get_all_vods():
|
||||||
|
"""
|
||||||
|
Returns data of all VODs by all streamers in a JSON-compatible format
|
||||||
|
"""
|
||||||
|
with Database() as db:
|
||||||
|
vods = db.fetchall("SELECT * FROM vods")
|
||||||
|
|
||||||
|
print("Fetched VODs from DB:", vods)
|
||||||
|
|
||||||
|
return jsonify(vods)
|
||||||
|
|
||||||
# RTMP Server Routes
|
# RTMP Server Routes
|
||||||
|
|
||||||
@@ -187,7 +209,7 @@ def init_stream():
|
|||||||
|
|
||||||
# Create necessary directories
|
# Create necessary directories
|
||||||
username = user_info["username"]
|
username = user_info["username"]
|
||||||
create_local_directories(username)
|
create_user_directories(username)
|
||||||
|
|
||||||
return redirect(f"/stream/{username}")
|
return redirect(f"/stream/{username}")
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ from utils.auth import *
|
|||||||
from utils.utils import get_category_id
|
from utils.utils import get_category_id
|
||||||
from blueprints.middleware import login_required
|
from blueprints.middleware import login_required
|
||||||
from utils.email import send_email, forgot_password_body, newsletter_conf
|
from utils.email import send_email, forgot_password_body, newsletter_conf
|
||||||
|
from utils.path_manager import PathManager
|
||||||
|
from celery_tasks.streaming import convert_image_to_png
|
||||||
import redis
|
import redis
|
||||||
|
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
@@ -14,6 +16,8 @@ r = redis.from_url(redis_url, decode_responses=True)
|
|||||||
|
|
||||||
user_bp = Blueprint("user", __name__)
|
user_bp = Blueprint("user", __name__)
|
||||||
|
|
||||||
|
path_manager = PathManager()
|
||||||
|
|
||||||
@user_bp.route('/user/<string:username>')
|
@user_bp.route('/user/<string:username>')
|
||||||
def user_data(username: str):
|
def user_data(username: str):
|
||||||
"""
|
"""
|
||||||
@@ -42,13 +46,19 @@ def user_profile_picture_save():
|
|||||||
"""
|
"""
|
||||||
Saves user profile picture
|
Saves user profile picture
|
||||||
"""
|
"""
|
||||||
user_id = session.get("user_id")
|
username = session.get("username")
|
||||||
image = request.files['image']
|
thumbnail_path = path_manager.get_profile_picture_file_path(username)
|
||||||
ext = image.filename.split('.')[-1]
|
|
||||||
|
|
||||||
image.save(f"/web_server/stream_data/{user_id}.{ext}")
|
# Check if the post request has the file part
|
||||||
|
if 'image' not in request.files:
|
||||||
|
return jsonify({"error": "No image found in request"}), 400
|
||||||
|
|
||||||
return "Success", 200
|
# Fetch image, convert to png, and save
|
||||||
|
image = Image.open(request.files['image'])
|
||||||
|
image.convert('RGB')
|
||||||
|
image.save(thumbnail_path, "PNG")
|
||||||
|
|
||||||
|
return jsonify({"message": "Profile picture saved"})
|
||||||
|
|
||||||
@login_required
|
@login_required
|
||||||
@user_bp.route('/user/same/<string:username>')
|
@user_bp.route('/user/same/<string:username>')
|
||||||
|
|||||||
@@ -1,10 +1,4 @@
|
|||||||
from celery import Celery, shared_task, Task
|
from celery import Celery, shared_task, Task
|
||||||
from utils.stream_utils import generate_thumbnail, get_streamer_live_status
|
|
||||||
from time import sleep
|
|
||||||
from os import listdir, remove
|
|
||||||
from datetime import datetime
|
|
||||||
from celery_tasks.preferences import user_preferences
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
def celery_init_app(app) -> Celery:
|
def celery_init_app(app) -> Celery:
|
||||||
class FlaskTask(Task):
|
class FlaskTask(Task):
|
||||||
@@ -23,53 +17,3 @@ def celery_init_app(app) -> Celery:
|
|||||||
celery_app.set_default()
|
celery_app.set_default()
|
||||||
app.extensions["celery"] = celery_app
|
app.extensions["celery"] = celery_app
|
||||||
return celery_app
|
return celery_app
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
|
||||||
def update_thumbnail(user_id, stream_file, thumbnail_file, sleep_time) -> None:
|
|
||||||
"""
|
|
||||||
Updates the thumbnail of a stream periodically
|
|
||||||
"""
|
|
||||||
|
|
||||||
if get_streamer_live_status(user_id)['is_live']:
|
|
||||||
print("Updating thumbnail...")
|
|
||||||
generate_thumbnail(stream_file, thumbnail_file)
|
|
||||||
update_thumbnail.apply_async((user_id, stream_file, thumbnail_file, sleep_time), countdown=sleep_time)
|
|
||||||
else:
|
|
||||||
print("Stream has ended, stopping thumbnail updates")
|
|
||||||
|
|
||||||
@shared_task
|
|
||||||
def combine_ts_stream(stream_path, vods_path, vod_file_name):
|
|
||||||
"""
|
|
||||||
Combines all ts files into a single vod, and removes the ts files
|
|
||||||
"""
|
|
||||||
ts_files = [f for f in listdir(stream_path) if f.endswith(".ts")]
|
|
||||||
ts_files.sort()
|
|
||||||
|
|
||||||
# Create temp file listing all ts files
|
|
||||||
with open(f"{stream_path}/list.txt", "w") as f:
|
|
||||||
for ts_file in ts_files:
|
|
||||||
f.write(f"file '{ts_file}'\n")
|
|
||||||
|
|
||||||
# Concatenate all ts files into a single vod
|
|
||||||
|
|
||||||
vod_command = [
|
|
||||||
"ffmpeg",
|
|
||||||
"-f",
|
|
||||||
"concat",
|
|
||||||
"-safe",
|
|
||||||
"0",
|
|
||||||
"-i",
|
|
||||||
f"{stream_path}/list.txt",
|
|
||||||
"-c",
|
|
||||||
"copy",
|
|
||||||
f"{vods_path}/{vod_file_name}.mp4"
|
|
||||||
]
|
|
||||||
|
|
||||||
subprocess.run(vod_command)
|
|
||||||
|
|
||||||
# Remove ts files
|
|
||||||
for ts_file in ts_files:
|
|
||||||
remove(f"{stream_path}/{ts_file}")
|
|
||||||
# Remove m3u8 file
|
|
||||||
remove(f"{stream_path}/index.m3u8")
|
|
||||||
71
web_server/celery_tasks/streaming.py
Normal file
71
web_server/celery_tasks/streaming.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
from celery import Celery, shared_task, Task
|
||||||
|
from datetime import datetime
|
||||||
|
from celery_tasks.preferences import user_preferences
|
||||||
|
from utils.stream_utils import generate_thumbnail, get_streamer_live_status
|
||||||
|
from time import sleep
|
||||||
|
from os import listdir, remove
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
@shared_task
|
||||||
|
def update_thumbnail(user_id, stream_file, thumbnail_file, sleep_time) -> None:
|
||||||
|
"""
|
||||||
|
Updates the thumbnail of a stream periodically
|
||||||
|
"""
|
||||||
|
|
||||||
|
if get_streamer_live_status(user_id)['is_live']:
|
||||||
|
print("Updating thumbnail...")
|
||||||
|
generate_thumbnail(stream_file, thumbnail_file)
|
||||||
|
update_thumbnail.apply_async((user_id, stream_file, thumbnail_file, sleep_time), countdown=sleep_time)
|
||||||
|
else:
|
||||||
|
print("Stream has ended, stopping thumbnail updates")
|
||||||
|
|
||||||
|
@shared_task
|
||||||
|
def combine_ts_stream(stream_path, vods_path, vod_file_name):
|
||||||
|
"""
|
||||||
|
Combines all ts files into a single vod, and removes the ts files
|
||||||
|
"""
|
||||||
|
ts_files = [f for f in listdir(stream_path) if f.endswith(".ts")]
|
||||||
|
ts_files.sort()
|
||||||
|
|
||||||
|
# Create temp file listing all ts files
|
||||||
|
with open(f"{stream_path}/list.txt", "w") as f:
|
||||||
|
for ts_file in ts_files:
|
||||||
|
f.write(f"file '{ts_file}'\n")
|
||||||
|
|
||||||
|
# Concatenate all ts files into a single vod
|
||||||
|
|
||||||
|
vod_command = [
|
||||||
|
"ffmpeg",
|
||||||
|
"-f",
|
||||||
|
"concat",
|
||||||
|
"-safe",
|
||||||
|
"0",
|
||||||
|
"-i",
|
||||||
|
f"{stream_path}/list.txt",
|
||||||
|
"-c",
|
||||||
|
"copy",
|
||||||
|
f"{vods_path}/{vod_file_name}.mp4"
|
||||||
|
]
|
||||||
|
|
||||||
|
subprocess.run(vod_command)
|
||||||
|
|
||||||
|
# Remove ts files
|
||||||
|
for ts_file in ts_files:
|
||||||
|
remove(f"{stream_path}/{ts_file}")
|
||||||
|
# Remove m3u8 file
|
||||||
|
remove(f"{stream_path}/index.m3u8")
|
||||||
|
|
||||||
|
@shared_task
|
||||||
|
def convert_image_to_png(image_path, png_path):
|
||||||
|
"""
|
||||||
|
Converts an image to a png
|
||||||
|
"""
|
||||||
|
image_command = [
|
||||||
|
"ffmpeg",
|
||||||
|
"-y",
|
||||||
|
"-i",
|
||||||
|
image_path,
|
||||||
|
png_path
|
||||||
|
]
|
||||||
|
|
||||||
|
subprocess.run(image_command)
|
||||||
Binary file not shown.
@@ -4,7 +4,29 @@ INSERT INTO users (username, password, email, num_followers, stream_key, is_part
|
|||||||
('MusicLover', 'music4life', 'musiclover@example.com', 1200, '2345', 0, 'I share my favorite tunes.', 1, 0),
|
('MusicLover', 'music4life', 'musiclover@example.com', 1200, '2345', 0, 'I share my favorite tunes.', 1, 0),
|
||||||
('ArtFan', 'artistic123', 'artfan@example.com', 300, '3456', 0, 'Exploring the world of art.', 1, 0),
|
('ArtFan', 'artistic123', 'artfan@example.com', 300, '3456', 0, 'Exploring the world of art.', 1, 0),
|
||||||
('EduGuru', 'learn123', 'eduguru@example.com', 800, '4567', 0, 'Teaching everything I know.', 1, 0),
|
('EduGuru', 'learn123', 'eduguru@example.com', 800, '4567', 0, 'Teaching everything I know.', 1, 0),
|
||||||
('SportsStar', 'sports123', 'sportsstar@example.com', 2000, '5678', 0, 'Join me for live sports updates!', 1, 0);
|
('SportsStar', 'sports123', 'sportsstar@example.com', 2000, '5678', 0, 'Join me for live sports updates!', 1, 0),
|
||||||
|
('TechEnthusiast', NULL, 'techenthusiast@example.com', 1500, '6789', 0, 'All about the latest tech news!', 1, 0),
|
||||||
|
('ChefMaster', NULL, 'chefmaster@example.com', 700, '7890', 0, 'Cooking live and sharing recipes.', 1, 0),
|
||||||
|
('TravelExplorer', NULL, 'travelexplorer@example.com', 900, '8901', 0, 'Exploring new places every day!', 1, 0),
|
||||||
|
('BookLover', NULL, 'booklover@example.com', 450, '9012', 0, 'Sharing my thoughts on every book I read.', 1, 0),
|
||||||
|
('FitnessFan', NULL, 'fitnessfan@example.com', 1300, '0123', 0, 'Join my fitness journey!', 1, 0),
|
||||||
|
('NatureLover', NULL, 'naturelover@example.com', 1100, '2346', 0, 'Live streaming nature walks and hikes.', 1, 0),
|
||||||
|
('MovieBuff', NULL, 'moviebuff@example.com', 800, '3457', 0, 'Sharing movie reviews and recommendations.', 1, 0),
|
||||||
|
('ScienceGeek', NULL, 'sciencegeek@example.com', 950, '4568', 0, 'Exploring the wonders of science.', 1, 0),
|
||||||
|
('Comedian', NULL, 'comedian@example.com', 650, '5679', 0, 'Bringing laughter with live stand-up comedy.', 1, 0),
|
||||||
|
('Fashionista', NULL, 'fashionista@example.com', 1200, '6780', 0, 'Join me for live fashion tips and trends.', 1, 0),
|
||||||
|
('HealthGuru', NULL, 'healthguru@example.com', 1400, '7891', 0, 'Live streaming health and wellness advice.', 1, 0),
|
||||||
|
('CarLover', NULL, 'carlove@example.com', 1700, '8902', 0, 'Streaming car reviews and automotive content.', 1, 0),
|
||||||
|
('PetLover', NULL, 'petlover@example.com', 1000, '9013', 0, 'Join me for fun and cute pet moments!', 1, 0),
|
||||||
|
('Dancer', NULL, 'dancer@example.com', 2000, '0124', 0, 'Sharing live dance performances.', 1, 0),
|
||||||
|
('Photographer', NULL, 'photographer@example.com', 1300, '1235', 0, 'Live streaming photography tutorials.', 1, 0),
|
||||||
|
('Motivator', NULL, 'motivator@example.com', 850, '2347', 0, 'Join me for daily motivation and positivity.', 1, 0),
|
||||||
|
('LanguageLearner', NULL, 'languagelearner@example.com', 950, '3458', 0, 'Live streaming language learning sessions.', 1, 0),
|
||||||
|
('HistoryBuff', NULL, 'historybuff@example.com', 750, '4569', 0, 'Exploring history live and in depth.', 1, 0),
|
||||||
|
('Blogger', NULL, 'blogger@example.com', 1200, '5670', 0, 'Sharing my experiences through live blogging.', 1, 0),
|
||||||
|
('DIYer', NULL, 'diyer@example.com', 1300, '6781', 0, 'Live streaming DIY projects and tutorials.', 1, 0),
|
||||||
|
('SportsAnalyst', NULL, 'sportsanalyst@example.com', 1400, '7892', 0, 'Live commentary and analysis on sports events.', 1, 0),
|
||||||
|
('LBozo', NULL, 'lbozo@example.com', 0, '250', 0, 'I like taking Ls.', 1, 0);
|
||||||
|
|
||||||
INSERT INTO users (username, password, email, num_followers, stream_key, is_partnered, bio, is_live, is_admin) VALUES
|
INSERT INTO users (username, password, email, num_followers, stream_key, is_partnered, bio, is_live, is_admin) VALUES
|
||||||
('GamerDude2', 'password123', 'gamerdude3@gmail.com', 3200, '7890', 0, 'Streaming my gaming adventures!', 0, 0),
|
('GamerDude2', 'password123', 'gamerdude3@gmail.com', 3200, '7890', 0, 'Streaming my gaming adventures!', 0, 0),
|
||||||
@@ -36,6 +58,7 @@ INSERT INTO subscribes (user_id, subscribed_id, since, expires) VALUES
|
|||||||
(4, 5, '2024-09-12', '2025-01-12'),
|
(4, 5, '2024-09-12', '2025-01-12'),
|
||||||
(5, 1, '2024-08-30', '2025-02-28');
|
(5, 1, '2024-08-30', '2025-02-28');
|
||||||
|
|
||||||
|
|
||||||
-- Sample Data for followed_categories
|
-- Sample Data for followed_categories
|
||||||
INSERT INTO followed_categories (user_id, category_id) VALUES
|
INSERT INTO followed_categories (user_id, category_id) VALUES
|
||||||
(1, 1),
|
(1, 1),
|
||||||
@@ -83,7 +106,29 @@ INSERT INTO streams (user_id, title, start_time, category_id) VALUES
|
|||||||
(2, 'Live Music Jam', '2025-01-25 20:00:00', 2),
|
(2, 'Live Music Jam', '2025-01-25 20:00:00', 2),
|
||||||
(3, 'Sketching Live', '2025-01-24 15:00:00', 3),
|
(3, 'Sketching Live', '2025-01-24 15:00:00', 3),
|
||||||
(4, 'Math Made Easy', '2025-01-23 10:00:00', 4),
|
(4, 'Math Made Easy', '2025-01-23 10:00:00', 4),
|
||||||
(5, 'Sports Highlights', '2025-02-15 23:00:00', 5);
|
(5, 'Sports Highlights', '2025-02-15 23:00:00', 5),
|
||||||
|
(6, 'Genshin1', '2025-02-17 18:00:00', 6),
|
||||||
|
(7, 'Genshin2', '2025-02-18 19:00:00', 7),
|
||||||
|
(8, 'Genshin3', '2025-02-19 20:00:00', 8),
|
||||||
|
(9, 'Genshin4', '2025-02-20 14:00:00', 9),
|
||||||
|
(10, 'Genshin5', '2025-02-21 09:00:00', 10),
|
||||||
|
(11, 'Genshin6', '2025-02-22 11:00:00', 11),
|
||||||
|
(12, 'Genshin7', '2025-02-23 21:00:00', 12),
|
||||||
|
(13, 'Genshin8', '2025-02-24 16:00:00', 13),
|
||||||
|
(14, 'Genshin9', '2025-02-25 22:00:00', 14),
|
||||||
|
(15, 'Genshin10', '2025-02-26 18:30:00', 15),
|
||||||
|
(16, 'Genshin11', '2025-02-27 17:00:00', 16),
|
||||||
|
(17, 'Genshin12', '2025-02-28 15:00:00', 17),
|
||||||
|
(18, 'Genshin13', '2025-03-01 10:00:00', 18),
|
||||||
|
(19, 'Genshin14', '2025-03-02 20:00:00', 19),
|
||||||
|
(20, 'Genshin15', '2025-03-03 13:00:00', 20),
|
||||||
|
(21, 'Genshin16', '2025-03-04 09:00:00', 21),
|
||||||
|
(22, 'Genshin17', '2025-03-05 12:00:00', 22),
|
||||||
|
(23, 'Genshin18', '2025-03-06 14:00:00', 23),
|
||||||
|
(24, 'Genshin19', '2025-03-07 16:00:00', 24),
|
||||||
|
(25, 'Genshin20', '2025-03-08 19:00:00', 25),
|
||||||
|
(26, 'Genshin21', '2025-03-09 21:00:00', 26),
|
||||||
|
(27, 'Genshin22', '2025-03-10 17:00:00', 27);
|
||||||
|
|
||||||
-- Sample Data for vods
|
-- Sample Data for vods
|
||||||
INSERT INTO vods (user_id, title, datetime, category_id, length, views) VALUES
|
INSERT INTO vods (user_id, title, datetime, category_id, length, views) VALUES
|
||||||
|
|||||||
@@ -1,20 +1,52 @@
|
|||||||
|
import os
|
||||||
# Description: This file contains the PathManager class which is responsible for managing the paths of the stream data.
|
# Description: This file contains the PathManager class which is responsible for managing the paths of the stream data.
|
||||||
|
|
||||||
class PathManager():
|
class PathManager():
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.root_path = "stream_data"
|
||||||
|
self.vods_path = os.path.join(self.root_path, "vods")
|
||||||
|
self.stream_path = os.path.join(self.root_path, "stream")
|
||||||
|
self.profile_pictures_path = os.path.join(self.root_path, "profile_pictures")
|
||||||
|
|
||||||
|
self._create_root_directories()
|
||||||
|
|
||||||
|
def _create_directory(self, path):
|
||||||
|
"""
|
||||||
|
Create a directory if it does not exist
|
||||||
|
"""
|
||||||
|
if not os.path.exists(path):
|
||||||
|
os.makedirs(path)
|
||||||
|
os.chmod(path, 0o777)
|
||||||
|
|
||||||
|
def _create_root_directories(self):
|
||||||
|
"""
|
||||||
|
Create directories for stream data if they do not exist
|
||||||
|
"""
|
||||||
|
self._create_directory(self.root_path)
|
||||||
|
self._create_directory(self.vods_path)
|
||||||
|
self._create_directory(self.stream_path)
|
||||||
|
self._create_directory(self.profile_pictures_path)
|
||||||
|
|
||||||
def get_vods_path(self, username):
|
def get_vods_path(self, username):
|
||||||
return f"stream_data/vods/{username}"
|
return os.path.join(self.vods_path, username)
|
||||||
|
|
||||||
def get_stream_path(self, username):
|
def get_stream_path(self, username):
|
||||||
return f"stream_data/stream/{username}"
|
return os.path.join(self.stream_path, username)
|
||||||
|
|
||||||
def get_stream_file_path(self, username):
|
def get_stream_file_path(self, username):
|
||||||
return f"{self.get_stream_path(username)}/index.m3u8"
|
return os.path.join(self.get_stream_path(username), "index.m3u8")
|
||||||
|
|
||||||
def get_current_stream_thumbnail_file_path(self, username):
|
def get_current_stream_thumbnail_file_path(self, username):
|
||||||
return f"{self.get_stream_path(username)}/index.jpg"
|
return os.path.join(self.get_stream_path(username), "index.png")
|
||||||
|
|
||||||
def get_vod_file_path(self, username, vod_id):
|
def get_vod_file_path(self, username, vod_id):
|
||||||
return f"{self.get_vods_path(username)}/{vod_id}.mp4"
|
return os.path.join(self.get_vods_path(username), f"{vod_id}.mp4")
|
||||||
|
|
||||||
def get_vod_thumbnail_file_path(self, username, vod_id):
|
def get_vod_thumbnail_file_path(self, username, vod_id):
|
||||||
return f"{self.get_vods_path(username)}/{vod_id}.jpg"
|
return os.path.join(self.get_vods_path(username), f"{vod_id}.png")
|
||||||
|
|
||||||
|
def get_profile_picture_file_path(self, username):
|
||||||
|
return os.path.join(self.profile_pictures_path, f"{username}.png")
|
||||||
|
|
||||||
|
def get_profile_picture_path(self):
|
||||||
|
return self.profile_pictures_path
|
||||||
@@ -33,6 +33,20 @@ def get_followed_categories_recommendations(user_id: int, no_streams: int = 4) -
|
|||||||
""", (user_id, no_streams))
|
""", (user_id, no_streams))
|
||||||
return streams
|
return streams
|
||||||
|
|
||||||
|
def get_followed_your_categories(user_id: int) -> Optional[List[dict]]:
|
||||||
|
"""
|
||||||
|
Returns all user followed categories
|
||||||
|
"""
|
||||||
|
with Database() as db:
|
||||||
|
categories = db.fetchall("""
|
||||||
|
SELECT categories.category_name
|
||||||
|
FROM categories
|
||||||
|
JOIN followed_categories
|
||||||
|
ON categories.category_id = followed_categories.category_id
|
||||||
|
WHERE followed_categories.user_id = ?;
|
||||||
|
""", (user_id,))
|
||||||
|
return categories
|
||||||
|
|
||||||
|
|
||||||
def get_streams_based_on_category(category_id: int, no_streams: int = 4, offset: int = 0) -> Optional[List[dict]]:
|
def get_streams_based_on_category(category_id: int, no_streams: int = 4, offset: int = 0) -> Optional[List[dict]]:
|
||||||
"""
|
"""
|
||||||
@@ -81,7 +95,7 @@ def get_highest_view_categories(no_categories: int = 4, offset: int = 0) -> Opti
|
|||||||
""", (no_categories, offset))
|
""", (no_categories, offset))
|
||||||
return categories
|
return categories
|
||||||
|
|
||||||
def get_user_category_recommendations(user_id: int, no_categories: int = 4) -> Optional[List[dict]]:
|
def get_user_category_recommendations(user_id: 1, no_categories: int = 4) -> Optional[List[dict]]:
|
||||||
"""
|
"""
|
||||||
Queries user_preferences database to find users top favourite streaming category and returns the category
|
Queries user_preferences database to find users top favourite streaming category and returns the category
|
||||||
"""
|
"""
|
||||||
@@ -90,8 +104,8 @@ def get_user_category_recommendations(user_id: int, no_categories: int = 4) -> O
|
|||||||
SELECT categories.category_id, categories.category_name
|
SELECT categories.category_id, categories.category_name
|
||||||
FROM categories
|
FROM categories
|
||||||
JOIN user_preferences ON categories.category_id = user_preferences.category_id
|
JOIN user_preferences ON categories.category_id = user_preferences.category_id
|
||||||
WHERE user_id = ?
|
WHERE user_preferences.user_id = ?
|
||||||
ORDER BY favourability DESC
|
ORDER BY user_preferences.favourability DESC
|
||||||
LIMIT ?
|
LIMIT ?
|
||||||
""", (user_id, no_categories))
|
""", (user_id, no_categories))
|
||||||
return categories
|
return categories
|
||||||
@@ -84,6 +84,14 @@ def get_user_vods(user_id: int):
|
|||||||
vods = db.fetchall("""SELECT * FROM vods WHERE user_id = ?;""", (user_id,))
|
vods = db.fetchall("""SELECT * FROM vods WHERE user_id = ?;""", (user_id,))
|
||||||
return vods
|
return vods
|
||||||
|
|
||||||
|
def get_all_vods():
|
||||||
|
"""
|
||||||
|
Returns data of all VODs by all streamers in a JSON-compatible format
|
||||||
|
"""
|
||||||
|
with Database() as db:
|
||||||
|
vods = db.fetchall("""SELECT * FROM vods""")
|
||||||
|
return vods
|
||||||
|
|
||||||
def generate_thumbnail(stream_file: str, thumbnail_file: str, retry_time=5, retry_count=3) -> None:
|
def generate_thumbnail(stream_file: str, thumbnail_file: str, retry_time=5, retry_count=3) -> None:
|
||||||
"""
|
"""
|
||||||
Generates the thumbnail of a stream
|
Generates the thumbnail of a stream
|
||||||
@@ -143,7 +151,7 @@ def get_vod_tags(vod_id: int):
|
|||||||
""", (vod_id,))
|
""", (vod_id,))
|
||||||
return tags
|
return tags
|
||||||
|
|
||||||
def create_local_directories(username: str):
|
def create_user_directories(username: str):
|
||||||
"""
|
"""
|
||||||
Create directories for user stream data if they do not exist
|
Create directories for user stream data if they do not exist
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user