| 1 | package edu.ucsb.cs156.happiercows.controllers; | |
| 2 | ||
| 3 | import com.fasterxml.jackson.databind.ObjectMapper; | |
| 4 | import io.swagger.v3.oas.annotations.tags.Tag; | |
| 5 | import lombok.extern.slf4j.Slf4j; | |
| 6 | import io.swagger.v3.oas.annotations.Operation; | |
| 7 | import io.swagger.v3.oas.annotations.Parameter; | |
| 8 | import org.springframework.beans.factory.annotation.Autowired; | |
| 9 | import org.springframework.http.HttpStatus; | |
| 10 | import org.springframework.http.ResponseEntity; | |
| 11 | import org.springframework.security.access.prepost.PreAuthorize; | |
| 12 | import org.springframework.security.core.context.SecurityContextHolder; | |
| 13 | import org.springframework.web.bind.annotation.*; | |
| 14 | import org.springframework.data.domain.Page; | |
| 15 | import org.springframework.data.domain.PageRequest; | |
| 16 | import org.springframework.data.domain.Sort; | |
| 17 | ||
| 18 | import edu.ucsb.cs156.happiercows.entities.ChatMessage; | |
| 19 | import edu.ucsb.cs156.happiercows.repositories.ChatMessageRepository; | |
| 20 | ||
| 21 | import edu.ucsb.cs156.happiercows.entities.BannedWord; | |
| 22 | import edu.ucsb.cs156.happiercows.entities.User; | |
| 23 | import edu.ucsb.cs156.happiercows.entities.Farmer; | |
| 24 | import edu.ucsb.cs156.happiercows.models.ChatMessagePostResponse; | |
| 25 | import edu.ucsb.cs156.happiercows.repositories.BannedWordRepository; | |
| 26 | import edu.ucsb.cs156.happiercows.repositories.FarmerRepository; | |
| 27 | import edu.ucsb.cs156.happiercows.repositories.UserRepository; | |
| 28 | import edu.ucsb.cs156.happiercows.services.ProfanityFilterService; | |
| 29 | ||
| 30 | import org.springframework.security.core.Authentication; | |
| 31 | ||
| 32 | ||
| 33 | import java.time.Duration; | |
| 34 | import java.time.Instant; | |
| 35 | import java.util.Optional; | |
| 36 | import java.util.regex.Pattern; | |
| 37 | ||
| 38 | @Tag(name = "Chat Message") | |
| 39 | @RequestMapping("/api/chat") | |
| 40 | @RestController | |
| 41 | @Slf4j | |
| 42 | public class ChatMessageController extends ApiController{ | |
| 43 | ||
| 44 | @Autowired | |
| 45 | private ChatMessageRepository chatMessageRepository; | |
| 46 | ||
| 47 | @Autowired | |
| 48 | private FarmerRepository farmerRepository; | |
| 49 | ||
| 50 | @Autowired | |
| 51 | private UserRepository userRepository; | |
| 52 | ||
| 53 | @Autowired | |
| 54 | private BannedWordRepository bannedWordRepository; | |
| 55 | ||
| 56 | @Autowired | |
| 57 | private ProfanityFilterService profanityFilterService; | |
| 58 | ||
| 59 | @Autowired | |
| 60 | ObjectMapper mapper; | |
| 61 | ||
| 62 | // How long a user is blocked from chatting after sending a message that contains a banned word | |
| 63 | static final Duration BANNED_WORD_COOLDOWN = Duration.ofMinutes(5); | |
| 64 | ||
| 65 | /** | |
| 66 | * Returns the first word from the banned_words table that the content contains, | |
| 67 | * or empty if it contains none. | |
| 68 | * Matching is case-insensitive and whole-word only, so a banned word that | |
| 69 | * appears inside a longer word (e.g. "darn" in "darned") does not match. | |
| 70 | */ | |
| 71 | Optional<String> findBannedWord(String content) { | |
| 72 | for (BannedWord bannedWord : bannedWordRepository.findAll()) { | |
| 73 | Pattern pattern = Pattern.compile( | |
| 74 | "(?<![\\p{L}\\p{N}])" + Pattern.quote(bannedWord.getWord()) + "(?![\\p{L}\\p{N}])", | |
| 75 | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); | |
| 76 |
1
1. findBannedWord : negated conditional → KILLED |
if (pattern.matcher(content).find()) { |
| 77 |
1
1. findBannedWord : replaced return value with Optional.empty for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::findBannedWord → KILLED |
return Optional.of(bannedWord.getWord()); |
| 78 | } | |
| 79 | } | |
| 80 | return Optional.empty(); | |
| 81 | } | |
| 82 | ||
| 83 | @Operation(summary = "Get all chat messages", description = "Get all chat messages associated with a specific game.") | |
| 84 | @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')") | |
| 85 | @GetMapping("/get") | |
| 86 | public ResponseEntity<Object> getChatMessages(@Parameter(description = "The id of the common") @RequestParam Long gameId, | |
| 87 | @Parameter(name="page") @RequestParam int page, | |
| 88 | @Parameter(name="size") @RequestParam int size) { | |
| 89 | | |
| 90 | // Make sure the user is part of the game and showChat is true, or user is an admin | |
| 91 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
| 92 |
3
1. lambda$getChatMessages$0 : replaced boolean return with false for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$getChatMessages$0 → KILLED 2. lambda$getChatMessages$0 : replaced boolean return with true for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$getChatMessages$0 → KILLED 3. getChatMessages : negated conditional → KILLED |
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){ |
| 93 | log.info("User is not an admin"); | |
| 94 | User user = getCurrentUser().getUser(); | |
| 95 | Long userId = user.getId(); | |
| 96 | Optional<Farmer> farmerLookup = farmerRepository.findByGameIdAndUserId(gameId, userId); | |
| 97 | ||
| 98 |
1
1. getChatMessages : negated conditional → KILLED |
if (!farmerLookup.isPresent()) { |
| 99 |
1
1. getChatMessages : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::getChatMessages → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); |
| 100 | } | |
| 101 | ||
| 102 | Farmer farmer = farmerLookup.get(); | |
| 103 |
1
1. getChatMessages : negated conditional → KILLED |
if(!farmer.getGame().isShowChat()){ |
| 104 |
1
1. getChatMessages : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::getChatMessages → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); |
| 105 | } | |
| 106 | } | |
| 107 | ||
| 108 | // Return the list of non-hidden chat messages | |
| 109 | Page<ChatMessage> messages = chatMessageRepository.findByGameId(gameId, PageRequest.of(page, size, Sort.by("timestamp").descending())); | |
| 110 |
1
1. getChatMessages : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::getChatMessages → KILLED |
return ResponseEntity.ok(messages); |
| 111 | } | |
| 112 | ||
| 113 | @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") | |
| 114 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
| 115 | @GetMapping("/admin/get") | |
| 116 | public ResponseEntity<Object> getAllChatMessages(@Parameter(description = "The id of the common") @RequestParam Long gameId, | |
| 117 | @Parameter(name="page") @RequestParam int page, | |
| 118 | @Parameter(name="size") @RequestParam int size) { | |
| 119 | | |
| 120 | // Return the list of chat messages | |
| 121 | Page<ChatMessage> messages = chatMessageRepository.findAllByGameId(gameId, PageRequest.of(page, size, Sort.by("timestamp").descending())); | |
| 122 |
1
1. getAllChatMessages : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::getAllChatMessages → KILLED |
return ResponseEntity.ok(messages); |
| 123 | } | |
| 124 | ||
| 125 | | |
| 126 | @Operation(summary = "Get hidden chat messages", description = "Get all hidden chat messages associated with a specific game. Used only by admins") | |
| 127 | @PreAuthorize("hasRole('ROLE_ADMIN')") | |
| 128 | @GetMapping("/admin/hidden") | |
| 129 | public ResponseEntity<Object> getHiddenChatMessages(@Parameter(description = "The id of the common") @RequestParam Long gameId, | |
| 130 | @Parameter(name="page") @RequestParam int page, | |
| 131 | @Parameter(name="size") @RequestParam int size) { | |
| 132 | | |
| 133 | // Return the list of hidden chat messages | |
| 134 | Page<ChatMessage> messages = chatMessageRepository.findByGameIdAndHidden(gameId, PageRequest.of(page, size, Sort.by("timestamp").descending())); | |
| 135 |
1
1. getHiddenChatMessages : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::getHiddenChatMessages → KILLED |
return ResponseEntity.ok(messages); |
| 136 | } | |
| 137 | | |
| 138 | | |
| 139 | @Operation(summary = "Create a chat message", description = "Create a chat message associated with a specific game") | |
| 140 | @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')") | |
| 141 | @PostMapping("/post") | |
| 142 | public ResponseEntity<Object> createChatMessage(@Parameter(description = "The id of the common") @RequestParam Long gameId, | |
| 143 | @Parameter(description = "The message to be sent") @RequestParam String content) { | |
| 144 | | |
| 145 | User user = getCurrentUser().getUser(); | |
| 146 | Long userId = user.getId(); | |
| 147 | ||
| 148 | // Read fresh from DB so a cooldown set after login applies immediately | |
| 149 | User freshUser = userRepository.findById(userId).orElse(user); | |
| 150 | Instant cooldownUntil = freshUser.getChatCooldownUntil(); | |
| 151 |
2
1. createChatMessage : negated conditional → KILLED 2. createChatMessage : negated conditional → KILLED |
if (cooldownUntil != null && cooldownUntil.isAfter(Instant.now())) { |
| 152 |
1
1. createChatMessage : Replaced long addition with subtraction → KILLED |
long secondsLeft = Duration.between(Instant.now(), cooldownUntil).toSeconds() + 1; |
| 153 |
1
1. createChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::createChatMessage → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN) |
| 154 | .body(genericMessage("You are on a chat cooldown for %d more seconds".formatted(secondsLeft))); | |
| 155 | } | |
| 156 | ||
| 157 | // Make sure the user is part of the game and showChat is true, or user is an admin | |
| 158 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
| 159 |
3
1. createChatMessage : negated conditional → KILLED 2. lambda$createChatMessage$0 : replaced boolean return with false for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$createChatMessage$0 → KILLED 3. lambda$createChatMessage$0 : replaced boolean return with true for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$createChatMessage$0 → KILLED |
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){ |
| 160 | log.info("User is not an admin"); | |
| 161 | Optional<Farmer> farmerLookup = farmerRepository.findByGameIdAndUserId(gameId, userId); | |
| 162 | ||
| 163 |
1
1. createChatMessage : negated conditional → KILLED |
if (!farmerLookup.isPresent()) { |
| 164 |
1
1. createChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::createChatMessage → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); |
| 165 | } | |
| 166 | ||
| 167 | Farmer farmer = farmerLookup.get(); | |
| 168 |
1
1. createChatMessage : negated conditional → KILLED |
if(!farmer.getGame().isShowChat()){ |
| 169 |
1
1. createChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::createChatMessage → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); |
| 170 | } | |
| 171 | } | |
| 172 | ||
| 173 | // A banned word puts the sender on a chat cooldown; the message is still posted. | |
| 174 | // Any earlier cooldown has already expired (otherwise we returned 403 above), | |
| 175 | // so this can never shorten an existing cooldown. | |
| 176 | Optional<String> bannedWord = findBannedWord(content); | |
| 177 |
1
1. createChatMessage : negated conditional → KILLED |
if (bannedWord.isPresent()) { |
| 178 |
1
1. createChatMessage : removed call to edu/ucsb/cs156/happiercows/entities/User::setChatCooldownUntil → KILLED |
freshUser.setChatCooldownUntil(Instant.now().plus(BANNED_WORD_COOLDOWN)); |
| 179 | userRepository.save(freshUser); | |
| 180 | } | |
| 181 | ||
| 182 | // Create the chat message | |
| 183 | ChatMessage chatMessage = ChatMessage.builder() | |
| 184 | .gameId(gameId) | |
| 185 | .userId(userId) | |
| 186 | .message(profanityFilterService.censor(content)) | |
| 187 | .hidden(false) | |
| 188 | .dm(false) | |
| 189 | .toUserId(0) | |
| 190 | .build(); | |
| 191 | ||
| 192 | // Save the message | |
| 193 | chatMessageRepository.save(chatMessage); | |
| 194 | ||
| 195 | // Tell the sender which banned word triggered the cooldown and for how long, | |
| 196 | // so the frontend can show them a notice right away. | |
| 197 | ChatMessagePostResponse body = ChatMessagePostResponse.builder() | |
| 198 | .chatMessage(chatMessage) | |
| 199 | .bannedWord(bannedWord.orElse(null)) | |
| 200 |
1
1. createChatMessage : negated conditional → KILLED |
.cooldownSeconds(bannedWord.isPresent() ? BANNED_WORD_COOLDOWN.toSeconds() : null) |
| 201 | .build(); | |
| 202 | ||
| 203 |
1
1. createChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::createChatMessage → KILLED |
return ResponseEntity.ok(body); |
| 204 | } | |
| 205 | ||
| 206 | @Operation(summary = "Delete a chat message", description = "Delete a chat message associated with a specific game") | |
| 207 | @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')") | |
| 208 | @PutMapping("/hide") | |
| 209 | public ResponseEntity<Object> hideChatMessage(@Parameter(description = "The id of the chat message") @RequestParam Long chatMessageId) { | |
| 210 | ||
| 211 | // Try to get the chat message | |
| 212 | Optional<ChatMessage> chatMessageLookup = chatMessageRepository.findById(chatMessageId); | |
| 213 |
1
1. hideChatMessage : negated conditional → KILLED |
if (!chatMessageLookup.isPresent()) { |
| 214 |
1
1. hideChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::hideChatMessage → KILLED |
return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); |
| 215 | } | |
| 216 | ChatMessage chatMessage = chatMessageLookup.get(); | |
| 217 | ||
| 218 | User user = getCurrentUser().getUser(); | |
| 219 | Long userId = user.getId(); | |
| 220 | ||
| 221 | // Check if the user is the author of the message | |
| 222 |
1
1. hideChatMessage : negated conditional → KILLED |
if (chatMessage.getUserId() != userId) { |
| 223 | // Check if the user is an admin | |
| 224 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
| 225 |
3
1. hideChatMessage : negated conditional → KILLED 2. lambda$hideChatMessage$0 : replaced boolean return with false for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$hideChatMessage$0 → KILLED 3. lambda$hideChatMessage$0 : replaced boolean return with true for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$hideChatMessage$0 → KILLED |
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){ |
| 226 |
1
1. hideChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::hideChatMessage → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); |
| 227 | } | |
| 228 | } | |
| 229 | ||
| 230 | // Check if showChat is true | |
| 231 | Optional<Farmer> farmerLookup = farmerRepository.findByGameIdAndUserId(chatMessage.getGameId(), userId); | |
| 232 | Farmer farmer = farmerLookup.get(); | |
| 233 |
1
1. hideChatMessage : negated conditional → KILLED |
if (!farmer.getGame().isShowChat()){ |
| 234 | // Check if the user is an admin | |
| 235 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
| 236 |
3
1. lambda$hideChatMessage$1 : replaced boolean return with false for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$hideChatMessage$1 → KILLED 2. lambda$hideChatMessage$1 : replaced boolean return with true for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::lambda$hideChatMessage$1 → KILLED 3. hideChatMessage : negated conditional → KILLED |
if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))){ |
| 237 |
1
1. hideChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::hideChatMessage → KILLED |
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); |
| 238 | } | |
| 239 | } | |
| 240 | ||
| 241 | // Hide the message | |
| 242 |
1
1. hideChatMessage : removed call to edu/ucsb/cs156/happiercows/entities/ChatMessage::setHidden → KILLED |
chatMessage.setHidden(true); |
| 243 | chatMessageRepository.save(chatMessage); | |
| 244 | ||
| 245 |
1
1. hideChatMessage : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/ChatMessageController::hideChatMessage → KILLED |
return ResponseEntity.ok(chatMessage); |
| 246 | } | |
| 247 | ||
| 248 | | |
| 249 | ||
| 250 | } | |
Mutations | ||
| 76 |
1.1 |
|
| 77 |
1.1 |
|
| 92 |
1.1 2.2 3.3 |
|
| 98 |
1.1 |
|
| 99 |
1.1 |
|
| 103 |
1.1 |
|
| 104 |
1.1 |
|
| 110 |
1.1 |
|
| 122 |
1.1 |
|
| 135 |
1.1 |
|
| 151 |
1.1 2.2 |
|
| 152 |
1.1 |
|
| 153 |
1.1 |
|
| 159 |
1.1 2.2 3.3 |
|
| 163 |
1.1 |
|
| 164 |
1.1 |
|
| 168 |
1.1 |
|
| 169 |
1.1 |
|
| 177 |
1.1 |
|
| 178 |
1.1 |
|
| 200 |
1.1 |
|
| 203 |
1.1 |
|
| 213 |
1.1 |
|
| 214 |
1.1 |
|
| 222 |
1.1 |
|
| 225 |
1.1 2.2 3.3 |
|
| 226 |
1.1 |
|
| 233 |
1.1 |
|
| 236 |
1.1 2.2 3.3 |
|
| 237 |
1.1 |
|
| 242 |
1.1 |
|
| 245 |
1.1 |