ChatMessageController.java
package edu.ucsb.cs156.happiercows.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import edu.ucsb.cs156.happiercows.entities.ChatMessage;
import edu.ucsb.cs156.happiercows.repositories.ChatMessageRepository;
import edu.ucsb.cs156.happiercows.entities.BannedWord;
import edu.ucsb.cs156.happiercows.entities.User;
import edu.ucsb.cs156.happiercows.entities.Farmer;
import edu.ucsb.cs156.happiercows.models.ChatMessagePostResponse;
import edu.ucsb.cs156.happiercows.repositories.BannedWordRepository;
import edu.ucsb.cs156.happiercows.repositories.FarmerRepository;
import edu.ucsb.cs156.happiercows.repositories.UserRepository;
import edu.ucsb.cs156.happiercows.services.ProfanityFilterService;
import org.springframework.security.core.Authentication;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.regex.Pattern;
@Tag(name = "Chat Message")
@RequestMapping("/api/chat")
@RestController
@Slf4j
public class ChatMessageController extends ApiController{
@Autowired
private ChatMessageRepository chatMessageRepository;
@Autowired
private FarmerRepository farmerRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private BannedWordRepository bannedWordRepository;
@Autowired
private ProfanityFilterService profanityFilterService;
@Autowired
ObjectMapper mapper;
// How long a user is blocked from chatting after sending a message that contains a banned word
static final Duration BANNED_WORD_COOLDOWN = Duration.ofMinutes(5);
/**
* Returns the first word from the banned_words table that the content contains,
* or empty if it contains none.
* Matching is case-insensitive and whole-word only, so a banned word that
* appears inside a longer word (e.g. "darn" in "darned") does not match.
*/
Optional<String> findBannedWord(String content) {
for (BannedWord bannedWord : bannedWordRepository.findAll()) {
Pattern pattern = Pattern.compile(
"(?<![\\p{L}\\p{N}])" + Pattern.quote(bannedWord.getWord()) + "(?![\\p{L}\\p{N}])",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
if (pattern.matcher(content).find()) {
return Optional.of(bannedWord.getWord());
}
}
return Optional.empty();
}
@Operation(summary = "Get all chat messages", description = "Get all chat messages associated with a specific game.")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@GetMapping("/get")
public ResponseEntity<Object> getChatMessages(@Parameter(description = "The id of the common") @RequestParam Long gameId,
@Parameter(name="page") @RequestParam int page,
@Parameter(name="size") @RequestParam int size) {
// Make sure the user is part of the game and showChat is true, or user is an admin
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){
log.info("User is not an admin");
User user = getCurrentUser().getUser();
Long userId = user.getId();
Optional<Farmer> farmerLookup = farmerRepository.findByGameIdAndUserId(gameId, userId);
if (!farmerLookup.isPresent()) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
Farmer farmer = farmerLookup.get();
if(!farmer.getGame().isShowChat()){
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
// Return the list of non-hidden chat messages
Page<ChatMessage> messages = chatMessageRepository.findByGameId(gameId, PageRequest.of(page, size, Sort.by("timestamp").descending()));
return ResponseEntity.ok(messages);
}
@Operation(summary = "Get all chat messages (Admins)", description = "Get all chat messages associated with a specific game, even the hidden ones. Used only by admins")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin/get")
public ResponseEntity<Object> getAllChatMessages(@Parameter(description = "The id of the common") @RequestParam Long gameId,
@Parameter(name="page") @RequestParam int page,
@Parameter(name="size") @RequestParam int size) {
// Return the list of chat messages
Page<ChatMessage> messages = chatMessageRepository.findAllByGameId(gameId, PageRequest.of(page, size, Sort.by("timestamp").descending()));
return ResponseEntity.ok(messages);
}
@Operation(summary = "Get hidden chat messages", description = "Get all hidden chat messages associated with a specific game. Used only by admins")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin/hidden")
public ResponseEntity<Object> getHiddenChatMessages(@Parameter(description = "The id of the common") @RequestParam Long gameId,
@Parameter(name="page") @RequestParam int page,
@Parameter(name="size") @RequestParam int size) {
// Return the list of hidden chat messages
Page<ChatMessage> messages = chatMessageRepository.findByGameIdAndHidden(gameId, PageRequest.of(page, size, Sort.by("timestamp").descending()));
return ResponseEntity.ok(messages);
}
@Operation(summary = "Create a chat message", description = "Create a chat message associated with a specific game")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@PostMapping("/post")
public ResponseEntity<Object> createChatMessage(@Parameter(description = "The id of the common") @RequestParam Long gameId,
@Parameter(description = "The message to be sent") @RequestParam String content) {
User user = getCurrentUser().getUser();
Long userId = user.getId();
// Read fresh from DB so a cooldown set after login applies immediately
User freshUser = userRepository.findById(userId).orElse(user);
Instant cooldownUntil = freshUser.getChatCooldownUntil();
if (cooldownUntil != null && cooldownUntil.isAfter(Instant.now())) {
long secondsLeft = Duration.between(Instant.now(), cooldownUntil).toSeconds() + 1;
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(genericMessage("You are on a chat cooldown for %d more seconds".formatted(secondsLeft)));
}
// Make sure the user is part of the game and showChat is true, or user is an admin
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){
log.info("User is not an admin");
Optional<Farmer> farmerLookup = farmerRepository.findByGameIdAndUserId(gameId, userId);
if (!farmerLookup.isPresent()) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
Farmer farmer = farmerLookup.get();
if(!farmer.getGame().isShowChat()){
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
// A banned word puts the sender on a chat cooldown; the message is still posted.
// Any earlier cooldown has already expired (otherwise we returned 403 above),
// so this can never shorten an existing cooldown.
Optional<String> bannedWord = findBannedWord(content);
if (bannedWord.isPresent()) {
freshUser.setChatCooldownUntil(Instant.now().plus(BANNED_WORD_COOLDOWN));
userRepository.save(freshUser);
}
// Create the chat message
ChatMessage chatMessage = ChatMessage.builder()
.gameId(gameId)
.userId(userId)
.message(profanityFilterService.censor(content))
.hidden(false)
.dm(false)
.toUserId(0)
.build();
// Save the message
chatMessageRepository.save(chatMessage);
// Tell the sender which banned word triggered the cooldown and for how long,
// so the frontend can show them a notice right away.
ChatMessagePostResponse body = ChatMessagePostResponse.builder()
.chatMessage(chatMessage)
.bannedWord(bannedWord.orElse(null))
.cooldownSeconds(bannedWord.isPresent() ? BANNED_WORD_COOLDOWN.toSeconds() : null)
.build();
return ResponseEntity.ok(body);
}
@Operation(summary = "Delete a chat message", description = "Delete a chat message associated with a specific game")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@PutMapping("/hide")
public ResponseEntity<Object> hideChatMessage(@Parameter(description = "The id of the chat message") @RequestParam Long chatMessageId) {
// Try to get the chat message
Optional<ChatMessage> chatMessageLookup = chatMessageRepository.findById(chatMessageId);
if (!chatMessageLookup.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
ChatMessage chatMessage = chatMessageLookup.get();
User user = getCurrentUser().getUser();
Long userId = user.getId();
// Check if the user is the author of the message
if (chatMessage.getUserId() != userId) {
// Check if the user is an admin
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
// Check if showChat is true
Optional<Farmer> farmerLookup = farmerRepository.findByGameIdAndUserId(chatMessage.getGameId(), userId);
Farmer farmer = farmerLookup.get();
if (!farmer.getGame().isShowChat()){
// Check if the user is an admin
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
// Hide the message
chatMessage.setHidden(true);
chatMessageRepository.save(chatMessage);
return ResponseEntity.ok(chatMessage);
}
}