This commit is contained in:
zadit
2024-11-16 23:44:48 +07:00
parent bea0ff63d7
commit b8c1d30d14
26 changed files with 1841 additions and 799 deletions

View File

@@ -3,7 +3,7 @@ import API_BASE_URL from "../config.js";
import "./MusicPlayer.css";
import MusicComponent from "./MusicComponent";
export function MusicPlayer({ socket, shopId, user, isSpotifyNeedLogin }) {
export function MusicPlayer({ socket, shopId, user, shopOwnerId, isSpotifyNeedLogin, queue }) {
const [currentTime, setCurrentTime] = useState(0);
const [trackLength, setTrackLength] = useState(0);
const [viewing, setViewing] = useState(false); // State for expansion
@@ -13,7 +13,6 @@ export function MusicPlayer({ socket, shopId, user, isSpotifyNeedLogin }) {
const [debouncedSongName, setDebouncedSongName] = useState(songName);
const [currentSong, setCurrentSong] = useState([]);
const [songs, setSongs] = useState([]);
const [queue, setQueue] = useState([]);
const [paused, setPaused] = useState([]);
const [lyrics, setLyrics] = useState([]);
@@ -111,6 +110,11 @@ export function MusicPlayer({ socket, shopId, user, isSpotifyNeedLogin }) {
fetchColor();
}, [currentSong]);
const convertToMilliseconds = (timeStr) => {
const [minutes, seconds] = timeStr.split(':').map(Number);
return (minutes * 60 + seconds) * 1000;
};
useEffect(() => {
if (!socket) return;
@@ -123,13 +127,9 @@ export function MusicPlayer({ socket, shopId, user, isSpotifyNeedLogin }) {
setCurrentSong(response);
setCurrentTime(response.progress_ms / 1000); // Convert milliseconds to seconds
setLyricProgressMs(response.progress_ms);
setTrackLength(response.item.duration_ms / 1000);
setTrackLength(convertToMilliseconds(response.item.length));
});
socket.on("updateQueue", (response) => {
setQueue(response);
console.log(response);
});
socket.on("updatePlayer", (response) => {
setPaused(response.decision);
@@ -149,42 +149,61 @@ export function MusicPlayer({ socket, shopId, user, isSpotifyNeedLogin }) {
socket.off("searchResponse");
};
}, [socket]);
// useEffect for setting up the socket listener
useEffect(() => {
const handleUpdateCanvas = (response) => {
if (response && response !== canvaz) {
console.log(response);
console.log(canvaz);
setCanvaz(response);
fetch(response)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(blob);
setVideoSrc(blobUrl);
if (videoRef.current) {
videoRef.current.load(); // Reload the video element
}
})
.catch((error) => console.error('Error loading video:', error));
} else if (!response) {
// Clear the video source if response is empty
setVideoSrc('');
if (videoRef.current) {
videoRef.current.load(); // Reload the video element
// useEffect for setting up the socket listener
useEffect(() => {
const handleUpdateCanvas = (response) => {
if (response && response !== canvaz) {
console.log(response);
console.log(canvaz);
setCanvaz(response);
fetch(response)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(blob);
setVideoSrc(blobUrl);
if (videoRef.current) {
videoRef.current.load(); // Reload the video element
}
})
.catch((error) => console.error('Error loading video:', error));
} else if (!response) {
// Clear the video source if response is empty
setVideoSrc('');
if (videoRef.current) {
videoRef.current.load(); // Reload the video element
}
}
}
};
};
// Listen for the "updateCanvas" event
socket.on("updateCanvas", handleUpdateCanvas);
// Listen for the "updateCanvas" event
socket.on("updateCanvas", handleUpdateCanvas);
// Clean up the socket listener when the component is unmounted
return () => {
socket.off("updateCanvas", handleUpdateCanvas);
};
}, [socket, canvaz]);
socket.on("claimPlayerRes", (response) => {
if (response.error) {
console.log('Error:', response.error);
// Handle error
} else {
window.open(response.url);
}
});
socket.on("unClaimPlayerRes", (response) => {
if (response.error) {
console.log('Error:', response.error);
// Handle error
} else {
console.log('Player token:', response.token);
// Handle success and use the player token
}
});
// Clean up the socket listener when the component is unmounted
return () => {
socket.off("updateCanvas", handleUpdateCanvas);
};
}, [socket, canvaz]);
useEffect(() => {
// Simulate progress every 100ms
@@ -235,10 +254,10 @@ useEffect(() => {
setSongName(event.target.value);
};
const onRequest = (trackId) => {
const onRequest = (track) => {
const token = localStorage.getItem("auth");
if (socket != null && token) {
socket.emit("songRequest", { token, shopId, trackId });
socket.emit("songRequest", { token, shopId, track });
setSongName("");
}
};
@@ -262,19 +281,20 @@ useEffect(() => {
}
};
const handleSpotifyAuth = () => {
const handleSetPlayer = () => {
const token = localStorage.getItem("auth");
let nextUrl = ""; // Use 'let' since the value will change
if (isSpotifyNeedLogin) {
nextUrl = API_BASE_URL + `/login?token=${token}&cafeId=${shopId}`;
} else {
nextUrl = API_BASE_URL + `/logout?token=${token}&cafeId=${shopId}`;
}
window.location.href = nextUrl;
};
const handleLogin = () => {
// navigate(`/login/${shopId}`);
if (isSpotifyNeedLogin) {
socket.emit("claimPlayer", {
token,
shopId,
});
} else {
socket.emit("unClaimPlayer", {
token,
shopId,
});
}
};
useEffect(() => {
@@ -354,7 +374,7 @@ useEffect(() => {
<div
onClick={toggleView}
className="current-bgr"
style={{ backgroundImage: `url(${videoSrc != ""? '':backgroundImage})` }}
style={{ backgroundImage: `url(${videoSrc != "" ? '' : backgroundImage})` }}
>
<video
ref={videoRef}
@@ -362,7 +382,7 @@ useEffect(() => {
loop
playsInline
muted
style={{ height: '100%', width: '100%', objectFit: 'cover', position:'absolute', top:0,right:0,zIndex:-1}}
style={{ height: '100%', width: '100%', objectFit: 'cover', position: 'absolute', top: 0, right: 0, zIndex: -1 }}
>
{videoSrc && <source src={videoSrc} type="video/mp4" />}
</video>
@@ -432,14 +452,14 @@ useEffect(() => {
className={`expandable-container ${expanded ? "expanded" : ""}`}
ref={expandableContainerRef}
>
{user.cafeId != null && user.cafeId == shopId && (
{user.cafeId == shopId || user.userId == shopOwnerId && (
<div className="auth-box">
<input
type="text"
placeholder={
isSpotifyNeedLogin ? "Login Spotify" : "Logout Spotify"
isSpotifyNeedLogin ? "Set as music player" : "Unset as music player"
}
onClick={handleSpotifyAuth}
onClick={handleSetPlayer}
/>
</div>
)}
@@ -466,20 +486,25 @@ useEffect(() => {
song={song}
min={0}
max={100}
onDecision={(e) => onRequest(song.trackId)}
/>
))}
{songName == "" &&
queue.length > 0 &&
queue.map((song, index) => (
<MusicComponent
key={index}
song={song}
min={-100}
max={100}
onDecision={(vote) => onDecision(song.trackId, vote)}
onDecision={(e) => onRequest(song)}
/>
))}
{
songName === "" &&
queue &&
Array.isArray(queue) &&
queue.length > 0 && (
queue.map((song, index) => (
<MusicComponent
key={index}
song={song}
min={-100}
max={100}
onDecision={(vote) => onDecision(song.trackId, vote)}
/>
))
)
}
{songName == "" && queue.length < 1 && (
<div className="rectangle">
<div className="diagonal-text">No Beats Ahead - Drop Your Hits</div>