alooo
This commit is contained in:
8
.idea/.gitignore
generated
vendored
Normal file
8
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
@@ -1,37 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
@@ -1,34 +0,0 @@
|
||||
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()));
|
||||
}
|
||||
}
|
@@ -5,30 +5,19 @@ 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();
|
||||
registry.addEndpoint("/ws").withSockJS();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry registry) {
|
||||
registry.setApplicationDestinationPrefixes("/app");
|
||||
registry.enableSimpleBroker("/topic");
|
||||
}
|
||||
}
|
||||
|
@@ -1,40 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
27
src/main/java/de/w665/testing/controller/ChatController.java
Normal file
27
src/main/java/de/w665/testing/controller/ChatController.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package de.w665.testing.controller;
|
||||
|
||||
import de.w665.testing.model.ChatMessage;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.messaging.handler.annotation.SendTo;
|
||||
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
@Controller
|
||||
public class ChatController {
|
||||
|
||||
@MessageMapping("/chat.sendMessage")
|
||||
@SendTo("/topic/public")
|
||||
public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
|
||||
return chatMessage;
|
||||
}
|
||||
|
||||
@MessageMapping("/chat.addUser")
|
||||
@SendTo("/topic/public")
|
||||
public ChatMessage addUser(@Payload ChatMessage chatMessage,
|
||||
SimpMessageHeaderAccessor headerAccessor) {
|
||||
// Add username in web socket session
|
||||
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
|
||||
return chatMessage;
|
||||
}
|
||||
}
|
@@ -1,29 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
@@ -1,45 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class AcceptInviteCommand {
|
||||
private String inviter;
|
||||
|
||||
public String getInviter() {
|
||||
return inviter;
|
||||
}
|
||||
|
||||
public void setInviter(String inviter) {
|
||||
this.inviter = inviter;
|
||||
}
|
||||
}
|
@@ -1,55 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class DeclineInviteCommand {
|
||||
private String inviter;
|
||||
|
||||
public String getInviter() {
|
||||
return inviter;
|
||||
}
|
||||
|
||||
public void setInviter(String inviter) {
|
||||
this.inviter = inviter;
|
||||
}
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class InviteCommand {
|
||||
private String to;
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
}
|
@@ -1,63 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
@@ -1,22 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
package de.w665.testing.dto;
|
||||
|
||||
public class SignupRequest {
|
||||
private String username;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
}
|
@@ -1,29 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
11
src/main/java/de/w665/testing/model/ChatMessage.java
Normal file
11
src/main/java/de/w665/testing/model/ChatMessage.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package de.w665.testing.model;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ChatMessage {
|
||||
private String content;
|
||||
private String sender;
|
||||
}
|
@@ -1,28 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
@@ -1,48 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,54 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
@@ -1,35 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
@@ -1,41 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
@@ -1,54 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,286 +1,168 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Simple Chat</title>
|
||||
<title>QChat</title>
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
|
||||
<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; }
|
||||
body {
|
||||
background-color: #f4f4f4;
|
||||
}
|
||||
#username-page, #chat-page {
|
||||
display: none;
|
||||
}
|
||||
#chat-page {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.chat-header {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
padding: 15px;
|
||||
border-radius: 5px 5px 0 0;
|
||||
}
|
||||
#message-area {
|
||||
height: 400px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #ddd;
|
||||
padding: 15px;
|
||||
background-color: white;
|
||||
}
|
||||
.message-form {
|
||||
margin-top: 15px;
|
||||
}
|
||||
</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 class="container">
|
||||
<div id="username-page">
|
||||
<div class="row justify-content-center mt-5">
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header text-center">
|
||||
<h3>Enter Your Name</h3>
|
||||
</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 class="card-body">
|
||||
<form id="username-form">
|
||||
<div class="form-group">
|
||||
<input type="text" id="name" placeholder="Username" class="form-control" autocomplete="off">
|
||||
</div>
|
||||
<div class="form-group text-center">
|
||||
<button type="submit" class="btn btn-primary">Join Chat</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="chat-page">
|
||||
<div class="chat-container">
|
||||
<div class="chat-header">
|
||||
<h2>QChat</h2>
|
||||
</div>
|
||||
<ul id="message-area" class="list-unstyled"></ul>
|
||||
<form id="message-form" name="messageForm" class="message-form">
|
||||
<div class="input-group">
|
||||
<input type="text" id="message" placeholder="Type a message..." class="form-control" autocomplete="off"/>
|
||||
<div class="input-group-append">
|
||||
<button class="btn btn-primary" type="submit">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.4.0/sockjs.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
|
||||
<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(),
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const usernamePage = document.querySelector('#username-page');
|
||||
const chatPage = document.querySelector('#chat-page');
|
||||
const usernameForm = document.querySelector('#username-form');
|
||||
const messageForm = document.querySelector('#message-form');
|
||||
const messageInput = document.querySelector('#message');
|
||||
const messageArea = document.querySelector('#message-area');
|
||||
|
||||
let stompClient = null;
|
||||
let username = null;
|
||||
|
||||
usernamePage.style.display = 'block';
|
||||
|
||||
usernameForm.addEventListener('submit', connect, true);
|
||||
messageForm.addEventListener('submit', sendMessage, true);
|
||||
|
||||
function connect(event) {
|
||||
username = document.querySelector('#name').value.trim();
|
||||
|
||||
if (username) {
|
||||
usernamePage.style.display = 'none';
|
||||
chatPage.style.display = 'block';
|
||||
|
||||
const socket = new SockJS('/ws');
|
||||
stompClient = Stomp.over(socket);
|
||||
|
||||
stompClient.connect({}, onConnected, onError);
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
function onConnected() {
|
||||
// Subscribe to the Public Topic
|
||||
stompClient.subscribe('/topic/public', onMessageReceived);
|
||||
|
||||
// Tell your username to the server
|
||||
stompClient.send("/app/chat.addUser",
|
||||
{},
|
||||
JSON.stringify({sender: username, type: 'JOIN'})
|
||||
)
|
||||
}
|
||||
|
||||
function onError(error) {
|
||||
const connectingElement = document.createElement('li');
|
||||
connectingElement.classList.add('list-group-item', 'list-group-item-danger');
|
||||
connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
|
||||
messageArea.appendChild(connectingElement);
|
||||
}
|
||||
|
||||
function sendMessage(event) {
|
||||
const messageContent = messageInput.value.trim();
|
||||
if (messageContent && stompClient) {
|
||||
const chatMessage = {
|
||||
sender: username,
|
||||
content: messageInput.value
|
||||
};
|
||||
stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage));
|
||||
messageInput.value = '';
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
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 onMessageReceived(payload) {
|
||||
const message = JSON.parse(payload.body);
|
||||
|
||||
function setMe() {
|
||||
if (state.username) {
|
||||
els.me.textContent = `Signed in as ${state.username}`;
|
||||
const messageElement = document.createElement('li');
|
||||
messageElement.classList.add('list-group-item');
|
||||
|
||||
if (message.type === 'JOIN') {
|
||||
messageElement.classList.add('list-group-item-success');
|
||||
message.content = message.sender + ' joined!';
|
||||
} else if (message.type === 'LEAVE') {
|
||||
messageElement.classList.add('list-group-item-warning');
|
||||
message.content = message.sender + ' left!';
|
||||
} else {
|
||||
els.me.textContent = 'Not signed in';
|
||||
}
|
||||
const usernameElement = document.createElement('strong');
|
||||
usernameElement.appendChild(document.createTextNode(message.sender + ': '));
|
||||
messageElement.appendChild(usernameElement);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
}
|
||||
messageElement.appendChild(document.createTextNode(message.content));
|
||||
|
||||
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.`);
|
||||
messageArea.appendChild(messageElement);
|
||||
messageArea.scrollTop = messageArea.scrollHeight;
|
||||
}
|
||||
});
|
||||
// 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