Skip to content

Commit

Permalink
✨feat: add room not exist socket exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Quantaphocpython committed Nov 10, 2024
1 parent 447b7eb commit 90cd17d
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 43 deletions.
25 changes: 11 additions & 14 deletions src/main/java/com/videocall/server/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package com.videocall.server.config;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
Expand All @@ -19,7 +18,9 @@
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;

@Configuration
@RequiredArgsConstructor
Expand All @@ -34,13 +35,12 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(AbstractHttpConfigurer::disable)
.cors(cor -> cor.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests(
author -> author
.requestMatchers(HttpMethod.POST, PUBLIC_ENDPOINTS)
.permitAll()
.requestMatchers("/websocket/**").permitAll()
.anyRequest()
.authenticated())
.authorizeHttpRequests(author -> author.requestMatchers(HttpMethod.POST, PUBLIC_ENDPOINTS)
.permitAll()
.requestMatchers("/websocket/**")
.permitAll()
.anyRequest()
.authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwtConfigurer -> jwtConfigurer
.decoder(customJwtDecoder)
Expand All @@ -65,9 +65,6 @@ JwtAuthenticationConverter jwtAuthenticationConverter() {
return jwtAuthenticationConverter;
}




@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public void configureMessageBroker(MessageBrokerRegistry config) {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket")
.setAllowedOrigins("http://127.0.0.1:5500/", "http://localhost:3000/", "https://wemeet-client.vercel.app")
.setAllowedOrigins(
"http://127.0.0.1:5500/", "http://localhost:3000/", "https://wemeet-client.vercel.app")
.withSockJS();
}
}
18 changes: 10 additions & 8 deletions src/main/java/com/videocall/server/controller/RoomController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import com.videocall.server.exception.AppException;
import com.videocall.server.exception.ErrorCode;
import com.videocall.server.exception.SocketException;
import org.json.JSONObject;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
Expand All @@ -15,6 +14,8 @@

import com.videocall.server.dto.ApiResponse;
import com.videocall.server.dto.response.RoomResponse;
import com.videocall.server.exception.AppException;
import com.videocall.server.exception.ErrorCode;
import com.videocall.server.service.RoomService;

import lombok.AccessLevel;
Expand Down Expand Up @@ -47,8 +48,7 @@ public void join(String join) {
String roomId = jsonObject.getString("roomId");
String userId = jsonObject.getString("userId");

Boolean isExist = roomService.exist(roomId);
if(!isExist) throw new AppException(ErrorCode.ROOM_NOT_EXISTED);
if (!roomService.exist(roomId)) throw new SocketException(ErrorCode.ROOM_NOT_EXISTED, userId);

rooms.computeIfAbsent(roomId, s -> new HashSet<>()).add(userId);
Set<String> roomUsers = rooms.get(roomId);
Expand All @@ -67,8 +67,12 @@ public void join(String join) {
public void call(String call) {
JSONObject jsonObject = new JSONObject(call);
log.info("Calling to: {} | Call from: {}", jsonObject.get("callTo"), jsonObject.get("callFrom"));
log.info("Calling to class: {} | Call from class: {}", jsonObject.get("callTo").getClass(), jsonObject.get("callFrom").getClass());
simpMessagingTemplate.convertAndSendToUser(jsonObject.getString("callTo"), "/topic/call", jsonObject.get("callFrom"));
log.info(
"Calling to class: {} | Call from class: {}",
jsonObject.get("callTo").getClass(),
jsonObject.get("callFrom").getClass());
simpMessagingTemplate.convertAndSendToUser(
jsonObject.getString("callTo"), "/topic/call", jsonObject.get("callFrom"));
}

@MessageMapping("/offer")
Expand Down Expand Up @@ -103,6 +107,4 @@ public void candidate(String candidate) {
simpMessagingTemplate.convertAndSendToUser(jsonObject.getString("toUser"), "/topic/candidate", candidate);
log.info("Candidate sent");
}


}
5 changes: 2 additions & 3 deletions src/main/java/com/videocall/server/entity/Room.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package com.videocall.server.entity;

import java.security.SecureRandom;

import jakarta.persistence.*;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.*;
import lombok.experimental.FieldDefaults;

import java.security.SecureRandom;
import java.util.UUID;

@Entity
@Getter
@Setter
Expand Down
5 changes: 1 addition & 4 deletions src/main/java/com/videocall/server/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ public enum ErrorCode {
PASSWORD_IS_REQUIRED(1009, "Mật khẩu không được để trống", HttpStatus.BAD_REQUEST),
PASSWORD_IS_NOT_CORRECT(1010, "Mật khẩu không chính xác", HttpStatus.BAD_REQUEST),


//ROOM
// ROOM
ROOM_NOT_EXISTED(2001, "Phòng không tồn tại", HttpStatus.BAD_REQUEST),
;

Expand All @@ -29,8 +28,6 @@ public enum ErrorCode {
this.statusCode = statusCode;
}



private final int code;
private final String message;
private final HttpStatusCode statusCode;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
package com.videocall.server.exception;

import com.videocall.server.dto.ApiResponse;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;

import com.videocall.server.dto.ApiResponse;

@ControllerAdvice
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class GlobalSocketExceptionHandler {
SimpMessagingTemplate simpMessagingTemplate;


@MessageExceptionHandler(AppException.class)
@SendToUser("/topic/errors")
public ResponseEntity<ApiResponse> handleAppException(AppException e) {
@MessageExceptionHandler(SocketException.class)
public ResponseEntity<ApiResponse> handleAppException(SocketException e) {
ErrorCode errorCode = e.getErrorCode();

return ResponseEntity.status(errorCode.getCode()).body(ApiResponse.builder()
// Tạo thông báo lỗi
ApiResponse errorResponse = ApiResponse.builder()
.message(e.getMessage())
.code(errorCode.getCode())
.build());
.build();

// Gửi thông báo lỗi tới /user/{userId}/topic/errors
simpMessagingTemplate.convertAndSendToUser(e.getUserId(), "/topic/errors", errorResponse);

return ResponseEntity.badRequest().body(errorResponse);
}
}
18 changes: 18 additions & 0 deletions src/main/java/com/videocall/server/exception/SocketException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.videocall.server.exception;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class SocketException extends RuntimeException {

public SocketException(ErrorCode errorCode, String userId) {
super(errorCode.getMessage());
this.errorCode = errorCode;
this.userId = userId;
}

private ErrorCode errorCode;
private String userId;
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package com.videocall.server.service.implement;

import com.videocall.server.exception.AppException;
import com.videocall.server.exception.ErrorCode;
import org.springframework.stereotype.Service;

import com.videocall.server.dto.response.RoomResponse;
import com.videocall.server.entity.Room;
import com.videocall.server.entity.User;
import com.videocall.server.exception.AppException;
import com.videocall.server.exception.ErrorCode;
import com.videocall.server.repository.RoomRepository;
import com.videocall.server.repository.UserRepository;
import com.videocall.server.service.RoomService;
Expand All @@ -26,7 +26,9 @@ public class RoomServiceImp implements RoomService {
@Override
public RoomResponse create() {
String currentUserName = UserUtils.getCurrentUserName();
User user = userRepository.findById(currentUserName).orElseThrow(() -> new AppException(ErrorCode.USER_NOT_EXISTED));
User user = userRepository
.findById(currentUserName)
.orElseThrow(() -> new AppException(ErrorCode.USER_NOT_EXISTED));
Room room = roomRepository.save(Room.builder().user(user).build());
return RoomResponse.builder().id(room.getId()).build();
}
Expand All @@ -35,6 +37,4 @@ public RoomResponse create() {
public Boolean exist(String roomId) {
return roomRepository.existsById(roomId);
}


}

0 comments on commit 90cd17d

Please sign in to comment.