Class ChatService

java.lang.Object
vaultWeb.services.ChatService

@Service public class ChatService extends Object
Service responsible for handling chat-related operations.

This service provides methods to save and decrypt chat messages for both group chats and private chats. Messages are encrypted before being stored in the database to ensure confidentiality. The service supports identifying the sender either by ID or username and can handle automatic timestamping if none is provided.

Main responsibilities:

  • Validate sender existence by ID or username.
  • Encrypt message content before saving.
  • Associate messages with a group or private chat.
  • Persist chat messages into the database.
  • Decrypt stored messages on demand.
  • Constructor Details

    • ChatService

      public ChatService()
  • Method Details

    • saveMessage

      public ChatMessage saveMessage(ChatMessageDto dto)
      Saves a chat message to a group or private chat.

      The message content is encrypted before being persisted. The sender is identified either by ID or username. If a timestamp is not provided, the current time is used. The message must belong to either a group or a private chat.

      Parameters:
      dto - DTO containing the message content, sender information, timestamp, and either a groupId or privateChatId.
      Returns:
      The persisted ChatMessage entity with encrypted content.
      Throws:
      UserNotFoundException - if the sender cannot be found by ID or username.
      GroupNotFoundException - if neither groupId nor privateChatId is provided, or if the specified group/private chat does not exist.
      EncryptionFailedException - if encryption fails.
    • decrypt

      public String decrypt(String cipherTextBase64, String ivBase64)
      Decrypts a previously encrypted chat message.

      Uses the IV and cipher text stored in the database to decrypt and return the original message content as a plain string.

      Parameters:
      cipherTextBase64 - The encrypted message in Base64 encoding.
      ivBase64 - The initialization vector used during encryption, in Base64.
      Returns:
      The decrypted plain text message.
      Throws:
      DecryptionFailedException - if decryption fails.