Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
96a4cd9
Reactions: keys, table and repository
svaka2000 Nov 22, 2026
8f749e9
Reactions: a service that saves and summarizes them
svaka2000 Nov 22, 2026
363242f
Reactions: react to a direct message
svaka2000 Nov 22, 2026
adb17e1
Reactions: react to a group chat message
svaka2000 Nov 22, 2026
bc79ac5
Group chat: a send keeps the history when S3 can't read it
svaka2000 Nov 22, 2026
5b99316
Group chat: two message writes at once keep both changes
svaka2000 Nov 22, 2026
7eb0e35
Reactions: document the routes and frames
svaka2000 Nov 22, 2026
9a3bf22
Group chat docs: a send reads its messages strictly
svaka2000 Nov 22, 2026
af1dba2
Group chat docs: message writes take a lock per group
svaka2000 Nov 22, 2026
457eb00
Push: a DM's notification shows its words, not the page's markers or …
svaka2000 Nov 23, 2026
1b7fb8d
Reactions: say who may make the six reaction requests
svaka2000 Nov 26, 2026
4b74634
Chat socket: drop client SENDs to every /topic destination
svaka2000 Nov 23, 2026
5e00000
Reactions: one-statement deletes, reactor names in one query, lowerca…
svaka2000 Nov 26, 2026
c791798
Reactions: a DM's reactions frame goes out after the commit, read aga…
svaka2000 Nov 26, 2026
3e38849
Reactions: a table that can't be made is logged as an error
svaka2000 Nov 26, 2026
d6c2bfe
Docs: list the reaction tests before the chat regression tests
svaka2000 Nov 26, 2026
d9a74b4
Group chat tests: build the send test's controller from its construct…
svaka2000 Nov 26, 2026
6217936
Group files: answer 503 when S3 can't take the write
svaka2000 Nov 20, 2026
b30e611
Group chat: a restart keeps the history when S3 can't check it
svaka2000 Nov 22, 2026
f344706
Group chat: a send whose read times out answers 503 like a shared file
svaka2000 Nov 22, 2026
1bc72b0
Group chat docs: the start-up check writes only over a missing file
svaka2000 Nov 22, 2026
6a48a14
Group files: note that a write that timed out may still be stored
svaka2000 Nov 22, 2026
a8f1c65
Group chat: a send, edit or delete answers 503 when S3 can't save it
svaka2000 Nov 26, 2026
ee2af19
Group chat docs: sends, edits and deletes save their messages strictly
svaka2000 Nov 26, 2026
258b8f6
Group chat: a send or edit answers with the messages it saved
svaka2000 Nov 26, 2026
320171c
Group chat: a delete of a message that isn't saved answers 404 and te…
svaka2000 Nov 26, 2026
1cc5536
Group chat: a line that doesn't read as a message is kept when the fi…
svaka2000 Nov 26, 2026
8dfea9a
Group chat docs: a send or edit returns the history as it was saved
svaka2000 Nov 26, 2026
aac4ab9
Group chat docs: a delete of a message that isn't saved answers 404
svaka2000 Nov 26, 2026
d5c3852
Group chat docs: a line that doesn't read as a message is kept
svaka2000 Nov 26, 2026
34de53d
Merge #296: Group chat: a lock per group so two sends at once can't l…
svaka2000 Nov 26, 2026
dd7982a
Merge #297: Group chat: a send returns 503 instead of wiping the hist…
svaka2000 Nov 26, 2026
c4ea6d7
Merge #298: Group chat: a restart no longer wipes a chat when S3 fail…
svaka2000 Nov 26, 2026
5d7a4c2
Merge #299: Group chat files: 503 instead of 500 when S3 can't store …
svaka2000 Nov 26, 2026
6697c9d
Merge fix/group-chat-strict-write: a send, edit or delete returns 503…
svaka2000 Nov 26, 2026
8d14a47
Merge fix/group-chat-answer-saved: a send or edit answers with the me…
svaka2000 Nov 26, 2026
44b3e59
Merge fix/group-chat-delete-unknown: deleting a message that isn't sa…
svaka2000 Nov 26, 2026
c4b030e
Merge fix/group-chat-keep-unreadable-lines: a line that doesn't read …
svaka2000 Nov 26, 2026
bb610c5
Merge #302: Chat reactions: react to a DM or group message with an emoji
svaka2000 Nov 26, 2026
9117d9d
Merge #293: Phone notifications: show a DM's words, not its markers o…
svaka2000 Nov 26, 2026
02ee508
Merge #295: Chat socket: drop client SENDs to every /topic destination
svaka2000 Nov 26, 2026
8fc7ef6
Group chat: a delete still tells the group when its reactions can't b…
svaka2000 Nov 26, 2026
6aa4b6a
Reactions: a DM delete no longer rolls back when its reactions can't …
svaka2000 Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Entity-removal helpers (run before any large cleanup):
- Realtime chat uses STOMP over a **second connector on port 8589**: broker config in `WebSocketBrokerConfig.java` (`/ws-chat`, `/app`, `/topic`), port gating in `ChatWebSocketPortFilter.java`, presence in `GroupChatPresenceService.java`. The native `/websocket` endpoint in `mvc/mortevision/nativesocket/WebSocketConfig.java` is separate.
- Gotcha: Java package is `mvc.groups` (plural) but templates live in `templates/group/` (singular); static JS exists both as legacy files in `static/js/group-*.js` and packaged versions in `static/js/group/*.js` — prefer the latter.
- [docs/group-chat-architecture.md](docs/group-chat-architecture.md) covers every groups and chat route, the WebSocket event contexts, S3 message storage (keyed by group name, not id) and the known issues. Over the WebSocket there is no Spring Security context, so a service that needs the signed-in account (like `GroupChatIdentityService`) only works from REST. The socket does read the `jwt_java_spring` cookie when it opens (`ChatSocketIdentityInterceptor`, same checks as `JwtRequestFilter`, and only when the request's `Origin` is in the REST CORS list, since a cross-site GET carries the cookie but no Origin), but only for `DirectMessageTopicGuard`: only a conversation's participants can subscribe to `/topic/dm/{id}`, and wildcard subscriptions, `/user/...` destinations and client SENDs to DM topics are dropped. It sets no Principal, on purpose, so `GroupChatWebSocketController` still ignores events. HTTP: `api/groups.http`.
- A client's SEND to any `/topic/...` destination is dropped too, group topics included, because the simple broker relays it to every subscriber. Only the server publishes there (the prefix is `WebSocketBrokerConfig.BROKER_PREFIX`).

## Assignment grading

Expand Down
16 changes: 16 additions & 0 deletions api/groups.http
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,22 @@ Content-Type: application/json

{"filename": "notes/hello.txt", "base64Data": "Z29vZGJ5ZQ=="}

### 13g. React to a message with a Like -> 200 with {messageId, reactions}, and a reactionsServer frame on /topic/group/{id}
# Any UUID is accepted: Spring doesn't read the S3 file to check the message, and a reaction
# on a message that doesn't exist is never shown.
PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like

### 13h. List the chat's reactions -> 200 with {"3f2c8a8e-...": [{"reaction": "like", "people": [{uid, name}]}]}
GET {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/reactions

### 13i. Take the Like back -> 200 with an empty reactions list
DELETE {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/like

### 13j. A key that isn't one of the six is refused -> 400
# Direct messages have the same three routes under /api/dm/conversations/{id}: GET .../reactions,
# and PUT or DELETE .../messages/{messageId}/reactions/{reaction}, for participants only.
PUT {{baseUrl}}/api/groups/chat/{{createGroup.response.body.$.id}}/messages/3f2c8a8e-5b1d-4c7e-9a52-8f0e6d4b2a10/reactions/thumbsup

### 14. Remove yourself from the test group -> 200

DELETE {{baseUrl}}/api/groups/{{createGroup.response.body.$.id}}/members/{{me.response.body.$.id}}
Expand Down
47 changes: 37 additions & 10 deletions docs/group-chat-architecture.md

Large diffs are not rendered by default.

12 changes: 10 additions & 2 deletions src/main/java/com/open/spring/StartupService.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
import com.open.spring.mvc.groups.GroupsJpaRepository;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Component
@RequiredArgsConstructor
@Slf4j
public class StartupService {

private final GroupsJpaRepository groupsRepository;
Expand All @@ -25,9 +27,15 @@ public ApplicationRunner initializeGroupStorage() {
// Fetch all existing groups from the database
List<Groups> groups = groupsRepository.findAll();

// Ensure S3 storage exists for each group
// Ensure S3 storage exists for each group. A group whose storage can't be checked is
// left as it is until the next start, and the other groups are still checked, so one
// group can't stop the server from starting.
for (Groups group : groups) {
groupChatService.ensureGroupStorageExists(group.getName());
try {
groupChatService.ensureGroupStorageExists(group.getName());
} catch (RuntimeException e) {
log.warn("Could not check the chat storage of group {}, so nothing was written to it", group.getName(), e);
}
}
};
}
Expand Down
47 changes: 47 additions & 0 deletions src/main/java/com/open/spring/mvc/S3uploads/S3FileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ public void init() {
this.s3Client = builder.build();
}

/** Whether this server has S3 settings (AWS credentials, region and bucket). Without them nothing is stored. */
public boolean isConfigured() {
return s3Client != null;
}

@Override
public String uploadFile(String base64Data, String filename, String uid) {
if (s3Client == null) {
Expand All @@ -105,6 +110,23 @@ public String uploadFile(String base64Data, String filename, String uid) {
}
}

/**
* Like uploadFile, but a write that fails throws instead of answering null, so a caller can
* tell S3 being unavailable for a moment (a throttle, a 5xx, no connection) from a request
* S3 refused.
*/
public String uploadFileOrThrow(String base64Data, String filename, String uid) {
if (s3Client == null) {
throw new IllegalStateException("S3 client is not configured");
}
s3Client.putObject(PutObjectRequest.builder()
.bucket(bucketName)
.key(generateKey(uid, filename))
.build(),
RequestBody.fromBytes(Base64.getDecoder().decode(base64Data)));
return filename;
}

@Override
public String decodeFile(String uid, String filename) {
if (s3Client == null) {
Expand Down Expand Up @@ -264,6 +286,31 @@ public boolean fileExistsOrThrow(String uid, String filename) {
}
}

/**
* Like decodeFile, but only "not found" (404) reads as nothing stored: any other failure to
* read (a throttle, a 5xx, no connection) throws. For a caller that writes back what it read,
* a read that failed is not an empty file. With no S3 client there is nothing to read and
* nothing can be written, so that reads as nothing stored, as in decodeFile.
*/
public String decodeFileOrThrow(String uid, String filename) {
if (s3Client == null) {
log.warn("S3 download attempted but S3 client is not configured.");
return null;
}
try {
ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObjectAsBytes(GetObjectRequest.builder()
.bucket(bucketName)
.key(generateKey(uid, filename))
.build());
return Base64.getEncoder().encodeToString(objectBytes.asByteArray());
} catch (S3Exception e) {
if (e.statusCode() == 404) {
return null;
}
throw e;
}
}

private String generateKey(String uid, String filename) {
return uid + "/" + filename;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,18 @@
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.open.spring.mvc.person.Person;
import com.open.spring.mvc.person.PersonJpaRepository;
import com.open.spring.mvc.reactions.ChatType;
import com.open.spring.mvc.reactions.MessageReactionService;
import com.open.spring.mvc.reactions.MessageReactionService.MessageReactions;
import com.open.spring.mvc.reactions.Reaction;

import lombok.AllArgsConstructor;
import lombok.Data;
Expand All @@ -46,6 +51,7 @@ public class DirectMessageApiController {
private final DirectMessageConversationJpaRepository conversationRepository;
private final DirectMessageJpaRepository messageRepository;
private final PersonJpaRepository personRepository;
private final MessageReactionService reactionService;

@Data
@NoArgsConstructor
Expand Down Expand Up @@ -295,6 +301,81 @@ public ResponseEntity<Object> deleteMessage(
}
}

/** Every reaction in the conversation, by message id: what the page draws when it opens it. */
@GetMapping("/conversations/{id}/reactions")
@Transactional(readOnly = true)
public ResponseEntity<Object> getReactions(
@AuthenticationPrincipal UserDetails userDetails,
@PathVariable("id") Long id) {
Person person = currentPerson(userDetails);
if (person == null) {
return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED);
}

Optional<DirectMessageConversation> conversationOpt = conversationRepository.findById(id);
if (conversationOpt.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (!directMessageService.isParticipant(conversationOpt.get(), person)) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

return new ResponseEntity<>(reactionService.forChat(ChatType.DM, id), HttpStatus.OK);
}

/** Adds the caller's reaction, by its lowercase key such as "like", and answers with the message's reactions. */
@PutMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}")
@Transactional
public ResponseEntity<Object> addReaction(
@AuthenticationPrincipal UserDetails userDetails,
@PathVariable("id") Long id,
@PathVariable("messageId") Long messageId,
@PathVariable("reaction") String reaction) {
return setReaction(userDetails, id, messageId, reaction, true);
}

/** Removes the caller's reaction; removing one that isn't there still answers 200. */
@DeleteMapping("/conversations/{id}/messages/{messageId}/reactions/{reaction}")
@Transactional
public ResponseEntity<Object> removeReaction(
@AuthenticationPrincipal UserDetails userDetails,
@PathVariable("id") Long id,
@PathVariable("messageId") Long messageId,
@PathVariable("reaction") String reaction) {
return setReaction(userDetails, id, messageId, reaction, false);
}

private ResponseEntity<Object> setReaction(UserDetails userDetails, Long id, Long messageId, String key, boolean on) {
Person person = currentPerson(userDetails);
if (person == null) {
return new ResponseEntity<>(Map.of("error", "User not authenticated"), HttpStatus.UNAUTHORIZED);
}

Optional<DirectMessageConversation> conversationOpt = conversationRepository.findById(id);
if (conversationOpt.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

DirectMessageConversation conversation = conversationOpt.get();
if (!directMessageService.isParticipant(conversation, person)) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

Optional<Reaction> reaction = Reaction.fromKey(key);
if (reaction.isEmpty()) {
return new ResponseEntity<>(Map.of("error", "unknown reaction"), HttpStatus.BAD_REQUEST);
}

try {
return new ResponseEntity<>(new MessageReactions(String.valueOf(messageId),
directMessageService.setReaction(conversation, person, messageId, reaction.get(), on)), HttpStatus.OK);
} catch (NoSuchElementException ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (IllegalStateException ex) {
return new ResponseEntity<>(Map.of("error", ex.getMessage()), HttpStatus.CONFLICT);
}
}

@PostMapping("/conversations/{id}/read")
@Transactional
public ResponseEntity<Object> markRead(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package com.open.spring.mvc.directmessages;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.open.spring.mvc.reactions.MessageReactionService;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
Expand All @@ -16,7 +21,7 @@
public class DirectMessageEvent {
private Long id;
private Long conversationId;
private String type; // "message" for new posts, "edited" for edits
private String type; // "message", "edited", "deleted", or "reactions"
private String senderUid;
private String senderName;
private String senderPfp;
Expand All @@ -26,4 +31,10 @@ public class DirectMessageEvent {
private String sentAt;
private boolean deleted;
private boolean edited;
/**
* On a "reactions" frame, the message's reactions after the change. Left out of every
* other frame, so those stay exactly as they were.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<MessageReactionService.ReactionSummary> reactions;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,22 @@
import java.util.NoSuchElementException;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.PageRequest;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.open.spring.mvc.person.Person;
import com.open.spring.mvc.push.PushNotificationService;
import com.open.spring.mvc.reactions.ChatType;
import com.open.spring.mvc.reactions.MessageReactionService;
import com.open.spring.mvc.reactions.Reaction;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
* Business logic for direct messages: finding/creating conversations, checking
Expand All @@ -26,6 +33,7 @@
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class DirectMessageService {

public static final String DM_TOPIC_PREFIX = "/topic/dm/";
Expand All @@ -41,6 +49,7 @@ public class DirectMessageService {
private final DirectMessageReadStateJpaRepository readStateRepository;
private final SimpMessagingTemplate messagingTemplate;
private final PushNotificationService pushNotificationService;
private final MessageReactionService reactionService;

public record UnreadSender(String uid, String name) {
}
Expand Down Expand Up @@ -222,6 +231,10 @@ public void deleteMessage(DirectMessageConversation conversation, Person request
message.setDeleted(true);
message.setBody("");
messageRepository.save(message);
// A tombstone shows no reactions, so none are kept for it. They're removed after the delete
// commits: an error from the reactions table inside this transaction would undo the delete.
Long conversationId = conversation.getId();
afterCommit(() -> removeReactions(conversationId, messageId));

DirectMessageEvent event = DirectMessageEvent.builder()
.id(message.getId())
Expand All @@ -235,6 +248,68 @@ public void deleteMessage(DirectMessageConversation conversation, Person request
messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversation.getId(), event);
}

/**
* Adds ({@code on}) or removes {@code person}'s reaction to a message, then tells the
* conversation's topic with a "reactions" frame. A reaction isn't a message: nobody gets a
* phone notification and nothing becomes unread. Throws {@link NoSuchElementException} if
* the message isn't in this conversation and {@link IllegalStateException} if it was
* deleted; {@code noRollbackFor} for the reason given on {@link #editMessage}.
*/
@Transactional(noRollbackFor = {NoSuchElementException.class, IllegalStateException.class})
public List<MessageReactionService.ReactionSummary> setReaction(DirectMessageConversation conversation,
Person person, Long messageId, Reaction reaction, boolean on) {
DirectMessage message = messageRepository.findByIdAndConversation(messageId, conversation)
.orElseThrow(() -> new NoSuchElementException("Message not found"));
if (message.isDeleted()) {
throw new IllegalStateException("Message was deleted");
}

String key = String.valueOf(messageId);
if (on) {
reactionService.add(ChatType.DM, conversation.getId(), key, person, reaction);
} else {
reactionService.remove(ChatType.DM, conversation.getId(), key, person, reaction);
}
List<MessageReactionService.ReactionSummary> reactions =
reactionService.forMessage(ChatType.DM, conversation.getId(), key);

// The frame goes out once this commits, with the reactions read again then. Read here,
// inside this transaction, they could miss a reaction someone else saved at the same time,
// and that person's frame would miss this one.
Long conversationId = conversation.getId();
afterCommit(() -> messagingTemplate.convertAndSend(DM_TOPIC_PREFIX + conversationId, DirectMessageEvent.builder()
.id(messageId)
.conversationId(conversationId)
.type("reactions")
.reactions(reactionService.forMessageNow(ChatType.DM, conversationId, key))
.build()));
return reactions;
}

// Runs once the current transaction commits, or right away outside one.
/** Removes a deleted message's reactions. The delete is already done, so a failure is only logged. */
private void removeReactions(Long conversationId, Long messageId) {
try {
reactionService.removeAllFor(ChatType.DM, conversationId, String.valueOf(messageId));
} catch (DataAccessException e) {
log.warn("Could not remove the reactions of deleted message {} in conversation {}",
messageId, conversationId, e);
}
}

private static void afterCommit(Runnable action) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
action.run();
}
});
} else {
action.run();
}
}

@Transactional(readOnly = true)
public UnreadSummary getUnreadSummary(Person person) {
Map<String, UnreadSender> people = new LinkedHashMap<>();
Expand Down
Loading