Skip to content

Commit

Permalink
Merge pull request #142 from Tech-Harbor/Bezsmertnyi
Browse files Browse the repository at this point in the history
Bezsmertnyi | WebSocket, LICENSE
  • Loading branch information
Vladik-gif authored Jul 11, 2024
2 parents 230cc40 + cc07051 commit d0729d7
Show file tree
Hide file tree
Showing 18 changed files with 329 additions and 5 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Oranger

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion src/main/java/com/example/backend/mail/MailService.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@

public interface MailService {
void sendEmail(UserSecurityDTO user, MailType type, Properties params);
}
}
26 changes: 26 additions & 0 deletions src/main/java/com/example/backend/mail/MailServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public void sendEmail(final UserSecurityDTO user, final MailType type, final Pro
switch (type) {
case REGISTRATION -> sendRegistrationEmail(user);
case NEW_PASSWORD -> sendNewPassword(user);
case UPDATED_PASSWORD -> sendUpdatedPassword(user);
default -> { }
}
}
Expand Down Expand Up @@ -84,4 +85,29 @@ private String getNewPasswordContent(final UserSecurityDTO user) {

return writer.getBuffer().toString();
}

@SneakyThrows
private void sendUpdatedPassword(final UserSecurityDTO user) {
final var mimeUpdatedPasswordMessage = mailSender.createMimeMessage();
final var passwordContent = getUpdatedPasswordContent(user);
final var helper = new MimeMessageHelper(mimeUpdatedPasswordMessage, false, UTF_8);

helper.setSubject("Updated Password, " + user.lastname());
helper.setTo(user.email());
helper.setText(passwordContent, true);

mailSender.send(mimeUpdatedPasswordMessage);
}

@SneakyThrows
private String getUpdatedPasswordContent(final UserSecurityDTO user) {
final var writer = new StringWriter();
final var model = new HashMap<String, Object>();

model.put("username", user.lastname());

configuration.getTemplate("updatedPassword.ftlh").process(model, writer);

return writer.getBuffer().toString();
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/example/backend/mail/MailType.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.example.backend.mail;

public enum MailType {
REGISTRATION, NEW_PASSWORD
}
REGISTRATION, NEW_PASSWORD, UPDATED_PASSWORD
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ public void formUpdatePassword(final String jwt, final PasswordRequest passwordR

log.info("Update Password: {}", user.getFirstname());

userService.mySecuritySave(user);
final var userSecurityDTO = userService.mySecuritySave(user);

mailService.sendEmail(userSecurityDTO, MailType.UPDATED_PASSWORD, new Properties());
}
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example.backend.websocket.controller;

import com.example.backend.websocket.models.ChatMessageEntity;
import com.example.backend.websocket.service.ChatMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class ChatController {

private final ChatMessageService chatMessageService;

@MessageMapping("/chat")
public void processMessage(final @Payload ChatMessageEntity chatMessage) {
chatMessageService.processMessage(chatMessage);
}

@GetMapping("/messages/{senderId}/{recipientId}")
public List<ChatMessageEntity> findChatMessages(final @PathVariable String senderId,
final @PathVariable String recipientId) {
return chatMessageService.findChatMessages(senderId, recipientId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.example.backend.websocket.models;

import jakarta.persistence.*;
import lombok.*;
import java.util.Date;

@Entity
@Table(name = "chatMessage")
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ChatMessageEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String chatId;
private String senderId;
private String recipientId;
private String content;
private Date timestamp;
private MessageType type;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.backend.websocket.models;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ChatMessageRepository extends JpaRepository<ChatMessageEntity, Long> {
List<ChatMessageEntity> findByChatId(String chatId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.backend.websocket.models;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatNotification {
private String senderId;
private String recipientId;
private String content;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.example.backend.websocket.models;

import jakarta.persistence.*;
import lombok.*;

@Entity
@Table(name = "chatRoom")
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ChatRoomEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String chatId;
private String senderId;
private String recipientId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.backend.websocket.models;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface ChatRoomRepository extends JpaRepository<ChatRoomEntity, Long> {
Optional<ChatRoomEntity> findBySenderIdAndRecipientId(String senderId, String recipientId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.example.backend.websocket.models;

public enum MessageType {
CHAT, LEAVE, JOIN
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.backend.websocket.service;

import com.example.backend.websocket.models.ChatMessageEntity;

import java.util.List;

public interface ChatMessageService {
void processMessage(ChatMessageEntity chatMessage);
List<ChatMessageEntity> findChatMessages(String senderId, String recipientId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.backend.websocket.service;

import com.example.backend.websocket.models.ChatMessageEntity;
import com.example.backend.websocket.models.ChatMessageRepository;
import com.example.backend.websocket.models.ChatNotification;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.example.backend.utils.exception.RequestException.badRequestException;

@Component
@RequiredArgsConstructor
public class ChatMessageServiceImpl implements ChatMessageService {

private final SimpMessagingTemplate messagingTemplate;
private final ChatMessageRepository repository;
private final ChatRoomService chatRoomService;

@Override
public void processMessage(final ChatMessageEntity chatMessage) {
final var savedMsg = save(chatMessage);

messagingTemplate.convertAndSendToUser(
chatMessage.getRecipientId(), "/queue/messages",

new ChatNotification(savedMsg.getSenderId(), savedMsg.getRecipientId(), savedMsg.getContent())
);
}

@Override
public List<ChatMessageEntity> findChatMessages(final String senderId, final String recipientId) {
var chatId = chatRoomService.getChatRoomId(senderId, recipientId, false);
return chatId.map(repository::findByChatId).orElse(new ArrayList<>());
}

private ChatMessageEntity save(final ChatMessageEntity chatMessage) {
var chatId = chatRoomService
.getChatRoomId(chatMessage.getSenderId(), chatMessage.getRecipientId(), true)
.orElseThrow(
() -> badRequestException("chat does not exist")
);

chatMessage.setChatId(chatId);

return repository.save(chatMessage);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.backend.websocket.service;

import java.util.Optional;

public interface ChatRoomService {
Optional<String> getChatRoomId(String senderId, String recipientId, boolean createNewRoomIfNotExists);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.example.backend.websocket.service;

import com.example.backend.websocket.models.ChatRoomEntity;
import com.example.backend.websocket.models.ChatRoomRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@RequiredArgsConstructor
public class ChatRoomServiceImpl implements ChatRoomService {

private final ChatRoomRepository chatRoomRepository;

@Override
public Optional<String> getChatRoomId(final String senderId,
final String recipientId,
final boolean createNewRoomIfNotExists) {
return chatRoomRepository
.findBySenderIdAndRecipientId(senderId, recipientId)
.map(ChatRoomEntity::getChatId)
.or(() -> {
if (createNewRoomIfNotExists) {
return Optional.of(createChatId(senderId, recipientId));
}
return Optional.empty();
}
);
}

private String createChatId(final String senderId, final String recipientId) {
final var chatId = String.format("%s_%s", senderId, recipientId);

final var senderRecipient = ChatRoomEntity.builder()
.chatId(chatId)
.senderId(senderId)
.recipientId(recipientId)
.build();

final var recipientSender = ChatRoomEntity.builder()
.chatId(chatId)
.senderId(recipientId)
.recipientId(senderId)
.build();

chatRoomRepository.save(senderRecipient);
chatRoomRepository.save(recipientSender);

return chatId;
}
}
36 changes: 36 additions & 0 deletions src/main/resources/templates/updatedPassword.ftlh
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<#ftl encoding="UTF-8">
<html lang="ru">
<head>
<meta charset="UTF-8">
<style>
#body {
display: flex;
flex-direction: column;
font-family: "Segoe UI", serif;
align-items: center;
background-color: #FF8A00;
font-size: 20px;
height: 100%;
}

#div {
display: block;
margin: 10%;
font-family: "Segoe UI", serif;
background-color: #E8F6DC;
padding: 3%;
border-radius: 20px;
color: #1B1E23;
}
</style>
</head>
<body>
<div id="body">
<div id="div">
<h1 style="text-align: center">Updated Password</h1>
<p style="text-align: center">Ви успішно змінили пароль, ${username}!</p>
<a href="https://oranger.store/">Oranger</a>
</div>
</div>
</body>
</html>
Loading

0 comments on commit d0729d7

Please sign in to comment.