Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chatroom-dev-003-user-user-chat-dev-1 - Minor fix #122

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.yen.springChatRoom.bean;

//public class User {
// private
//}
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.DestinationVariable;
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 org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.PathVariable;


import java.util.Set;

@Slf4j
@Controller
Expand Down Expand Up @@ -91,16 +94,29 @@ public void addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor
}

// TODO : check @DestinationVariable ?
@RequestMapping("/app/private/{username}")
public void handlePrivateMessage(@DestinationVariable String username, Message message){
@MessageMapping("/private/{username}")
public void handlePrivateMessage(@PathVariable String username, Message message){

log.info("handlePrivateMessage : username = " + username + " message = " + message);
// save to redis

// save to redis
// redisTemplate.convertAndSend(userStatus, JsonUtil.parseObjToJson(chatMessage));
redisTemplate.opsForSet().add(privateChannel + "." + username, JsonUtil.parseObjToJson(message));
// TODO : fix data model
// current : handlePrivateMessage : username = {"sender":"fewfew","content":"777","type":"PRIVATE_CHAT"} message = Message(sender=fewfew, content=777, type=PRIVATE_CHAT)
//redisTemplate.opsForSet().add(privateChannel + "." + username, JsonUtil.parseObjToJson(message));
redisTemplate.opsForSet().add(privateChannel + "." + message.getSender(), JsonUtil.parseObjToJson(message));

simpMessagingTemplate.convertAndSendToUser(username, "/topic/private", message);
}

@MessageMapping("/private/history/{username}")
public void getHistoryPrivateChat(@PathVariable String username, Message message){

String key = "/private/history/" + username;
// Set<String> resultSet = redisTemplate.opsForSet().members("key1");
Set<String> res = redisTemplate.opsForSet().members(key);
res.forEach(System.out::println);

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.yen.springChatRoom.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

@RestController
@Slf4j
public class HistoryController {

@Value("${redis.channel.private}")
private String privateChannel;

@Autowired
private RedisTemplate<String, String> redisTemplate;
//private RedisTemplate redisTemplate;

//@MessageMapping("/private/chat_history/{username}")
@GetMapping("/private/chat_history/{username}")
public void getChatHistory(@PathVariable String username){

log.info("getChatHistory : username = " + username);

String key = "websocket.privateMsg." + username; // websocket.privateMsg.zzz
log.info("key = " + key);
Set<String> resultSet = redisTemplate.opsForSet().members(key);

log.info("--> start");
resultSet.forEach(System.out::println);
log.info("--> end");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ public class RedisListenerBean {
@Value("${redis.channel.userStatus}")
private String userStatus;

@Value("${redis.channel.private}")
private String privateChannel;

/** Redis channel bean
*
* 1. listen Redis channel via binding (for example : container.addMessageListener)
Expand All @@ -44,8 +47,15 @@ RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory

// listen msgToAll (Redis channel)
container.addMessageListener(listenerAdapter, new PatternTopic(msgToAll));
container.addMessageListener(listenerAdapter, new PatternTopic(userStatus));

LOGGER.info("Subscribe Redis channel : " + msgToAll);
container.addMessageListener(listenerAdapter, new PatternTopic(userStatus));

LOGGER.info("Subscribe Redis channel : " + userStatus);

container.addMessageListener(listenerAdapter, new PatternTopic(privateChannel));
LOGGER.info("Subscribe Redis channel : " + privateChannel);

return container;
}

Expand Down
47 changes: 32 additions & 15 deletions springChatRoom/src/main/resources/static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ function onConnected() {
// Subscribe to the "/private" destination // TODO : make it general
//stompClient.subscribe('/private/user123', onPrivateMessageReceived);

console.log(">>> subscribe /app/private/"+username );
stompClient.subscribe('/app/private/'+username);

stompClient.subscribe(`/app/private/chat_history/${username}`);

// Tell your username to the server
stompClient.send("/app/chat.addUser",
{},
Expand Down Expand Up @@ -125,6 +130,7 @@ function getAvatarColor(messageSender) {

// online user
function fetchUserList() {
// NOTE !!! it's http call (not web socket call)
fetch('/user/online_user') // Replace with the actual endpoint URL
.then(response => response.json())
.then(data => {
Expand All @@ -139,12 +145,6 @@ function updateOnlineUsers(users) {
const userList = document.getElementById('userList');
userList.innerHTML = ''; // Clear the list first

// users.forEach(user => {
// const listItem = document.createElement('li');
// listItem.textContent = user;
// userList.appendChild(listItem);
// });

users.forEach(user => {
const listItem = document.createElement('li');

Expand Down Expand Up @@ -196,23 +196,38 @@ function startChat(username) {
const messageInput = popupWindow.document.getElementById('messageInput');
const chatMessages = popupWindow.document.getElementById('chatMessages');

//log.info(">>> chatMessages = " + JSON.stringify(chatMessages))

const message = messageInput.value.trim();
if (message !== '') {
// Customize the way messages are displayed in the popup window
chatMessages.innerHTML += '<p><strong>You:</strong> ' + message + '</p>';

// TODO: Fetch and display chat history
//fetchChatHistory(username, chatMessages);

// TODO : implement below in BE
// Add your logic to send the message to the other user
// Example: stompClient.send('/app/private/' + username, {}, JSON.stringify({ sender: 'You', content: message, type: 'CHAT' }));

// send msg to BE
//stompClient.subscribe('/app/private/' + username, onPrivateMessageReceived);
stompClient.subscribe('/app/private/' + username);
console.log(">>> send msg to /app/private/" + username + ", message = " + message);
stompClient.send('/app/private/' + username, {}, JSON.stringify({ sender: 'You', content: message, type: 'CHAT' }));
//stompClient.subscribe('/app/private/' + username);

var chatMessage = {
sender: username,
content: messageInput.value,
type: 'PRIVATE_CHAT'
};

console.log(">>> chatMessage = " + JSON.stringify(chatMessage))

console.log(">>> send msg to /private/" + chatMessage.sender + ", message = " + message + " chatMessage = " + chatMessage);
stompClient.send(`/app/private/${chatMessage.sender}`, {}, JSON.stringify(chatMessage) );

console.log("send private msg end")

// TODO : check whether send private msg to Redis or fetch history msg from Redis first ?
// TODO: Fetch and display chat history
//fetchChatHistory(username, chatMessages);
//fetchChatHistory(username);

// Clear the input field
messageInput.value = '';
Expand All @@ -221,12 +236,14 @@ function startChat(username) {
}

// Function to fetch and display chat history
function fetchChatHistory(username, chatMessages) {
fetch('/app/chat/history/' + username)
function fetchChatHistory(username) {
fetch(`/private/chat_history/${username}`)
.then(response => response.json())
.then(console.log(">>> response = " + JSON.stringify(response)))
.then(history => {
history.forEach(message => {
chatMessages.innerHTML += '<p><strong>' + message.sender + ':</strong> ' + message.content + '</p>';
//chatMessages.innerHTML += '<p><strong>' + message.sender + ':</strong> ' + message.content + '</p>';
console.log(">>> message = " + JSON.stringify(message))
});
})
.catch(error => {
Expand Down