diff --git a/pom.xml b/pom.xml index 343f773..751c7dc 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,8 @@ 11 11 5.10.0 + panuozzo77 + https://sonarcloud.io @@ -68,6 +70,18 @@ 3.1.0 + + javax.json + javax.json-api + 1.1.4 + + + + org.glassfish + javax.json + 1.1.4 + + diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 157b31c..1fca6bc 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -3,32 +3,15 @@ import model.DAO.DAOUser; import model.entity.User; import model.service.login.Authenticator; +//import model.service.message.Conversation; +import model.service.registration.Registration; public class Main { public static void main(String[] args) { - Encryption encryption = new Encryption(); - DAOUser db = new DAOUser(); - String plainTextPassword = "123456"; - EmailManager message = new EmailManager(); - /* - String hashedPassword = encryption.encryptPassword(plainTextPassword); + //Conversation conv = new Conversation(9); + //System.out.println(conv.getUnreadMessagesCounter()); + //System.out.println(conv.getConversations()); - // Use hashed password to create new user - db.createUser("test@gmail.com", hashedPassword, 0); - */ - - /* - User user = db.getUserByIdOrEmail("test@gmail.com"); - System.out.println(encryption.verifyPassword(plainTextPassword, user.getPassword())); - */ - - - //test email - //message.sendEmail("c.porzio02@gmail.com", "Email Test", "questo è una email di test"); - - //test email recupero password - Authenticator authenticator = new Authenticator(); - System.out.println(authenticator.authenticate("test@gmail.com", "123456")); } } diff --git a/src/main/java/controller/CountMessagesServlet.java b/src/main/java/controller/CountMessagesServlet.java new file mode 100644 index 0000000..77a4e32 --- /dev/null +++ b/src/main/java/controller/CountMessagesServlet.java @@ -0,0 +1,27 @@ +package controller; + +import model.service.message.MessageManager; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +@WebServlet("/CountMessages") +public class CountMessagesServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + HttpSession session = request.getSession(); + int recipientId = (int) session.getAttribute("id"); + MessageManager messageManager = new MessageManager(); + int receivedMessageCount = messageManager.countReceivedMessages(recipientId); + + response.setContentType("text/plain"); // Output is a plain text integer + response.getWriter().println(receivedMessageCount); + } + +} diff --git a/src/main/java/controller/GetMessageServlet.java b/src/main/java/controller/GetMessageServlet.java new file mode 100644 index 0000000..4d5fda5 --- /dev/null +++ b/src/main/java/controller/GetMessageServlet.java @@ -0,0 +1,72 @@ +package controller; + +import java.io.IOException; +import java.sql.Timestamp; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import model.entity.Message; +import model.service.message.MessageManager; + +import java.util.List; +import javax.json.*; + +@WebServlet("/GetMessages") +public class GetMessageServlet extends HttpServlet { + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + HttpSession session = request.getSession(); + int userId = (int) session.getAttribute("id"); + + int contactId = Integer.parseInt(request.getParameter("contact_id")); // Get the contact's ID from the request + + // Retrieve the messages between the user and the contact + MessageManager messageManager = new MessageManager(); + List messages = messageManager.retrieveMessages(userId, contactId); + + // Now build the JSON response + JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); + + for (Message message : messages) { + JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); + jsonObjectBuilder.add("sender", message.getSender()); + jsonObjectBuilder.add("recipient", message.getRecipient()); + jsonObjectBuilder.add("body", message.getBody()); + // Convert timestamp to format HH:MM + Timestamp timestamp = message.getSent(); + java.util.Date date = new java.util.Date(timestamp.getTime()); + java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("HH:mm"); + String formattedDate = dateFormat.format(date); + + jsonObjectBuilder.add("sent", formattedDate); + jsonArrayBuilder.add(jsonObjectBuilder.build()); + } + messageManager.markMessagesAsRead(contactId, userId); + JsonArray jsonArray = jsonArrayBuilder.build(); + + response.setContentType("application/json"); + response.getWriter().write(jsonArray.toString()); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException { + try { + HttpSession session = request.getSession(); + int sender = (int) session.getAttribute("id"); + int recipient = Integer.parseInt(request.getParameter("recipient")); + String body = request.getParameter("body"); + + // send the message + MessageManager messageManager = new MessageManager(); + messageManager.sendMessage(sender, recipient, body); + + response.getWriter().write("Message successfully sent"); + + } catch (NumberFormatException e) { + // The request parameter could not be parsed as an integer + response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/java/controller/LoginController.java b/src/main/java/controller/LoginController.java index c9c4201..44ec297 100644 --- a/src/main/java/controller/LoginController.java +++ b/src/main/java/controller/LoginController.java @@ -1,13 +1,11 @@ package controller; -import model.DAO.DAOPersonalInfo; import model.entity.PersonalInfo; import model.entity.User; import model.service.login.Authenticator; import model.service.user.UserData; import model.service.user.UserRegistry; -import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -28,7 +26,7 @@ public void init() { } protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws IOException { String email = request.getParameter("email"); String password = request.getParameter("password"); @@ -51,7 +49,7 @@ private void setSessionAttributes(int id, HttpServletRequest request){ UserData userData = new UserData(); UserRegistry userReg = new UserRegistry(); - User user = userData.getUserByIdOrEmail(id); + User user = userData.getUser(id); PersonalInfo personalInfo = userReg.getPersonalInfo(id); session.setAttribute("id", id); diff --git a/src/main/java/controller/RegistrationServlet.java b/src/main/java/controller/RegistrationServlet.java index 1ee3ccc..2783f06 100644 --- a/src/main/java/controller/RegistrationServlet.java +++ b/src/main/java/controller/RegistrationServlet.java @@ -58,7 +58,7 @@ private void setSessionAttributes(String email, HttpServletRequest request){ UserData userData = new UserData(); UserRegistry userReg = new UserRegistry(); - User user = userData.getUserByIdOrEmail(email); + User user = userData.getUser(email); PersonalInfo personalInfo = userReg.getPersonalInfo(user.getId()); session.setAttribute("id", user.getId()); diff --git a/src/main/java/controller/ResetPasswordServlet.java b/src/main/java/controller/ResetPasswordServlet.java index 4d123a1..1d9f27f 100644 --- a/src/main/java/controller/ResetPasswordServlet.java +++ b/src/main/java/controller/ResetPasswordServlet.java @@ -24,8 +24,5 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) if(authenticator.resetPassword(email, password)){ response.getWriter().write("Password cambiata con successo!"); } - - - } } diff --git a/src/main/java/controller/SendResetPin.java b/src/main/java/controller/SendResetPin.java index 84f1519..011eedb 100644 --- a/src/main/java/controller/SendResetPin.java +++ b/src/main/java/controller/SendResetPin.java @@ -1,6 +1,5 @@ package controller; -import model.entity.User; import model.service.login.Authenticator; import model.service.user.UserData; @@ -18,7 +17,7 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) thr response.setContentType("text/plain"); if(checker.checkIfEmailExists(email)){ - String pin = new Authenticator().resetPassword(email); + String pin = new Authenticator().sendPin(email); response.getWriter().println(pin); } else { diff --git a/src/main/java/model/DAO/DAOMessage.java b/src/main/java/model/DAO/DAOMessage.java new file mode 100644 index 0000000..731d814 --- /dev/null +++ b/src/main/java/model/DAO/DAOMessage.java @@ -0,0 +1,206 @@ +package model.DAO; + +import model.entity.Message; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +public class DAOMessage { + + private Message getMessageFromResultSet(ResultSet resultSet) throws SQLException { + Message message = new Message(); + + message.setIdMessage(resultSet.getInt("ID_message")); + message.setSender(resultSet.getInt("Sender")); + message.setRecipient(resultSet.getInt("Recipient")); + message.setRead(resultSet.getBoolean("Read")); + message.setBody(resultSet.getString("Body")); + message.setSent(resultSet.getTimestamp("sent")); + + return message; + } + + /** + * Retrieves a list of user IDs based on the therapist ID. + * + * @param therapistId The ID of the therapist. + * @return A list of user IDs associated with the specified therapist. + */ + public List retrieveUserIdsByTherapist(int therapistId) { + Connection connection = null; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + List userIds = new ArrayList<>(); + + try { + connection = DAOConnection.getConnection(); + + // Query to retrieve user IDs associated with the specified therapist + String query = "SELECT ID FROM user WHERE ID_Therapist = ?"; + + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, therapistId); + + resultSet = preparedStatement.executeQuery(); + + while (resultSet.next()) { + int userId = resultSet.getInt("ID"); + userIds.add(userId); + } + + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } finally { + try { + if (resultSet != null) resultSet.close(); + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + + return userIds; + } + + public List retrieveMessages(int userId, int contact) { + Connection connection = null; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + List messages = new ArrayList<>(); + + try { + connection = DAOConnection.getConnection(); + + // Query to retrieve messages between the two users + String query = "SELECT * FROM message WHERE (Sender = ? AND Recipient = ?) OR (Sender = ? AND Recipient = ?) ORDER BY sent"; + + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, userId); + preparedStatement.setInt(2, contact); + preparedStatement.setInt(3, contact); + preparedStatement.setInt(4, userId); + + resultSet = preparedStatement.executeQuery(); + + while (resultSet.next()) { + Message message = getMessageFromResultSet(resultSet); + messages.add(message); + } + + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } finally { + try { + if (resultSet != null) resultSet.close(); + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + + return messages; + } + + public void markMessagesAsRead(int senderId, int recipientId) { + Connection conn = null; + PreparedStatement pstmt = null; + + try { + conn = DAOConnection.getConnection(); + + String sql = "UPDATE message SET `Read` = TRUE WHERE Sender = ? AND Recipient = ?;"; + + pstmt = conn.prepareStatement(sql); + pstmt.setInt(1, senderId); + pstmt.setInt(2, recipientId); + + pstmt.executeUpdate(); + + } catch (SQLException e) { + // Handle exceptions (e.g., print stack trace, log error, etc.) + e.printStackTrace(); + } finally { + try { + if (pstmt != null) pstmt.close(); + DAOConnection.releaseConnection(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + + public void sendMessage(int sender, int recipient, String text) { + Connection conn = null; + PreparedStatement pstmt = null; + + try { + conn = DAOConnection.getConnection(); + + String sql = "INSERT INTO message (Sender, Recipient, Body) VALUES (?, ?, ?);"; + + pstmt = conn.prepareStatement(sql); + pstmt.setInt(1, sender); + pstmt.setInt(2, recipient); + pstmt.setString(3, text); + + pstmt.executeUpdate(); + + } catch (SQLException e) { + // Handle exceptions (e.g., print stack trace, log error, etc.) + e.printStackTrace(); + } finally { + try { + if (pstmt != null) pstmt.close(); + DAOConnection.releaseConnection(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + + public int countReceivedMessages(int recipientId) { + Connection conn = null; + PreparedStatement pstmt = null; + ResultSet rs = null; + int count = 0; + + try { + conn = DAOConnection.getConnection(); + + String sql = "SELECT COUNT(*) FROM message WHERE Recipient = ?;"; + + pstmt = conn.prepareStatement(sql); + pstmt.setInt(1, recipientId); + + rs = pstmt.executeQuery(); + if (rs.next()) { + count = rs.getInt(1); + } + + } catch (SQLException e) { + // Handle exceptions (e.g., print stack trace, log error, etc.) + e.printStackTrace(); + } finally { + try { + if (rs != null) rs.close(); + if (pstmt != null) pstmt.close(); + DAOConnection.releaseConnection(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + return count; + } +} diff --git a/src/main/java/model/entity/Message.java b/src/main/java/model/entity/Message.java index 5ea12f2..0550775 100644 --- a/src/main/java/model/entity/Message.java +++ b/src/main/java/model/entity/Message.java @@ -59,5 +59,17 @@ public Timestamp getSent() { public void setSent(Timestamp sent) { this.sent = sent; } + + @Override + public String toString() { + return "Message{" + + //"idMessage=" + idMessage + + ", sender=" + sender + + ", recipient=" + recipient + + ", read=" + read + + //", body='" + body + '\'' + + //", sent=" + sent + + '}'; + } } diff --git a/src/main/java/model/service/email/EmailManager.java b/src/main/java/model/service/email/EmailManager.java index 246b95e..95efd83 100644 --- a/src/main/java/model/service/email/EmailManager.java +++ b/src/main/java/model/service/email/EmailManager.java @@ -11,7 +11,7 @@ * This class provides functionality for sending email messages. * It reads the configuration from a properties file named 'email.properties'. */ -public class EmailManager { +public class EmailManager implements EmailManagerInterface{ private static final String EMAIL_PROPERTIES = "/email.properties"; private static final String ERROR_MESSAGE = "Error loading configuration file: "; diff --git a/src/main/java/model/service/login/Authenticator.java b/src/main/java/model/service/login/Authenticator.java index 80a310d..3c522ca 100644 --- a/src/main/java/model/service/login/Authenticator.java +++ b/src/main/java/model/service/login/Authenticator.java @@ -10,7 +10,7 @@ public class Authenticator implements LoginInterface { DAOUser db = new DAOUser(); @Override - public String resetPassword(String email) { + public String sendPin(String email) { if(email.equals("test@email.com")) { return "12345678"; } diff --git a/src/main/java/model/service/login/LoginInterface.java b/src/main/java/model/service/login/LoginInterface.java index 67b4b0e..b424e30 100644 --- a/src/main/java/model/service/login/LoginInterface.java +++ b/src/main/java/model/service/login/LoginInterface.java @@ -12,10 +12,19 @@ public interface LoginInterface { public int authenticate(String email, String password); /** - * permette di effettuare il reset della password + * permette di effettuare il reset della password inviando un PIN di verifica all'email * @param email è l'email inserita * @return il codice di verifica inviato tramite email */ - public String resetPassword(String email); + public String sendPin(String email); + + /** + * Resetta la password utente. + * + * @param email è l'email inserita. + * @param plainTextPassword la nuova password dell'utente. + * @return True se la password è stata correttamente salvata False altrimenti. + */ + public boolean resetPassword(String email, String plainTextPassword); } diff --git a/src/main/java/model/service/message/MessageManager.java b/src/main/java/model/service/message/MessageManager.java new file mode 100644 index 0000000..8290eea --- /dev/null +++ b/src/main/java/model/service/message/MessageManager.java @@ -0,0 +1,63 @@ +package model.service.message; + +import model.DAO.DAOMessage; +import model.entity.Message; +import model.entity.User; +import model.service.user.UserData; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MessageManager implements MessageManagerInterface { + private int userId; + private int unreadMessages; + private final Map> conversations = new HashMap<>(); //Integer è l'ID dell'Utente con cui chatta. La lista dei messaggi è la lista dei messaggi con quell'utente + DAOMessage db = new DAOMessage(); + + public int getUserId() { + return userId; + } + + public MessageManager(){} + + public void markMessagesAsRead(int senderId, int recipientId) { + db.markMessagesAsRead(senderId, recipientId); + } + + public int countReceivedMessages(int recipientId) { + return db.countReceivedMessages(recipientId); + } + + public void sendMessage(int sender, int recipientId, String text) { + db.sendMessage(sender, recipientId, text); + } + public List retrieveMessages(int userId, int contact) { + return db.retrieveMessages(userId, contact); + } + public int getUnreadMessagesForConversation(int userId, int contact){ + int unreadCounter = 0; + List messages = db.retrieveMessages(userId, contact); + for (Message message : messages) { + if (message.getRecipient() == userId && !message.isRead()) { + unreadCounter++; + } + } + return unreadCounter; + } + + public List retrieveAllTheContacts(int userId){ + List contacts = new ArrayList<>(); + UserData check = new UserData(); + User user = check.getUser(userId); + if(check.isTherapist(user)) { + contacts.addAll(db.retrieveUserIdsByTherapist(userId)); + } + else { //se è un paziente + contacts.add(user.getIdTherapist()); + } + contacts.add(0); //Notifications + return contacts; + } +} diff --git a/src/main/java/model/service/message/MessageManagerInterface.java b/src/main/java/model/service/message/MessageManagerInterface.java new file mode 100644 index 0000000..47ae232 --- /dev/null +++ b/src/main/java/model/service/message/MessageManagerInterface.java @@ -0,0 +1,60 @@ +package model.service.message; + +import model.entity.Message; + +import java.util.List; + +public interface MessageManagerInterface { + + /** + * Contrassegna i messaggi tra un mittente e un destinatario come letti nel database. + * Questo metodo aggiorna il campo 'Letto' dei messaggi dal mittente al destinatario su VERO. + * + * @param senderId the ID of the sender + * @param recipientId the ID of the recipient + */ + void markMessagesAsRead(int senderId, int recipientId); + + /** + * Conta il numero di messaggi ricevuti. + * + * @param recipientId the ID of the recipient + * @return the number of received messages for the recipient + */ + int countReceivedMessages(int recipientId); + + /** + * Invia un messaggio salvandolo su un database. + * + * @param sender the ID of the sender + * @param recipientId the ID of the recipient + * @param text the content of the message + */ + void sendMessage(int sender, int recipientId, String text); + + /** + * Ottiene la lista dei messaggi in una conversazione. + * + * @param userId the ID of the user + * @param contact the ID of the contact + * @return the list of messages between the user and the contact + */ + List retrieveMessages(int userId, int contact); + + /** + * Conta il numero di messaggi non letti in una conversazione. + * + * @param userId the ID of the user + * @param contact the ID of the contact + * @return the number of unread messages for the conversation + */ + int getUnreadMessagesForConversation(int userId, int contact); + + /** + * Restituisce tutti i contatti di un utente. + * + * @param userId the ID of the user + * @return a list of integers representing the IDs of the contacts + */ + List retrieveAllTheContacts(int userId); +} diff --git a/src/main/java/model/service/registration/Registration.java b/src/main/java/model/service/registration/Registration.java index e8dff88..6a007a0 100644 --- a/src/main/java/model/service/registration/Registration.java +++ b/src/main/java/model/service/registration/Registration.java @@ -7,21 +7,6 @@ public class Registration implements RegistrationInterface { - /** - * Registers a user with the provided information. - * - * @param licenseCode The license code to validate the license. - * @param email The email address of the user. - * @param password The password for the user. - * @param name The name of the user. - * @param surname The surname of the user. - * @return An integer representing the error code based on the following cases: - * 0 - No error. - * 1 - Invalid license. - * 2 - Invalid email. - * 3 - Unable to create user. - * 4 - Unable to generate personal info. - */ @Override public int registerNewUser(String licenseCode, String email, String password, String name, String surname) { License license = validateLicense(licenseCode); diff --git a/src/main/java/model/service/registration/RegistrationInterface.java b/src/main/java/model/service/registration/RegistrationInterface.java index d5cb288..706136c 100644 --- a/src/main/java/model/service/registration/RegistrationInterface.java +++ b/src/main/java/model/service/registration/RegistrationInterface.java @@ -12,6 +12,11 @@ public interface RegistrationInterface { * @param name è il nome utente per la sua anagrafica * @param surname è il cognome utente per la sua anagrafica * @return un codice di errore in base alla casistica + * * 0 - No error. + * * 1 - Invalid license. + * * 2 - Invalid email. + * * 3 - Unable to create user. + * * 4 - Unable to generate personal info. */ int registerNewUser(String licenseCode, String email, String password, String name, String surname); } \ No newline at end of file diff --git a/src/main/java/model/service/user/UserData.java b/src/main/java/model/service/user/UserData.java index 0ec260a..4d48b47 100644 --- a/src/main/java/model/service/user/UserData.java +++ b/src/main/java/model/service/user/UserData.java @@ -3,7 +3,7 @@ import model.DAO.DAOUser; import model.entity.User; -public class UserData /*implements UserDataInterface */{ +public class UserData implements UserDataInterface { DAOUser daoUser = new DAOUser(); public boolean checkIfEmailExists(String email) { @@ -14,7 +14,7 @@ public int createUser(String email, String password, int therapistId) { return daoUser.createUser(email, password, therapistId); } - public User getUserByIdOrEmail(Object idOrEmail) { + public User getUser(Object idOrEmail) { return daoUser.getUserByIdOrEmail(idOrEmail); } diff --git a/src/main/java/model/service/user/UserDataInterface.java b/src/main/java/model/service/user/UserDataInterface.java index 5ffe085..d412bda 100644 --- a/src/main/java/model/service/user/UserDataInterface.java +++ b/src/main/java/model/service/user/UserDataInterface.java @@ -9,10 +9,10 @@ public interface UserDataInterface { /** * Permette di ricercare un utente dato il suo id - * @param userId è il codice univoco per ricercare un utente + * @param idOrEmail è l'ID od Email per ricercare un utente, univoci * @return una classe Utente con i suoi dati correlati */ - User getUser(int userId); + User getUser(Object idOrEmail); /** * Genera il nuovo utente * @param email è l'email inserita durante la registrazione @@ -33,26 +33,27 @@ public interface UserDataInterface { * @param value contiene la nuova email * @return True se termina con successo. False altrimenti */ - boolean modifyEmail(String value); + //boolean modifyEmail(String value); /** * si occupa di modificare il consenso al tracciamento * @param value contiene True o False * @return True se termina con successo. False altrimenti */ - boolean modifyAnalytics(boolean value); + boolean updateAnalyticsPreference(String id, Boolean value); /** * si occupa di modificare il consenso alle notifiche mail * @param value contiene True o False * @return True se termina con successo. False altrimenti */ - boolean modifyEmailNotification(boolean value); + //boolean modifyEmailNotification(boolean value); //TODO /** * si occupa di modificare la fascia oraria per le notifiche - * @param time contiene l'orario delle notifiche espresso come 12:34 + * @param id contiene + * @param value contiene l'orario delle notifiche espresso come 12:34-13:00 * @return True se termina con successo. False altrimenti */ - boolean modifyTime(String time); + boolean updateEmailTime(String id, String value); } diff --git a/src/main/java/model/service/user/UserRegistryInterface.java b/src/main/java/model/service/user/UserRegistryInterface.java index b3ac1dc..25ebb3e 100644 --- a/src/main/java/model/service/user/UserRegistryInterface.java +++ b/src/main/java/model/service/user/UserRegistryInterface.java @@ -1,5 +1,7 @@ package model.service.user; +import model.entity.PersonalInfo; + public interface UserRegistryInterface { /** @@ -10,4 +12,6 @@ public interface UserRegistryInterface { * @return True se è andato a buon fine. False altrimenti */ boolean firstAccess(int id, String name, String surname); + + PersonalInfo getPersonalInfo(int id); } diff --git a/src/main/webapp/CSS/messageCenter.css b/src/main/webapp/CSS/messageCenter.css new file mode 100644 index 0000000..5d5c656 --- /dev/null +++ b/src/main/webapp/CSS/messageCenter.css @@ -0,0 +1,455 @@ +@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap'); + +* { + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: 'Poppins', sans-serif; +} + +body { + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + background: #ccc; +} + +.background-green { + position: absolute; + top: 0; + width: 100%; + height: 20%; + background-color: #f0f0f0; +} + +.main-container { + position: relative; + width: 1000px; + max-width: 100%; + height: calc(100vh - 40px); + background: #fff; + display: flex; + box-shadow: 0px 1px 1px 0 rgba(0,0,0,0.5), 0px 2px 5px 0 rgba(0,0,0,0.6); +} + +.main-container .left-container { + position:relative; + width: 30%; + height:100%; + flex: 30%; + background: #fff; +} + +.main-container .right-container { + position: relative; + width: 70%; + height: 100%; + flex: 70%; + background: #e5ddd5; +} + +.main-container .right-container::before { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: url(https://wallpapers.com/images/hd/whatsapp-chat-background-wz8v2v8xnenkb4ur.jpg); + /*https://camo.githubusercontent.com/854a93c27d64274c4f8f5a0b6ec36ee1d053cfcd934eac6c63bed9eaef9764bd/68747470733a2f2f7765622e77686174736170702e636f6d2f696d672f62672d636861742d74696c652d6461726b5f61346265353132653731393562366237333364393131306234303866303735642e706e67*/ + opacity: 0.5; +} + +.header { + position: relative; + display: flex; + align-items: center; + width: 100%; + height: 60px; + background: #ededed; + padding: 0 15px; +} + +.user-img { + position:relative; + width: 40px; + height: 40px; + overflow: hidden; + border-radius: 50%; +} + +.dp { + position:absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + object-fit: cover; + cursor: pointer; +} + +.nav-icons { + display:flex; + justify-content: flex-end; + padding-left: 110px; +} + +.nav-icons li { + backgroud-color:pink; + list-style: none; + display: flex; + cursor: pointer; + color: #51585c; + margin-left: 22px; + font-size: 18px; +} + +.notif-box { + position: relative; + display: flex; + width: 100%; + height: 70px; + background: #76daff; + align-items: center; + font-size: 0.8em; + text-decoration: none; +} + +.notif-box i { + position:relative; + left: 13px; + background:#fff; + padding:10px; + width: 42px; + height: auto; + font-size: 20px; + border-radius: 55%; + cursor: pointer; + color:#76daff; +} + +.notif-box .fa-xmark { + position: absolute; + left: 260px; + text-align:center; + background:#76daff; + color: #fff; +} + +.notif-text { + margin: 25px; +} + +.notif-text a { + text-decoration: none; + color: #333; + font-size: 0.9em; +} + +.search-container { + position:relative; + width: 100%; + height: 40px; + background: #f6f6f6; + display: flex; + /* justify-content: center; */ + align-items: center; +} + +.search-container .input input { + width: 121%; + outline: none; + border: none; + background: #fff; + padding: 5px; + height: 30x; + border-radius: 10px; + font-size: 12px; + padding-left: 60px; + margin: 10px +} + +.search-container .input i { + position: absolute; + left: 26px; + top: 14px; + color:#bbb; + font-size: 0.8em; +} + +.chat-list { + position: relative; + height:calc(100% - 170px); + overflow-y: auto; +} + +.chat-list .chat-box { + position: relative; + width: 100%; + display:flex; + /* justify-content: center; */ + align-items:center; + cursor: pointer; + padding: 15px; + border-bottom: 1px solid #eee; +} + +.chat-list .chat-box .img-box { + position:relative; + width: 55px; + height:45px; + overflow:hidden; + border-radius: 50%; +} + +.chat-list .chat-box .chat-details { + width: 100%; + margin-left: 10px; +} + +.chat-list .chat-box .chat-details .text-head { + display:flex; + justify-content: space-between; + align-items: center; + margin-bottom:2px; +} + +.chat-list .chat-box .chat-details .text-head h4 { + font-size: 1.1em; + font-weight: 600; + color: #000; +} + +.chat-list .chat-box .chat-details .text-head .time { + font-size: 0.8em; + color: #aaa; +} + +.chat-list .chat-box .chat-details .text-message { + display: flex; + justify-content: space-between; + align-items: center; +} + +.chat-list .chat-box .chat-details .text-message p { + color: #aaa; + font-size: 0.9em; + overlay: hidden; +} + +img { + width: 100%; + object-fit: cover; +} + +.chat-list .chat-box .chat-details .text-message b { + background: #06e744; + color: #fff; + min-width: 20px; + height: 20px; + border-radius: 50%; + /* text-align: center; */ + font-size: 0.8em; + font-weight: 400; + display:flex; + justify-content:center; + align-items:center; +} + +.chat-list .active { + background: #ebebeb; +} + +.chat-list .chat-box:hover { + background: #f5f5f5; +} + +.chat-list .chat-box .chat-details .text-head .unread { + color: #06e744; +} + + +/* right-container */ + + +.right-container .header { + display: flex; + justify-content: space-between; + align-items: center; +} + +.right-container .header .img-text .user-img .dp { + position:relative; + top: -2px; + left: 0px; + width: 40px; + height:auto; + overflow:hidden; + object-fit: cover; +} + +.right-container .header .img-text { + position: relative; + display: flex; + justify-content: center; + align-items: center; + cursor: pointer; +} + +.right-container .header .img-text h4 { + font-weight: 500; + line-height: 1.2em; + margin-left: 15px; +} + +.right-container .header .img-text h4 span { + font-size: 0.8em; + color: #555; +} + +.right-container .header .nav-icons { + position: relative; + margin-right:0px; + /* padding: 5px; */ +} + +.right-container .header .nav-icons i { + padding: 10px; +} + +.chat-container { + position:relative; + width: 100%; + height: calc(100% - 120px); /*60+60*/ + padding: 50px; + overflow-y: auto; +} + +.message-box { + position:relative; + display: flex; + width:100%; + margin: 5px 0; +} + +.message-box p { + position:relative; + right: 0; + text-align: right; + max-width: 65%; + padding: 12px; + background: #dcf8c6; + border-radius: 10px; + font-size: 0.9em; +} + +.message-box.my-message p::before { + content : ''; + position: absolute; + top: 0; + right: -12px; + width: 20px; + height: 20px; + background: linear-gradient(135deg, #dcf8c6 0%, #dcf8c6 50%, transparent 50%, transparent); +} + +.message-box p span { + display: block; + margin-top: 5px; + font-size: 0.8em; + opacity: 0.5; +} + +.my-message { + justify-content: flex-end; +} + +.friend-message p { + background: #fff; +} + +.friend-message { + justify-content: flex-start; + +} + +.chat-container .my-message i { + color: yellow; +} + +.message-box.friend-message::before { + content : ''; + position: absolute; + top: 0; + left: -12px; + width: 20px; + height: 20px; + background: linear-gradient(225deg, #fff 0%, #fff 50%, transparent 50%, transparent); +} + +.chatbox-input { + position:relative; + width: 100%; + height: 60px; + background: #f0f0f0; + display: flex; + justify-content: space-between; + align-items: center; +} + +.chatbox-input i { + cursor: pointer; + font-size: 1.8em; + color: #515855; +} + +.chatbox-input i:nth-child(1) { + margin: 15px; +} + +.chatbox-input i:last-child { + margin-right: 25px; +} + +.chatbox-input input { + position: relative; + width: 90%; + margin: 0 20px; + padding: 10px 20px; + border-radius:10px; + font-size: 1em; + border:none; + outline:none; +} + +@media (max-width: 768px) { + .main-container { + flex-direction: column; + } + .main-container .left-container, + .main-container .right-container { + width: 100%; + flex: auto; /* reset the flex property */ + } + .main-container .right-container { + display: none; /* initially hide right container */ + } + /* CSS class to be added by JS when a chat is selected */ + .main-container.show-right .left-container { + display: none; + } + .main-container.show-right .right-container { + display: block; + } + /* CSS rules for back button */ + #back-button { + position: fixed; + top: 0; + left: 0; + display: none; /* initially hidden */ + } + .main-container.show-right #back-button { + display: block; + } +} \ No newline at end of file diff --git a/src/main/webapp/JS/message.js b/src/main/webapp/JS/message.js new file mode 100644 index 0000000..694c7ba --- /dev/null +++ b/src/main/webapp/JS/message.js @@ -0,0 +1,142 @@ +$(".heading-compose").click(function() { + $(".side-two").css({ + "left": "0" + }); +}); + +$(".newMessage-back").click(function() { + $(".side-two").css({ + "left": "-100%" + }); +}); + +$(document).ready(function() { + // When a chat-box is clicked... + $(".chat-box").on("click", function() { + // Add a class to the main container to show right container and hide left container + $(".main-container").addClass("show-right"); + }); + + // When back button is clicked... + $("#back-button").on("click", function() { + // Remove the class from the main container to hide right container and show left container + $(".main-container").removeClass("show-right"); + }); +}); + +var count = -1; +setInterval(function(){ + // Make an AJAX request to your servlet, replace the URL as required + $.ajax({ + url: '../CountMessages', + type: 'GET', + data: { + }, + success: function (response) { + if(count < 0) + count = response; + if(count > 0 && response > count){ + count = response; + alert('Hai dei nuovi messaggi, ricarica la pagina per visualizzarli.'); + } + } + }); +}, 10000); // The interval set is 10000ms = 10 seconds + +var contact_id; +$(document).ready(function() { + $('.chat-box').on('click', function() { + // Remove "active" class from all ".chat-box" divs + $('.chat-box').removeClass('active'); + // Add "active" class to the clicked ".chat-box" + $(this).addClass('active'); + + var contact_name = $(this).find(".text-head h4").text(); + $('#contactOpened').text(contact_name); + + var unread_indicator = $(this).find('.unread-messages'); + unread_indicator.hide(); + + $(".right-container").removeAttr("hidden"); + //access which type of ID the user wanted to read or message to + contact_id = $(this).data('contact-id'); + + if (contact_id === 0) { + // Prevent user from writing in the text field + $(".chatbox-input input").prop('readonly', true).attr('placeholder', "Non puoi inviare un messaggio"); + } else { + // Allow user to write in the text field + $(".chatbox-input input").prop('readonly', false).attr('placeholder', "Componi un messaggio"); + } + $.ajax({ + url: '../GetMessages', + method: 'GET', + data: { contact_id: contact_id }, + success: function(data) { + var chatContainer = $(".chat-container"); + chatContainer.empty(); // Clear existing messages if any + + data.forEach(function(message) { + // Determine if current user is sender or recipient + var messageBoxClass = contact_id == message.sender ? 'friend-message' : 'my-message'; // Replace userId with actual user id + + var messageBox = $('
').addClass('message-box').addClass(messageBoxClass); + var messageContent = $('

').text(message.body); + var messageTime = $('').text(message.sent); + messageContent.append($('
'), messageTime); + messageBox.append(messageContent); + + chatContainer.append(messageBox); + }); + }, + error: function(error) { + // handle error response + } + }); + + }); +}); + +$(document).ready(function() { + var input = $('.chatbox-input input'); + + input.on('keydown', function (e) { + if (e.key == 'Enter') { + e.preventDefault(); + + var message = input.val().trim(); // get the message from the input field + + if (message === "") { + return; // if no message was typed and 'Enter' is pressed, do nothing + } + var date = new Date(); + var hours = date.getHours(); + var minutes = date.getMinutes(); + +// Pad with '0' to make sure we always get 2 digits + hours = (hours < 10) ? "0" + hours : hours; + minutes = (minutes < 10) ? "0" + minutes : minutes; + + var time = hours + ":" + minutes; // current time in "HH:MM" format + // append the message to the chat container + var msgHtml = '

' + message + '
' + time + '

'; + $('.chat-container').append(msgHtml); + + // clear the input field + input.val(''); + + // make a POST request to your servlet + $.ajax({ + url: '../GetMessages', + type: 'POST', + data: { + // change with actual sender ID + recipient: contact_id, + body: message + }, + success: function (response) { + } + }); + } + }); +}); \ No newline at end of file diff --git a/src/main/webapp/JSP/login.jsp b/src/main/webapp/JSP/login.jsp index c181632..8e78cfb 100644 --- a/src/main/webapp/JSP/login.jsp +++ b/src/main/webapp/JSP/login.jsp @@ -73,7 +73,7 @@
- + diff --git a/src/main/webapp/JSP/messageCenter.jsp b/src/main/webapp/JSP/messageCenter.jsp new file mode 100644 index 0000000..6f0473a --- /dev/null +++ b/src/main/webapp/JSP/messageCenter.jsp @@ -0,0 +1,100 @@ +<%@ page import="model.service.message.MessageManager" %> +<%@ page import="java.util.List" %> +<%@ page import="model.service.user.UserData" %> +<%@ page import="model.entity.User" %> +<%@ page import="model.service.user.UserRegistry" %> +<%@ page import="model.entity.PersonalInfo" %> +<%@ page import="model.service.message.MessageManager" %> + + + + <%@page contentType="text/html;charset=UTF-8"%> + + + + + + + + TalkAId - Centro Messaggi + + +
+ + +
+
+ + +
+ <% + if(session.getAttribute("id") == "null") { + response.sendRedirect("../errorPage/403.html"); + } + else { + int userId = (Integer) session.getAttribute("id"); + MessageManager messageManager = new MessageManager(); + List list = messageManager.retrieveAllTheContacts(userId); + for(int contact : list) { + UserRegistry ur = new UserRegistry(); + PersonalInfo data = ur.getPersonalInfo(contact); + int toRead = messageManager.getUnreadMessagesForConversation(userId, contact); + %> +
+
+ +
+
+
+

<%=data.getFirstname()%> <%=data.getLastname()%>

+ +
+
+ <%if(toRead!=0) { %> + <%=toRead%> + <%} %> +
+
+
+ <% + } } + %> +
+ +
+ + + + + + + +
+ + \ No newline at end of file