From f0fddedd2d405ca110d3b327b39310e52f5371a8 Mon Sep 17 00:00:00 2001 From: Oh-Myeongjae Date: Mon, 27 Oct 2025 18:28:49 +0900 Subject: [PATCH] =?UTF-8?q?sprint11=20=EA=B3=BC=EC=A0=9C=EC=A0=9C=EC=B6=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy.yml | 87 + .github/workflows/test.yml | 30 + .gitignore | 50 + Dockerfile | 40 + HELP.md | 22 + README.md | 5 + build.gradle | 73 + docker-compose.yml | 52 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43583 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 252 +++ gradlew.bat | 94 + settings.gradle | 1 + .../discodeit/DiscodeitApplication.java | 12 + .../mission/discodeit/config/AppConfig.java | 14 + .../mission/discodeit/config/AsyncConfig.java | 31 + .../mission/discodeit/config/CacheConfig.java | 89 + .../config/MDCLoggingInterceptor.java | 49 + .../discodeit/config/MDCTaskDecorator.java | 35 + .../discodeit/config/SecurityConfig.java | 137 ++ .../discodeit/config/SwaggerConfig.java | 25 + .../discodeit/config/WebMvcConfig.java | 24 + .../discodeit/controller/AuthController.java | 72 + .../controller/BinaryContentController.java | 60 + .../controller/ChannelController.java | 85 + .../controller/MessageController.java | 118 ++ .../controller/NotificationController.java | 44 + .../controller/ReadStatusController.java | 62 + .../discodeit/controller/UserController.java | 107 ++ .../discodeit/controller/api/AuthApi.java | 52 + .../controller/api/BinaryContentApi.java | 57 + .../discodeit/controller/api/ChannelApi.java | 89 + .../discodeit/controller/api/MessageApi.java | 90 + .../controller/api/ReadStatusApi.java | 67 + .../discodeit/controller/api/UserApi.java | 91 + .../discodeit/dto/data/BinaryContentDto.java | 12 + .../discodeit/dto/data/ChannelDto.java | 17 + .../mission/discodeit/dto/data/JwtDto.java | 7 + .../discodeit/dto/data/JwtInformation.java | 18 + .../discodeit/dto/data/MessageDto.java | 17 + .../discodeit/dto/data/NotificationDto.java | 14 + .../discodeit/dto/data/ReadStatusDto.java | 13 + .../mission/discodeit/dto/data/UserDto.java | 15 + .../request/BinaryContentCreateRequest.java | 19 + .../discodeit/dto/request/LoginRequest.java | 13 + .../dto/request/MessageCreateRequest.java | 20 + .../dto/request/MessageUpdateRequest.java | 12 + .../request/PrivateChannelCreateRequest.java | 16 + .../request/PublicChannelCreateRequest.java | 15 + .../request/PublicChannelUpdateRequest.java | 13 + .../dto/request/ReadStatusCreateRequest.java | 20 + .../dto/request/ReadStatusUpdateRequest.java | 14 + .../dto/request/RoleUpdateRequest.java | 11 + .../dto/request/UserCreateRequest.java | 25 + .../dto/request/UserUpdateRequest.java | 21 + .../discodeit/dto/response/PageResponse.java | 13 + .../discodeit/entity/BinaryContent.java | 39 + .../discodeit/entity/BinaryContentStatus.java | 7 + .../mission/discodeit/entity/Channel.java | 41 + .../mission/discodeit/entity/ChannelType.java | 6 + .../mission/discodeit/entity/Message.java | 55 + .../discodeit/entity/Notification.java | 33 + .../mission/discodeit/entity/ReadStatus.java | 51 + .../sprint/mission/discodeit/entity/Role.java | 7 + .../sprint/mission/discodeit/entity/User.java | 64 + .../discodeit/entity/base/BaseEntity.java | 31 + .../entity/base/BaseUpdatableEntity.java | 19 + .../event/BinaryContentCreatedEvent.java | 10 + .../discodeit/event/MessageCreatedEvent.java | 13 + .../discodeit/event/RoleUpdatedEvent.java | 13 + .../discodeit/event/S3UploadFailedEvent.java | 11 + .../BinaryContentCreatedEventListener.java | 75 + .../NotificationRequiredEventListener.java | 73 + .../exception/DiscodeitException.java | 32 + .../discodeit/exception/ErrorCode.java | 43 + .../discodeit/exception/ErrorResponse.java | 27 + .../exception/GlobalExceptionHandler.java | 96 + .../binarycontent/BinaryContentException.java | 14 + .../BinaryContentNotFoundException.java | 17 + .../exception/channel/ChannelException.java | 14 + .../channel/ChannelNotFoundException.java | 17 + .../PrivateChannelUpdateException.java | 17 + .../exception/message/MessageException.java | 14 + .../message/MessageNotFoundException.java | 17 + .../NotFoundNotificationException.java | 15 + .../notification/NotificationException.java | 12 + .../DuplicateReadStatusException.java | 18 + .../readstatus/ReadStatusException.java | 14 + .../ReadStatusNotFoundException.java | 17 + .../user/InvalidCredentialsException.java | 14 + .../user/UserAlreadyExistsException.java | 21 + .../exception/user/UserException.java | 14 + .../exception/user/UserNotFoundException.java | 23 + .../discodeit/mapper/BinaryContentMapper.java | 11 + .../discodeit/mapper/ChannelMapper.java | 48 + .../discodeit/mapper/MessageMapper.java | 13 + .../discodeit/mapper/NotificationMapper.java | 13 + .../discodeit/mapper/PageResponseMapper.java | 30 + .../discodeit/mapper/ReadStatusMapper.java | 14 + .../mission/discodeit/mapper/UserMapper.java | 18 + .../repository/BinaryContentRepository.java | 9 + .../repository/ChannelRepository.java | 12 + .../repository/MessageRepository.java | 31 + .../repository/NotificationRepository.java | 13 + .../repository/ReadStatusRepository.java | 27 + .../discodeit/repository/UserRepository.java | 26 + .../discodeit/security/AdminInitializer.java | 46 + .../security/DiscodeitUserDetails.java | 35 + .../security/DiscodeitUserDetailsService.java | 34 + .../Http403ForbiddenAccessDeniedHandler.java | 29 + .../security/LoginFailureHandler.java | 34 + .../security/LoginSuccessHandler.java | 42 + .../security/SpaCsrfTokenRequestHandler.java | 48 + .../security/jwt/InMemoryJwtRegistry.java | 129 ++ .../security/jwt/JwtAuthenticationFilter.java | 94 + .../security/jwt/JwtLoginSuccessHandler.java | 84 + .../security/jwt/JwtLogoutHandler.java | 41 + .../discodeit/security/jwt/JwtRegistry.java | 21 + .../security/jwt/JwtTokenProvider.java | 185 ++ .../discodeit/service/AuthService.java | 14 + .../service/BinaryContentService.java | 20 + .../discodeit/service/ChannelService.java | 23 + .../discodeit/service/MessageService.java | 25 + .../service/NotificationService.java | 12 + .../discodeit/service/ReadStatusService.java | 20 + .../discodeit/service/UserService.java | 24 + .../service/basic/BasicAuthService.java | 106 ++ .../basic/BasicBinaryContentService.java | 97 + .../service/basic/BasicChannelService.java | 129 ++ .../service/basic/BasicMessageService.java | 144 ++ .../basic/BasicNotificationService.java | 73 + .../service/basic/BasicReadStatusService.java | 108 ++ .../service/basic/BasicUserService.java | 171 ++ .../storage/BinaryContentStorage.java | 15 + .../local/LocalBinaryContentStorage.java | 93 + .../storage/s3/S3BinaryContentStorage.java | 181 ++ src/main/resources/application-dev.yaml | 30 + src/main/resources/application-prod.yaml | 25 + src/main/resources/application.yaml | 77 + src/main/resources/fe_bundle_1.2.3.zip | Bin 0 -> 95493 bytes src/main/resources/logback-spring.xml | 35 + src/main/resources/schema.sql | 113 ++ .../resources/static/assets/index-DB4IjbRs.js | 1572 +++++++++++++++++ .../static/assets/index-kQJbKSsj.css | 1 + src/main/resources/static/favicon.ico | Bin 0 -> 1588 bytes src/main/resources/static/index.html | 26 + .../controller/AuthControllerTest.java | 107 ++ .../BinaryContentControllerTest.java | 156 ++ .../controller/ChannelControllerTest.java | 291 +++ .../controller/MessageControllerTest.java | 321 ++++ .../controller/ReadStatusControllerTest.java | 183 ++ .../controller/UserControllerTest.java | 311 ++++ .../integration/AuthApiIntegrationTest.java | 124 ++ .../BinaryContentApiIntegrationTest.java | 217 +++ .../ChannelApiIntegrationTest.java | 288 +++ .../MessageApiIntegrationTest.java | 350 ++++ .../ReadStatusApiIntegrationTest.java | 280 +++ .../integration/UserApiIntegrationTest.java | 299 ++++ .../repository/ChannelRepositoryTest.java | 96 + .../repository/MessageRepositoryTest.java | 217 +++ .../repository/ReadStatusRepositoryTest.java | 197 +++ .../repository/UserRepositoryTest.java | 132 ++ .../mission/discodeit/security/CsrfTest.java | 34 + .../mission/discodeit/security/LoginTest.java | 138 ++ .../jwt/JwtAuthenticationFilterTest.java | 153 ++ .../jwt/JwtLoginSuccessHandlerTest.java | 130 ++ .../security/jwt/JwtTokenProviderTest.java | 208 +++ .../basic/BasicBinaryContentServiceTest.java | 172 ++ .../basic/BasicChannelServiceTest.java | 228 +++ .../basic/BasicMessageServiceTest.java | 370 ++++ .../service/basic/BasicUserServiceTest.java | 188 ++ .../discodeit/storage/s3/AWSS3Test.java | 174 ++ .../s3/S3BinaryContentStorageTest.java | 147 ++ src/test/resources/application-test.yaml | 32 + 174 files changed, 13216 insertions(+) create mode 100644 .github/workflows/deploy.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 HELP.md create mode 100644 README.md create mode 100644 build.gradle create mode 100644 docker-compose.yml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/AppConfig.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/AsyncConfig.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/CacheConfig.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/MDCLoggingInterceptor.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/MDCTaskDecorator.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/SecurityConfig.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/SwaggerConfig.java create mode 100644 src/main/java/com/sprint/mission/discodeit/config/WebMvcConfig.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/AuthController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/ChannelController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/MessageController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/NotificationController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/UserController.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/api/AuthApi.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/api/BinaryContentApi.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/api/ChannelApi.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/api/MessageApi.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/api/ReadStatusApi.java create mode 100644 src/main/java/com/sprint/mission/discodeit/controller/api/UserApi.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/BinaryContentDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/ChannelDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/JwtDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/JwtInformation.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/MessageDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/NotificationDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/ReadStatusDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/data/UserDto.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/BinaryContentCreateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/LoginRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/MessageCreateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/MessageUpdateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/PrivateChannelCreateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelCreateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelUpdateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusCreateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusUpdateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/RoleUpdateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/UserCreateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/request/UserUpdateRequest.java create mode 100644 src/main/java/com/sprint/mission/discodeit/dto/response/PageResponse.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/BinaryContent.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/BinaryContentStatus.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/Channel.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/ChannelType.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/Message.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/Notification.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/Role.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/User.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/base/BaseEntity.java create mode 100644 src/main/java/com/sprint/mission/discodeit/entity/base/BaseUpdatableEntity.java create mode 100644 src/main/java/com/sprint/mission/discodeit/event/BinaryContentCreatedEvent.java create mode 100644 src/main/java/com/sprint/mission/discodeit/event/MessageCreatedEvent.java create mode 100644 src/main/java/com/sprint/mission/discodeit/event/RoleUpdatedEvent.java create mode 100644 src/main/java/com/sprint/mission/discodeit/event/S3UploadFailedEvent.java create mode 100644 src/main/java/com/sprint/mission/discodeit/event/listener/BinaryContentCreatedEventListener.java create mode 100644 src/main/java/com/sprint/mission/discodeit/event/listener/NotificationRequiredEventListener.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/DiscodeitException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/ErrorCode.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/ErrorResponse.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentNotFoundException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelNotFoundException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/channel/PrivateChannelUpdateException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/message/MessageException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/message/MessageNotFoundException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/notification/NotFoundNotificationException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/notification/NotificationException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/readstatus/DuplicateReadStatusException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusNotFoundException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/user/InvalidCredentialsException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/user/UserAlreadyExistsException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/user/UserException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/exception/user/UserNotFoundException.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/BinaryContentMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/ChannelMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/MessageMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/NotificationMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/PageResponseMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/ReadStatusMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/mapper/UserMapper.java create mode 100644 src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java create mode 100644 src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java create mode 100644 src/main/java/com/sprint/mission/discodeit/repository/MessageRepository.java create mode 100644 src/main/java/com/sprint/mission/discodeit/repository/NotificationRepository.java create mode 100644 src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java create mode 100644 src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/AdminInitializer.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetails.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetailsService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/Http403ForbiddenAccessDeniedHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/LoginFailureHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/LoginSuccessHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/SpaCsrfTokenRequestHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/jwt/InMemoryJwtRegistry.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilter.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLogoutHandler.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/jwt/JwtRegistry.java create mode 100644 src/main/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProvider.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/AuthService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/ChannelService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/MessageService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/NotificationService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/UserService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicAuthService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicChannelService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicMessageService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicNotificationService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicReadStatusService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserService.java create mode 100644 src/main/java/com/sprint/mission/discodeit/storage/BinaryContentStorage.java create mode 100644 src/main/java/com/sprint/mission/discodeit/storage/local/LocalBinaryContentStorage.java create mode 100644 src/main/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorage.java create mode 100644 src/main/resources/application-dev.yaml create mode 100644 src/main/resources/application-prod.yaml create mode 100644 src/main/resources/application.yaml create mode 100644 src/main/resources/fe_bundle_1.2.3.zip create mode 100644 src/main/resources/logback-spring.xml create mode 100644 src/main/resources/schema.sql create mode 100644 src/main/resources/static/assets/index-DB4IjbRs.js create mode 100644 src/main/resources/static/assets/index-kQJbKSsj.css create mode 100644 src/main/resources/static/favicon.ico create mode 100644 src/main/resources/static/index.html create mode 100644 src/test/java/com/sprint/mission/discodeit/controller/AuthControllerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/controller/BinaryContentControllerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/controller/ChannelControllerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/controller/MessageControllerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/controller/ReadStatusControllerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/controller/UserControllerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/integration/AuthApiIntegrationTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/integration/BinaryContentApiIntegrationTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/integration/ChannelApiIntegrationTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/integration/MessageApiIntegrationTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/integration/ReadStatusApiIntegrationTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/integration/UserApiIntegrationTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/repository/ChannelRepositoryTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/repository/MessageRepositoryTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/repository/ReadStatusRepositoryTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/repository/UserRepositoryTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/security/CsrfTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/security/LoginTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilterTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandlerTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProviderTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentServiceTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/service/basic/BasicChannelServiceTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/service/basic/BasicMessageServiceTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserServiceTest.java create mode 100644 src/test/java/com/sprint/mission/discodeit/storage/s3/AWSS3Test.java create mode 100644 src/test/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorageTest.java create mode 100644 src/test/resources/application-test.yaml diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 000000000..068c6dfe6 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,87 @@ +name: 배포 + +on: + push: + branches: + - release + +jobs: + build-and-push: + runs-on: ubuntu-latest + outputs: + image_tag: ${{ github.sha }} + + steps: + - uses: actions/checkout@v4 + + - name: AWS CLI 설정 + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_KEY }} + aws-region: us-east-1 + + - name: ECR 로그인 + id: login-ecr + uses: aws-actions/amazon-ecr-login@v2 + with: + registry-type: public + + - name: Docker 이미지 빌드 및 푸시 + run: | + docker buildx build \ + -t ${{ vars.ECR_REPOSITORY_URI }}:${{ github.sha }} \ + -t ${{ vars.ECR_REPOSITORY_URI }}:latest \ + --push \ + . + deploy: + runs-on: ubuntu-latest + needs: build-and-push + + steps: + - name: AWS CLI 설정 + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_KEY }} + aws-region: ${{ vars.AWS_REGION }} + + - name: ECS 태스크 정의 업데이트 + run: | + TASK_DEFINITION=$( + aws ecs describe-task-definition \ + --task-definition ${{ vars.ECS_TASK_DEFINITION }} + ) + + NEW_TASK_DEFINITION=$( + echo $TASK_DEFINITION | jq \ + --arg IMAGE "${{ vars.ECR_REPOSITORY_URI }}:latest" \ + '.taskDefinition | .containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy)' + ) + + # 새로운 태스크 정의 등록 + NEW_TASK_DEF_ARN=$( + aws ecs register-task-definition \ + --cli-input-json "$NEW_TASK_DEFINITION" | \ + jq -r '.taskDefinition.taskDefinitionArn' + ) + + # 환경 파일에 변수 저장 (다음 단계에서 사용 가능) + echo "NEW_TASK_DEF_ARN=$NEW_TASK_DEF_ARN" >> $GITHUB_ENV + + - name: ECS 서비스 중지(프리티어 환경 고려) + run: | + aws ecs update-service \ + --cluster ${{ vars.ECS_CLUSTER }} \ + --service ${{ vars.ECS_SERVICE }} \ + --desired-count 0 + + - name: ECS 서비스 업데이트 + run: | + aws ecs update-service \ + --cluster ${{ vars.ECS_CLUSTER }} \ + --service ${{ vars.ECS_SERVICE }} \ + --task-definition $NEW_TASK_DEF_ARN \ + --desired-count 1 \ + --force-new-deployment + \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..97e594116 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,30 @@ +name: 테스트 + +on: + pull_request: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: 체크아웃 + uses: actions/checkout@v4 + + - name: JDK 17 설정 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'corretto' + cache: gradle + + - name: 테스트 실행 + run: ./gradlew test + + - name: Codecov 테스트 커버리지 업로드 + uses: codecov/codecov-action@v3 + with: + files: build/reports/jacoco/test/jacocoTestReport.xml + token: ${{ secrets.CODECOV_TOKEN }} # 퍼블릭 저장소라면 생략 가능 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..f14dfb825 --- /dev/null +++ b/.gitignore @@ -0,0 +1,50 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +### Discodeit ### +.discodeit + +### 숨김 파일 ### +.* +!.gitignore + + +### Github Actions ### +!.github/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..229bd68aa --- /dev/null +++ b/Dockerfile @@ -0,0 +1,40 @@ +# 빌드 스테이지 +FROM amazoncorretto:17 AS builder + +# 작업 디렉토리 설정 +WORKDIR /app + +# Gradle Wrapper 파일 먼저 복사 +COPY gradle ./gradle +COPY gradlew ./gradlew + +# Gradle 캐시를 위한 의존성 파일 복사 +COPY build.gradle settings.gradle ./ + +# 의존성 다운로드 +RUN ./gradlew dependencies + +# 소스 코드 복사 및 빌드 +COPY src ./src +RUN ./gradlew build -x test + + +# 런타임 스테이지 +FROM amazoncorretto:17-alpine3.21 + +# 작업 디렉토리 설정 +WORKDIR /app + +# 프로젝트 정보를 ENV로 설정 +ENV PROJECT_NAME=discodeit \ + PROJECT_VERSION=1.2-M8 \ + JVM_OPTS="" + +# 빌드 스테이지에서 jar 파일만 복사 +COPY --from=builder /app/build/libs/${PROJECT_NAME}-${PROJECT_VERSION}.jar ./ + +# 80 포트 노출 +EXPOSE 80 + +# jar 파일 실행 +ENTRYPOINT ["sh", "-c", "java ${JVM_OPTS} -jar ${PROJECT_NAME}-${PROJECT_VERSION}.jar"] \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 000000000..42c5f0023 --- /dev/null +++ b/HELP.md @@ -0,0 +1,22 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Gradle documentation](https://docs.gradle.org) +* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/3.4.0/gradle-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/3.4.0/gradle-plugin/packaging-oci-image.html) +* [Spring Web](https://docs.spring.io/spring-boot/3.4.0/reference/web/servlet.html) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) + +### Additional Links +These additional references should also help you: + +* [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) + diff --git a/README.md b/README.md new file mode 100644 index 000000000..a9e03e160 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# 0-spring-mission + +스프린트 미션 모범 답안 리포지토리입니다. + +[![codecov](https://codecov.io/gh/codeit-bootcamp-spring/0-sprint-mission/branch/s8%2Fadvanced/graph/badge.svg?token=XRIA1GENAM)](https://codecov.io/gh/codeit-bootcamp-spring/0-sprint-mission) \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..121cf45e9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,73 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.0' + id 'io.spring.dependency-management' version '1.1.6' + id 'jacoco' +} + +group = 'com.sprint.mission' +version = '2.2-M11' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } + testCompileOnly { + extendsFrom testAnnotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.4' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'software.amazon.awssdk:s3:2.31.7' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'com.nimbusds:nimbus-jose-jwt:10.3' + + runtimeOnly 'org.postgresql:postgresql' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + implementation 'org.mapstruct:mapstruct:1.6.3' + annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testImplementation 'com.h2database:h2' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' + implementation 'org.springframework.retry:spring-retry' + implementation 'org.springframework.boot:spring-boot-starter-aop' + implementation 'org.springframework.boot:spring-boot-starter-cache' + implementation 'com.github.ben-manes.caffeine:caffeine' +} + +tasks.named('test') { + useJUnitPlatform() +} + +test { + finalizedBy jacocoTestReport +} + +jacocoTestReport { + dependsOn test + reports { + xml.required = true + html.required = true + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..3e9c24f85 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,52 @@ +version: '3.8' + +services: + app: + image: discodeit:local + build: + context: . + dockerfile: Dockerfile + container_name: discodeit + ports: + - "8081:80" + environment: + - SPRING_PROFILES_ACTIVE=prod + - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/discodeit + - SPRING_DATASOURCE_USERNAME=${SPRING_DATASOURCE_USERNAME} + - SPRING_DATASOURCE_PASSWORD=${SPRING_DATASOURCE_PASSWORD} + - STORAGE_TYPE=s3 + - STORAGE_LOCAL_ROOT_PATH=.discodeit/storage + - AWS_S3_ACCESS_KEY=${AWS_S3_ACCESS_KEY} + - AWS_S3_SECRET_KEY=${AWS_S3_SECRET_KEY} + - AWS_S3_REGION=${AWS_S3_REGION} + - AWS_S3_BUCKET=${AWS_S3_BUCKET} + - AWS_S3_PRESIGNED_URL_EXPIRATION=600 + depends_on: + - db + volumes: + - binary-content-storage:/app/.discodeit/storage + networks: + - discodeit-network + + db: + image: postgres:16-alpine + container_name: discodeit-db + environment: + - POSTGRES_DB=discodeit + - POSTGRES_USER=${POSTGRES_USER} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + ports: + - "5432:5432" + volumes: + - postgres-data:/var/lib/postgresql/data + - ./src/main/resources/schema.sql:/docker-entrypoint-initdb.d/schema.sql + networks: + - discodeit-network + +volumes: + postgres-data: + binary-content-storage: + +networks: + discodeit-network: + driver: bridge \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..a4b76b9530d66f5e68d973ea569d8e19de379189 GIT binary patch literal 43583 zcma&N1CXTcmMvW9vTb(Rwr$&4wr$(C?dmSu>@vG-+vuvg^_??!{yS%8zW-#zn-LkA z5&1^$^{lnmUON?}LBF8_K|(?T0Ra(xUH{($5eN!MR#ZihR#HxkUPe+_R8Cn`RRs(P z_^*#_XlXmGv7!4;*Y%p4nw?{bNp@UZHv1?Um8r6)Fei3p@ClJn0ECfg1hkeuUU@Or zDaPa;U3fE=3L}DooL;8f;P0ipPt0Z~9P0)lbStMS)ag54=uL9ia-Lm3nh|@(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8=uYn z5BG-0g>pP21NPn>$ntBh>`*})Fl|38oC^9Qz>~MAazH%3Q~Qb!ALMf$srexgPZ2@&c~+hxRi1;}+)-06)!#Mq<6GhP z-Q?qmgo${aFBApb5p}$1OJKTClfi8%PpnczyVKkoHw7Ml9e7ikrF0d~UB}i3vizos zXW4DN$SiEV9{faLt5bHy2a>33K%7Td-n5C*N;f&ZqAg#2hIqEb(y<&f4u5BWJ>2^4 z414GosL=Aom#m&=x_v<0-fp1r%oVJ{T-(xnomNJ(Dryv zh?vj+%=II_nV+@NR+(!fZZVM&(W6{6%9cm+o+Z6}KqzLw{(>E86uA1`_K$HqINlb1 zKelh3-jr2I9V?ych`{hta9wQ2c9=MM`2cC{m6^MhlL2{DLv7C^j z$xXBCnDl_;l|bPGMX@*tV)B!c|4oZyftUlP*?$YU9C_eAsuVHJ58?)zpbr30P*C`T z7y#ao`uE-SOG(Pi+`$=e^mle~)pRrdwL5)N;o{gpW21of(QE#U6w%*C~`v-z0QqBML!!5EeYA5IQB0 z^l01c;L6E(iytN!LhL}wfwP7W9PNAkb+)Cst?qg#$n;z41O4&v+8-zPs+XNb-q zIeeBCh#ivnFLUCwfS;p{LC0O7tm+Sf9Jn)~b%uwP{%69;QC)Ok0t%*a5M+=;y8j=v z#!*pp$9@!x;UMIs4~hP#pnfVc!%-D<+wsG@R2+J&%73lK|2G!EQC)O05TCV=&3g)C!lT=czLpZ@Sa%TYuoE?v8T8`V;e$#Zf2_Nj6nvBgh1)2 GZ~q4|mN%#X literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..e2847c820 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 000000000..f5feea6d6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..9d21a2183 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..2437dfb29 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'discodeit' diff --git a/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java b/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java new file mode 100644 index 000000000..8f61230d4 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java @@ -0,0 +1,12 @@ +package com.sprint.mission.discodeit; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DiscodeitApplication { + + public static void main(String[] args) { + SpringApplication.run(DiscodeitApplication.class, args); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/config/AppConfig.java b/src/main/java/com/sprint/mission/discodeit/config/AppConfig.java new file mode 100644 index 000000000..ee9f8c2f8 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/AppConfig.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.retry.annotation.EnableRetry; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableJpaAuditing +@EnableScheduling +@EnableRetry +public class AppConfig { + +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/config/AsyncConfig.java b/src/main/java/com/sprint/mission/discodeit/config/AsyncConfig.java new file mode 100644 index 000000000..dfb87fbc9 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/AsyncConfig.java @@ -0,0 +1,31 @@ +package com.sprint.mission.discodeit.config; + +import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +@Configuration +@EnableAsync +public class AsyncConfig { + + @Bean(name = "customTaskExecutor") + public TaskExecutor taskExecutor() { + + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + + executor.setCorePoolSize(4); + executor.setMaxPoolSize(8); + executor.setQueueCapacity(50); + executor.setKeepAliveSeconds(30); + executor.setThreadNamePrefix("CustomExecutor-"); + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor.setTaskDecorator(new MDCTaskDecorator()); + + executor.initialize(); + + return executor; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/config/CacheConfig.java b/src/main/java/com/sprint/mission/discodeit/config/CacheConfig.java new file mode 100644 index 000000000..5501a6a1d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/CacheConfig.java @@ -0,0 +1,89 @@ +package com.sprint.mission.discodeit.config; + +import com.fasterxml.jackson.annotation.JsonTypeInfo.As; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.RemovalListener; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +@Slf4j +@Configuration +@EnableCaching +public class CacheConfig { + + @Bean + public CacheManager CacheManager() { + + CaffeineCacheManager cacheManager = new CaffeineCacheManager("users", "channelsByUser", + "notificationsByUser"); + + cacheManager.setCaffeine(caffeineConfig()); + + return cacheManager; + } + + @Bean + public Caffeine caffeineConfig() { + return Caffeine.newBuilder() + .initialCapacity(100) // 캐시 초기 용량 (HashMap 초기 용량 비슷한 개념) + .maximumSize(1000) // 캐시에 저장 가능한 최대 엔트리 수 + .expireAfterWrite(10, TimeUnit.MINUTES) // 값이 쓰여진 후 10분 지나면 만료 + .expireAfterAccess(10, TimeUnit.MINUTES) // 마지막 접근 후 10분 지나면 만료 + .removalListener(removalListener()) + .recordStats(); // hit/miss 등의 캐시 통계 수집 + } + + @Bean + public RemovalListener removalListener() { + return (key, value, cause) -> { + switch (cause) { + // SIZE: 크기 초과로 인한 제거 (정상적인 LRU/LFU 동작) + case SIZE: + log.debug("캐시 크기 초과로 인한 엔트리 제거 - key: {}", key); + break; + // EXPIRED: 시간 만료로 인한 제거 (TTL 정책) + case EXPIRED: + log.debug("만료 시간 도달로 인한 엔트리 제거 - key: {}", key); + break; + // EXPLICIT: 수동 삭제 (@CacheEvict 등) + case EXPLICIT: + log.info("수동 삭제로 인한 엔트리 제거 - key: {}", key); + break; + // REPLACED: 새 값으로 교체 + case REPLACED: + log.debug("새 값으로 교체로 인한 엔트리 제거 - key: {}", key); + break; + // 그 외 제거 원인 + default: + log.debug("캐시 엔트리 제거 - key: {}, cause: {}", key, cause); + } + }; + } + + @Bean("userIdKeyGenerator") + public KeyGenerator notificationUserKeyGenerator() { + return (target, method, params) -> { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + Object principal = auth.getPrincipal(); + + if (principal instanceof DiscodeitUserDetails userDetails) { + return userDetails.getUserDto().id(); + } + return UUID.randomUUID(); + }; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/config/MDCLoggingInterceptor.java b/src/main/java/com/sprint/mission/discodeit/config/MDCLoggingInterceptor.java new file mode 100644 index 000000000..569309f8a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/MDCLoggingInterceptor.java @@ -0,0 +1,49 @@ +package com.sprint.mission.discodeit.config; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.MDC; +import org.springframework.web.servlet.HandlerInterceptor; + +import java.util.UUID; + +/** + * 요청마다 MDC에 컨텍스트 정보를 추가하는 인터셉터 + */ +@Slf4j +public class MDCLoggingInterceptor implements HandlerInterceptor { + + /** + * MDC 로깅에 사용되는 상수 정의 + */ + public static final String REQUEST_ID = "requestId"; + public static final String REQUEST_METHOD = "requestMethod"; + public static final String REQUEST_URI = "requestUri"; + + public static final String REQUEST_ID_HEADER = "Discodeit-Request-ID"; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + // 요청 ID 생성 (UUID) + String requestId = UUID.randomUUID().toString().replaceAll("-", ""); + + // MDC에 컨텍스트 정보 추가 + MDC.put(REQUEST_ID, requestId); + MDC.put(REQUEST_METHOD, request.getMethod()); + MDC.put(REQUEST_URI, request.getRequestURI()); + + // 응답 헤더에 요청 ID 추가 + response.setHeader(REQUEST_ID_HEADER, requestId); + + log.debug("Request started"); + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { + // 요청 처리 후 MDC 데이터 정리 + log.debug("Request completed"); + MDC.clear(); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/config/MDCTaskDecorator.java b/src/main/java/com/sprint/mission/discodeit/config/MDCTaskDecorator.java new file mode 100644 index 000000000..de83f1e2e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/MDCTaskDecorator.java @@ -0,0 +1,35 @@ +package com.sprint.mission.discodeit.config; + +import java.util.Map; +import org.slf4j.MDC; +import org.springframework.core.task.TaskDecorator; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +@Component +public class MDCTaskDecorator implements TaskDecorator { + + @Override + public Runnable decorate(Runnable runnable) { + SecurityContext securityContext = SecurityContextHolder.getContext(); + Map mdcContext = MDC.getCopyOfContextMap(); + + return () -> { + try { + // 비동기 스레드에서 컨텍스트 복원 + SecurityContextHolder.setContext(securityContext); + + if (mdcContext != null) { + MDC.setContextMap(mdcContext); + } + + // 원본 작업 실행 + runnable.run(); + } finally { + SecurityContextHolder.clearContext(); + MDC.clear(); + } + }; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/config/SecurityConfig.java b/src/main/java/com/sprint/mission/discodeit/config/SecurityConfig.java new file mode 100644 index 000000000..aa03ba51a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/SecurityConfig.java @@ -0,0 +1,137 @@ +package com.sprint.mission.discodeit.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.security.Http403ForbiddenAccessDeniedHandler; +import com.sprint.mission.discodeit.security.LoginFailureHandler; +import com.sprint.mission.discodeit.security.SpaCsrfTokenRequestHandler; +import com.sprint.mission.discodeit.security.jwt.InMemoryJwtRegistry; +import com.sprint.mission.discodeit.security.jwt.JwtAuthenticationFilter; +import com.sprint.mission.discodeit.security.jwt.JwtLoginSuccessHandler; +import com.sprint.mission.discodeit.security.jwt.JwtLogoutHandler; +import com.sprint.mission.discodeit.security.jwt.JwtRegistry; +import com.sprint.mission.discodeit.security.jwt.JwtTokenProvider; +import java.util.List; +import java.util.stream.IntStream; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.NegatedRequestMatcher; + +@Slf4j +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain filterChain( + HttpSecurity http, + JwtLoginSuccessHandler jwtLoginSuccessHandler, + LoginFailureHandler loginFailureHandler, + ObjectMapper objectMapper, + JwtAuthenticationFilter jwtAuthenticationFilter, + JwtLogoutHandler jwtLogoutHandler + ) + throws Exception { + http + .csrf(csrf -> csrf + .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) + .csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()) + ) + .formLogin(login -> login + .loginProcessingUrl("/api/auth/login") + .successHandler(jwtLoginSuccessHandler) + .failureHandler(loginFailureHandler) + ) + .logout(logout -> logout + .logoutUrl("/api/auth/logout") + .addLogoutHandler(jwtLogoutHandler) + .logoutSuccessHandler( + new HttpStatusReturningLogoutSuccessHandler(HttpStatus.NO_CONTENT)) + ) + .authorizeHttpRequests(auth -> auth + .requestMatchers( + AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/api/auth/csrf-token"), + AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/api/users"), + AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/api/auth/login"), + AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/api/auth/refresh"), + AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/api/auth/logout"), + new NegatedRequestMatcher(AntPathRequestMatcher.antMatcher("/api/**")) + ).permitAll() + .anyRequest().authenticated() + ) + .exceptionHandling(ex -> ex + .authenticationEntryPoint(new Http403ForbiddenEntryPoint()) + .accessDeniedHandler(new Http403ForbiddenAccessDeniedHandler(objectMapper)) + ) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + // Add JWT authentication filter + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + ; + return http.build(); + } + + @Bean + public CommandLineRunner debugFilterChain(SecurityFilterChain filterChain) { + return args -> { + int filterSize = filterChain.getFilters().size(); + List filterNames = IntStream.range(0, filterSize) + .mapToObj(idx -> String.format("\t[%s/%s] %s", idx + 1, filterSize, + filterChain.getFilters().get(idx).getClass())) + .toList(); + log.debug("Debug Filter Chain...\n{}", String.join(System.lineSeparator(), filterNames)); + }; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.withDefaultRolePrefix() + .role(Role.ADMIN.name()) + .implies(Role.USER.name(), Role.CHANNEL_MANAGER.name()) + + .role(Role.CHANNEL_MANAGER.name()) + .implies(Role.USER.name()) + + .build(); + } + + @Bean + static MethodSecurityExpressionHandler methodSecurityExpressionHandler( + RoleHierarchy roleHierarchy) { + DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); + handler.setRoleHierarchy(roleHierarchy); + return handler; + } + + @Bean + public JwtRegistry jwtRegistry(JwtTokenProvider jwtTokenProvider) { + return new InMemoryJwtRegistry(1, jwtTokenProvider); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/config/SwaggerConfig.java b/src/main/java/com/sprint/mission/discodeit/config/SwaggerConfig.java new file mode 100644 index 000000000..d384d850f --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/SwaggerConfig.java @@ -0,0 +1,25 @@ +package com.sprint.mission.discodeit.config; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.servers.Server; +import java.util.List; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI customOpenAPI() { + return new OpenAPI() + .info(new Info() + .title("Discodeit API 문서") + .description("Discodeit 프로젝트의 Swagger API 문서입니다.") + .version("2.2") + ) + .servers(List.of( + new Server().url("http://localhost:8080").description("로컬 서버") + )); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/config/WebMvcConfig.java b/src/main/java/com/sprint/mission/discodeit/config/WebMvcConfig.java new file mode 100644 index 000000000..21790c7a0 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/WebMvcConfig.java @@ -0,0 +1,24 @@ +package com.sprint.mission.discodeit.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * 웹 MVC 설정 클래스 + */ +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Bean + public MDCLoggingInterceptor mdcLoggingInterceptor() { + return new MDCLoggingInterceptor(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(mdcLoggingInterceptor()) + .addPathPatterns("/**"); // 모든 경로에 적용 + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/controller/AuthController.java b/src/main/java/com/sprint/mission/discodeit/controller/AuthController.java new file mode 100644 index 000000000..5fa19d58d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/AuthController.java @@ -0,0 +1,72 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.controller.api.AuthApi; +import com.sprint.mission.discodeit.dto.data.JwtDto; +import com.sprint.mission.discodeit.dto.data.JwtInformation; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import com.sprint.mission.discodeit.security.jwt.JwtTokenProvider; +import com.sprint.mission.discodeit.service.AuthService; +import com.sprint.mission.discodeit.service.UserService; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.web.csrf.CsrfToken; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/auth") +public class AuthController implements AuthApi { + + private final AuthService authService; + private final UserService userService; + private final JwtTokenProvider jwtTokenProvider; + + @GetMapping("csrf-token") + public ResponseEntity getCsrfToken(CsrfToken csrfToken) { + log.debug("CSRF 토큰 요청"); + log.trace("CSRF 토큰: {}", csrfToken.getToken()); + return ResponseEntity + .status(HttpStatus.NO_CONTENT) + .build(); + } + + @PostMapping("refresh") + public ResponseEntity refresh(@CookieValue("REFRESH_TOKEN") String refreshToken, + HttpServletResponse response) { + log.info("토큰 리프레시 요청"); + JwtInformation jwtInformation = authService.refreshToken(refreshToken); + Cookie refreshCookie = jwtTokenProvider.genereateRefreshTokenCookie( + jwtInformation.getRefreshToken()); + response.addCookie(refreshCookie); + + JwtDto body = new JwtDto( + jwtInformation.getUserDto(), + jwtInformation.getAccessToken() + ); + return ResponseEntity + .status(HttpStatus.OK) + .body(body); + } + + @PutMapping("role") + public ResponseEntity updateRole(@RequestBody RoleUpdateRequest request) { + log.info("권한 수정 요청"); + UserDto userDto = authService.updateRole(request); + + return ResponseEntity + .status(HttpStatus.OK) + .body(userDto); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java b/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java new file mode 100644 index 000000000..a0b93ffde --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java @@ -0,0 +1,60 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.controller.api.BinaryContentApi; +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.service.BinaryContentService; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/binaryContents") +public class BinaryContentController implements BinaryContentApi { + + private final BinaryContentService binaryContentService; + private final BinaryContentStorage binaryContentStorage; + + @GetMapping(path = "{binaryContentId}") + public ResponseEntity find( + @PathVariable("binaryContentId") UUID binaryContentId) { + log.info("바이너리 컨텐츠 조회 요청: id={}", binaryContentId); + BinaryContentDto binaryContent = binaryContentService.find(binaryContentId); + log.debug("바이너리 컨텐츠 조회 응답: {}", binaryContent); + return ResponseEntity + .status(HttpStatus.OK) + .body(binaryContent); + } + + @GetMapping + public ResponseEntity> findAllByIdIn( + @RequestParam("binaryContentIds") List binaryContentIds) { + log.info("바이너리 컨텐츠 목록 조회 요청: ids={}", binaryContentIds); + List binaryContents = binaryContentService.findAllByIdIn(binaryContentIds); + log.debug("바이너리 컨텐츠 목록 조회 응답: count={}", binaryContents.size()); + return ResponseEntity + .status(HttpStatus.OK) + .body(binaryContents); + } + + @GetMapping(path = "{binaryContentId}/download") + public ResponseEntity download( + @PathVariable("binaryContentId") UUID binaryContentId) { + log.info("바이너리 컨텐츠 다운로드 요청: id={}", binaryContentId); + BinaryContentDto binaryContentDto = binaryContentService.find(binaryContentId); + ResponseEntity response = binaryContentStorage.download(binaryContentDto); + log.debug("바이너리 컨텐츠 다운로드 응답: contentType={}, contentLength={}", + response.getHeaders().getContentType(), response.getHeaders().getContentLength()); + return response; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/ChannelController.java b/src/main/java/com/sprint/mission/discodeit/controller/ChannelController.java new file mode 100644 index 000000000..3c8424236 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/ChannelController.java @@ -0,0 +1,85 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.controller.api.ChannelApi; +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import com.sprint.mission.discodeit.service.ChannelService; +import jakarta.validation.Valid; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/channels") +public class ChannelController implements ChannelApi { + + private final ChannelService channelService; + + @PostMapping(path = "public") + public ResponseEntity create(@RequestBody @Valid PublicChannelCreateRequest request) { + log.info("공개 채널 생성 요청: {}", request); + ChannelDto createdChannel = channelService.create(request); + log.debug("공개 채널 생성 응답: {}", createdChannel); + return ResponseEntity + .status(HttpStatus.CREATED) + .body(createdChannel); + } + + @PostMapping(path = "private") + public ResponseEntity create(@RequestBody @Valid PrivateChannelCreateRequest request) { + log.info("비공개 채널 생성 요청: {}", request); + ChannelDto createdChannel = channelService.create(request); + log.debug("비공개 채널 생성 응답: {}", createdChannel); + return ResponseEntity + .status(HttpStatus.CREATED) + .body(createdChannel); + } + + @PatchMapping(path = "{channelId}") + public ResponseEntity update( + @PathVariable("channelId") UUID channelId, + @RequestBody @Valid PublicChannelUpdateRequest request) { + log.info("채널 수정 요청: id={}, request={}", channelId, request); + ChannelDto updatedChannel = channelService.update(channelId, request); + log.debug("채널 수정 응답: {}", updatedChannel); + return ResponseEntity + .status(HttpStatus.OK) + .body(updatedChannel); + } + + @DeleteMapping(path = "{channelId}") + public ResponseEntity delete(@PathVariable("channelId") UUID channelId) { + log.info("채널 삭제 요청: id={}", channelId); + channelService.delete(channelId); + log.debug("채널 삭제 완료"); + return ResponseEntity + .status(HttpStatus.NO_CONTENT) + .build(); + } + + @GetMapping + public ResponseEntity> findAll(@RequestParam("userId") UUID userId) { + log.info("사용자별 채널 목록 조회 요청: userId={}", userId); + List channels = channelService.findAllByUserId(userId); + log.debug("사용자별 채널 목록 조회 응답: count={}", channels.size()); + return ResponseEntity + .status(HttpStatus.OK) + .body(channels); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/MessageController.java b/src/main/java/com/sprint/mission/discodeit/controller/MessageController.java new file mode 100644 index 000000000..ceb40ddcf --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/MessageController.java @@ -0,0 +1,118 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.controller.api.MessageApi; +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.response.PageResponse; +import com.sprint.mission.discodeit.service.MessageService; +import io.micrometer.core.annotation.Timed; +import jakarta.validation.Valid; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/messages") +public class MessageController implements MessageApi { + + private final MessageService messageService; + + @Timed("message.create.async") + @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity create( + @RequestPart("messageCreateRequest") @Valid MessageCreateRequest messageCreateRequest, + @RequestPart(value = "attachments", required = false) List attachments + ) { + log.info("메시지 생성 요청: request={}, attachmentCount={}", + messageCreateRequest, attachments != null ? attachments.size() : 0); + + List attachmentRequests = Optional.ofNullable(attachments) + .map(files -> files.stream() + .map(file -> { + try { + return new BinaryContentCreateRequest( + file.getOriginalFilename(), + file.getContentType(), + file.getBytes() + ); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .toList()) + .orElse(new ArrayList<>()); + MessageDto createdMessage = messageService.create(messageCreateRequest, attachmentRequests); + log.debug("메시지 생성 응답: {}", createdMessage); + return ResponseEntity + .status(HttpStatus.CREATED) + .body(createdMessage); + } + + @PatchMapping(path = "{messageId}") + public ResponseEntity update( + @PathVariable("messageId") UUID messageId, + @RequestBody @Valid MessageUpdateRequest request) { + log.info("메시지 수정 요청: id={}, request={}", messageId, request); + MessageDto updatedMessage = messageService.update(messageId, request); + log.debug("메시지 수정 응답: {}", updatedMessage); + return ResponseEntity + .status(HttpStatus.OK) + .body(updatedMessage); + } + + @DeleteMapping(path = "{messageId}") + public ResponseEntity delete(@PathVariable("messageId") UUID messageId) { + log.info("메시지 삭제 요청: id={}", messageId); + messageService.delete(messageId); + log.debug("메시지 삭제 완료"); + return ResponseEntity + .status(HttpStatus.NO_CONTENT) + .build(); + } + + @GetMapping + public ResponseEntity> findAllByChannelId( + @RequestParam("channelId") UUID channelId, + @RequestParam(value = "cursor", required = false) Instant cursor, + @PageableDefault( + size = 50, + page = 0, + sort = "createdAt", + direction = Direction.DESC + ) Pageable pageable) { + log.info("채널별 메시지 목록 조회 요청: channelId={}, cursor={}, pageable={}", + channelId, cursor, pageable); + PageResponse messages = messageService.findAllByChannelId(channelId, cursor, + pageable); + log.debug("채널별 메시지 목록 조회 응답: totalElements={}", messages.totalElements()); + return ResponseEntity + .status(HttpStatus.OK) + .body(messages); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/NotificationController.java b/src/main/java/com/sprint/mission/discodeit/controller/NotificationController.java new file mode 100644 index 000000000..04abb2691 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/NotificationController.java @@ -0,0 +1,44 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.dto.data.NotificationDto; +import com.sprint.mission.discodeit.service.NotificationService; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/notifications") +public class NotificationController { + + private final NotificationService notificationService; + + @GetMapping + public ResponseEntity> getNotifications() { + log.info("[NotificationController] 알림 조회 요청"); + + List result = notificationService.getNotifications(); + + return ResponseEntity.status(HttpStatus.OK).body(result); + } + + @DeleteMapping("/{notificationId}") + public ResponseEntity checkNotifications(@PathVariable UUID notificationId) { + log.info("[NotificationController] 알림 읽음 처리- notificationId: {}", notificationId); + + notificationService.checkNotifications(notificationId); + + log.info("[NotificationController] 알림 읽음 처리 완료- notificationId: {}", notificationId); + + return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java b/src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java new file mode 100644 index 000000000..ac980c066 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java @@ -0,0 +1,62 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.controller.api.ReadStatusApi; +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.dto.request.ReadStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusUpdateRequest; +import com.sprint.mission.discodeit.service.ReadStatusService; +import jakarta.validation.Valid; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/readStatuses") +public class ReadStatusController implements ReadStatusApi { + + private final ReadStatusService readStatusService; + + @PostMapping + public ResponseEntity create(@RequestBody @Valid ReadStatusCreateRequest request) { + log.info("읽음 상태 생성 요청: {}", request); + ReadStatusDto createdReadStatus = readStatusService.create(request); + log.debug("읽음 상태 생성 응답: {}", createdReadStatus); + return ResponseEntity + .status(HttpStatus.CREATED) + .body(createdReadStatus); + } + + @PatchMapping(path = "{readStatusId}") + public ResponseEntity update(@PathVariable("readStatusId") UUID readStatusId, + @RequestBody @Valid ReadStatusUpdateRequest request) { + log.info("읽음 상태 수정 요청: id={}, request={}", readStatusId, request); + ReadStatusDto updatedReadStatus = readStatusService.update(readStatusId, request); + log.debug("읽음 상태 수정 응답: {}", updatedReadStatus); + return ResponseEntity + .status(HttpStatus.OK) + .body(updatedReadStatus); + } + + @GetMapping + public ResponseEntity> findAllByUserId(@RequestParam("userId") UUID userId) { + log.info("사용자별 읽음 상태 목록 조회 요청: userId={}", userId); + List readStatuses = readStatusService.findAllByUserId(userId); + log.debug("사용자별 읽음 상태 목록 조회 응답: count={}", readStatuses.size()); + return ResponseEntity + .status(HttpStatus.OK) + .body(readStatuses); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/UserController.java b/src/main/java/com/sprint/mission/discodeit/controller/UserController.java new file mode 100644 index 000000000..4cdf75dda --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/UserController.java @@ -0,0 +1,107 @@ +package com.sprint.mission.discodeit.controller; + +import com.sprint.mission.discodeit.controller.api.UserApi; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import com.sprint.mission.discodeit.service.UserService; +import jakarta.validation.Valid; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/users") +public class UserController implements UserApi { + + private final UserService userService; + + @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) + @Override + public ResponseEntity create( + @RequestPart("userCreateRequest") @Valid UserCreateRequest userCreateRequest, + @RequestPart(value = "profile", required = false) MultipartFile profile + ) { + log.info("사용자 생성 요청: {}", userCreateRequest); + Optional profileRequest = Optional.ofNullable(profile) + .flatMap(this::resolveProfileRequest); + UserDto createdUser = userService.create(userCreateRequest, profileRequest); + log.debug("사용자 생성 응답: {}", createdUser); + return ResponseEntity + .status(HttpStatus.CREATED) + .body(createdUser); + } + + @PatchMapping( + path = "{userId}", + consumes = {MediaType.MULTIPART_FORM_DATA_VALUE} + ) + @Override + public ResponseEntity update( + @PathVariable("userId") UUID userId, + @RequestPart("userUpdateRequest") @Valid UserUpdateRequest userUpdateRequest, + @RequestPart(value = "profile", required = false) MultipartFile profile + ) { + log.info("사용자 수정 요청: id={}, request={}", userId, userUpdateRequest); + Optional profileRequest = Optional.ofNullable(profile) + .flatMap(this::resolveProfileRequest); + UserDto updatedUser = userService.update(userId, userUpdateRequest, profileRequest); + log.debug("사용자 수정 응답: {}", updatedUser); + return ResponseEntity + .status(HttpStatus.OK) + .body(updatedUser); + } + + @DeleteMapping(path = "{userId}") + @Override + public ResponseEntity delete(@PathVariable("userId") UUID userId) { + userService.delete(userId); + return ResponseEntity + .status(HttpStatus.NO_CONTENT) + .build(); + } + + @GetMapping + @Override + public ResponseEntity> findAll() { + List users = userService.findAll(); + return ResponseEntity + .status(HttpStatus.OK) + .body(users); + } + + private Optional resolveProfileRequest(MultipartFile profileFile) { + if (profileFile.isEmpty()) { + return Optional.empty(); + } else { + try { + BinaryContentCreateRequest binaryContentCreateRequest = new BinaryContentCreateRequest( + profileFile.getOriginalFilename(), + profileFile.getContentType(), + profileFile.getBytes() + ); + return Optional.of(binaryContentCreateRequest); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/controller/api/AuthApi.java b/src/main/java/com/sprint/mission/discodeit/controller/api/AuthApi.java new file mode 100644 index 000000000..9aa1e737c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/AuthApi.java @@ -0,0 +1,52 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.JwtDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.ResponseEntity; +import org.springframework.security.web.csrf.CsrfToken; + +@Tag(name = "Auth", description = "인증 API") +public interface AuthApi { + + @Operation(summary = "CSRF 토큰 요청") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "CSRF 토큰 요청 성공"), + @ApiResponse(responseCode = "400", description = "CSRF 토큰 요청 실패") + }) + ResponseEntity getCsrfToken( + @Parameter(hidden = true) CsrfToken csrfToken + ); + + + @Operation(summary = "사용자 권한 수정") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "권한 변경 성공", + content = @Content(schema = @Schema(implementation = UserDto.class)) + ) + }) + ResponseEntity updateRole( + @Parameter(description = "권한 수정 요청 정보") RoleUpdateRequest request); + + @Operation(summary = "토큰 리프레시") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "토큰 리프레시 성공", + content = @Content(schema = @Schema(implementation = UserDto.class)) + ), + @ApiResponse(responseCode = "401", description = "유효하지 않은 토큰") + }) + ResponseEntity refresh( + @Parameter(description = "리프레시 토큰") String refreshToken, + @Parameter(hidden = true) HttpServletResponse response + ); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/controller/api/BinaryContentApi.java b/src/main/java/com/sprint/mission/discodeit/controller/api/BinaryContentApi.java new file mode 100644 index 000000000..883ab8a88 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/BinaryContentApi.java @@ -0,0 +1,57 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.UUID; +import org.springframework.core.io.Resource; +import org.springframework.http.ResponseEntity; + +@Tag(name = "BinaryContent", description = "첨부 파일 API") +public interface BinaryContentApi { + + @Operation(summary = "첨부 파일 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "첨부 파일 조회 성공", + content = @Content(schema = @Schema(implementation = BinaryContentDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "첨부 파일을 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "BinaryContent with id {binaryContentId} not found")) + ) + }) + ResponseEntity find( + @Parameter(description = "조회할 첨부 파일 ID") UUID binaryContentId + ); + + @Operation(summary = "여러 첨부 파일 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "첨부 파일 목록 조회 성공", + content = @Content(array = @ArraySchema(schema = @Schema(implementation = BinaryContentDto.class))) + ) + }) + ResponseEntity> findAllByIdIn( + @Parameter(description = "조회할 첨부 파일 ID 목록") List binaryContentIds + ); + + @Operation(summary = "파일 다운로드") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "파일 다운로드 성공", + content = @Content(schema = @Schema(implementation = Resource.class)) + ) + }) + ResponseEntity download( + @Parameter(description = "다운로드할 파일 ID") UUID binaryContentId + ); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/controller/api/ChannelApi.java b/src/main/java/com/sprint/mission/discodeit/controller/api/ChannelApi.java new file mode 100644 index 000000000..af8c7afc7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/ChannelApi.java @@ -0,0 +1,89 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.UUID; +import org.springframework.http.ResponseEntity; + +@Tag(name = "Channel", description = "Channel API") +public interface ChannelApi { + + @Operation(summary = "Public Channel 생성") + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", description = "Public Channel이 성공적으로 생성됨", + content = @Content(schema = @Schema(implementation = ChannelDto.class)) + ) + }) + ResponseEntity create( + @Parameter(description = "Public Channel 생성 정보") PublicChannelCreateRequest request + ); + + @Operation(summary = "Private Channel 생성") + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", description = "Private Channel이 성공적으로 생성됨", + content = @Content(schema = @Schema(implementation = ChannelDto.class)) + ) + }) + ResponseEntity create( + @Parameter(description = "Private Channel 생성 정보") PrivateChannelCreateRequest request + ); + + @Operation(summary = "Channel 정보 수정") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "Channel 정보가 성공적으로 수정됨", + content = @Content(schema = @Schema(implementation = ChannelDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "Channel을 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "Channel with id {channelId} not found")) + ), + @ApiResponse( + responseCode = "400", description = "Private Channel은 수정할 수 없음", + content = @Content(examples = @ExampleObject(value = "Private channel cannot be updated")) + ) + }) + ResponseEntity update( + @Parameter(description = "수정할 Channel ID") UUID channelId, + @Parameter(description = "수정할 Channel 정보") PublicChannelUpdateRequest request + ); + + @Operation(summary = "Channel 삭제") + @ApiResponses(value = { + @ApiResponse( + responseCode = "204", description = "Channel이 성공적으로 삭제됨" + ), + @ApiResponse( + responseCode = "404", description = "Channel을 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "Channel with id {channelId} not found")) + ) + }) + ResponseEntity delete( + @Parameter(description = "삭제할 Channel ID") UUID channelId + ); + + @Operation(summary = "User가 참여 중인 Channel 목록 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "Channel 목록 조회 성공", + content = @Content(array = @ArraySchema(schema = @Schema(implementation = ChannelDto.class))) + ) + }) + ResponseEntity> findAll( + @Parameter(description = "조회할 User ID") UUID userId + ); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/controller/api/MessageApi.java b/src/main/java/com/sprint/mission/discodeit/controller/api/MessageApi.java new file mode 100644 index 000000000..c9a7aebbd --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/MessageApi.java @@ -0,0 +1,90 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.response.PageResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import org.springframework.data.domain.Pageable; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +@Tag(name = "Message", description = "Message API") +public interface MessageApi { + + @Operation(summary = "Message 생성") + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", description = "Message가 성공적으로 생성됨", + content = @Content(schema = @Schema(implementation = MessageDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "Channel 또는 User를 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "Channel | Author with id {channelId | authorId} not found")) + ), + }) + ResponseEntity create( + @Parameter( + description = "Message 생성 정보", + content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE) + ) MessageCreateRequest messageCreateRequest, + @Parameter( + description = "Message 첨부 파일들", + content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE) + ) List attachments + ); + + @Operation(summary = "Message 내용 수정") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "Message가 성공적으로 수정됨", + content = @Content(schema = @Schema(implementation = MessageDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "Message를 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "Message with id {messageId} not found")) + ), + }) + ResponseEntity update( + @Parameter(description = "수정할 Message ID") UUID messageId, + @Parameter(description = "수정할 Message 내용") MessageUpdateRequest request + ); + + @Operation(summary = "Message 삭제") + @ApiResponses(value = { + @ApiResponse( + responseCode = "204", description = "Message가 성공적으로 삭제됨" + ), + @ApiResponse( + responseCode = "404", description = "Message를 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "Message with id {messageId} not found")) + ), + }) + ResponseEntity delete( + @Parameter(description = "삭제할 Message ID") UUID messageId + ); + + @Operation(summary = "Channel의 Message 목록 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "Message 목록 조회 성공", + content = @Content(schema = @Schema(implementation = PageResponse.class)) + ) + }) + ResponseEntity> findAllByChannelId( + @Parameter(description = "조회할 Channel ID") UUID channelId, + @Parameter(description = "페이징 커서 정보") Instant cursor, + @Parameter(description = "페이징 정보", example = "{\"size\": 50, \"sort\": \"createdAt,desc\"}") Pageable pageable + ); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/controller/api/ReadStatusApi.java b/src/main/java/com/sprint/mission/discodeit/controller/api/ReadStatusApi.java new file mode 100644 index 000000000..eb08b359f --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/ReadStatusApi.java @@ -0,0 +1,67 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.dto.request.ReadStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusUpdateRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.UUID; +import org.springframework.http.ResponseEntity; + +@Tag(name = "ReadStatus", description = "Message 읽음 상태 API") +public interface ReadStatusApi { + + @Operation(summary = "Message 읽음 상태 생성") + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", description = "Message 읽음 상태가 성공적으로 생성됨", + content = @Content(schema = @Schema(implementation = ReadStatusDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "Channel 또는 User를 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "Channel | User with id {channelId | userId} not found")) + ), + @ApiResponse( + responseCode = "400", description = "이미 읽음 상태가 존재함", + content = @Content(examples = @ExampleObject(value = "ReadStatus with userId {userId} and channelId {channelId} already exists")) + ) + }) + ResponseEntity create( + @Parameter(description = "Message 읽음 상태 생성 정보") ReadStatusCreateRequest request + ); + + @Operation(summary = "Message 읽음 상태 수정") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "Message 읽음 상태가 성공적으로 수정됨", + content = @Content(schema = @Schema(implementation = ReadStatusDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "Message 읽음 상태를 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "ReadStatus with id {readStatusId} not found")) + ) + }) + ResponseEntity update( + @Parameter(description = "수정할 읽음 상태 ID") UUID readStatusId, + @Parameter(description = "수정할 읽음 상태 정보") ReadStatusUpdateRequest request + ); + + @Operation(summary = "User의 Message 읽음 상태 목록 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "Message 읽음 상태 목록 조회 성공", + content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReadStatusDto.class))) + ) + }) + ResponseEntity> findAllByUserId( + @Parameter(description = "조회할 User ID") UUID userId + ); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/controller/api/UserApi.java b/src/main/java/com/sprint/mission/discodeit/controller/api/UserApi.java new file mode 100644 index 000000000..6ab77d163 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/UserApi.java @@ -0,0 +1,91 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.UUID; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +@Tag(name = "User", description = "User API") +public interface UserApi { + + @Operation(summary = "User 등록") + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", description = "User가 성공적으로 생성됨", + content = @Content(schema = @Schema(implementation = UserDto.class)) + ), + @ApiResponse( + responseCode = "400", description = "같은 email 또는 username를 사용하는 User가 이미 존재함", + content = @Content(examples = @ExampleObject(value = "User with email {email} already exists")) + ), + }) + ResponseEntity create( + @Parameter( + description = "User 생성 정보", + content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE) + ) UserCreateRequest userCreateRequest, + @Parameter( + description = "User 프로필 이미지", + content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE) + ) MultipartFile profile + ); + + @Operation(summary = "User 정보 수정") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "User 정보가 성공적으로 수정됨", + content = @Content(schema = @Schema(implementation = UserDto.class)) + ), + @ApiResponse( + responseCode = "404", description = "User를 찾을 수 없음", + content = @Content(examples = @ExampleObject("User with id {userId} not found")) + ), + @ApiResponse( + responseCode = "400", description = "같은 email 또는 username를 사용하는 User가 이미 존재함", + content = @Content(examples = @ExampleObject("user with email {newEmail} already exists")) + ) + }) + ResponseEntity update( + @Parameter(description = "수정할 User ID") UUID userId, + @Parameter(description = "수정할 User 정보") UserUpdateRequest userUpdateRequest, + @Parameter(description = "수정할 User 프로필 이미지") MultipartFile profile + ); + + @Operation(summary = "User 삭제") + @ApiResponses(value = { + @ApiResponse( + responseCode = "204", + description = "User가 성공적으로 삭제됨" + ), + @ApiResponse( + responseCode = "404", + description = "User를 찾을 수 없음", + content = @Content(examples = @ExampleObject(value = "User with id {id} not found")) + ) + }) + ResponseEntity delete( + @Parameter(description = "삭제할 User ID") UUID userId + ); + + @Operation(summary = "전체 User 목록 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "User 목록 조회 성공", + content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserDto.class))) + ) + }) + ResponseEntity> findAll(); +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/BinaryContentDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/BinaryContentDto.java new file mode 100644 index 000000000..d44aee484 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/BinaryContentDto.java @@ -0,0 +1,12 @@ +package com.sprint.mission.discodeit.dto.data; + +import java.util.UUID; + +public record BinaryContentDto( + UUID id, + String fileName, + Long size, + String contentType +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/ChannelDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/ChannelDto.java new file mode 100644 index 000000000..cf9b99080 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/ChannelDto.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.dto.data; + +import com.sprint.mission.discodeit.entity.ChannelType; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record ChannelDto( + UUID id, + ChannelType type, + String name, + String description, + List participants, + Instant lastMessageAt +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/JwtDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/JwtDto.java new file mode 100644 index 000000000..eb64d7f80 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/JwtDto.java @@ -0,0 +1,7 @@ +package com.sprint.mission.discodeit.dto.data; + +public record JwtDto( + UserDto userDto, + String accessToken +) { +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/JwtInformation.java b/src/main/java/com/sprint/mission/discodeit/dto/data/JwtInformation.java new file mode 100644 index 000000000..18039aca3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/JwtInformation.java @@ -0,0 +1,18 @@ +package com.sprint.mission.discodeit.dto.data; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class JwtInformation { + + private UserDto userDto; + private String accessToken; + private String refreshToken; + + public void rotate(String newAccessToken, String newRefreshToken) { + this.accessToken = newAccessToken; + this.refreshToken = newRefreshToken; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/MessageDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/MessageDto.java new file mode 100644 index 000000000..6bcaa0907 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/MessageDto.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.dto.data; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record MessageDto( + UUID id, + Instant createdAt, + Instant updatedAt, + String content, + UUID channelId, + UserDto author, + List attachments +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/NotificationDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/NotificationDto.java new file mode 100644 index 000000000..779f73637 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/NotificationDto.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.dto.data; + +import java.time.Instant; +import java.util.UUID; + +public record NotificationDto( + UUID id, + Instant createdAt, + UUID receiverId, + String title, + String content +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/ReadStatusDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/ReadStatusDto.java new file mode 100644 index 000000000..1d0bc2c12 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/ReadStatusDto.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.dto.data; + +import java.time.Instant; +import java.util.UUID; + +public record ReadStatusDto( + UUID id, + UUID userId, + UUID channelId, + Instant lastReadAt +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/UserDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/UserDto.java new file mode 100644 index 000000000..7f3b6920b --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/UserDto.java @@ -0,0 +1,15 @@ +package com.sprint.mission.discodeit.dto.data; + +import com.sprint.mission.discodeit.entity.Role; +import java.util.UUID; + +public record UserDto( + UUID id, + String username, + String email, + BinaryContentDto profile, + Boolean online, + Role role +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/BinaryContentCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/BinaryContentCreateRequest.java new file mode 100644 index 000000000..402239697 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/BinaryContentCreateRequest.java @@ -0,0 +1,19 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +public record BinaryContentCreateRequest( + @NotBlank(message = "파일 이름은 필수입니다") + @Size(max = 255, message = "파일 이름은 255자 이하여야 합니다") + String fileName, + + @NotBlank(message = "콘텐츠 타입은 필수입니다") + String contentType, + + @NotNull(message = "파일 데이터는 필수입니다") + byte[] bytes +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/LoginRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/LoginRequest.java new file mode 100644 index 000000000..40452eea2 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/LoginRequest.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotBlank; + +public record LoginRequest( + @NotBlank(message = "사용자 이름은 필수입니다") + String username, + + @NotBlank(message = "비밀번호는 필수입니다") + String password +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/MessageCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/MessageCreateRequest.java new file mode 100644 index 000000000..366539aee --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/MessageCreateRequest.java @@ -0,0 +1,20 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.util.UUID; + +public record MessageCreateRequest( + @NotBlank(message = "메시지 내용은 필수입니다") + @Size(max = 2000, message = "메시지 내용은 2000자 이하여야 합니다") + String content, + + @NotNull(message = "채널 ID는 필수입니다") + UUID channelId, + + @NotNull(message = "작성자 ID는 필수입니다") + UUID authorId +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/MessageUpdateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/MessageUpdateRequest.java new file mode 100644 index 000000000..792ef27c2 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/MessageUpdateRequest.java @@ -0,0 +1,12 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +public record MessageUpdateRequest( + @NotBlank(message = "메시지 내용은 필수입니다") + @Size(max = 2000, message = "메시지 내용은 2000자 이하여야 합니다") + String newContent +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/PrivateChannelCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/PrivateChannelCreateRequest.java new file mode 100644 index 000000000..478cf4e32 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/PrivateChannelCreateRequest.java @@ -0,0 +1,16 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.util.List; +import java.util.UUID; + +public record PrivateChannelCreateRequest( + @NotNull(message = "참여자 목록은 필수입니다") + @NotEmpty(message = "참여자 목록은 비어있을 수 없습니다") + @Size(min = 2, message = "비공개 채널에는 최소 2명의 참여자가 필요합니다") + List participantIds +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelCreateRequest.java new file mode 100644 index 000000000..e2e284a02 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelCreateRequest.java @@ -0,0 +1,15 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +public record PublicChannelCreateRequest( + @NotBlank(message = "채널명은 필수입니다") + @Size(min = 2, max = 50, message = "채널명은 2자 이상 50자 이하여야 합니다") + String name, + + @Size(max = 255, message = "채널 설명은 255자 이하여야 합니다") + String description +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelUpdateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelUpdateRequest.java new file mode 100644 index 000000000..e438f761c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelUpdateRequest.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.Size; + +public record PublicChannelUpdateRequest( + @Size(min = 2, max = 50, message = "채널명은 2자 이상 50자 이하여야 합니다") + String newName, + + @Size(max = 255, message = "채널 설명은 255자 이하여야 합니다") + String newDescription +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusCreateRequest.java new file mode 100644 index 000000000..f7f485199 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusCreateRequest.java @@ -0,0 +1,20 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.PastOrPresent; +import java.time.Instant; +import java.util.UUID; + +public record ReadStatusCreateRequest( + @NotNull(message = "사용자 ID는 필수입니다") + UUID userId, + + @NotNull(message = "채널 ID는 필수입니다") + UUID channelId, + + @NotNull(message = "마지막 읽은 시간은 필수입니다") + @PastOrPresent(message = "마지막 읽은 시간은 현재 또는 과거 시간이어야 합니다") + Instant lastReadAt +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusUpdateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusUpdateRequest.java new file mode 100644 index 000000000..104490465 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusUpdateRequest.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.PastOrPresent; +import java.time.Instant; + +public record ReadStatusUpdateRequest( + @NotNull(message = "새로운 마지막 읽은 시간은 필수입니다") + @PastOrPresent(message = "마지막 읽은 시간은 현재 또는 과거 시간이어야 합니다") + Instant newLastReadAt, + boolean newNotificationEnabled +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/RoleUpdateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/RoleUpdateRequest.java new file mode 100644 index 000000000..63fb44989 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/RoleUpdateRequest.java @@ -0,0 +1,11 @@ +package com.sprint.mission.discodeit.dto.request; + +import com.sprint.mission.discodeit.entity.Role; +import java.util.UUID; + +public record RoleUpdateRequest( + UUID userId, + Role newRole +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/UserCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/UserCreateRequest.java new file mode 100644 index 000000000..a8c888423 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/UserCreateRequest.java @@ -0,0 +1,25 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; + +public record UserCreateRequest( + @NotBlank(message = "사용자 이름은 필수입니다") + @Size(min = 3, max = 50, message = "사용자 이름은 3자 이상 50자 이하여야 합니다") + String username, + + @NotBlank(message = "이메일은 필수입니다") + @Email(message = "유효한 이메일 형식이어야 합니다") + @Size(max = 100, message = "이메일은 100자 이하여야 합니다") + String email, + + @NotBlank(message = "비밀번호는 필수입니다") + @Size(min = 8, max = 60, message = "비밀번호는 8자 이상 60자 이하여야 합니다") + @Pattern(regexp = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,}$", + message = "비밀번호는 최소 8자 이상, 숫자, 문자, 특수문자를 포함해야 합니다") + String password +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/UserUpdateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/UserUpdateRequest.java new file mode 100644 index 000000000..96b8517c7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/UserUpdateRequest.java @@ -0,0 +1,21 @@ +package com.sprint.mission.discodeit.dto.request; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; + +public record UserUpdateRequest( + @Size(min = 3, max = 50, message = "사용자 이름은 3자 이상 50자 이하여야 합니다") + String newUsername, + + @Email(message = "유효한 이메일 형식이어야 합니다") + @Size(max = 100, message = "이메일은 100자 이하여야 합니다") + String newEmail, + + @Size(min = 8, max = 60, message = "비밀번호는 8자 이상 60자 이하여야 합니다") + @Pattern(regexp = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,}$", + message = "비밀번호는 최소 8자 이상, 숫자, 문자, 특수문자를 포함해야 합니다") + String newPassword +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/response/PageResponse.java b/src/main/java/com/sprint/mission/discodeit/dto/response/PageResponse.java new file mode 100644 index 000000000..181d532d7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/response/PageResponse.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.dto.response; + +import java.util.List; + +public record PageResponse( + List content, + Object nextCursor, + int size, + boolean hasNext, + Long totalElements +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/BinaryContent.java b/src/main/java/com/sprint/mission/discodeit/entity/BinaryContent.java new file mode 100644 index 000000000..021b094f7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/BinaryContent.java @@ -0,0 +1,39 @@ +package com.sprint.mission.discodeit.entity; + +import com.sprint.mission.discodeit.entity.base.BaseEntity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "binary_contents") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class BinaryContent extends BaseEntity { + + @Column(nullable = false) + private String fileName; + @Column(nullable = false) + private Long size; + @Column(length = 100, nullable = false) + private String contentType; + @Column(name = "status", nullable = false) + @Enumerated(EnumType.STRING) + private BinaryContentStatus status = BinaryContentStatus.PROCESSING; + + + public BinaryContent(String fileName, Long size, String contentType) { + this.fileName = fileName; + this.size = size; + this.contentType = contentType; + } + + public void updateStatus(BinaryContentStatus status) { + this.status = status; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/BinaryContentStatus.java b/src/main/java/com/sprint/mission/discodeit/entity/BinaryContentStatus.java new file mode 100644 index 000000000..e3f4823d6 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/BinaryContentStatus.java @@ -0,0 +1,7 @@ +package com.sprint.mission.discodeit.entity; + +public enum BinaryContentStatus { + PROCESSING, + SUCCESS, + FAIL +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Channel.java b/src/main/java/com/sprint/mission/discodeit/entity/Channel.java new file mode 100644 index 000000000..101b737bd --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/Channel.java @@ -0,0 +1,41 @@ +package com.sprint.mission.discodeit.entity; + +import com.sprint.mission.discodeit.entity.base.BaseUpdatableEntity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "channels") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Channel extends BaseUpdatableEntity { + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private ChannelType type; + @Column(length = 100) + private String name; + @Column(length = 500) + private String description; + + public Channel(ChannelType type, String name, String description) { + this.type = type; + this.name = name; + this.description = description; + } + + public void update(String newName, String newDescription) { + if (newName != null && !newName.equals(this.name)) { + this.name = newName; + } + if (newDescription != null && !newDescription.equals(this.description)) { + this.description = newDescription; + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/ChannelType.java b/src/main/java/com/sprint/mission/discodeit/entity/ChannelType.java new file mode 100644 index 000000000..4fca37721 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/ChannelType.java @@ -0,0 +1,6 @@ +package com.sprint.mission.discodeit.entity; + +public enum ChannelType { + PUBLIC, + PRIVATE, +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Message.java b/src/main/java/com/sprint/mission/discodeit/entity/Message.java new file mode 100644 index 000000000..7fe8865ea --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/Message.java @@ -0,0 +1,55 @@ +package com.sprint.mission.discodeit.entity; + +import com.sprint.mission.discodeit.entity.base.BaseUpdatableEntity; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import java.util.ArrayList; +import java.util.List; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.BatchSize; + +@Entity +@Table(name = "messages") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Message extends BaseUpdatableEntity { + + @Column(columnDefinition = "text", nullable = false) + private String content; + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "channel_id", columnDefinition = "uuid") + private Channel channel; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "author_id", columnDefinition = "uuid") + private User author; + @BatchSize(size = 100) + @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL) + @JoinTable( + name = "message_attachments", + joinColumns = @JoinColumn(name = "message_id"), + inverseJoinColumns = @JoinColumn(name = "attachment_id") + ) + private List attachments = new ArrayList<>(); + + public Message(String content, Channel channel, User author, List attachments) { + this.channel = channel; + this.content = content; + this.author = author; + this.attachments = attachments; + } + + public void update(String newContent) { + if (newContent != null && !newContent.equals(this.content)) { + this.content = newContent; + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Notification.java b/src/main/java/com/sprint/mission/discodeit/entity/Notification.java new file mode 100644 index 000000000..5d8093f4f --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/Notification.java @@ -0,0 +1,33 @@ +package com.sprint.mission.discodeit.entity; + +import com.sprint.mission.discodeit.entity.base.BaseEntity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "notifications") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Notification extends BaseEntity { + @Column(name = "title") + private String title; + + @Column(name = "content") + private String content; + + @ManyToOne + @JoinColumn(name = "user_id") + private User user; + + public Notification(String title, String content, User user) { + this.title = title; + this.content = content; + this.user = user; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java b/src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java new file mode 100644 index 000000000..ce1ad86db --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java @@ -0,0 +1,51 @@ +package com.sprint.mission.discodeit.entity; + +import com.sprint.mission.discodeit.entity.base.BaseUpdatableEntity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; +import java.time.Instant; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table( + name = "read_statuses", + uniqueConstraints = { + @UniqueConstraint(columnNames = {"user_id", "channel_id"}) + } +) +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class ReadStatus extends BaseUpdatableEntity { + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "user_id", columnDefinition = "uuid") + private User user; + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "channel_id", columnDefinition = "uuid") + private Channel channel; + @Column(columnDefinition = "timestamp with time zone", nullable = false) + private Instant lastReadAt; + @Column(name = "notification_enabled", nullable = false) + private boolean notificationEnabled; + + public ReadStatus(User user, Channel channel, Instant lastReadAt, boolean notificationEnabled) { + this.user = user; + this.channel = channel; + this.lastReadAt = lastReadAt; + this.notificationEnabled = notificationEnabled; + } + + public void update(Instant newLastReadAt, boolean notificationEnabled) { + if (newLastReadAt != null && !newLastReadAt.equals(this.lastReadAt)) { + this.lastReadAt = newLastReadAt; + } + this.notificationEnabled = notificationEnabled; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Role.java b/src/main/java/com/sprint/mission/discodeit/entity/Role.java new file mode 100644 index 000000000..6b9c0b052 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/Role.java @@ -0,0 +1,7 @@ +package com.sprint.mission.discodeit.entity; + +public enum Role { + ADMIN, + CHANNEL_MANAGER, + USER +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/User.java b/src/main/java/com/sprint/mission/discodeit/entity/User.java new file mode 100644 index 000000000..6044be8a2 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/User.java @@ -0,0 +1,64 @@ +package com.sprint.mission.discodeit.entity; + +import com.sprint.mission.discodeit.entity.base.BaseUpdatableEntity; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "users") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) // JPA를 위한 기본 생성자 +public class User extends BaseUpdatableEntity { + + @Column(length = 50, nullable = false, unique = true) + private String username; + @Column(length = 100, nullable = false, unique = true) + private String email; + @Column(length = 60, nullable = false) + private String password; + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) + @JoinColumn(name = "profile_id", columnDefinition = "uuid") + private BinaryContent profile; + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private Role role = Role.USER; + + public User(String username, String email, String password, BinaryContent profile) { + this.username = username; + this.email = email; + this.password = password; + this.profile = profile; + } + + public void update(String newUsername, String newEmail, String newPassword, + BinaryContent newProfile) { + if (newUsername != null && !newUsername.equals(this.username)) { + this.username = newUsername; + } + if (newEmail != null && !newEmail.equals(this.email)) { + this.email = newEmail; + } + if (newPassword != null && !newPassword.equals(this.password)) { + this.password = newPassword; + } + if (newProfile != null) { + this.profile = newProfile; + } + } + + public void updateRole(Role newRole) { + if (this.role != newRole) { + this.role = newRole; + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/base/BaseEntity.java b/src/main/java/com/sprint/mission/discodeit/entity/base/BaseEntity.java new file mode 100644 index 000000000..f28210164 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/base/BaseEntity.java @@ -0,0 +1,31 @@ +package com.sprint.mission.discodeit.entity.base; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import java.time.Instant; +import java.util.UUID; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + @Column(columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + @CreatedDate + @Column(columnDefinition = "timestamp with time zone", updatable = false, nullable = false) + private Instant createdAt; +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/base/BaseUpdatableEntity.java b/src/main/java/com/sprint/mission/discodeit/entity/base/BaseUpdatableEntity.java new file mode 100644 index 000000000..57d1d3169 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/base/BaseUpdatableEntity.java @@ -0,0 +1,19 @@ +package com.sprint.mission.discodeit.entity.base; + +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import java.time.Instant; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.LastModifiedDate; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@MappedSuperclass +public abstract class BaseUpdatableEntity extends BaseEntity { + + @LastModifiedDate + @Column(columnDefinition = "timestamp with time zone") + private Instant updatedAt; +} diff --git a/src/main/java/com/sprint/mission/discodeit/event/BinaryContentCreatedEvent.java b/src/main/java/com/sprint/mission/discodeit/event/BinaryContentCreatedEvent.java new file mode 100644 index 000000000..f201edb7a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/event/BinaryContentCreatedEvent.java @@ -0,0 +1,10 @@ +package com.sprint.mission.discodeit.event; + +import com.sprint.mission.discodeit.entity.BinaryContent; + +public record BinaryContentCreatedEvent( + BinaryContent binaryContent, + byte[] data +) { + +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/event/MessageCreatedEvent.java b/src/main/java/com/sprint/mission/discodeit/event/MessageCreatedEvent.java new file mode 100644 index 000000000..54131c3c7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/event/MessageCreatedEvent.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.event; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.User; +import java.util.UUID; + +public record MessageCreatedEvent( + User author, + Channel channel, + String content +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/event/RoleUpdatedEvent.java b/src/main/java/com/sprint/mission/discodeit/event/RoleUpdatedEvent.java new file mode 100644 index 000000000..2fd9cbfa9 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/event/RoleUpdatedEvent.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.event; + +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.entity.User; +import java.util.UUID; + +public record RoleUpdatedEvent( + User user, + Role oldRole, + Role newRole +) { + +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/event/S3UploadFailedEvent.java b/src/main/java/com/sprint/mission/discodeit/event/S3UploadFailedEvent.java new file mode 100644 index 000000000..afd7122b4 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/event/S3UploadFailedEvent.java @@ -0,0 +1,11 @@ +package com.sprint.mission.discodeit.event; + +import java.util.UUID; + +public record S3UploadFailedEvent( + String requestId, + UUID binaryContentId, + String errorMessage +) { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/event/listener/BinaryContentCreatedEventListener.java b/src/main/java/com/sprint/mission/discodeit/event/listener/BinaryContentCreatedEventListener.java new file mode 100644 index 000000000..829e022aa --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/event/listener/BinaryContentCreatedEventListener.java @@ -0,0 +1,75 @@ +package com.sprint.mission.discodeit.event.listener; + +import com.sprint.mission.discodeit.entity.BinaryContentStatus; +import com.sprint.mission.discodeit.entity.Notification; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.event.BinaryContentCreatedEvent; +import com.sprint.mission.discodeit.event.S3UploadFailedEvent; +import com.sprint.mission.discodeit.repository.NotificationRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.service.BinaryContentService; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.springframework.transaction.event.TransactionPhase; +import org.springframework.transaction.event.TransactionalEventListener; + +@Slf4j +@Component +@RequiredArgsConstructor +public class BinaryContentCreatedEventListener { + + private final BinaryContentStorage storage; + private final BinaryContentService binaryContentService; + private final UserRepository userRepository; + private final NotificationRepository notificationRepository; + + @Async("customTaskExecutor") + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void onBinaryContentCreated(BinaryContentCreatedEvent event) { + + log.debug("[BinaryContentCreatedEventListener] onBinaryContent id: {}, fileName: {}", + event.binaryContent().getId(), + event.binaryContent().getFileName()); + + UUID id = event.binaryContent().getId(); + byte[] data = event.data(); + + // 바이너리 데이터 저장 + try { + storage.put(id, event.data()); + binaryContentService.updateStatus(id, BinaryContentStatus.SUCCESS); + + log.info("[BinaryContentCreatedEventListener] 바이너리 데이터 저장 성공: {}", id); + } catch (Exception e) { + log.error("[BinaryContentCreatedEventListener] 바이너리 데이터 저장 성공: {}, 실패 이유: {}", id, + e.getMessage(), e); + + binaryContentService.updateStatus(id, BinaryContentStatus.FAIL); + } + } + + @Async("customTaskExecutor") + @EventListener + public void onS3UploadFailed(S3UploadFailedEvent event) { + + String content = + "Request Id: " + event.requestId() + "\n BinaryContentId: " + event.binaryContentId() + + "\n Error: " + + event.errorMessage(); + + List notifications = userRepository.findAllByRole(Role.ADMIN).stream() + .map(user -> new Notification("S3 파일 업로드 실패", content, user)) + .toList(); + + notificationRepository.saveAll(notifications); + + log.debug("[NotificationRequiredEventListener] S3 업로드 실패 알림 전송 완료- {}개", + notifications.size()); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/event/listener/NotificationRequiredEventListener.java b/src/main/java/com/sprint/mission/discodeit/event/listener/NotificationRequiredEventListener.java new file mode 100644 index 000000000..9f09fff52 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/event/listener/NotificationRequiredEventListener.java @@ -0,0 +1,73 @@ +package com.sprint.mission.discodeit.event.listener; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Notification; +import com.sprint.mission.discodeit.entity.ReadStatus; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.event.MessageCreatedEvent; +import com.sprint.mission.discodeit.event.RoleUpdatedEvent; +import com.sprint.mission.discodeit.repository.NotificationRepository; +import com.sprint.mission.discodeit.repository.ReadStatusRepository; +import java.util.List; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.event.TransactionPhase; +import org.springframework.transaction.event.TransactionalEventListener; + +@Slf4j +@Component +@RequiredArgsConstructor +public class NotificationRequiredEventListener { + + private final NotificationRepository notificationRepository; + private final ReadStatusRepository readStatusRepository; + private static final String ROLE_UPDATE_TITLE = "권한이 변경되었습니다."; + + @Async("customTaskExecutor") + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void on(MessageCreatedEvent event) { + + User author = event.author(); + Channel channel = event.channel(); + String title = author.getUsername() + " (#" + channel.getName() + ")"; + String content = event.content(); + + List readStatuses = readStatusRepository.findAllByChannel_IdAndNotificationEnabled( + channel.getId(), true + ); + + log.debug("[NotificationRequiredEventListener] 알림 수신 가능 사용자 수: {}", readStatuses.size()); + + List notifications = readStatuses.stream() + .filter(readStatus -> !readStatus.getUser().equals(author)) + .map(readStatus -> new Notification(title, content, readStatus.getUser())) + .toList(); + + notificationRepository.saveAll(notifications); + + log.debug("[NotificationRequiredEventListener] 알림 {}개 생성 완료", notifications.size()); + } + + @Async("customTaskExecutor") + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void on(RoleUpdatedEvent event) { + + User user = event.user(); + Role oldRole = event.oldRole(); + Role newRole = event.newRole(); + + String content = oldRole.name() + " -> " + newRole.name(); + + Notification notification = new Notification(ROLE_UPDATE_TITLE, content, user); + + Notification savedNotification = notificationRepository.save(notification); + + log.debug("[NotificationRequiredEventListener] 권한 변경 알림 생성 완료- id: {}", + savedNotification.getId()); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/DiscodeitException.java b/src/main/java/com/sprint/mission/discodeit/exception/DiscodeitException.java new file mode 100644 index 000000000..d929a51f8 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/DiscodeitException.java @@ -0,0 +1,32 @@ +package com.sprint.mission.discodeit.exception; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +import lombok.Getter; + +@Getter +public class DiscodeitException extends RuntimeException { + private final Instant timestamp; + private final ErrorCode errorCode; + private final Map details; + + public DiscodeitException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.timestamp = Instant.now(); + this.errorCode = errorCode; + this.details = new HashMap<>(); + } + + public DiscodeitException(ErrorCode errorCode, Throwable cause) { + super(errorCode.getMessage(), cause); + this.timestamp = Instant.now(); + this.errorCode = errorCode; + this.details = new HashMap<>(); + } + + public void addDetail(String key, Object value) { + this.details.put(key, value); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/ErrorCode.java b/src/main/java/com/sprint/mission/discodeit/exception/ErrorCode.java new file mode 100644 index 000000000..d6482ad2c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/ErrorCode.java @@ -0,0 +1,43 @@ +package com.sprint.mission.discodeit.exception; + +import lombok.Getter; + +@Getter +public enum ErrorCode { + // User 관련 에러 코드 + USER_NOT_FOUND("사용자를 찾을 수 없습니다."), + DUPLICATE_USER("이미 존재하는 사용자입니다."), + INVALID_USER_CREDENTIALS("잘못된 사용자 인증 정보입니다."), + + // Channel 관련 에러 코드 + CHANNEL_NOT_FOUND("채널을 찾을 수 없습니다."), + PRIVATE_CHANNEL_UPDATE("비공개 채널은 수정할 수 없습니다."), + + // Message 관련 에러 코드 + MESSAGE_NOT_FOUND("메시지를 찾을 수 없습니다."), + + // BinaryContent 관련 에러 코드 + BINARY_CONTENT_NOT_FOUND("바이너리 컨텐츠를 찾을 수 없습니다."), + + // ReadStatus 관련 에러 코드 + READ_STATUS_NOT_FOUND("읽음 상태를 찾을 수 없습니다."), + DUPLICATE_READ_STATUS("이미 존재하는 읽음 상태입니다."), + + // Server 에러 코드 + INTERNAL_SERVER_ERROR("서버 내부 오류가 발생했습니다."), + INVALID_REQUEST("잘못된 요청입니다."), + + // Security 관련 에러 코드 + INVALID_TOKEN("토큰이 유효하지 않습니다."), + INVALID_USER_DETAILS("사용자 인증 정보(UserDetails)가 유효하지 않습니다."), + + //Notification 관련 에러 코드 + NOTIFICATION_NOT_FOUND("알림을 찾을 수 없습니다."), + ; + + private final String message; + + ErrorCode(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/ErrorResponse.java b/src/main/java/com/sprint/mission/discodeit/exception/ErrorResponse.java new file mode 100644 index 000000000..6a9ae50ef --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/ErrorResponse.java @@ -0,0 +1,27 @@ +package com.sprint.mission.discodeit.exception; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class ErrorResponse { + private final Instant timestamp; + private final String code; + private final String message; + private final Map details; + private final String exceptionType; + private final int status; + + public ErrorResponse(DiscodeitException exception, int status) { + this(Instant.now(), exception.getErrorCode().name(), exception.getMessage(), exception.getDetails(), exception.getClass().getSimpleName(), status); + } + + public ErrorResponse(Exception exception, int status) { + this(Instant.now(), exception.getClass().getSimpleName(), exception.getMessage(), new HashMap<>(), exception.getClass().getSimpleName(), status); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/GlobalExceptionHandler.java b/src/main/java/com/sprint/mission/discodeit/exception/GlobalExceptionHandler.java new file mode 100644 index 000000000..ad2bf00a3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/GlobalExceptionHandler.java @@ -0,0 +1,96 @@ +package com.sprint.mission.discodeit.exception; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.boot.actuate.autoconfigure.observation.ObservationProperties.Http; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authorization.AuthorizationDeniedException; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception e) { + log.error("예상치 못한 오류 발생: {}", e.getMessage(), e); + ErrorResponse errorResponse = new ErrorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR.value()); + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(errorResponse); + } + + @ExceptionHandler(DiscodeitException.class) + public ResponseEntity handleDiscodeitException(DiscodeitException exception) { + log.error("커스텀 예외 발생: code={}, message={}", exception.getErrorCode(), exception.getMessage(), + exception); + HttpStatus status = determineHttpStatus(exception); + ErrorResponse response = new ErrorResponse(exception, status.value()); + return ResponseEntity + .status(status) + .body(response); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidationExceptions( + MethodArgumentNotValidException ex) { + log.error("요청 유효성 검사 실패: {}", ex.getMessage()); + + Map validationErrors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach(error -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + validationErrors.put(fieldName, errorMessage); + }); + + ErrorResponse response = new ErrorResponse( + Instant.now(), + "VALIDATION_ERROR", + "요청 데이터 유효성 검사에 실패했습니다", + validationErrors, + ex.getClass().getSimpleName(), + HttpStatus.BAD_REQUEST.value() + ); + + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .body(response); + } + + @ExceptionHandler(AuthorizationDeniedException.class) + public ResponseEntity handleAuthorizationDeniedException( + AuthorizationDeniedException ex) { + log.error("권한 거부 오류 발생: {}", ex.getMessage()); + ErrorResponse response = new ErrorResponse( + Instant.now(), + "AUTHORIZATION_DENIED", + "요청에 대한 권한이 없습니다", + null, + ex.getClass().getSimpleName(), + HttpStatus.FORBIDDEN.value() + ); + return ResponseEntity + .status(HttpStatus.FORBIDDEN) + .body(response); + } + + private HttpStatus determineHttpStatus(DiscodeitException exception) { + ErrorCode errorCode = exception.getErrorCode(); + return switch (errorCode) { + case USER_NOT_FOUND, CHANNEL_NOT_FOUND, MESSAGE_NOT_FOUND, BINARY_CONTENT_NOT_FOUND, + READ_STATUS_NOT_FOUND, NOTIFICATION_NOT_FOUND -> HttpStatus.NOT_FOUND; + case DUPLICATE_USER, DUPLICATE_READ_STATUS -> HttpStatus.CONFLICT; + case INVALID_USER_CREDENTIALS, INVALID_TOKEN, INVALID_USER_DETAILS -> HttpStatus.UNAUTHORIZED; + case PRIVATE_CHANNEL_UPDATE, INVALID_REQUEST -> HttpStatus.BAD_REQUEST; + case INTERNAL_SERVER_ERROR -> HttpStatus.INTERNAL_SERVER_ERROR; + }; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentException.java b/src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentException.java new file mode 100644 index 000000000..368025bf2 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentException.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.exception.binarycontent; + +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class BinaryContentException extends DiscodeitException { + public BinaryContentException(ErrorCode errorCode) { + super(errorCode); + } + + public BinaryContentException(ErrorCode errorCode, Throwable cause) { + super(errorCode, cause); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentNotFoundException.java b/src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentNotFoundException.java new file mode 100644 index 000000000..65ad82363 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/binarycontent/BinaryContentNotFoundException.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.exception.binarycontent; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +import java.util.UUID; + +public class BinaryContentNotFoundException extends BinaryContentException { + public BinaryContentNotFoundException() { + super(ErrorCode.BINARY_CONTENT_NOT_FOUND); + } + + public static BinaryContentNotFoundException withId(UUID binaryContentId) { + BinaryContentNotFoundException exception = new BinaryContentNotFoundException(); + exception.addDetail("binaryContentId", binaryContentId); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelException.java b/src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelException.java new file mode 100644 index 000000000..1ba3364ba --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelException.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.exception.channel; + +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class ChannelException extends DiscodeitException { + public ChannelException(ErrorCode errorCode) { + super(errorCode); + } + + public ChannelException(ErrorCode errorCode, Throwable cause) { + super(errorCode, cause); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelNotFoundException.java b/src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelNotFoundException.java new file mode 100644 index 000000000..ec7b1f335 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/channel/ChannelNotFoundException.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.exception.channel; + +import java.util.UUID; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class ChannelNotFoundException extends ChannelException { + public ChannelNotFoundException() { + super(ErrorCode.CHANNEL_NOT_FOUND); + } + + public static ChannelNotFoundException withId(UUID channelId) { + ChannelNotFoundException exception = new ChannelNotFoundException(); + exception.addDetail("channelId", channelId); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/channel/PrivateChannelUpdateException.java b/src/main/java/com/sprint/mission/discodeit/exception/channel/PrivateChannelUpdateException.java new file mode 100644 index 000000000..2b8b1597c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/channel/PrivateChannelUpdateException.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.exception.channel; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +import java.util.UUID; + +public class PrivateChannelUpdateException extends ChannelException { + public PrivateChannelUpdateException() { + super(ErrorCode.PRIVATE_CHANNEL_UPDATE); + } + + public static PrivateChannelUpdateException forChannel(UUID channelId) { + PrivateChannelUpdateException exception = new PrivateChannelUpdateException(); + exception.addDetail("channelId", channelId); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/message/MessageException.java b/src/main/java/com/sprint/mission/discodeit/exception/message/MessageException.java new file mode 100644 index 000000000..289922ed3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/message/MessageException.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.exception.message; + +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class MessageException extends DiscodeitException { + public MessageException(ErrorCode errorCode) { + super(errorCode); + } + + public MessageException(ErrorCode errorCode, Throwable cause) { + super(errorCode, cause); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/message/MessageNotFoundException.java b/src/main/java/com/sprint/mission/discodeit/exception/message/MessageNotFoundException.java new file mode 100644 index 000000000..423aafbb3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/message/MessageNotFoundException.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.exception.message; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +import java.util.UUID; + +public class MessageNotFoundException extends MessageException { + public MessageNotFoundException() { + super(ErrorCode.MESSAGE_NOT_FOUND); + } + + public static MessageNotFoundException withId(UUID messageId) { + MessageNotFoundException exception = new MessageNotFoundException(); + exception.addDetail("messageId", messageId); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/notification/NotFoundNotificationException.java b/src/main/java/com/sprint/mission/discodeit/exception/notification/NotFoundNotificationException.java new file mode 100644 index 000000000..1e4648872 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/notification/NotFoundNotificationException.java @@ -0,0 +1,15 @@ +package com.sprint.mission.discodeit.exception.notification; + + +import com.sprint.mission.discodeit.exception.ErrorCode; +import java.util.UUID; + +public class NotFoundNotificationException extends NotificationException { + public NotFoundNotificationException() {super(ErrorCode.NOTIFICATION_NOT_FOUND);} + + public static NotFoundNotificationException withId(UUID notificationId) { + NotFoundNotificationException exception = new NotFoundNotificationException(); + exception.addDetail("notificationId", notificationId); + return exception; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/exception/notification/NotificationException.java b/src/main/java/com/sprint/mission/discodeit/exception/notification/NotificationException.java new file mode 100644 index 000000000..1056847a3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/notification/NotificationException.java @@ -0,0 +1,12 @@ +package com.sprint.mission.discodeit.exception.notification; + +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; +import java.util.Map; + +public class NotificationException extends DiscodeitException { + + public NotificationException(ErrorCode errorCode) { + super(errorCode); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/exception/readstatus/DuplicateReadStatusException.java b/src/main/java/com/sprint/mission/discodeit/exception/readstatus/DuplicateReadStatusException.java new file mode 100644 index 000000000..5a30692d8 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/readstatus/DuplicateReadStatusException.java @@ -0,0 +1,18 @@ +package com.sprint.mission.discodeit.exception.readstatus; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +import java.util.UUID; + +public class DuplicateReadStatusException extends ReadStatusException { + public DuplicateReadStatusException() { + super(ErrorCode.DUPLICATE_READ_STATUS); + } + + public static DuplicateReadStatusException withUserIdAndChannelId(UUID userId, UUID channelId) { + DuplicateReadStatusException exception = new DuplicateReadStatusException(); + exception.addDetail("userId", userId); + exception.addDetail("channelId", channelId); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusException.java b/src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusException.java new file mode 100644 index 000000000..3860caf2e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusException.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.exception.readstatus; + +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class ReadStatusException extends DiscodeitException { + public ReadStatusException(ErrorCode errorCode) { + super(errorCode); + } + + public ReadStatusException(ErrorCode errorCode, Throwable cause) { + super(errorCode, cause); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusNotFoundException.java b/src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusNotFoundException.java new file mode 100644 index 000000000..86b9fde75 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/readstatus/ReadStatusNotFoundException.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.exception.readstatus; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +import java.util.UUID; + +public class ReadStatusNotFoundException extends ReadStatusException { + public ReadStatusNotFoundException() { + super(ErrorCode.READ_STATUS_NOT_FOUND); + } + + public static ReadStatusNotFoundException withId(UUID readStatusId) { + ReadStatusNotFoundException exception = new ReadStatusNotFoundException(); + exception.addDetail("readStatusId", readStatusId); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/user/InvalidCredentialsException.java b/src/main/java/com/sprint/mission/discodeit/exception/user/InvalidCredentialsException.java new file mode 100644 index 000000000..d75576fdf --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/user/InvalidCredentialsException.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.exception.user; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class InvalidCredentialsException extends UserException { + public InvalidCredentialsException() { + super(ErrorCode.INVALID_USER_CREDENTIALS); + } + + public static InvalidCredentialsException wrongPassword() { + InvalidCredentialsException exception = new InvalidCredentialsException(); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/user/UserAlreadyExistsException.java b/src/main/java/com/sprint/mission/discodeit/exception/user/UserAlreadyExistsException.java new file mode 100644 index 000000000..9d0b3b3d1 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/user/UserAlreadyExistsException.java @@ -0,0 +1,21 @@ +package com.sprint.mission.discodeit.exception.user; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class UserAlreadyExistsException extends UserException { + public UserAlreadyExistsException() { + super(ErrorCode.DUPLICATE_USER); + } + + public static UserAlreadyExistsException withEmail(String email) { + UserAlreadyExistsException exception = new UserAlreadyExistsException(); + exception.addDetail("email", email); + return exception; + } + + public static UserAlreadyExistsException withUsername(String username) { + UserAlreadyExistsException exception = new UserAlreadyExistsException(); + exception.addDetail("username", username); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/user/UserException.java b/src/main/java/com/sprint/mission/discodeit/exception/user/UserException.java new file mode 100644 index 000000000..f48629706 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/user/UserException.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.exception.user; + +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class UserException extends DiscodeitException { + public UserException(ErrorCode errorCode) { + super(errorCode); + } + + public UserException(ErrorCode errorCode, Throwable cause) { + super(errorCode, cause); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/exception/user/UserNotFoundException.java b/src/main/java/com/sprint/mission/discodeit/exception/user/UserNotFoundException.java new file mode 100644 index 000000000..bd76dfa9e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/user/UserNotFoundException.java @@ -0,0 +1,23 @@ +package com.sprint.mission.discodeit.exception.user; + +import java.util.UUID; + +import com.sprint.mission.discodeit.exception.ErrorCode; + +public class UserNotFoundException extends UserException { + public UserNotFoundException() { + super(ErrorCode.USER_NOT_FOUND); + } + + public static UserNotFoundException withId(UUID userId) { + UserNotFoundException exception = new UserNotFoundException(); + exception.addDetail("userId", userId); + return exception; + } + + public static UserNotFoundException withUsername(String username) { + UserNotFoundException exception = new UserNotFoundException(); + exception.addDetail("username", username); + return exception; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/BinaryContentMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/BinaryContentMapper.java new file mode 100644 index 000000000..d3ea1f137 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/BinaryContentMapper.java @@ -0,0 +1,11 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.entity.BinaryContent; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface BinaryContentMapper { + + BinaryContentDto toDto(BinaryContent binaryContent); +} diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/ChannelMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/ChannelMapper.java new file mode 100644 index 000000000..f39a5809c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/ChannelMapper.java @@ -0,0 +1,48 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.ReadStatus; +import com.sprint.mission.discodeit.repository.MessageRepository; +import com.sprint.mission.discodeit.repository.ReadStatusRepository; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.springframework.beans.factory.annotation.Autowired; + +@Mapper(componentModel = "spring", uses = {UserMapper.class}) +public abstract class ChannelMapper { + + @Autowired + private MessageRepository messageRepository; + @Autowired + private ReadStatusRepository readStatusRepository; + @Autowired + private UserMapper userMapper; + + @Mapping(target = "participants", expression = "java(resolveParticipants(channel))") + @Mapping(target = "lastMessageAt", expression = "java(resolveLastMessageAt(channel))") + abstract public ChannelDto toDto(Channel channel); + + protected Instant resolveLastMessageAt(Channel channel) { + return messageRepository.findLastMessageAtByChannelId( + channel.getId()) + .orElse(Instant.MIN); + } + + protected List resolveParticipants(Channel channel) { + List participants = new ArrayList<>(); + if (channel.getType().equals(ChannelType.PRIVATE)) { + readStatusRepository.findAllByChannelIdWithUser(channel.getId()) + .stream() + .map(ReadStatus::getUser) + .map(userMapper::toDto) + .forEach(participants::add); + } + return participants; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/MessageMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/MessageMapper.java new file mode 100644 index 000000000..e0301ac08 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/MessageMapper.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.entity.Message; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring", uses = {BinaryContentMapper.class, UserMapper.class}) +public interface MessageMapper { + + @Mapping(target = "channelId", source = "channel.id") + MessageDto toDto(Message message); +} diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/NotificationMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/NotificationMapper.java new file mode 100644 index 000000000..66058a3c4 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/NotificationMapper.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.NotificationDto; +import com.sprint.mission.discodeit.entity.Notification; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring") +public interface NotificationMapper { + + @Mapping(target = "receiverId", source = "user.id") + NotificationDto toDto(Notification notification); +} diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/PageResponseMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/PageResponseMapper.java new file mode 100644 index 000000000..108a9b59d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/PageResponseMapper.java @@ -0,0 +1,30 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.response.PageResponse; +import org.mapstruct.Mapper; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Slice; + +@Mapper(componentModel = "spring") +public interface PageResponseMapper { + + default PageResponse fromSlice(Slice slice, Object nextCursor) { + return new PageResponse<>( + slice.getContent(), + nextCursor, + slice.getSize(), + slice.hasNext(), + null + ); + } + + default PageResponse fromPage(Page page, Object nextCursor) { + return new PageResponse<>( + page.getContent(), + nextCursor, + page.getSize(), + page.hasNext(), + page.getTotalElements() + ); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/ReadStatusMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/ReadStatusMapper.java new file mode 100644 index 000000000..af9b85279 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/ReadStatusMapper.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.entity.ReadStatus; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring") +public interface ReadStatusMapper { + + @Mapping(target = "userId", source = "user.id") + @Mapping(target = "channelId", source = "channel.id") + ReadStatusDto toDto(ReadStatus readStatus); +} diff --git a/src/main/java/com/sprint/mission/discodeit/mapper/UserMapper.java b/src/main/java/com/sprint/mission/discodeit/mapper/UserMapper.java new file mode 100644 index 000000000..f42ddc96c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/UserMapper.java @@ -0,0 +1,18 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.security.jwt.JwtRegistry; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.springframework.beans.factory.annotation.Autowired; + +@Mapper(componentModel = "spring", uses = {BinaryContentMapper.class}) +public abstract class UserMapper { + + @Autowired + protected JwtRegistry jwtRegistry; + + @Mapping(target = "online", expression = "java(jwtRegistry.hasActiveJwtInformationByUserId(user.getId()))") + public abstract UserDto toDto(User user); +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java new file mode 100644 index 000000000..cbd8c79cf --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java @@ -0,0 +1,9 @@ +package com.sprint.mission.discodeit.repository; + +import com.sprint.mission.discodeit.entity.BinaryContent; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface BinaryContentRepository extends JpaRepository { + +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java new file mode 100644 index 000000000..e4b1fd235 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java @@ -0,0 +1,12 @@ +package com.sprint.mission.discodeit.repository; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import java.util.List; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ChannelRepository extends JpaRepository { + + List findAllByTypeOrIdIn(ChannelType type, List ids); +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/MessageRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/MessageRepository.java new file mode 100644 index 000000000..6996c05e2 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/repository/MessageRepository.java @@ -0,0 +1,31 @@ +package com.sprint.mission.discodeit.repository; + +import com.sprint.mission.discodeit.entity.Message; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface MessageRepository extends JpaRepository { + + @Query("SELECT m FROM Message m " + + "LEFT JOIN FETCH m.author a " + + "LEFT JOIN FETCH a.profile " + + "WHERE m.channel.id=:channelId AND m.createdAt < :createdAt") + Slice findAllByChannelIdWithAuthor(@Param("channelId") UUID channelId, + @Param("createdAt") Instant createdAt, + Pageable pageable); + + + @Query("SELECT m.createdAt " + + "FROM Message m " + + "WHERE m.channel.id = :channelId " + + "ORDER BY m.createdAt DESC LIMIT 1") + Optional findLastMessageAtByChannelId(@Param("channelId") UUID channelId); + + void deleteAllByChannelId(UUID channelId); +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/NotificationRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/NotificationRepository.java new file mode 100644 index 000000000..47d749c07 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/repository/NotificationRepository.java @@ -0,0 +1,13 @@ +package com.sprint.mission.discodeit.repository; + +import com.sprint.mission.discodeit.entity.Notification; +import java.util.List; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface NotificationRepository extends JpaRepository { + + List findAllByUserId(UUID userId); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java new file mode 100644 index 000000000..3640bcf17 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java @@ -0,0 +1,27 @@ +package com.sprint.mission.discodeit.repository; + +import com.sprint.mission.discodeit.entity.ReadStatus; +import java.util.List; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface ReadStatusRepository extends JpaRepository { + + + List findAllByUserId(UUID userId); + + @Query("SELECT r FROM ReadStatus r " + + "JOIN FETCH r.user u " + + "LEFT JOIN FETCH u.profile " + + "WHERE r.channel.id = :channelId") + List findAllByChannelIdWithUser(@Param("channelId") UUID channelId); + + Boolean existsByUserIdAndChannelId(UUID userId, UUID channelId); + + void deleteAllByChannelId(UUID channelId); + + List findAllByChannel_IdAndNotificationEnabled(UUID channelId, + boolean notificationEnabled); +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java new file mode 100644 index 000000000..392426c9a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java @@ -0,0 +1,26 @@ +package com.sprint.mission.discodeit.repository; + +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.entity.User; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +public interface UserRepository extends JpaRepository { + + Optional findByUsername(String username); + + boolean existsByEmail(String email); + + boolean existsByUsername(String username); + + @Query("SELECT u FROM User u " + + "LEFT JOIN FETCH u.profile") + List findAllWithProfile(); + + List findAllByRole(Role role); + +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/AdminInitializer.java b/src/main/java/com/sprint/mission/discodeit/security/AdminInitializer.java new file mode 100644 index 000000000..25c3c5eec --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/AdminInitializer.java @@ -0,0 +1,46 @@ +package com.sprint.mission.discodeit.security; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.exception.user.UserAlreadyExistsException; +import com.sprint.mission.discodeit.service.AuthService; +import com.sprint.mission.discodeit.service.UserService; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +@Slf4j +@RequiredArgsConstructor +@Component +public class AdminInitializer implements ApplicationRunner { + + @Value("${discodeit.admin.username}") + private String username; + @Value("${discodeit.admin.password}") + private String password; + @Value("${discodeit.admin.email}") + private String email; + private final UserService userService; + private final AuthService authService; + + @Override + public void run(ApplicationArguments args) { + // 관리자 계정 초기화 로직 + UserCreateRequest request = new UserCreateRequest(username, email, password); + try { + UserDto admin = userService.create(request, Optional.empty()); + authService.updateRoleInternal(new RoleUpdateRequest(admin.id(), Role.ADMIN)); + log.info("관리자 계정이 성공적으로 생성되었습니다."); + } catch (UserAlreadyExistsException e) { + log.warn("관리자 계정이 이미 존재합니다"); + } catch (Exception e) { + log.error("관리자 계정 생성 중 오류가 발생했습니다.: {}", e.getMessage()); + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetails.java b/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetails.java new file mode 100644 index 000000000..4b3a9dc82 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetails.java @@ -0,0 +1,35 @@ +package com.sprint.mission.discodeit.security; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import java.util.Collection; +import java.util.List; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +@EqualsAndHashCode(of = "userDto") +@Getter +@RequiredArgsConstructor +public class DiscodeitUserDetails implements UserDetails { + + private final UserDto userDto; + private final String password; + + @Override + public Collection getAuthorities() { + return List.of(new SimpleGrantedAuthority("ROLE_" + userDto.role().name())); + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getUsername() { + return userDto.username(); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetailsService.java b/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetailsService.java new file mode 100644 index 000000000..b48dd2d12 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetailsService.java @@ -0,0 +1,34 @@ +package com.sprint.mission.discodeit.security; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.UserMapper; +import com.sprint.mission.discodeit.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class DiscodeitUserDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + private final UserMapper userMapper; + + @Transactional(readOnly = true) + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userRepository.findByUsername(username) + .orElseThrow(() -> UserNotFoundException.withUsername(username)); + UserDto userDto = userMapper.toDto(user); + + return new DiscodeitUserDetails( + userDto, + user.getPassword() + ); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/Http403ForbiddenAccessDeniedHandler.java b/src/main/java/com/sprint/mission/discodeit/security/Http403ForbiddenAccessDeniedHandler.java new file mode 100644 index 000000000..9f47cc2c6 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/Http403ForbiddenAccessDeniedHandler.java @@ -0,0 +1,29 @@ +package com.sprint.mission.discodeit.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.exception.ErrorResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; + +@RequiredArgsConstructor +public class Http403ForbiddenAccessDeniedHandler implements AccessDeniedHandler { + + private final ObjectMapper objectMapper; + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, + AccessDeniedException accessDeniedException) throws IOException, ServletException { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + + ErrorResponse errorResponse = new ErrorResponse(accessDeniedException, + HttpServletResponse.SC_FORBIDDEN); + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/LoginFailureHandler.java b/src/main/java/com/sprint/mission/discodeit/security/LoginFailureHandler.java new file mode 100644 index 000000000..cf749dff9 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/LoginFailureHandler.java @@ -0,0 +1,34 @@ +package com.sprint.mission.discodeit.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.exception.ErrorResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class LoginFailureHandler implements AuthenticationFailureHandler { + + private final ObjectMapper objectMapper; + + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) throws IOException, ServletException { + log.error("Authentication failed: {}", exception.getMessage(), exception); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + + ErrorResponse errorResponse = new ErrorResponse(exception, HttpServletResponse.SC_UNAUTHORIZED); + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/LoginSuccessHandler.java b/src/main/java/com/sprint/mission/discodeit/security/LoginSuccessHandler.java new file mode 100644 index 000000000..135b31e60 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/LoginSuccessHandler.java @@ -0,0 +1,42 @@ +package com.sprint.mission.discodeit.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.exception.ErrorResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class LoginSuccessHandler implements AuthenticationSuccessHandler { + + private final ObjectMapper objectMapper; + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + response.setCharacterEncoding("UTF-8"); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + + if (authentication.getPrincipal() instanceof DiscodeitUserDetails userDetails) { + response.setStatus(HttpServletResponse.SC_OK); + UserDto userDto = userDetails.getUserDto(); + response.getWriter().write(objectMapper.writeValueAsString(userDto)); + + } else { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + ErrorResponse errorResponse = new ErrorResponse( + new RuntimeException("Authentication failed: Invalid user details"), + HttpServletResponse.SC_UNAUTHORIZED + ); + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/SpaCsrfTokenRequestHandler.java b/src/main/java/com/sprint/mission/discodeit/security/SpaCsrfTokenRequestHandler.java new file mode 100644 index 000000000..6314f37d4 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/SpaCsrfTokenRequestHandler.java @@ -0,0 +1,48 @@ +package com.sprint.mission.discodeit.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.function.Supplier; +import org.springframework.security.web.csrf.CsrfToken; +import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; +import org.springframework.security.web.csrf.CsrfTokenRequestHandler; +import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler; +import org.springframework.util.StringUtils; + +public class SpaCsrfTokenRequestHandler implements CsrfTokenRequestHandler { + + private final CsrfTokenRequestHandler plain = new CsrfTokenRequestAttributeHandler(); + private final CsrfTokenRequestHandler xor = new XorCsrfTokenRequestAttributeHandler(); + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, + Supplier csrfToken) { + /* + * Always use XorCsrfTokenRequestAttributeHandler to provide BREACH protection of + * the CsrfToken when it is rendered in the response body. + */ + this.xor.handle(request, response, csrfToken); + /* + * Render the token value to a cookie by causing the deferred token to be loaded. + */ + csrfToken.get(); + } + + @Override + public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) { + String headerValue = request.getHeader(csrfToken.getHeaderName()); + /* + * If the request contains a request header, use CsrfTokenRequestAttributeHandler + * to resolve the CsrfToken. This applies when a single-page application includes + * the header value automatically, which was obtained via a cookie containing the + * raw CsrfToken. + * + * In all other cases (e.g. if the request contains a request parameter), use + * XorCsrfTokenRequestAttributeHandler to resolve the CsrfToken. This applies + * when a server-side rendered form includes the _csrf request parameter as a + * hidden input. + */ + return (StringUtils.hasText(headerValue) ? this.plain : this.xor).resolveCsrfTokenValue(request, + csrfToken); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/InMemoryJwtRegistry.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/InMemoryJwtRegistry.java new file mode 100644 index 000000000..52caf8265 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/InMemoryJwtRegistry.java @@ -0,0 +1,129 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.sprint.mission.discodeit.dto.data.JwtInformation; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; + + +@RequiredArgsConstructor +public class InMemoryJwtRegistry implements JwtRegistry { + + // > + private final Map> origin = new ConcurrentHashMap<>(); + private final Set accessTokenIndexes = ConcurrentHashMap.newKeySet(); + private final Set refreshTokenIndexes = ConcurrentHashMap.newKeySet(); + + private final int maxActiveJwtCount; + private final JwtTokenProvider jwtTokenProvider; + + @Override + public void registerJwtInformation(JwtInformation jwtInformation) { + origin.compute(jwtInformation.getUserDto().id(), (key, queue) -> { + if (queue == null) { + queue = new ConcurrentLinkedQueue<>(); + } + // If the queue exceeds the max size, remove the oldest token + if (queue.size() >= maxActiveJwtCount) { + JwtInformation deprecatedJwtInformation = queue.poll();// Remove the oldest token + if (deprecatedJwtInformation != null) { + removeTokenIndex( + deprecatedJwtInformation.getAccessToken(), + deprecatedJwtInformation.getRefreshToken() + ); + } + } + queue.add(jwtInformation); // Add the new token + addTokenIndex( + jwtInformation.getAccessToken(), + jwtInformation.getRefreshToken() + ); + return queue; + }); + } + + @Override + public void invalidateJwtInformationByUserId(UUID userId) { + origin.computeIfPresent(userId, (key, queue) -> { + queue.forEach(jwtInformation -> { + removeTokenIndex( + jwtInformation.getAccessToken(), + jwtInformation.getRefreshToken() + ); + }); + queue.clear(); // Clear the queue for this user + return null; // Remove the user from the registry + }); + } + + @Override + public boolean hasActiveJwtInformationByUserId(UUID userId) { + return origin.containsKey(userId); + } + + @Override + public boolean hasActiveJwtInformationByAccessToken(String accessToken) { + return accessTokenIndexes.contains(accessToken); + } + + @Override + public boolean hasActiveJwtInformationByRefreshToken(String refreshToken) { + return refreshTokenIndexes.contains(refreshToken); + } + + @Override + public void rotateJwtInformation(String refreshToken, JwtInformation newJwtInformation) { + origin.computeIfPresent(newJwtInformation.getUserDto().id(), (key, queue) -> { + queue.stream().filter(jwtInformation -> jwtInformation.getRefreshToken().equals(refreshToken)) + .findFirst() + .ifPresent(jwtInformation -> { + removeTokenIndex(jwtInformation.getAccessToken(), jwtInformation.getRefreshToken()); + jwtInformation.rotate( + newJwtInformation.getAccessToken(), + newJwtInformation.getRefreshToken() + ); + addTokenIndex( + newJwtInformation.getAccessToken(), + newJwtInformation.getRefreshToken() + ); + }); + return queue; + }); + } + + @Scheduled(fixedDelay = 1000 * 60 * 5) + @Override + public void clearExpiredJwtInformation() { + origin.entrySet().removeIf(entry -> { + Queue queue = entry.getValue(); + queue.removeIf(jwtInformation -> { + boolean isExpired = + !jwtTokenProvider.validateAccessToken(jwtInformation.getAccessToken()) || + !jwtTokenProvider.validateRefreshToken(jwtInformation.getRefreshToken()); + if (isExpired) { + removeTokenIndex( + jwtInformation.getAccessToken(), + jwtInformation.getRefreshToken() + ); + } + return isExpired; + }); + return queue.isEmpty(); // Remove the entry if the queue is empty + }); + } + + private void addTokenIndex(String accessToken, String refreshToken) { + accessTokenIndexes.add(accessToken); + refreshTokenIndexes.add(refreshToken); + } + + private void removeTokenIndex(String accessToken, String refreshToken) { + accessTokenIndexes.remove(accessToken); + refreshTokenIndexes.remove(refreshToken); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilter.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilter.java new file mode 100644 index 000000000..fb58b0fe6 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilter.java @@ -0,0 +1,94 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.exception.ErrorResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtTokenProvider tokenProvider; + private final UserDetailsService userDetailsService; + private final ObjectMapper objectMapper; + private final JwtRegistry jwtRegistry; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + + try { + String token = resolveToken(request); + + if (StringUtils.hasText(token)) { + if (tokenProvider.validateAccessToken(token) && jwtRegistry.hasActiveJwtInformationByAccessToken( + token)) { + String username = tokenProvider.getUsernameFromToken(token); + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities() + ); + + authentication.setDetails( + new WebAuthenticationDetailsSource().buildDetails(request) + ); + + SecurityContextHolder.getContext().setAuthentication(authentication); + log.debug("Set authentication for user: {}", username); + } else { + log.debug("Invalid JWT token"); + sendErrorResponse(response, "Invalid JWT token", HttpServletResponse.SC_UNAUTHORIZED); + return; + } + } + } catch (Exception e) { + log.debug("JWT authentication failed: {}", e.getMessage()); + SecurityContextHolder.clearContext(); + sendErrorResponse(response, "JWT authentication failed", HttpServletResponse.SC_UNAUTHORIZED); + return; + } + + filterChain.doFilter(request, response); + } + + private String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } + + private void sendErrorResponse(HttpServletResponse response, String message, int status) + throws IOException { + ErrorResponse errorResponse = new ErrorResponse(new RuntimeException(message), status); + + response.setStatus(status); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + + String jsonResponse = objectMapper.writeValueAsString(errorResponse); + response.getWriter().write(jsonResponse); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandler.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandler.java new file mode 100644 index 000000000..d7ce4dca2 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandler.java @@ -0,0 +1,84 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nimbusds.jose.JOSEException; +import com.sprint.mission.discodeit.dto.data.JwtDto; +import com.sprint.mission.discodeit.dto.data.JwtInformation; +import com.sprint.mission.discodeit.exception.ErrorResponse; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtLoginSuccessHandler implements AuthenticationSuccessHandler { + + private final ObjectMapper objectMapper; + private final JwtTokenProvider tokenProvider; + private final JwtRegistry jwtRegistry; + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, + HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + + response.setCharacterEncoding("UTF-8"); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + + if (authentication.getPrincipal() instanceof DiscodeitUserDetails userDetails) { + try { + String accessToken = tokenProvider.generateAccessToken(userDetails); + String refreshToken = tokenProvider.generateRefreshToken(userDetails); + + // Set refresh token in HttpOnly cookie + Cookie refreshCookie = tokenProvider.genereateRefreshTokenCookie(refreshToken); + response.addCookie(refreshCookie); + + JwtDto jwtDto = new JwtDto( + userDetails.getUserDto(), + accessToken + ); + + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().write(objectMapper.writeValueAsString(jwtDto)); + + jwtRegistry.registerJwtInformation( + new JwtInformation( + userDetails.getUserDto(), + accessToken, + refreshToken + ) + ); + + log.info("JWT access and refresh tokens issued for user: {}", userDetails.getUsername()); + + } catch (JOSEException e) { + log.error("Failed to generate JWT token for user: {}", userDetails.getUsername(), e); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + ErrorResponse errorResponse = new ErrorResponse( + new RuntimeException("Token generation failed"), + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ); + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); + } + } else { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + ErrorResponse errorResponse = new ErrorResponse( + new RuntimeException("Authentication failed: Invalid user details"), + HttpServletResponse.SC_UNAUTHORIZED + ); + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLogoutHandler.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLogoutHandler.java new file mode 100644 index 000000000..aa053de62 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLogoutHandler.java @@ -0,0 +1,41 @@ +package com.sprint.mission.discodeit.security.jwt; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.Arrays; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtLogoutHandler implements LogoutHandler { + + private final JwtTokenProvider tokenProvider; + private final JwtRegistry jwtRegistry; + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) { + + // Clear refresh token cookie + Cookie refreshTokenExpirationCookie = tokenProvider.genereateRefreshTokenExpirationCookie(); + response.addCookie(refreshTokenExpirationCookie); + + Arrays.stream(request.getCookies()) + .filter(cookie -> cookie.getName().equals(JwtTokenProvider.REFRESH_TOKEN_COOKIE_NAME)) + .findFirst() + .ifPresent(cookie -> { + String refreshToken = cookie.getValue(); + UUID userId = tokenProvider.getUserId(refreshToken); + jwtRegistry.invalidateJwtInformationByUserId(userId); + }); + + log.debug("JWT logout handler executed - refresh token cookie cleared"); + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtRegistry.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtRegistry.java new file mode 100644 index 000000000..b153c41cc --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtRegistry.java @@ -0,0 +1,21 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.sprint.mission.discodeit.dto.data.JwtInformation; +import java.util.UUID; + +public interface JwtRegistry { + + void registerJwtInformation(JwtInformation jwtInformation); + + void invalidateJwtInformationByUserId(UUID userId); + + boolean hasActiveJwtInformationByUserId(UUID userId); + + boolean hasActiveJwtInformationByAccessToken(String accessToken); + + boolean hasActiveJwtInformationByRefreshToken(String refreshToken); + + void rotateJwtInformation(String refreshToken, JwtInformation newJwtInformation); + + void clearExpiredJwtInformation(); +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProvider.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProvider.java new file mode 100644 index 000000000..debfafdda --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProvider.java @@ -0,0 +1,185 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSSigner; +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.crypto.MACVerifier; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import jakarta.servlet.http.Cookie; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.UUID; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class JwtTokenProvider { + + public static final String REFRESH_TOKEN_COOKIE_NAME = "REFRESH_TOKEN"; + + private final int accessTokenExpirationMs; + private final int refreshTokenExpirationMs; + + private final JWSSigner accessTokenSigner; + private final JWSVerifier accessTokenVerifier; + private final JWSSigner refreshTokenSigner; + private final JWSVerifier refreshTokenVerifier; + + public JwtTokenProvider( + @Value("${discodeit.jwt.access-token.secret}") String accessTokenSecret, + @Value("${discodeit.jwt.access-token.expiration-ms}") int accessTokenExpirationMs, + @Value("${discodeit.jwt.refresh-token.secret}") String refreshTokenSecret, + @Value("${discodeit.jwt.refresh-token.expiration-ms}") int refreshTokenExpirationMs) + throws JOSEException { + + this.accessTokenExpirationMs = accessTokenExpirationMs; + this.refreshTokenExpirationMs = refreshTokenExpirationMs; + + byte[] accessSecretBytes = accessTokenSecret.getBytes(StandardCharsets.UTF_8); + this.accessTokenSigner = new MACSigner(accessSecretBytes); + this.accessTokenVerifier = new MACVerifier(accessSecretBytes); + + byte[] refreshSecretBytes = refreshTokenSecret.getBytes(StandardCharsets.UTF_8); + this.refreshTokenSigner = new MACSigner(refreshSecretBytes); + this.refreshTokenVerifier = new MACVerifier(refreshSecretBytes); + } + + public String generateAccessToken(DiscodeitUserDetails userDetails) throws JOSEException { + return generateToken(userDetails, accessTokenExpirationMs, accessTokenSigner, "access"); + } + + public String generateRefreshToken(DiscodeitUserDetails userDetails) throws JOSEException { + return generateToken(userDetails, refreshTokenExpirationMs, refreshTokenSigner, "refresh"); + } + + private String generateToken(DiscodeitUserDetails userDetails, int expirationMs, JWSSigner signer, + String tokenType) throws JOSEException { + String tokenId = UUID.randomUUID().toString(); + UserDto user = userDetails.getUserDto(); + + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + expirationMs); + + JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() + .subject(user.username()) + .jwtID(tokenId) + .claim("userId", user.id().toString()) + .claim("type", tokenType) + .claim("roles", userDetails.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.toList())) + .issueTime(now) + .expirationTime(expiryDate) + .build(); + + SignedJWT signedJWT = new SignedJWT( + new JWSHeader(JWSAlgorithm.HS256), + claimsSet + ); + + signedJWT.sign(signer); + String token = signedJWT.serialize(); + + log.debug("Generated {} token for user: {}", tokenType, user.username()); + return token; + } + + public boolean validateAccessToken(String token) { + return validateToken(token, accessTokenVerifier, "access"); + } + + public boolean validateRefreshToken(String token) { + return validateToken(token, refreshTokenVerifier, "refresh"); + } + + private boolean validateToken(String token, JWSVerifier verifier, String expectedType) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + + // Verify signature + if (!signedJWT.verify(verifier)) { + log.debug("JWT signature verification failed for {} token", expectedType); + return false; + } + + // Check token type + String tokenType = (String) signedJWT.getJWTClaimsSet().getClaim("type"); + if (!expectedType.equals(tokenType)) { + log.debug("JWT token type mismatch: expected {}, got {}", expectedType, tokenType); + return false; + } + + // Check expiration + Date expirationTime = signedJWT.getJWTClaimsSet().getExpirationTime(); + if (expirationTime == null || expirationTime.before(new Date())) { + log.debug("JWT {} token expired", expectedType); + return false; + } + + return true; + } catch (Exception e) { + log.debug("JWT {} token validation failed: {}", expectedType, e.getMessage()); + return false; + } + } + + public String getUsernameFromToken(String token) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + return signedJWT.getJWTClaimsSet().getSubject(); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid JWT token", e); + } + } + + public String getTokenId(String token) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + return signedJWT.getJWTClaimsSet().getJWTID(); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid JWT token", e); + } + } + + public UUID getUserId(String token) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + String userIdStr = (String) signedJWT.getJWTClaimsSet().getClaim("userId"); + if (userIdStr == null) { + throw new IllegalArgumentException("User ID claim not found in JWT token"); + } + return UUID.fromString(userIdStr); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid JWT token", e); + } + } + + public Cookie genereateRefreshTokenCookie(String refreshToken) { + // Set refresh token in HttpOnly cookie + Cookie refreshCookie = new Cookie(REFRESH_TOKEN_COOKIE_NAME, refreshToken); + refreshCookie.setHttpOnly(true); + refreshCookie.setSecure(true); // Use HTTPS in production + refreshCookie.setPath("/"); + refreshCookie.setMaxAge(refreshTokenExpirationMs / 1000); + return refreshCookie; + } + + public Cookie genereateRefreshTokenExpirationCookie() { + Cookie refreshCookie = new Cookie(REFRESH_TOKEN_COOKIE_NAME, ""); + refreshCookie.setHttpOnly(true); + refreshCookie.setSecure(true); // Use HTTPS in production + refreshCookie.setPath("/"); + refreshCookie.setMaxAge(0); + return refreshCookie; + } +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/service/AuthService.java b/src/main/java/com/sprint/mission/discodeit/service/AuthService.java new file mode 100644 index 000000000..dd3f6cda3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/AuthService.java @@ -0,0 +1,14 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.JwtInformation; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; + +public interface AuthService { + + UserDto updateRole(RoleUpdateRequest request); + + UserDto updateRoleInternal(RoleUpdateRequest request); + + JwtInformation refreshToken(String refreshToken); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java b/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java new file mode 100644 index 000000000..1853e5af3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java @@ -0,0 +1,20 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.entity.BinaryContentStatus; +import java.util.List; +import java.util.UUID; + +public interface BinaryContentService { + + BinaryContentDto create(BinaryContentCreateRequest request); + + BinaryContentDto find(UUID binaryContentId); + + List findAllByIdIn(List binaryContentIds); + + void delete(UUID binaryContentId); + + BinaryContentDto updateStatus(UUID binaryContentId, BinaryContentStatus status); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java b/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java new file mode 100644 index 000000000..a082c9ff9 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java @@ -0,0 +1,23 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import java.util.List; +import java.util.UUID; + +public interface ChannelService { + + ChannelDto create(PublicChannelCreateRequest request); + + ChannelDto create(PrivateChannelCreateRequest request); + + ChannelDto find(UUID channelId); + + List findAllByUserId(UUID userId); + + ChannelDto update(UUID channelId, PublicChannelUpdateRequest request); + + void delete(UUID channelId); +} \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/service/MessageService.java b/src/main/java/com/sprint/mission/discodeit/service/MessageService.java new file mode 100644 index 000000000..8ac5ee924 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/MessageService.java @@ -0,0 +1,25 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.response.PageResponse; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import org.springframework.data.domain.Pageable; + +public interface MessageService { + + MessageDto create(MessageCreateRequest messageCreateRequest, + List binaryContentCreateRequests); + + MessageDto find(UUID messageId); + + PageResponse findAllByChannelId(UUID channelId, Instant createdAt, Pageable pageable); + + MessageDto update(UUID messageId, MessageUpdateRequest request); + + void delete(UUID messageId); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/NotificationService.java b/src/main/java/com/sprint/mission/discodeit/service/NotificationService.java new file mode 100644 index 000000000..7cf3d5b5d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/NotificationService.java @@ -0,0 +1,12 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.NotificationDto; +import java.util.List; +import java.util.UUID; + +public interface NotificationService { + + List getNotifications(); + + void checkNotifications(UUID notificationId); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java b/src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java new file mode 100644 index 000000000..8b0c80a31 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java @@ -0,0 +1,20 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.dto.request.ReadStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusUpdateRequest; +import java.util.List; +import java.util.UUID; + +public interface ReadStatusService { + + ReadStatusDto create(ReadStatusCreateRequest request); + + ReadStatusDto find(UUID readStatusId); + + List findAllByUserId(UUID userId); + + ReadStatusDto update(UUID readStatusId, ReadStatusUpdateRequest request); + + void delete(UUID readStatusId); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/UserService.java b/src/main/java/com/sprint/mission/discodeit/service/UserService.java new file mode 100644 index 000000000..444118780 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/UserService.java @@ -0,0 +1,24 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface UserService { + + UserDto create(UserCreateRequest userCreateRequest, + Optional profileCreateRequest); + + UserDto find(UUID userId); + + List findAll(); + + UserDto update(UUID userId, UserUpdateRequest userUpdateRequest, + Optional profileCreateRequest); + + void delete(UUID userId); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicAuthService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicAuthService.java new file mode 100644 index 000000000..969ca347b --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicAuthService.java @@ -0,0 +1,106 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.nimbusds.jose.JOSEException; +import com.sprint.mission.discodeit.dto.data.JwtInformation; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.event.RoleUpdatedEvent; +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.UserMapper; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.security.jwt.JwtRegistry; +import com.sprint.mission.discodeit.security.jwt.JwtTokenProvider; +import com.sprint.mission.discodeit.service.AuthService; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@RequiredArgsConstructor +@Service +public class BasicAuthService implements AuthService { + + private final UserRepository userRepository; + private final UserMapper userMapper; + private final JwtRegistry jwtRegistry; + private final JwtTokenProvider tokenProvider; + private final UserDetailsService userDetailsService; + private final ApplicationEventPublisher eventPublisher; + + @PreAuthorize("hasRole('ADMIN')") + @Transactional + @Override + @CacheEvict(value = "users", allEntries = true) + public UserDto updateRole(RoleUpdateRequest request) { + return updateRoleInternal(request); + } + + @Transactional + @Override + public UserDto updateRoleInternal(RoleUpdateRequest request) { + UUID userId = request.userId(); + User user = userRepository.findById(userId) + .orElseThrow(() -> UserNotFoundException.withId(userId)); + + Role oldRole = user.getRole(); + Role newRole = request.newRole(); + user.updateRole(newRole); + + jwtRegistry.invalidateJwtInformationByUserId(userId); + + eventPublisher.publishEvent(new RoleUpdatedEvent(user,oldRole,newRole)); + + return userMapper.toDto(user); + } + + @Override + public JwtInformation refreshToken(String refreshToken) { + // Validate refresh token + if (!tokenProvider.validateRefreshToken(refreshToken) + || !jwtRegistry.hasActiveJwtInformationByRefreshToken(refreshToken)) { + log.error("Invalid or expired refresh token: {}", refreshToken); + throw new DiscodeitException(ErrorCode.INVALID_TOKEN); + } + + String username = tokenProvider.getUsernameFromToken(refreshToken); + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + if (!(userDetails instanceof DiscodeitUserDetails discodeitUserDetails)) { + throw new DiscodeitException(ErrorCode.INVALID_USER_DETAILS); + } + + try { + String newAccessToken = tokenProvider.generateAccessToken(discodeitUserDetails); + String newRefreshToken = tokenProvider.generateRefreshToken(discodeitUserDetails); + log.info("Access token refreshed for user: {}", username); + + JwtInformation newJwtInformation = new JwtInformation( + discodeitUserDetails.getUserDto(), + newAccessToken, + newRefreshToken + ); + jwtRegistry.rotateJwtInformation( + refreshToken, + newJwtInformation + ); + + return newJwtInformation; + + } catch (JOSEException e) { + log.error("Failed to generate new tokens for user: {}", username, e); + throw new DiscodeitException(ErrorCode.INTERNAL_SERVER_ERROR, e); + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentService.java new file mode 100644 index 000000000..88b601446 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentService.java @@ -0,0 +1,97 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.BinaryContentStatus; +import com.sprint.mission.discodeit.event.BinaryContentCreatedEvent; +import com.sprint.mission.discodeit.exception.binarycontent.BinaryContentNotFoundException; +import com.sprint.mission.discodeit.mapper.BinaryContentMapper; +import com.sprint.mission.discodeit.repository.BinaryContentRepository; +import com.sprint.mission.discodeit.service.BinaryContentService; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@RequiredArgsConstructor +@Service +public class BasicBinaryContentService implements BinaryContentService { + + private final BinaryContentRepository binaryContentRepository; + private final BinaryContentMapper binaryContentMapper; + private final BinaryContentStorage binaryContentStorage; + private final ApplicationEventPublisher eventPublisher; + + @Transactional + @Override + public BinaryContentDto create(BinaryContentCreateRequest request) { + log.debug("바이너리 컨텐츠 생성 시작: fileName={}, size={}, contentType={}", + request.fileName(), request.bytes().length, request.contentType()); + + String fileName = request.fileName(); + byte[] bytes = request.bytes(); + String contentType = request.contentType(); + BinaryContent binaryContent = new BinaryContent( + fileName, + (long) bytes.length, + contentType + ); + binaryContentRepository.save(binaryContent); + eventPublisher.publishEvent(new BinaryContentCreatedEvent(binaryContent,bytes)); + + log.info("바이너리 컨텐츠 생성 완료: id={}, fileName={}, size={}", + binaryContent.getId(), fileName, bytes.length); + return binaryContentMapper.toDto(binaryContent); + } + + @Override + public BinaryContentDto find(UUID binaryContentId) { + log.debug("바이너리 컨텐츠 조회 시작: id={}", binaryContentId); + BinaryContentDto dto = binaryContentRepository.findById(binaryContentId) + .map(binaryContentMapper::toDto) + .orElseThrow(() -> BinaryContentNotFoundException.withId(binaryContentId)); + log.info("바이너리 컨텐츠 조회 완료: id={}, fileName={}", + dto.id(), dto.fileName()); + return dto; + } + + @Override + public List findAllByIdIn(List binaryContentIds) { + log.debug("바이너리 컨텐츠 목록 조회 시작: ids={}", binaryContentIds); + List dtos = binaryContentRepository.findAllById(binaryContentIds).stream() + .map(binaryContentMapper::toDto) + .toList(); + log.info("바이너리 컨텐츠 목록 조회 완료: 조회된 항목 수={}", dtos.size()); + return dtos; + } + + @Transactional + @Override + public void delete(UUID binaryContentId) { + log.debug("바이너리 컨텐츠 삭제 시작: id={}", binaryContentId); + if (!binaryContentRepository.existsById(binaryContentId)) { + throw BinaryContentNotFoundException.withId(binaryContentId); + } + binaryContentRepository.deleteById(binaryContentId); + log.info("바이너리 컨텐츠 삭제 완료: id={}", binaryContentId); + } + + @Override + @Transactional + public BinaryContentDto updateStatus(UUID binaryContentId, BinaryContentStatus status) { + BinaryContent binarycontent = binaryContentRepository.findById(binaryContentId) + .orElseThrow(() -> BinaryContentNotFoundException.withId(binaryContentId)); + + binarycontent.updateStatus(status); + + BinaryContent updatedBinaryContent = binaryContentRepository.save(binarycontent); + + return binaryContentMapper.toDto(updatedBinaryContent); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicChannelService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicChannelService.java new file mode 100644 index 000000000..0d8b91283 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicChannelService.java @@ -0,0 +1,129 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.ReadStatus; +import com.sprint.mission.discodeit.exception.channel.ChannelNotFoundException; +import com.sprint.mission.discodeit.exception.channel.PrivateChannelUpdateException; +import com.sprint.mission.discodeit.mapper.ChannelMapper; +import com.sprint.mission.discodeit.repository.ChannelRepository; +import com.sprint.mission.discodeit.repository.MessageRepository; +import com.sprint.mission.discodeit.repository.ReadStatusRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.service.ChannelService; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@RequiredArgsConstructor +public class BasicChannelService implements ChannelService { + + private final ChannelRepository channelRepository; + // + private final ReadStatusRepository readStatusRepository; + private final MessageRepository messageRepository; + private final UserRepository userRepository; + private final ChannelMapper channelMapper; + + @PreAuthorize("hasRole('CHANNEL_MANAGER')") + @CacheEvict(value = "channelsByUser", key = "#userId") + @Transactional + @Override + public ChannelDto create(PublicChannelCreateRequest request) { + log.debug("채널 생성 시작: {}", request); + String name = request.name(); + String description = request.description(); + Channel channel = new Channel(ChannelType.PUBLIC, name, description); + + channelRepository.save(channel); + log.info("채널 생성 완료: id={}, name={}", channel.getId(), channel.getName()); + return channelMapper.toDto(channel); + } + + @CacheEvict(value = "channelsByUser", key = "#userId") + @Transactional + @Override + public ChannelDto create(PrivateChannelCreateRequest request) { + log.debug("채널 생성 시작: {}", request); + Channel channel = new Channel(ChannelType.PRIVATE, null, null); + channelRepository.save(channel); + + List readStatuses = userRepository.findAllById(request.participantIds()).stream() + .map(user -> new ReadStatus(user, channel, channel.getCreatedAt(),channel.getType() == ChannelType.PRIVATE)) + .toList(); + readStatusRepository.saveAll(readStatuses); + + log.info("채널 생성 완료: id={}, name={}", channel.getId(), channel.getName()); + return channelMapper.toDto(channel); + } + + @Transactional(readOnly = true) + @Override + public ChannelDto find(UUID channelId) { + return channelRepository.findById(channelId) + .map(channelMapper::toDto) + .orElseThrow(() -> ChannelNotFoundException.withId(channelId)); + } + + @Transactional(readOnly = true) + @Cacheable(value = "channelsByUser", key = "#userId") + @Override + public List findAllByUserId(UUID userId) { + List mySubscribedChannelIds = readStatusRepository.findAllByUserId(userId).stream() + .map(ReadStatus::getChannel) + .map(Channel::getId) + .toList(); + + return channelRepository.findAllByTypeOrIdIn(ChannelType.PUBLIC, mySubscribedChannelIds) + .stream() + .map(channelMapper::toDto) + .toList(); + } + + @PreAuthorize("hasRole('CHANNEL_MANAGER')") + @CacheEvict(value = "channelsByUser", key = "#userId") + @Transactional + @Override + public ChannelDto update(UUID channelId, PublicChannelUpdateRequest request) { + log.debug("채널 수정 시작: id={}, request={}", channelId, request); + String newName = request.newName(); + String newDescription = request.newDescription(); + Channel channel = channelRepository.findById(channelId) + .orElseThrow(() -> ChannelNotFoundException.withId(channelId)); + if (channel.getType().equals(ChannelType.PRIVATE)) { + throw PrivateChannelUpdateException.forChannel(channelId); + } + channel.update(newName, newDescription); + log.info("채널 수정 완료: id={}, name={}", channelId, channel.getName()); + return channelMapper.toDto(channel); + } + + @PreAuthorize("hasRole('CHANNEL_MANAGER')") + @CacheEvict(value = "channelsByUser", key = "#userId") + @Transactional + @Override + public void delete(UUID channelId) { + log.debug("채널 삭제 시작: id={}", channelId); + if (!channelRepository.existsById(channelId)) { + throw ChannelNotFoundException.withId(channelId); + } + + messageRepository.deleteAllByChannelId(channelId); + readStatusRepository.deleteAllByChannelId(channelId); + + channelRepository.deleteById(channelId); + log.info("채널 삭제 완료: id={}", channelId); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicMessageService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicMessageService.java new file mode 100644 index 000000000..f45b2870f --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicMessageService.java @@ -0,0 +1,144 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.response.PageResponse; +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.event.BinaryContentCreatedEvent; +import com.sprint.mission.discodeit.event.MessageCreatedEvent; +import com.sprint.mission.discodeit.exception.channel.ChannelNotFoundException; +import com.sprint.mission.discodeit.exception.message.MessageNotFoundException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.MessageMapper; +import com.sprint.mission.discodeit.mapper.PageResponseMapper; +import com.sprint.mission.discodeit.repository.BinaryContentRepository; +import com.sprint.mission.discodeit.repository.ChannelRepository; +import com.sprint.mission.discodeit.repository.MessageRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.service.MessageService; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@RequiredArgsConstructor +public class BasicMessageService implements MessageService { + + private final MessageRepository messageRepository; + private final ChannelRepository channelRepository; + private final UserRepository userRepository; + private final MessageMapper messageMapper; + private final BinaryContentStorage binaryContentStorage; + private final BinaryContentRepository binaryContentRepository; + private final PageResponseMapper pageResponseMapper; + private final ApplicationEventPublisher eventPublisher; + + @Transactional + @Override + public MessageDto create(MessageCreateRequest messageCreateRequest, + List binaryContentCreateRequests) { + log.debug("메시지 생성 시작: request={}", messageCreateRequest); + UUID channelId = messageCreateRequest.channelId(); + UUID authorId = messageCreateRequest.authorId(); + + Channel channel = channelRepository.findById(channelId) + .orElseThrow(() -> ChannelNotFoundException.withId(channelId)); + User author = userRepository.findById(authorId) + .orElseThrow(() -> UserNotFoundException.withId(authorId)); + + List attachments = binaryContentCreateRequests.stream() + .map(attachmentRequest -> { + String fileName = attachmentRequest.fileName(); + String contentType = attachmentRequest.contentType(); + byte[] bytes = attachmentRequest.bytes(); + + BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, + contentType); + binaryContentRepository.save(binaryContent); + eventPublisher.publishEvent(new BinaryContentCreatedEvent(binaryContent,bytes)); + return binaryContent; + }) + .toList(); + + String content = messageCreateRequest.content(); + Message message = new Message( + content, + channel, + author, + attachments + ); + + messageRepository.save(message); + + eventPublisher.publishEvent(new MessageCreatedEvent(author, channel, message.getContent())); + log.info("메시지 생성 완료: id={}, channelId={}", message.getId(), channelId); + return messageMapper.toDto(message); + } + + @Transactional(readOnly = true) + @Override + public MessageDto find(UUID messageId) { + return messageRepository.findById(messageId) + .map(messageMapper::toDto) + .orElseThrow(() -> MessageNotFoundException.withId(messageId)); + } + + @Transactional(readOnly = true) + @Override + public PageResponse findAllByChannelId(UUID channelId, Instant createAt, + Pageable pageable) { + Slice slice = messageRepository.findAllByChannelIdWithAuthor(channelId, + Optional.ofNullable(createAt).orElse(Instant.now()), + pageable) + .map(messageMapper::toDto); + + Instant nextCursor = null; + if (!slice.getContent().isEmpty()) { + nextCursor = slice.getContent().get(slice.getContent().size() - 1) + .createdAt(); + } + + return pageResponseMapper.fromSlice(slice, nextCursor); + } + + @PreAuthorize("principal.userDto.id == @basicMessageService.find(#messageId).author.id") + @Transactional + @Override + public MessageDto update(UUID messageId, MessageUpdateRequest request) { + log.debug("메시지 수정 시작: id={}, request={}", messageId, request); + Message message = messageRepository.findById(messageId) + .orElseThrow(() -> MessageNotFoundException.withId(messageId)); + + message.update(request.newContent()); + log.info("메시지 수정 완료: id={}, channelId={}", messageId, message.getChannel().getId()); + return messageMapper.toDto(message); + } + + @PreAuthorize("principal.userDto.id == @basicMessageService.find(#messageId).author.id") + @Transactional + @Override + public void delete(UUID messageId) { + log.debug("메시지 삭제 시작: id={}", messageId); + if (!messageRepository.existsById(messageId)) { + throw MessageNotFoundException.withId(messageId); + } + messageRepository.deleteById(messageId); + log.info("메시지 삭제 완료: id={}", messageId); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicNotificationService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicNotificationService.java new file mode 100644 index 000000000..7287a979a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicNotificationService.java @@ -0,0 +1,73 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.sprint.mission.discodeit.dto.data.NotificationDto; +import com.sprint.mission.discodeit.entity.Notification; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.notification.NotFoundNotificationException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.NotificationMapper; +import com.sprint.mission.discodeit.repository.NotificationRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.service.NotificationService; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +@RequiredArgsConstructor +public class BasicNotificationService implements NotificationService { + + private final UserRepository userRepository; + private final NotificationRepository notificationRepository; + private final NotificationMapper notificationMapper; + + @Override + @Cacheable(value = "notificationsByUser", keyGenerator = "userIdKeyGenerator") + public List getNotifications() { + User user = getUser(); + + log.info("[BasicNotificationService] 사용자: {}의 알림 조회", user.getUsername()); + + List result = notificationRepository.findAllByUserId(user.getId()).stream() + .map(notificationMapper::toDto) + .toList(); + + log.info("[BasicNotificationService] 알림 조회 완료- 총 {}개 ", result.size()); + + return result; + } + + @Override + @Cacheable(value = "notificationsByUser", keyGenerator = "userIdKeyGenerator") + public void checkNotifications(UUID notificationId) { + User user = getUser(); + + Notification notification = notificationRepository.findById(notificationId) + .orElseThrow(() -> NotFoundNotificationException.withId(notificationId)); + + UUID userId = user.getId(); + if (!notification.getUser().getId().equals(userId)) { + throw new AccessDeniedException("본인의 알림만 확인 가능합니다."); + } + + notificationRepository.deleteById(notificationId); + + log.info("[BasicNotificationService] 알림 읽음 처리 완료- notificationId: {}", notificationId); + } + + private User getUser() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + String name = authentication.getName(); + + return userRepository.findByUsername(name) + .orElseThrow(() -> UserNotFoundException.withUsername(name)); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicReadStatusService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicReadStatusService.java new file mode 100644 index 000000000..c1787bf32 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicReadStatusService.java @@ -0,0 +1,108 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.dto.request.ReadStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusUpdateRequest; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.ReadStatus; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.channel.ChannelNotFoundException; +import com.sprint.mission.discodeit.exception.readstatus.DuplicateReadStatusException; +import com.sprint.mission.discodeit.exception.readstatus.ReadStatusNotFoundException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.ReadStatusMapper; +import com.sprint.mission.discodeit.repository.ChannelRepository; +import com.sprint.mission.discodeit.repository.ReadStatusRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.service.ReadStatusService; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +@Service +public class BasicReadStatusService implements ReadStatusService { + + private final ReadStatusRepository readStatusRepository; + private final UserRepository userRepository; + private final ChannelRepository channelRepository; + private final ReadStatusMapper readStatusMapper; + + @Transactional + @Override + public ReadStatusDto create(ReadStatusCreateRequest request) { + log.debug("읽음 상태 생성 시작: userId={}, channelId={}", request.userId(), request.channelId()); + + UUID userId = request.userId(); + UUID channelId = request.channelId(); + + User user = userRepository.findById(userId) + .orElseThrow(() -> UserNotFoundException.withId(userId)); + Channel channel = channelRepository.findById(channelId) + .orElseThrow(() -> ChannelNotFoundException.withId(channelId)); + + if (readStatusRepository.existsByUserIdAndChannelId(user.getId(), channel.getId())) { + throw DuplicateReadStatusException.withUserIdAndChannelId(userId, channelId); + } + + Instant lastReadAt = request.lastReadAt(); + ReadStatus readStatus = new ReadStatus(user, channel, lastReadAt, channel.getType() == ChannelType.PRIVATE); + readStatusRepository.save(readStatus); + + log.info("읽음 상태 생성 완료: id={}, userId={}, channelId={}", + readStatus.getId(), userId, channelId); + return readStatusMapper.toDto(readStatus); + } + + @Transactional(readOnly = true) + @Override + public ReadStatusDto find(UUID readStatusId) { + log.debug("읽음 상태 조회 시작: id={}", readStatusId); + ReadStatusDto dto = readStatusRepository.findById(readStatusId) + .map(readStatusMapper::toDto) + .orElseThrow(() -> ReadStatusNotFoundException.withId(readStatusId)); + log.info("읽음 상태 조회 완료: id={}", readStatusId); + return dto; + } + + @Transactional(readOnly = true) + @Override + public List findAllByUserId(UUID userId) { + log.debug("사용자별 읽음 상태 목록 조회 시작: userId={}", userId); + List dtos = readStatusRepository.findAllByUserId(userId).stream() + .map(readStatusMapper::toDto) + .toList(); + log.info("사용자별 읽음 상태 목록 조회 완료: userId={}, 조회된 항목 수={}", userId, dtos.size()); + return dtos; + } + + @Transactional + @Override + public ReadStatusDto update(UUID readStatusId, ReadStatusUpdateRequest request) { + log.debug("읽음 상태 수정 시작: id={}, newLastReadAt={}", readStatusId, request.newLastReadAt()); + + ReadStatus readStatus = readStatusRepository.findById(readStatusId) + .orElseThrow(() -> ReadStatusNotFoundException.withId(readStatusId)); + readStatus.update(request.newLastReadAt(), request.newNotificationEnabled()); + + log.info("읽음 상태 수정 완료: id={}", readStatusId); + return readStatusMapper.toDto(readStatus); + } + + @Transactional + @Override + public void delete(UUID readStatusId) { + log.debug("읽음 상태 삭제 시작: id={}", readStatusId); + if (!readStatusRepository.existsById(readStatusId)) { + throw ReadStatusNotFoundException.withId(readStatusId); + } + readStatusRepository.deleteById(readStatusId); + log.info("읽음 상태 삭제 완료: id={}", readStatusId); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserService.java new file mode 100644 index 000000000..2b7439b8f --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserService.java @@ -0,0 +1,171 @@ +package com.sprint.mission.discodeit.service.basic; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.event.BinaryContentCreatedEvent; +import com.sprint.mission.discodeit.exception.user.UserAlreadyExistsException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.UserMapper; +import com.sprint.mission.discodeit.repository.BinaryContentRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.service.UserService; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@RequiredArgsConstructor +@Service +public class BasicUserService implements UserService { + + private final UserRepository userRepository; + private final UserMapper userMapper; + private final BinaryContentRepository binaryContentRepository; + private final BinaryContentStorage binaryContentStorage; + private final PasswordEncoder passwordEncoder; + + private final ApplicationEventPublisher eventPublisher; + + @Transactional + @Override + @CacheEvict(value = "users", allEntries = true) + public UserDto create(UserCreateRequest userCreateRequest, + Optional optionalProfileCreateRequest) { + log.debug("사용자 생성 시작: {}", userCreateRequest); + + String username = userCreateRequest.username(); + String email = userCreateRequest.email(); + + if (userRepository.existsByEmail(email)) { + throw UserAlreadyExistsException.withEmail(email); + } + if (userRepository.existsByUsername(username)) { + throw UserAlreadyExistsException.withUsername(username); + } + + BinaryContent nullableProfile = optionalProfileCreateRequest + .map(profileRequest -> { + String fileName = profileRequest.fileName(); + String contentType = profileRequest.contentType(); + byte[] bytes = profileRequest.bytes(); + BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, + contentType); + binaryContentRepository.save(binaryContent); + + eventPublisher.publishEvent(new BinaryContentCreatedEvent(binaryContent,bytes)); + return binaryContent; + }) + .orElse(null); + + String password = userCreateRequest.password(); + String encodedPassword = passwordEncoder.encode(password); + + User user = new User(username, email, encodedPassword, nullableProfile); + + userRepository.save(user); + log.info("사용자 생성 완료: id={}, username={}", user.getId(), username); + return userMapper.toDto(user); + } + + @Transactional(readOnly = true) + @Override + public UserDto find(UUID userId) { + log.debug("사용자 조회 시작: id={}", userId); + UserDto userDto = userRepository.findById(userId) + .map(userMapper::toDto) + .orElseThrow(() -> UserNotFoundException.withId(userId)); + log.info("사용자 조회 완료: id={}", userId); + return userDto; + } + + @Transactional(readOnly = true) + @Override + @Cacheable("users") + public List findAll() { + log.debug("모든 사용자 조회 시작"); + List userDtos = userRepository.findAllWithProfile() + .stream() + .map(userMapper::toDto) + .toList(); + log.info("모든 사용자 조회 완료: 총 {}명", userDtos.size()); + return userDtos; + } + + @PreAuthorize("principal.userDto.id == #userId") + @Transactional + @Override + @CachePut(value = "users", key = "#userId") + public UserDto update(UUID userId, UserUpdateRequest userUpdateRequest, + Optional optionalProfileCreateRequest) { + log.debug("사용자 수정 시작: id={}, request={}", userId, userUpdateRequest); + + User user = userRepository.findById(userId) + .orElseThrow(() -> { + UserNotFoundException exception = UserNotFoundException.withId(userId); + return exception; + }); + + String newUsername = userUpdateRequest.newUsername(); + String newEmail = userUpdateRequest.newEmail(); + + if (userRepository.existsByEmail(newEmail)) { + throw UserAlreadyExistsException.withEmail(newEmail); + } + + if (userRepository.existsByUsername(newUsername)) { + throw UserAlreadyExistsException.withUsername(newUsername); + } + + BinaryContent nullableProfile = optionalProfileCreateRequest + .map(profileRequest -> { + + String fileName = profileRequest.fileName(); + String contentType = profileRequest.contentType(); + byte[] bytes = profileRequest.bytes(); + BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, + contentType); + binaryContentRepository.save(binaryContent); + eventPublisher.publishEvent(new BinaryContentCreatedEvent(binaryContent,bytes)); + return binaryContent; + }) + .orElse(null); + + String newPassword = userUpdateRequest.newPassword(); + String encodedPassword = Optional.ofNullable(newPassword).map(passwordEncoder::encode) + .orElse(user.getPassword()); + user.update(newUsername, newEmail, encodedPassword, nullableProfile); + + log.info("사용자 수정 완료: id={}", userId); + return userMapper.toDto(user); + } + + @PreAuthorize("principal.userDto.id == #userId") + @Transactional + @Override + @CacheEvict(value = "users", allEntries = true) + public void delete(UUID userId) { + log.debug("사용자 삭제 시작: id={}", userId); + + if (!userRepository.existsById(userId)) { + throw UserNotFoundException.withId(userId); + } + + userRepository.deleteById(userId); + log.info("사용자 삭제 완료: id={}", userId); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/storage/BinaryContentStorage.java b/src/main/java/com/sprint/mission/discodeit/storage/BinaryContentStorage.java new file mode 100644 index 000000000..f00216c40 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/storage/BinaryContentStorage.java @@ -0,0 +1,15 @@ +package com.sprint.mission.discodeit.storage; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import java.io.InputStream; +import java.util.UUID; +import org.springframework.http.ResponseEntity; + +public interface BinaryContentStorage { + + UUID put(UUID binaryContentId, byte[] bytes); + + InputStream get(UUID binaryContentId); + + ResponseEntity download(BinaryContentDto metaData); +} diff --git a/src/main/java/com/sprint/mission/discodeit/storage/local/LocalBinaryContentStorage.java b/src/main/java/com/sprint/mission/discodeit/storage/local/LocalBinaryContentStorage.java new file mode 100644 index 000000000..565898816 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/storage/local/LocalBinaryContentStorage.java @@ -0,0 +1,93 @@ +package com.sprint.mission.discodeit.storage.local; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.NoSuchElementException; +import java.util.UUID; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.io.InputStreamResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +@ConditionalOnProperty(name = "discodeit.storage.type", havingValue = "local") +@Component +public class LocalBinaryContentStorage implements BinaryContentStorage { + + private final Path root; + + public LocalBinaryContentStorage( + @Value("${discodeit.storage.local.root-path}") Path root + ) { + this.root = root; + } + + @PostConstruct + public void init() { + if (!Files.exists(root)) { + try { + Files.createDirectories(root); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + } + + public UUID put(UUID binaryContentId, byte[] bytes) { + Path filePath = resolvePath(binaryContentId); + if (Files.exists(filePath)) { + throw new IllegalArgumentException("File with key " + binaryContentId + " already exists"); + } + try (OutputStream outputStream = Files.newOutputStream(filePath)) { + outputStream.write(bytes); + Thread.sleep(3000); + } catch (IOException e) { + throw new RuntimeException(e); + }catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Thread interrupted while simulating delay", e); + } + return binaryContentId; + } + + public InputStream get(UUID binaryContentId) { + Path filePath = resolvePath(binaryContentId); + if (Files.notExists(filePath)) { + throw new NoSuchElementException("File with key " + binaryContentId + " does not exist"); + } + try { + return Files.newInputStream(filePath); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + private Path resolvePath(UUID key) { + return root.resolve(key.toString()); + } + + @Override + public ResponseEntity download(BinaryContentDto metaData) { + InputStream inputStream = get(metaData.id()); + Resource resource = new InputStreamResource(inputStream); + + return ResponseEntity + .status(HttpStatus.OK) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + metaData.fileName() + "\"") + .header(HttpHeaders.CONTENT_TYPE, metaData.contentType()) + .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(metaData.size())) + .body(resource); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorage.java b/src/main/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorage.java new file mode 100644 index 000000000..d31e1e92d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorage.java @@ -0,0 +1,181 @@ +package com.sprint.mission.discodeit.storage.s3; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.event.S3UploadFailedEvent; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; +import java.util.NoSuchElementException; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Component; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; +import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; + +@Slf4j +@ConditionalOnProperty(name = "discodeit.storage.type", havingValue = "s3") +@Component +public class S3BinaryContentStorage implements BinaryContentStorage { + + private final String accessKey; + private final String secretKey; + private final String region; + private final String bucket; + private final ApplicationEventPublisher eventPublisher; + + @Value("${discodeit.storage.s3.presigned-url-expiration:600}") // 기본값 10분 + private long presignedUrlExpirationSeconds; + + public S3BinaryContentStorage( + @Value("${discodeit.storage.s3.access-key}") String accessKey, + @Value("${discodeit.storage.s3.secret-key}") String secretKey, + @Value("${discodeit.storage.s3.region}") String region, + @Value("${discodeit.storage.s3.bucket}") String bucket, + ApplicationEventPublisher eventPublisher + ) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.region = region; + this.bucket = bucket; + this.eventPublisher = eventPublisher; + } + + @Override + @Retryable( + value = {S3Exception.class, IOException.class}, + maxAttempts = 3, // 최대 3회 시도 + backoff = @Backoff(delay = 2000) // 각 시도 사이 2초 대기 + ) + public UUID put(UUID binaryContentId, byte[] bytes) { + String key = binaryContentId.toString(); + try { + Thread.sleep(3000); + S3Client s3Client = getS3Client(); + + PutObjectRequest request = PutObjectRequest.builder() + .bucket(bucket) + .key(key) + .build(); + + s3Client.putObject(request, RequestBody.fromBytes(bytes)); + log.info("S3에 파일 업로드 성공: {}", key); + + return binaryContentId; + } catch (S3Exception e) { + log.error("S3에 파일 업로드 실패: {}", e.getMessage()); + throw e; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Thread interrupted while simulating delay", e); + } + } + + @Override + public InputStream get(UUID binaryContentId) { + String key = binaryContentId.toString(); + try { + S3Client s3Client = getS3Client(); + + GetObjectRequest request = GetObjectRequest.builder() + .bucket(bucket) + .key(key) + .build(); + + byte[] bytes = s3Client.getObjectAsBytes(request).asByteArray(); + return new ByteArrayInputStream(bytes); + } catch (S3Exception e) { + log.error("S3에서 파일 다운로드 실패: {}", e.getMessage()); + throw new NoSuchElementException("File with key " + key + " does not exist"); + } + } + + private S3Client getS3Client() { + return S3Client.builder() + .region(Region.of(region)) + .credentialsProvider( + StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey) + ) + ) + .build(); + } + + @Override + public ResponseEntity download(BinaryContentDto metaData) { + try { + String key = metaData.id().toString(); + String presignedUrl = generatePresignedUrl(key, metaData.contentType()); + + log.info("생성된 Presigned URL: {}", presignedUrl); + + return ResponseEntity + .status(HttpStatus.FOUND) + .header(HttpHeaders.LOCATION, presignedUrl) + .build(); + } catch (Exception e) { + log.error("Presigned URL 생성 실패: {}", e.getMessage()); + throw new RuntimeException("Presigned URL 생성 실패", e); + } + } + + private String generatePresignedUrl(String key, String contentType) { + try (S3Presigner presigner = getS3Presigner()) { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucket) + .key(key) + .responseContentType(contentType) + .build(); + + GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder() + .signatureDuration(Duration.ofSeconds(presignedUrlExpirationSeconds)) + .getObjectRequest(getObjectRequest) + .build(); + + PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(presignRequest); + return presignedRequest.url().toString(); + } + } + + private S3Presigner getS3Presigner() { + return S3Presigner.builder() + .region(Region.of(region)) + .credentialsProvider( + StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey) + ) + ) + .build(); + } + + @Recover + public void recover(Exception e, UUID binaryContentId) { + + log.info("[S3BinaryContentStorage] 재시도 모두 실패 binaryContentId: {}", binaryContentId, e); + + S3UploadFailedEvent event = new S3UploadFailedEvent(MDC.get("requestId"), binaryContentId, + e.getMessage()); + + eventPublisher.publishEvent(event); + } +} \ No newline at end of file diff --git a/src/main/resources/application-dev.yaml b/src/main/resources/application-dev.yaml new file mode 100644 index 000000000..de2d9bb63 --- /dev/null +++ b/src/main/resources/application-dev.yaml @@ -0,0 +1,30 @@ +server: + port: 8080 + +spring: + datasource: + url: jdbc:postgresql://localhost:5432/discodeit + username: discodeit_user + password: discodeit1234 + jpa: + properties: + hibernate: + format_sql: true + +logging: + level: + com.sprint.mission.discodeit: debug + org.hibernate.SQL: debug + org.hibernate.orm.jdbc.bind: trace + org.springframework.security: trace + +management: + endpoint: + health: + show-details: always + info: + env: + enabled: true + observations: + annotations: + enabled: true \ No newline at end of file diff --git a/src/main/resources/application-prod.yaml b/src/main/resources/application-prod.yaml new file mode 100644 index 000000000..3074885d3 --- /dev/null +++ b/src/main/resources/application-prod.yaml @@ -0,0 +1,25 @@ +server: + port: 80 + +spring: + datasource: + url: ${SPRING_DATASOURCE_URL} + username: ${SPRING_DATASOURCE_USERNAME} + password: ${SPRING_DATASOURCE_PASSWORD} + jpa: + properties: + hibernate: + format_sql: false + +logging: + level: + com.sprint.mission.discodeit: info + org.hibernate.SQL: info + +management: + endpoint: + health: + show-details: never + info: + env: + enabled: false \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 000000000..940d9e45b --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,77 @@ +spring: + application: + name: discodeit + servlet: + multipart: + maxFileSize: 10MB # 파일 하나의 최대 크기 + maxRequestSize: 30MB # 한 번에 최대 업로드 가능 용량 + datasource: + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: validate + open-in-view: false + profiles: + active: + - dev + config: + import: optional:file:.env[.properties] + +management: + endpoints: + web: + exposure: + include: health,info,metrics,loggers + endpoint: + health: + show-details: always + +info: + name: Discodeit + version: 1.7.0 + java: + version: 17 + spring-boot: + version: 3.4.0 + config: + datasource: + url: ${spring.datasource.url} + driver-class-name: ${spring.datasource.driver-class-name} + jpa: + ddl-auto: ${spring.jpa.hibernate.ddl-auto} + storage: + type: ${discodeit.storage.type} + path: ${discodeit.storage.local.root-path} + multipart: + max-file-size: ${spring.servlet.multipart.maxFileSize} + max-request-size: ${spring.servlet.multipart.maxRequestSize} + +discodeit: + storage: + type: ${STORAGE_TYPE:local} # local | s3 (기본값: local) + local: + root-path: ${STORAGE_LOCAL_ROOT_PATH:.discodeit/storage} + s3: + access-key: ${AWS_S3_ACCESS_KEY} + secret-key: ${AWS_S3_SECRET_KEY} + region: ${AWS_S3_REGION} + bucket: ${AWS_S3_BUCKET} + presigned-url-expiration: ${AWS_S3_PRESIGNED_URL_EXPIRATION:600} # (기본값: 10분) + admin: +# username: ${DISCODEIT_ADMIN_USERNAME} +# email: ${DISCODEIT_ADMIN_EMAIL} +# password: ${DISCODEIT_ADMIN_PASSWORD} + username: admin + email: admin@google.com + password: asdf1234! + jwt: + access-token: + secret: ${JWT_ACCESS_SECRET:your-access-token-secret-key-here-make-it-long-and-random} + expiration-ms: ${JWT_ACCESS_EXPIRATION_MS:1800000} # 30 minutes + refresh-token: + secret: ${JWT_REFRESH_SECRET:your-refresh-token-secret-key-here-make-it-different-and-long} + expiration-ms: ${JWT_REFRESH_EXPIRATION_MS:604800000} # 7 days + +logging: + level: + root: info \ No newline at end of file diff --git a/src/main/resources/fe_bundle_1.2.3.zip b/src/main/resources/fe_bundle_1.2.3.zip new file mode 100644 index 0000000000000000000000000000000000000000..852a0869c0058982bcd14d2879e20e95e78927c2 GIT binary patch literal 95493 zcmd41Q?M}4mnC{^>pQk>+qP}n=R3A-+qP}nwr$Vv-!u2#nU3!1hx;&7QI%2kvSQcH zy;iQw*z!`qASeL;x{PhyH2>}8e+&o!_yDFRdWJ5x#?~f!477~2Omr&BumIrN@w;aK z&*S0_4FCx83UvT~Z!T)!- zM*65mX8MNucQVqdckrrV@_s;Z=)hzMSbz=$2!U^r7-2v$1Ox)|q~fD6_$Q)D17Qe% zWM*cUrKrirB$lbjC+MW6rKY50P4tZo-LdUO9)La@!vW-_z#*WfV*6D8iSJ)A{(sR+ z{!h7J1_J=V`VVqpYT#;NWM@nJ&+u>I)BF?m-~W-Ce;58G%$?Keal(P2zW(0xlRYHR z0u=sKKMb)>iZc$dBK3JpPYetU)@S=KaRbnM)Ud#fEX?K1co#^y^b5p;iGG=)k-oXP zf&LpPiluvhpS)#X-yNmDf4?OdaG-mCmX1Fwzqb;wm!P&klqLF4Y(amZAOHJGU}RsI z1r6i_w5k3c>#S9ip)nE)!oAVeVORc`Df>_J-lmxtguw_C{jf@5QF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pd)e=K^=yG;U?GP0~dnQ3+wY8I~OdQSiF>8n6gPLC=N&r~6 zL;zmIwE;NT2Ye_nB>*H878u<7A!p;J4fda<;QgBej1){?UtUZ?QB{-0)I{IN#n#x` zM4yeBotcBh(87=fP3|f-~Unn#_*5U{}{GETK}^$ z!Jk_XPd!iVOiy!axCA2<7#JrE7#QK7bP5BI!2dgisiCU{ z$j+Ae{o}tT#q&R*{sqtpiD`hz&fU1)vGsx+$?&5!;{JUjx{zWzw>0eO(&0qb~9{eA`|Li?!|I!0n zGh4C(z4e_!-fcHr-4{|2H( BOw#}W literal 0 HcmV?d00001 diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 000000000..0f338e0b1 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + ${LOG_PATTERN} + + + + + + ${LOG_FILE_PATH}/${LOG_FILE_NAME}.log + + ${LOG_PATTERN} + + + ${LOG_FILE_PATH}/${LOG_FILE_NAME}.%d{yyyy-MM-dd}.log + 30 + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 000000000..8871aef6c --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,113 @@ +-- 테이블 +-- User +CREATE TABLE users +( + id uuid PRIMARY KEY, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone, + username varchar(50) UNIQUE NOT NULL, + email varchar(100) UNIQUE NOT NULL, + password varchar(60) NOT NULL, + profile_id uuid, + role varchar(20) NOT NULL +); + +-- BinaryContent +CREATE TABLE binary_contents +( + id uuid PRIMARY KEY, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone, + file_name varchar(255) NOT NULL, + size bigint NOT NULL, + content_type varchar(100) NOT NULL, + status varchar(20) NOT NULL +); + + +-- Channel +CREATE TABLE channels +( + id uuid PRIMARY KEY, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone, + name varchar(100), + description varchar(500), + type varchar(10) NOT NULL +); + +-- Message +CREATE TABLE messages +( + id uuid PRIMARY KEY, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone, + content text, + channel_id uuid NOT NULL, + author_id uuid +); + +-- Message.attachments +CREATE TABLE message_attachments +( + message_id uuid, + attachment_id uuid, + PRIMARY KEY (message_id, attachment_id) +); + +-- ReadStatus +CREATE TABLE read_statuses +( + id uuid PRIMARY KEY, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone, + user_id uuid NOT NULL, + channel_id uuid NOT NULL, + last_read_at timestamp with time zone NOT NULL, + notification_enabled boolean NOT NULL, + UNIQUE (user_id, channel_id) +); + + +-- 제약 조건 +-- User (1) -> BinaryContent (1) +ALTER TABLE users + ADD CONSTRAINT fk_user_binary_content + FOREIGN KEY (profile_id) + REFERENCES binary_contents (id) + ON DELETE SET NULL; + +-- Message (N) -> Channel (1) +ALTER TABLE messages + ADD CONSTRAINT fk_message_channel + FOREIGN KEY (channel_id) + REFERENCES channels (id) + ON DELETE CASCADE; + +-- Message (N) -> Author (1) +ALTER TABLE messages + ADD CONSTRAINT fk_message_user + FOREIGN KEY (author_id) + REFERENCES users (id) + ON DELETE SET NULL; + +-- MessageAttachment (1) -> BinaryContent (1) +ALTER TABLE message_attachments + ADD CONSTRAINT fk_message_attachment_binary_content + FOREIGN KEY (attachment_id) + REFERENCES binary_contents (id) + ON DELETE CASCADE; + +-- ReadStatus (N) -> User (1) +ALTER TABLE read_statuses + ADD CONSTRAINT fk_read_status_user + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE CASCADE; + +-- ReadStatus (N) -> User (1) +ALTER TABLE read_statuses + ADD CONSTRAINT fk_read_status_channel + FOREIGN KEY (channel_id) + REFERENCES channels (id) + ON DELETE CASCADE; \ No newline at end of file diff --git a/src/main/resources/static/assets/index-DB4IjbRs.js b/src/main/resources/static/assets/index-DB4IjbRs.js new file mode 100644 index 000000000..3056ff41a --- /dev/null +++ b/src/main/resources/static/assets/index-DB4IjbRs.js @@ -0,0 +1,1572 @@ +var Vg=Object.defineProperty;var Wg=(n,i,s)=>i in n?Vg(n,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):n[i]=s;var kf=(n,i,s)=>Wg(n,typeof i!="symbol"?i+"":i,s);(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))l(c);new MutationObserver(c=>{for(const d of c)if(d.type==="childList")for(const f of d.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function s(c){const d={};return c.integrity&&(d.integrity=c.integrity),c.referrerPolicy&&(d.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?d.credentials="include":c.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function l(c){if(c.ep)return;c.ep=!0;const d=s(c);fetch(c.href,d)}})();function mu(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Ma={exports:{}},Co={},_a={exports:{}},ke={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Cf;function qg(){if(Cf)return ke;Cf=1;var n=Symbol.for("react.element"),i=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),d=Symbol.for("react.provider"),f=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),y=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),j=Symbol.iterator;function $(w){return w===null||typeof w!="object"?null:(w=j&&w[j]||w["@@iterator"],typeof w=="function"?w:null)}var I={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,A={};function _(w,L,ie){this.props=w,this.context=L,this.refs=A,this.updater=ie||I}_.prototype.isReactComponent={},_.prototype.setState=function(w,L){if(typeof w!="object"&&typeof w!="function"&&w!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,w,L,"setState")},_.prototype.forceUpdate=function(w){this.updater.enqueueForceUpdate(this,w,"forceUpdate")};function J(){}J.prototype=_.prototype;function G(w,L,ie){this.props=w,this.context=L,this.refs=A,this.updater=ie||I}var H=G.prototype=new J;H.constructor=G,k(H,_.prototype),H.isPureReactComponent=!0;var X=Array.isArray,D=Object.prototype.hasOwnProperty,N={current:null},Q={key:!0,ref:!0,__self:!0,__source:!0};function le(w,L,ie){var ae,de={},he=null,we=null;if(L!=null)for(ae in L.ref!==void 0&&(we=L.ref),L.key!==void 0&&(he=""+L.key),L)D.call(L,ae)&&!Q.hasOwnProperty(ae)&&(de[ae]=L[ae]);var ye=arguments.length-2;if(ye===1)de.children=ie;else if(1>>1,L=P[w];if(0>>1;wc(de,B))hec(we,de)?(P[w]=we,P[he]=B,w=he):(P[w]=de,P[ae]=B,w=ae);else if(hec(we,B))P[w]=we,P[he]=B,w=he;else break e}}return F}function c(P,F){var B=P.sortIndex-F.sortIndex;return B!==0?B:P.id-F.id}if(typeof performance=="object"&&typeof performance.now=="function"){var d=performance;n.unstable_now=function(){return d.now()}}else{var f=Date,m=f.now();n.unstable_now=function(){return f.now()-m}}var x=[],y=[],S=1,j=null,$=3,I=!1,k=!1,A=!1,_=typeof setTimeout=="function"?setTimeout:null,J=typeof clearTimeout=="function"?clearTimeout:null,G=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function H(P){for(var F=s(y);F!==null;){if(F.callback===null)l(y);else if(F.startTime<=P)l(y),F.sortIndex=F.expirationTime,i(x,F);else break;F=s(y)}}function X(P){if(A=!1,H(P),!k)if(s(x)!==null)k=!0,b(D);else{var F=s(y);F!==null&&W(X,F.startTime-P)}}function D(P,F){k=!1,A&&(A=!1,J(le),le=-1),I=!0;var B=$;try{for(H(F),j=s(x);j!==null&&(!(j.expirationTime>F)||P&&!pe());){var w=j.callback;if(typeof w=="function"){j.callback=null,$=j.priorityLevel;var L=w(j.expirationTime<=F);F=n.unstable_now(),typeof L=="function"?j.callback=L:j===s(x)&&l(x),H(F)}else l(x);j=s(x)}if(j!==null)var ie=!0;else{var ae=s(y);ae!==null&&W(X,ae.startTime-F),ie=!1}return ie}finally{j=null,$=B,I=!1}}var N=!1,Q=null,le=-1,Se=5,ge=-1;function pe(){return!(n.unstable_now()-geP||125w?(P.sortIndex=B,i(y,P),s(x)===null&&P===s(y)&&(A?(J(le),le=-1):A=!0,W(X,B-w))):(P.sortIndex=L,i(x,P),k||I||(k=!0,b(D))),P},n.unstable_shouldYield=pe,n.unstable_wrapCallback=function(P){var F=$;return function(){var B=$;$=F;try{return P.apply(this,arguments)}finally{$=B}}}}($a)),$a}var Pf;function Xg(){return Pf||(Pf=1,Na.exports=Kg()),Na.exports}/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Mf;function Jg(){if(Mf)return ht;Mf=1;var n=gu(),i=Xg();function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),x=Object.prototype.hasOwnProperty,y=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,S={},j={};function $(e){return x.call(j,e)?!0:x.call(S,e)?!1:y.test(e)?j[e]=!0:(S[e]=!0,!1)}function I(e,t,r,o){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function k(e,t,r,o){if(t===null||typeof t>"u"||I(e,t,r,o))return!0;if(o)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function A(e,t,r,o,a,u,p){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=u,this.removeEmptyString=p}var _={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){_[e]=new A(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];_[t]=new A(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){_[e]=new A(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){_[e]=new A(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){_[e]=new A(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){_[e]=new A(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){_[e]=new A(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){_[e]=new A(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){_[e]=new A(e,5,!1,e.toLowerCase(),null,!1,!1)});var J=/[\-:]([a-z])/g;function G(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(J,G);_[t]=new A(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(J,G);_[t]=new A(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(J,G);_[t]=new A(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){_[e]=new A(e,1,!1,e.toLowerCase(),null,!1,!1)}),_.xlinkHref=new A("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){_[e]=new A(e,1,!1,e.toLowerCase(),null,!0,!0)});function H(e,t,r,o){var a=_.hasOwnProperty(t)?_[t]:null;(a!==null?a.type!==0:o||!(2g||a[p]!==u[g]){var v=` +`+a[p].replace(" at new "," at ");return e.displayName&&v.includes("")&&(v=v.replace("",e.displayName)),v}while(1<=p&&0<=g);break}}}finally{ie=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?L(e):""}function de(e){switch(e.tag){case 5:return L(e.type);case 16:return L("Lazy");case 13:return L("Suspense");case 19:return L("SuspenseList");case 0:case 2:case 15:return e=ae(e.type,!1),e;case 11:return e=ae(e.type.render,!1),e;case 1:return e=ae(e.type,!0),e;default:return""}}function he(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Q:return"Fragment";case N:return"Portal";case Se:return"Profiler";case le:return"StrictMode";case Fe:return"Suspense";case V:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case pe:return(e.displayName||"Context")+".Consumer";case ge:return(e._context.displayName||"Context")+".Provider";case Be:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case z:return t=e.displayName||null,t!==null?t:he(e.type)||"Memo";case b:t=e._payload,e=e._init;try{return he(e(t))}catch{}}return null}function we(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return he(t);case 8:return t===le?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ye(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function xe(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ee(e){var t=xe(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,u=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(p){o=""+p,u.call(this,p)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return o},setValue:function(p){o=""+p},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function We(e){e._valueTracker||(e._valueTracker=Ee(e))}function Xe(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),o="";return e&&(o=xe(e)?e.checked?"true":"false":e.value),e=o,e!==r?(t.setValue(e),!0):!1}function qt(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Ds(e,t){var r=t.checked;return B({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Pu(e,t){var r=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;r=ye(t.value!=null?t.value:r),e._wrapperState={initialChecked:o,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Mu(e,t){t=t.checked,t!=null&&H(e,"checked",t,!1)}function Is(e,t){Mu(e,t);var r=ye(t.value),o=t.type;if(r!=null)o==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?bs(e,t.type,r):t.hasOwnProperty("defaultValue")&&bs(e,t.type,ye(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function _u(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var o=t.type;if(!(o!=="submit"&&o!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function bs(e,t,r){(t!=="number"||qt(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Ir=Array.isArray;function Xn(e,t,r,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Uo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function br(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var zr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Kh=["Webkit","ms","Moz","O"];Object.keys(zr).forEach(function(e){Kh.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),zr[t]=zr[e]})});function Du(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||zr.hasOwnProperty(e)&&zr[e]?(""+t).trim():t+"px"}function Iu(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var o=r.indexOf("--")===0,a=Du(r,t[r],o);r==="float"&&(r="cssFloat"),o?e.setProperty(r,a):e[r]=a}}var Xh=B({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Fs(e,t){if(t){if(Xh[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(s(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(s(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(s(61))}if(t.style!=null&&typeof t.style!="object")throw Error(s(62))}}function Us(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Hs=null;function Ys(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Vs=null,Jn=null,Zn=null;function bu(e){if(e=lo(e)){if(typeof Vs!="function")throw Error(s(280));var t=e.stateNode;t&&(t=di(t),Vs(e.stateNode,e.type,t))}}function zu(e){Jn?Zn?Zn.push(e):Zn=[e]:Jn=e}function Bu(){if(Jn){var e=Jn,t=Zn;if(Zn=Jn=null,bu(e),t)for(e=0;e>>=0,e===0?32:31-(am(e)/um|0)|0}var qo=64,Qo=4194304;function Hr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Go(e,t){var r=e.pendingLanes;if(r===0)return 0;var o=0,a=e.suspendedLanes,u=e.pingedLanes,p=r&268435455;if(p!==0){var g=p&~a;g!==0?o=Hr(g):(u&=p,u!==0&&(o=Hr(u)))}else p=r&~a,p!==0?o=Hr(p):u!==0&&(o=Hr(u));if(o===0)return 0;if(t!==0&&t!==o&&!(t&a)&&(a=o&-o,u=t&-t,a>=u||a===16&&(u&4194240)!==0))return t;if(o&4&&(o|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0r;r++)t.push(e);return t}function Yr(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Tt(t),e[t]=r}function pm(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var o=e.eventTimes;for(e=e.expirationTimes;0=Jr),hc=" ",mc=!1;function gc(e,t){switch(e){case"keyup":return Fm.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function yc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var nr=!1;function Hm(e,t){switch(e){case"compositionend":return yc(t);case"keypress":return t.which!==32?null:(mc=!0,hc);case"textInput":return e=t.data,e===hc&&mc?null:e;default:return null}}function Ym(e,t){if(nr)return e==="compositionend"||!ul&&gc(e,t)?(e=ac(),ei=rl=un=null,nr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-e};e=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Ec(r)}}function Ac(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ac(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Rc(){for(var e=window,t=qt();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=qt(e.document)}return t}function fl(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Zm(e){var t=Rc(),r=e.focusedElem,o=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&Ac(r.ownerDocument.documentElement,r)){if(o!==null&&fl(r)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=r.textContent.length,u=Math.min(o.start,a);o=o.end===void 0?u:Math.min(o.end,a),!e.extend&&u>o&&(a=o,o=u,u=a),a=jc(r,u);var p=jc(r,o);a&&p&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==p.node||e.focusOffset!==p.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),u>o?(e.addRange(t),e.extend(p.node,p.offset)):(t.setEnd(p.node,p.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,rr=null,pl=null,no=null,hl=!1;function Pc(e,t,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;hl||rr==null||rr!==qt(o)||(o=rr,"selectionStart"in o&&fl(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),no&&to(no,o)||(no=o,o=ai(pl,"onSelect"),0ar||(e.current=Al[ar],Al[ar]=null,ar--)}function Pe(e,t){ar++,Al[ar]=e.current,e.current=t}var pn={},tt=fn(pn),ut=fn(!1),_n=pn;function ur(e,t){var r=e.type.contextTypes;if(!r)return pn;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},u;for(u in r)a[u]=t[u];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function ct(e){return e=e.childContextTypes,e!=null}function fi(){_e(ut),_e(tt)}function Hc(e,t,r){if(tt.current!==pn)throw Error(s(168));Pe(tt,t),Pe(ut,r)}function Yc(e,t,r){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return r;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(s(108,we(e)||"Unknown",a));return B({},r,o)}function pi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||pn,_n=tt.current,Pe(tt,e),Pe(ut,ut.current),!0}function Vc(e,t,r){var o=e.stateNode;if(!o)throw Error(s(169));r?(e=Yc(e,t,_n),o.__reactInternalMemoizedMergedChildContext=e,_e(ut),_e(tt),Pe(tt,e)):_e(ut),Pe(ut,r)}var Gt=null,hi=!1,Rl=!1;function Wc(e){Gt===null?Gt=[e]:Gt.push(e)}function dg(e){hi=!0,Wc(e)}function hn(){if(!Rl&&Gt!==null){Rl=!0;var e=0,t=Re;try{var r=Gt;for(Re=1;e>=p,a-=p,Kt=1<<32-Tt(t)+a|r<fe?(Ge=ce,ce=null):Ge=ce.sibling;var je=U(R,ce,M[fe],K);if(je===null){ce===null&&(ce=Ge);break}e&&ce&&je.alternate===null&&t(R,ce),C=u(je,C,fe),ue===null?se=je:ue.sibling=je,ue=je,ce=Ge}if(fe===M.length)return r(R,ce),Ne&&Nn(R,fe),se;if(ce===null){for(;fefe?(Ge=ce,ce=null):Ge=ce.sibling;var Cn=U(R,ce,je.value,K);if(Cn===null){ce===null&&(ce=Ge);break}e&&ce&&Cn.alternate===null&&t(R,ce),C=u(Cn,C,fe),ue===null?se=Cn:ue.sibling=Cn,ue=Cn,ce=Ge}if(je.done)return r(R,ce),Ne&&Nn(R,fe),se;if(ce===null){for(;!je.done;fe++,je=M.next())je=q(R,je.value,K),je!==null&&(C=u(je,C,fe),ue===null?se=je:ue.sibling=je,ue=je);return Ne&&Nn(R,fe),se}for(ce=o(R,ce);!je.done;fe++,je=M.next())je=te(ce,R,fe,je.value,K),je!==null&&(e&&je.alternate!==null&&ce.delete(je.key===null?fe:je.key),C=u(je,C,fe),ue===null?se=je:ue.sibling=je,ue=je);return e&&ce.forEach(function(Yg){return t(R,Yg)}),Ne&&Nn(R,fe),se}function be(R,C,M,K){if(typeof M=="object"&&M!==null&&M.type===Q&&M.key===null&&(M=M.props.children),typeof M=="object"&&M!==null){switch(M.$$typeof){case D:e:{for(var se=M.key,ue=C;ue!==null;){if(ue.key===se){if(se=M.type,se===Q){if(ue.tag===7){r(R,ue.sibling),C=a(ue,M.props.children),C.return=R,R=C;break e}}else if(ue.elementType===se||typeof se=="object"&&se!==null&&se.$$typeof===b&&Jc(se)===ue.type){r(R,ue.sibling),C=a(ue,M.props),C.ref=ao(R,ue,M),C.return=R,R=C;break e}r(R,ue);break}else t(R,ue);ue=ue.sibling}M.type===Q?(C=Bn(M.props.children,R.mode,K,M.key),C.return=R,R=C):(K=Ui(M.type,M.key,M.props,null,R.mode,K),K.ref=ao(R,C,M),K.return=R,R=K)}return p(R);case N:e:{for(ue=M.key;C!==null;){if(C.key===ue)if(C.tag===4&&C.stateNode.containerInfo===M.containerInfo&&C.stateNode.implementation===M.implementation){r(R,C.sibling),C=a(C,M.children||[]),C.return=R,R=C;break e}else{r(R,C);break}else t(R,C);C=C.sibling}C=Ea(M,R.mode,K),C.return=R,R=C}return p(R);case b:return ue=M._init,be(R,C,ue(M._payload),K)}if(Ir(M))return re(R,C,M,K);if(F(M))return oe(R,C,M,K);xi(R,M)}return typeof M=="string"&&M!==""||typeof M=="number"?(M=""+M,C!==null&&C.tag===6?(r(R,C.sibling),C=a(C,M),C.return=R,R=C):(r(R,C),C=Ca(M,R.mode,K),C.return=R,R=C),p(R)):r(R,C)}return be}var pr=Zc(!0),ed=Zc(!1),vi=fn(null),wi=null,hr=null,$l=null;function Ol(){$l=hr=wi=null}function Ll(e){var t=vi.current;_e(vi),e._currentValue=t}function Dl(e,t,r){for(;e!==null;){var o=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,o!==null&&(o.childLanes|=t)):o!==null&&(o.childLanes&t)!==t&&(o.childLanes|=t),e===r)break;e=e.return}}function mr(e,t){wi=e,$l=hr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(dt=!0),e.firstContext=null)}function At(e){var t=e._currentValue;if($l!==e)if(e={context:e,memoizedValue:t,next:null},hr===null){if(wi===null)throw Error(s(308));hr=e,wi.dependencies={lanes:0,firstContext:e}}else hr=hr.next=e;return t}var $n=null;function Il(e){$n===null?$n=[e]:$n.push(e)}function td(e,t,r,o){var a=t.interleaved;return a===null?(r.next=r,Il(t)):(r.next=a.next,a.next=r),t.interleaved=r,Jt(e,o)}function Jt(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var mn=!1;function bl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function nd(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Zt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gn(e,t,r){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,Ce&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Jt(e,r)}return a=o.interleaved,a===null?(t.next=t,Il(o)):(t.next=a.next,a.next=t),o.interleaved=t,Jt(e,r)}function Si(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,r|=o,t.lanes=r,Js(e,r)}}function rd(e,t){var r=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var a=null,u=null;if(r=r.firstBaseUpdate,r!==null){do{var p={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};u===null?a=u=p:u=u.next=p,r=r.next}while(r!==null);u===null?a=u=t:u=u.next=t}else a=u=t;r={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:u,shared:o.shared,effects:o.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function ki(e,t,r,o){var a=e.updateQueue;mn=!1;var u=a.firstBaseUpdate,p=a.lastBaseUpdate,g=a.shared.pending;if(g!==null){a.shared.pending=null;var v=g,T=v.next;v.next=null,p===null?u=T:p.next=T,p=v;var Y=e.alternate;Y!==null&&(Y=Y.updateQueue,g=Y.lastBaseUpdate,g!==p&&(g===null?Y.firstBaseUpdate=T:g.next=T,Y.lastBaseUpdate=v))}if(u!==null){var q=a.baseState;p=0,Y=T=v=null,g=u;do{var U=g.lane,te=g.eventTime;if((o&U)===U){Y!==null&&(Y=Y.next={eventTime:te,lane:0,tag:g.tag,payload:g.payload,callback:g.callback,next:null});e:{var re=e,oe=g;switch(U=t,te=r,oe.tag){case 1:if(re=oe.payload,typeof re=="function"){q=re.call(te,q,U);break e}q=re;break e;case 3:re.flags=re.flags&-65537|128;case 0:if(re=oe.payload,U=typeof re=="function"?re.call(te,q,U):re,U==null)break e;q=B({},q,U);break e;case 2:mn=!0}}g.callback!==null&&g.lane!==0&&(e.flags|=64,U=a.effects,U===null?a.effects=[g]:U.push(g))}else te={eventTime:te,lane:U,tag:g.tag,payload:g.payload,callback:g.callback,next:null},Y===null?(T=Y=te,v=q):Y=Y.next=te,p|=U;if(g=g.next,g===null){if(g=a.shared.pending,g===null)break;U=g,g=U.next,U.next=null,a.lastBaseUpdate=U,a.shared.pending=null}}while(!0);if(Y===null&&(v=q),a.baseState=v,a.firstBaseUpdate=T,a.lastBaseUpdate=Y,t=a.shared.interleaved,t!==null){a=t;do p|=a.lane,a=a.next;while(a!==t)}else u===null&&(a.shared.lanes=0);Dn|=p,e.lanes=p,e.memoizedState=q}}function od(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var o=Hl.transition;Hl.transition={};try{e(!1),t()}finally{Re=r,Hl.transition=o}}function Cd(){return Rt().memoizedState}function mg(e,t,r){var o=wn(e);if(r={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null},Ed(e))jd(t,r);else if(r=td(e,t,r,o),r!==null){var a=at();It(r,e,o,a),Ad(r,t,o)}}function gg(e,t,r){var o=wn(e),a={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null};if(Ed(e))jd(t,a);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var p=t.lastRenderedState,g=u(p,r);if(a.hasEagerState=!0,a.eagerState=g,Nt(g,p)){var v=t.interleaved;v===null?(a.next=a,Il(t)):(a.next=v.next,v.next=a),t.interleaved=a;return}}catch{}finally{}r=td(e,t,a,o),r!==null&&(a=at(),It(r,e,o,a),Ad(r,t,o))}}function Ed(e){var t=e.alternate;return e===Oe||t!==null&&t===Oe}function jd(e,t){po=ji=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function Ad(e,t,r){if(r&4194240){var o=t.lanes;o&=e.pendingLanes,r|=o,t.lanes=r,Js(e,r)}}var Pi={readContext:At,useCallback:nt,useContext:nt,useEffect:nt,useImperativeHandle:nt,useInsertionEffect:nt,useLayoutEffect:nt,useMemo:nt,useReducer:nt,useRef:nt,useState:nt,useDebugValue:nt,useDeferredValue:nt,useTransition:nt,useMutableSource:nt,useSyncExternalStore:nt,useId:nt,unstable_isNewReconciler:!1},yg={readContext:At,useCallback:function(e,t){return Ht().memoizedState=[e,t===void 0?null:t],e},useContext:At,useEffect:md,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,Ai(4194308,4,xd.bind(null,t,e),r)},useLayoutEffect:function(e,t){return Ai(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ai(4,2,e,t)},useMemo:function(e,t){var r=Ht();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var o=Ht();return t=r!==void 0?r(t):t,o.memoizedState=o.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},o.queue=e,e=e.dispatch=mg.bind(null,Oe,e),[o.memoizedState,e]},useRef:function(e){var t=Ht();return e={current:e},t.memoizedState=e},useState:pd,useDebugValue:Kl,useDeferredValue:function(e){return Ht().memoizedState=e},useTransition:function(){var e=pd(!1),t=e[0];return e=hg.bind(null,e[1]),Ht().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var o=Oe,a=Ht();if(Ne){if(r===void 0)throw Error(s(407));r=r()}else{if(r=t(),Qe===null)throw Error(s(349));Ln&30||ad(o,t,r)}a.memoizedState=r;var u={value:r,getSnapshot:t};return a.queue=u,md(cd.bind(null,o,u,e),[e]),o.flags|=2048,go(9,ud.bind(null,o,u,r,t),void 0,null),r},useId:function(){var e=Ht(),t=Qe.identifierPrefix;if(Ne){var r=Xt,o=Kt;r=(o&~(1<<32-Tt(o)-1)).toString(32)+r,t=":"+t+"R"+r,r=ho++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=p.createElement(r,{is:o.is}):(e=p.createElement(r),r==="select"&&(p=e,o.multiple?p.multiple=!0:o.size&&(p.size=o.size))):e=p.createElementNS(e,r),e[Ft]=t,e[so]=o,Wd(e,t,!1,!1),t.stateNode=e;e:{switch(p=Us(r,o),r){case"dialog":Me("cancel",e),Me("close",e),a=o;break;case"iframe":case"object":case"embed":Me("load",e),a=o;break;case"video":case"audio":for(a=0;awr&&(t.flags|=128,o=!0,yo(u,!1),t.lanes=4194304)}else{if(!o)if(e=Ci(p),e!==null){if(t.flags|=128,o=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),yo(u,!0),u.tail===null&&u.tailMode==="hidden"&&!p.alternate&&!Ne)return rt(t),null}else 2*Ie()-u.renderingStartTime>wr&&r!==1073741824&&(t.flags|=128,o=!0,yo(u,!1),t.lanes=4194304);u.isBackwards?(p.sibling=t.child,t.child=p):(r=u.last,r!==null?r.sibling=p:t.child=p,u.last=p)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ie(),t.sibling=null,r=$e.current,Pe($e,o?r&1|2:r&1),t):(rt(t),null);case 22:case 23:return wa(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?vt&1073741824&&(rt(t),t.subtreeFlags&6&&(t.flags|=8192)):rt(t),null;case 24:return null;case 25:return null}throw Error(s(156,t.tag))}function jg(e,t){switch(Ml(t),t.tag){case 1:return ct(t.type)&&fi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return gr(),_e(ut),_e(tt),Ul(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Bl(t),null;case 13:if(_e($e),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));fr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return _e($e),null;case 4:return gr(),null;case 10:return Ll(t.type._context),null;case 22:case 23:return wa(),null;case 24:return null;default:return null}}var Ni=!1,ot=!1,Ag=typeof WeakSet=="function"?WeakSet:Set,ne=null;function xr(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(o){De(e,t,o)}else r.current=null}function aa(e,t,r){try{r()}catch(o){De(e,t,o)}}var Gd=!1;function Rg(e,t){if(wl=Jo,e=Rc(),fl(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var a=o.anchorOffset,u=o.focusNode;o=o.focusOffset;try{r.nodeType,u.nodeType}catch{r=null;break e}var p=0,g=-1,v=-1,T=0,Y=0,q=e,U=null;t:for(;;){for(var te;q!==r||a!==0&&q.nodeType!==3||(g=p+a),q!==u||o!==0&&q.nodeType!==3||(v=p+o),q.nodeType===3&&(p+=q.nodeValue.length),(te=q.firstChild)!==null;)U=q,q=te;for(;;){if(q===e)break t;if(U===r&&++T===a&&(g=p),U===u&&++Y===o&&(v=p),(te=q.nextSibling)!==null)break;q=U,U=q.parentNode}q=te}r=g===-1||v===-1?null:{start:g,end:v}}else r=null}r=r||{start:0,end:0}}else r=null;for(Sl={focusedElem:e,selectionRange:r},Jo=!1,ne=t;ne!==null;)if(t=ne,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ne=e;else for(;ne!==null;){t=ne;try{var re=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(re!==null){var oe=re.memoizedProps,be=re.memoizedState,R=t.stateNode,C=R.getSnapshotBeforeUpdate(t.elementType===t.type?oe:Ot(t.type,oe),be);R.__reactInternalSnapshotBeforeUpdate=C}break;case 3:var M=t.stateNode.containerInfo;M.nodeType===1?M.textContent="":M.nodeType===9&&M.documentElement&&M.removeChild(M.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(s(163))}}catch(K){De(t,t.return,K)}if(e=t.sibling,e!==null){e.return=t.return,ne=e;break}ne=t.return}return re=Gd,Gd=!1,re}function xo(e,t,r){var o=t.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var a=o=o.next;do{if((a.tag&e)===e){var u=a.destroy;a.destroy=void 0,u!==void 0&&aa(t,r,u)}a=a.next}while(a!==o)}}function $i(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var o=r.create;r.destroy=o()}r=r.next}while(r!==t)}}function ua(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function Kd(e){var t=e.alternate;t!==null&&(e.alternate=null,Kd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ft],delete t[so],delete t[jl],delete t[ug],delete t[cg])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xd(e){return e.tag===5||e.tag===3||e.tag===4}function Jd(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ca(e,t,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=ci));else if(o!==4&&(e=e.child,e!==null))for(ca(e,t,r),e=e.sibling;e!==null;)ca(e,t,r),e=e.sibling}function da(e,t,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(da(e,t,r),e=e.sibling;e!==null;)da(e,t,r),e=e.sibling}var Je=null,Lt=!1;function yn(e,t,r){for(r=r.child;r!==null;)Zd(e,t,r),r=r.sibling}function Zd(e,t,r){if(Bt&&typeof Bt.onCommitFiberUnmount=="function")try{Bt.onCommitFiberUnmount(Wo,r)}catch{}switch(r.tag){case 5:ot||xr(r,t);case 6:var o=Je,a=Lt;Je=null,yn(e,t,r),Je=o,Lt=a,Je!==null&&(Lt?(e=Je,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Je.removeChild(r.stateNode));break;case 18:Je!==null&&(Lt?(e=Je,r=r.stateNode,e.nodeType===8?El(e.parentNode,r):e.nodeType===1&&El(e,r),Gr(e)):El(Je,r.stateNode));break;case 4:o=Je,a=Lt,Je=r.stateNode.containerInfo,Lt=!0,yn(e,t,r),Je=o,Lt=a;break;case 0:case 11:case 14:case 15:if(!ot&&(o=r.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var u=a,p=u.destroy;u=u.tag,p!==void 0&&(u&2||u&4)&&aa(r,t,p),a=a.next}while(a!==o)}yn(e,t,r);break;case 1:if(!ot&&(xr(r,t),o=r.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=r.memoizedProps,o.state=r.memoizedState,o.componentWillUnmount()}catch(g){De(r,t,g)}yn(e,t,r);break;case 21:yn(e,t,r);break;case 22:r.mode&1?(ot=(o=ot)||r.memoizedState!==null,yn(e,t,r),ot=o):yn(e,t,r);break;default:yn(e,t,r)}}function ef(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new Ag),t.forEach(function(o){var a=Dg.bind(null,e,o);r.has(o)||(r.add(o),o.then(a,a))})}}function Dt(e,t){var r=t.deletions;if(r!==null)for(var o=0;oa&&(a=p),o&=~u}if(o=a,o=Ie()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*Mg(o/1960))-o,10e?16:e,vn===null)var o=!1;else{if(e=vn,vn=null,bi=0,Ce&6)throw Error(s(331));var a=Ce;for(Ce|=4,ne=e.current;ne!==null;){var u=ne,p=u.child;if(ne.flags&16){var g=u.deletions;if(g!==null){for(var v=0;vIe()-ha?bn(e,0):pa|=r),pt(e,t)}function hf(e,t){t===0&&(e.mode&1?(t=Qo,Qo<<=1,!(Qo&130023424)&&(Qo=4194304)):t=1);var r=at();e=Jt(e,t),e!==null&&(Yr(e,t,r),pt(e,r))}function Lg(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),hf(e,r)}function Dg(e,t){var r=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(r=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(s(314))}o!==null&&o.delete(t),hf(e,r)}var mf;mf=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||ut.current)dt=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return dt=!1,Cg(e,t,r);dt=!!(e.flags&131072)}else dt=!1,Ne&&t.flags&1048576&&qc(t,gi,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;Ti(e,t),e=t.pendingProps;var a=ur(t,tt.current);mr(t,r),a=Vl(null,t,o,e,a,r);var u=Wl();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ct(o)?(u=!0,pi(t)):u=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,bl(t),a.updater=Mi,t.stateNode=a,a._reactInternals=t,Jl(t,o,e,r),t=na(null,t,o,!0,u,r)):(t.tag=0,Ne&&u&&Pl(t),lt(null,t,a,r),t=t.child),t;case 16:o=t.elementType;e:{switch(Ti(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=bg(o),e=Ot(o,e),a){case 0:t=ta(null,t,o,e,r);break e;case 1:t=Bd(null,t,o,e,r);break e;case 11:t=Ld(null,t,o,e,r);break e;case 14:t=Dd(null,t,o,Ot(o.type,e),r);break e}throw Error(s(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Ot(o,a),ta(e,t,o,a,r);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Ot(o,a),Bd(e,t,o,a,r);case 3:e:{if(Fd(t),e===null)throw Error(s(387));o=t.pendingProps,u=t.memoizedState,a=u.element,nd(e,t),ki(t,o,null,r);var p=t.memoizedState;if(o=p.element,u.isDehydrated)if(u={element:o,isDehydrated:!1,cache:p.cache,pendingSuspenseBoundaries:p.pendingSuspenseBoundaries,transitions:p.transitions},t.updateQueue.baseState=u,t.memoizedState=u,t.flags&256){a=yr(Error(s(423)),t),t=Ud(e,t,o,r,a);break e}else if(o!==a){a=yr(Error(s(424)),t),t=Ud(e,t,o,r,a);break e}else for(xt=dn(t.stateNode.containerInfo.firstChild),yt=t,Ne=!0,$t=null,r=ed(t,null,o,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(fr(),o===a){t=en(e,t,r);break e}lt(e,t,o,r)}t=t.child}return t;case 5:return id(t),e===null&&Tl(t),o=t.type,a=t.pendingProps,u=e!==null?e.memoizedProps:null,p=a.children,kl(o,a)?p=null:u!==null&&kl(o,u)&&(t.flags|=32),zd(e,t),lt(e,t,p,r),t.child;case 6:return e===null&&Tl(t),null;case 13:return Hd(e,t,r);case 4:return zl(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=pr(t,null,o,r):lt(e,t,o,r),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Ot(o,a),Ld(e,t,o,a,r);case 7:return lt(e,t,t.pendingProps,r),t.child;case 8:return lt(e,t,t.pendingProps.children,r),t.child;case 12:return lt(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,u=t.memoizedProps,p=a.value,Pe(vi,o._currentValue),o._currentValue=p,u!==null)if(Nt(u.value,p)){if(u.children===a.children&&!ut.current){t=en(e,t,r);break e}}else for(u=t.child,u!==null&&(u.return=t);u!==null;){var g=u.dependencies;if(g!==null){p=u.child;for(var v=g.firstContext;v!==null;){if(v.context===o){if(u.tag===1){v=Zt(-1,r&-r),v.tag=2;var T=u.updateQueue;if(T!==null){T=T.shared;var Y=T.pending;Y===null?v.next=v:(v.next=Y.next,Y.next=v),T.pending=v}}u.lanes|=r,v=u.alternate,v!==null&&(v.lanes|=r),Dl(u.return,r,t),g.lanes|=r;break}v=v.next}}else if(u.tag===10)p=u.type===t.type?null:u.child;else if(u.tag===18){if(p=u.return,p===null)throw Error(s(341));p.lanes|=r,g=p.alternate,g!==null&&(g.lanes|=r),Dl(p,r,t),p=u.sibling}else p=u.child;if(p!==null)p.return=u;else for(p=u;p!==null;){if(p===t){p=null;break}if(u=p.sibling,u!==null){u.return=p.return,p=u;break}p=p.return}u=p}lt(e,t,a.children,r),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,mr(t,r),a=At(a),o=o(a),t.flags|=1,lt(e,t,o,r),t.child;case 14:return o=t.type,a=Ot(o,t.pendingProps),a=Ot(o.type,a),Dd(e,t,o,a,r);case 15:return Id(e,t,t.type,t.pendingProps,r);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Ot(o,a),Ti(e,t),t.tag=1,ct(o)?(e=!0,pi(t)):e=!1,mr(t,r),Pd(t,o,a),Jl(t,o,a,r),na(null,t,o,!0,e,r);case 19:return Vd(e,t,r);case 22:return bd(e,t,r)}throw Error(s(156,t.tag))};function gf(e,t){return Qu(e,t)}function Ig(e,t,r,o){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Mt(e,t,r,o){return new Ig(e,t,r,o)}function ka(e){return e=e.prototype,!(!e||!e.isReactComponent)}function bg(e){if(typeof e=="function")return ka(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Be)return 11;if(e===z)return 14}return 2}function kn(e,t){var r=e.alternate;return r===null?(r=Mt(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Ui(e,t,r,o,a,u){var p=2;if(o=e,typeof e=="function")ka(e)&&(p=1);else if(typeof e=="string")p=5;else e:switch(e){case Q:return Bn(r.children,a,u,t);case le:p=8,a|=8;break;case Se:return e=Mt(12,r,t,a|2),e.elementType=Se,e.lanes=u,e;case Fe:return e=Mt(13,r,t,a),e.elementType=Fe,e.lanes=u,e;case V:return e=Mt(19,r,t,a),e.elementType=V,e.lanes=u,e;case W:return Hi(r,a,u,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ge:p=10;break e;case pe:p=9;break e;case Be:p=11;break e;case z:p=14;break e;case b:p=16,o=null;break e}throw Error(s(130,e==null?e:typeof e,""))}return t=Mt(p,r,t,a),t.elementType=e,t.type=o,t.lanes=u,t}function Bn(e,t,r,o){return e=Mt(7,e,o,t),e.lanes=r,e}function Hi(e,t,r,o){return e=Mt(22,e,o,t),e.elementType=W,e.lanes=r,e.stateNode={isHidden:!1},e}function Ca(e,t,r){return e=Mt(6,e,null,t),e.lanes=r,e}function Ea(e,t,r){return t=Mt(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function zg(e,t,r,o,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Xs(0),this.expirationTimes=Xs(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Xs(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function ja(e,t,r,o,a,u,p,g,v){return e=new zg(e,t,r,g,v),t===1?(t=1,u===!0&&(t|=8)):t=0,u=Mt(3,null,null,t),e.current=u,u.stateNode=e,u.memoizedState={element:o,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},bl(u),e}function Bg(e,t,r){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(i){console.error(i)}}return n(),Ta.exports=Jg(),Ta.exports}var Tf;function ey(){if(Tf)return Ki;Tf=1;var n=Zg();return Ki.createRoot=n.createRoot,Ki.hydrateRoot=n.hydrateRoot,Ki}var ty=ey(),st=function(){return st=Object.assign||function(i){for(var s,l=1,c=arguments.length;l0?Ke($r,--_t):0,Mr--,He===10&&(Mr=1,js--),He}function bt(){return He=_t2||eu(He)>3?"":" "}function dy(n,i){for(;--i&&bt()&&!(He<48||He>102||He>57&&He<65||He>70&&He<97););return Rs(n,ls()+(i<6&&Yn()==32&&bt()==32))}function tu(n){for(;bt();)switch(He){case n:return _t;case 34:case 39:n!==34&&n!==39&&tu(He);break;case 40:n===41&&tu(n);break;case 92:bt();break}return _t}function fy(n,i){for(;bt()&&n+He!==57;)if(n+He===84&&Yn()===47)break;return"/*"+Rs(i,_t-1)+"*"+xu(n===47?n:bt())}function py(n){for(;!eu(Yn());)bt();return Rs(n,_t)}function hy(n){return uy(as("",null,null,null,[""],n=ay(n),0,[0],n))}function as(n,i,s,l,c,d,f,m,x){for(var y=0,S=0,j=f,$=0,I=0,k=0,A=1,_=1,J=1,G=0,H="",X=c,D=d,N=l,Q=H;_;)switch(k=G,G=bt()){case 40:if(k!=108&&Ke(Q,j-1)==58){ss(Q+=ve(Oa(G),"&","&\f"),"&\f",Ip(y?m[y-1]:0))!=-1&&(J=-1);break}case 34:case 39:case 91:Q+=Oa(G);break;case 9:case 10:case 13:case 32:Q+=cy(k);break;case 92:Q+=dy(ls()-1,7);continue;case 47:switch(Yn()){case 42:case 47:Mo(my(fy(bt(),ls()),i,s,x),x);break;default:Q+="/"}break;case 123*A:m[y++]=Wt(Q)*J;case 125*A:case 59:case 0:switch(G){case 0:case 125:_=0;case 59+S:J==-1&&(Q=ve(Q,/\f/g,"")),I>0&&Wt(Q)-j&&Mo(I>32?Of(Q+";",l,s,j-1,x):Of(ve(Q," ","")+";",l,s,j-2,x),x);break;case 59:Q+=";";default:if(Mo(N=$f(Q,i,s,y,S,c,m,H,X=[],D=[],j,d),d),G===123)if(S===0)as(Q,i,N,N,X,d,j,m,D);else switch($===99&&Ke(Q,3)===110?100:$){case 100:case 108:case 109:case 115:as(n,N,N,l&&Mo($f(n,N,N,0,0,c,m,H,c,X=[],j,D),D),c,D,j,m,l?X:D);break;default:as(Q,N,N,N,[""],D,0,m,D)}}y=S=I=0,A=J=1,H=Q="",j=f;break;case 58:j=1+Wt(Q),I=k;default:if(A<1){if(G==123)--A;else if(G==125&&A++==0&&ly()==125)continue}switch(Q+=xu(G),G*A){case 38:J=S>0?1:(Q+="\f",-1);break;case 44:m[y++]=(Wt(Q)-1)*J,J=1;break;case 64:Yn()===45&&(Q+=Oa(bt())),$=Yn(),S=j=Wt(H=Q+=py(ls())),G++;break;case 45:k===45&&Wt(Q)==2&&(A=0)}}return d}function $f(n,i,s,l,c,d,f,m,x,y,S,j){for(var $=c-1,I=c===0?d:[""],k=zp(I),A=0,_=0,J=0;A0?I[G]+" "+H:ve(H,/&\f/g,I[G])))&&(x[J++]=X);return As(n,i,s,c===0?Es:m,x,y,S,j)}function my(n,i,s,l){return As(n,i,s,Lp,xu(sy()),Pr(n,2,-2),0,l)}function Of(n,i,s,l,c){return As(n,i,s,yu,Pr(n,0,l),Pr(n,l+1,-1),l,c)}function Fp(n,i,s){switch(oy(n,i)){case 5103:return Ae+"print-"+n+n;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return Ae+n+n;case 4789:return _o+n+n;case 5349:case 4246:case 4810:case 6968:case 2756:return Ae+n+_o+n+Te+n+n;case 5936:switch(Ke(n,i+11)){case 114:return Ae+n+Te+ve(n,/[svh]\w+-[tblr]{2}/,"tb")+n;case 108:return Ae+n+Te+ve(n,/[svh]\w+-[tblr]{2}/,"tb-rl")+n;case 45:return Ae+n+Te+ve(n,/[svh]\w+-[tblr]{2}/,"lr")+n}case 6828:case 4268:case 2903:return Ae+n+Te+n+n;case 6165:return Ae+n+Te+"flex-"+n+n;case 5187:return Ae+n+ve(n,/(\w+).+(:[^]+)/,Ae+"box-$1$2"+Te+"flex-$1$2")+n;case 5443:return Ae+n+Te+"flex-item-"+ve(n,/flex-|-self/g,"")+(nn(n,/flex-|baseline/)?"":Te+"grid-row-"+ve(n,/flex-|-self/g,""))+n;case 4675:return Ae+n+Te+"flex-line-pack"+ve(n,/align-content|flex-|-self/g,"")+n;case 5548:return Ae+n+Te+ve(n,"shrink","negative")+n;case 5292:return Ae+n+Te+ve(n,"basis","preferred-size")+n;case 6060:return Ae+"box-"+ve(n,"-grow","")+Ae+n+Te+ve(n,"grow","positive")+n;case 4554:return Ae+ve(n,/([^-])(transform)/g,"$1"+Ae+"$2")+n;case 6187:return ve(ve(ve(n,/(zoom-|grab)/,Ae+"$1"),/(image-set)/,Ae+"$1"),n,"")+n;case 5495:case 3959:return ve(n,/(image-set\([^]*)/,Ae+"$1$`$1");case 4968:return ve(ve(n,/(.+:)(flex-)?(.*)/,Ae+"box-pack:$3"+Te+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+Ae+n+n;case 4200:if(!nn(n,/flex-|baseline/))return Te+"grid-column-align"+Pr(n,i)+n;break;case 2592:case 3360:return Te+ve(n,"template-","")+n;case 4384:case 3616:return s&&s.some(function(l,c){return i=c,nn(l.props,/grid-\w+-end/)})?~ss(n+(s=s[i].value),"span",0)?n:Te+ve(n,"-start","")+n+Te+"grid-row-span:"+(~ss(s,"span",0)?nn(s,/\d+/):+nn(s,/\d+/)-+nn(n,/\d+/))+";":Te+ve(n,"-start","")+n;case 4896:case 4128:return s&&s.some(function(l){return nn(l.props,/grid-\w+-start/)})?n:Te+ve(ve(n,"-end","-span"),"span ","")+n;case 4095:case 3583:case 4068:case 2532:return ve(n,/(.+)-inline(.+)/,Ae+"$1$2")+n;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(Wt(n)-1-i>6)switch(Ke(n,i+1)){case 109:if(Ke(n,i+4)!==45)break;case 102:return ve(n,/(.+:)(.+)-([^]+)/,"$1"+Ae+"$2-$3$1"+_o+(Ke(n,i+3)==108?"$3":"$2-$3"))+n;case 115:return~ss(n,"stretch",0)?Fp(ve(n,"stretch","fill-available"),i,s)+n:n}break;case 5152:case 5920:return ve(n,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(l,c,d,f,m,x,y){return Te+c+":"+d+y+(f?Te+c+"-span:"+(m?x:+x-+d)+y:"")+n});case 4949:if(Ke(n,i+6)===121)return ve(n,":",":"+Ae)+n;break;case 6444:switch(Ke(n,Ke(n,14)===45?18:11)){case 120:return ve(n,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+Ae+(Ke(n,14)===45?"inline-":"")+"box$3$1"+Ae+"$2$3$1"+Te+"$2box$3")+n;case 100:return ve(n,":",":"+Te)+n}break;case 5719:case 2647:case 2135:case 3927:case 2391:return ve(n,"scroll-","scroll-snap-")+n}return n}function xs(n,i){for(var s="",l=0;l-1&&!n.return)switch(n.type){case yu:n.return=Fp(n.value,n.length,s);return;case Dp:return xs([En(n,{value:ve(n.value,"@","@"+Ae)})],l);case Es:if(n.length)return iy(s=n.props,function(c){switch(nn(c,l=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":kr(En(n,{props:[ve(c,/:(read-\w+)/,":"+_o+"$1")]})),kr(En(n,{props:[c]})),Za(n,{props:Nf(s,l)});break;case"::placeholder":kr(En(n,{props:[ve(c,/:(plac\w+)/,":"+Ae+"input-$1")]})),kr(En(n,{props:[ve(c,/:(plac\w+)/,":"+_o+"$1")]})),kr(En(n,{props:[ve(c,/:(plac\w+)/,Te+"input-$1")]})),kr(En(n,{props:[c]})),Za(n,{props:Nf(s,l)});break}return""})}}var wy={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},wt={},_r=typeof process<"u"&&wt!==void 0&&(wt.REACT_APP_SC_ATTR||wt.SC_ATTR)||"data-styled",Up="active",Hp="data-styled-version",Ps="6.1.14",vu=`/*!sc*/ +`,vs=typeof window<"u"&&"HTMLElement"in window,Sy=!!(typeof SC_DISABLE_SPEEDY=="boolean"?SC_DISABLE_SPEEDY:typeof process<"u"&&wt!==void 0&&wt.REACT_APP_SC_DISABLE_SPEEDY!==void 0&&wt.REACT_APP_SC_DISABLE_SPEEDY!==""?wt.REACT_APP_SC_DISABLE_SPEEDY!=="false"&&wt.REACT_APP_SC_DISABLE_SPEEDY:typeof process<"u"&&wt!==void 0&&wt.SC_DISABLE_SPEEDY!==void 0&&wt.SC_DISABLE_SPEEDY!==""&&wt.SC_DISABLE_SPEEDY!=="false"&&wt.SC_DISABLE_SPEEDY),Ms=Object.freeze([]),Tr=Object.freeze({});function ky(n,i,s){return s===void 0&&(s=Tr),n.theme!==s.theme&&n.theme||i||s.theme}var Yp=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","track","u","ul","use","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"]),Cy=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,Ey=/(^-|-$)/g;function Lf(n){return n.replace(Cy,"-").replace(Ey,"")}var jy=/(a)(d)/gi,Xi=52,Df=function(n){return String.fromCharCode(n+(n>25?39:97))};function nu(n){var i,s="";for(i=Math.abs(n);i>Xi;i=i/Xi|0)s=Df(i%Xi)+s;return(Df(i%Xi)+s).replace(jy,"$1-$2")}var La,Vp=5381,Er=function(n,i){for(var s=i.length;s;)n=33*n^i.charCodeAt(--s);return n},Wp=function(n){return Er(Vp,n)};function Ay(n){return nu(Wp(n)>>>0)}function Ry(n){return n.displayName||n.name||"Component"}function Da(n){return typeof n=="string"&&!0}var qp=typeof Symbol=="function"&&Symbol.for,Qp=qp?Symbol.for("react.memo"):60115,Py=qp?Symbol.for("react.forward_ref"):60112,My={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},_y={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Gp={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Ty=((La={})[Py]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},La[Qp]=Gp,La);function If(n){return("type"in(i=n)&&i.type.$$typeof)===Qp?Gp:"$$typeof"in n?Ty[n.$$typeof]:My;var i}var Ny=Object.defineProperty,$y=Object.getOwnPropertyNames,bf=Object.getOwnPropertySymbols,Oy=Object.getOwnPropertyDescriptor,Ly=Object.getPrototypeOf,zf=Object.prototype;function Kp(n,i,s){if(typeof i!="string"){if(zf){var l=Ly(i);l&&l!==zf&&Kp(n,l,s)}var c=$y(i);bf&&(c=c.concat(bf(i)));for(var d=If(n),f=If(i),m=0;m0?" Args: ".concat(i.join(", ")):""))}var Dy=function(){function n(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}return n.prototype.indexOfGroup=function(i){for(var s=0,l=0;l=this.groupSizes.length){for(var l=this.groupSizes,c=l.length,d=c;i>=d;)if((d<<=1)<0)throw Qn(16,"".concat(i));this.groupSizes=new Uint32Array(d),this.groupSizes.set(l),this.length=d;for(var f=c;f=this.length||this.groupSizes[i]===0)return s;for(var l=this.groupSizes[i],c=this.indexOfGroup(i),d=c+l,f=c;f=0){var l=document.createTextNode(s);return this.element.insertBefore(l,this.nodes[i]||null),this.length++,!0}return!1},n.prototype.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},n.prototype.getRule=function(i){return i0&&(_+="".concat(J,","))}),x+="".concat(k).concat(A,'{content:"').concat(_,'"}').concat(vu)},S=0;S0?".".concat(i):$},S=x.slice();S.push(function($){$.type===Es&&$.value.includes("&")&&($.props[0]=$.props[0].replace(qy,s).replace(l,y))}),f.prefix&&S.push(vy),S.push(gy);var j=function($,I,k,A){I===void 0&&(I=""),k===void 0&&(k=""),A===void 0&&(A="&"),i=A,s=I,l=new RegExp("\\".concat(s,"\\b"),"g");var _=$.replace(Qy,""),J=hy(k||I?"".concat(k," ").concat(I," { ").concat(_," }"):_);f.namespace&&(J=Zp(J,f.namespace));var G=[];return xs(J,yy(S.concat(xy(function(H){return G.push(H)})))),G};return j.hash=x.length?x.reduce(function($,I){return I.name||Qn(15),Er($,I.name)},Vp).toString():"",j}var Ky=new Jp,ou=Gy(),eh=St.createContext({shouldForwardProp:void 0,styleSheet:Ky,stylis:ou});eh.Consumer;St.createContext(void 0);function Hf(){return Z.useContext(eh)}var Xy=function(){function n(i,s){var l=this;this.inject=function(c,d){d===void 0&&(d=ou);var f=l.name+d.hash;c.hasNameForId(l.id,f)||c.insertRules(l.id,f,d(l.rules,f,"@keyframes"))},this.name=i,this.id="sc-keyframes-".concat(i),this.rules=s,Su(this,function(){throw Qn(12,String(l.name))})}return n.prototype.getName=function(i){return i===void 0&&(i=ou),this.name+i.hash},n}(),Jy=function(n){return n>="A"&&n<="Z"};function Yf(n){for(var i="",s=0;s>>0);if(!s.hasNameForId(this.componentId,f)){var m=l(d,".".concat(f),void 0,this.componentId);s.insertRules(this.componentId,f,m)}c=Un(c,f),this.staticRulesId=f}else{for(var x=Er(this.baseHash,l.hash),y="",S=0;S>>0);s.hasNameForId(this.componentId,I)||s.insertRules(this.componentId,I,l(y,".".concat(I),void 0,this.componentId)),c=Un(c,I)}}return c},n}(),Ss=St.createContext(void 0);Ss.Consumer;function Vf(n){var i=St.useContext(Ss),s=Z.useMemo(function(){return function(l,c){if(!l)throw Qn(14);if(qn(l)){var d=l(c);return d}if(Array.isArray(l)||typeof l!="object")throw Qn(8);return c?st(st({},c),l):l}(n.theme,i)},[n.theme,i]);return n.children?St.createElement(Ss.Provider,{value:s},n.children):null}var Ia={};function n0(n,i,s){var l=wu(n),c=n,d=!Da(n),f=i.attrs,m=f===void 0?Ms:f,x=i.componentId,y=x===void 0?function(X,D){var N=typeof X!="string"?"sc":Lf(X);Ia[N]=(Ia[N]||0)+1;var Q="".concat(N,"-").concat(Ay(Ps+N+Ia[N]));return D?"".concat(D,"-").concat(Q):Q}(i.displayName,i.parentComponentId):x,S=i.displayName,j=S===void 0?function(X){return Da(X)?"styled.".concat(X):"Styled(".concat(Ry(X),")")}(n):S,$=i.displayName&&i.componentId?"".concat(Lf(i.displayName),"-").concat(i.componentId):i.componentId||y,I=l&&c.attrs?c.attrs.concat(m).filter(Boolean):m,k=i.shouldForwardProp;if(l&&c.shouldForwardProp){var A=c.shouldForwardProp;if(i.shouldForwardProp){var _=i.shouldForwardProp;k=function(X,D){return A(X,D)&&_(X,D)}}else k=A}var J=new t0(s,$,l?c.componentStyle:void 0);function G(X,D){return function(N,Q,le){var Se=N.attrs,ge=N.componentStyle,pe=N.defaultProps,Be=N.foldedComponentIds,Fe=N.styledComponentId,V=N.target,z=St.useContext(Ss),b=Hf(),W=N.shouldForwardProp||b.shouldForwardProp,P=ky(Q,z,pe)||Tr,F=function(de,he,we){for(var ye,xe=st(st({},he),{className:void 0,theme:we}),Ee=0;Ee{let i;const s=new Set,l=(y,S)=>{const j=typeof y=="function"?y(i):y;if(!Object.is(j,i)){const $=i;i=S??(typeof j!="object"||j===null)?j:Object.assign({},i,j),s.forEach(I=>I(i,$))}},c=()=>i,m={setState:l,getState:c,getInitialState:()=>x,subscribe:y=>(s.add(y),()=>s.delete(y))},x=i=n(l,c,m);return m},o0=n=>n?Qf(n):Qf,i0=n=>n;function s0(n,i=i0){const s=St.useSyncExternalStore(n.subscribe,()=>i(n.getState()),()=>i(n.getInitialState()));return St.useDebugValue(s),s}const Gf=n=>{const i=o0(n),s=l=>s0(i,l);return Object.assign(s,i),s},Kn=n=>n?Gf(n):Gf;function oh(n,i){return function(){return n.apply(i,arguments)}}const{toString:l0}=Object.prototype,{getPrototypeOf:ku}=Object,_s=(n=>i=>{const s=l0.call(i);return n[s]||(n[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),zt=n=>(n=n.toLowerCase(),i=>_s(i)===n),Ts=n=>i=>typeof i===n,{isArray:Or}=Array,Do=Ts("undefined");function a0(n){return n!==null&&!Do(n)&&n.constructor!==null&&!Do(n.constructor)&&kt(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}const ih=zt("ArrayBuffer");function u0(n){let i;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?i=ArrayBuffer.isView(n):i=n&&n.buffer&&ih(n.buffer),i}const c0=Ts("string"),kt=Ts("function"),sh=Ts("number"),Ns=n=>n!==null&&typeof n=="object",d0=n=>n===!0||n===!1,ds=n=>{if(_s(n)!=="object")return!1;const i=ku(n);return(i===null||i===Object.prototype||Object.getPrototypeOf(i)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},f0=zt("Date"),p0=zt("File"),h0=zt("Blob"),m0=zt("FileList"),g0=n=>Ns(n)&&kt(n.pipe),y0=n=>{let i;return n&&(typeof FormData=="function"&&n instanceof FormData||kt(n.append)&&((i=_s(n))==="formdata"||i==="object"&&kt(n.toString)&&n.toString()==="[object FormData]"))},x0=zt("URLSearchParams"),[v0,w0,S0,k0]=["ReadableStream","Request","Response","Headers"].map(zt),C0=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function bo(n,i,{allOwnKeys:s=!1}={}){if(n===null||typeof n>"u")return;let l,c;if(typeof n!="object"&&(n=[n]),Or(n))for(l=0,c=n.length;l0;)if(c=s[l],i===c.toLowerCase())return c;return null}const Hn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ah=n=>!Do(n)&&n!==Hn;function su(){const{caseless:n}=ah(this)&&this||{},i={},s=(l,c)=>{const d=n&&lh(i,c)||c;ds(i[d])&&ds(l)?i[d]=su(i[d],l):ds(l)?i[d]=su({},l):Or(l)?i[d]=l.slice():i[d]=l};for(let l=0,c=arguments.length;l(bo(i,(c,d)=>{s&&kt(c)?n[d]=oh(c,s):n[d]=c},{allOwnKeys:l}),n),j0=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),A0=(n,i,s,l)=>{n.prototype=Object.create(i.prototype,l),n.prototype.constructor=n,Object.defineProperty(n,"super",{value:i.prototype}),s&&Object.assign(n.prototype,s)},R0=(n,i,s,l)=>{let c,d,f;const m={};if(i=i||{},n==null)return i;do{for(c=Object.getOwnPropertyNames(n),d=c.length;d-- >0;)f=c[d],(!l||l(f,n,i))&&!m[f]&&(i[f]=n[f],m[f]=!0);n=s!==!1&&ku(n)}while(n&&(!s||s(n,i))&&n!==Object.prototype);return i},P0=(n,i,s)=>{n=String(n),(s===void 0||s>n.length)&&(s=n.length),s-=i.length;const l=n.indexOf(i,s);return l!==-1&&l===s},M0=n=>{if(!n)return null;if(Or(n))return n;let i=n.length;if(!sh(i))return null;const s=new Array(i);for(;i-- >0;)s[i]=n[i];return s},_0=(n=>i=>n&&i instanceof n)(typeof Uint8Array<"u"&&ku(Uint8Array)),T0=(n,i)=>{const l=(n&&n[Symbol.iterator]).call(n);let c;for(;(c=l.next())&&!c.done;){const d=c.value;i.call(n,d[0],d[1])}},N0=(n,i)=>{let s;const l=[];for(;(s=n.exec(i))!==null;)l.push(s);return l},$0=zt("HTMLFormElement"),O0=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,l,c){return l.toUpperCase()+c}),Kf=(({hasOwnProperty:n})=>(i,s)=>n.call(i,s))(Object.prototype),L0=zt("RegExp"),uh=(n,i)=>{const s=Object.getOwnPropertyDescriptors(n),l={};bo(s,(c,d)=>{let f;(f=i(c,d,n))!==!1&&(l[d]=f||c)}),Object.defineProperties(n,l)},D0=n=>{uh(n,(i,s)=>{if(kt(n)&&["arguments","caller","callee"].indexOf(s)!==-1)return!1;const l=n[s];if(kt(l)){if(i.enumerable=!1,"writable"in i){i.writable=!1;return}i.set||(i.set=()=>{throw Error("Can not rewrite read-only method '"+s+"'")})}})},I0=(n,i)=>{const s={},l=c=>{c.forEach(d=>{s[d]=!0})};return Or(n)?l(n):l(String(n).split(i)),s},b0=()=>{},z0=(n,i)=>n!=null&&Number.isFinite(n=+n)?n:i,ba="abcdefghijklmnopqrstuvwxyz",Xf="0123456789",ch={DIGIT:Xf,ALPHA:ba,ALPHA_DIGIT:ba+ba.toUpperCase()+Xf},B0=(n=16,i=ch.ALPHA_DIGIT)=>{let s="";const{length:l}=i;for(;n--;)s+=i[Math.random()*l|0];return s};function F0(n){return!!(n&&kt(n.append)&&n[Symbol.toStringTag]==="FormData"&&n[Symbol.iterator])}const U0=n=>{const i=new Array(10),s=(l,c)=>{if(Ns(l)){if(i.indexOf(l)>=0)return;if(!("toJSON"in l)){i[c]=l;const d=Or(l)?[]:{};return bo(l,(f,m)=>{const x=s(f,c+1);!Do(x)&&(d[m]=x)}),i[c]=void 0,d}}return l};return s(n,0)},H0=zt("AsyncFunction"),Y0=n=>n&&(Ns(n)||kt(n))&&kt(n.then)&&kt(n.catch),dh=((n,i)=>n?setImmediate:i?((s,l)=>(Hn.addEventListener("message",({source:c,data:d})=>{c===Hn&&d===s&&l.length&&l.shift()()},!1),c=>{l.push(c),Hn.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",kt(Hn.postMessage)),V0=typeof queueMicrotask<"u"?queueMicrotask.bind(Hn):typeof process<"u"&&process.nextTick||dh,O={isArray:Or,isArrayBuffer:ih,isBuffer:a0,isFormData:y0,isArrayBufferView:u0,isString:c0,isNumber:sh,isBoolean:d0,isObject:Ns,isPlainObject:ds,isReadableStream:v0,isRequest:w0,isResponse:S0,isHeaders:k0,isUndefined:Do,isDate:f0,isFile:p0,isBlob:h0,isRegExp:L0,isFunction:kt,isStream:g0,isURLSearchParams:x0,isTypedArray:_0,isFileList:m0,forEach:bo,merge:su,extend:E0,trim:C0,stripBOM:j0,inherits:A0,toFlatObject:R0,kindOf:_s,kindOfTest:zt,endsWith:P0,toArray:M0,forEachEntry:T0,matchAll:N0,isHTMLForm:$0,hasOwnProperty:Kf,hasOwnProp:Kf,reduceDescriptors:uh,freezeMethods:D0,toObjectSet:I0,toCamelCase:O0,noop:b0,toFiniteNumber:z0,findKey:lh,global:Hn,isContextDefined:ah,ALPHABET:ch,generateString:B0,isSpecCompliantForm:F0,toJSONObject:U0,isAsyncFn:H0,isThenable:Y0,setImmediate:dh,asap:V0};function me(n,i,s,l,c){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=n,this.name="AxiosError",i&&(this.code=i),s&&(this.config=s),l&&(this.request=l),c&&(this.response=c,this.status=c.status?c.status:null)}O.inherits(me,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:O.toJSONObject(this.config),code:this.code,status:this.status}}});const fh=me.prototype,ph={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(n=>{ph[n]={value:n}});Object.defineProperties(me,ph);Object.defineProperty(fh,"isAxiosError",{value:!0});me.from=(n,i,s,l,c,d)=>{const f=Object.create(fh);return O.toFlatObject(n,f,function(x){return x!==Error.prototype},m=>m!=="isAxiosError"),me.call(f,n.message,i,s,l,c),f.cause=n,f.name=n.name,d&&Object.assign(f,d),f};const W0=null;function lu(n){return O.isPlainObject(n)||O.isArray(n)}function hh(n){return O.endsWith(n,"[]")?n.slice(0,-2):n}function Jf(n,i,s){return n?n.concat(i).map(function(c,d){return c=hh(c),!s&&d?"["+c+"]":c}).join(s?".":""):i}function q0(n){return O.isArray(n)&&!n.some(lu)}const Q0=O.toFlatObject(O,{},null,function(i){return/^is[A-Z]/.test(i)});function $s(n,i,s){if(!O.isObject(n))throw new TypeError("target must be an object");i=i||new FormData,s=O.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(A,_){return!O.isUndefined(_[A])});const l=s.metaTokens,c=s.visitor||S,d=s.dots,f=s.indexes,x=(s.Blob||typeof Blob<"u"&&Blob)&&O.isSpecCompliantForm(i);if(!O.isFunction(c))throw new TypeError("visitor must be a function");function y(k){if(k===null)return"";if(O.isDate(k))return k.toISOString();if(!x&&O.isBlob(k))throw new me("Blob is not supported. Use a Buffer instead.");return O.isArrayBuffer(k)||O.isTypedArray(k)?x&&typeof Blob=="function"?new Blob([k]):Buffer.from(k):k}function S(k,A,_){let J=k;if(k&&!_&&typeof k=="object"){if(O.endsWith(A,"{}"))A=l?A:A.slice(0,-2),k=JSON.stringify(k);else if(O.isArray(k)&&q0(k)||(O.isFileList(k)||O.endsWith(A,"[]"))&&(J=O.toArray(k)))return A=hh(A),J.forEach(function(H,X){!(O.isUndefined(H)||H===null)&&i.append(f===!0?Jf([A],X,d):f===null?A:A+"[]",y(H))}),!1}return lu(k)?!0:(i.append(Jf(_,A,d),y(k)),!1)}const j=[],$=Object.assign(Q0,{defaultVisitor:S,convertValue:y,isVisitable:lu});function I(k,A){if(!O.isUndefined(k)){if(j.indexOf(k)!==-1)throw Error("Circular reference detected in "+A.join("."));j.push(k),O.forEach(k,function(J,G){(!(O.isUndefined(J)||J===null)&&c.call(i,J,O.isString(G)?G.trim():G,A,$))===!0&&I(J,A?A.concat(G):[G])}),j.pop()}}if(!O.isObject(n))throw new TypeError("data must be an object");return I(n),i}function Zf(n){const i={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g,function(l){return i[l]})}function Cu(n,i){this._pairs=[],n&&$s(n,this,i)}const mh=Cu.prototype;mh.append=function(i,s){this._pairs.push([i,s])};mh.toString=function(i){const s=i?function(l){return i.call(this,l,Zf)}:Zf;return this._pairs.map(function(c){return s(c[0])+"="+s(c[1])},"").join("&")};function G0(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function gh(n,i,s){if(!i)return n;const l=s&&s.encode||G0;O.isFunction(s)&&(s={serialize:s});const c=s&&s.serialize;let d;if(c?d=c(i,s):d=O.isURLSearchParams(i)?i.toString():new Cu(i,s).toString(l),d){const f=n.indexOf("#");f!==-1&&(n=n.slice(0,f)),n+=(n.indexOf("?")===-1?"?":"&")+d}return n}class ep{constructor(){this.handlers=[]}use(i,s,l){return this.handlers.push({fulfilled:i,rejected:s,synchronous:l?l.synchronous:!1,runWhen:l?l.runWhen:null}),this.handlers.length-1}eject(i){this.handlers[i]&&(this.handlers[i]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(i){O.forEach(this.handlers,function(l){l!==null&&i(l)})}}const yh={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},K0=typeof URLSearchParams<"u"?URLSearchParams:Cu,X0=typeof FormData<"u"?FormData:null,J0=typeof Blob<"u"?Blob:null,Z0={isBrowser:!0,classes:{URLSearchParams:K0,FormData:X0,Blob:J0},protocols:["http","https","file","blob","url","data"]},Eu=typeof window<"u"&&typeof document<"u",au=typeof navigator=="object"&&navigator||void 0,ex=Eu&&(!au||["ReactNative","NativeScript","NS"].indexOf(au.product)<0),tx=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",nx=Eu&&window.location.href||"http://localhost",rx=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Eu,hasStandardBrowserEnv:ex,hasStandardBrowserWebWorkerEnv:tx,navigator:au,origin:nx},Symbol.toStringTag,{value:"Module"})),it={...rx,...Z0};function ox(n,i){return $s(n,new it.classes.URLSearchParams,Object.assign({visitor:function(s,l,c,d){return it.isNode&&O.isBuffer(s)?(this.append(l,s.toString("base64")),!1):d.defaultVisitor.apply(this,arguments)}},i))}function ix(n){return O.matchAll(/\w+|\[(\w*)]/g,n).map(i=>i[0]==="[]"?"":i[1]||i[0])}function sx(n){const i={},s=Object.keys(n);let l;const c=s.length;let d;for(l=0;l=s.length;return f=!f&&O.isArray(c)?c.length:f,x?(O.hasOwnProp(c,f)?c[f]=[c[f],l]:c[f]=l,!m):((!c[f]||!O.isObject(c[f]))&&(c[f]=[]),i(s,l,c[f],d)&&O.isArray(c[f])&&(c[f]=sx(c[f])),!m)}if(O.isFormData(n)&&O.isFunction(n.entries)){const s={};return O.forEachEntry(n,(l,c)=>{i(ix(l),c,s,0)}),s}return null}function lx(n,i,s){if(O.isString(n))try{return(i||JSON.parse)(n),O.trim(n)}catch(l){if(l.name!=="SyntaxError")throw l}return(0,JSON.stringify)(n)}const zo={transitional:yh,adapter:["xhr","http","fetch"],transformRequest:[function(i,s){const l=s.getContentType()||"",c=l.indexOf("application/json")>-1,d=O.isObject(i);if(d&&O.isHTMLForm(i)&&(i=new FormData(i)),O.isFormData(i))return c?JSON.stringify(xh(i)):i;if(O.isArrayBuffer(i)||O.isBuffer(i)||O.isStream(i)||O.isFile(i)||O.isBlob(i)||O.isReadableStream(i))return i;if(O.isArrayBufferView(i))return i.buffer;if(O.isURLSearchParams(i))return s.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),i.toString();let m;if(d){if(l.indexOf("application/x-www-form-urlencoded")>-1)return ox(i,this.formSerializer).toString();if((m=O.isFileList(i))||l.indexOf("multipart/form-data")>-1){const x=this.env&&this.env.FormData;return $s(m?{"files[]":i}:i,x&&new x,this.formSerializer)}}return d||c?(s.setContentType("application/json",!1),lx(i)):i}],transformResponse:[function(i){const s=this.transitional||zo.transitional,l=s&&s.forcedJSONParsing,c=this.responseType==="json";if(O.isResponse(i)||O.isReadableStream(i))return i;if(i&&O.isString(i)&&(l&&!this.responseType||c)){const f=!(s&&s.silentJSONParsing)&&c;try{return JSON.parse(i)}catch(m){if(f)throw m.name==="SyntaxError"?me.from(m,me.ERR_BAD_RESPONSE,this,null,this.response):m}}return i}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:it.classes.FormData,Blob:it.classes.Blob},validateStatus:function(i){return i>=200&&i<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};O.forEach(["delete","get","head","post","put","patch"],n=>{zo.headers[n]={}});const ax=O.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ux=n=>{const i={};let s,l,c;return n&&n.split(` +`).forEach(function(f){c=f.indexOf(":"),s=f.substring(0,c).trim().toLowerCase(),l=f.substring(c+1).trim(),!(!s||i[s]&&ax[s])&&(s==="set-cookie"?i[s]?i[s].push(l):i[s]=[l]:i[s]=i[s]?i[s]+", "+l:l)}),i},tp=Symbol("internals");function Eo(n){return n&&String(n).trim().toLowerCase()}function fs(n){return n===!1||n==null?n:O.isArray(n)?n.map(fs):String(n)}function cx(n){const i=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let l;for(;l=s.exec(n);)i[l[1]]=l[2];return i}const dx=n=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function za(n,i,s,l,c){if(O.isFunction(l))return l.call(this,i,s);if(c&&(i=s),!!O.isString(i)){if(O.isString(l))return i.indexOf(l)!==-1;if(O.isRegExp(l))return l.test(i)}}function fx(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(i,s,l)=>s.toUpperCase()+l)}function px(n,i){const s=O.toCamelCase(" "+i);["get","set","has"].forEach(l=>{Object.defineProperty(n,l+s,{value:function(c,d,f){return this[l].call(this,i,c,d,f)},configurable:!0})})}class mt{constructor(i){i&&this.set(i)}set(i,s,l){const c=this;function d(m,x,y){const S=Eo(x);if(!S)throw new Error("header name must be a non-empty string");const j=O.findKey(c,S);(!j||c[j]===void 0||y===!0||y===void 0&&c[j]!==!1)&&(c[j||x]=fs(m))}const f=(m,x)=>O.forEach(m,(y,S)=>d(y,S,x));if(O.isPlainObject(i)||i instanceof this.constructor)f(i,s);else if(O.isString(i)&&(i=i.trim())&&!dx(i))f(ux(i),s);else if(O.isHeaders(i))for(const[m,x]of i.entries())d(x,m,l);else i!=null&&d(s,i,l);return this}get(i,s){if(i=Eo(i),i){const l=O.findKey(this,i);if(l){const c=this[l];if(!s)return c;if(s===!0)return cx(c);if(O.isFunction(s))return s.call(this,c,l);if(O.isRegExp(s))return s.exec(c);throw new TypeError("parser must be boolean|regexp|function")}}}has(i,s){if(i=Eo(i),i){const l=O.findKey(this,i);return!!(l&&this[l]!==void 0&&(!s||za(this,this[l],l,s)))}return!1}delete(i,s){const l=this;let c=!1;function d(f){if(f=Eo(f),f){const m=O.findKey(l,f);m&&(!s||za(l,l[m],m,s))&&(delete l[m],c=!0)}}return O.isArray(i)?i.forEach(d):d(i),c}clear(i){const s=Object.keys(this);let l=s.length,c=!1;for(;l--;){const d=s[l];(!i||za(this,this[d],d,i,!0))&&(delete this[d],c=!0)}return c}normalize(i){const s=this,l={};return O.forEach(this,(c,d)=>{const f=O.findKey(l,d);if(f){s[f]=fs(c),delete s[d];return}const m=i?fx(d):String(d).trim();m!==d&&delete s[d],s[m]=fs(c),l[m]=!0}),this}concat(...i){return this.constructor.concat(this,...i)}toJSON(i){const s=Object.create(null);return O.forEach(this,(l,c)=>{l!=null&&l!==!1&&(s[c]=i&&O.isArray(l)?l.join(", "):l)}),s}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([i,s])=>i+": "+s).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(i){return i instanceof this?i:new this(i)}static concat(i,...s){const l=new this(i);return s.forEach(c=>l.set(c)),l}static accessor(i){const l=(this[tp]=this[tp]={accessors:{}}).accessors,c=this.prototype;function d(f){const m=Eo(f);l[m]||(px(c,f),l[m]=!0)}return O.isArray(i)?i.forEach(d):d(i),this}}mt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);O.reduceDescriptors(mt.prototype,({value:n},i)=>{let s=i[0].toUpperCase()+i.slice(1);return{get:()=>n,set(l){this[s]=l}}});O.freezeMethods(mt);function Ba(n,i){const s=this||zo,l=i||s,c=mt.from(l.headers);let d=l.data;return O.forEach(n,function(m){d=m.call(s,d,c.normalize(),i?i.status:void 0)}),c.normalize(),d}function vh(n){return!!(n&&n.__CANCEL__)}function Lr(n,i,s){me.call(this,n??"canceled",me.ERR_CANCELED,i,s),this.name="CanceledError"}O.inherits(Lr,me,{__CANCEL__:!0});function wh(n,i,s){const l=s.config.validateStatus;!s.status||!l||l(s.status)?n(s):i(new me("Request failed with status code "+s.status,[me.ERR_BAD_REQUEST,me.ERR_BAD_RESPONSE][Math.floor(s.status/100)-4],s.config,s.request,s))}function hx(n){const i=/^([-+\w]{1,25})(:?\/\/|:)/.exec(n);return i&&i[1]||""}function mx(n,i){n=n||10;const s=new Array(n),l=new Array(n);let c=0,d=0,f;return i=i!==void 0?i:1e3,function(x){const y=Date.now(),S=l[d];f||(f=y),s[c]=x,l[c]=y;let j=d,$=0;for(;j!==c;)$+=s[j++],j=j%n;if(c=(c+1)%n,c===d&&(d=(d+1)%n),y-f{s=S,c=null,d&&(clearTimeout(d),d=null),n.apply(null,y)};return[(...y)=>{const S=Date.now(),j=S-s;j>=l?f(y,S):(c=y,d||(d=setTimeout(()=>{d=null,f(c)},l-j)))},()=>c&&f(c)]}const ks=(n,i,s=3)=>{let l=0;const c=mx(50,250);return gx(d=>{const f=d.loaded,m=d.lengthComputable?d.total:void 0,x=f-l,y=c(x),S=f<=m;l=f;const j={loaded:f,total:m,progress:m?f/m:void 0,bytes:x,rate:y||void 0,estimated:y&&m&&S?(m-f)/y:void 0,event:d,lengthComputable:m!=null,[i?"download":"upload"]:!0};n(j)},s)},np=(n,i)=>{const s=n!=null;return[l=>i[0]({lengthComputable:s,total:n,loaded:l}),i[1]]},rp=n=>(...i)=>O.asap(()=>n(...i)),yx=it.hasStandardBrowserEnv?((n,i)=>s=>(s=new URL(s,it.origin),n.protocol===s.protocol&&n.host===s.host&&(i||n.port===s.port)))(new URL(it.origin),it.navigator&&/(msie|trident)/i.test(it.navigator.userAgent)):()=>!0,xx=it.hasStandardBrowserEnv?{write(n,i,s,l,c,d){const f=[n+"="+encodeURIComponent(i)];O.isNumber(s)&&f.push("expires="+new Date(s).toGMTString()),O.isString(l)&&f.push("path="+l),O.isString(c)&&f.push("domain="+c),d===!0&&f.push("secure"),document.cookie=f.join("; ")},read(n){const i=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return i?decodeURIComponent(i[3]):null},remove(n){this.write(n,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function vx(n){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function wx(n,i){return i?n.replace(/\/?\/$/,"")+"/"+i.replace(/^\/+/,""):n}function Sh(n,i){return n&&!vx(i)?wx(n,i):i}const op=n=>n instanceof mt?{...n}:n;function Gn(n,i){i=i||{};const s={};function l(y,S,j,$){return O.isPlainObject(y)&&O.isPlainObject(S)?O.merge.call({caseless:$},y,S):O.isPlainObject(S)?O.merge({},S):O.isArray(S)?S.slice():S}function c(y,S,j,$){if(O.isUndefined(S)){if(!O.isUndefined(y))return l(void 0,y,j,$)}else return l(y,S,j,$)}function d(y,S){if(!O.isUndefined(S))return l(void 0,S)}function f(y,S){if(O.isUndefined(S)){if(!O.isUndefined(y))return l(void 0,y)}else return l(void 0,S)}function m(y,S,j){if(j in i)return l(y,S);if(j in n)return l(void 0,y)}const x={url:d,method:d,data:d,baseURL:f,transformRequest:f,transformResponse:f,paramsSerializer:f,timeout:f,timeoutMessage:f,withCredentials:f,withXSRFToken:f,adapter:f,responseType:f,xsrfCookieName:f,xsrfHeaderName:f,onUploadProgress:f,onDownloadProgress:f,decompress:f,maxContentLength:f,maxBodyLength:f,beforeRedirect:f,transport:f,httpAgent:f,httpsAgent:f,cancelToken:f,socketPath:f,responseEncoding:f,validateStatus:m,headers:(y,S,j)=>c(op(y),op(S),j,!0)};return O.forEach(Object.keys(Object.assign({},n,i)),function(S){const j=x[S]||c,$=j(n[S],i[S],S);O.isUndefined($)&&j!==m||(s[S]=$)}),s}const kh=n=>{const i=Gn({},n);let{data:s,withXSRFToken:l,xsrfHeaderName:c,xsrfCookieName:d,headers:f,auth:m}=i;i.headers=f=mt.from(f),i.url=gh(Sh(i.baseURL,i.url),n.params,n.paramsSerializer),m&&f.set("Authorization","Basic "+btoa((m.username||"")+":"+(m.password?unescape(encodeURIComponent(m.password)):"")));let x;if(O.isFormData(s)){if(it.hasStandardBrowserEnv||it.hasStandardBrowserWebWorkerEnv)f.setContentType(void 0);else if((x=f.getContentType())!==!1){const[y,...S]=x?x.split(";").map(j=>j.trim()).filter(Boolean):[];f.setContentType([y||"multipart/form-data",...S].join("; "))}}if(it.hasStandardBrowserEnv&&(l&&O.isFunction(l)&&(l=l(i)),l||l!==!1&&yx(i.url))){const y=c&&d&&xx.read(d);y&&f.set(c,y)}return i},Sx=typeof XMLHttpRequest<"u",kx=Sx&&function(n){return new Promise(function(s,l){const c=kh(n);let d=c.data;const f=mt.from(c.headers).normalize();let{responseType:m,onUploadProgress:x,onDownloadProgress:y}=c,S,j,$,I,k;function A(){I&&I(),k&&k(),c.cancelToken&&c.cancelToken.unsubscribe(S),c.signal&&c.signal.removeEventListener("abort",S)}let _=new XMLHttpRequest;_.open(c.method.toUpperCase(),c.url,!0),_.timeout=c.timeout;function J(){if(!_)return;const H=mt.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),D={data:!m||m==="text"||m==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:H,config:n,request:_};wh(function(Q){s(Q),A()},function(Q){l(Q),A()},D),_=null}"onloadend"in _?_.onloadend=J:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.indexOf("file:")===0)||setTimeout(J)},_.onabort=function(){_&&(l(new me("Request aborted",me.ECONNABORTED,n,_)),_=null)},_.onerror=function(){l(new me("Network Error",me.ERR_NETWORK,n,_)),_=null},_.ontimeout=function(){let X=c.timeout?"timeout of "+c.timeout+"ms exceeded":"timeout exceeded";const D=c.transitional||yh;c.timeoutErrorMessage&&(X=c.timeoutErrorMessage),l(new me(X,D.clarifyTimeoutError?me.ETIMEDOUT:me.ECONNABORTED,n,_)),_=null},d===void 0&&f.setContentType(null),"setRequestHeader"in _&&O.forEach(f.toJSON(),function(X,D){_.setRequestHeader(D,X)}),O.isUndefined(c.withCredentials)||(_.withCredentials=!!c.withCredentials),m&&m!=="json"&&(_.responseType=c.responseType),y&&([$,k]=ks(y,!0),_.addEventListener("progress",$)),x&&_.upload&&([j,I]=ks(x),_.upload.addEventListener("progress",j),_.upload.addEventListener("loadend",I)),(c.cancelToken||c.signal)&&(S=H=>{_&&(l(!H||H.type?new Lr(null,n,_):H),_.abort(),_=null)},c.cancelToken&&c.cancelToken.subscribe(S),c.signal&&(c.signal.aborted?S():c.signal.addEventListener("abort",S)));const G=hx(c.url);if(G&&it.protocols.indexOf(G)===-1){l(new me("Unsupported protocol "+G+":",me.ERR_BAD_REQUEST,n));return}_.send(d||null)})},Cx=(n,i)=>{const{length:s}=n=n?n.filter(Boolean):[];if(i||s){let l=new AbortController,c;const d=function(y){if(!c){c=!0,m();const S=y instanceof Error?y:this.reason;l.abort(S instanceof me?S:new Lr(S instanceof Error?S.message:S))}};let f=i&&setTimeout(()=>{f=null,d(new me(`timeout ${i} of ms exceeded`,me.ETIMEDOUT))},i);const m=()=>{n&&(f&&clearTimeout(f),f=null,n.forEach(y=>{y.unsubscribe?y.unsubscribe(d):y.removeEventListener("abort",d)}),n=null)};n.forEach(y=>y.addEventListener("abort",d));const{signal:x}=l;return x.unsubscribe=()=>O.asap(m),x}},Ex=function*(n,i){let s=n.byteLength;if(s{const c=jx(n,i);let d=0,f,m=x=>{f||(f=!0,l&&l(x))};return new ReadableStream({async pull(x){try{const{done:y,value:S}=await c.next();if(y){m(),x.close();return}let j=S.byteLength;if(s){let $=d+=j;s($)}x.enqueue(new Uint8Array(S))}catch(y){throw m(y),y}},cancel(x){return m(x),c.return()}},{highWaterMark:2})},Os=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Ch=Os&&typeof ReadableStream=="function",Rx=Os&&(typeof TextEncoder=="function"?(n=>i=>n.encode(i))(new TextEncoder):async n=>new Uint8Array(await new Response(n).arrayBuffer())),Eh=(n,...i)=>{try{return!!n(...i)}catch{return!1}},Px=Ch&&Eh(()=>{let n=!1;const i=new Request(it.origin,{body:new ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type");return n&&!i}),sp=64*1024,uu=Ch&&Eh(()=>O.isReadableStream(new Response("").body)),Cs={stream:uu&&(n=>n.body)};Os&&(n=>{["text","arrayBuffer","blob","formData","stream"].forEach(i=>{!Cs[i]&&(Cs[i]=O.isFunction(n[i])?s=>s[i]():(s,l)=>{throw new me(`Response type '${i}' is not supported`,me.ERR_NOT_SUPPORT,l)})})})(new Response);const Mx=async n=>{if(n==null)return 0;if(O.isBlob(n))return n.size;if(O.isSpecCompliantForm(n))return(await new Request(it.origin,{method:"POST",body:n}).arrayBuffer()).byteLength;if(O.isArrayBufferView(n)||O.isArrayBuffer(n))return n.byteLength;if(O.isURLSearchParams(n)&&(n=n+""),O.isString(n))return(await Rx(n)).byteLength},_x=async(n,i)=>{const s=O.toFiniteNumber(n.getContentLength());return s??Mx(i)},Tx=Os&&(async n=>{let{url:i,method:s,data:l,signal:c,cancelToken:d,timeout:f,onDownloadProgress:m,onUploadProgress:x,responseType:y,headers:S,withCredentials:j="same-origin",fetchOptions:$}=kh(n);y=y?(y+"").toLowerCase():"text";let I=Cx([c,d&&d.toAbortSignal()],f),k;const A=I&&I.unsubscribe&&(()=>{I.unsubscribe()});let _;try{if(x&&Px&&s!=="get"&&s!=="head"&&(_=await _x(S,l))!==0){let D=new Request(i,{method:"POST",body:l,duplex:"half"}),N;if(O.isFormData(l)&&(N=D.headers.get("content-type"))&&S.setContentType(N),D.body){const[Q,le]=np(_,ks(rp(x)));l=ip(D.body,sp,Q,le)}}O.isString(j)||(j=j?"include":"omit");const J="credentials"in Request.prototype;k=new Request(i,{...$,signal:I,method:s.toUpperCase(),headers:S.normalize().toJSON(),body:l,duplex:"half",credentials:J?j:void 0});let G=await fetch(k);const H=uu&&(y==="stream"||y==="response");if(uu&&(m||H&&A)){const D={};["status","statusText","headers"].forEach(Se=>{D[Se]=G[Se]});const N=O.toFiniteNumber(G.headers.get("content-length")),[Q,le]=m&&np(N,ks(rp(m),!0))||[];G=new Response(ip(G.body,sp,Q,()=>{le&&le(),A&&A()}),D)}y=y||"text";let X=await Cs[O.findKey(Cs,y)||"text"](G,n);return!H&&A&&A(),await new Promise((D,N)=>{wh(D,N,{data:X,headers:mt.from(G.headers),status:G.status,statusText:G.statusText,config:n,request:k})})}catch(J){throw A&&A(),J&&J.name==="TypeError"&&/fetch/i.test(J.message)?Object.assign(new me("Network Error",me.ERR_NETWORK,n,k),{cause:J.cause||J}):me.from(J,J&&J.code,n,k)}}),cu={http:W0,xhr:kx,fetch:Tx};O.forEach(cu,(n,i)=>{if(n){try{Object.defineProperty(n,"name",{value:i})}catch{}Object.defineProperty(n,"adapterName",{value:i})}});const lp=n=>`- ${n}`,Nx=n=>O.isFunction(n)||n===null||n===!1,jh={getAdapter:n=>{n=O.isArray(n)?n:[n];const{length:i}=n;let s,l;const c={};for(let d=0;d`adapter ${m} `+(x===!1?"is not supported by the environment":"is not available in the build"));let f=i?d.length>1?`since : +`+d.map(lp).join(` +`):" "+lp(d[0]):"as no adapter specified";throw new me("There is no suitable adapter to dispatch the request "+f,"ERR_NOT_SUPPORT")}return l},adapters:cu};function Fa(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new Lr(null,n)}function ap(n){return Fa(n),n.headers=mt.from(n.headers),n.data=Ba.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),jh.getAdapter(n.adapter||zo.adapter)(n).then(function(l){return Fa(n),l.data=Ba.call(n,n.transformResponse,l),l.headers=mt.from(l.headers),l},function(l){return vh(l)||(Fa(n),l&&l.response&&(l.response.data=Ba.call(n,n.transformResponse,l.response),l.response.headers=mt.from(l.response.headers))),Promise.reject(l)})}const Ah="1.7.9",Ls={};["object","boolean","number","function","string","symbol"].forEach((n,i)=>{Ls[n]=function(l){return typeof l===n||"a"+(i<1?"n ":" ")+n}});const up={};Ls.transitional=function(i,s,l){function c(d,f){return"[Axios v"+Ah+"] Transitional option '"+d+"'"+f+(l?". "+l:"")}return(d,f,m)=>{if(i===!1)throw new me(c(f," has been removed"+(s?" in "+s:"")),me.ERR_DEPRECATED);return s&&!up[f]&&(up[f]=!0,console.warn(c(f," has been deprecated since v"+s+" and will be removed in the near future"))),i?i(d,f,m):!0}};Ls.spelling=function(i){return(s,l)=>(console.warn(`${l} is likely a misspelling of ${i}`),!0)};function $x(n,i,s){if(typeof n!="object")throw new me("options must be an object",me.ERR_BAD_OPTION_VALUE);const l=Object.keys(n);let c=l.length;for(;c-- >0;){const d=l[c],f=i[d];if(f){const m=n[d],x=m===void 0||f(m,d,n);if(x!==!0)throw new me("option "+d+" must be "+x,me.ERR_BAD_OPTION_VALUE);continue}if(s!==!0)throw new me("Unknown option "+d,me.ERR_BAD_OPTION)}}const ps={assertOptions:$x,validators:Ls},Vt=ps.validators;class Wn{constructor(i){this.defaults=i,this.interceptors={request:new ep,response:new ep}}async request(i,s){try{return await this._request(i,s)}catch(l){if(l instanceof Error){let c={};Error.captureStackTrace?Error.captureStackTrace(c):c=new Error;const d=c.stack?c.stack.replace(/^.+\n/,""):"";try{l.stack?d&&!String(l.stack).endsWith(d.replace(/^.+\n.+\n/,""))&&(l.stack+=` +`+d):l.stack=d}catch{}}throw l}}_request(i,s){typeof i=="string"?(s=s||{},s.url=i):s=i||{},s=Gn(this.defaults,s);const{transitional:l,paramsSerializer:c,headers:d}=s;l!==void 0&&ps.assertOptions(l,{silentJSONParsing:Vt.transitional(Vt.boolean),forcedJSONParsing:Vt.transitional(Vt.boolean),clarifyTimeoutError:Vt.transitional(Vt.boolean)},!1),c!=null&&(O.isFunction(c)?s.paramsSerializer={serialize:c}:ps.assertOptions(c,{encode:Vt.function,serialize:Vt.function},!0)),ps.assertOptions(s,{baseUrl:Vt.spelling("baseURL"),withXsrfToken:Vt.spelling("withXSRFToken")},!0),s.method=(s.method||this.defaults.method||"get").toLowerCase();let f=d&&O.merge(d.common,d[s.method]);d&&O.forEach(["delete","get","head","post","put","patch","common"],k=>{delete d[k]}),s.headers=mt.concat(f,d);const m=[];let x=!0;this.interceptors.request.forEach(function(A){typeof A.runWhen=="function"&&A.runWhen(s)===!1||(x=x&&A.synchronous,m.unshift(A.fulfilled,A.rejected))});const y=[];this.interceptors.response.forEach(function(A){y.push(A.fulfilled,A.rejected)});let S,j=0,$;if(!x){const k=[ap.bind(this),void 0];for(k.unshift.apply(k,m),k.push.apply(k,y),$=k.length,S=Promise.resolve(s);j<$;)S=S.then(k[j++],k[j++]);return S}$=m.length;let I=s;for(j=0;j<$;){const k=m[j++],A=m[j++];try{I=k(I)}catch(_){A.call(this,_);break}}try{S=ap.call(this,I)}catch(k){return Promise.reject(k)}for(j=0,$=y.length;j<$;)S=S.then(y[j++],y[j++]);return S}getUri(i){i=Gn(this.defaults,i);const s=Sh(i.baseURL,i.url);return gh(s,i.params,i.paramsSerializer)}}O.forEach(["delete","get","head","options"],function(i){Wn.prototype[i]=function(s,l){return this.request(Gn(l||{},{method:i,url:s,data:(l||{}).data}))}});O.forEach(["post","put","patch"],function(i){function s(l){return function(d,f,m){return this.request(Gn(m||{},{method:i,headers:l?{"Content-Type":"multipart/form-data"}:{},url:d,data:f}))}}Wn.prototype[i]=s(),Wn.prototype[i+"Form"]=s(!0)});class ju{constructor(i){if(typeof i!="function")throw new TypeError("executor must be a function.");let s;this.promise=new Promise(function(d){s=d});const l=this;this.promise.then(c=>{if(!l._listeners)return;let d=l._listeners.length;for(;d-- >0;)l._listeners[d](c);l._listeners=null}),this.promise.then=c=>{let d;const f=new Promise(m=>{l.subscribe(m),d=m}).then(c);return f.cancel=function(){l.unsubscribe(d)},f},i(function(d,f,m){l.reason||(l.reason=new Lr(d,f,m),s(l.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(i){if(this.reason){i(this.reason);return}this._listeners?this._listeners.push(i):this._listeners=[i]}unsubscribe(i){if(!this._listeners)return;const s=this._listeners.indexOf(i);s!==-1&&this._listeners.splice(s,1)}toAbortSignal(){const i=new AbortController,s=l=>{i.abort(l)};return this.subscribe(s),i.signal.unsubscribe=()=>this.unsubscribe(s),i.signal}static source(){let i;return{token:new ju(function(c){i=c}),cancel:i}}}function Ox(n){return function(s){return n.apply(null,s)}}function Lx(n){return O.isObject(n)&&n.isAxiosError===!0}const du={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(du).forEach(([n,i])=>{du[i]=n});function Rh(n){const i=new Wn(n),s=oh(Wn.prototype.request,i);return O.extend(s,Wn.prototype,i,{allOwnKeys:!0}),O.extend(s,i,null,{allOwnKeys:!0}),s.create=function(c){return Rh(Gn(n,c))},s}const ze=Rh(zo);ze.Axios=Wn;ze.CanceledError=Lr;ze.CancelToken=ju;ze.isCancel=vh;ze.VERSION=Ah;ze.toFormData=$s;ze.AxiosError=me;ze.Cancel=ze.CanceledError;ze.all=function(i){return Promise.all(i)};ze.spread=Ox;ze.isAxiosError=Lx;ze.mergeConfig=Gn;ze.AxiosHeaders=mt;ze.formToJSON=n=>xh(O.isHTMLForm(n)?new FormData(n):n);ze.getAdapter=jh.getAdapter;ze.HttpStatusCode=du;ze.default=ze;const Ph={apiBaseUrl:"/api"};class Dx{constructor(){kf(this,"events",{})}on(i,s){return this.events[i]||(this.events[i]=[]),this.events[i].push(s),()=>this.off(i,s)}off(i,s){this.events[i]&&(this.events[i]=this.events[i].filter(l=>l!==s))}emit(i,s){this.events[i]&&this.events[i].forEach(l=>{l(s)})}}const jr=new Dx,Ix=async(n,i)=>{const s=new FormData;return s.append("username",n),s.append("password",i),(await Bo.post("/auth/login",s,{headers:{"Content-Type":"multipart/form-data"}})).data},bx=async n=>(await Bo.post("/users",n,{headers:{"Content-Type":"multipart/form-data"}})).data,zx=async()=>{await Bo.get("/auth/csrf-token")},Bx=async()=>{await Bo.post("/auth/logout")},Fx=async()=>(await Bo.post("/auth/refresh")).data,Ux=async(n,i)=>{const s={userId:n,newRole:i};return(await Le.put("/auth/role",s)).data},et=Kn((n,i)=>({currentUser:null,accessToken:null,login:async(s,l)=>{const{userDto:c,accessToken:d}=await Ix(s,l);await i().fetchCsrfToken(),n({currentUser:c,accessToken:d})},logout:async()=>{await Bx(),i().clear(),i().fetchCsrfToken()},fetchCsrfToken:async()=>{await zx()},refreshToken:async()=>{i().clear();const{userDto:s,accessToken:l}=await Fx();n({currentUser:s,accessToken:l})},clear:()=>{n({currentUser:null,accessToken:null})},updateUserRole:async(s,l)=>{await Ux(s,l)}}));let jo=[],Zi=!1;const Le=ze.create({baseURL:Ph.apiBaseUrl,headers:{"Content-Type":"application/json"},withCredentials:!0}),Bo=ze.create({baseURL:Ph.apiBaseUrl,headers:{"Content-Type":"application/json"},withCredentials:!0});Le.interceptors.request.use(n=>{const i=et.getState().accessToken;return i&&(n.headers.Authorization=`Bearer ${i}`),n},n=>Promise.reject(n));Le.interceptors.response.use(n=>n,async n=>{var s,l,c,d;const i=(s=n.response)==null?void 0:s.data;if(i){const f=(c=(l=n.response)==null?void 0:l.headers)==null?void 0:c["discodeit-request-id"];f&&(i.requestId=f),n.response.data=i}if(console.log({error:n,errorResponse:i}),jr.emit("api-error",{error:n,alert:((d=n.response)==null?void 0:d.status)===403}),n.response&&n.response.status===401){const f=n.config;if(f&&f.headers&&f.headers._retry)return jr.emit("auth-error"),Promise.reject(n);if(Zi&&f)return new Promise((m,x)=>{jo.push({config:f,resolve:m,reject:x})});if(f){Zi=!0;try{return await et.getState().refreshToken(),jo.forEach(({config:m,resolve:x,reject:y})=>{m.headers=m.headers||{},m.headers._retry="true",Le(m).then(x).catch(y)}),f.headers=f.headers||{},f.headers._retry="true",jo=[],Zi=!1,Le(f)}catch(m){return jo.forEach(({reject:x})=>x(m)),jo=[],Zi=!1,jr.emit("auth-error"),Promise.reject(m)}}}return Promise.reject(n)});const Hx=async(n,i)=>(await Le.patch(`/users/${n}`,i,{headers:{"Content-Type":"multipart/form-data"}})).data,Yx=async()=>(await Le.get("/users")).data,Nr=Kn(n=>({users:[],fetchUsers:async()=>{try{const i=await Yx();n({users:i})}catch(i){console.error("사용자 목록 조회 실패:",i)}}})),ee={colors:{brand:{primary:"#5865F2",hover:"#4752C4"},background:{primary:"#1a1a1a",secondary:"#2a2a2a",tertiary:"#333333",input:"#40444B",hover:"rgba(255, 255, 255, 0.1)"},text:{primary:"#ffffff",secondary:"#cccccc",muted:"#999999"},status:{online:"#43b581",idle:"#faa61a",dnd:"#f04747",offline:"#747f8d",error:"#ED4245"},border:{primary:"#404040"}}},Mh=E.div` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; +`,_h=E.div` + background: ${ee.colors.background.primary}; + padding: 32px; + border-radius: 8px; + width: 440px; + + h2 { + color: ${ee.colors.text.primary}; + margin-bottom: 24px; + font-size: 24px; + font-weight: bold; + } + + form { + display: flex; + flex-direction: column; + gap: 16px; + } +`,To=E.input` + width: 100%; + padding: 10px; + border-radius: 4px; + background: ${ee.colors.background.input}; + border: none; + color: ${ee.colors.text.primary}; + font-size: 16px; + + &::placeholder { + color: ${ee.colors.text.muted}; + } + + &:focus { + outline: none; + } +`;E.input.attrs({type:"checkbox"})` + width: 16px; + height: 16px; + padding: 0; + border-radius: 4px; + background: ${ee.colors.background.input}; + border: none; + color: ${ee.colors.text.primary}; + cursor: pointer; + + &:focus { + outline: none; + } + + &:checked { + background: ${ee.colors.brand.primary}; + } +`;const Th=E.button` + width: 100%; + padding: 12px; + border-radius: 4px; + background: ${ee.colors.brand.primary}; + color: white; + font-size: 16px; + font-weight: 500; + border: none; + cursor: pointer; + transition: background-color 0.2s; + + &:hover { + background: ${ee.colors.brand.hover}; + } +`,Nh=E.div` + color: ${ee.colors.status.error}; + font-size: 14px; + text-align: center; +`,Vx=E.p` + text-align: center; + margin-top: 16px; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 14px; +`,Wx=E.span` + color: ${({theme:n})=>n.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,es=E.div` + margin-bottom: 20px; +`,ts=E.label` + display: block; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,Ua=E.span` + color: ${({theme:n})=>n.colors.status.error}; +`,qx=E.div` + display: flex; + flex-direction: column; + align-items: center; + margin: 10px 0; +`,Qx=E.img` + width: 80px; + height: 80px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,Gx=E.input` + display: none; +`,Kx=E.label` + color: ${({theme:n})=>n.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,Xx=E.span` + color: ${({theme:n})=>n.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,Jx=E(Xx)` + display: block; + text-align: center; + margin-top: 16px; +`,Ct="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAACXBIWXMAACE4AAAhOAFFljFgAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAw2SURBVHgB7d3PT1XpHcfxBy5g6hipSMolGViACThxJDbVRZ2FXejKlf9h/4GmC1fTRdkwC8fE0JgyJuICFkCjEA04GeZe6P0cPC0698I95zzPc57v5f1K6DSto3A8n/v9nufXGfrr338+dgBMGnYAzCLAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwbcTDvyuWh//33w1/1dexwMRBgYxTW5vVh9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p12qqaHO7HXQHURH6ngZ5RVqdCLBBqqj62jCwiknbBJefEd5QCDCCUWgV3hRa+EFFgBEEbXMcBBjeabR55UWLUzYiIMDwRoHVK1iZKoqHAMMLqm49CDAqyxefID42MwCGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhv0XZkN9IbEGbp4AAAAASUVORK5CYII=",Zx=({isOpen:n,onClose:i})=>{const[s,l]=Z.useState(""),[c,d]=Z.useState(""),[f,m]=Z.useState(""),[x,y]=Z.useState(null),[S,j]=Z.useState(null),[$,I]=Z.useState(""),{fetchCsrfToken:k}=et(),A=Z.useCallback(()=>{S&&URL.revokeObjectURL(S),j(null),y(null),l(""),d(""),m(""),I("")},[S]),_=Z.useCallback(()=>{A(),i()},[]),J=H=>{var D;const X=(D=H.target.files)==null?void 0:D[0];if(X){y(X);const N=new FileReader;N.onloadend=()=>{j(N.result)},N.readAsDataURL(X)}},G=async H=>{H.preventDefault(),I("");try{const X=new FormData;X.append("userCreateRequest",new Blob([JSON.stringify({email:s,username:c,password:f})],{type:"application/json"})),x&&X.append("profile",x),await bx(X),await k(),i()}catch{I("회원가입에 실패했습니다.")}};return n?h.jsx(Mh,{children:h.jsxs(_h,{children:[h.jsx("h2",{children:"계정 만들기"}),h.jsxs("form",{onSubmit:G,children:[h.jsxs(es,{children:[h.jsxs(ts,{children:["이메일 ",h.jsx(Ua,{children:"*"})]}),h.jsx(To,{type:"email",value:s,onChange:H=>l(H.target.value),required:!0})]}),h.jsxs(es,{children:[h.jsxs(ts,{children:["사용자명 ",h.jsx(Ua,{children:"*"})]}),h.jsx(To,{type:"text",value:c,onChange:H=>d(H.target.value),required:!0})]}),h.jsxs(es,{children:[h.jsxs(ts,{children:["비밀번호 ",h.jsx(Ua,{children:"*"})]}),h.jsx(To,{type:"password",value:f,onChange:H=>m(H.target.value),required:!0})]}),h.jsxs(es,{children:[h.jsx(ts,{children:"프로필 이미지"}),h.jsxs(qx,{children:[h.jsx(Qx,{src:S||Ct,alt:"profile"}),h.jsx(Gx,{type:"file",accept:"image/*",onChange:J,id:"profile-image"}),h.jsx(Kx,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),$&&h.jsx(Nh,{children:$}),h.jsx(Th,{type:"submit",children:"계속하기"}),h.jsx(Jx,{onClick:_,children:"이미 계정이 있으신가요?"})]})]})}):null},ev=({isOpen:n,onClose:i})=>{const[s,l]=Z.useState(""),[c,d]=Z.useState(""),[f,m]=Z.useState(""),[x,y]=Z.useState(!1),{login:S}=et(),{fetchUsers:j}=Nr(),$=Z.useCallback(()=>{l(""),d(""),m(""),y(!1)},[]),I=Z.useCallback(()=>{$(),y(!0)},[$,i]),k=async()=>{var A;try{await S(s,c),await j(),$(),i()}catch(_){console.error("로그인 에러:",_),((A=_.response)==null?void 0:A.status)===401?m("아이디 또는 비밀번호가 올바르지 않습니다."):m("로그인에 실패했습니다.")}};return n?h.jsxs(h.Fragment,{children:[h.jsx(Mh,{children:h.jsxs(_h,{children:[h.jsx("h2",{children:"돌아오신 것을 환영해요!"}),h.jsxs("form",{onSubmit:A=>{A.preventDefault(),k()},children:[h.jsx(To,{type:"text",placeholder:"사용자 이름",value:s,onChange:A=>l(A.target.value)}),h.jsx(To,{type:"password",placeholder:"비밀번호",value:c,onChange:A=>d(A.target.value)}),f&&h.jsx(Nh,{children:f}),h.jsx(Th,{type:"submit",children:"로그인"})]}),h.jsxs(Vx,{children:["계정이 필요한가요? ",h.jsx(Wx,{onClick:I,children:"가입하기"})]})]})}),h.jsx(Zx,{isOpen:x,onClose:()=>y(!1)})]}):null},tv=async n=>(await Le.get(`/channels?userId=${n}`)).data,nv=async n=>(await Le.post("/channels/public",n)).data,rv=async n=>{const i={participantIds:n};return(await Le.post("/channels/private",i)).data},ov=async(n,i)=>(await Le.patch(`/channels/${n}`,i)).data,iv=async n=>{await Le.delete(`/channels/${n}`)},sv=async n=>(await Le.get("/readStatuses",{params:{userId:n}})).data,cp=async(n,{newLastReadAt:i,newNotificationEnabled:s})=>{const l={newLastReadAt:i,newNotificationEnabled:s};return(await Le.patch(`/readStatuses/${n}`,l)).data},lv=async(n,i,s)=>{const l={userId:n,channelId:i,lastReadAt:s};return(await Le.post("/readStatuses",l)).data},Ar=Kn((n,i)=>({readStatuses:{},fetchReadStatuses:async()=>{try{const{currentUser:s}=et.getState();if(!s)return;const c=(await sv(s.id)).reduce((d,f)=>(d[f.channelId]={id:f.id,lastReadAt:f.lastReadAt,notificationEnabled:f.notificationEnabled},d),{});n({readStatuses:c})}catch(s){console.error("읽음 상태 조회 실패:",s)}},updateReadStatus:async s=>{try{const{currentUser:l}=et.getState();if(!l)return;const c=i().readStatuses[s];let d;c?d=await cp(c.id,{newLastReadAt:new Date().toISOString(),newNotificationEnabled:null}):d=await lv(l.id,s,new Date().toISOString()),n(f=>({readStatuses:{...f.readStatuses,[s]:{id:d.id,lastReadAt:d.lastReadAt,notificationEnabled:d.notificationEnabled}}}))}catch(l){console.error("읽음 상태 업데이트 실패:",l)}},updateNotificationEnabled:async(s,l)=>{try{const{currentUser:c}=et.getState();if(!c)return;const d=i().readStatuses[s];let f;if(d)f=await cp(d.id,{newLastReadAt:null,newNotificationEnabled:l});else return;n(m=>({readStatuses:{...m.readStatuses,[s]:{id:f.id,lastReadAt:f.lastReadAt,notificationEnabled:f.notificationEnabled}}}))}catch(c){console.error("알림 상태 업데이트 실패:",c)}},hasUnreadMessages:(s,l)=>{const c=i().readStatuses[s],d=c==null?void 0:c.lastReadAt;return!d||new Date(l)>new Date(d)}})),An=Kn((n,i)=>({channels:[],pollingInterval:null,loading:!1,error:null,fetchChannels:async s=>{n({loading:!0,error:null});try{const l=await tv(s);n(d=>{const f=new Set(d.channels.map(S=>S.id)),m=l.filter(S=>!f.has(S.id));return{channels:[...d.channels.filter(S=>l.some(j=>j.id===S.id)),...m],loading:!1}});const{fetchReadStatuses:c}=Ar.getState();return c(),l}catch(l){return n({error:l,loading:!1}),[]}},startPolling:s=>{const l=i().pollingInterval;l&&clearInterval(l);const c=setInterval(()=>{i().fetchChannels(s)},3e3);n({pollingInterval:c})},stopPolling:()=>{const s=i().pollingInterval;s&&(clearInterval(s),n({pollingInterval:null}))},createPublicChannel:async s=>{try{const l=await nv(s);return n(c=>c.channels.some(f=>f.id===l.id)?c:{channels:[...c.channels,{...l,participantIds:[],lastMessageAt:new Date().toISOString()}]}),l}catch(l){throw console.error("공개 채널 생성 실패:",l),l}},createPrivateChannel:async s=>{try{const l=await rv(s);return n(c=>c.channels.some(f=>f.id===l.id)?c:{channels:[...c.channels,{...l,participantIds:s,lastMessageAt:new Date().toISOString()}]}),l}catch(l){throw console.error("비공개 채널 생성 실패:",l),l}},updatePublicChannel:async(s,l)=>{try{const c=await ov(s,l);return n(d=>({channels:d.channels.map(f=>f.id===s?{...f,...c}:f)})),c}catch(c){throw console.error("채널 수정 실패:",c),c}},deleteChannel:async s=>{try{await iv(s),n(l=>({channels:l.channels.filter(c=>c.id!==s)}))}catch(l){throw console.error("채널 삭제 실패:",l),l}}})),dp=async n=>(await Le.get(`/binaryContents/${n}`)).data,fp=async n=>({blob:(await Le.get(`/binaryContents/${n}/download`,{responseType:"blob"})).data});var jn=(n=>(n.USER="USER",n.CHANNEL_MANAGER="CHANNEL_MANAGER",n.ADMIN="ADMIN",n))(jn||{}),Cr=(n=>(n.PROCESSING="PROCESSING",n.SUCCESS="SUCCESS",n.FAIL="FAIL",n))(Cr||{});let Fn={};const Rn=Kn((n,i)=>({binaryContents:{},pollingIds:new Set,fetchBinaryContent:async s=>{if(i().binaryContents[s])return i().binaryContents[s];try{const l=await dp(s),{contentType:c,fileName:d,size:f,status:m}=l,x={contentType:c,fileName:d,size:f,status:m};if(m===Cr.SUCCESS){const y=await fp(s),S=URL.createObjectURL(y.blob);x.url=S,x.revokeUrl=()=>URL.revokeObjectURL(S)}return n(y=>({binaryContents:{...y.binaryContents,[s]:x}})),x}catch(l){return console.error("첨부파일 정보 조회 실패:",l),null}},startPolling:s=>{if(Fn[s])return;const l=setInterval(async()=>{try{const c=await dp(s),{status:d}=c;if(d===Cr.SUCCESS){console.log(`Polling: ${s} 상태가 SUCCESS로 변경됨`);const f=await fp(s),m=URL.createObjectURL(f.blob);n(x=>({binaryContents:{...x.binaryContents,[s]:{...x.binaryContents[s],url:m,status:Cr.SUCCESS,revokeUrl:()=>URL.revokeObjectURL(m)}}})),i().stopPolling(s)}else d===Cr.FAIL?(console.log(`Polling: ${s} 상태가 FAIL로 변경됨`),n(f=>({binaryContents:{...f.binaryContents,[s]:{...f.binaryContents[s],status:Cr.FAIL}}})),i().stopPolling(s)):console.log(`Polling: ${s} 상태가 여전히 PROCESSING임`)}catch(c){console.error("polling 중 오류:",c),i().stopPolling(s)}},2e3);Fn[s]=l,n(c=>({pollingIds:new Set([...c.pollingIds,s])}))},stopPolling:s=>{Fn[s]&&(clearInterval(Fn[s]),delete Fn[s]),n(l=>{const c=new Set(l.pollingIds);return c.delete(s),{pollingIds:c}})},clearAllPolling:()=>{Object.values(Fn).forEach(s=>{clearInterval(s)}),Fn={},n({pollingIds:new Set})},clearBinaryContent:s=>{const{binaryContents:l}=i(),c=l[s];c!=null&&c.revokeUrl&&(c.revokeUrl(),n(d=>{const{[s]:f,...m}=d.binaryContents;return{binaryContents:m}}))},clearBinaryContents:s=>{const{binaryContents:l}=i(),c=[];s.forEach(d=>{const f=l[d];f&&(f.revokeUrl&&f.revokeUrl(),c.push(d))}),c.length>0&&n(d=>{const f={...d.binaryContents};return c.forEach(m=>{delete f[m]}),{binaryContents:f}})},clearAllBinaryContents:()=>{const{binaryContents:s}=i();Object.values(s).forEach(l=>{l.revokeUrl&&l.revokeUrl()}),n({binaryContents:{}})}})),Fo=E.div` + position: absolute; + bottom: -3px; + right: -3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: ${n=>n.$online?ee.colors.status.online:ee.colors.status.offline}; + border: 4px solid ${n=>n.$background||ee.colors.background.secondary}; +`;E.div` + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + background: ${n=>ee.colors.status[n.status||"offline"]||ee.colors.status.offline}; +`;const Dr=E.div` + position: relative; + width: ${n=>n.$size||"32px"}; + height: ${n=>n.$size||"32px"}; + flex-shrink: 0; + margin: ${n=>n.$margin||"0"}; +`,rn=E.img` + width: 100%; + height: 100%; + border-radius: 50%; + object-fit: cover; + border: ${n=>n.$border||"none"}; +`;function av({isOpen:n,onClose:i,user:s}){var N,Q;const[l,c]=Z.useState(s.username),[d,f]=Z.useState(s.email),[m,x]=Z.useState(""),[y,S]=Z.useState(null),[j,$]=Z.useState(""),[I,k]=Z.useState(null),{binaryContents:A,fetchBinaryContent:_}=Rn(),{logout:J,refreshToken:G}=et();Z.useEffect(()=>{var le;(le=s.profile)!=null&&le.id&&!A[s.profile.id]&&_(s.profile.id)},[s.profile,A,_]);const H=()=>{c(s.username),f(s.email),x(""),S(null),k(null),$(""),i()},X=le=>{var ge;const Se=(ge=le.target.files)==null?void 0:ge[0];if(Se){S(Se);const pe=new FileReader;pe.onloadend=()=>{k(pe.result)},pe.readAsDataURL(Se)}},D=async le=>{le.preventDefault(),$("");try{const Se=new FormData,ge={};l!==s.username&&(ge.newUsername=l),d!==s.email&&(ge.newEmail=d),m&&(ge.newPassword=m),(Object.keys(ge).length>0||y)&&(Se.append("userUpdateRequest",new Blob([JSON.stringify(ge)],{type:"application/json"})),y&&Se.append("profile",y),await Hx(s.id,Se),await G()),i()}catch{$("사용자 정보 수정에 실패했습니다.")}};return n?h.jsx(uv,{children:h.jsxs(cv,{children:[h.jsx("h2",{children:"프로필 수정"}),h.jsxs("form",{onSubmit:D,children:[h.jsxs(ns,{children:[h.jsx(rs,{children:"프로필 이미지"}),h.jsxs(fv,{children:[h.jsx(pv,{src:I||((N=s.profile)!=null&&N.id?(Q=A[s.profile.id])==null?void 0:Q.url:void 0)||Ct,alt:"profile"}),h.jsx(hv,{type:"file",accept:"image/*",onChange:X,id:"profile-image"}),h.jsx(mv,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),h.jsxs(ns,{children:[h.jsxs(rs,{children:["사용자명 ",h.jsx(hp,{children:"*"})]}),h.jsx(Ha,{type:"text",value:l,onChange:le=>c(le.target.value),required:!0})]}),h.jsxs(ns,{children:[h.jsxs(rs,{children:["이메일 ",h.jsx(hp,{children:"*"})]}),h.jsx(Ha,{type:"email",value:d,onChange:le=>f(le.target.value),required:!0})]}),h.jsxs(ns,{children:[h.jsx(rs,{children:"새 비밀번호"}),h.jsx(Ha,{type:"password",placeholder:"변경하지 않으려면 비워두세요",value:m,onChange:le=>x(le.target.value)})]}),j&&h.jsx(dv,{children:j}),h.jsxs(gv,{children:[h.jsx(pp,{type:"button",onClick:H,$secondary:!0,children:"취소"}),h.jsx(pp,{type:"submit",children:"저장"})]})]}),h.jsx(yv,{onClick:J,children:"로그아웃"})]})}):null}const uv=E.div` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; +`,cv=E.div` + background: ${({theme:n})=>n.colors.background.secondary}; + padding: 32px; + border-radius: 5px; + width: 100%; + max-width: 480px; + + h2 { + color: ${({theme:n})=>n.colors.text.primary}; + margin-bottom: 24px; + text-align: center; + font-size: 24px; + } +`,Ha=E.input` + width: 100%; + padding: 10px; + margin-bottom: 10px; + border: none; + border-radius: 4px; + background: ${({theme:n})=>n.colors.background.input}; + color: ${({theme:n})=>n.colors.text.primary}; + + &::placeholder { + color: ${({theme:n})=>n.colors.text.muted}; + } + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${({theme:n})=>n.colors.brand.primary}; + } +`,pp=E.button` + width: 100%; + padding: 10px; + border: none; + border-radius: 4px; + background: ${({$secondary:n,theme:i})=>n?"transparent":i.colors.brand.primary}; + color: ${({theme:n})=>n.colors.text.primary}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({$secondary:n,theme:i})=>n?i.colors.background.hover:i.colors.brand.hover}; + } +`,dv=E.div` + color: ${({theme:n})=>n.colors.status.error}; + font-size: 14px; + margin-bottom: 10px; +`,fv=E.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 20px; +`,pv=E.img` + width: 100px; + height: 100px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,hv=E.input` + display: none; +`,mv=E.label` + color: ${({theme:n})=>n.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,gv=E.div` + display: flex; + gap: 10px; + margin-top: 20px; +`,yv=E.button` + width: 100%; + padding: 10px; + margin-top: 16px; + border: none; + border-radius: 4px; + background: transparent; + color: ${({theme:n})=>n.colors.status.error}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({theme:n})=>n.colors.status.error}20; + } +`,ns=E.div` + margin-bottom: 20px; +`,rs=E.label` + display: block; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,hp=E.span` + color: ${({theme:n})=>n.colors.status.error}; +`,xv=E.div` + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.5rem 0.75rem; + background-color: ${({theme:n})=>n.colors.background.tertiary}; + width: 100%; + height: 52px; +`,vv=E(Dr)``;E(rn)``;const wv=E.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; +`,Sv=E.div` + font-weight: 500; + color: ${({theme:n})=>n.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.875rem; + line-height: 1.2; +`,kv=E.div` + font-size: 0.75rem; + color: ${({theme:n})=>n.colors.text.secondary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.2; +`,Cv=E.div` + display: flex; + align-items: center; + flex-shrink: 0; +`,Ev=E.button` + background: none; + border: none; + padding: 0.25rem; + cursor: pointer; + color: ${({theme:n})=>n.colors.text.secondary}; + font-size: 18px; + + &:hover { + color: ${({theme:n})=>n.colors.text.primary}; + } +`;function jv({user:n}){var d,f;const[i,s]=Z.useState(!1),{binaryContents:l,fetchBinaryContent:c}=Rn();return Z.useEffect(()=>{var m;(m=n.profile)!=null&&m.id&&!l[n.profile.id]&&c(n.profile.id)},[n.profile,l,c]),h.jsxs(h.Fragment,{children:[h.jsxs(xv,{children:[h.jsxs(vv,{children:[h.jsx(rn,{src:(d=n.profile)!=null&&d.id?(f=l[n.profile.id])==null?void 0:f.url:Ct,alt:n.username}),h.jsx(Fo,{$online:!0})]}),h.jsxs(wv,{children:[h.jsx(Sv,{children:n.username}),h.jsx(kv,{children:"온라인"})]}),h.jsx(Cv,{children:h.jsx(Ev,{onClick:()=>s(!0),children:"⚙️"})})]}),h.jsx(av,{isOpen:i,onClose:()=>s(!1),user:n})]})}const Av=E.div` + width: 240px; + background: ${ee.colors.background.secondary}; + border-right: 1px solid ${ee.colors.border.primary}; + display: flex; + flex-direction: column; +`,Rv=E.div` + flex: 1; + overflow-y: auto; +`,Pv=E.div` + padding: 16px; + font-size: 16px; + font-weight: bold; + color: ${ee.colors.text.primary}; +`,Au=E.div` + height: 34px; + padding: 0 8px; + margin: 1px 8px; + display: flex; + align-items: center; + gap: 6px; + color: ${n=>n.$hasUnread?n.theme.colors.text.primary:n.theme.colors.text.muted}; + font-weight: ${n=>n.$hasUnread?"600":"normal"}; + cursor: pointer; + background: ${n=>n.$isActive?n.theme.colors.background.hover:"transparent"}; + border-radius: 4px; + + &:hover { + background: ${n=>n.theme.colors.background.hover}; + color: ${n=>n.theme.colors.text.primary}; + } +`,mp=E.div` + margin-bottom: 8px; +`,fu=E.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${ee.colors.text.muted}; + text-transform: uppercase; + font-size: 12px; + font-weight: 600; + cursor: pointer; + user-select: none; + + & > span:nth-child(2) { + flex: 1; + margin-right: auto; + } + + &:hover { + color: ${ee.colors.text.primary}; + } +`,gp=E.span` + margin-right: 4px; + font-size: 10px; + transition: transform 0.2s; + transform: rotate(${n=>n.$folded?"-90deg":"0deg"}); +`,yp=E.div` + display: ${n=>n.$folded?"none":"block"}; +`,pu=E(Au)` + height: ${n=>n.hasSubtext?"42px":"34px"}; +`,Mv=E(Dr)` + width: 32px; + height: 32px; + margin: 0 8px; +`,xp=E.div` + font-size: 16px; + line-height: 18px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: ${n=>n.$isActive||n.$hasUnread?n.theme.colors.text.primary:n.theme.colors.text.muted}; + font-weight: ${n=>n.$hasUnread?"600":"normal"}; +`;E(Fo)` + border-color: ${ee.colors.background.primary}; +`;const vp=E.button` + background: none; + border: none; + color: ${ee.colors.text.muted}; + font-size: 18px; + padding: 0; + cursor: pointer; + width: 16px; + height: 16px; + display: flex; + align-items: center; + justify-content: center; + opacity: 0; + transition: opacity 0.2s, color 0.2s; + + ${fu}:hover & { + opacity: 1; + } + + &:hover { + color: ${ee.colors.text.primary}; + } +`,_v=E(Dr)` + width: 40px; + height: 24px; + margin: 0 8px; +`,Tv=E.div` + font-size: 12px; + line-height: 13px; + color: ${ee.colors.text.muted}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,wp=E.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; +`,$h=E.div` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.85); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; +`,Oh=E.div` + background: ${ee.colors.background.primary}; + border-radius: 4px; + width: 440px; + max-width: 90%; +`,Lh=E.div` + padding: 16px; + display: flex; + justify-content: space-between; + align-items: center; +`,Dh=E.h2` + color: ${ee.colors.text.primary}; + font-size: 20px; + font-weight: 600; + margin: 0; +`,Ih=E.div` + padding: 0 16px 16px; +`,bh=E.form` + display: flex; + flex-direction: column; + gap: 16px; +`,No=E.div` + display: flex; + flex-direction: column; + gap: 8px; +`,$o=E.label` + color: ${ee.colors.text.primary}; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; +`,zh=E.p` + color: ${ee.colors.text.muted}; + font-size: 14px; + margin: -4px 0 0; +`,Io=E.input` + padding: 10px; + background: ${ee.colors.background.tertiary}; + border: none; + border-radius: 3px; + color: ${ee.colors.text.primary}; + font-size: 16px; + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${ee.colors.status.online}; + } + + &::placeholder { + color: ${ee.colors.text.muted}; + } +`,Bh=E.button` + margin-top: 8px; + padding: 12px; + background: ${ee.colors.status.online}; + color: white; + border: none; + border-radius: 3px; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: background 0.2s; + + &:hover { + background: #3ca374; + } +`,Fh=E.button` + background: none; + border: none; + color: ${ee.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px; + line-height: 1; + + &:hover { + color: ${ee.colors.text.primary}; + } +`,Nv=E(Io)` + margin-bottom: 8px; +`,$v=E.div` + max-height: 300px; + overflow-y: auto; + background: ${ee.colors.background.tertiary}; + border-radius: 4px; +`,Ov=E.div` + display: flex; + align-items: center; + padding: 8px 12px; + cursor: pointer; + transition: background 0.2s; + + &:hover { + background: ${ee.colors.background.hover}; + } + + & + & { + border-top: 1px solid ${ee.colors.border.primary}; + } +`,Lv=E.input` + margin-right: 12px; + width: 16px; + height: 16px; + cursor: pointer; +`,Sp=E.img` + width: 32px; + height: 32px; + border-radius: 50%; + margin-right: 12px; +`,Dv=E.div` + flex: 1; + min-width: 0; +`,Iv=E.div` + color: ${ee.colors.text.primary}; + font-size: 14px; + font-weight: 500; +`,bv=E.div` + color: ${ee.colors.text.muted}; + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,zv=E.div` + padding: 16px; + text-align: center; + color: ${ee.colors.text.muted}; +`,Uh=E.div` + color: ${ee.colors.status.error}; + font-size: 14px; + padding: 8px 0; + text-align: center; + background-color: ${({theme:n})=>n.colors.background.tertiary}; + border-radius: 4px; + margin-bottom: 8px; +`,Ya=E.div` + position: relative; + margin-left: auto; + z-index: 99999; +`,Va=E.button` + background: none; + border: none; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 16px; + cursor: pointer; + padding: 4px; + border-radius: 3px; + opacity: 0; + transition: opacity 0.2s, background 0.2s; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + color: ${({theme:n})=>n.colors.text.primary}; + } + + ${Au}:hover &, + ${pu}:hover & { + opacity: 1; + } +`,Wa=E.div` + position: absolute; + top: 100%; + right: 0; + background: ${({theme:n})=>n.colors.background.primary}; + border: 1px solid ${({theme:n})=>n.colors.border.primary}; + border-radius: 4px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); + min-width: 120px; + z-index: 100000; +`,os=E.div` + padding: 8px 12px; + color: ${({theme:n})=>n.colors.text.primary}; + cursor: pointer; + font-size: 14px; + display: flex; + align-items: center; + gap: 8px; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + } + + &:first-child { + border-radius: 4px 4px 0 0; + } + + &:last-child { + border-radius: 0 0 4px 4px; + } + + &:only-child { + border-radius: 4px; + } +`;function Bv(){return h.jsx(Pv,{children:"채널 목록"})}function Fv({isOpen:n,channel:i,onClose:s,onUpdateSuccess:l}){const[c,d]=Z.useState({name:"",description:""}),[f,m]=Z.useState(""),[x,y]=Z.useState(!1),{updatePublicChannel:S}=An();Z.useEffect(()=>{i&&n&&(d({name:i.name||"",description:i.description||""}),m(""))},[i,n]);const j=I=>{const{name:k,value:A}=I.target;d(_=>({..._,[k]:A}))},$=async I=>{var k,A;if(I.preventDefault(),!!i){m(""),y(!0);try{if(!c.name.trim()){m("채널 이름을 입력해주세요."),y(!1);return}const _={newName:c.name.trim(),newDescription:c.description.trim()},J=await S(i.id,_);l(J)}catch(_){console.error("채널 수정 실패:",_),m(((A=(k=_.response)==null?void 0:k.data)==null?void 0:A.message)||"채널 수정에 실패했습니다. 다시 시도해주세요.")}finally{y(!1)}}};return!n||!i||i.type!=="PUBLIC"?null:h.jsx($h,{onClick:s,children:h.jsxs(Oh,{onClick:I=>I.stopPropagation(),children:[h.jsxs(Lh,{children:[h.jsx(Dh,{children:"채널 수정"}),h.jsx(Fh,{onClick:s,children:"×"})]}),h.jsx(Ih,{children:h.jsxs(bh,{onSubmit:$,children:[f&&h.jsx(Uh,{children:f}),h.jsxs(No,{children:[h.jsx($o,{children:"채널 이름"}),h.jsx(Io,{name:"name",value:c.name,onChange:j,placeholder:"새로운-채널",required:!0,disabled:x})]}),h.jsxs(No,{children:[h.jsx($o,{children:"채널 설명"}),h.jsx(zh,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Io,{name:"description",value:c.description,onChange:j,placeholder:"채널 설명을 입력하세요",disabled:x})]}),h.jsx(Bh,{type:"submit",disabled:x,children:x?"수정 중...":"채널 수정"})]})})]})})}function kp({channel:n,isActive:i,onClick:s,hasUnread:l}){var G;const{currentUser:c}=et(),{binaryContents:d}=Rn(),{deleteChannel:f}=An(),[m,x]=Z.useState(null),[y,S]=Z.useState(!1),j=(c==null?void 0:c.role)===jn.ADMIN||(c==null?void 0:c.role)===jn.CHANNEL_MANAGER;Z.useEffect(()=>{const H=()=>{m&&x(null)};if(m)return document.addEventListener("click",H),()=>document.removeEventListener("click",H)},[m]);const $=H=>{x(m===H?null:H)},I=()=>{x(null),S(!0)},k=H=>{S(!1),console.log("Channel updated successfully:",H)},A=()=>{S(!1)},_=async H=>{var D;x(null);const X=n.type==="PUBLIC"?n.name:n.type==="PRIVATE"&&n.participants.length>2?`그룹 채팅 (멤버 ${n.participants.length}명)`:((D=n.participants.filter(N=>N.id!==(c==null?void 0:c.id))[0])==null?void 0:D.username)||"1:1 채팅";if(confirm(`"${X}" 채널을 삭제하시겠습니까?`))try{await f(H),console.log("Channel deleted successfully:",H)}catch(N){console.error("Channel delete failed:",N),alert("채널 삭제에 실패했습니다. 다시 시도해주세요.")}};let J;if(n.type==="PUBLIC")J=h.jsxs(Au,{$isActive:i,onClick:s,$hasUnread:l,children:["# ",n.name,j&&h.jsxs(Ya,{children:[h.jsx(Va,{onClick:H=>{H.stopPropagation(),$(n.id)},children:"⋯"}),m===n.id&&h.jsxs(Wa,{onClick:H=>H.stopPropagation(),children:[h.jsx(os,{onClick:()=>I(),children:"✏️ 수정"}),h.jsx(os,{onClick:()=>_(n.id),children:"🗑️ 삭제"})]})]})]});else{const H=n.participants;if(H.length>2){const X=H.filter(D=>D.id!==(c==null?void 0:c.id)).map(D=>D.username).join(", ");J=h.jsxs(pu,{$isActive:i,onClick:s,children:[h.jsx(_v,{children:H.filter(D=>D.id!==(c==null?void 0:c.id)).slice(0,2).map((D,N)=>{var Q;return h.jsx(rn,{src:D.profile?(Q=d[D.profile.id])==null?void 0:Q.url:Ct,style:{position:"absolute",left:N*16,zIndex:2-N,width:"24px",height:"24px",border:"2px solid #2a2a2a"}},D.id)})}),h.jsxs(wp,{children:[h.jsx(xp,{$hasUnread:l,children:X}),h.jsxs(Tv,{children:["멤버 ",H.length,"명"]})]}),j&&h.jsxs(Ya,{children:[h.jsx(Va,{onClick:D=>{D.stopPropagation(),$(n.id)},children:"⋯"}),m===n.id&&h.jsx(Wa,{onClick:D=>D.stopPropagation(),children:h.jsx(os,{onClick:()=>_(n.id),children:"🗑️ 삭제"})})]})]})}else{const X=H.filter(D=>D.id!==(c==null?void 0:c.id))[0];J=X?h.jsxs(pu,{$isActive:i,onClick:s,children:[h.jsxs(Mv,{children:[h.jsx(rn,{src:X.profile?(G=d[X.profile.id])==null?void 0:G.url:Ct,alt:"profile"}),h.jsx(Fo,{$online:X.online})]}),h.jsx(wp,{children:h.jsx(xp,{$hasUnread:l,children:X.username})}),j&&h.jsxs(Ya,{children:[h.jsx(Va,{onClick:D=>{D.stopPropagation(),$(n.id)},children:"⋯"}),m===n.id&&h.jsx(Wa,{onClick:D=>D.stopPropagation(),children:h.jsx(os,{onClick:()=>_(n.id),children:"🗑️ 삭제"})})]})]}):h.jsx("div",{})}}return h.jsxs(h.Fragment,{children:[J,h.jsx(Fv,{isOpen:y,channel:n,onClose:A,onUpdateSuccess:k})]})}function Uv({isOpen:n,type:i,onClose:s,onCreateSuccess:l}){const[c,d]=Z.useState({name:"",description:""}),[f,m]=Z.useState(""),[x,y]=Z.useState([]),[S,j]=Z.useState(""),$=Nr(D=>D.users),I=Rn(D=>D.binaryContents),{currentUser:k}=et(),A=Z.useMemo(()=>$.filter(D=>D.id!==(k==null?void 0:k.id)).filter(D=>D.username.toLowerCase().includes(f.toLowerCase())||D.email.toLowerCase().includes(f.toLowerCase())),[f,$,k]),_=An(D=>D.createPublicChannel),J=An(D=>D.createPrivateChannel),G=D=>{const{name:N,value:Q}=D.target;d(le=>({...le,[N]:Q}))},H=D=>{y(N=>N.includes(D)?N.filter(Q=>Q!==D):[...N,D])},X=async D=>{var N,Q;D.preventDefault(),j("");try{let le;if(i==="PUBLIC"){if(!c.name.trim()){j("채널 이름을 입력해주세요.");return}const Se={name:c.name,description:c.description};le=await _(Se)}else{if(x.length===0){j("대화 상대를 선택해주세요.");return}const Se=(k==null?void 0:k.id)&&[...x,k.id]||x;le=await J(Se)}l(le)}catch(le){console.error("채널 생성 실패:",le),j(((Q=(N=le.response)==null?void 0:N.data)==null?void 0:Q.message)||"채널 생성에 실패했습니다. 다시 시도해주세요.")}};return n?h.jsx($h,{onClick:s,children:h.jsxs(Oh,{onClick:D=>D.stopPropagation(),children:[h.jsxs(Lh,{children:[h.jsx(Dh,{children:i==="PUBLIC"?"채널 만들기":"개인 메시지 시작하기"}),h.jsx(Fh,{onClick:s,children:"×"})]}),h.jsx(Ih,{children:h.jsxs(bh,{onSubmit:X,children:[S&&h.jsx(Uh,{children:S}),i==="PUBLIC"?h.jsxs(h.Fragment,{children:[h.jsxs(No,{children:[h.jsx($o,{children:"채널 이름"}),h.jsx(Io,{name:"name",value:c.name,onChange:G,placeholder:"새로운-채널",required:!0})]}),h.jsxs(No,{children:[h.jsx($o,{children:"채널 설명"}),h.jsx(zh,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Io,{name:"description",value:c.description,onChange:G,placeholder:"채널 설명을 입력하세요"})]})]}):h.jsxs(No,{children:[h.jsx($o,{children:"사용자 검색"}),h.jsx(Nv,{type:"text",value:f,onChange:D=>m(D.target.value),placeholder:"사용자명 또는 이메일로 검색"}),h.jsx($v,{children:A.length>0?A.map(D=>h.jsxs(Ov,{children:[h.jsx(Lv,{type:"checkbox",checked:x.includes(D.id),onChange:()=>H(D.id)}),D.profile?h.jsx(Sp,{src:I[D.profile.id].url}):h.jsx(Sp,{src:Ct}),h.jsxs(Dv,{children:[h.jsx(Iv,{children:D.username}),h.jsx(bv,{children:D.email})]})]},D.id)):h.jsx(zv,{children:"검색 결과가 없습니다."})})]}),h.jsx(Bh,{type:"submit",children:i==="PUBLIC"?"채널 만들기":"대화 시작하기"})]})})]})}):null}function Hv({currentUser:n,activeChannel:i,onChannelSelect:s}){var X,D;const[l,c]=Z.useState({PUBLIC:!1,PRIVATE:!1}),[d,f]=Z.useState({isOpen:!1,type:null}),m=An(N=>N.channels),x=An(N=>N.fetchChannels),y=An(N=>N.startPolling),S=An(N=>N.stopPolling),j=Ar(N=>N.fetchReadStatuses),$=Ar(N=>N.updateReadStatus),I=Ar(N=>N.hasUnreadMessages);Z.useEffect(()=>{if(n)return x(n.id),j(),y(n.id),()=>{S()}},[n,x,j,y,S]);const k=N=>{c(Q=>({...Q,[N]:!Q[N]}))},A=(N,Q)=>{Q.stopPropagation(),f({isOpen:!0,type:N})},_=()=>{f({isOpen:!1,type:null})},J=async N=>{try{const le=(await x(n.id)).find(Se=>Se.id===N.id);le&&s(le),_()}catch(Q){console.error("채널 생성 실패:",Q)}},G=N=>{s(N),$(N.id)},H=m.reduce((N,Q)=>(N[Q.type]||(N[Q.type]=[]),N[Q.type].push(Q),N),{});return h.jsxs(Av,{children:[h.jsx(Bv,{}),h.jsxs(Rv,{children:[h.jsxs(mp,{children:[h.jsxs(fu,{onClick:()=>k("PUBLIC"),children:[h.jsx(gp,{$folded:l.PUBLIC,children:"▼"}),h.jsx("span",{children:"일반 채널"}),h.jsx(vp,{onClick:N=>A("PUBLIC",N),children:"+"})]}),h.jsx(yp,{$folded:l.PUBLIC,children:(X=H.PUBLIC)==null?void 0:X.map(N=>h.jsx(kp,{channel:N,isActive:(i==null?void 0:i.id)===N.id,hasUnread:I(N.id,N.lastMessageAt),onClick:()=>G(N)},N.id))})]}),h.jsxs(mp,{children:[h.jsxs(fu,{onClick:()=>k("PRIVATE"),children:[h.jsx(gp,{$folded:l.PRIVATE,children:"▼"}),h.jsx("span",{children:"개인 메시지"}),h.jsx(vp,{onClick:N=>A("PRIVATE",N),children:"+"})]}),h.jsx(yp,{$folded:l.PRIVATE,children:(D=H.PRIVATE)==null?void 0:D.map(N=>h.jsx(kp,{channel:N,isActive:(i==null?void 0:i.id)===N.id,hasUnread:I(N.id,N.lastMessageAt),onClick:()=>G(N)},N.id))})]})]}),h.jsx(Yv,{children:h.jsx(jv,{user:n})}),h.jsx(Uv,{isOpen:d.isOpen,type:d.type,onClose:_,onCreateSuccess:J})]})}const Yv=E.div` + margin-top: auto; + border-top: 1px solid ${({theme:n})=>n.colors.border.primary}; + background-color: ${({theme:n})=>n.colors.background.tertiary}; +`,Vv=E.div` + flex: 1; + display: flex; + flex-direction: column; + background: ${({theme:n})=>n.colors.background.primary}; +`,Wv=E.div` + display: flex; + flex-direction: column; + height: 100%; + background: ${({theme:n})=>n.colors.background.primary}; +`,qv=E(Wv)` + justify-content: center; + align-items: center; + flex: 1; + padding: 0 20px; +`,Qv=E.div` + text-align: center; + max-width: 400px; + padding: 20px; + margin-bottom: 80px; +`,Gv=E.div` + font-size: 48px; + margin-bottom: 16px; + animation: wave 2s infinite; + transform-origin: 70% 70%; + + @keyframes wave { + 0% { transform: rotate(0deg); } + 10% { transform: rotate(14deg); } + 20% { transform: rotate(-8deg); } + 30% { transform: rotate(14deg); } + 40% { transform: rotate(-4deg); } + 50% { transform: rotate(10deg); } + 60% { transform: rotate(0deg); } + 100% { transform: rotate(0deg); } + } +`,Kv=E.h2` + color: ${({theme:n})=>n.colors.text.primary}; + font-size: 28px; + font-weight: 700; + margin-bottom: 16px; +`,Xv=E.p` + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 16px; + line-height: 1.6; + word-break: keep-all; +`,Cp=E.div` + height: 48px; + padding: 0 16px; + background: ${ee.colors.background.primary}; + border-bottom: 1px solid ${ee.colors.border.primary}; + display: flex; + align-items: center; +`,Ep=E.div` + display: flex; + align-items: center; + gap: 8px; + height: 100%; +`,Jv=E.div` + display: flex; + align-items: center; + gap: 12px; + height: 100%; +`,Zv=E(Dr)` + width: 24px; + height: 24px; +`;E.img` + width: 24px; + height: 24px; + border-radius: 50%; +`;const e1=E.div` + position: relative; + width: 40px; + height: 24px; + flex-shrink: 0; +`,t1=E(Fo)` + border-color: ${ee.colors.background.primary}; + bottom: -3px; + right: -3px; +`,n1=E.div` + font-size: 12px; + color: ${ee.colors.text.muted}; + line-height: 13px; +`,jp=E.div` + font-weight: bold; + color: ${ee.colors.text.primary}; + line-height: 20px; + font-size: 16px; +`,r1=E.div` + flex: 1; + display: flex; + flex-direction: column-reverse; + overflow-y: auto; + position: relative; +`,o1=E.div` + padding: 16px; + display: flex; + flex-direction: column; +`,Hh=E.div` + margin-bottom: 16px; + display: flex; + align-items: flex-start; + position: relative; + z-index: 1; +`,i1=E(Dr)` + margin-right: 16px; + width: 40px; + height: 40px; +`;E.img` + width: 40px; + height: 40px; + border-radius: 50%; +`;const s1=E.div` + display: flex; + align-items: center; + margin-bottom: 4px; + position: relative; +`,l1=E.span` + font-weight: bold; + color: ${ee.colors.text.primary}; + margin-right: 8px; +`,a1=E.span` + font-size: 0.75rem; + color: ${ee.colors.text.muted}; +`,u1=E.div` + color: ${ee.colors.text.secondary}; + margin-top: 4px; +`,c1=E.form` + display: flex; + align-items: center; + gap: 8px; + padding: 16px; + background: ${({theme:n})=>n.colors.background.secondary}; + position: relative; + z-index: 1; +`,d1=E.textarea` + flex: 1; + padding: 12px; + background: ${({theme:n})=>n.colors.background.tertiary}; + border: none; + border-radius: 4px; + color: ${({theme:n})=>n.colors.text.primary}; + font-size: 14px; + resize: none; + min-height: 44px; + max-height: 144px; + + &:focus { + outline: none; + } + + &::placeholder { + color: ${({theme:n})=>n.colors.text.muted}; + } +`,f1=E.button` + background: none; + border: none; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px 8px; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + color: ${({theme:n})=>n.colors.text.primary}; + } +`;E.div` + flex: 1; + display: flex; + align-items: center; + justify-content: center; + color: ${ee.colors.text.muted}; + font-size: 16px; + font-weight: 500; + padding: 20px; + text-align: center; +`;const is=E.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; + width: 100%; +`,p1=E.a` + display: block; + border-radius: 4px; + overflow: hidden; + max-width: 300px; + + img { + width: 100%; + height: auto; + display: block; + } +`,qa=E.a` + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + background: ${({theme:n})=>n.colors.background.tertiary}; + border-radius: 8px; + text-decoration: none; + width: fit-content; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + } +`,Qa=E.div` + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + font-size: 40px; + color: #0B93F6; +`,Ga=E.div` + display: flex; + flex-direction: column; + gap: 2px; +`,Ka=E.span` + font-size: 14px; + color: #0B93F6; + font-weight: 500; +`,Xa=E.span` + font-size: 13px; + color: ${({theme:n})=>n.colors.text.muted}; +`,h1=E.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px 0; +`,Yh=E.div` + position: relative; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: ${({theme:n})=>n.colors.background.tertiary}; + border-radius: 4px; + max-width: 300px; +`,m1=E(Yh)` + padding: 0; + overflow: hidden; + width: 200px; + height: 120px; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } +`,g1=E.div` + color: #0B93F6; + font-size: 20px; +`,y1=E.div` + font-size: 13px; + color: ${({theme:n})=>n.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,Ap=E.button` + position: absolute; + top: -6px; + right: -6px; + width: 20px; + height: 20px; + border-radius: 50%; + background: ${({theme:n})=>n.colors.background.secondary}; + border: none; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 16px; + line-height: 1; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + padding: 0; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + + &:hover { + color: ${({theme:n})=>n.colors.text.primary}; + } +`,x1=E.div` + width: 16px; + height: 16px; + border: 2px solid ${({theme:n})=>n.colors.background.tertiary}; + border-top: 2px solid ${({theme:n})=>n.colors.brand.primary}; + border-radius: 50%; + animation: spin 1s linear infinite; + margin-right: 8px; + + @keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } + } +`,v1=E.div` + position: relative; + margin-left: auto; + z-index: 99999; +`,w1=E.button` + background: none; + border: none; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 16px; + cursor: pointer; + padding: 4px 8px; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + opacity: 0; + transition: opacity 0.2s ease; + + &:hover { + color: ${({theme:n})=>n.colors.text.primary}; + background: ${({theme:n})=>n.colors.background.hover}; + } + + ${Hh}:hover & { + opacity: 1; + } +`,S1=E.div` + position: absolute; + top: 0; + background: ${({theme:n})=>n.colors.background.primary}; + border: 1px solid ${({theme:n})=>n.colors.border.primary}; + border-radius: 6px; + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15); + width: 80px; + z-index: 99999; + overflow: hidden; +`,Rp=E.button` + display: flex; + align-items: center; + gap: 8px; + width: fit-content; + background: none; + border: none; + color: ${({theme:n})=>n.colors.text.primary}; + font-size: 14px; + cursor: pointer; + text-align: center ; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + } + + &:first-child { + border-radius: 6px 6px 0 0; + } + + &:last-child { + border-radius: 0 0 6px 6px; + } +`,k1=E.div` + margin-top: 4px; +`,C1=E.textarea` + width: 100%; + max-width: 600px; + min-height: 80px; + padding: 12px 16px; + background: ${({theme:n})=>n.colors.background.tertiary}; + border: 1px solid ${({theme:n})=>n.colors.border.primary}; + border-radius: 4px; + color: ${({theme:n})=>n.colors.text.primary}; + font-size: 14px; + font-family: inherit; + resize: vertical; + outline: none; + box-sizing: border-box; + + &:focus { + border-color: ${({theme:n})=>n.colors.primary}; + } + + &::placeholder { + color: ${({theme:n})=>n.colors.text.muted}; + } +`,E1=E.div` + display: flex; + gap: 8px; + margin-top: 8px; +`,Pp=E.button` + padding: 6px 12px; + border-radius: 4px; + font-size: 12px; + font-weight: 500; + cursor: pointer; + border: none; + transition: background-color 0.2s ease; + + ${({variant:n,theme:i})=>n==="primary"?` + background: ${i.colors.primary}; + color: white; + + &:hover { + background: ${i.colors.primaryHover||i.colors.primary}; + } + `:` + background: ${i.colors.background.secondary}; + color: ${i.colors.text.secondary}; + + &:hover { + background: ${i.colors.background.hover}; + } + `} +`,Mp=E.button` + background: none; + border: none; + padding: 8px; + cursor: pointer; + color: ${({theme:n,$enabled:i})=>i?n.colors.brand.primary:n.colors.text.muted}; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + color: ${({theme:n})=>n.colors.brand.primary}; + } +`;function j1({channel:n}){var I;const{currentUser:i}=et(),s=Nr(k=>k.users),l=Rn(k=>k.binaryContents),{readStatuses:c,updateNotificationEnabled:d}=Ar(),[f,m]=Z.useState(!1);Z.useEffect(()=>{c[n==null?void 0:n.id]&&m(c[n.id].notificationEnabled)},[c,n]);const x=Z.useCallback(async()=>{if(!i||!n)return;const k=!f;m(k);try{await d(n.id,k)}catch(A){console.error("알림 설정 업데이트 실패:",A),m(f)}},[i,n,f,d]);if(!n)return null;if(n.type==="PUBLIC")return h.jsxs(Cp,{children:[h.jsx(Ep,{children:h.jsxs(jp,{children:["# ",n.name]})}),h.jsx(Mp,{onClick:x,$enabled:f,children:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),h.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})})]});const y=n.participants.map(k=>s.find(A=>A.id===k.id)).filter(Boolean),S=y.filter(k=>k.id!==(i==null?void 0:i.id)),j=y.length>2,$=y.filter(k=>k.id!==(i==null?void 0:i.id)).map(k=>k.username).join(", ");return h.jsxs(Cp,{children:[h.jsx(Ep,{children:h.jsxs(Jv,{children:[j?h.jsx(e1,{children:S.slice(0,2).map((k,A)=>{var _;return h.jsx(rn,{src:k.profile?(_=l[k.profile.id])==null?void 0:_.url:Ct,style:{position:"absolute",left:A*16,zIndex:2-A,width:"24px",height:"24px"}},k.id)})}):h.jsxs(Zv,{children:[h.jsx(rn,{src:S[0].profile?(I=l[S[0].profile.id])==null?void 0:I.url:Ct}),h.jsx(t1,{$online:S[0].online})]}),h.jsxs("div",{children:[h.jsx(jp,{children:$}),j&&h.jsxs(n1,{children:["멤버 ",y.length,"명"]})]})]})}),h.jsx(Mp,{onClick:x,$enabled:f,children:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),h.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})})]})}const A1=async(n,i,s)=>{var c;return(await Le.get("/messages",{params:{channelId:n,cursor:i,size:s.size,sort:(c=s.sort)==null?void 0:c.join(",")}})).data},R1=async(n,i)=>{const s=new FormData,l={content:n.content,channelId:n.channelId,authorId:n.authorId};return s.append("messageCreateRequest",new Blob([JSON.stringify(l)],{type:"application/json"})),i&&i.length>0&&i.forEach(d=>{s.append("attachments",d)}),(await Le.post("/messages",s,{headers:{"Content-Type":"multipart/form-data"}})).data},P1=async(n,i)=>(await Le.patch(`/messages/${n}`,i)).data,M1=async n=>{await Le.delete(`/messages/${n}`)},Ja={size:50,sort:["createdAt,desc"]},Vh=Kn((n,i)=>({messages:[],pollingIntervals:{},lastMessageId:null,pagination:{nextCursor:null,pageSize:50,hasNext:!1},isCreating:!1,fetchMessages:async(s,l,c=Ja)=>{try{if(i().isCreating)return Promise.resolve(!0);const d=await A1(s,l,c),f=d.content,m=f.length>0?f[0]:null,x=(m==null?void 0:m.id)!==i().lastMessageId;return n(y=>{var A;const S=!l,j=s!==((A=y.messages[0])==null?void 0:A.channelId),$=S&&(y.messages.length===0||j);let I=[],k={...y.pagination};if($)I=f,k={nextCursor:d.nextCursor,pageSize:d.size,hasNext:d.hasNext};else if(S){const _=new Set(y.messages.map(G=>G.id));I=[...f.filter(G=>!_.has(G.id)&&(y.messages.length===0||G.createdAt>y.messages[0].createdAt)),...y.messages]}else{const _=new Set(y.messages.map(G=>G.id)),J=f.filter(G=>!_.has(G.id));I=[...y.messages,...J],k={nextCursor:d.nextCursor,pageSize:d.size,hasNext:d.hasNext}}return{messages:I,lastMessageId:(m==null?void 0:m.id)||null,pagination:k}}),x}catch(d){return console.error("메시지 목록 조회 실패:",d),!1}},loadMoreMessages:async s=>{const{pagination:l}=i();l.hasNext&&await i().fetchMessages(s,l.nextCursor,{...Ja})},startPolling:s=>{const l=i();if(l.pollingIntervals[s]){const m=l.pollingIntervals[s];typeof m=="number"&&clearTimeout(m)}let c=300;const d=3e3;n(m=>({pollingIntervals:{...m.pollingIntervals,[s]:!0}}));const f=async()=>{const m=i();if(!m.pollingIntervals[s])return;const x=await m.fetchMessages(s,null,Ja);if(!(i().messages.length==0)&&x?c=300:c=Math.min(c*1.5,d),i().pollingIntervals[s]){const S=setTimeout(f,c);n(j=>({pollingIntervals:{...j.pollingIntervals,[s]:S}}))}};f()},stopPolling:s=>{const{pollingIntervals:l}=i();if(l[s]){const c=l[s];typeof c=="number"&&clearTimeout(c),n(d=>{const f={...d.pollingIntervals};return delete f[s],{pollingIntervals:f}})}},createMessage:async(s,l)=>{try{n({isCreating:!0});const c=await R1(s,l),d=Ar.getState().updateReadStatus;return await d(s.channelId),n(f=>f.messages.some(x=>x.id===c.id)?f:{messages:[c,...f.messages],lastMessageId:c.id}),c}catch(c){throw console.error("메시지 생성 실패:",c),c}finally{n({isCreating:!1})}},updateMessage:async(s,l)=>{try{const c=await P1(s,{newContent:l});return n(d=>({messages:d.messages.map(f=>f.id===s?{...f,content:l}:f)})),c}catch(c){throw console.error("메시지 업데이트 실패:",c),c}},deleteMessage:async s=>{try{await M1(s),n(l=>({messages:l.messages.filter(c=>c.id!==s)}))}catch(l){throw console.error("메시지 삭제 실패:",l),l}}}));function _1({channel:n}){const[i,s]=Z.useState(""),[l,c]=Z.useState([]),[d,f]=Z.useState(!1),m=Vh(k=>k.createMessage),{currentUser:x}=et(),y=async k=>{if(k.preventDefault(),!(!i.trim()&&l.length===0)&&!d){f(!0);try{await m({content:i.trim(),channelId:n.id,authorId:(x==null?void 0:x.id)??""},l),s(""),c([])}catch(A){console.error("메시지 전송 실패:",A)}finally{f(!1)}}},S=k=>{const A=Array.from(k.target.files||[]);c(_=>[..._,...A]),k.target.value=""},j=k=>{c(A=>A.filter((_,J)=>J!==k))},$=k=>{if(k.key==="Enter"&&!k.shiftKey){if(console.log("Enter key pressed"),k.preventDefault(),k.nativeEvent.isComposing)return;y(k)}},I=(k,A)=>k.type.startsWith("image/")?h.jsxs(m1,{children:[h.jsx("img",{src:URL.createObjectURL(k),alt:k.name}),h.jsx(Ap,{onClick:()=>j(A),children:"×"})]},A):h.jsxs(Yh,{children:[h.jsx(g1,{children:"📎"}),h.jsx(y1,{children:k.name}),h.jsx(Ap,{onClick:()=>j(A),children:"×"})]},A);return Z.useEffect(()=>()=>{l.forEach(k=>{k.type.startsWith("image/")&&URL.revokeObjectURL(URL.createObjectURL(k))})},[l]),n?h.jsxs(h.Fragment,{children:[l.length>0&&!d&&h.jsx(h1,{children:l.map((k,A)=>I(k,A))}),h.jsxs(c1,{onSubmit:y,children:[h.jsxs(f1,{as:"label",children:["+",h.jsx("input",{type:"file",multiple:!0,onChange:S,style:{display:"none"}})]}),h.jsx(d1,{value:i,onChange:k=>s(k.target.value),onKeyDown:$,disabled:d,placeholder:d?"메시지 전송 중...":n.type==="PUBLIC"?`#${n.name}에 메시지 보내기`:"메시지 보내기"}),d&&h.jsx(x1,{})]})]}):null}/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */var hu=function(n,i){return hu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,l){s.__proto__=l}||function(s,l){for(var c in l)l.hasOwnProperty(c)&&(s[c]=l[c])},hu(n,i)};function T1(n,i){hu(n,i);function s(){this.constructor=n}n.prototype=i===null?Object.create(i):(s.prototype=i.prototype,new s)}var Oo=function(){return Oo=Object.assign||function(i){for(var s,l=1,c=arguments.length;ln?I():i!==!0&&(c=setTimeout(l?k:I,l===void 0?n-j:n))}return y.cancel=x,y}var Rr={Pixel:"Pixel",Percent:"Percent"},_p={unit:Rr.Percent,value:.8};function Tp(n){return typeof n=="number"?{unit:Rr.Percent,value:n*100}:typeof n=="string"?n.match(/^(\d*(\.\d+)?)px$/)?{unit:Rr.Pixel,value:parseFloat(n)}:n.match(/^(\d*(\.\d+)?)%$/)?{unit:Rr.Percent,value:parseFloat(n)}:(console.warn('scrollThreshold format is invalid. Valid formats: "120px", "50%"...'),_p):(console.warn("scrollThreshold should be string or number"),_p)}var $1=function(n){T1(i,n);function i(s){var l=n.call(this,s)||this;return l.lastScrollTop=0,l.actionTriggered=!1,l.startY=0,l.currentY=0,l.dragging=!1,l.maxPullDownDistance=0,l.getScrollableTarget=function(){return l.props.scrollableTarget instanceof HTMLElement?l.props.scrollableTarget:typeof l.props.scrollableTarget=="string"?document.getElementById(l.props.scrollableTarget):(l.props.scrollableTarget===null&&console.warn(`You are trying to pass scrollableTarget but it is null. This might + happen because the element may not have been added to DOM yet. + See https://github.com/ankeetmaini/react-infinite-scroll-component/issues/59 for more info. + `),null)},l.onStart=function(c){l.lastScrollTop||(l.dragging=!0,c instanceof MouseEvent?l.startY=c.pageY:c instanceof TouchEvent&&(l.startY=c.touches[0].pageY),l.currentY=l.startY,l._infScroll&&(l._infScroll.style.willChange="transform",l._infScroll.style.transition="transform 0.2s cubic-bezier(0,0,0.31,1)"))},l.onMove=function(c){l.dragging&&(c instanceof MouseEvent?l.currentY=c.pageY:c instanceof TouchEvent&&(l.currentY=c.touches[0].pageY),!(l.currentY=Number(l.props.pullDownToRefreshThreshold)&&l.setState({pullToRefreshThresholdBreached:!0}),!(l.currentY-l.startY>l.maxPullDownDistance*1.5)&&l._infScroll&&(l._infScroll.style.overflow="visible",l._infScroll.style.transform="translate3d(0px, "+(l.currentY-l.startY)+"px, 0px)")))},l.onEnd=function(){l.startY=0,l.currentY=0,l.dragging=!1,l.state.pullToRefreshThresholdBreached&&(l.props.refreshFunction&&l.props.refreshFunction(),l.setState({pullToRefreshThresholdBreached:!1})),requestAnimationFrame(function(){l._infScroll&&(l._infScroll.style.overflow="auto",l._infScroll.style.transform="none",l._infScroll.style.willChange="unset")})},l.onScrollListener=function(c){typeof l.props.onScroll=="function"&&setTimeout(function(){return l.props.onScroll&&l.props.onScroll(c)},0);var d=l.props.height||l._scrollableNode?c.target:document.documentElement.scrollTop?document.documentElement:document.body;if(!l.actionTriggered){var f=l.props.inverse?l.isElementAtTop(d,l.props.scrollThreshold):l.isElementAtBottom(d,l.props.scrollThreshold);f&&l.props.hasMore&&(l.actionTriggered=!0,l.setState({showLoader:!0}),l.props.next&&l.props.next()),l.lastScrollTop=d.scrollTop}},l.state={showLoader:!1,pullToRefreshThresholdBreached:!1,prevDataLength:s.dataLength},l.throttledOnScrollListener=N1(150,l.onScrollListener).bind(l),l.onStart=l.onStart.bind(l),l.onMove=l.onMove.bind(l),l.onEnd=l.onEnd.bind(l),l}return i.prototype.componentDidMount=function(){if(typeof this.props.dataLength>"u")throw new Error('mandatory prop "dataLength" is missing. The prop is needed when loading more content. Check README.md for usage');if(this._scrollableNode=this.getScrollableTarget(),this.el=this.props.height?this._infScroll:this._scrollableNode||window,this.el&&this.el.addEventListener("scroll",this.throttledOnScrollListener),typeof this.props.initialScrollY=="number"&&this.el&&this.el instanceof HTMLElement&&this.el.scrollHeight>this.props.initialScrollY&&this.el.scrollTo(0,this.props.initialScrollY),this.props.pullDownToRefresh&&this.el&&(this.el.addEventListener("touchstart",this.onStart),this.el.addEventListener("touchmove",this.onMove),this.el.addEventListener("touchend",this.onEnd),this.el.addEventListener("mousedown",this.onStart),this.el.addEventListener("mousemove",this.onMove),this.el.addEventListener("mouseup",this.onEnd),this.maxPullDownDistance=this._pullDown&&this._pullDown.firstChild&&this._pullDown.firstChild.getBoundingClientRect().height||0,this.forceUpdate(),typeof this.props.refreshFunction!="function"))throw new Error(`Mandatory prop "refreshFunction" missing. + Pull Down To Refresh functionality will not work + as expected. Check README.md for usage'`)},i.prototype.componentWillUnmount=function(){this.el&&(this.el.removeEventListener("scroll",this.throttledOnScrollListener),this.props.pullDownToRefresh&&(this.el.removeEventListener("touchstart",this.onStart),this.el.removeEventListener("touchmove",this.onMove),this.el.removeEventListener("touchend",this.onEnd),this.el.removeEventListener("mousedown",this.onStart),this.el.removeEventListener("mousemove",this.onMove),this.el.removeEventListener("mouseup",this.onEnd)))},i.prototype.componentDidUpdate=function(s){this.props.dataLength!==s.dataLength&&(this.actionTriggered=!1,this.setState({showLoader:!1}))},i.getDerivedStateFromProps=function(s,l){var c=s.dataLength!==l.prevDataLength;return c?Oo(Oo({},l),{prevDataLength:s.dataLength}):null},i.prototype.isElementAtTop=function(s,l){l===void 0&&(l=.8);var c=s===document.body||s===document.documentElement?window.screen.availHeight:s.clientHeight,d=Tp(l);return d.unit===Rr.Pixel?s.scrollTop<=d.value+c-s.scrollHeight+1:s.scrollTop<=d.value/100+c-s.scrollHeight+1},i.prototype.isElementAtBottom=function(s,l){l===void 0&&(l=.8);var c=s===document.body||s===document.documentElement?window.screen.availHeight:s.clientHeight,d=Tp(l);return d.unit===Rr.Pixel?s.scrollTop+c>=s.scrollHeight-d.value:s.scrollTop+c>=d.value/100*s.scrollHeight},i.prototype.render=function(){var s=this,l=Oo({height:this.props.height||"auto",overflow:"auto",WebkitOverflowScrolling:"touch"},this.props.style),c=this.props.hasChildren||!!(this.props.children&&this.props.children instanceof Array&&this.props.children.length),d=this.props.pullDownToRefresh&&this.props.height?{overflow:"auto"}:{};return St.createElement("div",{style:d,className:"infinite-scroll-component__outerdiv"},St.createElement("div",{className:"infinite-scroll-component "+(this.props.className||""),ref:function(f){return s._infScroll=f},style:l},this.props.pullDownToRefresh&&St.createElement("div",{style:{position:"relative"},ref:function(f){return s._pullDown=f}},St.createElement("div",{style:{position:"absolute",left:0,right:0,top:-1*this.maxPullDownDistance}},this.state.pullToRefreshThresholdBreached?this.props.releaseToRefreshContent:this.props.pullDownToRefreshContent)),this.props.children,!this.state.showLoader&&!c&&this.props.hasMore&&this.props.loader,this.state.showLoader&&this.props.hasMore&&this.props.loader,!this.props.hasMore&&this.props.endMessage))},i}(Z.Component);const O1=n=>n<1024?n+" B":n<1024*1024?(n/1024).toFixed(2)+" KB":n<1024*1024*1024?(n/(1024*1024)).toFixed(2)+" MB":(n/(1024*1024*1024)).toFixed(2)+" GB";function L1({channel:n}){const{messages:i,fetchMessages:s,loadMoreMessages:l,pagination:c,startPolling:d,stopPolling:f,updateMessage:m,deleteMessage:x}=Vh(),{binaryContents:y,fetchBinaryContent:S,clearBinaryContents:j,startPolling:$,clearAllPolling:I}=Rn(),{currentUser:k}=et(),[A,_]=Z.useState(null),[J,G]=Z.useState(null),[H,X]=Z.useState("");Z.useEffect(()=>{if(n!=null&&n.id)return s(n.id,null),d(n.id),()=>{f(n.id),I()}},[n==null?void 0:n.id,s,d,f,I]),Z.useEffect(()=>{i.forEach(V=>{var z;(z=V.attachments)==null||z.forEach(b=>{y[b.id]||S(b.id).then(W=>{W&&W.status==="PROCESSING"&&$(b.id)})})})},[i,S,$]),Z.useEffect(()=>()=>{const V=i.map(z=>{var b;return(b=z.attachments)==null?void 0:b.map(W=>W.id)}).flat();j(V),I()},[j,I]),Z.useEffect(()=>{const V=()=>{A&&_(null)};if(A)return document.addEventListener("click",V),()=>document.removeEventListener("click",V)},[A]);const D=async V=>{try{const{url:z,fileName:b}=V;if(z==null)return;const W=document.createElement("a");W.href=z,W.download=b,W.style.display="none",document.body.appendChild(W);try{const F=await(await window.showSaveFilePicker({suggestedName:V.fileName,types:[{description:"Files",accept:{"*/*":[".txt",".pdf",".doc",".docx",".xls",".xlsx",".jpg",".jpeg",".png",".gif"]}}]})).createWritable(),w=await(await fetch(z)).blob();await F.write(w),await F.close()}catch(P){P.name!=="AbortError"&&W.click()}document.body.removeChild(W),window.URL.revokeObjectURL(z)}catch(z){console.error("파일 다운로드 실패:",z)}},N=V=>V!=null&&V.length?(console.log("renderAttachments 호출됨",{attachments:V.map(z=>{var b;return{id:z.id,binaryContent:(b=y[z.id])==null?void 0:b.status}})}),V.map(z=>{const b=y[z.id];if(!b)return null;const W=b.contentType.startsWith("image/"),P=b.status;return P==="FAIL"?h.jsx(is,{children:h.jsxs(qa,{href:"#",style:{opacity:.5,backgroundColor:"#fff2f2"},onClick:F=>{F.preventDefault()},children:[h.jsx(Qa,{children:h.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",children:[h.jsx("path",{d:"M8 3C8 1.89543 8.89543 1 10 1H22L32 11V37C32 38.1046 31.1046 39 30 39H10C8.89543 39 8 38.1046 8 37V3Z",fill:"#ef4444",fillOpacity:"0.1"}),h.jsx("path",{d:"M22 1L32 11H24C22.8954 11 22 10.1046 22 9V1Z",fill:"#ef4444",fillOpacity:"0.3"}),h.jsx("path",{d:"M13 19H27M13 25H27M13 31H27",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round"})]})}),h.jsxs(Ga,{children:[h.jsx(Ka,{style:{color:"#ef4444"},children:z.fileName}),h.jsx(Xa,{style:{color:"#ef4444"},children:"업로드 실패"})]})]})},z.id):P==="PROCESSING"?h.jsx(is,{children:h.jsxs(qa,{href:"#",style:{opacity:.7,backgroundColor:"#fef3c7"},onClick:F=>{F.preventDefault()},children:[h.jsx(Qa,{children:h.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",children:[h.jsx("path",{d:"M8 3C8 1.89543 8.89543 1 10 1H22L32 11V37C32 38.1046 31.1046 39 30 39H10C8.89543 39 8 38.1046 8 37V3Z",fill:"#f59e0b",fillOpacity:"0.1"}),h.jsx("path",{d:"M22 1L32 11H24C22.8954 11 22 10.1046 22 9V1Z",fill:"#f59e0b",fillOpacity:"0.3"}),h.jsx("path",{d:"M13 19H27M13 25H27M13 31H27",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round"})]})}),h.jsxs(Ga,{children:[h.jsx(Ka,{style:{color:"#f59e0b"},children:z.fileName}),h.jsx(Xa,{style:{color:"#f59e0b"},children:"업로드 중..."})]})]})},z.id):b.url?W?h.jsx(is,{children:h.jsx(p1,{href:"#",onClick:F=>{F.preventDefault(),D(b)},children:h.jsx("img",{src:b.url,alt:b.fileName})})},b.url):h.jsx(is,{children:h.jsxs(qa,{href:"#",onClick:F=>{F.preventDefault(),D(b)},children:[h.jsx(Qa,{children:h.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",children:[h.jsx("path",{d:"M8 3C8 1.89543 8.89543 1 10 1H22L32 11V37C32 38.1046 31.1046 39 30 39H10C8.89543 39 8 38.1046 8 37V3Z",fill:"#0B93F6",fillOpacity:"0.1"}),h.jsx("path",{d:"M22 1L32 11H24C22.8954 11 22 10.1046 22 9V1Z",fill:"#0B93F6",fillOpacity:"0.3"}),h.jsx("path",{d:"M13 19H27M13 25H27M13 31H27",stroke:"#0B93F6",strokeWidth:"2",strokeLinecap:"round"})]})}),h.jsxs(Ga,{children:[h.jsx(Ka,{children:b.fileName}),h.jsx(Xa,{children:O1(b.size)})]})]})},b.url):null})):null,Q=V=>new Date(V).toLocaleTimeString(),le=()=>{n!=null&&n.id&&l(n.id)},Se=V=>{_(A===V?null:V)},ge=V=>{_(null);const z=i.find(b=>b.id===V);z&&(G(V),X(z.content))},pe=V=>{m(V,H).catch(z=>{console.error("메시지 수정 실패:",z),jr.emit("api-error",{error:z,alert:!0})}),G(null),X("")},Be=()=>{G(null),X("")},Fe=V=>{_(null),x(V)};return h.jsx(r1,{children:h.jsx("div",{id:"scrollableDiv",style:{height:"100%",overflow:"auto",display:"flex",flexDirection:"column-reverse"},children:h.jsx($1,{dataLength:i.length,next:le,hasMore:c.hasNext,loader:h.jsx("h4",{style:{textAlign:"center"},children:"메시지를 불러오는 중..."}),scrollableTarget:"scrollableDiv",style:{display:"flex",flexDirection:"column-reverse"},inverse:!0,endMessage:h.jsx("p",{style:{textAlign:"center"},children:h.jsx("b",{children:c.nextCursor!==null?"모든 메시지를 불러왔습니다":""})}),children:h.jsx(o1,{children:[...i].reverse().map(V=>{var W;const z=V.author,b=k&&z&&z.id===k.id;return h.jsxs(Hh,{children:[h.jsx(i1,{children:h.jsx(rn,{src:z&&z.profile?(W=y[z.profile.id])==null?void 0:W.url:Ct,alt:z&&z.username||"알 수 없음"})}),h.jsxs("div",{children:[h.jsxs(s1,{children:[h.jsx(l1,{children:z&&z.username||"알 수 없음"}),h.jsx(a1,{children:Q(V.createdAt)}),b&&h.jsxs(v1,{children:[h.jsx(w1,{onClick:P=>{P.stopPropagation(),Se(V.id)},children:"⋯"}),A===V.id&&h.jsxs(S1,{onClick:P=>P.stopPropagation(),children:[h.jsx(Rp,{onClick:()=>ge(V.id),children:"✏️ 수정"}),h.jsx(Rp,{onClick:()=>Fe(V.id),children:"🗑️ 삭제"})]})]})]}),J===V.id?h.jsxs(k1,{children:[h.jsx(C1,{value:H,onChange:P=>X(P.target.value),onKeyDown:P=>{P.key==="Escape"?Be():P.key==="Enter"&&(P.ctrlKey||P.metaKey)&&(P.preventDefault(),pe(V.id))},placeholder:"메시지를 입력하세요..."}),h.jsxs(E1,{children:[h.jsx(Pp,{variant:"secondary",onClick:Be,children:"취소"}),h.jsx(Pp,{variant:"primary",onClick:()=>pe(V.id),children:"저장"})]})]}):h.jsx(u1,{children:V.content}),N(V.attachments)]})]},V.id)})})})})})}function D1({channel:n}){return n?h.jsxs(Vv,{children:[h.jsx(j1,{channel:n}),h.jsx(L1,{channel:n}),h.jsx(_1,{channel:n})]}):h.jsx(qv,{children:h.jsxs(Qv,{children:[h.jsx(Gv,{children:"👋"}),h.jsx(Kv,{children:"채널을 선택해주세요"}),h.jsxs(Xv,{children:["왼쪽의 채널 목록에서 채널을 선택하여",h.jsx("br",{}),"대화를 시작하세요."]})]})})}function I1(n,i="yyyy-MM-dd HH:mm:ss"){if(!n||!(n instanceof Date)||isNaN(n.getTime()))return"";const s=n.getFullYear(),l=String(n.getMonth()+1).padStart(2,"0"),c=String(n.getDate()).padStart(2,"0"),d=String(n.getHours()).padStart(2,"0"),f=String(n.getMinutes()).padStart(2,"0"),m=String(n.getSeconds()).padStart(2,"0");return i.replace("yyyy",s.toString()).replace("MM",l).replace("dd",c).replace("HH",d).replace("mm",f).replace("ss",m)}const b1=E.div` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.7); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; +`,z1=E.div` + background: ${({theme:n})=>n.colors.background.primary}; + border-radius: 8px; + width: 500px; + max-width: 90%; + padding: 24px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); +`,B1=E.div` + display: flex; + align-items: center; + margin-bottom: 16px; +`,F1=E.div` + color: ${({theme:n})=>n.colors.status.error}; + font-size: 24px; + margin-right: 12px; +`,U1=E.h3` + color: ${({theme:n})=>n.colors.text.primary}; + margin: 0; + font-size: 18px; +`,H1=E.div` + background: ${({theme:n})=>n.colors.background.tertiary}; + color: ${({theme:n})=>n.colors.text.muted}; + padding: 2px 8px; + border-radius: 4px; + font-size: 14px; + margin-left: auto; +`,Y1=E.p` + color: ${({theme:n})=>n.colors.text.secondary}; + margin-bottom: 20px; + line-height: 1.5; + font-weight: 500; +`,V1=E.div` + margin-bottom: 20px; + background: ${({theme:n})=>n.colors.background.secondary}; + border-radius: 6px; + padding: 12px; +`,Ao=E.div` + display: flex; + margin-bottom: 8px; + font-size: 14px; +`,Ro=E.span` + color: ${({theme:n})=>n.colors.text.muted}; + min-width: 100px; +`,Po=E.span` + color: ${({theme:n})=>n.colors.text.secondary}; + word-break: break-word; +`,W1=E.button` + background: ${({theme:n})=>n.colors.brand.primary}; + color: white; + border: none; + border-radius: 4px; + padding: 8px 16px; + font-size: 14px; + font-weight: 500; + cursor: pointer; + width: 100%; + + &:hover { + background: ${({theme:n})=>n.colors.brand.hover}; + } +`;function q1({isOpen:n,onClose:i,error:s}){var $,I;if(!n)return null;console.log({error:s});const l=($=s==null?void 0:s.response)==null?void 0:$.data,c=(l==null?void 0:l.status)||((I=s==null?void 0:s.response)==null?void 0:I.status)||"오류",d=(l==null?void 0:l.code)||"",f=(l==null?void 0:l.message)||(s==null?void 0:s.message)||"알 수 없는 오류가 발생했습니다.",m=l!=null&&l.timestamp?new Date(l.timestamp):new Date,x=I1(m),y=(l==null?void 0:l.exceptionType)||"",S=(l==null?void 0:l.details)||{},j=(l==null?void 0:l.requestId)||"";return h.jsx(b1,{onClick:i,children:h.jsxs(z1,{onClick:k=>k.stopPropagation(),children:[h.jsxs(B1,{children:[h.jsx(F1,{children:"⚠️"}),h.jsx(U1,{children:"오류가 발생했습니다"}),h.jsxs(H1,{children:[c,d?` (${d})`:""]})]}),h.jsx(Y1,{children:f}),h.jsxs(V1,{children:[h.jsxs(Ao,{children:[h.jsx(Ro,{children:"시간:"}),h.jsx(Po,{children:x})]}),j&&h.jsxs(Ao,{children:[h.jsx(Ro,{children:"요청 ID:"}),h.jsx(Po,{children:j})]}),d&&h.jsxs(Ao,{children:[h.jsx(Ro,{children:"에러 코드:"}),h.jsx(Po,{children:d})]}),y&&h.jsxs(Ao,{children:[h.jsx(Ro,{children:"예외 유형:"}),h.jsx(Po,{children:y})]}),Object.keys(S).length>0&&h.jsxs(Ao,{children:[h.jsx(Ro,{children:"상세 정보:"}),h.jsx(Po,{children:Object.entries(S).map(([k,A])=>h.jsxs("div",{children:[k,": ",String(A)]},k))})]})]}),h.jsx(W1,{onClick:i,children:"확인"})]})})}const Q1=E.div` + width: 240px; + background: ${ee.colors.background.secondary}; + border-left: 1px solid ${ee.colors.border.primary}; + display: flex; + flex-direction: column; + height: 100%; +`,G1=E.div` + padding: 0px 16px; + height: 48px; + font-size: 14px; + font-weight: bold; + color: ${ee.colors.text.muted}; + text-transform: uppercase; + border-bottom: 1px solid ${ee.colors.border.primary}; +`,K1=E.div` + display: flex; + justify-content: space-between; + align-items: center; +`,X1=E.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${ee.colors.text.muted}; + &:hover { + background: ${ee.colors.background.primary}; + cursor: pointer; + } +`,J1=E(Dr)` + margin-right: 12px; +`;E(rn)``;const Z1=E.div` + display: flex; + align-items: center; +`;function ew({member:n}){var l,c,d;const{binaryContents:i,fetchBinaryContent:s}=Rn();return Z.useEffect(()=>{var f;(f=n.profile)!=null&&f.id&&!i[n.profile.id]&&s(n.profile.id)},[(l=n.profile)==null?void 0:l.id,i,s]),h.jsxs(X1,{children:[h.jsxs(J1,{children:[h.jsx(rn,{src:(c=n.profile)!=null&&c.id&&((d=i[n.profile.id])==null?void 0:d.url)||Ct,alt:n.username}),h.jsx(Fo,{$online:n.online})]}),h.jsx(Z1,{children:n.username})]})}function tw({member:n,onClose:i}){var I,k,A;const{binaryContents:s,fetchBinaryContent:l}=Rn(),{currentUser:c,updateUserRole:d}=et(),[f,m]=Z.useState(n.role),[x,y]=Z.useState(!1);Z.useEffect(()=>{var _;(_=n.profile)!=null&&_.id&&!s[n.profile.id]&&l(n.profile.id)},[(I=n.profile)==null?void 0:I.id,s,l]);const S={[jn.USER]:{name:"사용자",color:"#2ed573"},[jn.CHANNEL_MANAGER]:{name:"채널 관리자",color:"#ff4757"},[jn.ADMIN]:{name:"어드민",color:"#0097e6"}},j=_=>{m(_),y(!0)},$=()=>{d(n.id,f),y(!1)};return h.jsx(ow,{onClick:i,children:h.jsxs(iw,{onClick:_=>_.stopPropagation(),children:[h.jsx("h2",{children:"사용자 정보"}),h.jsxs(sw,{children:[h.jsx(lw,{src:(k=n.profile)!=null&&k.id&&((A=s[n.profile.id])==null?void 0:A.url)||Ct,alt:n.username}),h.jsx(aw,{children:n.username}),h.jsx(uw,{children:n.email}),h.jsx(cw,{$online:n.online,children:n.online?"온라인":"오프라인"}),(c==null?void 0:c.role)===jn.ADMIN?h.jsx(rw,{value:f,onChange:_=>j(_.target.value),children:Object.entries(S).map(([_,J])=>h.jsx("option",{value:_,style:{marginTop:"8px",textAlign:"center"},children:J.name},_))}):h.jsx(nw,{style:{backgroundColor:S[n.role].color},children:S[n.role].name})]}),h.jsx(dw,{children:(c==null?void 0:c.role)===jn.ADMIN&&x&&h.jsx(fw,{onClick:$,disabled:!x,$secondary:!x,children:"저장"})})]})})}const nw=E.div` + padding: 6px 16px; + border-radius: 20px; + font-size: 13px; + font-weight: 600; + color: white; + margin-top: 12px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + letter-spacing: 0.3px; +`,rw=E.select` + padding: 10px 16px; + border-radius: 8px; + border: 1.5px solid ${ee.colors.border.primary}; + background: ${ee.colors.background.primary}; + color: ${ee.colors.text.primary}; + font-size: 14px; + width: 140px; + cursor: pointer; + transition: all 0.2s ease; + margin-top: 12px; + font-weight: 500; + + &:hover { + border-color: ${ee.colors.brand.primary}; + } + + &:focus { + outline: none; + border-color: ${ee.colors.brand.primary}; + box-shadow: 0 0 0 2px ${ee.colors.brand.primary}20; + } + + option { + background: ${ee.colors.background.primary}; + color: ${ee.colors.text.primary}; + padding: 12px; + } +`,ow=E.div` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.6); + backdrop-filter: blur(4px); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; +`,iw=E.div` + background: ${ee.colors.background.secondary}; + padding: 40px; + border-radius: 16px; + width: 100%; + max-width: 420px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12); + + h2 { + color: ${ee.colors.text.primary}; + margin-bottom: 32px; + text-align: center; + font-size: 26px; + font-weight: 600; + letter-spacing: -0.5px; + } +`,sw=E.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 32px; + padding: 24px; + background: ${ee.colors.background.primary}; + border-radius: 12px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); +`,lw=E.img` + width: 140px; + height: 140px; + border-radius: 50%; + margin-bottom: 20px; + object-fit: cover; + border: 4px solid ${ee.colors.background.secondary}; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); +`,aw=E.div` + font-size: 22px; + font-weight: 600; + color: ${ee.colors.text.primary}; + margin-bottom: 8px; + letter-spacing: -0.3px; +`,uw=E.div` + font-size: 14px; + color: ${ee.colors.text.muted}; + margin-bottom: 16px; + font-weight: 500; +`,cw=E.div` + padding: 6px 16px; + border-radius: 20px; + font-size: 13px; + font-weight: 600; + background-color: ${({$online:n,theme:i})=>n?i.colors.status.online:i.colors.status.offline}; + color: white; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + letter-spacing: 0.3px; +`,dw=E.div` + display: flex; + gap: 12px; + margin-top: 24px; +`,fw=E.button` + width: 100%; + padding: 12px; + border: none; + border-radius: 8px; + background: ${({$secondary:n,theme:i})=>n?"transparent":i.colors.brand.primary}; + color: ${({$secondary:n,theme:i})=>n?i.colors.text.primary:"white"}; + cursor: pointer; + font-weight: 600; + font-size: 15px; + transition: all 0.2s ease; + border: ${({$secondary:n,theme:i})=>n?`1.5px solid ${i.colors.border.primary}`:"none"}; + + &:hover { + background: ${({$secondary:n,theme:i})=>n?i.colors.background.hover:i.colors.brand.hover}; + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } +`,pw=async()=>(await Le.get("/notifications")).data,hw=async n=>{await Le.delete(`/notifications/${n}`)},Wh=Kn(n=>({notifications:[],fetchNotifications:async()=>{const i=await pw();n({notifications:i})},readNotification:async i=>{await hw(i),n(s=>({notifications:s.notifications.filter(l=>l.id!==i)}))}}));var hs={exports:{}},mw=hs.exports,Np;function qh(){return Np||(Np=1,function(n,i){(function(s,l){n.exports=l()})(mw,function(){var s=1e3,l=6e4,c=36e5,d="millisecond",f="second",m="minute",x="hour",y="day",S="week",j="month",$="quarter",I="year",k="date",A="Invalid Date",_=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,J=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,G={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(V){var z=["th","st","nd","rd"],b=V%100;return"["+V+(z[(b-20)%10]||z[b]||z[0])+"]"}},H=function(V,z,b){var W=String(V);return!W||W.length>=z?V:""+Array(z+1-W.length).join(b)+V},X={s:H,z:function(V){var z=-V.utcOffset(),b=Math.abs(z),W=Math.floor(b/60),P=b%60;return(z<=0?"+":"-")+H(W,2,"0")+":"+H(P,2,"0")},m:function V(z,b){if(z.date()1)return V(B[0])}else{var w=z.name;N[w]=z,P=w}return!W&&P&&(D=P),P||!W&&D},ge=function(V,z){if(le(V))return V.clone();var b=typeof z=="object"?z:{};return b.date=V,b.args=arguments,new Be(b)},pe=X;pe.l=Se,pe.i=le,pe.w=function(V,z){return ge(V,{locale:z.$L,utc:z.$u,x:z.$x,$offset:z.$offset})};var Be=function(){function V(b){this.$L=Se(b.locale,null,!0),this.parse(b),this.$x=this.$x||b.x||{},this[Q]=!0}var z=V.prototype;return z.parse=function(b){this.$d=function(W){var P=W.date,F=W.utc;if(P===null)return new Date(NaN);if(pe.u(P))return new Date;if(P instanceof Date)return new Date(P);if(typeof P=="string"&&!/Z$/i.test(P)){var B=P.match(_);if(B){var w=B[2]-1||0,L=(B[7]||"0").substring(0,3);return F?new Date(Date.UTC(B[1],w,B[3]||1,B[4]||0,B[5]||0,B[6]||0,L)):new Date(B[1],w,B[3]||1,B[4]||0,B[5]||0,B[6]||0,L)}}return new Date(P)}(b),this.init()},z.init=function(){var b=this.$d;this.$y=b.getFullYear(),this.$M=b.getMonth(),this.$D=b.getDate(),this.$W=b.getDay(),this.$H=b.getHours(),this.$m=b.getMinutes(),this.$s=b.getSeconds(),this.$ms=b.getMilliseconds()},z.$utils=function(){return pe},z.isValid=function(){return this.$d.toString()!==A},z.isSame=function(b,W){var P=ge(b);return this.startOf(W)<=P&&P<=this.endOf(W)},z.isAfter=function(b,W){return ge(b)0,N<=D.r||!D.r){N<=1&&X>0&&(D=G[X-1]);var Q=J[D.l];I&&(N=I(""+N)),A=typeof Q=="string"?Q.replace("%d",N):Q(N,S,D.l,_);break}}if(S)return A;var le=_?J.future:J.past;return typeof le=="function"?le(A):le.replace("%s",A)},d.to=function(y,S){return m(y,S,this,!0)},d.from=function(y,S){return m(y,S,this)};var x=function(y){return y.$u?c.utc():c()};d.toNow=function(y){return this.to(x(this),y)},d.fromNow=function(y){return this.from(x(this),y)}}})}(ms)),ms.exports}var vw=xw();const ww=mu(vw);var gs={exports:{}},Sw=gs.exports,Op;function kw(){return Op||(Op=1,function(n,i){(function(s,l){n.exports=l(qh())})(Sw,function(s){function l(f){return f&&typeof f=="object"&&"default"in f?f:{default:f}}var c=l(s),d={name:"ko",weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),ordinal:function(f){return f+"일"},formats:{LT:"A h:mm",LTS:"A h:mm:ss",L:"YYYY.MM.DD.",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 A h:mm",LLLL:"YYYY년 MMMM D일 dddd A h:mm",l:"YYYY.MM.DD.",ll:"YYYY년 MMMM D일",lll:"YYYY년 MMMM D일 A h:mm",llll:"YYYY년 MMMM D일 dddd A h:mm"},meridiem:function(f){return f<12?"오전":"오후"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇 초",m:"1분",mm:"%d분",h:"한 시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한 달",MM:"%d달",y:"일 년",yy:"%d년"}};return c.default.locale(d,null,!0),d})}(gs)),gs.exports}kw();Ru.extend(ww);Ru.locale("ko");const Cw=E.div` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.5); + opacity: ${({$isOpen:n})=>n?1:0}; + visibility: ${({$isOpen:n})=>n?"visible":"hidden"}; + transition: all 0.3s ease; + z-index: 1000; +`,Ew=E.div` + position: fixed; + top: 0; + right: 0; + width: 360px; + height: 100vh; + background: ${({theme:n})=>n.colors.background.primary}; + box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1); + transform: translateX(${({$isOpen:n})=>n?"0":"100%"}); + transition: transform 0.3s ease; + z-index: 1001; + display: flex; + flex-direction: column; +`,jw=E.div` + padding: 0px 16px; + height: 48px; + font-size: 14px; + font-weight: bold; + color: ${ee.colors.text.muted}; + text-transform: uppercase; + border-bottom: 1px solid ${({theme:n})=>n.colors.border.primary}; + display: flex; + justify-content: space-between; + align-items: center; +`,Aw=E.h2` + margin: 0; + font-size: 18px; + font-weight: 600; + color: ${({theme:n})=>n.colors.text.primary}; + text-transform: none; +`,Rw=E.button` + background: none; + border: none; + padding: 8px; + cursor: pointer; + color: ${({theme:n})=>n.colors.text.muted}; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + color: ${({theme:n})=>n.colors.text.primary}; + } +`,Pw=E.div` + flex: 1; + overflow-y: auto; + padding: 16px; + display: flex; + flex-direction: column; + gap: 12px; + width: 100%; + box-sizing: border-box; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background: ${({theme:n})=>n.colors.background.primary}; + } + + &::-webkit-scrollbar-thumb { + background: ${({theme:n})=>n.colors.border.primary}; + border-radius: 3px; + } + + &::-webkit-scrollbar-thumb:hover { + background: ${({theme:n})=>n.colors.text.muted}; + } +`,Mw=E.div` + position: relative; + flex: 1; +`,Qh=E.button` + position: absolute; + top: 0; + right: 0; + background: none; + border: none; + padding: 4px; + cursor: pointer; + color: ${({theme:n})=>n.colors.text.muted}; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + opacity: 0; + + &:hover { + background: ${({theme:n})=>n.colors.background.hover}; + color: ${({theme:n})=>n.colors.text.primary}; + } +`,_w=E.div` + background: ${({theme:n})=>n.colors.background.primary}; + border-radius: 8px; + padding: 16px; + cursor: pointer; + transition: all 0.2s ease; + border-left: 4px solid ${({theme:n})=>n.colors.brand.primary}; + width: 100%; + box-sizing: border-box; + position: relative; + + &:hover { + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); + + ${Qh} { + opacity: 1; + } + } +`,Tw=E.h4` + color: ${({theme:n})=>n.colors.text.primary}; + margin: 0 0 8px 0; + font-size: 15px; + font-weight: 600; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 300px; + text-transform: none; +`,Nw=E.p` + color: ${({theme:n})=>n.colors.text.secondary}; + margin: 0 0 8px 0; + font-size: 14px; + line-height: 1.4; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + max-width: 300px; + word-break: break-word; + text-transform: none; +`,$w=E.span` + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 12px; +`,Ow=E.div` + text-align: center; + padding: 32px 16px; + color: ${({theme:n})=>n.colors.text.muted}; + font-size: 14px; +`,Lw=E.div` + position: absolute; + top: -30px; + right: 0; + background: ${({theme:n})=>n.colors.background.secondary}; + color: ${({theme:n})=>n.colors.text.primary}; + padding: 4px 8px; + border-radius: 4px; + font-size: 12px; + opacity: ${({$show:n})=>n?1:0}; + transition: opacity 0.2s ease; + pointer-events: none; + white-space: nowrap; +`,Dw=({isOpen:n,onClose:i})=>{const{notifications:s,readNotification:l}=Wh(),[c,d]=Z.useState(null),f=async x=>{await l(x.id)},m=async(x,y,S)=>{x.stopPropagation();try{await navigator.clipboard.writeText(y),d(S),setTimeout(()=>d(null),2e3)}catch(j){console.error("클립보드 복사 실패:",j)}};return h.jsxs(h.Fragment,{children:[h.jsx(Cw,{$isOpen:n,onClick:i}),h.jsxs(Ew,{$isOpen:n,children:[h.jsxs(jw,{children:[h.jsxs(Aw,{children:["알림 ",s.length>0&&`(${s.length})`]}),h.jsx(Rw,{onClick:i,children:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),h.jsx(Pw,{children:s.length===0?h.jsx(Ow,{children:"새로운 알림이 없습니다"}):s.map(x=>h.jsx(_w,{onClick:()=>f(x),children:h.jsxs(Mw,{children:[h.jsx(Tw,{children:x.title}),h.jsx(Nw,{children:x.content}),h.jsx($w,{children:Ru(new Date(x.createdAt)).fromNow()}),h.jsx(Qh,{onClick:y=>m(y,x.content,x.id),title:"내용 복사",children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),h.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),h.jsx(Lw,{$show:c===x.id,children:"복사되었습니다"})]})},x.id))})]})]})},Iw=E.div` + position: relative; + cursor: pointer; + padding: 8px; + border-radius: 50%; + transition: background-color 0.2s ease; + + &:hover { + background-color: ${({theme:n})=>n.colors.background.hover}; + } +`,bw=E.div` + position: absolute; + top: 5px; + right: 5px; + background-color: ${({theme:n})=>n.colors.status.error}; + color: white; + font-size: 12px; + font-weight: 600; + min-width: 18px; + height: 18px; + border-radius: 9px; + display: flex; + align-items: center; + justify-content: center; + padding: 0 4px; + transform: translate(25%, -25%); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +`,zw=()=>{const{notifications:n,fetchNotifications:i}=Wh(),[s,l]=Z.useState(!1);Z.useEffect(()=>{i();const d=setInterval(i,1e4);return()=>clearInterval(d)},[i]);const c=n.length;return h.jsxs(h.Fragment,{children:[h.jsxs(Iw,{onClick:()=>l(!0),children:[h.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),h.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]}),c>0&&h.jsx(bw,{children:c>99?"99+":c})]}),h.jsx(Dw,{isOpen:s,onClose:()=>l(!1)})]})};function Bw(){const n=Nr(f=>f.users),i=Nr(f=>f.fetchUsers),{currentUser:s}=et(),[l,c]=Z.useState(null);Z.useEffect(()=>{i()},[i]);const d=[...n].sort((f,m)=>f.id===(s==null?void 0:s.id)?-1:m.id===(s==null?void 0:s.id)?1:f.online&&!m.online?-1:!f.online&&m.online?1:f.username.localeCompare(m.username));return h.jsxs(Q1,{children:[h.jsx(G1,{children:h.jsxs(K1,{children:["멤버 목록 - ",n.length,h.jsx(zw,{})]})}),d.map(f=>h.jsx("div",{onClick:()=>c(f),children:h.jsx(ew,{member:f},f.id)},f.id)),l&&h.jsx(tw,{member:l,onClose:()=>c(null)})]})}function Fw(){const{logout:n,fetchCsrfToken:i,refreshToken:s}=et(),{fetchUsers:l}=Nr(),[c,d]=Z.useState(null),[f,m]=Z.useState(null),[x,y]=Z.useState(!1),[S,j]=Z.useState(!0),{currentUser:$}=et();Z.useEffect(()=>{i(),s()},[]),Z.useEffect(()=>{(async()=>{try{if($)try{await l()}catch(A){console.warn("사용자 상태 업데이트 실패. 로그아웃합니다.",A),n()}}catch(A){console.error("초기화 오류:",A)}finally{j(!1)}})()},[$,l,n]),Z.useEffect(()=>{const k=G=>{G!=null&&G.error&&m(G.error),G!=null&&G.alert&&y(!0)},A=()=>{n()},_=jr.on("api-error",k),J=jr.on("auth-error",A);return()=>{_("api-error",k),J("auth-error",A)}},[n]),Z.useEffect(()=>{if($){const k=setInterval(()=>{l()},6e4);return()=>{clearInterval(k)}}},[$,l]);const I=()=>{y(!1),m(null)};return S?h.jsx(Vf,{theme:ee,children:h.jsx(Hw,{children:h.jsx(Yw,{})})}):h.jsxs(Vf,{theme:ee,children:[$?h.jsxs(Uw,{children:[h.jsx(Hv,{currentUser:$,activeChannel:c,onChannelSelect:d}),h.jsx(D1,{channel:c}),h.jsx(Bw,{})]}):h.jsx(ev,{isOpen:!0,onClose:()=>{}}),h.jsx(q1,{isOpen:x,onClose:I,error:f})]})}const Uw=E.div` + display: flex; + height: 100vh; + width: 100vw; + position: relative; +`,Hw=E.div` + display: flex; + justify-content: center; + align-items: center; + height: 100vh; + width: 100vw; + background-color: ${({theme:n})=>n.colors.background.primary}; +`,Yw=E.div` + width: 40px; + height: 40px; + border: 4px solid ${({theme:n})=>n.colors.background.tertiary}; + border-top: 4px solid ${({theme:n})=>n.colors.brand.primary}; + border-radius: 50%; + animation: spin 1s linear infinite; + + @keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } + } +`,Gh=document.getElementById("root");if(!Gh)throw new Error("Root element not found");ty.createRoot(Gh).render(h.jsx(Z.StrictMode,{children:h.jsx(Fw,{})})); diff --git a/src/main/resources/static/assets/index-kQJbKSsj.css b/src/main/resources/static/assets/index-kQJbKSsj.css new file mode 100644 index 000000000..096eb4112 --- /dev/null +++ b/src/main/resources/static/assets/index-kQJbKSsj.css @@ -0,0 +1 @@ +:root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color-scheme:light dark;color:#ffffffde;background-color:#242424;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}a{font-weight:500;color:#646cff;text-decoration:inherit}a:hover{color:#535bf2}body{margin:0;display:flex;place-items:center;min-width:320px;min-height:100vh}h1{font-size:3.2em;line-height:1.1}button{border-radius:8px;border:1px solid transparent;padding:.6em 1.2em;font-size:1em;font-weight:500;font-family:inherit;background-color:#1a1a1a;cursor:pointer;transition:border-color .25s}button:hover{border-color:#646cff}button:focus,button:focus-visible{outline:4px auto -webkit-focus-ring-color}@media (prefers-color-scheme: light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:#f9f9f9}} diff --git a/src/main/resources/static/favicon.ico b/src/main/resources/static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..479bed6a3da0a8dbdd08a51d81b30e4d4fabae89 GIT binary patch literal 1588 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE3?yBabR7dyEa{HEjtmSN`?>!lvI6;x#X;^) z4C~IxyacIC_6YK2V5m}KU}$JzVE6?TYIwoGP-?)y@G60U!Dv>Mu*Du8ycRt4Yw>0&$ytddU zdTHwA$vlU)7;*ZQn^d>r9eiw}SEV3v&DP3PpZVm?c2D=&D? zJg+7dT;x9cg;(mDqrovi2QemjySudY+_R1aaySb-B8!2p69!>MhFNnYfC{QST^vI! zPM@6=9?WDY()wLtM|S>=KoQ44K~Zk4us5=<8xs!eeY>~&=ly4!jD%AXj+wvro>aU~ zrMO$=?`j4U&ZyW$Je*!Zo0>H2RZVqmn^V&mZ(9Dkv!~|IuDF1RBN|EPJE zX3ok)rzF<3&vZKWEj4ag73&t}uJvVk^<~M;*V0n54#8@&v!WGjE_hAaeAZEF z$~V4aF>{^dUc7o%=f8f9m%*2vzjfI@vJ2Z97)VU5x-s2*r@e{H>FEn3A3Dr3G&8U| z)>wFiQO&|Yl6}UkXAQ>%q$jNWac-tTL*)AEyto|onkmnmcJLf?71w_<>4WODmBMxF zwGM7``txcQgT`x>(tH-DrT2Kg=4LzpNv>|+a@TgYDZ`5^$KJVb`K=%k^tRpoxP|4? zwXb!O5~dXYKYt*j(YSx+#_rP{TNcK=40T|)+k3s|?t||EQTgwGgs{E0Y+(QPL&Wx4 zMP23By&sn`zn7oCQQLp%-(Axm|M=5-u;TlFiTn5B^PWnb%fAPV8r2flh?11Vl2ohY zqEsNoU}Ruqple{LYiJr`U}|M-Vr62aZD3$!V6dZTmJ5o8-29Zxv`X9>PU+TH>UWRL)v7?M$%n`C9>lAm0fo0?Z*WfcHaTFhX${Qqu! zG&Nv5t*kOqGt)Cl7z{0q_!){?fojB&%z>&2&rB)F04ce=Mv()kL=s7fZ)R?4No7GQ z1K3si1$pWAo5K9i%<&BYs$wuSHMcY{Gc&O;(${(hEL0izk<1CstV(4taB`Zm$nFhL zDhx>~G{}=7Ei)$-=zaa%ypo*!bp5o%vdrZCykdPs#ORw@rkW)uCz=~4Cz={1nkQNs oC7PHSBpVtgnwc6|q*&+yb?5=zccWrGsMu%lboFyt=akR{0N~++#sB~S literal 0 HcmV?d00001 diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 000000000..fd56b43a0 --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,26 @@ + + + + + + Discodeit + + + + + +
+ + diff --git a/src/test/java/com/sprint/mission/discodeit/controller/AuthControllerTest.java b/src/test/java/com/sprint/mission/discodeit/controller/AuthControllerTest.java new file mode 100644 index 000000000..ee35ecb2d --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/AuthControllerTest.java @@ -0,0 +1,107 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.service.AuthService; +import com.sprint.mission.discodeit.service.UserService; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class AuthControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private UserDetailsService userDetailsService; + + @MockitoBean + private AuthService authService; + + @MockitoBean + private UserService userService; + + @Test + @DisplayName("현재 사용자 정보 조회 - 인증되지 않은 사용자") + void me_Unauthorized() throws Exception { + // When & Then + mockMvc.perform(get("/api/auth/me") + .with(csrf())) + .andExpect(status().isForbidden()); + } + + @Test + @DisplayName("권한 업데이트 - 성공") + void updateRole_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + RoleUpdateRequest request = new RoleUpdateRequest(userId, Role.ADMIN); + UserDto updatedUserDto = new UserDto( + userId, + "testuser", + "test@example.com", + null, + false, + Role.ADMIN + ); + UserDto mockUserDto = new UserDto(userId, "testuser", "test@example.com", null, false, + Role.USER); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(mockUserDto, "password"); + + given(authService.updateRole(any(RoleUpdateRequest.class))).willReturn(updatedUserDto); + + // When & Then + mockMvc.perform(put("/api/auth/role") + .with(csrf()) + .with(user(userDetails)) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(userId.toString())) + .andExpect(jsonPath("$.role").value("ADMIN")); + } + + @Test + @DisplayName("권한 업데이트 - 인증되지 않은 사용자") + void updateRole_Unauthorized() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + RoleUpdateRequest request = new RoleUpdateRequest(userId, Role.ADMIN); + + // When & Then + mockMvc.perform(put("/api/auth/role") + .with(csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isForbidden()); + } + + +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/controller/BinaryContentControllerTest.java b/src/test/java/com/sprint/mission/discodeit/controller/BinaryContentControllerTest.java new file mode 100644 index 000000000..d33bfdd78 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/BinaryContentControllerTest.java @@ -0,0 +1,156 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doReturn; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.exception.binarycontent.BinaryContentNotFoundException; +import com.sprint.mission.discodeit.service.BinaryContentService; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.FilterType; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(value = BinaryContentController.class, + excludeFilters = @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = ".*\\.security\\.jwt\\..*")) +@AutoConfigureMockMvc(addFilters = false) +class BinaryContentControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private BinaryContentService binaryContentService; + + @MockitoBean + private BinaryContentStorage binaryContentStorage; + + @Test + @DisplayName("바이너리 컨텐츠 조회 성공 테스트") + void find_Success() throws Exception { + // Given + UUID binaryContentId = UUID.randomUUID(); + BinaryContentDto binaryContent = new BinaryContentDto( + binaryContentId, + "test.jpg", + 10240L, + MediaType.IMAGE_JPEG_VALUE + ); + + given(binaryContentService.find(binaryContentId)).willReturn(binaryContent); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}", binaryContentId) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(binaryContentId.toString())) + .andExpect(jsonPath("$.fileName").value("test.jpg")) + .andExpect(jsonPath("$.size").value(10240)) + .andExpect(jsonPath("$.contentType").value(MediaType.IMAGE_JPEG_VALUE)); + } + + @Test + @DisplayName("바이너리 컨텐츠 조회 실패 테스트 - 존재하지 않는 컨텐츠") + void find_Failure_BinaryContentNotFound() throws Exception { + // Given + UUID nonExistentId = UUID.randomUUID(); + + given(binaryContentService.find(nonExistentId)) + .willThrow(BinaryContentNotFoundException.withId(nonExistentId)); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}", nonExistentId) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("ID 목록으로 바이너리 컨텐츠 조회 성공 테스트") + void findAllByIdIn_Success() throws Exception { + // Given + UUID id1 = UUID.randomUUID(); + UUID id2 = UUID.randomUUID(); + + List binaryContentIds = List.of(id1, id2); + + List binaryContents = List.of( + new BinaryContentDto(id1, "test1.jpg", 10240L, MediaType.IMAGE_JPEG_VALUE), + new BinaryContentDto(id2, "test2.pdf", 20480L, MediaType.APPLICATION_PDF_VALUE) + ); + + given(binaryContentService.findAllByIdIn(binaryContentIds)).willReturn(binaryContents); + + // When & Then + mockMvc.perform(get("/api/binaryContents") + .param("binaryContentIds", id1.toString(), id2.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(id1.toString())) + .andExpect(jsonPath("$[0].fileName").value("test1.jpg")) + .andExpect(jsonPath("$[1].id").value(id2.toString())) + .andExpect(jsonPath("$[1].fileName").value("test2.pdf")); + } + + @Test + @DisplayName("바이너리 컨텐츠 다운로드 성공 테스트") + void download_Success() throws Exception { + // Given + UUID binaryContentId = UUID.randomUUID(); + BinaryContentDto binaryContent = new BinaryContentDto( + binaryContentId, + "test.jpg", + 10240L, + MediaType.IMAGE_JPEG_VALUE + ); + + given(binaryContentService.find(binaryContentId)).willReturn(binaryContent); + + // doReturn 사용하여 타입 문제 우회 + ResponseEntity mockResponse = ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"test.jpg\"") + .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE) + .body(new ByteArrayResource("test data".getBytes())); + + doReturn(mockResponse).when(binaryContentStorage).download(any(BinaryContentDto.class)); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}/download", binaryContentId)) + .andExpect(status().isOk()); + } + + @Test + @DisplayName("바이너리 컨텐츠 다운로드 실패 테스트 - 존재하지 않는 컨텐츠") + void download_Failure_BinaryContentNotFound() throws Exception { + // Given + UUID nonExistentId = UUID.randomUUID(); + + given(binaryContentService.find(nonExistentId)) + .willThrow(BinaryContentNotFoundException.withId(nonExistentId)); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}/download", nonExistentId)) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/controller/ChannelControllerTest.java b/src/test/java/com/sprint/mission/discodeit/controller/ChannelControllerTest.java new file mode 100644 index 000000000..6b8b4aa31 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/ChannelControllerTest.java @@ -0,0 +1,291 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willDoNothing; +import static org.mockito.BDDMockito.willThrow; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.exception.channel.ChannelNotFoundException; +import com.sprint.mission.discodeit.exception.channel.PrivateChannelUpdateException; +import com.sprint.mission.discodeit.service.ChannelService; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.FilterType; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(value = ChannelController.class, + excludeFilters = @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = ".*\\.security\\.jwt\\..*")) +@AutoConfigureMockMvc(addFilters = false) +class ChannelControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private ChannelService channelService; + + @Test + @DisplayName("공개 채널 생성 성공 테스트") + void createPublicChannel_Success() throws Exception { + // Given + PublicChannelCreateRequest createRequest = new PublicChannelCreateRequest( + "test-channel", + "채널 설명입니다." + ); + + UUID channelId = UUID.randomUUID(); + ChannelDto createdChannel = new ChannelDto( + channelId, + ChannelType.PUBLIC, + "test-channel", + "채널 설명입니다.", + new ArrayList<>(), + Instant.now() + ); + + given(channelService.create(any(PublicChannelCreateRequest.class))) + .willReturn(createdChannel); + + // When & Then + mockMvc.perform(post("/api/channels/public") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(createRequest)) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(channelId.toString())) + .andExpect(jsonPath("$.type").value("PUBLIC")) + .andExpect(jsonPath("$.name").value("test-channel")) + .andExpect(jsonPath("$.description").value("채널 설명입니다.")); + } + + @Test + @DisplayName("공개 채널 생성 실패 테스트 - 유효하지 않은 요청") + void createPublicChannel_Failure_InvalidRequest() throws Exception { + // Given + PublicChannelCreateRequest invalidRequest = new PublicChannelCreateRequest( + "a", // 최소 길이 위반 (2자 이상이어야 함) + "채널 설명은 최대 255자까지 가능합니다.".repeat(10) // 최대 길이 위반 + ); + + // When & Then + mockMvc.perform(post("/api/channels/public") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(invalidRequest)) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("비공개 채널 생성 성공 테스트") + void createPrivateChannel_Success() throws Exception { + // Given + List participantIds = List.of(UUID.randomUUID(), UUID.randomUUID()); + PrivateChannelCreateRequest createRequest = new PrivateChannelCreateRequest(participantIds); + + UUID channelId = UUID.randomUUID(); + List participants = new ArrayList<>(); + for (UUID userId : participantIds) { + participants.add(new UserDto(userId, "user-" + userId.toString().substring(0, 5), + "user" + userId.toString().substring(0, 5) + "@example.com", null, false, Role.USER)); + } + + ChannelDto createdChannel = new ChannelDto( + channelId, + ChannelType.PRIVATE, + null, + null, + participants, + Instant.now() + ); + + given(channelService.create(any(PrivateChannelCreateRequest.class))) + .willReturn(createdChannel); + + // When & Then + mockMvc.perform(post("/api/channels/private") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(createRequest)) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(channelId.toString())) + .andExpect(jsonPath("$.type").value("PRIVATE")) + .andExpect(jsonPath("$.participants").isArray()) + .andExpect(jsonPath("$.participants.length()").value(2)); + } + + @Test + @DisplayName("공개 채널 업데이트 성공 테스트") + void updateChannel_Success() throws Exception { + // Given + UUID channelId = UUID.randomUUID(); + PublicChannelUpdateRequest updateRequest = new PublicChannelUpdateRequest( + "updated-channel", + "업데이트된 채널 설명입니다." + ); + + ChannelDto updatedChannel = new ChannelDto( + channelId, + ChannelType.PUBLIC, + "updated-channel", + "업데이트된 채널 설명입니다.", + new ArrayList<>(), + Instant.now() + ); + + given(channelService.update(eq(channelId), any(PublicChannelUpdateRequest.class))) + .willReturn(updatedChannel); + + // When & Then + mockMvc.perform(patch("/api/channels/{channelId}", channelId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(channelId.toString())) + .andExpect(jsonPath("$.name").value("updated-channel")) + .andExpect(jsonPath("$.description").value("업데이트된 채널 설명입니다.")); + } + + @Test + @DisplayName("채널 업데이트 실패 테스트 - 존재하지 않는 채널") + void updateChannel_Failure_ChannelNotFound() throws Exception { + // Given + UUID nonExistentChannelId = UUID.randomUUID(); + PublicChannelUpdateRequest updateRequest = new PublicChannelUpdateRequest( + "updated-channel", + "업데이트된 채널 설명입니다." + ); + + given(channelService.update(eq(nonExistentChannelId), any(PublicChannelUpdateRequest.class))) + .willThrow(ChannelNotFoundException.withId(nonExistentChannelId)); + + // When & Then + mockMvc.perform(patch("/api/channels/{channelId}", nonExistentChannelId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("채널 업데이트 실패 테스트 - 비공개 채널 업데이트 시도") + void updateChannel_Failure_PrivateChannelUpdate() throws Exception { + // Given + UUID privateChannelId = UUID.randomUUID(); + PublicChannelUpdateRequest updateRequest = new PublicChannelUpdateRequest( + "updated-channel", + "업데이트된 채널 설명입니다." + ); + + given(channelService.update(eq(privateChannelId), any(PublicChannelUpdateRequest.class))) + .willThrow(PrivateChannelUpdateException.forChannel(privateChannelId)); + + // When & Then + mockMvc.perform(patch("/api/channels/{channelId}", privateChannelId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("채널 삭제 성공 테스트") + void deleteChannel_Success() throws Exception { + // Given + UUID channelId = UUID.randomUUID(); + willDoNothing().given(channelService).delete(channelId); + + // When & Then + mockMvc.perform(delete("/api/channels/{channelId}", channelId) + .contentType(MediaType.APPLICATION_JSON) + .with(csrf())) + .andExpect(status().isNoContent()); + } + + @Test + @DisplayName("채널 삭제 실패 테스트 - 존재하지 않는 채널") + void deleteChannel_Failure_ChannelNotFound() throws Exception { + // Given + UUID nonExistentChannelId = UUID.randomUUID(); + willThrow(ChannelNotFoundException.withId(nonExistentChannelId)) + .given(channelService).delete(nonExistentChannelId); + + // When & Then + mockMvc.perform(delete("/api/channels/{channelId}", nonExistentChannelId) + .contentType(MediaType.APPLICATION_JSON) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("사용자별 채널 목록 조회 성공 테스트") + void findAllByUserId_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + UUID channelId1 = UUID.randomUUID(); + UUID channelId2 = UUID.randomUUID(); + + List channels = List.of( + new ChannelDto( + channelId1, + ChannelType.PUBLIC, + "public-channel", + "공개 채널 설명", + new ArrayList<>(), + Instant.now() + ), + new ChannelDto( + channelId2, + ChannelType.PRIVATE, + null, + null, + List.of(new UserDto(userId, "user1", "user1@example.com", null, true, Role.USER)), + Instant.now().minusSeconds(3600) + ) + ); + + given(channelService.findAllByUserId(userId)).willReturn(channels); + + // When & Then + mockMvc.perform(get("/api/channels") + .param("userId", userId.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(channelId1.toString())) + .andExpect(jsonPath("$[0].type").value("PUBLIC")) + .andExpect(jsonPath("$[0].name").value("public-channel")) + .andExpect(jsonPath("$[1].id").value(channelId2.toString())) + .andExpect(jsonPath("$[1].type").value("PRIVATE")); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/controller/MessageControllerTest.java b/src/test/java/com/sprint/mission/discodeit/controller/MessageControllerTest.java new file mode 100644 index 000000000..de35f7a41 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/MessageControllerTest.java @@ -0,0 +1,321 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willDoNothing; +import static org.mockito.BDDMockito.willThrow; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.response.PageResponse; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.exception.message.MessageNotFoundException; +import com.sprint.mission.discodeit.service.MessageService; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.FilterType; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(value = MessageController.class, + excludeFilters = @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = ".*\\.security\\.jwt\\..*")) +@AutoConfigureMockMvc(addFilters = false) +class MessageControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private MessageService messageService; + + @Test + @DisplayName("메시지 생성 성공 테스트") + void createMessage_Success() throws Exception { + // Given + UUID channelId = UUID.randomUUID(); + UUID authorId = UUID.randomUUID(); + MessageCreateRequest createRequest = new MessageCreateRequest( + "안녕하세요, 테스트 메시지입니다.", + channelId, + authorId + ); + + MockMultipartFile messageCreateRequestPart = new MockMultipartFile( + "messageCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(createRequest) + ); + + MockMultipartFile attachment = new MockMultipartFile( + "attachments", + "test.jpg", + MediaType.IMAGE_JPEG_VALUE, + "test-image".getBytes() + ); + + UUID messageId = UUID.randomUUID(); + Instant now = Instant.now(); + + UserDto author = new UserDto( + authorId, + "testuser", + "test@example.com", + null, + true, + Role.USER + ); + + BinaryContentDto attachmentDto = new BinaryContentDto( + UUID.randomUUID(), + "test.jpg", + 10L, + MediaType.IMAGE_JPEG_VALUE + ); + + MessageDto createdMessage = new MessageDto( + messageId, + now, + now, + "안녕하세요, 테스트 메시지입니다.", + channelId, + author, + List.of(attachmentDto) + ); + + given(messageService.create(any(MessageCreateRequest.class), any(List.class))) + .willReturn(createdMessage); + + // When & Then + mockMvc.perform(multipart("/api/messages") + .file(messageCreateRequestPart) + .file(attachment) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(messageId.toString())) + .andExpect(jsonPath("$.content").value("안녕하세요, 테스트 메시지입니다.")) + .andExpect(jsonPath("$.channelId").value(channelId.toString())) + .andExpect(jsonPath("$.author.id").value(authorId.toString())) + .andExpect(jsonPath("$.attachments[0].fileName").value("test.jpg")); + } + + @Test + @DisplayName("메시지 생성 실패 테스트 - 유효하지 않은 요청") + void createMessage_Failure_InvalidRequest() throws Exception { + // Given + MessageCreateRequest invalidRequest = new MessageCreateRequest( + "", // 내용이 비어있음 (NotBlank 위반) + null, // 채널 ID가 비어있음 (NotNull 위반) + null // 작성자 ID가 비어있음 (NotNull 위반) + ); + + MockMultipartFile messageCreateRequestPart = new MockMultipartFile( + "messageCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(invalidRequest) + ); + + // When & Then + mockMvc.perform(multipart("/api/messages") + .file(messageCreateRequestPart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("메시지 업데이트 성공 테스트") + void updateMessage_Success() throws Exception { + // Given + UUID messageId = UUID.randomUUID(); + UUID channelId = UUID.randomUUID(); + UUID authorId = UUID.randomUUID(); + + MessageUpdateRequest updateRequest = new MessageUpdateRequest( + "수정된 메시지 내용입니다." + ); + + Instant now = Instant.now(); + + UserDto author = new UserDto( + authorId, + "testuser", + "test@example.com", + null, + true, + Role.USER + ); + + MessageDto updatedMessage = new MessageDto( + messageId, + now.minusSeconds(60), + now, + "수정된 메시지 내용입니다.", + channelId, + author, + new ArrayList<>() + ); + + given(messageService.update(eq(messageId), any(MessageUpdateRequest.class))) + .willReturn(updatedMessage); + + // When & Then + mockMvc.perform(patch("/api/messages/{messageId}", messageId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(messageId.toString())) + .andExpect(jsonPath("$.content").value("수정된 메시지 내용입니다.")) + .andExpect(jsonPath("$.channelId").value(channelId.toString())) + .andExpect(jsonPath("$.author.id").value(authorId.toString())); + } + + @Test + @DisplayName("메시지 업데이트 실패 테스트 - 존재하지 않는 메시지") + void updateMessage_Failure_MessageNotFound() throws Exception { + // Given + UUID nonExistentMessageId = UUID.randomUUID(); + + MessageUpdateRequest updateRequest = new MessageUpdateRequest( + "수정된 메시지 내용입니다." + ); + + given(messageService.update(eq(nonExistentMessageId), any(MessageUpdateRequest.class))) + .willThrow(MessageNotFoundException.withId(nonExistentMessageId)); + + // When & Then + mockMvc.perform(patch("/api/messages/{messageId}", nonExistentMessageId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("메시지 삭제 성공 테스트") + void deleteMessage_Success() throws Exception { + // Given + UUID messageId = UUID.randomUUID(); + willDoNothing().given(messageService).delete(messageId); + + // When & Then + mockMvc.perform(delete("/api/messages/{messageId}", messageId) + .contentType(MediaType.APPLICATION_JSON) + .with(csrf())) + .andExpect(status().isNoContent()); + } + + @Test + @DisplayName("메시지 삭제 실패 테스트 - 존재하지 않는 메시지") + void deleteMessage_Failure_MessageNotFound() throws Exception { + // Given + UUID nonExistentMessageId = UUID.randomUUID(); + willThrow(MessageNotFoundException.withId(nonExistentMessageId)) + .given(messageService).delete(nonExistentMessageId); + + // When & Then + mockMvc.perform(delete("/api/messages/{messageId}", nonExistentMessageId) + .contentType(MediaType.APPLICATION_JSON) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("채널별 메시지 목록 조회 성공 테스트") + void findAllByChannelId_Success() throws Exception { + // Given + UUID channelId = UUID.randomUUID(); + UUID authorId = UUID.randomUUID(); + Instant cursor = Instant.now(); + Pageable pageable = PageRequest.of(0, 50, Sort.Direction.DESC, "createdAt"); + + UserDto author = new UserDto( + authorId, + "testuser", + "test@example.com", + null, + true, + Role.USER + ); + + List messages = List.of( + new MessageDto( + UUID.randomUUID(), + cursor.minusSeconds(10), + cursor.minusSeconds(10), + "첫 번째 메시지", + channelId, + author, + new ArrayList<>() + ), + new MessageDto( + UUID.randomUUID(), + cursor.minusSeconds(20), + cursor.minusSeconds(20), + "두 번째 메시지", + channelId, + author, + new ArrayList<>() + ) + ); + + PageResponse pageResponse = new PageResponse<>( + messages, + cursor.minusSeconds(30), // nextCursor 값 + pageable.getPageSize(), + true, // hasNext + (long) messages.size() // totalElements + ); + + given(messageService.findAllByChannelId(eq(channelId), eq(cursor), any(Pageable.class))) + .willReturn(pageResponse); + + // When & Then + mockMvc.perform(get("/api/messages") + .param("channelId", channelId.toString()) + .param("cursor", cursor.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content").isArray()) + .andExpect(jsonPath("$.content.length()").value(2)) + .andExpect(jsonPath("$.content[0].content").value("첫 번째 메시지")) + .andExpect(jsonPath("$.content[1].content").value("두 번째 메시지")) + .andExpect(jsonPath("$.nextCursor").exists()) + .andExpect(jsonPath("$.size").value(50)) + .andExpect(jsonPath("$.hasNext").value(true)) + .andExpect(jsonPath("$.totalElements").value(2)); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/controller/ReadStatusControllerTest.java b/src/test/java/com/sprint/mission/discodeit/controller/ReadStatusControllerTest.java new file mode 100644 index 000000000..a91a7e9a6 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/ReadStatusControllerTest.java @@ -0,0 +1,183 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.dto.request.ReadStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusUpdateRequest; +import com.sprint.mission.discodeit.exception.readstatus.ReadStatusNotFoundException; +import com.sprint.mission.discodeit.service.ReadStatusService; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.FilterType; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(value = ReadStatusController.class, + excludeFilters = @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = ".*\\.security\\.jwt\\..*")) +@AutoConfigureMockMvc(addFilters = false) +class ReadStatusControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private ReadStatusService readStatusService; + + @Test + @DisplayName("읽음 상태 생성 성공 테스트") + void create_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + UUID channelId = UUID.randomUUID(); + Instant lastReadAt = Instant.now(); + + ReadStatusCreateRequest createRequest = new ReadStatusCreateRequest( + userId, + channelId, + lastReadAt + ); + + UUID readStatusId = UUID.randomUUID(); + ReadStatusDto createdReadStatus = new ReadStatusDto( + readStatusId, + userId, + channelId, + lastReadAt + ); + + given(readStatusService.create(any(ReadStatusCreateRequest.class))) + .willReturn(createdReadStatus); + + // When & Then + mockMvc.perform(post("/api/readStatuses") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(createRequest)) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(readStatusId.toString())) + .andExpect(jsonPath("$.userId").value(userId.toString())) + .andExpect(jsonPath("$.channelId").value(channelId.toString())) + .andExpect(jsonPath("$.lastReadAt").exists()); + } + + @Test + @DisplayName("읽음 상태 생성 실패 테스트 - 유효하지 않은 요청") + void create_Failure_InvalidRequest() throws Exception { + // Given + ReadStatusCreateRequest invalidRequest = new ReadStatusCreateRequest( + null, // userId가 null (NotNull 위반) + null, // channelId가 null (NotNull 위반) + null // lastReadAt이 null (NotNull 위반) + ); + + // When & Then + mockMvc.perform(post("/api/readStatuses") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(invalidRequest)) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("읽음 상태 업데이트 성공 테스트") + void update_Success() throws Exception { + // Given + UUID readStatusId = UUID.randomUUID(); + UUID userId = UUID.randomUUID(); + UUID channelId = UUID.randomUUID(); + Instant newLastReadAt = Instant.now(); + + ReadStatusUpdateRequest updateRequest = new ReadStatusUpdateRequest(newLastReadAt); + + ReadStatusDto updatedReadStatus = new ReadStatusDto( + readStatusId, + userId, + channelId, + newLastReadAt + ); + + given(readStatusService.update(eq(readStatusId), any(ReadStatusUpdateRequest.class))) + .willReturn(updatedReadStatus); + + // When & Then + mockMvc.perform(patch("/api/readStatuses/{readStatusId}", readStatusId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(readStatusId.toString())) + .andExpect(jsonPath("$.userId").value(userId.toString())) + .andExpect(jsonPath("$.channelId").value(channelId.toString())) + .andExpect(jsonPath("$.lastReadAt").exists()); + } + + @Test + @DisplayName("읽음 상태 업데이트 실패 테스트 - 존재하지 않는 읽음 상태") + void update_Failure_ReadStatusNotFound() throws Exception { + // Given + UUID nonExistentId = UUID.randomUUID(); + Instant newLastReadAt = Instant.now(); + + ReadStatusUpdateRequest updateRequest = new ReadStatusUpdateRequest(newLastReadAt); + + given(readStatusService.update(eq(nonExistentId), any(ReadStatusUpdateRequest.class))) + .willThrow(ReadStatusNotFoundException.withId(nonExistentId)); + + // When & Then + mockMvc.perform(patch("/api/readStatuses/{readStatusId}", nonExistentId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest)) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("사용자별 읽음 상태 목록 조회 성공 테스트") + void findAllByUserId_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + UUID channelId1 = UUID.randomUUID(); + UUID channelId2 = UUID.randomUUID(); + Instant now = Instant.now(); + + List readStatuses = List.of( + new ReadStatusDto(UUID.randomUUID(), userId, channelId1, now.minusSeconds(60)), + new ReadStatusDto(UUID.randomUUID(), userId, channelId2, now) + ); + + given(readStatusService.findAllByUserId(userId)).willReturn(readStatuses); + + // When & Then + mockMvc.perform(get("/api/readStatuses") + .param("userId", userId.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].userId").value(userId.toString())) + .andExpect(jsonPath("$[0].channelId").value(channelId1.toString())) + .andExpect(jsonPath("$[1].userId").value(userId.toString())) + .andExpect(jsonPath("$[1].channelId").value(channelId2.toString())); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/controller/UserControllerTest.java b/src/test/java/com/sprint/mission/discodeit/controller/UserControllerTest.java new file mode 100644 index 000000000..cf273a16f --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/UserControllerTest.java @@ -0,0 +1,311 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willDoNothing; +import static org.mockito.BDDMockito.willThrow; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.service.UserService; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.FilterType; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(value = UserController.class, + excludeFilters = @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = ".*\\.security\\.jwt\\..*")) +@AutoConfigureMockMvc(addFilters = false) +class UserControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private UserService userService; + + + @Test + @DisplayName("사용자 생성 성공 테스트") + void createUser_Success() throws Exception { + // Given + UserCreateRequest createRequest = new UserCreateRequest( + "testuser", + "test@example.com", + "Password1!" + ); + + MockMultipartFile userCreateRequestPart = new MockMultipartFile( + "userCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(createRequest) + ); + + MockMultipartFile profilePart = new MockMultipartFile( + "profile", + "profile.jpg", + MediaType.IMAGE_JPEG_VALUE, + "test-image".getBytes() + ); + + UUID userId = UUID.randomUUID(); + BinaryContentDto profileDto = new BinaryContentDto( + UUID.randomUUID(), + "profile.jpg", + 12L, + MediaType.IMAGE_JPEG_VALUE + ); + + UserDto createdUser = new UserDto( + userId, + "testuser", + "test@example.com", + profileDto, + false, + Role.USER + ); + + given(userService.create(any(UserCreateRequest.class), any(Optional.class))) + .willReturn(createdUser); + + // When & Then + mockMvc.perform(multipart("/api/users") + .file(userCreateRequestPart) + .file(profilePart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(userId.toString())) + .andExpect(jsonPath("$.username").value("testuser")) + .andExpect(jsonPath("$.email").value("test@example.com")) + .andExpect(jsonPath("$.profile.fileName").value("profile.jpg")) + .andExpect(jsonPath("$.online").value(false)); + } + + @Test + @DisplayName("사용자 생성 실패 테스트 - 유효하지 않은 요청") + void createUser_Failure_InvalidRequest() throws Exception { + // Given + UserCreateRequest invalidRequest = new UserCreateRequest( + "t", // 최소 길이 위반 + "invalid-email", // 이메일 형식 위반 + "short" // 비밀번호 정책 위반 + ); + + MockMultipartFile userCreateRequestPart = new MockMultipartFile( + "userCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(invalidRequest) + ); + + // When & Then + mockMvc.perform(multipart("/api/users") + .file(userCreateRequestPart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("사용자 조회 성공 테스트") + void findAllUsers_Success() throws Exception { + // Given + UUID userId1 = UUID.randomUUID(); + UUID userId2 = UUID.randomUUID(); + + UserDto user1 = new UserDto( + userId1, + "user1", + "user1@example.com", + null, + true, + Role.USER + ); + + UserDto user2 = new UserDto( + userId2, + "user2", + "user2@example.com", + null, + false, + Role.USER + ); + + List users = List.of(user1, user2); + + given(userService.findAll()).willReturn(users); + + // When & Then + mockMvc.perform(get("/api/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(userId1.toString())) + .andExpect(jsonPath("$[0].username").value("user1")) + .andExpect(jsonPath("$[0].online").value(true)) + .andExpect(jsonPath("$[1].id").value(userId2.toString())) + .andExpect(jsonPath("$[1].username").value("user2")) + .andExpect(jsonPath("$[1].online").value(false)); + } + + @Test + @DisplayName("사용자 업데이트 성공 테스트") + void updateUser_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + UserUpdateRequest updateRequest = new UserUpdateRequest( + "updateduser", + "updated@example.com", + "UpdatedPassword1!" + ); + + MockMultipartFile userUpdateRequestPart = new MockMultipartFile( + "userUpdateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(updateRequest) + ); + + MockMultipartFile profilePart = new MockMultipartFile( + "profile", + "updated-profile.jpg", + MediaType.IMAGE_JPEG_VALUE, + "updated-image".getBytes() + ); + + BinaryContentDto profileDto = new BinaryContentDto( + UUID.randomUUID(), + "updated-profile.jpg", + 14L, + MediaType.IMAGE_JPEG_VALUE + ); + + UserDto updatedUser = new UserDto( + userId, + "updateduser", + "updated@example.com", + profileDto, + true, + Role.USER + ); + + given(userService.update(eq(userId), any(UserUpdateRequest.class), any(Optional.class))) + .willReturn(updatedUser); + + // When & Then + mockMvc.perform(multipart("/api/users/{userId}", userId) + .file(userUpdateRequestPart) + .file(profilePart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(request -> { + request.setMethod("PATCH"); + return request; + }) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(userId.toString())) + .andExpect(jsonPath("$.username").value("updateduser")) + .andExpect(jsonPath("$.email").value("updated@example.com")) + .andExpect(jsonPath("$.profile.fileName").value("updated-profile.jpg")) + .andExpect(jsonPath("$.online").value(true)); + } + + @Test + @DisplayName("사용자 업데이트 실패 테스트 - 존재하지 않는 사용자") + void updateUser_Failure_UserNotFound() throws Exception { + // Given + UUID nonExistentUserId = UUID.randomUUID(); + UserUpdateRequest updateRequest = new UserUpdateRequest( + "updateduser", + "updated@example.com", + "UpdatedPassword1!" + ); + + MockMultipartFile userUpdateRequestPart = new MockMultipartFile( + "userUpdateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(updateRequest) + ); + + MockMultipartFile profilePart = new MockMultipartFile( + "profile", + "updated-profile.jpg", + MediaType.IMAGE_JPEG_VALUE, + "updated-image".getBytes() + ); + + given(userService.update(eq(nonExistentUserId), any(UserUpdateRequest.class), + any(Optional.class))) + .willThrow(UserNotFoundException.withId(nonExistentUserId)); + + // When & Then + mockMvc.perform(multipart("/api/users/{userId}", nonExistentUserId) + .file(userUpdateRequestPart) + .file(profilePart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(request -> { + request.setMethod("PATCH"); + return request; + }) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("사용자 삭제 성공 테스트") + void deleteUser_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + willDoNothing().given(userService).delete(userId); + + // When & Then + mockMvc.perform(delete("/api/users/{userId}", userId) + .contentType(MediaType.APPLICATION_JSON) + .with(csrf())) + .andExpect(status().isNoContent()); + } + + @Test + @DisplayName("사용자 삭제 실패 테스트 - 존재하지 않는 사용자") + void deleteUser_Failure_UserNotFound() throws Exception { + // Given + UUID nonExistentUserId = UUID.randomUUID(); + willThrow(UserNotFoundException.withId(nonExistentUserId)) + .given(userService).delete(nonExistentUserId); + + // When & Then + mockMvc.perform(delete("/api/users/{userId}", nonExistentUserId) + .contentType(MediaType.APPLICATION_JSON) + .with(csrf())) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/integration/AuthApiIntegrationTest.java b/src/test/java/com/sprint/mission/discodeit/integration/AuthApiIntegrationTest.java new file mode 100644 index 000000000..16b05fa23 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/AuthApiIntegrationTest.java @@ -0,0 +1,124 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.sprint.mission.discodeit.dto.request.LoginRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.service.UserService; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class AuthApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserService userService; + + @Test + @DisplayName("로그인 API 통합 테스트 - 성공") + void login_Success() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "loginuser", + "login@example.com", + "Password1!" + ); + + userService.create(userRequest, Optional.empty()); + + // 로그인 요청 + LoginRequest loginRequest = new LoginRequest( + "loginuser", + "Password1!" + ); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .with(csrf()) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .formFields(MultiValueMap.fromMultiValue(Map.of( + "username", List.of(loginRequest.username()), + "password", List.of(loginRequest.password()) + )))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.userDto.id", notNullValue())) + .andExpect(jsonPath("$.userDto.username", is("loginuser"))) + .andExpect(jsonPath("$.userDto.email", is("login@example.com"))) + .andExpect(jsonPath("$.accessToken", notNullValue())); + } + + @Test + @DisplayName("로그인 API 통합 테스트 - 실패 (존재하지 않는 사용자)") + void login_Failure_UserNotFound() throws Exception { + // Given + LoginRequest loginRequest = new LoginRequest( + "nonexistentuser", + "Password1!" + ); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .with(csrf()) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .formFields(MultiValueMap.fromMultiValue(Map.of( + "username", List.of(loginRequest.username()), + "password", List.of(loginRequest.password()) + )))) + .andExpect(status().isUnauthorized()); + } + + @Test + @DisplayName("로그인 API 통합 테스트 - 실패 (잘못된 비밀번호)") + void login_Failure_InvalidCredentials() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "loginuser2", + "login2@example.com", + "Password1!" + ); + + userService.create(userRequest, Optional.empty()); + + // 잘못된 비밀번호로 로그인 시도 + LoginRequest loginRequest = new LoginRequest( + "loginuser2", + "WrongPassword1!" + ); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .with(csrf()) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .formFields(MultiValueMap.fromMultiValue(Map.of( + "username", List.of(loginRequest.username()), + "password", List.of(loginRequest.password()) + )))) + .andExpect(status().isUnauthorized()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/integration/BinaryContentApiIntegrationTest.java b/src/test/java/com/sprint/mission/discodeit/integration/BinaryContentApiIntegrationTest.java new file mode 100644 index 000000000..47ad4e7bc --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/BinaryContentApiIntegrationTest.java @@ -0,0 +1,217 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.service.BinaryContentService; +import com.sprint.mission.discodeit.service.ChannelService; +import com.sprint.mission.discodeit.service.MessageService; +import com.sprint.mission.discodeit.service.UserService; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class BinaryContentApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private BinaryContentService binaryContentService; + + @Autowired + private UserService userService; + + @Autowired + private ChannelService channelService; + + @Autowired + private MessageService messageService; + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("바이너리 컨텐츠 조회 API 통합 테스트") + void findBinaryContent_Success() throws Exception { + // Given + // 테스트 바이너리 컨텐츠 생성 (메시지 첨부파일을 통해 생성) + // 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "contentuser", + "content@example.com", + "Password1!" + ); + UserDto user = userService.create(userRequest, Optional.empty()); + + // 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "테스트 채널", + "테스트 채널 설명입니다." + ); + var channel = channelService.create(channelRequest); + + // 첨부파일이 있는 메시지 생성 + MessageCreateRequest messageRequest = new MessageCreateRequest( + "첨부파일이 있는 메시지입니다.", + channel.id(), + user.id() + ); + + byte[] fileContent = "테스트 파일 내용입니다.".getBytes(); + BinaryContentCreateRequest attachmentRequest = new BinaryContentCreateRequest( + "test.txt", + MediaType.TEXT_PLAIN_VALUE, + fileContent + ); + + MessageDto message = messageService.create(messageRequest, List.of(attachmentRequest)); + UUID binaryContentId = message.attachments().get(0).id(); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}", binaryContentId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(binaryContentId.toString()))) + .andExpect(jsonPath("$.fileName", is("test.txt"))) + .andExpect(jsonPath("$.contentType", is(MediaType.TEXT_PLAIN_VALUE))) + .andExpect(jsonPath("$.size", is(fileContent.length))); + } + + @Test + @WithMockUser(roles = "USER") + @DisplayName("존재하지 않는 바이너리 컨텐츠 조회 API 통합 테스트") + void findBinaryContent_Failure_NotFound() throws Exception { + // Given + UUID nonExistentBinaryContentId = UUID.randomUUID(); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}", nonExistentBinaryContentId)) + .andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("여러 바이너리 컨텐츠 조회 API 통합 테스트") + void findAllBinaryContentsByIds_Success() throws Exception { + // Given + // 테스트 바이너리 컨텐츠 생성 (메시지 첨부파일을 통해 생성) + UserCreateRequest userRequest = new UserCreateRequest( + "contentuser2", + "content2@example.com", + "Password1!" + ); + UserDto user = userService.create(userRequest, Optional.empty()); + + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "테스트 채널2", + "테스트 채널 설명입니다." + ); + var channel = channelService.create(channelRequest); + + MessageCreateRequest messageRequest = new MessageCreateRequest( + "첨부파일이 있는 메시지입니다.", + channel.id(), + user.id() + ); + + // 첫 번째 첨부파일 + BinaryContentCreateRequest attachmentRequest1 = new BinaryContentCreateRequest( + "test1.txt", + MediaType.TEXT_PLAIN_VALUE, + "첫 번째 테스트 파일 내용입니다.".getBytes() + ); + + // 두 번째 첨부파일 + BinaryContentCreateRequest attachmentRequest2 = new BinaryContentCreateRequest( + "test2.txt", + MediaType.TEXT_PLAIN_VALUE, + "두 번째 테스트 파일 내용입니다.".getBytes() + ); + + // 첨부파일 두 개를 가진 메시지 생성 + MessageDto message = messageService.create( + messageRequest, + List.of(attachmentRequest1, attachmentRequest2) + ); + + List binaryContentIds = message.attachments().stream() + .map(BinaryContentDto::id) + .toList(); + + // When & Then + mockMvc.perform(get("/api/binaryContents") + .param("binaryContentIds", binaryContentIds.get(0).toString()) + .param("binaryContentIds", binaryContentIds.get(1).toString())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[*].fileName", hasItems("test1.txt", "test2.txt"))); + } + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("바이너리 컨텐츠 다운로드 API 통합 테스트") + void downloadBinaryContent_Success() throws Exception { + // Given + String fileContent = "다운로드 테스트 파일 내용입니다."; + BinaryContentCreateRequest createRequest = new BinaryContentCreateRequest( + "download-test.txt", + MediaType.TEXT_PLAIN_VALUE, + fileContent.getBytes() + ); + + BinaryContentDto binaryContent = binaryContentService.create(createRequest); + UUID binaryContentId = binaryContent.id(); + + // When & Then + mockMvc.perform(get("/api/binaryContents/{binaryContentId}/download", binaryContentId)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Disposition", + "attachment; filename=\"download-test.txt\"")) + .andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE)) + .andExpect(content().bytes(fileContent.getBytes())); + } + + @Test + @WithMockUser(roles = "USER") + @DisplayName("존재하지 않는 바이너리 컨텐츠 다운로드 API 통합 테스트") + void downloadBinaryContent_Failure_NotFound() throws Exception { + // Given + UUID nonExistentBinaryContentId = UUID.randomUUID(); + + // When & Then + mockMvc.perform( + get("/api/binaryContents/{binaryContentId}/download", nonExistentBinaryContentId)) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/integration/ChannelApiIntegrationTest.java b/src/test/java/com/sprint/mission/discodeit/integration/ChannelApiIntegrationTest.java new file mode 100644 index 000000000..f6629a375 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/ChannelApiIntegrationTest.java @@ -0,0 +1,288 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.service.ChannelService; +import com.sprint.mission.discodeit.service.UserService; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class ChannelApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private ChannelService channelService; + + @Autowired + private UserService userService; + + @Test + @DisplayName("공개 채널 생성 API 통합 테스트") + @WithMockUser(roles = "CHANNEL_MANAGER") + void createPublicChannel_Success() throws Exception { + // Given + PublicChannelCreateRequest createRequest = new PublicChannelCreateRequest( + "테스트 채널", + "테스트 채널 설명입니다." + ); + + String requestBody = objectMapper.writeValueAsString(createRequest); + + // When & Then + mockMvc.perform(post("/api/channels/public") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.type", is(ChannelType.PUBLIC.name()))) + .andExpect(jsonPath("$.name", is("테스트 채널"))) + .andExpect(jsonPath("$.description", is("테스트 채널 설명입니다."))); + } + + @Test + @DisplayName("공개 채널 생성 실패 API 통합 테스트 - 유효하지 않은 요청") + @WithMockUser(roles = "CHANNEL_MANAGER") + void createPublicChannel_Failure_InvalidRequest() throws Exception { + // Given + PublicChannelCreateRequest invalidRequest = new PublicChannelCreateRequest( + "a", // 최소 길이 위반 + "테스트 채널 설명입니다." + ); + + String requestBody = objectMapper.writeValueAsString(invalidRequest); + + // When & Then + mockMvc.perform(post("/api/channels/public") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("비공개 채널 생성 API 통합 테스트") + @WithMockUser(roles = "USER") + void createPrivateChannel_Success() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest1 = new UserCreateRequest( + "user1", + "user1@example.com", + "Password1!" + ); + + UserCreateRequest userRequest2 = new UserCreateRequest( + "user2", + "user2@example.com", + "Password1!" + ); + + UserDto user1 = userService.create(userRequest1, Optional.empty()); + UserDto user2 = userService.create(userRequest2, Optional.empty()); + + List participantIds = List.of(user1.id(), user2.id()); + PrivateChannelCreateRequest createRequest = new PrivateChannelCreateRequest(participantIds); + + String requestBody = objectMapper.writeValueAsString(createRequest); + + // When & Then + mockMvc.perform(post("/api/channels/private") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.type", is(ChannelType.PRIVATE.name()))) + .andExpect(jsonPath("$.participants", hasSize(2))); + } + + @Test + @DisplayName("사용자별 채널 목록 조회 API 통합 테스트") + @WithMockUser(roles = "CHANNEL_MANAGER") + void findAllChannelsByUserId_Success() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "channeluser", + "channeluser@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + UUID userId = user.id(); + + // 공개 채널 생성 + PublicChannelCreateRequest publicChannelRequest = new PublicChannelCreateRequest( + "공개 채널 1", + "공개 채널 설명입니다." + ); + + channelService.create(publicChannelRequest); + + // 비공개 채널 생성 + UserCreateRequest otherUserRequest = new UserCreateRequest( + "otheruser", + "otheruser@example.com", + "Password1!" + ); + + UserDto otherUser = userService.create(otherUserRequest, Optional.empty()); + + PrivateChannelCreateRequest privateChannelRequest = new PrivateChannelCreateRequest( + List.of(userId, otherUser.id()) + ); + + channelService.create(privateChannelRequest); + + // When & Then + mockMvc.perform(get("/api/channels") + .param("userId", userId.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].type", is(ChannelType.PUBLIC.name()))) + .andExpect(jsonPath("$[1].type", is(ChannelType.PRIVATE.name()))); + } + + @Test + @DisplayName("채널 업데이트 API 통합 테스트") + @WithMockUser(roles = "CHANNEL_MANAGER") + void updateChannel_Success() throws Exception { + // Given + // 공개 채널 생성 + PublicChannelCreateRequest createRequest = new PublicChannelCreateRequest( + "원본 채널", + "원본 채널 설명입니다." + ); + + ChannelDto createdChannel = channelService.create(createRequest); + UUID channelId = createdChannel.id(); + + PublicChannelUpdateRequest updateRequest = new PublicChannelUpdateRequest( + "수정된 채널", + "수정된 채널 설명입니다." + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/channels/{channelId}", channelId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(channelId.toString()))) + .andExpect(jsonPath("$.name", is("수정된 채널"))) + .andExpect(jsonPath("$.description", is("수정된 채널 설명입니다."))); + } + + @Test + @DisplayName("채널 업데이트 실패 API 통합 테스트 - 존재하지 않는 채널") + @WithMockUser(roles = "CHANNEL_MANAGER") + void updateChannel_Failure_ChannelNotFound() throws Exception { + // Given + UUID nonExistentChannelId = UUID.randomUUID(); + + PublicChannelUpdateRequest updateRequest = new PublicChannelUpdateRequest( + "수정된 채널", + "수정된 채널 설명입니다." + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/channels/{channelId}", nonExistentChannelId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("채널 삭제 API 통합 테스트") + @WithMockUser(roles = "CHANNEL_MANAGER") + void deleteChannel_Success() throws Exception { + // Given + // 공개 채널 생성 + PublicChannelCreateRequest createRequest = new PublicChannelCreateRequest( + "삭제할 채널", + "삭제할 채널 설명입니다." + ); + + ChannelDto createdChannel = channelService.create(createRequest); + UUID channelId = createdChannel.id(); + + // When & Then + mockMvc.perform(delete("/api/channels/{channelId}", channelId) + .with(csrf())) + .andExpect(status().isNoContent()); + + // 삭제 확인 - 사용자로 채널 조회 시 삭제된 채널은 조회되지 않아야 함 + UserCreateRequest userRequest = new UserCreateRequest( + "testuser", + "testuser@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + + mockMvc.perform(get("/api/channels") + .param("userId", user.id().toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[?(@.id == '" + channelId + "')]").doesNotExist()); + } + + @Test + @DisplayName("채널 삭제 실패 API 통합 테스트 - 존재하지 않는 채널") + @WithMockUser(roles = "CHANNEL_MANAGER") + void deleteChannel_Failure_ChannelNotFound() throws Exception { + // Given + UUID nonExistentChannelId = UUID.randomUUID(); + + // When & Then + mockMvc.perform(delete("/api/channels/{channelId}", nonExistentChannelId) + .with(csrf())) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/integration/MessageApiIntegrationTest.java b/src/test/java/com/sprint/mission/discodeit/integration/MessageApiIntegrationTest.java new file mode 100644 index 000000000..f012e42a9 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/MessageApiIntegrationTest.java @@ -0,0 +1,350 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.service.ChannelService; +import com.sprint.mission.discodeit.service.MessageService; +import com.sprint.mission.discodeit.service.UserService; +import java.util.ArrayList; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class MessageApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private MessageService messageService; + + @Autowired + private ChannelService channelService; + + @Autowired + private UserService userService; + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("메시지 생성 API 통합 테스트") + void createMessage_Success() throws Exception { + // Given + // 테스트 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "테스트 채널", + "테스트 채널 설명입니다." + ); + + ChannelDto channel = channelService.create(channelRequest); + + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "messageuser", + "messageuser@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + + // 메시지 생성 요청 + MessageCreateRequest createRequest = new MessageCreateRequest( + "테스트 메시지 내용입니다.", + channel.id(), + user.id() + ); + + MockMultipartFile messageCreateRequestPart = new MockMultipartFile( + "messageCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(createRequest) + ); + + MockMultipartFile attachmentPart = new MockMultipartFile( + "attachments", + "test.txt", + MediaType.TEXT_PLAIN_VALUE, + "테스트 첨부 파일 내용".getBytes() + ); + + // When & Then + mockMvc.perform(multipart("/api/messages") + .file(messageCreateRequestPart) + .file(attachmentPart) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.content", is("테스트 메시지 내용입니다."))) + .andExpect(jsonPath("$.channelId", is(channel.id().toString()))) + .andExpect(jsonPath("$.author.id", is(user.id().toString()))) + .andExpect(jsonPath("$.attachments", hasSize(1))) + .andExpect(jsonPath("$.attachments[0].fileName", is("test.txt"))); + } + + @Test + @WithMockUser(roles = "USER") + @DisplayName("메시지 생성 실패 API 통합 테스트 - 유효하지 않은 요청") + void createMessage_Failure_InvalidRequest() throws Exception { + // Given + MessageCreateRequest invalidRequest = new MessageCreateRequest( + "", // 내용이 비어있음 + UUID.randomUUID(), + UUID.randomUUID() + ); + + MockMultipartFile messageCreateRequestPart = new MockMultipartFile( + "messageCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(invalidRequest) + ); + + // When & Then + mockMvc.perform(multipart("/api/messages") + .file(messageCreateRequestPart) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("채널별 메시지 목록 조회 API 통합 테스트") + void findAllMessagesByChannelId_Success() throws Exception { + // Given + // 테스트 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "테스트 채널", + "테스트 채널 설명입니다." + ); + + ChannelDto channel = channelService.create(channelRequest); + + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "messageuser", + "messageuser@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + + // 메시지 생성 + MessageCreateRequest messageRequest1 = new MessageCreateRequest( + "첫 번째 메시지 내용입니다.", + channel.id(), + user.id() + ); + + MessageCreateRequest messageRequest2 = new MessageCreateRequest( + "두 번째 메시지 내용입니다.", + channel.id(), + user.id() + ); + + messageService.create(messageRequest1, new ArrayList<>()); + messageService.create(messageRequest2, new ArrayList<>()); + + // When & Then + mockMvc.perform(get("/api/messages") + .param("channelId", channel.id().toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content", hasSize(2))) + .andExpect(jsonPath("$.content[0].content", is("두 번째 메시지 내용입니다."))) + .andExpect(jsonPath("$.content[1].content", is("첫 번째 메시지 내용입니다."))) + .andExpect(jsonPath("$.size").exists()) + .andExpect(jsonPath("$.hasNext").exists()) + .andExpect(jsonPath("$.totalElements").isEmpty()); + } + + @Test + @WithMockUser(roles = "ADMIN") + @DisplayName("메시지 업데이트 API 통합 테스트") + void updateMessage_Success() throws Exception { + // Given + // 테스트 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "테스트 채널", + "테스트 채널 설명입니다." + ); + + ChannelDto channel = channelService.create(channelRequest); + + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "messageuser", + "messageuser@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(user, "Password1!"); + + // 메시지 생성 + MessageCreateRequest createRequest = new MessageCreateRequest( + "원본 메시지 내용입니다.", + channel.id(), + user.id() + ); + + MessageDto createdMessage = messageService.create(createRequest, new ArrayList<>()); + UUID messageId = createdMessage.id(); + + // 메시지 업데이트 요청 + MessageUpdateRequest updateRequest = new MessageUpdateRequest( + "수정된 메시지 내용입니다." + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/messages/{messageId}", messageId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(messageId.toString()))) + .andExpect(jsonPath("$.content", is("수정된 메시지 내용입니다."))) + .andExpect(jsonPath("$.updatedAt").exists()); + } + + @Test + @DisplayName("메시지 업데이트 실패 API 통합 테스트 - 존재하지 않는 메시지") + void updateMessage_Failure_MessageNotFound() throws Exception { + // Given + UUID nonExistentMessageId = UUID.randomUUID(); + + // 테스트 사용자 생성 (권한 검증을 위해) + UserCreateRequest userRequest = new UserCreateRequest( + "testuser", + "test@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(user, "Password1!"); + + MessageUpdateRequest updateRequest = new MessageUpdateRequest( + "수정된 메시지 내용입니다." + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/messages/{messageId}", nonExistentMessageId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "ADMIN") + @DisplayName("메시지 삭제 API 통합 테스트") + void deleteMessage_Success() throws Exception { + // Given + // 테스트 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "테스트 채널", + "테스트 채널 설명입니다." + ); + + ChannelDto channel = channelService.create(channelRequest); + + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "messageuser", + "messageuser@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(user, "Password1!"); + + // 메시지 생성 + MessageCreateRequest createRequest = new MessageCreateRequest( + "삭제할 메시지 내용입니다.", + channel.id(), + user.id() + ); + + MessageDto createdMessage = messageService.create(createRequest, new ArrayList<>()); + UUID messageId = createdMessage.id(); + + // When & Then + mockMvc.perform(delete("/api/messages/{messageId}", messageId) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isNoContent()); + + // 삭제 확인 - 채널의 메시지 목록 조회 시 삭제된 메시지는 조회되지 않아야 함 + mockMvc.perform(get("/api/messages") + .param("channelId", channel.id().toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content", hasSize(0))); + } + + @Test + @DisplayName("메시지 삭제 실패 API 통합 테스트 - 존재하지 않는 메시지") + void deleteMessage_Failure_MessageNotFound() throws Exception { + // Given + UUID nonExistentMessageId = UUID.randomUUID(); + + // 테스트 사용자 생성 (권한 검증을 위해) + UserCreateRequest userRequest = new UserCreateRequest( + "testuser", + "test@example.com", + "Password1!" + ); + + UserDto user = userService.create(userRequest, Optional.empty()); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(user, "Password1!"); + + // When & Then + mockMvc.perform(delete("/api/messages/{messageId}", nonExistentMessageId) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/integration/ReadStatusApiIntegrationTest.java b/src/test/java/com/sprint/mission/discodeit/integration/ReadStatusApiIntegrationTest.java new file mode 100644 index 000000000..c289ae985 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/ReadStatusApiIntegrationTest.java @@ -0,0 +1,280 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.data.ReadStatusDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.ReadStatusUpdateRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.service.ChannelService; +import com.sprint.mission.discodeit.service.ReadStatusService; +import com.sprint.mission.discodeit.service.UserService; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.security.test.context.support.WithMockUser; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class ReadStatusApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private ReadStatusService readStatusService; + + @Autowired + private UserService userService; + + @Autowired + private ChannelService channelService; + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("읽음 상태 생성 API 통합 테스트") + void createReadStatus_Success() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "readstatususer", + "readstatus@example.com", + "Password1!" + ); + UserDto user = userService.create(userRequest, Optional.empty()); + + // 공개 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "읽음 상태 테스트 채널", + "읽음 상태 테스트 채널 설명입니다." + ); + ChannelDto channel = channelService.create(channelRequest); + + // 읽음 상태 생성 요청 + Instant lastReadAt = Instant.now(); + ReadStatusCreateRequest createRequest = new ReadStatusCreateRequest( + user.id(), + channel.id(), + lastReadAt + ); + + String requestBody = objectMapper.writeValueAsString(createRequest); + + // When & Then + mockMvc.perform(post("/api/readStatuses") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.userId", is(user.id().toString()))) + .andExpect(jsonPath("$.channelId", is(channel.id().toString()))) + .andExpect(jsonPath("$.lastReadAt", is(lastReadAt.toString()))); + } + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("읽음 상태 생성 실패 API 통합 테스트 - 중복 생성") + void createReadStatus_Failure_Duplicate() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "duplicateuser", + "duplicate@example.com", + "Password1!" + ); + UserDto user = userService.create(userRequest, Optional.empty()); + + // 공개 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "중복 테스트 채널", + "중복 테스트 채널 설명입니다." + ); + ChannelDto channel = channelService.create(channelRequest); + + // 첫 번째 읽음 상태 생성 요청 (성공) + Instant lastReadAt = Instant.now(); + ReadStatusCreateRequest firstCreateRequest = new ReadStatusCreateRequest( + user.id(), + channel.id(), + lastReadAt + ); + + String firstRequestBody = objectMapper.writeValueAsString(firstCreateRequest); + mockMvc.perform(post("/api/readStatuses") + .contentType(MediaType.APPLICATION_JSON) + .content(firstRequestBody) + .with(csrf())) + .andExpect(status().isCreated()); + + // 두 번째 읽음 상태 생성 요청 (동일 사용자, 동일 채널) - 실패해야 함 + ReadStatusCreateRequest duplicateCreateRequest = new ReadStatusCreateRequest( + user.id(), + channel.id(), + Instant.now() + ); + + String duplicateRequestBody = objectMapper.writeValueAsString(duplicateCreateRequest); + + // When & Then + mockMvc.perform(post("/api/readStatuses") + .contentType(MediaType.APPLICATION_JSON) + .content(duplicateRequestBody) + .with(csrf())) + .andExpect(status().isConflict()); + } + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("읽음 상태 업데이트 API 통합 테스트") + void updateReadStatus_Success() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "updateuser", + "update@example.com", + "Password1!" + ); + UserDto user = userService.create(userRequest, Optional.empty()); + + // 공개 채널 생성 + PublicChannelCreateRequest channelRequest = new PublicChannelCreateRequest( + "업데이트 테스트 채널", + "업데이트 테스트 채널 설명입니다." + ); + ChannelDto channel = channelService.create(channelRequest); + + // 읽음 상태 생성 + Instant initialLastReadAt = Instant.now().minusSeconds(3600); // 1시간 전 + ReadStatusCreateRequest createRequest = new ReadStatusCreateRequest( + user.id(), + channel.id(), + initialLastReadAt + ); + + ReadStatusDto createdReadStatus = readStatusService.create(createRequest); + UUID readStatusId = createdReadStatus.id(); + + // 읽음 상태 업데이트 요청 + Instant newLastReadAt = Instant.now(); + ReadStatusUpdateRequest updateRequest = new ReadStatusUpdateRequest( + newLastReadAt + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/readStatuses/{readStatusId}", readStatusId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(readStatusId.toString()))) + .andExpect(jsonPath("$.userId", is(user.id().toString()))) + .andExpect(jsonPath("$.channelId", is(channel.id().toString()))) + .andExpect(jsonPath("$.lastReadAt", is(newLastReadAt.toString()))); + } + + @Test + @WithMockUser(roles = "USER") + @DisplayName("읽음 상태 업데이트 실패 API 통합 테스트 - 존재하지 않는 읽음 상태") + void updateReadStatus_Failure_NotFound() throws Exception { + // Given + UUID nonExistentReadStatusId = UUID.randomUUID(); + + ReadStatusUpdateRequest updateRequest = new ReadStatusUpdateRequest( + Instant.now() + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/readStatuses/{readStatusId}", nonExistentReadStatusId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody) + .with(csrf())) + .andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "CHANNEL_MANAGER") + @DisplayName("사용자별 읽음 상태 목록 조회 API 통합 테스트") + void findAllReadStatusesByUserId_Success() throws Exception { + // Given + // 테스트 사용자 생성 + UserCreateRequest userRequest = new UserCreateRequest( + "listuser", + "list@example.com", + "Password1!" + ); + UserDto user = userService.create(userRequest, Optional.empty()); + + // 여러 채널 생성 + PublicChannelCreateRequest channelRequest1 = new PublicChannelCreateRequest( + "목록 테스트 채널 1", + "목록 테스트 채널 설명입니다." + ); + + PublicChannelCreateRequest channelRequest2 = new PublicChannelCreateRequest( + "목록 테스트 채널 2", + "목록 테스트 채널 설명입니다." + ); + + ChannelDto channel1 = channelService.create(channelRequest1); + ChannelDto channel2 = channelService.create(channelRequest2); + + // 각 채널에 대한 읽음 상태 생성 + ReadStatusCreateRequest createRequest1 = new ReadStatusCreateRequest( + user.id(), + channel1.id(), + Instant.now().minusSeconds(3600) + ); + + ReadStatusCreateRequest createRequest2 = new ReadStatusCreateRequest( + user.id(), + channel2.id(), + Instant.now() + ); + + readStatusService.create(createRequest1); + readStatusService.create(createRequest2); + + // When & Then + mockMvc.perform(get("/api/readStatuses") + .param("userId", user.id().toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[*].channelId", + hasItems(channel1.id().toString(), channel2.id().toString()))); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/integration/UserApiIntegrationTest.java b/src/test/java/com/sprint/mission/discodeit/integration/UserApiIntegrationTest.java new file mode 100644 index 000000000..ed89bcfbe --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/UserApiIntegrationTest.java @@ -0,0 +1,299 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.service.UserService; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class UserApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private UserService userService; + + + @Test + @WithMockUser(roles = "USER") + @DisplayName("사용자 생성 API 통합 테스트") + void createUser_Success() throws Exception { + // Given + UserCreateRequest createRequest = new UserCreateRequest( + "testuser", + "test@example.com", + "Password1!" + ); + + MockMultipartFile userCreateRequestPart = new MockMultipartFile( + "userCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(createRequest) + ); + + MockMultipartFile profilePart = new MockMultipartFile( + "profile", + "profile.jpg", + MediaType.IMAGE_JPEG_VALUE, + "test-image".getBytes() + ); + + // When & Then + mockMvc.perform(multipart("/api/users") + .file(userCreateRequestPart) + .file(profilePart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(csrf())) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.username", is("testuser"))) + .andExpect(jsonPath("$.email", is("test@example.com"))) + .andExpect(jsonPath("$.profile.fileName", is("profile.jpg"))) + .andExpect(jsonPath("$.online", is(false))); + } + + @Test + @WithMockUser(roles = "USER") + @DisplayName("사용자 생성 실패 API 통합 테스트 - 유효하지 않은 요청") + void createUser_Failure_InvalidRequest() throws Exception { + // Given + UserCreateRequest invalidRequest = new UserCreateRequest( + "t", // 최소 길이 위반 + "invalid-email", // 이메일 형식 위반 + "short" // 비밀번호 정책 위반 + ); + + MockMultipartFile userCreateRequestPart = new MockMultipartFile( + "userCreateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(invalidRequest) + ); + + // When & Then + mockMvc.perform(multipart("/api/users") + .file(userCreateRequestPart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(csrf())) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + @DisplayName("모든 사용자 조회 API 통합 테스트") + void findAllUsers_Success() throws Exception { + // Given + // 테스트 사용자 생성 - Service를 통해 초기화 + UserCreateRequest userRequest1 = new UserCreateRequest( + "user1", + "user1@example.com", + "Password1!" + ); + + UserCreateRequest userRequest2 = new UserCreateRequest( + "user2", + "user2@example.com", + "Password1!" + ); + + userService.create(userRequest1, Optional.empty()); + userService.create(userRequest2, Optional.empty()); + + // When & Then + mockMvc.perform(get("/api/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))) // 시스템 사용자 포함하여 3개 + .andExpect(jsonPath("$[?(@.username == 'user1')].email", hasItems("user1@example.com"))) + .andExpect(jsonPath("$[?(@.username == 'user2')].email", hasItems("user2@example.com"))); + } + + @Test + @WithMockUser(roles = "ADMIN") + @DisplayName("사용자 업데이트 API 통합 테스트") + void updateUser_Success() throws Exception { + // Given + // 테스트 사용자 생성 - Service를 통해 초기화 + UserCreateRequest createRequest = new UserCreateRequest( + "originaluser", + "original@example.com", + "Password1!" + ); + + UserDto createdUser = userService.create(createRequest, Optional.empty()); + UUID userId = createdUser.id(); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(createdUser, "Password1!"); + + UserUpdateRequest updateRequest = new UserUpdateRequest( + "updateduser", + "updated@example.com", + "UpdatedPassword1!" + ); + + MockMultipartFile userUpdateRequestPart = new MockMultipartFile( + "userUpdateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(updateRequest) + ); + + MockMultipartFile profilePart = new MockMultipartFile( + "profile", + "updated-profile.jpg", + MediaType.IMAGE_JPEG_VALUE, + "updated-image".getBytes() + ); + + // When & Then + mockMvc.perform(multipart("/api/users/{userId}", userId) + .file(userUpdateRequestPart) + .file(profilePart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(request -> { + request.setMethod("PATCH"); + return request; + }) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(userId.toString()))) + .andExpect(jsonPath("$.username", is("updateduser"))) + .andExpect(jsonPath("$.email", is("updated@example.com"))) + .andExpect(jsonPath("$.profile.fileName", is("updated-profile.jpg"))); + } + + @Test + @DisplayName("사용자 업데이트 실패 API 통합 테스트 - 존재하지 않는 사용자") + void updateUser_Failure_UserNotFound() throws Exception { + // Given + // 존재하지 않는 UUID를 사용하여 DiscodeitUserDetails 생성 + UUID nonExistentUserId = UUID.fromString("00000000-0000-0000-0000-000000000999"); + + // 가짜 UserDto 생성 (인증용) + UserDto fakeUser = new UserDto( + nonExistentUserId, + "fakeuser", + "fake@example.com", + null, + false, +Role.USER + ); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(fakeUser, "Password1!"); + + UserUpdateRequest updateRequest = new UserUpdateRequest( + "updateduser", + "updated@example.com", + "UpdatedPassword1!" + ); + + MockMultipartFile userUpdateRequestPart = new MockMultipartFile( + "userUpdateRequest", + "", + MediaType.APPLICATION_JSON_VALUE, + objectMapper.writeValueAsBytes(updateRequest) + ); + + // When & Then + mockMvc.perform(multipart("/api/users/{userId}", nonExistentUserId) + .file(userUpdateRequestPart) + .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) + .with(request -> { + request.setMethod("PATCH"); + return request; + }) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "ADMIN") + @DisplayName("사용자 삭제 API 통합 테스트") + void deleteUser_Success() throws Exception { + // Given + // 테스트 사용자 생성 - Service를 통해 초기화 + UserCreateRequest createRequest = new UserCreateRequest( + "deleteuser", + "delete@example.com", + "Password1!" + ); + + UserDto createdUser = userService.create(createRequest, Optional.empty()); + UUID userId = createdUser.id(); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(createdUser, "Password1!"); + + // When & Then + mockMvc.perform(delete("/api/users/{userId}", userId) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isNoContent()); + + // 삭제 확인 + mockMvc.perform(get("/api/users")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[?(@.id == '" + userId + "')]").doesNotExist()); + } + + @Test + @DisplayName("사용자 삭제 실패 API 통합 테스트 - 존재하지 않는 사용자") + void deleteUser_Failure_UserNotFound() throws Exception { + // Given + // 존재하지 않는 UUID를 사용하여 DiscodeitUserDetails 생성 + UUID nonExistentUserId = UUID.fromString("00000000-0000-0000-0000-000000000999"); + + // 가짜 UserDto 생성 (인증용) + UserDto fakeUser = new UserDto( + nonExistentUserId, + "fakeuser", + "fake@example.com", + null, + false, +Role.USER + ); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(fakeUser, "Password1!"); + + // When & Then + mockMvc.perform(delete("/api/users/{userId}", nonExistentUserId) + .with(csrf()) + .with(user(userDetails))) + .andExpect(status().isNotFound()); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/repository/ChannelRepositoryTest.java b/src/test/java/com/sprint/mission/discodeit/repository/ChannelRepositoryTest.java new file mode 100644 index 000000000..6d4563153 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/ChannelRepositoryTest.java @@ -0,0 +1,96 @@ +package com.sprint.mission.discodeit.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.test.context.ActiveProfiles; + +/** + * ChannelRepository 슬라이스 테스트 + */ +@DataJpaTest +@EnableJpaAuditing +@ActiveProfiles("test") +class ChannelRepositoryTest { + + @Autowired + private ChannelRepository channelRepository; + + @Autowired + private TestEntityManager entityManager; + + /** + * TestFixture: 채널 생성용 테스트 픽스처 + */ + private Channel createTestChannel(ChannelType type, String name) { + Channel channel = new Channel(type, name, "설명: " + name); + return channelRepository.save(channel); + } + + @Test + @DisplayName("타입이 PUBLIC이거나 ID 목록에 포함된 채널을 모두 조회할 수 있다") + void findAllByTypeOrIdIn_ReturnsChannels() { + // given + Channel publicChannel1 = createTestChannel(ChannelType.PUBLIC, "공개채널1"); + Channel publicChannel2 = createTestChannel(ChannelType.PUBLIC, "공개채널2"); + Channel privateChannel1 = createTestChannel(ChannelType.PRIVATE, "비공개채널1"); + Channel privateChannel2 = createTestChannel(ChannelType.PRIVATE, "비공개채널2"); + + channelRepository.saveAll( + Arrays.asList(publicChannel1, publicChannel2, privateChannel1, privateChannel2)); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + List selectedPrivateIds = List.of(privateChannel1.getId()); + List foundChannels = channelRepository.findAllByTypeOrIdIn(ChannelType.PUBLIC, + selectedPrivateIds); + + // then + assertThat(foundChannels).hasSize(3); // 공개채널 2개 + 선택된 비공개채널 1개 + + // 공개 채널 2개가 모두 포함되어 있는지 확인 + assertThat( + foundChannels.stream().filter(c -> c.getType() == ChannelType.PUBLIC).count()).isEqualTo(2); + + // 선택된 비공개 채널만 포함되어 있는지 확인 + List privateChannels = foundChannels.stream() + .filter(c -> c.getType() == ChannelType.PRIVATE) + .toList(); + assertThat(privateChannels).hasSize(1); + assertThat(privateChannels.get(0).getId()).isEqualTo(privateChannel1.getId()); + } + + @Test + @DisplayName("타입이 PUBLIC이 아니고 ID 목록이 비어있으면 비어있는 리스트를 반환한다") + void findAllByTypeOrIdIn_EmptyList_ReturnsEmptyList() { + // given + Channel privateChannel1 = createTestChannel(ChannelType.PRIVATE, "비공개채널1"); + Channel privateChannel2 = createTestChannel(ChannelType.PRIVATE, "비공개채널2"); + + channelRepository.saveAll(Arrays.asList(privateChannel1, privateChannel2)); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + List foundChannels = channelRepository.findAllByTypeOrIdIn(ChannelType.PUBLIC, + List.of()); + + // then + assertThat(foundChannels).isEmpty(); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/repository/MessageRepositoryTest.java b/src/test/java/com/sprint/mission/discodeit/repository/MessageRepositoryTest.java new file mode 100644 index 000000000..39e4fa6cf --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/MessageRepositoryTest.java @@ -0,0 +1,217 @@ +package com.sprint.mission.discodeit.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.hibernate.Hibernate; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.util.ReflectionTestUtils; + +/** + * MessageRepository 슬라이스 테스트 + */ +@DataJpaTest +@EnableJpaAuditing +@ActiveProfiles("test") +class MessageRepositoryTest { + + @Autowired + private MessageRepository messageRepository; + + @Autowired + private ChannelRepository channelRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private TestEntityManager entityManager; + + /** + * TestFixture: 테스트용 사용자 생성 + */ + private User createTestUser(String username, String email) { + BinaryContent profile = new BinaryContent("profile.jpg", 1024L, "image/jpeg"); + User user = new User(username, email, "password123!@#", profile); + return userRepository.save(user); + } + + /** + * TestFixture: 테스트용 채널 생성 + */ + private Channel createTestChannel(ChannelType type, String name) { + Channel channel = new Channel(type, name, "설명: " + name); + return channelRepository.save(channel); + } + + /** + * TestFixture: 테스트용 메시지 생성 ReflectionTestUtils를 사용하여 createdAt 필드를 직접 설정 + */ + private Message createTestMessage(String content, Channel channel, User author, + Instant createdAt) { + Message message = new Message(content, channel, author, new ArrayList<>()); + + // 생성 시간이 지정된 경우, ReflectionTestUtils로 설정 + if (createdAt != null) { + ReflectionTestUtils.setField(message, "createdAt", createdAt); + } + + Message savedMessage = messageRepository.save(message); + entityManager.flush(); + + return savedMessage; + } + + @Test + @DisplayName("채널 ID와 생성 시간으로 메시지를 페이징하여 조회할 수 있다") + void findAllByChannelIdWithAuthor_ReturnsMessagesWithAuthor() { + // given + User user = createTestUser("testUser", "test@example.com"); + Channel channel = createTestChannel(ChannelType.PUBLIC, "테스트채널"); + + Instant now = Instant.now(); + Instant fiveMinutesAgo = now.minus(5, ChronoUnit.MINUTES); + Instant tenMinutesAgo = now.minus(10, ChronoUnit.MINUTES); + + // 채널에 세 개의 메시지 생성 (시간 순서대로) + Message message1 = createTestMessage("첫 번째 메시지", channel, user, tenMinutesAgo); + Message message2 = createTestMessage("두 번째 메시지", channel, user, fiveMinutesAgo); + Message message3 = createTestMessage("세 번째 메시지", channel, user, now); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when - 최신 메시지보다 이전 시간으로 조회 + Slice messages = messageRepository.findAllByChannelIdWithAuthor( + channel.getId(), + now.plus(1, ChronoUnit.MINUTES), // 현재 시간보다 더 미래 + PageRequest.of(0, 2, Sort.by(Sort.Direction.DESC, "createdAt")) + ); + + // then + assertThat(messages).isNotNull(); + assertThat(messages.hasContent()).isTrue(); + assertThat(messages.getNumberOfElements()).isEqualTo(2); // 페이지 크기 만큼만 반환 + assertThat(messages.hasNext()).isTrue(); + + // 시간 역순(최신순)으로 정렬되어 있는지 확인 + List content = messages.getContent(); + assertThat(content.get(0).getCreatedAt()).isAfterOrEqualTo(content.get(1).getCreatedAt()); + + // 저자 정보가 함께 로드되었는지 확인 (FETCH JOIN) + Message firstMessage = content.get(0); + assertThat(Hibernate.isInitialized(firstMessage.getAuthor())).isTrue(); + assertThat(Hibernate.isInitialized(firstMessage.getAuthor().getProfile())).isTrue(); + } + + @Test + @DisplayName("채널의 마지막 메시지 시간을 조회할 수 있다") + void findLastMessageAtByChannelId_ReturnsLastMessageTime() { + // given + User user = createTestUser("testUser", "test@example.com"); + Channel channel = createTestChannel(ChannelType.PUBLIC, "테스트채널"); + + Instant now = Instant.now(); + Instant fiveMinutesAgo = now.minus(5, ChronoUnit.MINUTES); + Instant tenMinutesAgo = now.minus(10, ChronoUnit.MINUTES); + + // 채널에 세 개의 메시지 생성 (시간 순서대로) + createTestMessage("첫 번째 메시지", channel, user, tenMinutesAgo); + createTestMessage("두 번째 메시지", channel, user, fiveMinutesAgo); + Message lastMessage = createTestMessage("세 번째 메시지", channel, user, now); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + Optional lastMessageAt = messageRepository.findLastMessageAtByChannelId( + channel.getId()); + + // then + assertThat(lastMessageAt).isPresent(); + // 마지막 메시지 시간과 일치하는지 확인 (밀리초 단위 이하의 차이는 무시) + assertThat(lastMessageAt.get().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(lastMessage.getCreatedAt().truncatedTo(ChronoUnit.MILLIS)); + } + + @Test + @DisplayName("메시지가 없는 채널에서는 마지막 메시지 시간이 없다") + void findLastMessageAtByChannelId_NoMessages_ReturnsEmpty() { + // given + Channel emptyChannel = createTestChannel(ChannelType.PUBLIC, "빈채널"); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + Optional lastMessageAt = messageRepository.findLastMessageAtByChannelId( + emptyChannel.getId()); + + // then + assertThat(lastMessageAt).isEmpty(); + } + + @Test + @DisplayName("채널의 모든 메시지를 삭제할 수 있다") + void deleteAllByChannelId_DeletesAllMessages() { + // given + User user = createTestUser("testUser", "test@example.com"); + Channel channel = createTestChannel(ChannelType.PUBLIC, "테스트채널"); + Channel otherChannel = createTestChannel(ChannelType.PUBLIC, "다른채널"); + + // 테스트 채널에 메시지 3개 생성 + createTestMessage("첫 번째 메시지", channel, user, null); + createTestMessage("두 번째 메시지", channel, user, null); + createTestMessage("세 번째 메시지", channel, user, null); + + // 다른 채널에 메시지 1개 생성 + createTestMessage("다른 채널 메시지", otherChannel, user, null); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + messageRepository.deleteAllByChannelId(channel.getId()); + entityManager.flush(); + entityManager.clear(); + + // then + // 해당 채널의 메시지는 삭제되었는지 확인 + List channelMessages = messageRepository.findAllByChannelIdWithAuthor( + channel.getId(), + Instant.now().plus(1, ChronoUnit.DAYS), + PageRequest.of(0, 100) + ).getContent(); + assertThat(channelMessages).isEmpty(); + + // 다른 채널의 메시지는 그대로인지 확인 + List otherChannelMessages = messageRepository.findAllByChannelIdWithAuthor( + otherChannel.getId(), + Instant.now().plus(1, ChronoUnit.DAYS), + PageRequest.of(0, 100) + ).getContent(); + assertThat(otherChannelMessages).hasSize(1); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/repository/ReadStatusRepositoryTest.java b/src/test/java/com/sprint/mission/discodeit/repository/ReadStatusRepositoryTest.java new file mode 100644 index 000000000..aa475562a --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/ReadStatusRepositoryTest.java @@ -0,0 +1,197 @@ +package com.sprint.mission.discodeit.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.ReadStatus; +import com.sprint.mission.discodeit.entity.User; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import org.hibernate.Hibernate; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.test.context.ActiveProfiles; + +/** + * ReadStatusRepository 슬라이스 테스트 + */ +@DataJpaTest +@EnableJpaAuditing +@ActiveProfiles("test") +class ReadStatusRepositoryTest { + + @Autowired + private ReadStatusRepository readStatusRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private ChannelRepository channelRepository; + + @Autowired + private TestEntityManager entityManager; + + /** + * TestFixture: 테스트용 사용자 생성 + */ + private User createTestUser(String username, String email) { + BinaryContent profile = new BinaryContent("profile.jpg", 1024L, "image/jpeg"); + User user = new User(username, email, "password123!@#", profile); + return userRepository.save(user); + } + + /** + * TestFixture: 테스트용 채널 생성 + */ + private Channel createTestChannel(ChannelType type, String name) { + Channel channel = new Channel(type, name, "설명: " + name); + return channelRepository.save(channel); + } + + /** + * TestFixture: 테스트용 읽음 상태 생성 + */ + private ReadStatus createTestReadStatus(User user, Channel channel, Instant lastReadAt) { + ReadStatus readStatus = new ReadStatus(user, channel, lastReadAt); + return readStatusRepository.save(readStatus); + } + + @Test + @DisplayName("사용자 ID로 모든 읽음 상태를 조회할 수 있다") + void findAllByUserId_ReturnsReadStatuses() { + // given + User user = createTestUser("testUser", "test@example.com"); + Channel channel1 = createTestChannel(ChannelType.PUBLIC, "채널1"); + Channel channel2 = createTestChannel(ChannelType.PRIVATE, "채널2"); + + Instant now = Instant.now(); + ReadStatus readStatus1 = createTestReadStatus(user, channel1, now.minus(1, ChronoUnit.DAYS)); + ReadStatus readStatus2 = createTestReadStatus(user, channel2, now); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + List readStatuses = readStatusRepository.findAllByUserId(user.getId()); + + // then + assertThat(readStatuses).hasSize(2); + } + + @Test + @DisplayName("채널 ID로 모든 읽음 상태를 사용자 정보와 함께 조회할 수 있다") + void findAllByChannelIdWithUser_ReturnsReadStatusesWithUser() { + // given + User user1 = createTestUser("user1", "user1@example.com"); + User user2 = createTestUser("user2", "user2@example.com"); + Channel channel = createTestChannel(ChannelType.PUBLIC, "공개채널"); + + Instant now = Instant.now(); + ReadStatus readStatus1 = createTestReadStatus(user1, channel, now.minus(1, ChronoUnit.DAYS)); + ReadStatus readStatus2 = createTestReadStatus(user2, channel, now); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + List readStatuses = readStatusRepository.findAllByChannelIdWithUser( + channel.getId()); + + // then + assertThat(readStatuses).hasSize(2); + + // 사용자 정보가 함께 로드되었는지 확인 (FETCH JOIN) + for (ReadStatus status : readStatuses) { + assertThat(Hibernate.isInitialized(status.getUser())).isTrue(); + assertThat(Hibernate.isInitialized(status.getUser().getProfile())).isTrue(); + } + } + + @Test + @DisplayName("사용자 ID와 채널 ID로 읽음 상태 존재 여부를 확인할 수 있다") + void existsByUserIdAndChannelId_ExistingStatus_ReturnsTrue() { + // given + User user = createTestUser("testUser", "test@example.com"); + Channel channel = createTestChannel(ChannelType.PUBLIC, "공개채널"); + + ReadStatus readStatus = createTestReadStatus(user, channel, Instant.now()); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + Boolean exists = readStatusRepository.existsByUserIdAndChannelId(user.getId(), channel.getId()); + + // then + assertThat(exists).isTrue(); + } + + @Test + @DisplayName("존재하지 않는 읽음 상태에 대해 false를 반환한다") + void existsByUserIdAndChannelId_NonExistingStatus_ReturnsFalse() { + // given + User user = createTestUser("testUser", "test@example.com"); + Channel channel = createTestChannel(ChannelType.PUBLIC, "공개채널"); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // 읽음 상태를 생성하지 않음 + + // when + Boolean exists = readStatusRepository.existsByUserIdAndChannelId(user.getId(), channel.getId()); + + // then + assertThat(exists).isFalse(); + } + + @Test + @DisplayName("채널의 모든 읽음 상태를 삭제할 수 있다") + void deleteAllByChannelId_DeletesAllReadStatuses() { + // given + User user1 = createTestUser("user1", "user1@example.com"); + User user2 = createTestUser("user2", "user2@example.com"); + + Channel channel = createTestChannel(ChannelType.PUBLIC, "삭제할채널"); + Channel otherChannel = createTestChannel(ChannelType.PUBLIC, "유지할채널"); + + // 삭제할 채널에 읽음 상태 2개 생성 + createTestReadStatus(user1, channel, Instant.now()); + createTestReadStatus(user2, channel, Instant.now()); + + // 유지할 채널에 읽음 상태 1개 생성 + createTestReadStatus(user1, otherChannel, Instant.now()); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + readStatusRepository.deleteAllByChannelId(channel.getId()); + entityManager.flush(); + entityManager.clear(); + + // then + // 해당 채널의 읽음 상태는 삭제되었는지 확인 + List channelReadStatuses = readStatusRepository.findAllByChannelIdWithUser( + channel.getId()); + assertThat(channelReadStatuses).isEmpty(); + + // 다른 채널의 읽음 상태는 그대로인지 확인 + List otherChannelReadStatuses = readStatusRepository.findAllByChannelIdWithUser( + otherChannel.getId()); + assertThat(otherChannelReadStatuses).hasSize(1); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/repository/UserRepositoryTest.java b/src/test/java/com/sprint/mission/discodeit/repository/UserRepositoryTest.java new file mode 100644 index 000000000..94bc50641 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/UserRepositoryTest.java @@ -0,0 +1,132 @@ +package com.sprint.mission.discodeit.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.User; +import java.util.List; +import java.util.Optional; +import org.hibernate.Hibernate; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.test.context.ActiveProfiles; + +/** + * UserRepository 슬라이스 테스트 + */ +@DataJpaTest +@EnableJpaAuditing +@ActiveProfiles("test") +class UserRepositoryTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private TestEntityManager entityManager; + + /** + * TestFixture: 테스트에서 일관된 상태를 제공하기 위한 고정된 객체 세트 여러 테스트에서 재사용할 수 있는 테스트 데이터를 생성하는 메서드 + */ + private User createTestUser(String username, String email) { + BinaryContent profile = new BinaryContent("profile.jpg", 1024L, "image/jpeg"); + User user = new User(username, email, "password123!@#", profile); + return user; + } + + @Test + @DisplayName("사용자 이름으로 사용자를 찾을 수 있다") + void findByUsername_ExistingUsername_ReturnsUser() { + // given + String username = "testUser"; + User user = createTestUser(username, "test@example.com"); + userRepository.save(user); + + // 영속성 컨텍스트 초기화 - 1차 캐시 비우기 + entityManager.flush(); + entityManager.clear(); + + // when + Optional foundUser = userRepository.findByUsername(username); + + // then + assertThat(foundUser).isPresent(); + assertThat(foundUser.get().getUsername()).isEqualTo(username); + } + + @Test + @DisplayName("존재하지 않는 사용자 이름으로 검색하면 빈 Optional을 반환한다") + void findByUsername_NonExistingUsername_ReturnsEmptyOptional() { + // given + String nonExistingUsername = "nonExistingUser"; + + // when + Optional foundUser = userRepository.findByUsername(nonExistingUsername); + + // then + assertThat(foundUser).isEmpty(); + } + + @Test + @DisplayName("이메일로 사용자 존재 여부를 확인할 수 있다") + void existsByEmail_ExistingEmail_ReturnsTrue() { + // given + String email = "test@example.com"; + User user = createTestUser("testUser", email); + userRepository.save(user); + + // when + boolean exists = userRepository.existsByEmail(email); + + // then + assertThat(exists).isTrue(); + } + + @Test + @DisplayName("존재하지 않는 이메일로 확인하면 false를 반환한다") + void existsByEmail_NonExistingEmail_ReturnsFalse() { + // given + String nonExistingEmail = "nonexisting@example.com"; + + // when + boolean exists = userRepository.existsByEmail(nonExistingEmail); + + // then + assertThat(exists).isFalse(); + } + + @Test + @DisplayName("모든 사용자를 프로필과 함께 조회할 수 있다") + void findAllWithProfileAndStatus_ReturnsUsersWithProfileAndStatus() { + // given + User user1 = createTestUser("user1", "user1@example.com"); + User user2 = createTestUser("user2", "user2@example.com"); + + userRepository.saveAll(List.of(user1, user2)); + + // 영속성 컨텍스트 초기화 - 1차 캐시 비우기 + entityManager.flush(); + entityManager.clear(); + + // when + List users = userRepository.findAllWithProfile(); + + // then + assertThat(users).hasSize(2); + assertThat(users).extracting("username").containsExactlyInAnyOrder("user1", "user2"); + + // 프로필과 상태 정보가 함께 조회되었는지 확인 - 프록시 초기화 없이도 접근 가능한지 테스트 + User foundUser1 = users.stream().filter(u -> u.getUsername().equals("user1")).findFirst() + .orElseThrow(); + User foundUser2 = users.stream().filter(u -> u.getUsername().equals("user2")).findFirst() + .orElseThrow(); + + // 프록시 초기화 여부 확인 + assertThat(Hibernate.isInitialized(foundUser1.getProfile())).isTrue(); + assertThat(Hibernate.isInitialized(foundUser2.getProfile())).isTrue(); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/security/CsrfTest.java b/src/test/java/com/sprint/mission/discodeit/security/CsrfTest.java new file mode 100644 index 000000000..270aba61d --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/security/CsrfTest.java @@ -0,0 +1,34 @@ +package com.sprint.mission.discodeit.security; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class CsrfTest { + + @Autowired + private MockMvc mockMvc; + + @Test + @DisplayName("CSRF 토큰 요청 테스트") + void getCsrfToken() throws Exception { + // When & Then - CSRF 토큰 엔드포인트가 정상적으로 호출되는지만 확인 + mockMvc.perform(get("/api/auth/csrf-token")) + .andExpect(status().isNoContent()) + .andExpect(cookie().exists("XSRF-TOKEN")) + ; + } +} diff --git a/src/test/java/com/sprint/mission/discodeit/security/LoginTest.java b/src/test/java/com/sprint/mission/discodeit/security/LoginTest.java new file mode 100644 index 000000000..b6a2c025a --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/security/LoginTest.java @@ -0,0 +1,138 @@ +package com.sprint.mission.discodeit.security; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.LoginRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.util.MultiValueMap; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class LoginTest { + + @Autowired + private MockMvc mockMvc; + @Autowired + private PasswordEncoder passwordEncoder; + @MockitoBean + private UserDetailsService userDetailsService; + + @Test + @DisplayName("로그인 성공 테스트") + void login_Success() throws Exception { + // Given + LoginRequest loginRequest = new LoginRequest( + "testuser", + "Password1!" + ); + + UUID userId = UUID.randomUUID(); + UserDto loggedInUser = new UserDto( + userId, + "testuser", + "test@example.com", + null, + false, + Role.USER + ); + + given(userDetailsService.loadUserByUsername(any(String.class))) + .willReturn(new DiscodeitUserDetails(loggedInUser, passwordEncoder.encode("Password1!"))); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .with(csrf()) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .formFields(MultiValueMap.fromMultiValue(Map.of( + "username", List.of(loginRequest.username()), + "password", List.of(loginRequest.password()) + )))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.userDto.id").value(userId.toString())) + .andExpect(jsonPath("$.userDto.username").value("testuser")) + .andExpect(jsonPath("$.userDto.email").value("test@example.com")) + .andExpect(jsonPath("$.userDto.online").value(false)) + .andExpect(jsonPath("$.accessToken").exists()); + } + + @Test + @DisplayName("로그인 실패 테스트 - 존재하지 않는 사용자") + void login_Failure_UserNotFound() throws Exception { + // Given + + LoginRequest loginRequest = new LoginRequest( + "nonexistentuser", + "Password1!" + ); + + given(userDetailsService.loadUserByUsername(any(String.class))) + .willThrow(UserNotFoundException.withUsername(loginRequest.username())); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .with(csrf()) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .formFields(MultiValueMap.fromMultiValue(Map.of( + "username", List.of(loginRequest.username()), + "password", List.of(loginRequest.password()) + )))) + .andExpect(status().isUnauthorized()); + } + + @Test + @DisplayName("로그인 실패 테스트 - 잘못된 비밀번호") + void login_Failure_InvalidCredentials() throws Exception { + // Given + LoginRequest loginRequest = new LoginRequest( + "testuser", + "WrongPassword1!" + ); + UUID userId = UUID.randomUUID(); + UserDto loggedInUser = new UserDto( + userId, + "testuser", + "test@example.com", + null, + false, + Role.USER + ); + + given(userDetailsService.loadUserByUsername(any(String.class))) + .willReturn(new DiscodeitUserDetails(loggedInUser, passwordEncoder.encode("Password1!"))); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .with(csrf()) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .formFields(MultiValueMap.fromMultiValue(Map.of( + "username", List.of(loginRequest.username()), + "password", List.of(loginRequest.password()) + )))) + .andExpect(status().isUnauthorized()); + } + +} diff --git a/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilterTest.java b/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilterTest.java new file mode 100644 index 000000000..82f938bf0 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilterTest.java @@ -0,0 +1,153 @@ +package com.sprint.mission.discodeit.security.jwt; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.security.DiscodeitUserDetailsService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; + +@ExtendWith(MockitoExtension.class) +class JwtAuthenticationFilterTest { + + @Mock + private JwtTokenProvider tokenProvider; + + @Mock + private DiscodeitUserDetailsService userDetailsService; + + @Mock + private HttpServletRequest request; + + @Mock + private HttpServletResponse response; + + @Mock + private FilterChain filterChain; + + @Mock + private SecurityContext securityContext; + + @Mock + private PrintWriter printWriter; + + @Mock + private JwtRegistry jwtRegistry; + + private JwtAuthenticationFilter jwtAuthenticationFilter; + private DiscodeitUserDetails userDetails; + private ObjectMapper objectMapper; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + + jwtAuthenticationFilter = new JwtAuthenticationFilter(tokenProvider, userDetailsService, + objectMapper, jwtRegistry); + + UUID userId = UUID.randomUUID(); + UserDto userDto = new UserDto( + userId, + "testuser", + "test@example.com", + null, + false, + Role.USER + ); + + userDetails = new DiscodeitUserDetails(userDto, "encoded-password"); + + SecurityContextHolder.setContext(securityContext); + } + + @Test + @DisplayName("JWT 인증 필터 - 유효한 토큰으로 인증 성공") + void doFilterInternal_ValidToken_SetsAuthentication() throws Exception { + // Given + String token = "valid.jwt.token"; + String username = "testuser"; + + when(request.getHeader("Authorization")).thenReturn("Bearer " + token); + given(tokenProvider.validateAccessToken(token)).willReturn(true); + given(tokenProvider.getUsernameFromToken(token)).willReturn(username); + given(userDetailsService.loadUserByUsername(username)).willReturn(userDetails); + given(jwtRegistry.hasActiveJwtInformationByAccessToken(token)).willReturn(true); + + // When + jwtAuthenticationFilter.doFilterInternal(request, response, filterChain); + + // Then + verify(securityContext).setAuthentication(any()); + verify(filterChain).doFilter(request, response); + } + + @Test + @DisplayName("JWT 인증 필터 - 토큰 없음, 인증 설정하지 않음") + void doFilterInternal_NoToken_DoesNotSetAuthentication() throws Exception { + // Given + when(request.getHeader("Authorization")).thenReturn(null); + + // When + jwtAuthenticationFilter.doFilterInternal(request, response, filterChain); + + // Then + verify(securityContext, never()).setAuthentication(any()); + verify(tokenProvider, never()).validateAccessToken(any()); + verify(filterChain).doFilter(request, response); + } + + @Test + @DisplayName("JWT 인증 필터 - 잘못된 토큰, 인증 설정하지 않음") + void doFilterInternal_InvalidToken_DoesNotSetAuthentication() throws Exception { + // Given + String token = "invalid.jwt.token"; + + when(request.getHeader("Authorization")).thenReturn("Bearer " + token); + given(tokenProvider.validateAccessToken(token)).willReturn(false); + when(response.getWriter()).thenReturn(printWriter); + + // When + jwtAuthenticationFilter.doFilterInternal(request, response, filterChain); + + // Then + verify(securityContext, never()).setAuthentication(any()); + verify(userDetailsService, never()).loadUserByUsername(any()); + verify(filterChain, never()).doFilter(request, response); + verify(response).setStatus(401); + } + + @Test + @DisplayName("JWT 인증 필터 - Bearer 없는 Authorization 헤더, 인증 설정하지 않음") + void doFilterInternal_NonBearerToken_DoesNotSetAuthentication() throws Exception { + // Given + when(request.getHeader("Authorization")).thenReturn("Basic dGVzdDp0ZXN0"); + + // When + jwtAuthenticationFilter.doFilterInternal(request, response, filterChain); + + // Then + verify(securityContext, never()).setAuthentication(any()); + verify(tokenProvider, never()).validateAccessToken(any()); + verify(filterChain).doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandlerTest.java b/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandlerTest.java new file mode 100644 index 000000000..ab911bfa4 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandlerTest.java @@ -0,0 +1,130 @@ +package com.sprint.mission.discodeit.security.jwt; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.nimbusds.jose.JOSEException; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; + +@ExtendWith(MockitoExtension.class) +class JwtLoginSuccessHandlerTest { + + @Mock + private JwtTokenProvider tokenProvider; + + @Mock + private HttpServletRequest request; + + @Mock + private HttpServletResponse response; + + @Mock + private Authentication authentication; + + @Mock + private JwtRegistry jwtRegistry; + + private JwtLoginSuccessHandler jwtLoginSuccessHandler; + private ObjectMapper objectMapper; + private DiscodeitUserDetails userDetails; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + jwtLoginSuccessHandler = new JwtLoginSuccessHandler(objectMapper, tokenProvider, jwtRegistry); + + UUID userId = UUID.randomUUID(); + UserDto userDto = new UserDto( + userId, + "testuser", + "test@example.com", + null, + false, + Role.USER + ); + + userDetails = new DiscodeitUserDetails(userDto, "encoded-password"); + } + + @Test + @DisplayName("JWT 로그인 성공 핸들러 - 성공 테스트") + void onAuthenticationSuccess_Success() throws Exception { + // Given + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(response.getWriter()).thenReturn(printWriter); + when(authentication.getPrincipal()).thenReturn(userDetails); + given(tokenProvider.generateAccessToken(any(DiscodeitUserDetails.class))) + .willReturn("test.jwt.token"); + + // When + jwtLoginSuccessHandler.onAuthenticationSuccess(request, response, authentication); + + // Then + verify(response).setCharacterEncoding("UTF-8"); + verify(response).setContentType(MediaType.APPLICATION_JSON_VALUE); + verify(response).setStatus(HttpServletResponse.SC_OK); + verify(tokenProvider).generateAccessToken(userDetails); + + String responseBody = stringWriter.toString(); + assert responseBody.contains("\"accessToken\":\"test.jwt.token\""); + assert responseBody.contains("\"username\":\"testuser\""); + } + + @Test + @DisplayName("JWT 로그인 성공 핸들러 - 토큰 생성 실패 테스트") + void onAuthenticationSuccess_TokenGenerationFailure() throws Exception { + // Given + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(response.getWriter()).thenReturn(printWriter); + when(authentication.getPrincipal()).thenReturn(userDetails); + given(tokenProvider.generateAccessToken(any(DiscodeitUserDetails.class))) + .willThrow(new JOSEException("Token generation failed")); + + // When + jwtLoginSuccessHandler.onAuthenticationSuccess(request, response, authentication); + + // Then + verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + @Test + @DisplayName("JWT 로그인 성공 핸들러 - 잘못된 사용자 정보 테스트") + void onAuthenticationSuccess_InvalidUserDetails() throws Exception { + // Given + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(response.getWriter()).thenReturn(printWriter); + when(authentication.getPrincipal()).thenReturn("invalid-user-details"); + + // When + jwtLoginSuccessHandler.onAuthenticationSuccess(request, response, authentication); + + // Then + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProviderTest.java b/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProviderTest.java new file mode 100644 index 000000000..d1d446411 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/security/jwt/JwtTokenProviderTest.java @@ -0,0 +1,208 @@ +package com.sprint.mission.discodeit.security.jwt; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.nimbusds.jose.JOSEException; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class JwtTokenProviderTest { + + private JwtTokenProvider jwtTokenProvider; + private DiscodeitUserDetails userDetails; + + @BeforeEach + void setUp() throws JOSEException { + String testAccessSecret = "test-access-secret-key-for-jwt-token-generation-and-validation-must-be-long-enough"; + String testRefreshSecret = "test-refresh-secret-key-for-jwt-token-generation-and-validation-must-be-long-enough"; + int testAccessExpirationMs = 1800000; // 30 minutes + int testRefreshExpirationMs = 604800000; // 7 days + + jwtTokenProvider = new JwtTokenProvider(testAccessSecret, testAccessExpirationMs, + testRefreshSecret, testRefreshExpirationMs); + + UUID userId = UUID.randomUUID(); + UserDto userDto = new UserDto( + userId, + "testuser", + "test@example.com", + null, + false, + Role.USER + ); + + userDetails = new DiscodeitUserDetails(userDto, "encoded-password"); + } + + @Test + @DisplayName("JWT 토큰 생성 테스트") + void generateAccessToken_Success() throws JOSEException { + // When + String token = jwtTokenProvider.generateAccessToken(userDetails); + + // Then + assertThat(token).isNotNull(); + assertThat(token).isNotEmpty(); + assertThat(token.split("\\.")).hasSize(3); // JWT should have 3 parts: header.payload.signature + } + + @Test + @DisplayName("유효한 JWT 토큰 검증 테스트") + void validateToken_ValidAccessToken_ReturnsTrue() throws JOSEException { + // Given + String token = jwtTokenProvider.generateAccessToken(userDetails); + + // When + boolean isValid = jwtTokenProvider.validateAccessToken(token); + + // Then + assertThat(isValid).isTrue(); + } + + @Test + @DisplayName("잘못된 JWT 토큰 검증 테스트") + void validateToken_InvalidAccessToken_ReturnsFalse() { + // Given + String invalidToken = "invalid.jwt.token"; + + // When + boolean isValid = jwtTokenProvider.validateAccessToken(invalidToken); + + // Then + assertThat(isValid).isFalse(); + } + + @Test + @DisplayName("null 토큰 검증 테스트") + void validateToken_NullAccessToken_ReturnsFalse() { + // When + boolean isValid = jwtTokenProvider.validateAccessToken(null); + + // Then + assertThat(isValid).isFalse(); + } + + @Test + @DisplayName("빈 토큰 검증 테스트") + void validateToken_EmptyAccessToken_ReturnsFalse() { + // When + boolean isValid = jwtTokenProvider.validateAccessToken(""); + + // Then + assertThat(isValid).isFalse(); + } + + @Test + @DisplayName("JWT 토큰에서 사용자명 추출 테스트") + void getUsernameFromToken_ValidToken_ReturnsUsername() throws JOSEException { + // Given + String token = jwtTokenProvider.generateAccessToken(userDetails); + + // When + String username = jwtTokenProvider.getUsernameFromToken(token); + + // Then + assertThat(username).isEqualTo("testuser"); + } + + @Test + @DisplayName("잘못된 토큰에서 사용자명 추출 테스트 - 예외 발생") + void getUsernameFromToken_InvalidToken_ThrowsException() { + // Given + String invalidToken = "invalid.jwt.token"; + + // When & Then + assertThatThrownBy(() -> jwtTokenProvider.getUsernameFromToken(invalidToken)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid JWT token"); + } + + @Test + @DisplayName("JWT 토큰에서 토큰 ID 추출 테스트") + void getTokenId_ValidToken_ReturnsTokenId() throws JOSEException { + // Given + String token = jwtTokenProvider.generateAccessToken(userDetails); + + // When + String tokenId = jwtTokenProvider.getTokenId(token); + + // Then + assertThat(tokenId).isNotNull(); + assertThat(tokenId).isNotEmpty(); + // UUID format check + assertThat(UUID.fromString(tokenId)).isNotNull(); + } + + @Test + @DisplayName("잘못된 토큰에서 토큰 ID 추출 테스트 - 예외 발생") + void getTokenId_InvalidToken_ThrowsException() { + // Given + String invalidToken = "invalid.jwt.token"; + + // When & Then + assertThatThrownBy(() -> jwtTokenProvider.getTokenId(invalidToken)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid JWT token"); + } + + @Test + @DisplayName("만료된 토큰 검증 테스트") + void validateToken_ExpiredAccessToken_ReturnsFalse() throws JOSEException { + // Given - Create provider with very short expiration (1ms) + JwtTokenProvider shortExpirationProvider = new JwtTokenProvider( + "test-access-secret-key-for-jwt-token-generation-and-validation-must-be-long-enough", + 1, + "test-refresh-secret-key-for-jwt-token-generation-and-validation-must-be-long-enough", + 604800000 + ); + + String token = shortExpirationProvider.generateAccessToken(userDetails); + + // Wait for token to expire + try { + Thread.sleep(10); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + // When + boolean isValid = shortExpirationProvider.validateAccessToken(token); + + // Then + assertThat(isValid).isFalse(); + } + + @Test + @DisplayName("다른 사용자의 토큰 생성 및 검증 테스트") + void generateAccessToken_DifferentUser_HasDifferentClaims() throws JOSEException { + // Given + UUID anotherUserId = UUID.randomUUID(); + UserDto anotherUserDto = new UserDto( + anotherUserId, + "anotheruser", + "another@example.com", + null, + true, + Role.ADMIN + ); + DiscodeitUserDetails anotherUserDetails = new DiscodeitUserDetails(anotherUserDto, + "another-password"); + + // When + String token1 = jwtTokenProvider.generateAccessToken(userDetails); + String token2 = jwtTokenProvider.generateAccessToken(anotherUserDetails); + + // Then + assertThat(token1).isNotEqualTo(token2); + assertThat(jwtTokenProvider.getUsernameFromToken(token1)).isEqualTo("testuser"); + assertThat(jwtTokenProvider.getUsernameFromToken(token2)).isEqualTo("anotheruser"); + assertThat(jwtTokenProvider.getTokenId(token1)).isNotEqualTo( + jwtTokenProvider.getTokenId(token2)); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentServiceTest.java b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentServiceTest.java new file mode 100644 index 000000000..fba3f3d65 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentServiceTest.java @@ -0,0 +1,172 @@ +package com.sprint.mission.discodeit.service.basic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.exception.binarycontent.BinaryContentNotFoundException; +import com.sprint.mission.discodeit.mapper.BinaryContentMapper; +import com.sprint.mission.discodeit.repository.BinaryContentRepository; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; + +@ExtendWith(MockitoExtension.class) +class BasicBinaryContentServiceTest { + + @Mock + private BinaryContentRepository binaryContentRepository; + + @Mock + private BinaryContentMapper binaryContentMapper; + + @Mock + private BinaryContentStorage binaryContentStorage; + + @InjectMocks + private BasicBinaryContentService binaryContentService; + + private UUID binaryContentId; + private String fileName; + private String contentType; + private byte[] bytes; + private BinaryContent binaryContent; + private BinaryContentDto binaryContentDto; + + @BeforeEach + void setUp() { + binaryContentId = UUID.randomUUID(); + fileName = "test.jpg"; + contentType = "image/jpeg"; + bytes = "test data".getBytes(); + + binaryContent = new BinaryContent(fileName, (long) bytes.length, contentType); + ReflectionTestUtils.setField(binaryContent, "id", binaryContentId); + + binaryContentDto = new BinaryContentDto( + binaryContentId, + fileName, + (long) bytes.length, + contentType + ); + } + + @Test + @DisplayName("바이너리 콘텐츠 생성 성공") + void createBinaryContent_Success() { + // given + BinaryContentCreateRequest request = new BinaryContentCreateRequest(fileName, contentType, + bytes); + + given(binaryContentRepository.save(any(BinaryContent.class))).will(invocation -> { + BinaryContent binaryContent = invocation.getArgument(0); + ReflectionTestUtils.setField(binaryContent, "id", binaryContentId); + return binaryContent; + }); + given(binaryContentMapper.toDto(any(BinaryContent.class))).willReturn(binaryContentDto); + + // when + BinaryContentDto result = binaryContentService.create(request); + + // then + assertThat(result).isEqualTo(binaryContentDto); + verify(binaryContentRepository).save(any(BinaryContent.class)); + verify(binaryContentStorage).put(binaryContentId, bytes); + } + + @Test + @DisplayName("바이너리 콘텐츠 조회 성공") + void findBinaryContent_Success() { + // given + given(binaryContentRepository.findById(eq(binaryContentId))).willReturn( + Optional.of(binaryContent)); + given(binaryContentMapper.toDto(eq(binaryContent))).willReturn(binaryContentDto); + + // when + BinaryContentDto result = binaryContentService.find(binaryContentId); + + // then + assertThat(result).isEqualTo(binaryContentDto); + } + + @Test + @DisplayName("존재하지 않는 바이너리 콘텐츠 조회 시 예외 발생") + void findBinaryContent_WithNonExistentId_ThrowsException() { + // given + given(binaryContentRepository.findById(eq(binaryContentId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> binaryContentService.find(binaryContentId)) + .isInstanceOf(BinaryContentNotFoundException.class); + } + + @Test + @DisplayName("여러 ID로 바이너리 콘텐츠 목록 조회 성공") + void findAllByIdIn_Success() { + // given + UUID id1 = UUID.randomUUID(); + UUID id2 = UUID.randomUUID(); + List ids = Arrays.asList(id1, id2); + + BinaryContent content1 = new BinaryContent("file1.jpg", 100L, "image/jpeg"); + ReflectionTestUtils.setField(content1, "id", id1); + + BinaryContent content2 = new BinaryContent("file2.jpg", 200L, "image/png"); + ReflectionTestUtils.setField(content2, "id", id2); + + List contents = Arrays.asList(content1, content2); + + BinaryContentDto dto1 = new BinaryContentDto(id1, "file1.jpg", 100L, "image/jpeg"); + BinaryContentDto dto2 = new BinaryContentDto(id2, "file2.jpg", 200L, "image/png"); + + given(binaryContentRepository.findAllById(eq(ids))).willReturn(contents); + given(binaryContentMapper.toDto(eq(content1))).willReturn(dto1); + given(binaryContentMapper.toDto(eq(content2))).willReturn(dto2); + + // when + List result = binaryContentService.findAllByIdIn(ids); + + // then + assertThat(result).containsExactly(dto1, dto2); + } + + @Test + @DisplayName("바이너리 콘텐츠 삭제 성공") + void deleteBinaryContent_Success() { + // given + given(binaryContentRepository.existsById(binaryContentId)).willReturn(true); + + // when + binaryContentService.delete(binaryContentId); + + // then + verify(binaryContentRepository).deleteById(binaryContentId); + } + + @Test + @DisplayName("존재하지 않는 바이너리 콘텐츠 삭제 시 예외 발생") + void deleteBinaryContent_WithNonExistentId_ThrowsException() { + // given + given(binaryContentRepository.existsById(eq(binaryContentId))).willReturn(false); + + // when & then + assertThatThrownBy(() -> binaryContentService.delete(binaryContentId)) + .isInstanceOf(BinaryContentNotFoundException.class); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/service/basic/BasicChannelServiceTest.java b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicChannelServiceTest.java new file mode 100644 index 000000000..da1dd0ca0 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicChannelServiceTest.java @@ -0,0 +1,228 @@ +package com.sprint.mission.discodeit.service.basic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.sprint.mission.discodeit.dto.data.ChannelDto; +import com.sprint.mission.discodeit.dto.request.PrivateChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelCreateRequest; +import com.sprint.mission.discodeit.dto.request.PublicChannelUpdateRequest; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.ReadStatus; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.channel.ChannelNotFoundException; +import com.sprint.mission.discodeit.exception.channel.PrivateChannelUpdateException; +import com.sprint.mission.discodeit.mapper.ChannelMapper; +import com.sprint.mission.discodeit.repository.ChannelRepository; +import com.sprint.mission.discodeit.repository.MessageRepository; +import com.sprint.mission.discodeit.repository.ReadStatusRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; + +@ExtendWith(MockitoExtension.class) +class BasicChannelServiceTest { + + @Mock + private ChannelRepository channelRepository; + + @Mock + private ReadStatusRepository readStatusRepository; + + @Mock + private MessageRepository messageRepository; + + @Mock + private UserRepository userRepository; + + @Mock + private ChannelMapper channelMapper; + + @InjectMocks + private BasicChannelService channelService; + + private UUID channelId; + private UUID userId; + private String channelName; + private String channelDescription; + private Channel channel; + private ChannelDto channelDto; + private User user; + + @BeforeEach + void setUp() { + channelId = UUID.randomUUID(); + userId = UUID.randomUUID(); + channelName = "testChannel"; + channelDescription = "testDescription"; + + channel = new Channel(ChannelType.PUBLIC, channelName, channelDescription); + ReflectionTestUtils.setField(channel, "id", channelId); + channelDto = new ChannelDto(channelId, ChannelType.PUBLIC, channelName, channelDescription, + List.of(), Instant.now()); + user = new User("testUser", "test@example.com", "password", null); + } + + @Test + @DisplayName("공개 채널 생성 성공") + void createPublicChannel_Success() { + // given + PublicChannelCreateRequest request = new PublicChannelCreateRequest(channelName, + channelDescription); + given(channelMapper.toDto(any(Channel.class))).willReturn(channelDto); + + // when + ChannelDto result = channelService.create(request); + + // then + assertThat(result).isEqualTo(channelDto); + verify(channelRepository).save(any(Channel.class)); + } + + @Test + @DisplayName("비공개 채널 생성 성공") + void createPrivateChannel_Success() { + // given + List participantIds = List.of(userId); + PrivateChannelCreateRequest request = new PrivateChannelCreateRequest(participantIds); + given(userRepository.findAllById(eq(participantIds))).willReturn(List.of(user)); + given(channelMapper.toDto(any(Channel.class))).willReturn(channelDto); + + // when + ChannelDto result = channelService.create(request); + + // then + assertThat(result).isEqualTo(channelDto); + verify(channelRepository).save(any(Channel.class)); + verify(readStatusRepository).saveAll(anyList()); + } + + @Test + @DisplayName("채널 조회 성공") + void findChannel_Success() { + // given + given(channelRepository.findById(eq(channelId))).willReturn(Optional.of(channel)); + given(channelMapper.toDto(any(Channel.class))).willReturn(channelDto); + + // when + ChannelDto result = channelService.find(channelId); + + // then + assertThat(result).isEqualTo(channelDto); + } + + @Test + @DisplayName("존재하지 않는 채널 조회 시 실패") + void findChannel_WithNonExistentId_ThrowsException() { + // given + given(channelRepository.findById(eq(channelId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> channelService.find(channelId)) + .isInstanceOf(ChannelNotFoundException.class); + } + + @Test + @DisplayName("사용자별 채널 목록 조회 성공") + void findAllByUserId_Success() { + // given + List readStatuses = List.of(new ReadStatus(user, channel, Instant.now())); + given(readStatusRepository.findAllByUserId(eq(userId))).willReturn(readStatuses); + given(channelRepository.findAllByTypeOrIdIn(eq(ChannelType.PUBLIC), eq(List.of(channel.getId())))) + .willReturn(List.of(channel)); + given(channelMapper.toDto(any(Channel.class))).willReturn(channelDto); + + // when + List result = channelService.findAllByUserId(userId); + + // then + assertThat(result).containsExactly(channelDto); + } + + @Test + @DisplayName("공개 채널 수정 성공") + void updatePublicChannel_Success() { + // given + String newName = "newChannelName"; + String newDescription = "newDescription"; + PublicChannelUpdateRequest request = new PublicChannelUpdateRequest(newName, newDescription); + + given(channelRepository.findById(eq(channelId))).willReturn(Optional.of(channel)); + given(channelMapper.toDto(any(Channel.class))).willReturn(channelDto); + + // when + ChannelDto result = channelService.update(channelId, request); + + // then + assertThat(result).isEqualTo(channelDto); + } + + @Test + @DisplayName("비공개 채널 수정 시도 시 실패") + void updatePrivateChannel_ThrowsException() { + // given + Channel privateChannel = new Channel(ChannelType.PRIVATE, null, null); + PublicChannelUpdateRequest request = new PublicChannelUpdateRequest("newName", + "newDescription"); + given(channelRepository.findById(eq(channelId))).willReturn(Optional.of(privateChannel)); + + // when & then + assertThatThrownBy(() -> channelService.update(channelId, request)) + .isInstanceOf(PrivateChannelUpdateException.class); + } + + @Test + @DisplayName("존재하지 않는 채널 수정 시도 시 실패") + void updateChannel_WithNonExistentId_ThrowsException() { + // given + PublicChannelUpdateRequest request = new PublicChannelUpdateRequest("newName", + "newDescription"); + given(channelRepository.findById(eq(channelId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> channelService.update(channelId, request)) + .isInstanceOf(ChannelNotFoundException.class); + } + + @Test + @DisplayName("채널 삭제 성공") + void deleteChannel_Success() { + // given + given(channelRepository.existsById(eq(channelId))).willReturn(true); + + // when + channelService.delete(channelId); + + // then + verify(messageRepository).deleteAllByChannelId(eq(channelId)); + verify(readStatusRepository).deleteAllByChannelId(eq(channelId)); + verify(channelRepository).deleteById(eq(channelId)); + } + + @Test + @DisplayName("존재하지 않는 채널 삭제 시도 시 실패") + void deleteChannel_WithNonExistentId_ThrowsException() { + // given + given(channelRepository.existsById(eq(channelId))).willReturn(false); + + // when & then + assertThatThrownBy(() -> channelService.delete(channelId)) + .isInstanceOf(ChannelNotFoundException.class); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/service/basic/BasicMessageServiceTest.java b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicMessageServiceTest.java new file mode 100644 index 000000000..08e25cb60 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicMessageServiceTest.java @@ -0,0 +1,370 @@ +package com.sprint.mission.discodeit.service.basic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.dto.data.MessageDto; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.BinaryContentCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageCreateRequest; +import com.sprint.mission.discodeit.dto.request.MessageUpdateRequest; +import com.sprint.mission.discodeit.dto.response.PageResponse; +import com.sprint.mission.discodeit.entity.BinaryContent; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.ChannelType; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.channel.ChannelNotFoundException; +import com.sprint.mission.discodeit.exception.message.MessageNotFoundException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.MessageMapper; +import com.sprint.mission.discodeit.mapper.PageResponseMapper; +import com.sprint.mission.discodeit.repository.BinaryContentRepository; +import com.sprint.mission.discodeit.repository.ChannelRepository; +import com.sprint.mission.discodeit.repository.MessageRepository; +import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.SliceImpl; +import org.springframework.test.util.ReflectionTestUtils; + +@ExtendWith(MockitoExtension.class) +class BasicMessageServiceTest { + + @Mock + private MessageRepository messageRepository; + + @Mock + private ChannelRepository channelRepository; + + @Mock + private UserRepository userRepository; + + @Mock + private MessageMapper messageMapper; + + @Mock + private BinaryContentStorage binaryContentStorage; + + @Mock + private BinaryContentRepository binaryContentRepository; + + @Mock + private PageResponseMapper pageResponseMapper; + + @InjectMocks + private BasicMessageService messageService; + + private UUID messageId; + private UUID channelId; + private UUID authorId; + private String content; + private Message message; + private MessageDto messageDto; + private Channel channel; + private User author; + private BinaryContent attachment; + private BinaryContentDto attachmentDto; + + @BeforeEach + void setUp() { + messageId = UUID.randomUUID(); + channelId = UUID.randomUUID(); + authorId = UUID.randomUUID(); + content = "test message"; + + channel = new Channel(ChannelType.PUBLIC, "testChannel", "testDescription"); + ReflectionTestUtils.setField(channel, "id", channelId); + + author = new User("testUser", "test@example.com", "password", null); + ReflectionTestUtils.setField(author, "id", authorId); + + attachment = new BinaryContent("test.txt", 100L, "text/plain"); + ReflectionTestUtils.setField(attachment, "id", UUID.randomUUID()); + attachmentDto = new BinaryContentDto(attachment.getId(), "test.txt", 100L, "text/plain"); + + message = new Message(content, channel, author, List.of(attachment)); + ReflectionTestUtils.setField(message, "id", messageId); + + messageDto = new MessageDto( + messageId, + Instant.now(), + Instant.now(), + content, + channelId, + new UserDto(authorId, "testUser", "test@example.com", null, true, Role.USER), + List.of(attachmentDto) + ); + } + + @Test + @DisplayName("메시지 생성 성공") + void createMessage_Success() { + // given + MessageCreateRequest request = new MessageCreateRequest(content, channelId, authorId); + BinaryContentCreateRequest attachmentRequest = new BinaryContentCreateRequest("test.txt", + "text/plain", new byte[100]); + List attachmentRequests = List.of(attachmentRequest); + + given(channelRepository.findById(eq(channelId))).willReturn(Optional.of(channel)); + given(userRepository.findById(eq(authorId))).willReturn(Optional.of(author)); + given(binaryContentRepository.save(any(BinaryContent.class))).will(invocation -> { + BinaryContent binaryContent = invocation.getArgument(0); + ReflectionTestUtils.setField(binaryContent, "id", attachment.getId()); + return attachment; + }); + given(messageRepository.save(any(Message.class))).willReturn(message); + given(messageMapper.toDto(any(Message.class))).willReturn(messageDto); + + // when + MessageDto result = messageService.create(request, attachmentRequests); + + // then + assertThat(result).isEqualTo(messageDto); + verify(messageRepository).save(any(Message.class)); + verify(binaryContentStorage).put(eq(attachment.getId()), any(byte[].class)); + } + + @Test + @DisplayName("존재하지 않는 채널에 메시지 생성 시도 시 실패") + void createMessage_WithNonExistentChannel_ThrowsException() { + // given + MessageCreateRequest request = new MessageCreateRequest(content, channelId, authorId); + given(channelRepository.findById(eq(channelId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> messageService.create(request, List.of())) + .isInstanceOf(ChannelNotFoundException.class); + } + + @Test + @DisplayName("존재하지 않는 작성자로 메시지 생성 시도 시 실패") + void createMessage_WithNonExistentAuthor_ThrowsException() { + // given + MessageCreateRequest request = new MessageCreateRequest(content, channelId, authorId); + given(channelRepository.findById(eq(channelId))).willReturn(Optional.of(channel)); + given(userRepository.findById(eq(authorId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> messageService.create(request, List.of())) + .isInstanceOf(UserNotFoundException.class); + } + + @Test + @DisplayName("메시지 조회 성공") + void findMessage_Success() { + // given + given(messageRepository.findById(eq(messageId))).willReturn(Optional.of(message)); + given(messageMapper.toDto(eq(message))).willReturn(messageDto); + + // when + MessageDto result = messageService.find(messageId); + + // then + assertThat(result).isEqualTo(messageDto); + } + + @Test + @DisplayName("존재하지 않는 메시지 조회 시 실패") + void findMessage_WithNonExistentId_ThrowsException() { + // given + given(messageRepository.findById(eq(messageId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> messageService.find(messageId)) + .isInstanceOf(MessageNotFoundException.class); + } + + @Test + @DisplayName("채널별 메시지 목록 조회 성공") + void findAllByChannelId_Success() { + // given + int pageSize = 2; // 페이지 크기를 2로 설정 + Instant createdAt = Instant.now(); + Pageable pageable = PageRequest.of(0, pageSize); + + // 여러 메시지 생성 (페이지 사이즈보다 많게) + Message message1 = new Message(content + "1", channel, author, List.of(attachment)); + Message message2 = new Message(content + "2", channel, author, List.of(attachment)); + Message message3 = new Message(content + "3", channel, author, List.of(attachment)); + + ReflectionTestUtils.setField(message1, "id", UUID.randomUUID()); + ReflectionTestUtils.setField(message2, "id", UUID.randomUUID()); + ReflectionTestUtils.setField(message3, "id", UUID.randomUUID()); + + // 각 메시지에 해당하는 DTO 생성 + Instant message1CreatedAt = Instant.now().minusSeconds(30); + Instant message2CreatedAt = Instant.now().minusSeconds(20); + Instant message3CreatedAt = Instant.now().minusSeconds(10); + + ReflectionTestUtils.setField(message1, "createdAt", message1CreatedAt); + ReflectionTestUtils.setField(message2, "createdAt", message2CreatedAt); + ReflectionTestUtils.setField(message3, "createdAt", message3CreatedAt); + + MessageDto messageDto1 = new MessageDto( + message1.getId(), + message1CreatedAt, + message1CreatedAt, + content + "1", + channelId, + new UserDto(authorId, "testUser", "test@example.com", null, true, Role.USER), + List.of(attachmentDto) + ); + + MessageDto messageDto2 = new MessageDto( + message2.getId(), + message2CreatedAt, + message2CreatedAt, + content + "2", + channelId, + new UserDto(authorId, "testUser", "test@example.com", null, true, Role.USER), + List.of(attachmentDto) + ); + + // 첫 페이지 결과 세팅 (2개 메시지) + List firstPageMessages = List.of(message1, message2); + List firstPageDtos = List.of(messageDto1, messageDto2); + + // 첫 페이지는 다음 페이지가 있고, 커서는 message2의 생성 시간이어야 함 + SliceImpl firstPageSlice = new SliceImpl<>(firstPageMessages, pageable, true); + PageResponse firstPageResponse = new PageResponse<>( + firstPageDtos, + message2CreatedAt, + pageSize, + true, + null + ); + + // 모의 객체 설정 + given( + messageRepository.findAllByChannelIdWithAuthor(eq(channelId), eq(createdAt), eq(pageable))) + .willReturn(firstPageSlice); + given(messageMapper.toDto(eq(message1))).willReturn(messageDto1); + given(messageMapper.toDto(eq(message2))).willReturn(messageDto2); + given(pageResponseMapper.fromSlice(any(), eq(message2CreatedAt))) + .willReturn(firstPageResponse); + + // when + PageResponse result = messageService.findAllByChannelId(channelId, createdAt, + pageable); + + // then + assertThat(result).isEqualTo(firstPageResponse); + assertThat(result.content()).hasSize(pageSize); + assertThat(result.hasNext()).isTrue(); + assertThat(result.nextCursor()).isEqualTo(message2CreatedAt); + + // 두 번째 페이지 테스트 + // given + List secondPageMessages = List.of(message3); + MessageDto messageDto3 = new MessageDto( + message3.getId(), + message3CreatedAt, + message3CreatedAt, + content + "3", + channelId, + new UserDto(authorId, "testUser", "test@example.com", null, true, Role.USER), + List.of(attachmentDto) + ); + List secondPageDtos = List.of(messageDto3); + + // 두 번째 페이지는 다음 페이지가 없음 + SliceImpl secondPageSlice = new SliceImpl<>(secondPageMessages, pageable, false); + PageResponse secondPageResponse = new PageResponse<>( + secondPageDtos, + message3CreatedAt, + pageSize, + false, + null + ); + + // 두 번째 페이지 모의 객체 설정 + given(messageRepository.findAllByChannelIdWithAuthor(eq(channelId), eq(message2CreatedAt), + eq(pageable))) + .willReturn(secondPageSlice); + given(messageMapper.toDto(eq(message3))).willReturn(messageDto3); + given(pageResponseMapper.fromSlice(any(), eq(message3CreatedAt))) + .willReturn(secondPageResponse); + + // when - 두 번째 페이지 요청 (첫 페이지의 커서 사용) + PageResponse secondResult = messageService.findAllByChannelId(channelId, + message2CreatedAt, + pageable); + + // then - 두 번째 페이지 검증 + assertThat(secondResult).isEqualTo(secondPageResponse); + assertThat(secondResult.content()).hasSize(1); // 마지막 페이지는 항목 1개만 있음 + assertThat(secondResult.hasNext()).isFalse(); // 더 이상 다음 페이지 없음 + } + + @Test + @DisplayName("메시지 수정 성공") + void updateMessage_Success() { + // given + String newContent = "updated content"; + MessageUpdateRequest request = new MessageUpdateRequest(newContent); + + given(messageRepository.findById(eq(messageId))).willReturn(Optional.of(message)); + given(messageMapper.toDto(eq(message))).willReturn(messageDto); + + // when + MessageDto result = messageService.update(messageId, request); + + // then + assertThat(result).isEqualTo(messageDto); + } + + @Test + @DisplayName("존재하지 않는 메시지 수정 시도 시 실패") + void updateMessage_WithNonExistentId_ThrowsException() { + // given + MessageUpdateRequest request = new MessageUpdateRequest("new content"); + given(messageRepository.findById(eq(messageId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> messageService.update(messageId, request)) + .isInstanceOf(MessageNotFoundException.class); + } + + @Test + @DisplayName("메시지 삭제 성공") + void deleteMessage_Success() { + // given + given(messageRepository.existsById(eq(messageId))).willReturn(true); + + // when + messageService.delete(messageId); + + // then + verify(messageRepository).deleteById(eq(messageId)); + } + + @Test + @DisplayName("존재하지 않는 메시지 삭제 시도 시 실패") + void deleteMessage_WithNonExistentId_ThrowsException() { + // given + given(messageRepository.existsById(eq(messageId))).willReturn(false); + + // when & then + assertThatThrownBy(() -> messageService.delete(messageId)) + .isInstanceOf(MessageNotFoundException.class); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserServiceTest.java b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserServiceTest.java new file mode 100644 index 000000000..1dd89c512 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserServiceTest.java @@ -0,0 +1,188 @@ +package com.sprint.mission.discodeit.service.basic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import com.sprint.mission.discodeit.entity.Role; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.user.UserAlreadyExistsException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.UserMapper; +import com.sprint.mission.discodeit.repository.UserRepository; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.util.ReflectionTestUtils; + +@ExtendWith(MockitoExtension.class) +class BasicUserServiceTest { + + @Mock + private UserRepository userRepository; + + @Mock + private UserMapper userMapper; + @Mock + private PasswordEncoder passwordEncoder; + + @InjectMocks + private BasicUserService userService; + + private UUID userId; + private String username; + private String email; + private String password; + private User user; + private UserDto userDto; + + @BeforeEach + void setUp() { + userId = UUID.randomUUID(); + username = "testUser"; + email = "test@example.com"; + password = "password123"; + + user = new User(username, email, password, null); + ReflectionTestUtils.setField(user, "id", userId); + userDto = new UserDto(userId, username, email, null, true, Role.USER); + } + + @Test + @DisplayName("사용자 생성 성공") + void createUser_Success() { + // given + UserCreateRequest request = new UserCreateRequest(username, email, password); + given(userRepository.existsByEmail(eq(email))).willReturn(false); + given(userRepository.existsByUsername(eq(username))).willReturn(false); + given(userMapper.toDto(any(User.class))).willReturn(userDto); + + // when + UserDto result = userService.create(request, Optional.empty()); + + // then + assertThat(result).isEqualTo(userDto); + verify(userRepository).save(any(User.class)); + } + + @Test + @DisplayName("이미 존재하는 이메일로 사용자 생성 시도 시 실패") + void createUser_WithExistingEmail_ThrowsException() { + // given + UserCreateRequest request = new UserCreateRequest(username, email, password); + given(userRepository.existsByEmail(eq(email))).willReturn(true); + + // when & then + assertThatThrownBy(() -> userService.create(request, Optional.empty())) + .isInstanceOf(UserAlreadyExistsException.class); + } + + @Test + @DisplayName("이미 존재하는 사용자명으로 사용자 생성 시도 시 실패") + void createUser_WithExistingUsername_ThrowsException() { + // given + UserCreateRequest request = new UserCreateRequest(username, email, password); + given(userRepository.existsByEmail(eq(email))).willReturn(false); + given(userRepository.existsByUsername(eq(username))).willReturn(true); + + // when & then + assertThatThrownBy(() -> userService.create(request, Optional.empty())) + .isInstanceOf(UserAlreadyExistsException.class); + } + + @Test + @DisplayName("사용자 조회 성공") + void findUser_Success() { + // given + given(userRepository.findById(eq(userId))).willReturn(Optional.of(user)); + given(userMapper.toDto(any(User.class))).willReturn(userDto); + + // when + UserDto result = userService.find(userId); + + // then + assertThat(result).isEqualTo(userDto); + } + + @Test + @DisplayName("존재하지 않는 사용자 조회 시 실패") + void findUser_WithNonExistentId_ThrowsException() { + // given + given(userRepository.findById(eq(userId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> userService.find(userId)) + .isInstanceOf(UserNotFoundException.class); + } + + @Test + @DisplayName("사용자 수정 성공") + void updateUser_Success() { + // given + String newUsername = "newUsername"; + String newEmail = "new@example.com"; + String newPassword = "newPassword"; + UserUpdateRequest request = new UserUpdateRequest(newUsername, newEmail, newPassword); + + given(userRepository.findById(eq(userId))).willReturn(Optional.of(user)); + given(userRepository.existsByEmail(eq(newEmail))).willReturn(false); + given(userRepository.existsByUsername(eq(newUsername))).willReturn(false); + given(userMapper.toDto(any(User.class))).willReturn(userDto); + + // when + UserDto result = userService.update(userId, request, Optional.empty()); + + // then + assertThat(result).isEqualTo(userDto); + } + + @Test + @DisplayName("존재하지 않는 사용자 수정 시도 시 실패") + void updateUser_WithNonExistentId_ThrowsException() { + // given + UserUpdateRequest request = new UserUpdateRequest("newUsername", "new@example.com", + "newPassword"); + given(userRepository.findById(eq(userId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> userService.update(userId, request, Optional.empty())) + .isInstanceOf(UserNotFoundException.class); + } + + @Test + @DisplayName("사용자 삭제 성공") + void deleteUser_Success() { + // given + given(userRepository.existsById(eq(userId))).willReturn(true); + + // when + userService.delete(userId); + + // then + verify(userRepository).deleteById(eq(userId)); + } + + @Test + @DisplayName("존재하지 않는 사용자 삭제 시도 시 실패") + void deleteUser_WithNonExistentId_ThrowsException() { + // given + given(userRepository.existsById(eq(userId))).willReturn(false); + + // when & then + assertThatThrownBy(() -> userService.delete(userId)) + .isInstanceOf(UserNotFoundException.class); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/storage/s3/AWSS3Test.java b/src/test/java/com/sprint/mission/discodeit/storage/s3/AWSS3Test.java new file mode 100644 index 000000000..9f016686a --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/storage/s3/AWSS3Test.java @@ -0,0 +1,174 @@ +package com.sprint.mission.discodeit.storage.s3; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.time.Duration; +import java.util.Properties; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; +import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; + +@Disabled +@Slf4j +@DisplayName("S3 API 테스트") +public class AWSS3Test { + + private static String accessKey; + private static String secretKey; + private static String region; + private static String bucket; + private S3Client s3Client; + private S3Presigner presigner; + private String testKey; + + @BeforeAll + static void loadEnv() throws IOException { + Properties props = new Properties(); + try (FileInputStream fis = new FileInputStream(".env")) { + props.load(fis); + } + + accessKey = props.getProperty("AWS_S3_ACCESS_KEY"); + secretKey = props.getProperty("AWS_S3_SECRET_KEY"); + region = props.getProperty("AWS_S3_REGION"); + bucket = props.getProperty("AWS_S3_BUCKET"); + + if (accessKey == null || secretKey == null || region == null || bucket == null) { + throw new IllegalStateException("AWS S3 설정이 .env 파일에 올바르게 정의되지 않았습니다."); + } + } + + @BeforeEach + void setUp() { + s3Client = S3Client.builder() + .region(Region.of(region)) + .credentialsProvider( + StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey) + ) + ) + .build(); + + presigner = S3Presigner.builder() + .region(Region.of(region)) + .credentialsProvider( + StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey) + ) + ) + .build(); + + testKey = "test-" + UUID.randomUUID().toString(); + } + + @Test + @DisplayName("S3에 파일을 업로드한다") + void uploadToS3() { + String content = "Hello from .env via Properties!"; + + try { + PutObjectRequest request = PutObjectRequest.builder() + .bucket(bucket) + .key(testKey) + .contentType("text/plain") + .build(); + + s3Client.putObject(request, RequestBody.fromString(content)); + log.info("파일 업로드 성공: {}", testKey); + } catch (S3Exception e) { + log.error("파일 업로드 실패: {}", e.getMessage()); + throw e; + } + } + + @Test + @DisplayName("S3에서 파일을 다운로드한다") + void downloadFromS3() { + // 테스트를 위한 파일 먼저 업로드 + String content = "Test content for download"; + PutObjectRequest uploadRequest = PutObjectRequest.builder() + .bucket(bucket) + .key(testKey) + .contentType("text/plain") + .build(); + s3Client.putObject(uploadRequest, RequestBody.fromString(content)); + + try { + GetObjectRequest request = GetObjectRequest.builder() + .bucket(bucket) + .key(testKey) + .build(); + + String downloadedContent = s3Client.getObjectAsBytes(request).asUtf8String(); + log.info("다운로드된 파일 내용: {}", downloadedContent); + } catch (S3Exception e) { + log.error("파일 다운로드 실패: {}", e.getMessage()); + throw e; + } + } + + @Test + @DisplayName("S3 파일에 대한 Presigned URL을 생성한다") + void generatePresignedUrl() { + // 테스트를 위한 파일 먼저 업로드 + String content = "Test content for presigned URL"; + PutObjectRequest uploadRequest = PutObjectRequest.builder() + .bucket(bucket) + .key(testKey) + .contentType("text/plain") + .build(); + s3Client.putObject(uploadRequest, RequestBody.fromString(content)); + + try { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucket) + .key(testKey) + .build(); + + GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder() + .signatureDuration(Duration.ofMinutes(10)) + .getObjectRequest(getObjectRequest) + .build(); + + PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(presignRequest); + URL url = presignedRequest.url(); + + log.info("생성된 Presigned URL: {}", url); + } catch (S3Exception e) { + log.error("Presigned URL 생성 실패: {}", e.getMessage()); + throw e; + } + } + + @AfterEach + void cleanup() { + try { + DeleteObjectRequest request = DeleteObjectRequest.builder() + .bucket(bucket) + .key(testKey) + .build(); + s3Client.deleteObject(request); + log.info("테스트 파일 정리 완료: {}", testKey); + } catch (S3Exception e) { + log.error("테스트 파일 정리 실패: {}", e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorageTest.java b/src/test/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorageTest.java new file mode 100644 index 000000000..b758d402f --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorageTest.java @@ -0,0 +1,147 @@ +package com.sprint.mission.discodeit.storage.s3; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import java.io.IOException; +import java.io.InputStream; +import java.util.NoSuchElementException; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.NoSuchKeyException; + +@Disabled +@SpringBootTest +@ActiveProfiles("test") +@DisplayName("S3BinaryContentStorage 테스트") +class S3BinaryContentStorageTest { + + @Autowired + private S3BinaryContentStorage s3BinaryContentStorage; + + @Value("${discodeit.storage.s3.bucket}") + private String bucket; + + @Value("${discodeit.storage.s3.access-key}") + private String accessKey; + + @Value("${discodeit.storage.s3.secret-key}") + private String secretKey; + + @Value("${discodeit.storage.s3.region}") + private String region; + + private final UUID testId = UUID.randomUUID(); + private final byte[] testData = "테스트 데이터".getBytes(); + + @BeforeEach + void setUp() { + // 테스트 준비 작업 + // 실제 S3BinaryContentStorage는 스프링이 의존성 주입으로 제공 + } + + @AfterEach + void tearDown() { + // 테스트 종료 후 생성된 S3 객체 삭제 + try { + // S3 클라이언트 생성 + S3Client s3Client = S3Client.builder() + .region(Region.of(region)) + .credentialsProvider( + StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey) + ) + ) + .build(); + + // 테스트에서 생성한 객체 삭제 + DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder() + .bucket(bucket) + .key(testId.toString()) + .build(); + + s3Client.deleteObject(deleteRequest); + System.out.println("테스트 객체 삭제 완료: " + testId); + } catch (NoSuchKeyException e) { + // 객체가 이미 없는 경우는 무시 + System.out.println("삭제할 객체가 없음: " + testId); + } catch (Exception e) { + // 정리 실패 시 로그만 남기고 테스트는 실패로 처리하지 않음 + System.err.println("테스트 객체 정리 실패: " + e.getMessage()); + } + } + + @Test + @DisplayName("S3에 파일 업로드 성공 테스트") + void put_success() { + // when + UUID resultId = s3BinaryContentStorage.put(testId, testData); + + // then + assertThat(resultId).isEqualTo(testId); + } + + @Test + @DisplayName("S3에서 파일 다운로드 테스트") + void get_success() throws IOException { + // given + s3BinaryContentStorage.put(testId, testData); + + // when + InputStream result = s3BinaryContentStorage.get(testId); + + // then + assertNotNull(result); + + // 내용 검증 + byte[] resultBytes = result.readAllBytes(); + assertThat(resultBytes).isEqualTo(testData); + } + + @Test + @DisplayName("존재하지 않는 파일 조회 시 예외 발생 테스트") + void get_notFound() { + // when & then + assertThatThrownBy(() -> s3BinaryContentStorage.get(UUID.randomUUID())) + .isInstanceOf(NoSuchElementException.class); + } + + @Test + @DisplayName("Presigned URL 생성 테스트") + void download_success() { + // given + s3BinaryContentStorage.put(testId, testData); + BinaryContentDto dto = new BinaryContentDto( + testId, "test.txt", (long) testData.length, "text/plain" + ); + + // when + ResponseEntity response = s3BinaryContentStorage.download(dto); + + // then + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(response.getHeaders().get(HttpHeaders.LOCATION)).isNotNull(); + + String location = response.getHeaders().getFirst(HttpHeaders.LOCATION); + assertThat(location).contains(bucket); + assertThat(location).contains(testId.toString()); + } +} \ No newline at end of file diff --git a/src/test/resources/application-test.yaml b/src/test/resources/application-test.yaml new file mode 100644 index 000000000..12bc7a717 --- /dev/null +++ b/src/test/resources/application-test.yaml @@ -0,0 +1,32 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb;MODE=PostgreSQL + driver-class-name: org.h2.Driver + username: sa + password: + jpa: + hibernate: + ddl-auto: create + show-sql: true + properties: + hibernate: + format_sql: true + sql: + init: + mode: never + +discodeit: + jwt: + access-token: + secret: test-access-token-secret-key-for-jwt-token-generation-and-validation-must-be-long-enough-for-testing + expiration-ms: 1800000 # 30 minutes + refresh-token: + secret: test-refresh-token-secret-key-for-jwt-token-generation-and-validation-must-be-different-and-long-for-testing + expiration-ms: 604800000 # 7 days + +logging: + level: + com.sprint.mission.discodeit: debug + org.hibernate.SQL: debug + org.hibernate.orm.jdbc.bind: trace + org.springframework.security: trace \ No newline at end of file