Skip to content

Commit

Permalink
ver2
Browse files Browse the repository at this point in the history
  • Loading branch information
alaneelee committed Jan 8, 2024
2 parents 2204dea + 25e0594 commit 6704239
Show file tree
Hide file tree
Showing 15 changed files with 230 additions and 183 deletions.
2 changes: 2 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
REACT_APP_API_URL = http://localhost:8081
REACT_APP_CHAT_URL = ws://localhost:8082/chat
2 changes: 2 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
REACT_APP_API_URL = https://api.lemonair.me
REACT_APP_CHAT_URL = wss://chat.lemonair.me/chat
21 changes: 17 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.2",
"dotenv": "^16.3.1",
"hls.js": "^1.4.14",
"http-proxy-middleware": "^2.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-player": "^2.14.0",
Expand Down
4 changes: 2 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import "./App.css";
import Router from "./shared/Router";
import './App.css';
import Router from './shared/Router';

const App = () => {
return <Router />;
Expand Down
90 changes: 71 additions & 19 deletions src/components/Chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ const InputContainer = styled.div`
justify-content: center;
`;

const NotLoginInputContainer = styled.div`
margin-top: auto;
border-top: 1px solid #333333;
height: 8vh;
display: flex;
align-items: center;
justify-content: center;
`;

const TextInput = styled.input`
border-radius: 10px;
width: 70%;
Expand All @@ -65,19 +74,29 @@ const ChatComponent = ({ chattingRoomId }) => {
const [messages, setMessages] = useState([]);
const [inputMessage, setInputMessage] = useState('');
const [socket, setSocket] = useState(null);
const [socketIntervalId, setSocketIntervalId] = useState(null);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const messagesEndRef = useRef(null);

const chattingRoomIdString = chattingRoomId;
const accessToken = localStorage.getItem('accessToken');
useEffect(() => {
if (accessToken) {
setIsLoggedIn(true);
}
}, [accessToken]);
const fetchToken = useCallback(async () => {
try {
console.log(accessToken);
const response = await fetch('https://api.lemonair.me/api/auth/chat', {
method: 'POST',
headers: {
Authorization: accessToken,
},
});
const response = await fetch(
`${process.env.REACT_APP_API_URL}/api/auth/chat`,
{
method: 'POST',
headers: {
Authorization: accessToken,
},
}
);
if (!response.ok) {
throw new Error('Network response was not ok.');
}
Expand All @@ -99,15 +118,20 @@ const ChatComponent = ({ chattingRoomId }) => {
chatToken = 'notlogin'; // 로그인하지 않은 사용자의 경우 토큰 정보를 notlogin으로 요청한다.
}
const newSocket = new WebSocket(
`wss://chat.lemonair.me/chat/${chattingRoomIdString}/${chatToken}`
`${process.env.REACT_APP_CHAT_URL}/${chattingRoomIdString}/${chatToken}`
);
setSocket(newSocket);
newSocket.onopen = () => {
console.log('웹소켓 연결됨');
const heartbeatInterval = setInterval(() => {
newSocket.send('heartbeat');
}, 30000);

setSocketIntervalId(heartbeatInterval);
};

newSocket.onmessage = (event) => {
console.log(event.data);
// console.log(event.data);
const receiveData = event.data.split(':');
const from = receiveData[0];
const message = receiveData.slice(1).join(':').trim();
Expand All @@ -116,6 +140,8 @@ const ChatComponent = ({ chattingRoomId }) => {

newSocket.onclose = () => {
console.log('웹소켓 연결 종료');
clearInterval(socketIntervalId);

// 연결 종료 시 재연결 시도
setTimeout(async () => {
if (accessToken) {
Expand All @@ -124,26 +150,36 @@ const ChatComponent = ({ chattingRoomId }) => {
chatToken = 'notlogin'; // 로그인하지 않은 사용자의 경우 토큰 정보를 notlogin으로 요청한다.
}
const reconnectSocket = new WebSocket(
`wss://chat.lemonair.me/chat/${chattingRoomIdString}/${chatToken}`
`${process.env.REACT_APP_CHAT_URL}/${chattingRoomIdString}/${chatToken}`
);
setSocket(reconnectSocket);

reconnectSocket.onopen = () => {
console.log('웹소켓 재연결됨');
setSocket(reconnectSocket);
const heartbeatInterval = setInterval(() => {
newSocket.send('heartbeat');
}, 30000);
setSocketIntervalId(heartbeatInterval);
};

reconnectSocket.onmessage = (event) => {
console.log(event.data);
// console.log(event.data);
const receiveData = event.data.split(':');
const from = receiveData[0];
const message = receiveData.slice(1).join(':').trim();
setMessages((prevMessages) => [...prevMessages, { from, message }]);
};

reconnectSocket.onclose = () => {
console.log('웹소켓 연결 종료');
clearInterval(socketIntervalId);
};
}, 1000); // 1초 후 재연결 시도
};
return () => {
newSocket.close();
clearInterval(socketIntervalId);
};
};

Expand All @@ -164,6 +200,11 @@ const ChatComponent = ({ chattingRoomId }) => {
};

const handleKeyDown = (event) => {
if (!isLoggedIn && event.key === 'Enter') {
setInputMessage('');
return;
}

if (event.key === 'Enter') {
event.preventDefault();
sendMessage();
Expand All @@ -181,15 +222,26 @@ const ChatComponent = ({ chattingRoomId }) => {
))}
<div ref={messagesEndRef} />
</MessageBox>
<InputContainer>
<TextInput
type='text'
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyDown={handleKeyDown}
/>
<SendButton onClick={sendMessage}>전송</SendButton>
</InputContainer>
{isLoggedIn ? (
<InputContainer>
<TextInput
type='text'
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyDown={handleKeyDown}
/>
<SendButton
onClick={sendMessage}
disabled={isLoggedIn ? false : true}
>
전송
</SendButton>
</InputContainer>
) : (
<NotLoginInputContainer>
로그인한 사용자만 채팅을 입력할 수 있습니다.
</NotLoginInputContainer>
)}
</ChatContainer>
);
};
Expand Down
38 changes: 23 additions & 15 deletions src/components/HlsPlayer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import Hls from 'hls.js';
import Hls from 'hls.js/dist/hls.min';

const HlsVideoPlayer = ({ videoUrl }) => {
const videoRef = useRef(null);
Expand All @@ -14,21 +14,24 @@ const HlsVideoPlayer = ({ videoUrl }) => {
console.log('initialize 실행');
// 자동재생
console.log('play 실행 전');
videoElement.play();

// videoElement.play();
console.log('play 실행 후ㅡ');
// 마지막 청크의 재생시간으로 이동
console.log('hls', hls);
// videoElement.muted = false;
// console.log("hls.media.current.segments", hls.media.current.segments);
console.log(data.lastSegment);
console.log(hls.media.segments);
const lastSegment = hls.media.segments[hls.media.segments.length - 1];
console.log('lastSegment', lastSegment);

let myFragments = data.levels[0].details.fragments;
// console.log(hls.media.segments);
const lastSegment = myFragments[myFragments.length - 1];

// console.log("lastSegment", lastSegment);
if (lastSegment) {
videoElement.currentTime = lastSegment.end;
videoElement.currentTime = lastSegment.start - 0.5;
}
};

// Hls 지원 여부 확인
if (Hls.isSupported()) {
console.log('hls를 지원한다.');
var config = {
Expand Down Expand Up @@ -130,11 +133,6 @@ const HlsVideoPlayer = ({ videoUrl }) => {
};

hls = new Hls(config);
// 이벤트 리스너 등록
// hls.on(Hls.Events.MEDIA_ATTACHED, (event, data) => {
// console.log("event listener 등록");
// initializeHls(data);
// });

hls.on(Hls.Events.MEDIA_ATTACHED, function () {
console.log('video and hls.js are now bound together !');
Expand All @@ -159,10 +157,20 @@ const HlsVideoPlayer = ({ videoUrl }) => {
console.log('컴포넌트 unmount시에 destroy');
hls.destroy();
}
if (videoElement) {
console.log('video pause');
videoElement.pause();
}
};
}, [videoUrl]);
}, [videoUrl, videoRef.current]);

return <video ref={videoRef} controls width='100%' height='100%' />;
return (
<div>
{videoRef ? (
<video ref={videoRef} controls width='100%' height='100%' muted />
) : null}
</div>
);
};

export default HlsVideoPlayer;
4 changes: 2 additions & 2 deletions src/components/ReactPlayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// <ReactPlayer
// url={videoUrl}
// controls={true}
// width='68%'
// height='68%'
// width='100%'
// height='100%'
// playing={true}
// config={{
// hls: {
Expand Down
24 changes: 12 additions & 12 deletions src/components/Slide.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react";
import { Link } from "react-router-dom";
import "./Slide.css";
import React from 'react';
import { Link } from 'react-router-dom';
import './Slide.css';

export const Slide = React.memo(function (StackedCarouselSlideProps) {
const { data, dataIndex, isCenterSlide, swipeTo, slideIndex } =
Expand All @@ -9,29 +9,29 @@ export const Slide = React.memo(function (StackedCarouselSlideProps) {
const text = data[dataIndex].title;
const channelId = data[dataIndex].channelId;
return (
<div className="card-card" draggable={false}>
<div className='card-card' draggable={false}>
<Link
to={`/channels/${channelId}`}
style={{ textDecoration: "none", color: "inherit" }}
style={{ textDecoration: 'none', color: 'inherit' }}
>
<div className={`cover fill ${isCenterSlide ? "off" : "on"}`}>
<div className={`cover fill ${isCenterSlide ? 'off' : 'on'}`}>
<div
className="card-overlay fill"
className='card-overlay fill'
onClick={() => {
if (!isCenterSlide) swipeTo(slideIndex);
}}
/>
</div>
<div className="detail fill">
<div className="discription">
<div className='detail fill'>
<div className='discription'>
<img
style={{ width: 430 }}
alt="j"
className="cover-image"
alt='j'
className='cover-image'
src={coverImage}
/>
<p>{text}</p>
<p>{channelId}</p>
{/* <p>{channelId}</p> */}
</div>
</div>
</Link>
Expand Down
Loading

0 comments on commit 6704239

Please sign in to comment.