Skip to content

Commit

Permalink
chats.4
Browse files Browse the repository at this point in the history
  • Loading branch information
RyuDSora committed Jul 27, 2024
1 parent 0661286 commit 8a7878a
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 41 deletions.
5 changes: 4 additions & 1 deletion client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ import DashST from './DashboardStudent/DashST.jsx';
import SubscriptionPlans from './SubscriptionPlans.jsx';
import withAuth from './hoc/withAuth';

const socket = io('http://localhost:3000');
const socket = io('https://tutorias-five.vercel.app', {
transports: ['websocket'],
withCredentials: true,
});

function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
Expand Down
77 changes: 38 additions & 39 deletions client/src/DashboardTutor/Chats.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import React, { useState, useEffect, useRef } from 'react';
import { Container, Row, Col, ListGroup, Form, Button, Alert } from 'react-bootstrap';
import { io } from 'socket.io-client';
import axios from 'axios';
import { url, urichat,URIUser } from '../components/Urls';

// Configura la conexión con socket.io
const socket = io('https://tutorias-five.vercel.app');
import { url, urichat, URIUser } from '../components/Urls';

const Chats = ({ userId }) => {
const UserId = parseInt(userId);
Expand All @@ -17,44 +14,65 @@ const Chats = ({ userId }) => {
const [filteredUsers, setFilteredUsers] = useState([]);
const messagesEndRef = useRef(null);

// Función para obtener el historial de chat entre dos usuarios
useEffect(() => {
const socket = io('https://tutorias-five.vercel.app');

socket.on('connect', () => {
console.log('Connected to server');
socket.emit('user_connected', UserId);
});

socket.on('connect_error', (err) => {
console.error('Connection error:', err);
});

socket.on('active_users', (users) => {
setConnectedStudents(users);
});

return () => {
socket.disconnect();
};
}, [UserId]);

const fetchChatHistory = async (user1, user2) => {
try {
const response = await axios.get(`${urichat}/${user1}/${user2}`);
return response.data;
} catch (error) {
//console.log('Error fetching chat history:', error);
console.error('Error fetching chat history:', error);
return [];
}
};

// Usuarios para chatear
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await axios.get(URIUser);
const usuarios = response.data.filter(user => user.id !== UserId);
setUsers(usuarios);
} catch (error) {
//console.log('Error fetching users:', error);
console.error('Error fetching users:', error);
}
};
fetchUsers();
}, [UserId]);

// Usuarios activos y mensajes recibidos
useEffect(() => {
// Emitir el evento de conexión del usuario
socket.emit('user_connected', UserId);
const filterUsers = async () => {
const usersWithHistory = [];
for (const user of users) {
const chatHistory = await fetchChatHistory(UserId, user.id);
if (chatHistory.length > 0 || connectedStudents.includes(user.id)) {
usersWithHistory.push(user);
}
}
setFilteredUsers(usersWithHistory);
};

if (UserId) {
socket.on('active_users', (users) => {
setConnectedStudents(users);
});
}
}, [UserId]);
filterUsers();
}, [users, connectedStudents]);

// Obtener historial de mensajes cuando se selecciona un estudiante
useEffect(() => {
if (selectedStudent) {
fetchChatHistory(UserId, selectedStudent.id).then(chatHistory => {
Expand All @@ -66,7 +84,6 @@ const Chats = ({ userId }) => {
}
}, [selectedStudent]);

// Verificar nuevos mensajes periódicamente
useEffect(() => {
const interval = setInterval(() => {
if (selectedStudent) {
Expand All @@ -82,30 +99,12 @@ const Chats = ({ userId }) => {
return () => clearInterval(interval);
}, [selectedStudent]);

// Filtrar usuarios conectados o con historial
useEffect(() => {
const filterUsers = async () => {
const usersWithHistory = [];
for (const user of users) {
const chatHistory = await fetchChatHistory(UserId, user.id);
if (chatHistory.length > 0 || connectedStudents.includes(user.id)) {
usersWithHistory.push(user);
}
}
setFilteredUsers(usersWithHistory);
};

filterUsers();
}, [users, connectedStudents]);

// Función para desplazar el contenedor de mensajes al final
const scrollToBottom = () => {
if (messagesEndRef.current) {
messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
};

// Llamar a scrollToBottom cuando los mensajes cambien
useEffect(() => {
scrollToBottom();
}, [messages, selectedStudent]);
Expand All @@ -116,7 +115,7 @@ const Chats = ({ userId }) => {
const msg = { emisor: UserId, mensaje: input, receptor: selectedStudent.id };

try {
await axios.post('http://localhost:3000/api/messages', msg);
await axios.post(urichat, msg);
setMessages((prevMessages) => {
const studentId = selectedStudent.id;
return {
Expand Down Expand Up @@ -172,7 +171,7 @@ const Chats = ({ userId }) => {
borderRadius: '5px',
padding: '10px',
height: '400px',
overflowY: 'auto', // Cambiar a 'auto' para permitir el desplazamiento dentro del contenedor
overflowY: 'auto',
marginBottom: '20px',
}}
>
Expand Down
4 changes: 3 additions & 1 deletion server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ io.on('connection', (socket) => {

server.listen(port, () => {});


app.get('/test', (req, res) => {
res.status(200).send('Server is running');
});

/*
Expand Down

0 comments on commit 8a7878a

Please sign in to comment.