Init
This commit is contained in:
13
src/main/java/de/w665/testing/TestingApplication.java
Normal file
13
src/main/java/de/w665/testing/TestingApplication.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class TestingApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TestingApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,37 @@
|
||||
package de.w665.testing.config;
|
||||
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.server.HandshakeInterceptor;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class UsernameHandshakeInterceptor implements HandshakeInterceptor {
|
||||
@Override
|
||||
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
|
||||
URI uri = request.getURI();
|
||||
String query = uri.getQuery();
|
||||
if (query != null) {
|
||||
for (String pair : query.split("&")) {
|
||||
String[] kv = pair.split("=", 2);
|
||||
if (kv.length == 2 && kv[0].equals("token")) {
|
||||
attributes.put("token", kv[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Also check headers (not used by SockJS handshake, but harmless)
|
||||
List<String> header = request.getHeaders().get("X-Auth-Token");
|
||||
if (header != null && !header.isEmpty()) {
|
||||
attributes.put("token", header.getFirst());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
|
||||
// no-op
|
||||
}
|
||||
}
|
@@ -0,0 +1,34 @@
|
||||
package de.w665.testing.config;
|
||||
|
||||
import de.w665.testing.service.TokenService;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UsernamePrincipalHandshakeHandler extends DefaultHandshakeHandler {
|
||||
private final TokenService tokenService;
|
||||
|
||||
public UsernamePrincipalHandshakeHandler(TokenService tokenService) {
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Principal determineUser(ServerHttpRequest request,
|
||||
WebSocketHandler wsHandler,
|
||||
Map<String, Object> attributes) {
|
||||
Object tokenObj = attributes.get("token");
|
||||
String token = tokenObj != null ? tokenObj.toString() : null;
|
||||
if (token == null) {
|
||||
// Anonymous session (reject by generating random, effectively not mapped to any user)
|
||||
return () -> "anon-" + UUID.randomUUID();
|
||||
}
|
||||
Optional<String> user = tokenService.resolveUsername(token);
|
||||
return user.<Principal>map(name -> () -> name)
|
||||
.orElseGet(() -> (()-> "anon-" + UUID.randomUUID()));
|
||||
}
|
||||
}
|
34
src/main/java/de/w665/testing/config/WebSocketConfig.java
Normal file
34
src/main/java/de/w665/testing/config/WebSocketConfig.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package de.w665.testing.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
import de.w665.testing.service.TokenService;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
private final TokenService tokenService;
|
||||
|
||||
public WebSocketConfig(TokenService tokenService) {
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic", "/queue");
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
config.setUserDestinationPrefix("/user");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/ws")
|
||||
.setAllowedOriginPatterns("*")
|
||||
.addInterceptors(new UsernameHandshakeInterceptor())
|
||||
.setHandshakeHandler(new UsernamePrincipalHandshakeHandler(tokenService))
|
||||
.withSockJS();
|
||||
}
|
||||
}
|
40
src/main/java/de/w665/testing/controller/AuthController.java
Normal file
40
src/main/java/de/w665/testing/controller/AuthController.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.dto.SignupRequest;
|
||||
import de.w665.testing.dto.SignupResponse;
|
||||
import de.w665.testing.service.PresenceService;
|
||||
import de.w665.testing.service.TokenService;
|
||||
import de.w665.testing.service.UserService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class AuthController {
|
||||
private final UserService userService;
|
||||
private final PresenceService presenceService;
|
||||
private final TokenService tokenService;
|
||||
|
||||
public AuthController(UserService userService, PresenceService presenceService, TokenService tokenService) {
|
||||
this.userService = userService;
|
||||
this.presenceService = presenceService;
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@PostMapping("/signup")
|
||||
public ResponseEntity<?> signup(@RequestBody SignupRequest request) {
|
||||
try {
|
||||
String token = userService.signup(request.getUsername());
|
||||
return ResponseEntity.ok(new SignupResponse(request.getUsername().trim().toLowerCase(), token));
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return ResponseEntity.status(409).body(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/online")
|
||||
public Set<String> online() {
|
||||
return presenceService.getOnlineUsers();
|
||||
}
|
||||
}
|
@@ -0,0 +1,29 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.dto.ChatMessage;
|
||||
import de.w665.testing.dto.SendMessageCommand;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@Controller
|
||||
public class WebSocketChatController {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
public WebSocketChatController(SimpMessagingTemplate messagingTemplate) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
}
|
||||
|
||||
@MessageMapping("/chat/send")
|
||||
public void send(@Payload SendMessageCommand cmd, Principal principal) {
|
||||
if (principal == null || cmd.getRoomId() == null || cmd.getRoomId().isBlank() || cmd.getContent() == null || cmd.getContent().isBlank()) {
|
||||
return;
|
||||
}
|
||||
String sender = principal.getName();
|
||||
ChatMessage msg = ChatMessage.of(cmd.getRoomId(), sender, cmd.getContent());
|
||||
messagingTemplate.convertAndSend("/topic/room." + cmd.getRoomId(), msg);
|
||||
}
|
||||
}
|
@@ -0,0 +1,45 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.dto.AcceptInviteCommand;
|
||||
import de.w665.testing.dto.DeclineInviteCommand;
|
||||
import de.w665.testing.dto.InviteCommand;
|
||||
import de.w665.testing.service.InviteService;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@Controller
|
||||
public class WebSocketInviteController {
|
||||
private final InviteService inviteService;
|
||||
|
||||
public WebSocketInviteController(InviteService inviteService) {
|
||||
this.inviteService = inviteService;
|
||||
}
|
||||
|
||||
@MessageMapping("/invite/send")
|
||||
public void sendInvite(@Payload InviteCommand cmd, Principal principal) {
|
||||
if (principal == null) return;
|
||||
String from = principal.getName();
|
||||
if (cmd.getTo() == null || cmd.getTo().isBlank()) return;
|
||||
if (from.equalsIgnoreCase(cmd.getTo())) return;
|
||||
inviteService.sendInvite(from, cmd.getTo().trim().toLowerCase());
|
||||
}
|
||||
|
||||
@MessageMapping("/invite/accept")
|
||||
public void acceptInvite(@Payload AcceptInviteCommand cmd, Principal principal) {
|
||||
if (principal == null) return;
|
||||
String recipient = principal.getName();
|
||||
if (cmd.getInviter() == null || cmd.getInviter().isBlank()) return;
|
||||
inviteService.acceptInvite(recipient, cmd.getInviter().trim().toLowerCase());
|
||||
}
|
||||
|
||||
@MessageMapping("/invite/decline")
|
||||
public void declineInvite(@Payload DeclineInviteCommand cmd, Principal principal) {
|
||||
if (principal == null) return;
|
||||
String recipient = principal.getName();
|
||||
if (cmd.getInviter() == null || cmd.getInviter().isBlank()) return;
|
||||
inviteService.declineInvite(recipient, cmd.getInviter().trim().toLowerCase());
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/AcceptInviteCommand.java
Normal file
13
src/main/java/de/w665/testing/dto/AcceptInviteCommand.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class AcceptInviteCommand {
|
||||
private String inviter;
|
||||
|
||||
public String getInviter() {
|
||||
return inviter;
|
||||
}
|
||||
|
||||
public void setInviter(String inviter) {
|
||||
this.inviter = inviter;
|
||||
}
|
||||
}
|
55
src/main/java/de/w665/testing/dto/ChatMessage.java
Normal file
55
src/main/java/de/w665/testing/dto/ChatMessage.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class ChatMessage {
|
||||
private String roomId;
|
||||
private String sender;
|
||||
private String content;
|
||||
private long timestamp;
|
||||
|
||||
public ChatMessage() {}
|
||||
|
||||
public ChatMessage(String roomId, String sender, String content, long timestamp) {
|
||||
this.roomId = roomId;
|
||||
this.sender = sender;
|
||||
this.content = content;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public static ChatMessage of(String roomId, String sender, String content) {
|
||||
return new ChatMessage(roomId, sender, content, Instant.now().toEpochMilli());
|
||||
}
|
||||
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public void setRoomId(String roomId) {
|
||||
this.roomId = roomId;
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public void setSender(String sender) {
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/DeclineInviteCommand.java
Normal file
13
src/main/java/de/w665/testing/dto/DeclineInviteCommand.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class DeclineInviteCommand {
|
||||
private String inviter;
|
||||
|
||||
public String getInviter() {
|
||||
return inviter;
|
||||
}
|
||||
|
||||
public void setInviter(String inviter) {
|
||||
this.inviter = inviter;
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/InviteCommand.java
Normal file
13
src/main/java/de/w665/testing/dto/InviteCommand.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class InviteCommand {
|
||||
private String to;
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
}
|
63
src/main/java/de/w665/testing/dto/InviteEvent.java
Normal file
63
src/main/java/de/w665/testing/dto/InviteEvent.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class InviteEvent {
|
||||
public enum Type { INVITE, ACCEPT, DECLINE }
|
||||
|
||||
private Type type;
|
||||
private String from;
|
||||
private String to;
|
||||
private String roomId; // present when type == ACCEPT
|
||||
|
||||
public InviteEvent() {}
|
||||
|
||||
public InviteEvent(Type type, String from, String to, String roomId) {
|
||||
this.type = type;
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.roomId = roomId;
|
||||
}
|
||||
|
||||
public static InviteEvent invite(String from, String to) {
|
||||
return new InviteEvent(Type.INVITE, from, to, null);
|
||||
}
|
||||
|
||||
public static InviteEvent accept(String from, String to, String roomId) {
|
||||
return new InviteEvent(Type.ACCEPT, from, to, roomId);
|
||||
}
|
||||
|
||||
public static InviteEvent decline(String from, String to) {
|
||||
return new InviteEvent(Type.DECLINE, from, to, null);
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public void setRoomId(String roomId) {
|
||||
this.roomId = roomId;
|
||||
}
|
||||
}
|
22
src/main/java/de/w665/testing/dto/SendMessageCommand.java
Normal file
22
src/main/java/de/w665/testing/dto/SendMessageCommand.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SendMessageCommand {
|
||||
private String roomId;
|
||||
private String content;
|
||||
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public void setRoomId(String roomId) {
|
||||
this.roomId = roomId;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
13
src/main/java/de/w665/testing/dto/SignupRequest.java
Normal file
13
src/main/java/de/w665/testing/dto/SignupRequest.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SignupRequest {
|
||||
private String username;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
}
|
29
src/main/java/de/w665/testing/dto/SignupResponse.java
Normal file
29
src/main/java/de/w665/testing/dto/SignupResponse.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SignupResponse {
|
||||
private String username;
|
||||
private String token;
|
||||
|
||||
public SignupResponse() {}
|
||||
|
||||
public SignupResponse(String username, String token) {
|
||||
this.username = username;
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
}
|
28
src/main/java/de/w665/testing/service/ChatRoomService.java
Normal file
28
src/main/java/de/w665/testing/service/ChatRoomService.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class ChatRoomService {
|
||||
// key: canonicalPair(userA,userB) -> roomId
|
||||
private final Map<String, String> pairToRoom = new ConcurrentHashMap<>();
|
||||
|
||||
public String getOrCreateRoom(String userA, String userB) {
|
||||
String key = canonicalPair(userA, userB);
|
||||
return pairToRoom.computeIfAbsent(key, k -> "room-" + Math.abs(k.hashCode()));
|
||||
}
|
||||
|
||||
public Optional<String> getRoomIfExists(String userA, String userB) {
|
||||
return Optional.ofNullable(pairToRoom.get(canonicalPair(userA, userB)));
|
||||
}
|
||||
|
||||
private String canonicalPair(String a, String b) {
|
||||
String u1 = a.toLowerCase();
|
||||
String u2 = b.toLowerCase();
|
||||
return (u1.compareTo(u2) <= 0) ? (u1 + "|" + u2) : (u2 + "|" + u1);
|
||||
}
|
||||
}
|
48
src/main/java/de/w665/testing/service/InviteService.java
Normal file
48
src/main/java/de/w665/testing/service/InviteService.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import de.w665.testing.dto.InviteEvent;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class InviteService {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final ChatRoomService chatRoomService;
|
||||
|
||||
// recipient -> set of inviters
|
||||
private final Map<String, Set<String>> pending = new ConcurrentHashMap<>();
|
||||
|
||||
public InviteService(SimpMessagingTemplate messagingTemplate, ChatRoomService chatRoomService) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
this.chatRoomService = chatRoomService;
|
||||
}
|
||||
|
||||
public void sendInvite(String from, String to) {
|
||||
pending.computeIfAbsent(to, k -> ConcurrentHashMap.newKeySet()).add(from);
|
||||
InviteEvent event = InviteEvent.invite(from, to);
|
||||
messagingTemplate.convertAndSendToUser(to, "/queue/invites", event);
|
||||
}
|
||||
|
||||
public void acceptInvite(String recipient, String inviter) {
|
||||
Set<String> inviters = pending.getOrDefault(recipient, ConcurrentHashMap.newKeySet());
|
||||
if (inviters.remove(inviter)) {
|
||||
String room = chatRoomService.getOrCreateRoom(inviter, recipient);
|
||||
InviteEvent acceptForInviter = InviteEvent.accept(recipient, inviter, room);
|
||||
InviteEvent acceptForRecipient = InviteEvent.accept(inviter, recipient, room);
|
||||
messagingTemplate.convertAndSendToUser(inviter, "/queue/invites", acceptForInviter);
|
||||
messagingTemplate.convertAndSendToUser(recipient, "/queue/invites", acceptForRecipient);
|
||||
}
|
||||
}
|
||||
|
||||
public void declineInvite(String recipient, String inviter) {
|
||||
Set<String> inviters = pending.getOrDefault(recipient, ConcurrentHashMap.newKeySet());
|
||||
if (inviters.remove(inviter)) {
|
||||
InviteEvent declineForInviter = InviteEvent.decline(recipient, inviter);
|
||||
messagingTemplate.convertAndSendToUser(inviter, "/queue/invites", declineForInviter);
|
||||
}
|
||||
}
|
||||
}
|
54
src/main/java/de/w665/testing/service/PresenceService.java
Normal file
54
src/main/java/de/w665/testing/service/PresenceService.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class PresenceService {
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
// sessionId -> username
|
||||
private final Map<String, String> sessionToUser = new ConcurrentHashMap<>();
|
||||
// username -> session count
|
||||
private final Map<String, Integer> userSessionCounts = new ConcurrentHashMap<>();
|
||||
|
||||
public PresenceService(SimpMessagingTemplate messagingTemplate) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
}
|
||||
|
||||
public void userConnected(String sessionId, String username) {
|
||||
sessionToUser.put(sessionId, username);
|
||||
userSessionCounts.merge(username, 1, Integer::sum);
|
||||
broadcastOnlineUsers();
|
||||
}
|
||||
|
||||
public void userDisconnected(String sessionId) {
|
||||
String username = sessionToUser.remove(sessionId);
|
||||
if (username != null) {
|
||||
userSessionCounts.computeIfPresent(username, (u, count) -> {
|
||||
int next = count - 1;
|
||||
return next <= 0 ? null : next;
|
||||
});
|
||||
broadcastOnlineUsers();
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> getOnlineUsers() {
|
||||
return Collections.unmodifiableSet(
|
||||
userSessionCounts.entrySet().stream()
|
||||
.filter(e -> e.getValue() != null && e.getValue() > 0)
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toSet())
|
||||
);
|
||||
}
|
||||
|
||||
public void broadcastOnlineUsers() {
|
||||
messagingTemplate.convertAndSend("/topic/online-users", getOnlineUsers());
|
||||
}
|
||||
}
|
35
src/main/java/de/w665/testing/service/TokenService.java
Normal file
35
src/main/java/de/w665/testing/service/TokenService.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class TokenService {
|
||||
private final Map<String, String> tokenToUser = new ConcurrentHashMap<>();
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public String createTokenForUsername(String username) {
|
||||
String token = generateToken();
|
||||
tokenToUser.put(token, username);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Optional<String> resolveUsername(String token) {
|
||||
return Optional.ofNullable(tokenToUser.get(token));
|
||||
}
|
||||
|
||||
public void invalidate(String token) {
|
||||
tokenToUser.remove(token);
|
||||
}
|
||||
|
||||
private String generateToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
}
|
41
src/main/java/de/w665/testing/service/UserService.java
Normal file
41
src/main/java/de/w665/testing/service/UserService.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package de.w665.testing.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
private final TokenService tokenService;
|
||||
private final Map<String, String> usernameToToken = new ConcurrentHashMap<>();
|
||||
|
||||
public UserService(TokenService tokenService) {
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
public synchronized String signup(String username) {
|
||||
String normalized = normalize(username);
|
||||
if (usernameToToken.containsKey(normalized)) {
|
||||
throw new IllegalArgumentException("Username already taken");
|
||||
}
|
||||
String token = tokenService.createTokenForUsername(normalized);
|
||||
usernameToToken.put(normalized, token);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Optional<String> getTokenFor(String username) {
|
||||
return Optional.ofNullable(usernameToToken.get(normalize(username)));
|
||||
}
|
||||
|
||||
public Set<String> getAllRegisteredUsers() {
|
||||
return Collections.unmodifiableSet(usernameToToken.keySet());
|
||||
}
|
||||
|
||||
private String normalize(String username) {
|
||||
return username.trim().toLowerCase();
|
||||
}
|
||||
}
|
@@ -0,0 +1,54 @@
|
||||
package de.w665.testing.ws;
|
||||
|
||||
import de.w665.testing.service.PresenceService;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.messaging.SessionConnectEvent;
|
||||
import org.springframework.web.socket.messaging.SessionConnectedEvent;
|
||||
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class WebSocketPresenceEventListener {
|
||||
private final PresenceService presenceService;
|
||||
private final Set<String> connectedSessions = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public WebSocketPresenceEventListener(PresenceService presenceService) {
|
||||
this.presenceService = presenceService;
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleWebSocketConnectListener(SessionConnectEvent event) {
|
||||
StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
|
||||
Principal p = sha.getUser();
|
||||
String sessionId = sha.getSessionId();
|
||||
if (p != null && sessionId != null && connectedSessions.add(sessionId)) {
|
||||
presenceService.userConnected(sessionId, p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleWebSocketConnectedListener(SessionConnectedEvent event) {
|
||||
StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
|
||||
Principal p = sha.getUser();
|
||||
String sessionId = sha.getSessionId();
|
||||
if (p != null && sessionId != null && connectedSessions.add(sessionId)) {
|
||||
presenceService.userConnected(sessionId, p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
|
||||
String sessionId = event.getSessionId();
|
||||
if (sessionId != null && connectedSessions.remove(sessionId)) {
|
||||
presenceService.userDisconnected(sessionId);
|
||||
} else {
|
||||
// Even if we didn't mark it as connected (edge cases), attempt to notify presence
|
||||
presenceService.userDisconnected(sessionId);
|
||||
}
|
||||
}
|
||||
}
|
17
src/main/resources/application.properties
Normal file
17
src/main/resources/application.properties
Normal file
@@ -0,0 +1,17 @@
|
||||
spring.application.name=testing
|
||||
|
||||
# H2 Database configuration
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2-console
|
||||
|
||||
# JPA configuration
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.show-sql=true
|
||||
|
||||
# Server configuration
|
||||
server.port=8080
|
286
src/main/resources/static/index.html
Normal file
286
src/main/resources/static/index.html
Normal file
@@ -0,0 +1,286 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Simple Chat</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; margin: 0; background: #0f172a; color: #e2e8f0; }
|
||||
header { padding: 16px; background: #111827; display: flex; justify-content: space-between; align-items: center; }
|
||||
header h1 { margin: 0; font-size: 18px; }
|
||||
.container { display: grid; grid-template-columns: 300px 1fr; gap: 16px; padding: 16px; height: calc(100vh - 64px); box-sizing: border-box; }
|
||||
.panel { background: #1f2937; border-radius: 8px; padding: 12px; overflow: hidden; display: flex; flex-direction: column; }
|
||||
.panel h2 { margin: 0 0 8px 0; font-size: 14px; color: #93c5fd; }
|
||||
.row { display: flex; gap: 8px; align-items: center; }
|
||||
input, button, select { padding: 8px 10px; border-radius: 6px; border: 1px solid #374151; background: #0b1220; color: #e5e7eb; }
|
||||
button { cursor: pointer; background: #2563eb; border: none; }
|
||||
button.secondary { background: #374151; }
|
||||
button:disabled { background: #1f2937; cursor: not-allowed; }
|
||||
ul { list-style: none; padding: 0; margin: 0; overflow: auto; }
|
||||
li { padding: 8px; border-bottom: 1px solid #374151; display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.badge { background: #10b981; color: #052e1a; border-radius: 999px; padding: 2px 8px; font-size: 12px; }
|
||||
.chat { display: grid; grid-template-rows: 1fr auto; gap: 8px; height: 100%; }
|
||||
.messages { background: #0b1220; border-radius: 8px; padding: 8px; overflow: auto; border: 1px solid #1f2937; }
|
||||
.msg { margin: 6px 0; }
|
||||
.msg .sender { font-weight: 600; color: #60a5fa; margin-right: 6px; }
|
||||
.system { color: #9ca3af; font-style: italic; }
|
||||
.rooms { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 8px; }
|
||||
.pill { padding: 6px 10px; border-radius: 999px; background: #0b1220; border: 1px solid #374151; cursor: pointer; }
|
||||
.pill.active { background: #1d4ed8; border-color: #1d4ed8; }
|
||||
.invite { display: flex; gap: 6px; align-items: center; }
|
||||
.footer { color: #9ca3af; font-size: 12px; }
|
||||
</style>
|
||||
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.6.1/dist/sockjs.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>Simple Chat</h1>
|
||||
<div id="me" class="footer"></div>
|
||||
</header>
|
||||
<div class="container">
|
||||
<div class="panel">
|
||||
<h2>Sign up</h2>
|
||||
<div class="row" style="margin-bottom:8px;">
|
||||
<input id="username" placeholder="username (a-z, 0-9)" />
|
||||
<button id="signupBtn">Sign up</button>
|
||||
</div>
|
||||
<div class="footer">After signup, a WebSocket connection is created. Your online status will be visible to others.</div>
|
||||
|
||||
<h2 style="margin-top:16px;">Online users</h2>
|
||||
<ul id="users"></ul>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h2>Chat</h2>
|
||||
<div class="rooms" id="rooms"></div>
|
||||
<div class="chat">
|
||||
<div class="messages" id="messages"></div>
|
||||
<div class="row">
|
||||
<input id="messageInput" placeholder="Type a message..." style="flex:1" />
|
||||
<button id="sendBtn" disabled>Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function(){
|
||||
const state = {
|
||||
username: localStorage.getItem('username') || '',
|
||||
token: localStorage.getItem('token') || '',
|
||||
client: null,
|
||||
connected: false,
|
||||
online: new Set(),
|
||||
rooms: {}, // roomId -> { participants: [a,b], messages: [] }
|
||||
activeRoom: null,
|
||||
subscribedRooms: new Set(),
|
||||
};
|
||||
|
||||
const els = {
|
||||
username: document.getElementById('username'),
|
||||
signupBtn: document.getElementById('signupBtn'),
|
||||
users: document.getElementById('users'),
|
||||
messages: document.getElementById('messages'),
|
||||
messageInput: document.getElementById('messageInput'),
|
||||
sendBtn: document.getElementById('sendBtn'),
|
||||
rooms: document.getElementById('rooms'),
|
||||
me: document.getElementById('me'),
|
||||
};
|
||||
|
||||
function setMe() {
|
||||
if (state.username) {
|
||||
els.me.textContent = `Signed in as ${state.username}`;
|
||||
} else {
|
||||
els.me.textContent = 'Not signed in';
|
||||
}
|
||||
}
|
||||
|
||||
function api(path, options={}){
|
||||
return fetch(path, {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...options,
|
||||
}).then(r => {
|
||||
if (!r.ok) return r.text().then(t => Promise.reject(new Error(t||r.statusText)));
|
||||
const ct = r.headers.get('content-type')||'';
|
||||
if (ct.includes('application/json')) return r.json();
|
||||
return r.text();
|
||||
});
|
||||
}
|
||||
|
||||
function renderUsers(){
|
||||
els.users.innerHTML = '';
|
||||
const arr = Array.from(state.online).filter(u => u !== state.username).sort();
|
||||
if (!arr.length) {
|
||||
const li = document.createElement('li');
|
||||
li.innerHTML = '<span class="system">No other users online</span>';
|
||||
els.users.appendChild(li);
|
||||
return;
|
||||
}
|
||||
arr.forEach(u => {
|
||||
const li = document.createElement('li');
|
||||
const span = document.createElement('span');
|
||||
span.textContent = u;
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = 'Invite';
|
||||
btn.onclick = () => sendInvite(u);
|
||||
li.appendChild(span);
|
||||
li.appendChild(btn);
|
||||
els.users.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
function renderRooms(){
|
||||
els.rooms.innerHTML = '';
|
||||
Object.entries(state.rooms).forEach(([roomId, room]) => {
|
||||
const pill = document.createElement('div');
|
||||
pill.className = 'pill' + (state.activeRoom === roomId ? ' active' : '');
|
||||
const other = room.participants.find(p => p !== state.username) || 'room';
|
||||
pill.textContent = other;
|
||||
pill.onclick = () => setActiveRoom(roomId);
|
||||
els.rooms.appendChild(pill);
|
||||
});
|
||||
}
|
||||
|
||||
function renderMessages(){
|
||||
els.messages.innerHTML = '';
|
||||
const room = state.rooms[state.activeRoom];
|
||||
if (!room) {
|
||||
const d = document.createElement('div');
|
||||
d.className = 'system';
|
||||
d.textContent = 'No active room. Send or accept an invite to start chatting.';
|
||||
els.messages.appendChild(d);
|
||||
els.sendBtn.disabled = true;
|
||||
return;
|
||||
}
|
||||
els.sendBtn.disabled = false;
|
||||
room.messages.forEach(m => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'msg';
|
||||
const sender = document.createElement('span');
|
||||
sender.className = 'sender';
|
||||
sender.textContent = m.sender + ':';
|
||||
const content = document.createElement('span');
|
||||
content.textContent = ' ' + m.content;
|
||||
div.appendChild(sender);
|
||||
div.appendChild(content);
|
||||
els.messages.appendChild(div);
|
||||
});
|
||||
els.messages.scrollTop = els.messages.scrollHeight;
|
||||
}
|
||||
|
||||
function setActiveRoom(roomId){
|
||||
state.activeRoom = roomId;
|
||||
renderRooms();
|
||||
renderMessages();
|
||||
}
|
||||
|
||||
function upsertRoom(roomId, participants){
|
||||
if (!state.rooms[roomId]) {
|
||||
state.rooms[roomId] = { participants: participants || [], messages: [] };
|
||||
if (!state.activeRoom) setActiveRoom(roomId);
|
||||
}
|
||||
}
|
||||
|
||||
function connectWebSocket(){
|
||||
if (!state.token) return;
|
||||
const sock = new SockJS(`/ws?token=${encodeURIComponent(state.token)}`);
|
||||
const client = Stomp.over(sock);
|
||||
client.debug = () => {};
|
||||
client.connect({}, () => {
|
||||
state.client = client;
|
||||
state.connected = true;
|
||||
// Online users topic
|
||||
client.subscribe('/topic/online-users', msg => {
|
||||
try{ const set = new Set(JSON.parse(msg.body)); state.online = set; renderUsers(); } catch(e){}
|
||||
});
|
||||
// Invite queue (user-specific)
|
||||
client.subscribe('/user/queue/invites', msg => {
|
||||
const ev = JSON.parse(msg.body);
|
||||
if (ev.type === 'INVITE') {
|
||||
const accept = confirm(`${ev.from} invited you to chat. Accept?`);
|
||||
if (accept) {
|
||||
client.send('/app/invite/accept', {}, JSON.stringify({ inviter: ev.from }));
|
||||
} else {
|
||||
client.send('/app/invite/decline', {}, JSON.stringify({ inviter: ev.from }));
|
||||
}
|
||||
} else if (ev.type === 'ACCEPT') {
|
||||
// Both sides receive ACCEPT with roomId
|
||||
upsertRoom(ev.roomId, [ev.from, ev.to]);
|
||||
subscribeRoom(ev.roomId);
|
||||
} else if (ev.type === 'DECLINE') {
|
||||
alert(`${ev.from} declined your invite.`);
|
||||
}
|
||||
});
|
||||
// Get initial online users
|
||||
refreshOnline();
|
||||
}, (err) => {
|
||||
console.error('WS error', err);
|
||||
state.connected = false;
|
||||
setTimeout(connectWebSocket, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
function subscribeRoom(roomId){
|
||||
if (!state.client) return;
|
||||
if (state.subscribedRooms.has(roomId)) return;
|
||||
state.subscribedRooms.add(roomId);
|
||||
state.client.subscribe(`/topic/room.${roomId}`, msg => {
|
||||
const chat = JSON.parse(msg.body);
|
||||
upsertRoom(chat.roomId);
|
||||
state.rooms[chat.roomId].messages.push(chat);
|
||||
renderMessages();
|
||||
});
|
||||
}
|
||||
|
||||
function sendInvite(to){
|
||||
if (!state.client) return;
|
||||
state.client.send('/app/invite/send', {}, JSON.stringify({ to }));
|
||||
alert(`Invite sent to ${to}`);
|
||||
}
|
||||
|
||||
function sendMessage(){
|
||||
const roomId = state.activeRoom;
|
||||
const content = els.messageInput.value.trim();
|
||||
if (!content || !roomId || !state.client) return;
|
||||
state.client.send('/app/chat/send', {}, JSON.stringify({ roomId, content }));
|
||||
els.messageInput.value = '';
|
||||
}
|
||||
|
||||
function refreshOnline(){
|
||||
api('/api/online').then(list => {
|
||||
state.online = new Set(list);
|
||||
renderUsers();
|
||||
}).catch(()=>{});
|
||||
}
|
||||
|
||||
function signup(){
|
||||
const raw = els.username.value.trim().toLowerCase();
|
||||
const username = raw.replace(/[^a-z0-9_-]/g, '');
|
||||
if (!username) { alert('Please enter a username'); return; }
|
||||
api('/api/signup', { method: 'POST', body: JSON.stringify({ username }) })
|
||||
.then(res => {
|
||||
state.username = res.username;
|
||||
state.token = res.token;
|
||||
localStorage.setItem('username', state.username);
|
||||
localStorage.setItem('token', state.token);
|
||||
setMe();
|
||||
connectWebSocket();
|
||||
refreshOnline();
|
||||
})
|
||||
.catch(err => alert('Signup failed: ' + err.message));
|
||||
}
|
||||
|
||||
// Init
|
||||
setMe();
|
||||
if (state.username && state.token) {
|
||||
connectWebSocket();
|
||||
refreshOnline();
|
||||
}
|
||||
|
||||
els.signupBtn.addEventListener('click', signup);
|
||||
els.messageInput.addEventListener('keydown', (e)=>{ if (e.key === 'Enter') sendMessage(); });
|
||||
els.sendBtn.addEventListener('click', sendMessage);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
Reference in New Issue
Block a user