diff --git a/apps/amakrushi/lang/en.json b/apps/amakrushi/lang/en.json index cc8e9e44..aa525599 100644 --- a/apps/amakrushi/lang/en.json +++ b/apps/amakrushi/lang/en.json @@ -44,6 +44,7 @@ "message.no_signal":"No signal. \nPlease check your internet connection", "message.click_to_type": "Click here to type", "message.downloading": "Downloading...", + "message.download_audio": "Loading Audio", "message.no_link": "Something went wrong, please try later.", "message.sharing": "Sharing...", "message.no_history":"Your Chat History with AI will come here", diff --git a/apps/amakrushi/lang/or.json b/apps/amakrushi/lang/or.json index 86858b49..39663315 100644 --- a/apps/amakrushi/lang/or.json +++ b/apps/amakrushi/lang/or.json @@ -44,6 +44,7 @@ "message.no_signal":"ସିଗ୍ନାଲ ନାହିଁ। \nଦୟାକରି ଆପଣଙ୍କ ଇଣ୍ଟରନେଟ ସଂଯୋଗ କୁ ଚେକ୍ କରନ୍ତ", "message.click_to_type": "ଟାଇପ୍ କରିବାକୁ ଏଠାରେ କ୍ଲିକ୍ କରନ୍ତୁ", "message.downloading": "ଡାଉନଲୋଡ୍ ହେଉଛି ....", + "message.download_audio": "ଅଡିଓ ଲୋଡିଂ କରୁଛି |", "message.no_link": "କିଛି ଭୁଲ ହୋଇଗଲା, ଦୟାକରି ପରେ ଚେଷ୍ଟା କରନ୍ତୁ|", "message.sharing": "ସେୟାରିଂ ....", "message.no_history":"AI ସହିତ ଆପଣଙ୍କର ଚାଟ୍ ଇତିହାସ ଏଠାକୁ ଆସିବ |", diff --git a/apps/amakrushi/src/components/ChatWindow/ChatUiWindow.tsx b/apps/amakrushi/src/components/ChatWindow/ChatUiWindow.tsx index 5c2f57e6..aaf50ed4 100644 --- a/apps/amakrushi/src/components/ChatWindow/ChatUiWindow.tsx +++ b/apps/amakrushi/src/components/ChatWindow/ChatUiWindow.tsx @@ -96,7 +96,8 @@ const ChatUiWindow: React.FC = () => { reaction: item.reaction, msgId: item.id, messageId: item.id, - audio_url: item.audioURL + audio_url: item.audioURL, + isEnd: true, }, ].filter(Boolean) ); @@ -131,7 +132,7 @@ const ChatUiWindow: React.FC = () => { ); console.log('fghj:', { messages: context?.messages }); const msgToRender = useMemo(() => { - return context?.isMsgReceiving + return context?.loading ? [ ...normalizeMsgs, { @@ -141,7 +142,7 @@ const ChatUiWindow: React.FC = () => { }, ] : normalizeMsgs; - }, [context?.isMsgReceiving, normalizeMsgs]); + }, [context?.loading, normalizeMsgs]); console.log('debug:', { msgToRender }); @@ -242,7 +243,7 @@ const ChatUiWindow: React.FC = () => { { )} diff --git a/apps/amakrushi/src/components/NavBar/index.tsx b/apps/amakrushi/src/components/NavBar/index.tsx index 2a273540..6dcd5526 100644 --- a/apps/amakrushi/src/components/NavBar/index.tsx +++ b/apps/amakrushi/src/components/NavBar/index.tsx @@ -37,7 +37,7 @@ function NavBar() { ); const newChatHandler = useCallback(() => { - if (context?.loading) { + if (context?.isMsgReceiving) { toast.error(`${t('error.wait_new_chat')}`); return; } diff --git a/apps/amakrushi/src/components/Sidemenu/index.tsx b/apps/amakrushi/src/components/Sidemenu/index.tsx index e7ac4a94..5d01aa4a 100644 --- a/apps/amakrushi/src/components/Sidemenu/index.tsx +++ b/apps/amakrushi/src/components/Sidemenu/index.tsx @@ -22,6 +22,7 @@ import { useCookies } from 'react-cookie'; import router from 'next/router'; import { logEvent } from 'firebase/analytics'; import { analytics } from '../../utils/firebase'; +import toast from 'react-hot-toast'; export const Sidemenu = () => { const t = useLocalization(); @@ -121,6 +122,11 @@ export const Sidemenu = () => {
{ + if (context?.isMsgReceiving) { + toast.error(`${t('error.wait_new_chat')}`); + onClose(); + return; + } router.push('/history'); onClose(); }}> @@ -137,6 +143,11 @@ export const Sidemenu = () => {
{ + if (context?.isMsgReceiving) { + toast.error(`${t('error.wait_new_chat')}`); + onClose(); + return; + } router.push('/faq'); onClose(); }}> @@ -153,6 +164,11 @@ export const Sidemenu = () => {
{ + if (context?.isMsgReceiving) { + toast.error(`${t('error.wait_new_chat')}`); + onClose(); + return; + } router.push('/feedback'); onClose(); }}> diff --git a/apps/amakrushi/src/components/blinking-spinner/index.module.css b/apps/amakrushi/src/components/blinking-spinner/index.module.css new file mode 100644 index 00000000..a8403d7e --- /dev/null +++ b/apps/amakrushi/src/components/blinking-spinner/index.module.css @@ -0,0 +1,13 @@ +@keyframes blink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0; } +} + +.spinner { + display: inline-block; + height: 15px; + width: 1px; + background-color: var(--secondarygreen); + /* border-radius: 50%; */ + animation: blink .5s infinite; +} \ No newline at end of file diff --git a/apps/amakrushi/src/components/blinking-spinner/index.tsx b/apps/amakrushi/src/components/blinking-spinner/index.tsx new file mode 100644 index 00000000..c33a5347 --- /dev/null +++ b/apps/amakrushi/src/components/blinking-spinner/index.tsx @@ -0,0 +1,10 @@ +import React from 'react'; +import styles from './index.module.css'; + +const BlinkingSpinner = () => { + return ( +

+ ); +} + +export default BlinkingSpinner; \ No newline at end of file diff --git a/apps/amakrushi/src/components/chat-message-item/index.tsx b/apps/amakrushi/src/components/chat-message-item/index.tsx index c89294e0..5c72bd90 100644 --- a/apps/amakrushi/src/components/chat-message-item/index.tsx +++ b/apps/amakrushi/src/components/chat-message-item/index.tsx @@ -20,7 +20,7 @@ import React, { } from 'react'; import { toast } from 'react-hot-toast'; - +import { oriaWeatherTranslates } from '../../utils/getWeatherTranslation'; import styles from './index.module.css'; import { analytics } from '../../utils/firebase'; import { logEvent } from 'firebase/analytics'; @@ -39,15 +39,23 @@ import Image from 'next/image'; import { Button } from '@chakra-ui/react'; import flagsmith from 'flagsmith/isomorphic'; import Loader from '../loader'; -import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@material-ui/core'; +import { + Paper, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, +} from '@material-ui/core'; import { useIntl } from 'react-intl'; +import BlinkingSpinner from '../blinking-spinner/index'; const getToastMessage = (t: any, reaction: number): string => { if (reaction === 1) return t('toast.reaction_like'); return t('toast.reaction_reset'); }; const ChatMessageItem: FC = ({ - currentUser, message, onSend, }) => { @@ -56,6 +64,8 @@ const ChatMessageItem: FC = ({ const t = useLocalization(); const context = useContext(AppContext); const [reaction, setReaction] = useState(message?.content?.data?.reaction); + const [audioFetched, setAudioFetched] = useState(false); + const [ttsLoader, setTtsLoader] = useState(false); useEffect(() => { setReaction(message?.content?.data?.reaction); @@ -159,15 +169,6 @@ const ChatMessageItem: FC = ({ [context, t] ); - const handleAudio = (url: any) => { - // console.log(url) - if (!url || typeof url !== "string") { - toast.error('No audio'); - return; - } - context?.playAudio(url, content); - }; - const getFormattedDate = (datestr: string) => { const today = new Date(datestr); const yyyy = today.getFullYear(); @@ -178,10 +179,98 @@ const ChatMessageItem: FC = ({ if (mm < 10) mm = '0' + mm; return dd + '/' + mm + '/' + yyyy; - } + }; const { content, type } = message; // console.log('#-debug:', content); + + const handleAudio = useCallback( + (url: any) => { + // console.log(url) + if (!url) { + if (audioFetched) toast.error('No audio'); + // else { + // const toastId = toast.loading('Downloading audio'); + // setTimeout(() => { + // toast.dismiss(toastId); + // }, 1000); + // } + return; + } + context?.playAudio(url, content); + setTtsLoader(false); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [audioFetched, content, context?.playAudio] + ); + + const downloadAudio = useCallback(() => { + const cacheAudio = async (url: string) => { + const apiUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/storeaudio`; + + const requestData = { + queryId: message?.content?.data?.messageId, + audioUrl: url, + }; + + axios + .post(apiUrl, requestData, { + headers: { + 'Content-Type': 'application/json', + }, + }) + .then((response) => { + console.log('Cache Audio Response:', response.data); + }) + .catch((error) => { + console.error('Cache Audio Error:', error); + }); + }; + + const fetchAudio = async (text: string) => { + try { + const response = await axios.post( + `${process.env.NEXT_PUBLIC_BASE_URL}/aitools/t2s`, + { + text: text, + } + ); + setAudioFetched(true); + // cacheAudio(response.data); + return response.data; + } catch (error) { + console.error('Error fetching audio:', error); + setAudioFetched(true); + return null; + } + }; + + const fetchData = async () => { + if ( + !message?.content?.data?.audio_url && + message?.content?.data?.position === 'left' && + message?.content?.text + ) { + const toastId = toast.loading(`${t('message.download_audio')}`); + setTimeout(() => { + toast.dismiss(toastId); + }, 1500); + const audioUrl = await fetchAudio(message?.content?.text); + setTtsLoader(false); + if (audioUrl) { + message.content.data.audio_url = audioUrl; + handleAudio(audioUrl); + } else setTtsLoader(false); + } + }; + if (message.content?.data?.audio_url) { + handleAudio(message.content.data.audio_url); + } else { + setTtsLoader(true); + fetchData(); + } + }, [handleAudio, message.content?.data, message.content?.text, t]); + switch (type) { case 'loader': return ; @@ -209,7 +298,10 @@ const ChatMessageItem: FC = ({ color: content?.data?.position === 'right' ? 'white' : 'var(--font)', }}> - {content.text} + {content.text}{' '} + {content?.data?.position === 'right' + ? null + : !content?.data?.isEnd && }
= ({
handleAudio(content?.data?.audio_url || '')}> + onClick={!ttsLoader ? downloadAudio : () => { }} + style={ + !content?.data?.isEnd + ? { + pointerEvents: 'none', + filter: 'grayscale(100%)', + opacity: '0.5', + } + : { + pointerEvents: 'auto', + opacity: '1', + filter: 'grayscale(0%)', + } + }> {context?.clickedAudioUrl === content?.data?.audio_url ? ( - context?.ttsLoader ? ( - - ) : ( - - ) + + ) : ttsLoader ? ( + ) : ( )} + {/*

+ {t('message.speaker')} +

*/}
) @@ -454,12 +571,13 @@ const ChatMessageItem: FC = ({ } case 'table': { - return ( <>
-
{t('table.header_date')}
+
+ {t('table.header_date')} +
{t('table.header_temp_max')}
{t('table.header_temp_min')}
{t('table.header_temp')}
@@ -471,23 +589,26 @@ const ChatMessageItem: FC = ({
{t('table.header_conditions')}
- {JSON.parse(content?.text)?.map((el: any, idx: any) =>
-
{getFormattedDate(el.datetime)}
-
{el.tempmax} °C
-
{el.tempmin} °C
-
{el.temp} °C
-
{el.humidity} %
-
{el.precip} mm
-
{el.precipprob} %
-
{el.windspeed} m/s
-
{el.cloudcover} %
-
{intl.locale == 'or' ? 'ପାର୍ଟିଆଲ କ୍ଲାଉଡି' : el.conditions}
-
)} + {JSON.parse(content?.text)?.map((el: any, idx: any) => ( +
+
+ {getFormattedDate(el.datetime)} +
+
{el.tempmax} °C
+
{el.tempmin} °C
+
{el.temp} °C
+
{el.humidity} %
+
{el.precip} mm
+
{el.precipprob} %
+
{el.windspeed} m/s
+
{el.cloudcover} %
+
{intl.locale == 'or' ? oriaWeatherTranslates[el?.conditions?.trim()?.split(" ")?.join("")?.toLowerCase()] : el.conditions}
+
+ ))}
-
- ) + ); } default: return ( diff --git a/apps/amakrushi/src/context/ContextProvider.tsx b/apps/amakrushi/src/context/ContextProvider.tsx index fcc11758..8c15b8e8 100644 --- a/apps/amakrushi/src/context/ContextProvider.tsx +++ b/apps/amakrushi/src/context/ContextProvider.tsx @@ -12,7 +12,6 @@ import _ from 'underscore'; import { v4 as uuidv4 } from 'uuid'; import { analytics } from '../utils/firebase'; import { logEvent } from 'firebase/analytics'; -import { UserType } from '../types'; import { IntlProvider } from 'react-intl'; import { useLocalization } from '../hooks'; import toast from 'react-hot-toast'; @@ -44,8 +43,6 @@ const ContextProvider: FC<{ }> = ({ locale, children, localeMsgs, setLocale }) => { const t = useLocalization(); const flags = useFlags(['health_check_time']); - const [users, setUsers] = useState([]); - const [currentUser, setCurrentUser] = useState(); const [loading, setLoading] = useState(false); const [isMsgReceiving, setIsMsgReceiving] = useState(false); const [messages, setMessages] = useState>([]); @@ -64,8 +61,7 @@ const ContextProvider: FC<{ const [cookie, setCookie, removeCookie] = useCookies(); const [isOnline, setIsOnline] = useState(navigator.onLine); const [audioElement, setAudioElement] = useState(null); - const [ttsLoader, setTtsLoader] = useState(false); - const [audioPlaying, setAudioPlaying] = useState(false); + const [audioPlaying, setAudioPlaying] = useState(true); const [clickedAudioUrl, setClickedAudioUrl] = useState(null); const [startTime, setStartTime] = useState(Date.now()); const [endTime, setEndTime] = useState(Date.now()); @@ -106,19 +102,19 @@ const ContextProvider: FC<{ //@ts-ignore if (audioElement.paused) { setClickedAudioUrl(url); - setTtsLoader(true); + // setTtsLoader(true); audioElement //@ts-ignore .play() .then(() => { - setTtsLoader(false); + // setTtsLoader(false); setAudioPlaying(true); console.log('Resumed audio:', url); }) //@ts-ignore .catch((error) => { setAudioPlaying(false); - setTtsLoader(false); + // setTtsLoader(false); setAudioElement(null); setClickedAudioUrl(null); console.error('Error resuming audio:', error); @@ -139,7 +135,7 @@ const ContextProvider: FC<{ } } setClickedAudioUrl(url); - setTtsLoader(true); + // setTtsLoader(true); const audio = new Audio(url); audio.playbackRate = audio_playback; audio.addEventListener('ended', () => { @@ -157,7 +153,7 @@ const ContextProvider: FC<{ audio .play() .then(() => { - setTtsLoader(false); + // setTtsLoader(false); setAudioPlaying(true); console.log('Audio played:', url); // Update the current audio to the new audio element @@ -166,7 +162,7 @@ const ContextProvider: FC<{ }) .catch((error) => { setAudioPlaying(false); - setTtsLoader(false); + // setTtsLoader(false); setAudioElement(null); setClickedAudioUrl(null); console.error('Error playing audio:', error); @@ -174,28 +170,45 @@ const ContextProvider: FC<{ }; }, [audioElement, audio_playback]); - useEffect(() => { - console.log('online'); - if (navigator.onLine) { - console.log('online'); - setIsOnline(true); - } else { - console.log('online'); + const checkInternetConnection = () => { + if (!navigator.onLine) { setIsOnline(false); - onMessageReceived({ - content: { - title: t('message.no_signal'), - choices: null, + setMessages((prev) => [ + ...prev, + { + text: `${t('message.no_signal')}`, + choices: [], + position: 'left', + reaction: 0, + messageId: uuidv4(), conversationId: conversationId, - msg_type: 'text', - timeTaken: 3999, + sentTimestamp: Date.now(), btns: true, + audio_url: '', }, - messageId: uuidv4(), - }); + ]); + setLoading(false); + setIsMsgReceiving(false); + } else { + setIsOnline(true); } + }; + + useEffect(() => { + // Initial check + checkInternetConnection(); + + // Set up event listeners to detect changes in the internet connection status + window.addEventListener('online', checkInternetConnection); + window.addEventListener('offline', checkInternetConnection); + + // Clean up event listeners on component unmount + return () => { + window.removeEventListener('online', checkInternetConnection); + window.removeEventListener('offline', checkInternetConnection); + }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [navigator.onLine]); + }, []); useEffect(() => { if (localStorage.getItem('userID') && localStorage.getItem('auth')) { @@ -215,8 +228,8 @@ const ContextProvider: FC<{ deviceId: localStorage.getItem('userID'), }, autoConnect: false, - // transports: ['polling', 'websocket'], - upgrade: false, + transports: ['polling', 'websocket'], + upgrade: true, }, onMessageReceived ) @@ -233,47 +246,59 @@ const ContextProvider: FC<{ }, [localStorage.getItem('userID'), localStorage.getItem('auth')]); const updateMsgState = useCallback( - ({ - user, - msg, - media, - }: { - user: { name: string; id: string }; - msg: { - content: { - title: string; - choices: any; - conversationId: any; - btns?: boolean; - audio_url: string; - }; - messageId: string; - }; - media: any; - }) => { - if (msg.content.title !== '') { - const newMsg = { - username: user?.name, - text: msg.content.title, - choices: msg.content.choices, - position: 'left', - id: user?.id, - botUuid: user?.id, - reaction: 0, - messageId: msg?.messageId, - conversationId: msg?.content?.conversationId, - sentTimestamp: Date.now(), - btns: msg.content.btns, - audio_url: msg.content.audio_url, - ...media, - }; - - //@ts-ignore + async ({ msg, media }: { msg: any; media: any }) => { + console.log('updatemsgstate:', msg); + if (msg?.content?.title) { if ( sessionStorage.getItem('conversationId') === msg?.content?.conversationId ) { - setMessages((prev: any) => _.uniq([...prev, newMsg], ['messageId'])); + const word = msg.content.title; + + setMessages((prev: any) => { + const updatedMessages = [...prev]; + const existingMsgIndex = updatedMessages.findIndex( + (m: any) => m.messageId === msg.messageId + ); + console.log('existingMsgIndex', existingMsgIndex); + + if (existingMsgIndex !== -1) { + // Update the existing message with the new word + if (word.endsWith('')) { + updatedMessages[existingMsgIndex].isEnd = true; + } + updatedMessages[existingMsgIndex].text += + word.replace('', '') + ' '; + } else { + // If the message doesn't exist, create a new one + const newMsg = { + text: word.replace('', '') + ' ', + isEnd: word.endsWith('') ? true : false, + choices: msg?.content?.choices, + position: 'left', + reaction: 0, + messageId: msg?.messageId, + conversationId: msg?.content?.conversationId, + sentTimestamp: Date.now(), + btns: msg?.content?.btns, + audio_url: msg?.content?.audio_url, + ...media, + }; + + updatedMessages.push(newMsg); + } + return updatedMessages; + }); + if (msg?.content?.title?.endsWith('')) { + // syncChatHistory( + // msg?.messageId, + // msg?.content?.title.replace('', '') + // ); + setLastMsgId(msg?.messageId); + setEndTime(Date.now()); + setIsMsgReceiving(false); + } + setLoading(false); } } }, @@ -283,30 +308,25 @@ const ContextProvider: FC<{ console.log('erty:', { conversationId }); const onMessageReceived = useCallback( - (msg: any): void => { - console.log('mssgs:', messages); - console.log('#-debug:', msg.content); - console.log('#-debug:', msg.content.msg_type); - setLoading(false); - setIsMsgReceiving(false); - //@ts-ignore - const user = JSON.parse(localStorage.getItem('currentUser')); - + async (msg: any) => { + if (!msg?.content?.id) msg.content.id = ''; if (msg.content.msg_type.toUpperCase() === 'IMAGE') { - updateMsgState({ - user, - msg, - media: { imageUrl: msg?.content?.media_url }, - }); + if ( + // msg.content.timeTaken + 1000 < timer2 && + isOnline + ) { + await updateMsgState({ + msg: msg, + media: { imageUrls: msg?.content?.media_url }, + }); + } } else if (msg.content.msg_type.toUpperCase() === 'AUDIO') { updateMsgState({ - user, msg, media: { audioUrl: msg?.content?.media_url }, }); } else if (msg.content.msg_type.toUpperCase() === 'VIDEO') { updateMsgState({ - user, msg, media: { videoUrl: msg?.content?.media_url }, }); @@ -315,19 +335,19 @@ const ContextProvider: FC<{ msg.content.msg_type.toUpperCase() === 'FILE' ) { updateMsgState({ - user, msg, media: { fileUrl: msg?.content?.media_url }, }); } else if (msg.content.msg_type.toUpperCase() === 'TEXT') { - if (msg.content.timeTaken + 1000 < timer2 && isOnline) { - setLastMsgId(msg?.messageId); - setEndTime(Date.now()); - updateMsgState({ user, msg, media: {} }); + if ( + // msg.content.timeTaken + 1000 < timer2 && + isOnline + ) { + await updateMsgState({ msg: msg, media: null }); } } }, - [isOnline, messages, timer2, updateMsgState] + [isOnline, updateMsgState] ); useEffect(() => { @@ -352,19 +372,18 @@ const ContextProvider: FC<{ // eslint-disable-next-line react-hooks/exhaustive-deps }, [endTime]); - const onChangeCurrentUser = useCallback((newUser: UserType) => { - setCurrentUser({ ...newUser, active: true }); - // setMessages([]); - }, []); - console.log('vbnmm:', { newSocket }); - //@ts-ignore const sendMessage = useCallback( (text: string, media: any, isVisibile = true): void => { - if ( - !localStorage.getItem('userID') || - !sessionStorage.getItem('conversationId') - ) { + if (!sessionStorage.getItem('conversationId')) { + const cId = uuidv4(); + console.log('convId', cId); + setConversationId(() => { + sessionStorage.setItem('conversationId', cId); + return cId; + }); + } else sessionStorage.setItem('conversationId', conversationId || ''); + if (!localStorage.getItem('userID')) { removeCookie('access_token', { path: '/' }); location?.reload(); return; @@ -372,7 +391,6 @@ const ContextProvider: FC<{ // console.log('mssgs:', messages) setLoading(true); setIsMsgReceiving(true); - sessionStorage.setItem('conversationId', conversationId || ''); //@ts-ignore logEvent(analytics, 'Query_sent'); @@ -391,7 +409,7 @@ const ContextProvider: FC<{ state: sessionStorage.getItem('state'), asrId: sessionStorage.getItem('asrId'), userId: localStorage.getItem('userID'), - conversationId: sessionStorage.getItem('conversationId') + conversationId: sessionStorage.getItem('conversationId'), } }); setStartTime(Date.now()); @@ -409,10 +427,8 @@ const ContextProvider: FC<{ setMessages((prev: any) => [ ...prev.map((prevMsg: any) => ({ ...prevMsg, disabled: true })), { - username: 'state.username', text: text, position: 'right', - botUuid: currentUser?.id, payload: { text }, time: Date.now(), disabled: true, @@ -421,10 +437,9 @@ const ContextProvider: FC<{ }, ]); sessionStorage.removeItem('asrId'); - // console.log('mssgs:',messages) } }, - [removeCookie, newSocket, conversationId, currentUser?.id] + [conversationId, newSocket, removeCookie] ); const fetchIsDown = useCallback(async () => { @@ -453,61 +468,148 @@ const ContextProvider: FC<{ sessionStorage.removeItem('asrId'); }, [conversationId]); + const normalizedChat = (chats: any): any => { + console.log('in normalized', chats); + const conversationId = sessionStorage.getItem('conversationId'); + const history = chats + .filter( + (item: any) => + conversationId === 'null' || item.conversationId === conversationId + ) + .flatMap((item: any) => + [ + item.query?.length && { + text: item.query, + position: 'right', + repliedTimestamp: item.createdAt, + messageId: uuidv4(), + }, + { + text: item.response, + position: 'left', + sentTimestamp: item.createdAt, + reaction: item.reaction, + msgId: item.id, + messageId: item.id, + audio_url: item.audioURL, + isEnd: true, + }, + ].filter(Boolean) + ); + + console.log('historyyy', history); + console.log('history length:', history.length); + + return history; + }; + useEffect(() => { if (isDown) return; - let secondTimer: any; - const timer = setTimeout(() => { - if (isMsgReceiving && loading) { + let secondTimer: any = null; + let timer: any = null; + if (timer || secondTimer) { + clearTimeout(secondTimer); + clearTimeout(timer); + } + timer = setTimeout(() => { + if (loading) { toast(() => {t('message.taking_longer')}, { // @ts-ignore icon: , }); - secondTimer = setTimeout(() => { - if (isMsgReceiving && loading) { - // toast.error(`${t('message.retry')}`); - onMessageReceived({ - content: { - title: t('message.no_signal'), - choices: null, - conversationId: conversationId, - msg_type: 'text', - timeTaken: 3999, - btns: true, - }, - messageId: uuidv4(), - }); - fetchIsDown(); + } + secondTimer = setTimeout(async () => { + fetchIsDown(); + console.log('log: here'); + if (loading) { + //@ts-ignore + logEvent(analytics, 'msg_fetched_from_history'); + console.log('log:', loading); + try { + const chatHistory = await axios.get( + `${process.env.NEXT_PUBLIC_BASE_URL + }/user/chathistory/${sessionStorage.getItem('conversationId')}`, + { + headers: { + authorization: `Bearer ${localStorage.getItem('auth')}`, + }, + } + ); + console.log('ghji:', chatHistory); + console.log('history:', chatHistory.data); + + if (!chatHistory.data[chatHistory.data.length - 1].response) { + chatHistory.data[chatHistory.data.length - 1].response = `${t( + 'message.no_signal' + )}`; + } + const normalizedChats = normalizedChat(chatHistory); + console.log('normalized chats', normalizedChats); + if (normalizedChats.length > 0) { + setIsMsgReceiving(false); + setLoading(false); + setMessages(normalizedChats); + } + } catch (error: any) { + setIsMsgReceiving(false); + setLoading(false); //@ts-ignore - logEvent(analytics, 'Msg_delay', { - user_id: localStorage.getItem('userID'), - phone_number: localStorage.getItem('phoneNumber'), + logEvent(analytics, 'console_error', { + error_message: error.message, }); } - }, timer2); - } + } else if (isMsgReceiving) { + console.log('log: here'); + const secondLastMsg = + messages.length > 2 ? messages[messages.length - 2] : null; + setMessages((prev: any) => { + if (prev.length > 0) { + // Create a new array without the last element + const updatedMessages = prev.slice(0, -1); + // Update the state with the new array + return updatedMessages; + } else { + return prev; + } + }); + setLoading(true); + console.log('log:', secondLastMsg); + if (secondLastMsg) { + newSocket.sendMessage({ + text: secondLastMsg.text, + to: localStorage.getItem('userID'), + from: localStorage.getItem('phoneNumber'), + optional: { + appId: 'AKAI_App_Id', + channel: 'AKAI', + }, + asrId: sessionStorage.getItem('asrId'), + userId: localStorage.getItem('userID'), + conversationId: sessionStorage.getItem('conversationId'), + }); + } + } else { + setLoading(false); + setIsMsgReceiving(false); + } + //@ts-ignore + logEvent(analytics, 'Msg_delay', { + user_id: localStorage.getItem('userID'), + phone_number: localStorage.getItem('phoneNumber'), + }); + }, timer2); + console.log('log:', secondTimer); }, timer1); - + console.log('log: called', isMsgReceiving, loading); return () => { clearTimeout(timer); clearTimeout(secondTimer); }; - }, [ - conversationId, - fetchIsDown, - isDown, - isMsgReceiving, - loading, - onMessageReceived, - t, - timer1, - timer2, - ]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isDown, isMsgReceiving, loading, t, timer1, timer2]); const values = useMemo( () => ({ - currentUser, - allUsers: users, - toChangeCurrentUser: onChangeCurrentUser, sendMessage, messages, setMessages, @@ -526,8 +628,6 @@ const ContextProvider: FC<{ setShowDialerPopup, playAudio, audioElement, - ttsLoader, - setTtsLoader, shareChat, clickedAudioUrl, downloadChat, @@ -538,9 +638,6 @@ const ContextProvider: FC<{ locale, setLocale, localeMsgs, - currentUser, - users, - onChangeCurrentUser, sendMessage, messages, loading, @@ -555,8 +652,6 @@ const ContextProvider: FC<{ setShowDialerPopup, playAudio, audioElement, - ttsLoader, - setTtsLoader, shareChat, clickedAudioUrl, downloadChat, diff --git a/apps/amakrushi/src/context/index.ts b/apps/amakrushi/src/context/index.ts index dbd070b9..0e28f328 100644 --- a/apps/amakrushi/src/context/index.ts +++ b/apps/amakrushi/src/context/index.ts @@ -1,14 +1,4 @@ import { createContext } from 'react'; -import { ToChangeCurrentUserType, UserType } from '../types'; - -type AppContextType = - | { - toChangeCurrentUser: ToChangeCurrentUserType; - currentUser: UserType; - allUsers: Array; - } - | any; - -export const AppContext = createContext(null); \ No newline at end of file +export const AppContext = createContext(null); \ No newline at end of file diff --git a/apps/amakrushi/src/types/chat-message-item/index.d.ts b/apps/amakrushi/src/types/chat-message-item/index.d.ts index 13237b83..46c4cf89 100644 --- a/apps/amakrushi/src/types/chat-message-item/index.d.ts +++ b/apps/amakrushi/src/types/chat-message-item/index.d.ts @@ -1,7 +1,5 @@ -import { UserType } from "../context"; export type ChatMessageItemPropType = { - currentUser: UserType; message: any; - onSend: (text: string, aa: null, a3: boolean, currentUser: UserType) => void; + onSend: (text: string, aa: null, a3: boolean) => void; }; diff --git a/apps/amakrushi/src/types/context/index.d.ts b/apps/amakrushi/src/types/context/index.d.ts deleted file mode 100644 index 1dbc2df5..00000000 --- a/apps/amakrushi/src/types/context/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export type UserType = { - name: string; - number: string; - active: boolean; - id?: string; - botUuid?: string; - startingMessage?: string; -}; - -export type ToChangeCurrentUserType = (arg: User) => void; \ No newline at end of file diff --git a/apps/amakrushi/src/types/index.d.ts b/apps/amakrushi/src/types/index.d.ts index c0e9f2b0..5c783a19 100644 --- a/apps/amakrushi/src/types/index.d.ts +++ b/apps/amakrushi/src/types/index.d.ts @@ -1,4 +1,3 @@ export * from './chat-item'; -export * from './context'; export * from './chat-message-item'; \ No newline at end of file diff --git a/apps/amakrushi/src/utils/getWeatherTranslation.tsx b/apps/amakrushi/src/utils/getWeatherTranslation.tsx new file mode 100644 index 00000000..c63700de --- /dev/null +++ b/apps/amakrushi/src/utils/getWeatherTranslation.tsx @@ -0,0 +1,46 @@ +//@ts-ignore +export const oriaWeatherTranslates: any = { + blowingordriftingsnow: 'ଝୋଡ଼ା ବା ଘସିଯିବା ବରଫ', + 'heavyfreezingdrizzle/freezingrain': 'ଘନ ହିମବର୍ଷା/ହିମଜଳ', + 'lightfreezingdrizzle/freezingrain': 'ଅଲ୍ପ ହିମବର୍ଷା/ହିମଜଳ', + freezingfog: 'ହିମ କୁହୁଡ଼ା', + heavyfreezingrain: 'ଘନ ହିମଜଳ', + lightfreezingrain: 'ଅଲ୍ପ ହିମଜଳ', + 'funnelcloud/tornado': 'ଫନେଲ ମେଘ/ବାତୁଳି', + hailshowers: 'ବରଫ ଝଡ଼', + ice: 'ବରଫ', + lightningwithoutthunder: 'ବଜ୍ରପାତ ବିନା ଗୁଡ଼ଗୁଡ଼ି', + mist: 'କୁହୁଡ଼ା', + drizzle: 'ଅଲ୍ପ ବର୍ଷା', + precipitationinvicinity: 'ନିକଟବର୍ତୀ ବର୍ଷା', + rain: 'ବର୍ଷା', + heavyrainandsnow: 'ଘନ ବର୍ଷା ଓ ବରଫ', + lightrainandsnow: 'ଅଲ୍ପ ବର୍ଷା ଓ ବରଫ', + rainshowers: 'ବର୍ଷା ଝଡ଼', + heavyrain: 'ଘନ ବର୍ଷା', + lightrain: 'ଅଲ୍ପ ବର୍ଷା', + skycoveragedecreasing: 'ଆକାଶ ଆବରଣ କମିଯିବା', + skycoverageincreasing: 'ଆକାଶ ଆବରଣ ବୃଦ୍ଧି', + skyunchanged: 'ଆକାଶ ଅପରିବର୍ତିତ', + heavydrizzle: 'ଘନ ଅଲ୍ପ ବର୍ଷା', + smokeorhaze: 'ଧୂମ୍ର ବା ଧୂମଳତା', + snow: 'ବରଫ', + snowandrainshowers: 'ବରଫ ଏବଂ ବର୍ଷା ଝଡ଼', + snowshowers: 'ବରଫ ଝଡ଼', + heavysnow: 'ଘନ ବରଫ', + lightsnow: 'ଅଲ୍ପ ବରଫ', + squalls: 'ଝଡ଼', + thunderstorm: 'ବଜ୍ରପାତ', + thunderstormwithoutprecipitation: 'ବଜ୍ରପାତ ବିନା ବର୍ଷା', + diamonddust: 'ହୀରା ଧୂଳି', + lightdrizzle: 'ଅଲ୍ପ ଅଲ୍ପ ବର୍ଷା', + hail: 'କୁଆପଥର', + overcast: 'ମେଘାଚ୍ଛନ୍ନ', + partiallycloudy: 'ଆଂଶିକ ମେଘୁଆ', + clear: 'ସ୍ପଷ୍ଟ', + 'heavydrizzle/rain': 'ଘନ ଅଲ୍ପ ବର୍ଷା/ବର୍ଷା', + 'lightdrizzle/rain': 'ଅଲ୍ପ ଅଲ୍ପ ବର୍ଷା/ବର୍ଷା', + duststorm: 'ଧୂଳିଝଡ', + fog: 'କୁହୁଡ଼ି', + 'freezingdrizzle/freezingrain': 'ହିମ ଅଲ୍ପ ବର୍ଷା/ହିମବର୍ଷା' +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 685f1877..17499571 100644 --- a/yarn.lock +++ b/yarn.lock @@ -20534,10 +20534,10 @@ snapdragon@^0.8.1: source-map-resolve "^0.5.0" use "^3.1.0" -socket-package@0.13.0: - version "0.13.0" - resolved "https://registry.npmjs.org/socket-package/-/socket-package-0.13.0.tgz" - integrity sha512-xLJ423aFMlnVRhFq2rdM125QDc7mTi+o4seOiECjZAbcTyupdfTSNI6l+OpltMUDjWjXMrQ4Vxy4wK2YnU8Pig== +socket-package@0.14.0: + version "0.14.0" + resolved "https://registry.yarnpkg.com/socket-package/-/socket-package-0.14.0.tgz#64e30cb740a79de026ebf7356bc1ff757eabfaf3" + integrity sha512-A2JhHljXHwl07C6kbMJc5kwhq7Gen2eZAVJ6uvZ0Ld5ajoNY8HG+uPt7/gToYmTSd/6fl+bz+7nvn9HG9h9oJw== dependencies: socket.io "^4.7.1" socket.io-client "^4.7.1"