Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 77 additions & 84 deletions src/App.jsx

Large diffs are not rendered by default.

21 changes: 16 additions & 5 deletions src/api/axios.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import axios from 'axios'
import { fetchAuthSession, signOut } from 'aws-amplify/auth'

const API_BASE_URL = import.meta.env.VITE_API_URL

Expand All @@ -14,8 +15,7 @@ const api = axios.create({
api.interceptors.request.use(
async (config) => {
try {
// Cognito 세션에서 토큰 가져오기
const session = await fetchAuthSession()

const token = localStorage.getItem('accessToken')

if (token) {
Expand Down Expand Up @@ -45,16 +45,27 @@ api.interceptors.response.use(

try {
// 토큰 갱신 시도
const session = await fetchAuthSession({forceRefresh: true})
const session = await fetchAuthSession({ forceRefresh: true })
const newToken = session.tokens?.accessToken?.toString()

if (newToken) {
localStorage.setItem('accessToken', newToken)
originalRequest.headers['Authorization'] = `Bearer ${newToken}`
return api(originalRequest)
}
} catch (refreshError) {
// 토큰 갱신 실패 시 로그인 페이지로 리다이렉트
window.location.href = '/login'
try {
await signOut()
} catch (e) {
console.error('[Axios] Sign out error:', e)
}

localStorage.removeItem('accessToken')

// 로그인 페이지로 리다이렉트 (무한 루프 방지)
if (window.location.pathname !== '/login') {
window.location.href = '/login'
}
}
}
return Promise.reject(error)
Expand Down
41 changes: 41 additions & 0 deletions src/api/speakingApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import axios from 'axios'

// Bedrock/Polly 사용으로 응답 시간(timeout) 제한 늘림
const speakingApi = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 30000, // 30초
headers: {
'Content-Type': 'application/json',
},
})

// Request interceptor - JWT 토큰 자동 추가
speakingApi.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)

// Response interceptor - 401 에러 처리 및 데이터 추출
speakingApi.interceptors.response.use(
(response) => response.data, // response.data를 바로 반환하도록 설정
(error) => {
console.error('Speaking API Error:', error.response?.data || error.message)

if (error.response?.status === 401) {
localStorage.removeItem('accessToken')
window.location.href = '/login'
}

return Promise.reject(error)
}
)

export default speakingApi
163 changes: 163 additions & 0 deletions src/domains/speaking/components/SpeakingChatMessage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { useState, useRef } from 'react'
import { Avatar, Box, IconButton, Typography, Tooltip, keyframes } from '@mui/material'
import {
Person as PersonIcon,
SmartToy as AiIcon,
VolumeUp as VolumeUpIcon,
Stop as StopIcon,
} from '@mui/icons-material'
import { useSettings } from '../../../contexts/SettingsContext'

const pulse = keyframes`
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
`

export default function SpeakingChatMessage({ message, isUser = false }) {
const { isKorean } = useSettings()
const [isPlaying, setIsPlaying] = useState(false)
const audioRef = useRef(null)

const {
content,
userTranscript,
aiText,
aiAudioUrl,
confidence,
} = message

const displayText = isUser ? (userTranscript || content) : (aiText || content)

/**
* AI 응답 음성 재생
*/
const playAudio = () => {
if (!aiAudioUrl) return

if (audioRef.current) {
audioRef.current.pause()
}

const audio = new Audio(aiAudioUrl)
audioRef.current = audio

audio.onplay = () => setIsPlaying(true)
audio.onended = () => setIsPlaying(false)
audio.onerror = () => {
setIsPlaying(false)
console.error('Audio playback error')
}

audio.play()
}

const stopAudio = () => {
if (audioRef.current) {
audioRef.current.pause()
audioRef.current.currentTime = 0
setIsPlaying(false)
}
}

return (
<Box
sx={{
display: 'flex',
gap: 1.5,
mb: 2,
flexDirection: isUser ? 'row-reverse' : 'row',
}}
>
{/* 아바타 */}
<Avatar
sx={{
width: 36,
height: 36,
backgroundColor: isUser ? '#3b82f6' : '#10b981',
}}
>
{isUser ? <PersonIcon /> : <AiIcon />}
</Avatar>

{/* 메시지 내용 */}
<Box sx={{ maxWidth: '70%' }}>
{/* 역할 라벨 */}
<Typography
variant="caption"
sx={{
color: '#6b7280',
mb: 0.5,
display: 'block',
textAlign: isUser ? 'right' : 'left',
}}
>
{isUser
? (isKorean ? '나' : 'You')
: 'Amy (AI)'}
</Typography>

{/* 메시지 버블 */}
<Box
sx={{
p: 2,
borderRadius: '16px',
backgroundColor: isUser ? '#3b82f6' : '#f3f4f6',
color: isUser ? '#fff' : '#374151',
borderTopRightRadius: isUser ? 4 : 16,
borderTopLeftRadius: isUser ? 16 : 4,
}}
>
<Typography sx={{ fontSize: '1rem', lineHeight: 1.6 }}>
{displayText}
</Typography>

{/* STT 신뢰도 표시 (사용자 메시지) */}
{isUser && confidence && (
<Typography
variant="caption"
sx={{ opacity: 0.7, mt: 1, display: 'block' }}
>
{isKorean ? '인식률' : 'Confidence'}: {Math.round(confidence * 100)}%
</Typography>
)}
</Box>

{/* AI 응답 음성 재생 버튼 */}
{!isUser && aiAudioUrl && (
<Box sx={{ mt: 1 }}>
<Tooltip
title={
isPlaying
? (isKorean ? '정지' : 'Stop')
: (isKorean ? '음성 듣기' : 'Listen')
}
>
<IconButton
size="small"
onClick={isPlaying ? stopAudio : playAudio}
sx={{
backgroundColor: isPlaying ? '#ef4444' : '#10b981',
color: '#fff',
'&:hover': {
backgroundColor: isPlaying ? '#dc2626' : '#059669',
},
animation: isPlaying ? `${pulse} 1s infinite` : 'none',
}}
>
{isPlaying ? <StopIcon fontSize="small" /> : <VolumeUpIcon fontSize="small" />}
</IconButton>
</Tooltip>
<Typography
variant="caption"
sx={{ ml: 1, color: '#6b7280' }}
>
{isPlaying
? (isKorean ? '재생 중...' : 'Playing...')
: (isKorean ? '음성 듣기' : 'Listen')}
</Typography>
</Box>
)}
</Box>
</Box>
)
}
Loading