diff --git a/.gitignore b/.gitignore index cd26dd7e0..f14dfb825 100644 --- a/.gitignore +++ b/.gitignore @@ -3,14 +3,9 @@ build/ !gradle/wrapper/gradle-wrapper.jar !**/src/main/**/build/ !**/src/test/**/build/ -.discodeit/ ### IntelliJ IDEA ### .idea -.idea/modules.xml -.idea/jarRepositories.xml -.idea/compiler.xml -.idea/libraries/ *.iws *.iml *.ipr @@ -41,4 +36,15 @@ bin/ .vscode/ ### Mac OS ### -.DS_Store \ No newline at end of file +.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 index 696539264..42c5f0023 100644 --- a/HELP.md +++ b/HELP.md @@ -1,16 +1,14 @@ # 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.5.4/gradle-plugin) -* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.4/gradle-plugin/packaging-oci-image.html) -* [Spring Web](https://docs.spring.io/spring-boot/3.5.4/reference/web/servlet.html) +* [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/) @@ -18,7 +16,6 @@ The following guides illustrate how to use some features concretely: * [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..e3f11b5c0 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# 5-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/api-docs_1.2.json b/api-docs_1.2.json new file mode 100644 index 000000000..7253644c9 --- /dev/null +++ b/api-docs_1.2.json @@ -0,0 +1,1278 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Discodeit API 문서", + "description": "Discodeit 프로젝트의 Swagger API 문서입니다.", + "version": "1.2" + }, + "servers": [ + { + "url": "http://localhost:8080", + "description": "로컬 서버" + } + ], + "tags": [ + { + "name": "Channel", + "description": "Channel API" + }, + { + "name": "ReadStatus", + "description": "Message 읽음 상태 API" + }, + { + "name": "Message", + "description": "Message API" + }, + { + "name": "User", + "description": "User API" + }, + { + "name": "BinaryContent", + "description": "첨부 파일 API" + }, + { + "name": "Auth", + "description": "인증 API" + } + ], + "paths": { + "/api/users": { + "get": { + "tags": [ + "User" + ], + "summary": "전체 User 목록 조회", + "operationId": "findAll", + "responses": { + "200": { + "description": "User 목록 조회 성공", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserDto" + } + } + } + } + } + } + }, + "post": { + "tags": [ + "User" + ], + "summary": "User 등록", + "operationId": "create", + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "userCreateRequest": { + "$ref": "#/components/schemas/UserCreateRequest" + }, + "profile": { + "type": "string", + "format": "binary", + "description": "User 프로필 이미지" + } + }, + "required": [ + "userCreateRequest" + ] + } + } + } + }, + "responses": { + "201": { + "description": "User가 성공적으로 생성됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/UserDto" + } + } + } + }, + "400": { + "description": "같은 email 또는 username를 사용하는 User가 이미 존재함", + "content": { + "*/*": { + "example": "User with email {email} already exists" + } + } + } + } + } + }, + "/api/readStatuses": { + "get": { + "tags": [ + "ReadStatus" + ], + "summary": "User의 Message 읽음 상태 목록 조회", + "operationId": "findAllByUserId", + "parameters": [ + { + "name": "userId", + "in": "query", + "description": "조회할 User ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Message 읽음 상태 목록 조회 성공", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReadStatusDto" + } + } + } + } + } + } + }, + "post": { + "tags": [ + "ReadStatus" + ], + "summary": "Message 읽음 상태 생성", + "operationId": "create_1", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadStatusCreateRequest" + } + } + }, + "required": true + }, + "responses": { + "400": { + "description": "이미 읽음 상태가 존재함", + "content": { + "*/*": { + "example": "ReadStatus with userId {userId} and channelId {channelId} already exists" + } + } + }, + "201": { + "description": "Message 읽음 상태가 성공적으로 생성됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/ReadStatusDto" + } + } + } + }, + "404": { + "description": "Channel 또는 User를 찾을 수 없음", + "content": { + "*/*": { + "example": "Channel | User with id {channelId | userId} not found" + } + } + } + } + } + }, + "/api/messages": { + "get": { + "tags": [ + "Message" + ], + "summary": "Channel의 Message 목록 조회", + "operationId": "findAllByChannelId", + "parameters": [ + { + "name": "channelId", + "in": "query", + "description": "조회할 Channel ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "cursor", + "in": "query", + "description": "페이징 커서 정보", + "required": true, + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "pageable", + "in": "query", + "description": "페이징 정보", + "required": true, + "schema": { + "$ref": "#/components/schemas/Pageable" + }, + "example": { + "size": 50, + "sort": "createdAt,desc" + } + } + ], + "responses": { + "200": { + "description": "Message 목록 조회 성공", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/PageResponse" + } + } + } + } + } + }, + "post": { + "tags": [ + "Message" + ], + "summary": "Message 생성", + "operationId": "create_2", + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "messageCreateRequest": { + "$ref": "#/components/schemas/MessageCreateRequest" + }, + "attachments": { + "type": "array", + "description": "Message 첨부 파일들", + "items": { + "type": "string", + "format": "binary" + } + } + }, + "required": [ + "messageCreateRequest" + ] + } + } + } + }, + "responses": { + "201": { + "description": "Message가 성공적으로 생성됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/MessageDto" + } + } + } + }, + "404": { + "description": "Channel 또는 User를 찾을 수 없음", + "content": { + "*/*": { + "example": "Channel | Author with id {channelId | authorId} not found" + } + } + } + } + } + }, + "/api/channels/public": { + "post": { + "tags": [ + "Channel" + ], + "summary": "Public Channel 생성", + "operationId": "create_3", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicChannelCreateRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Public Channel이 성공적으로 생성됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/ChannelDto" + } + } + } + } + } + } + }, + "/api/channels/private": { + "post": { + "tags": [ + "Channel" + ], + "summary": "Private Channel 생성", + "operationId": "create_4", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PrivateChannelCreateRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Private Channel이 성공적으로 생성됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/ChannelDto" + } + } + } + } + } + } + }, + "/api/auth/login": { + "post": { + "tags": [ + "Auth" + ], + "summary": "로그인", + "operationId": "login", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "로그인 성공", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/UserDto" + } + } + } + }, + "404": { + "description": "사용자를 찾을 수 없음", + "content": { + "*/*": { + "example": "User with username {username} not found" + } + } + }, + "400": { + "description": "비밀번호가 일치하지 않음", + "content": { + "*/*": { + "example": "Wrong password" + } + } + } + } + } + }, + "/api/users/{userId}": { + "delete": { + "tags": [ + "User" + ], + "summary": "User 삭제", + "operationId": "delete", + "parameters": [ + { + "name": "userId", + "in": "path", + "description": "삭제할 User ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "404": { + "description": "User를 찾을 수 없음", + "content": { + "*/*": { + "example": "User with id {id} not found" + } + } + }, + "204": { + "description": "User가 성공적으로 삭제됨" + } + } + }, + "patch": { + "tags": [ + "User" + ], + "summary": "User 정보 수정", + "operationId": "update", + "parameters": [ + { + "name": "userId", + "in": "path", + "description": "수정할 User ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "userUpdateRequest": { + "$ref": "#/components/schemas/UserUpdateRequest" + }, + "profile": { + "type": "string", + "format": "binary", + "description": "수정할 User 프로필 이미지" + } + }, + "required": [ + "userUpdateRequest" + ] + } + } + } + }, + "responses": { + "400": { + "description": "같은 email 또는 username를 사용하는 User가 이미 존재함", + "content": { + "*/*": { + "example": "user with email {newEmail} already exists" + } + } + }, + "200": { + "description": "User 정보가 성공적으로 수정됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/UserDto" + } + } + } + }, + "404": { + "description": "User를 찾을 수 없음", + "content": { + "*/*": { + "example": "User with id {userId} not found" + } + } + } + } + } + }, + "/api/users/{userId}/userStatus": { + "patch": { + "tags": [ + "User" + ], + "summary": "User 온라인 상태 업데이트", + "operationId": "updateUserStatusByUserId", + "parameters": [ + { + "name": "userId", + "in": "path", + "description": "상태를 변경할 User ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserStatusUpdateRequest" + } + } + }, + "required": true + }, + "responses": { + "404": { + "description": "해당 User의 UserStatus를 찾을 수 없음", + "content": { + "*/*": { + "example": "UserStatus with userId {userId} not found" + } + } + }, + "200": { + "description": "User 온라인 상태가 성공적으로 업데이트됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/UserStatusDto" + } + } + } + } + } + } + }, + "/api/readStatuses/{readStatusId}": { + "patch": { + "tags": [ + "ReadStatus" + ], + "summary": "Message 읽음 상태 수정", + "operationId": "update_1", + "parameters": [ + { + "name": "readStatusId", + "in": "path", + "description": "수정할 읽음 상태 ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadStatusUpdateRequest" + } + } + }, + "required": true + }, + "responses": { + "404": { + "description": "Message 읽음 상태를 찾을 수 없음", + "content": { + "*/*": { + "example": "ReadStatus with id {readStatusId} not found" + } + } + }, + "200": { + "description": "Message 읽음 상태가 성공적으로 수정됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/ReadStatusDto" + } + } + } + } + } + } + }, + "/api/messages/{messageId}": { + "delete": { + "tags": [ + "Message" + ], + "summary": "Message 삭제", + "operationId": "delete_1", + "parameters": [ + { + "name": "messageId", + "in": "path", + "description": "삭제할 Message ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "204": { + "description": "Message가 성공적으로 삭제됨" + }, + "404": { + "description": "Message를 찾을 수 없음", + "content": { + "*/*": { + "example": "Message with id {messageId} not found" + } + } + } + } + }, + "patch": { + "tags": [ + "Message" + ], + "summary": "Message 내용 수정", + "operationId": "update_2", + "parameters": [ + { + "name": "messageId", + "in": "path", + "description": "수정할 Message ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageUpdateRequest" + } + } + }, + "required": true + }, + "responses": { + "404": { + "description": "Message를 찾을 수 없음", + "content": { + "*/*": { + "example": "Message with id {messageId} not found" + } + } + }, + "200": { + "description": "Message가 성공적으로 수정됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/MessageDto" + } + } + } + } + } + } + }, + "/api/channels/{channelId}": { + "delete": { + "tags": [ + "Channel" + ], + "summary": "Channel 삭제", + "operationId": "delete_2", + "parameters": [ + { + "name": "channelId", + "in": "path", + "description": "삭제할 Channel ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "404": { + "description": "Channel을 찾을 수 없음", + "content": { + "*/*": { + "example": "Channel with id {channelId} not found" + } + } + }, + "204": { + "description": "Channel이 성공적으로 삭제됨" + } + } + }, + "patch": { + "tags": [ + "Channel" + ], + "summary": "Channel 정보 수정", + "operationId": "update_3", + "parameters": [ + { + "name": "channelId", + "in": "path", + "description": "수정할 Channel ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicChannelUpdateRequest" + } + } + }, + "required": true + }, + "responses": { + "404": { + "description": "Channel을 찾을 수 없음", + "content": { + "*/*": { + "example": "Channel with id {channelId} not found" + } + } + }, + "400": { + "description": "Private Channel은 수정할 수 없음", + "content": { + "*/*": { + "example": "Private channel cannot be updated" + } + } + }, + "200": { + "description": "Channel 정보가 성공적으로 수정됨", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/ChannelDto" + } + } + } + } + } + } + }, + "/api/channels": { + "get": { + "tags": [ + "Channel" + ], + "summary": "User가 참여 중인 Channel 목록 조회", + "operationId": "findAll_1", + "parameters": [ + { + "name": "userId", + "in": "query", + "description": "조회할 User ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Channel 목록 조회 성공", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChannelDto" + } + } + } + } + } + } + } + }, + "/api/binaryContents": { + "get": { + "tags": [ + "BinaryContent" + ], + "summary": "여러 첨부 파일 조회", + "operationId": "findAllByIdIn", + "parameters": [ + { + "name": "binaryContentIds", + "in": "query", + "description": "조회할 첨부 파일 ID 목록", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + } + ], + "responses": { + "200": { + "description": "첨부 파일 목록 조회 성공", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BinaryContentDto" + } + } + } + } + } + } + } + }, + "/api/binaryContents/{binaryContentId}": { + "get": { + "tags": [ + "BinaryContent" + ], + "summary": "첨부 파일 조회", + "operationId": "find", + "parameters": [ + { + "name": "binaryContentId", + "in": "path", + "description": "조회할 첨부 파일 ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "첨부 파일 조회 성공", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/BinaryContentDto" + } + } + } + }, + "404": { + "description": "첨부 파일을 찾을 수 없음", + "content": { + "*/*": { + "example": "BinaryContent with id {binaryContentId} not found" + } + } + } + } + } + }, + "/api/binaryContents/{binaryContentId}/download": { + "get": { + "tags": [ + "BinaryContent" + ], + "summary": "파일 다운로드", + "operationId": "download", + "parameters": [ + { + "name": "binaryContentId", + "in": "path", + "description": "다운로드할 파일 ID", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "파일 다운로드 성공", + "content": { + "*/*": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "UserCreateRequest": { + "type": "object", + "description": "User 생성 정보", + "properties": { + "username": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "BinaryContentDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "fileName": { + "type": "string" + }, + "size": { + "type": "integer", + "format": "int64" + }, + "contentType": { + "type": "string" + } + } + }, + "UserDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "username": { + "type": "string" + }, + "email": { + "type": "string" + }, + "profile": { + "$ref": "#/components/schemas/BinaryContentDto" + }, + "online": { + "type": "boolean" + } + } + }, + "ReadStatusCreateRequest": { + "type": "object", + "description": "Message 읽음 상태 생성 정보", + "properties": { + "userId": { + "type": "string", + "format": "uuid" + }, + "channelId": { + "type": "string", + "format": "uuid" + }, + "lastReadAt": { + "type": "string", + "format": "date-time" + } + } + }, + "ReadStatusDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "userId": { + "type": "string", + "format": "uuid" + }, + "channelId": { + "type": "string", + "format": "uuid" + }, + "lastReadAt": { + "type": "string", + "format": "date-time" + } + } + }, + "MessageCreateRequest": { + "type": "object", + "description": "Message 생성 정보", + "properties": { + "content": { + "type": "string" + }, + "channelId": { + "type": "string", + "format": "uuid" + }, + "authorId": { + "type": "string", + "format": "uuid" + } + } + }, + "MessageDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "content": { + "type": "string" + }, + "channelId": { + "type": "string", + "format": "uuid" + }, + "author": { + "$ref": "#/components/schemas/UserDto" + }, + "attachments": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BinaryContentDto" + } + } + } + }, + "PublicChannelCreateRequest": { + "type": "object", + "description": "Public Channel 생성 정보", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + } + }, + "ChannelDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "type": { + "type": "string", + "enum": [ + "PUBLIC", + "PRIVATE" + ] + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "participants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserDto" + } + }, + "lastMessageAt": { + "type": "string", + "format": "date-time" + } + } + }, + "PrivateChannelCreateRequest": { + "type": "object", + "description": "Private Channel 생성 정보", + "properties": { + "participantIds": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, + "LoginRequest": { + "type": "object", + "description": "로그인 정보", + "properties": { + "username": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "UserUpdateRequest": { + "type": "object", + "description": "수정할 User 정보", + "properties": { + "newUsername": { + "type": "string" + }, + "newEmail": { + "type": "string" + }, + "newPassword": { + "type": "string" + } + } + }, + "UserStatusUpdateRequest": { + "type": "object", + "description": "변경할 User 온라인 상태 정보", + "properties": { + "newLastActiveAt": { + "type": "string", + "format": "date-time" + } + } + }, + "UserStatusDto": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "userId": { + "type": "string", + "format": "uuid" + }, + "lastActiveAt": { + "type": "string", + "format": "date-time" + } + } + }, + "ReadStatusUpdateRequest": { + "type": "object", + "description": "수정할 읽음 상태 정보", + "properties": { + "newLastReadAt": { + "type": "string", + "format": "date-time" + } + } + }, + "MessageUpdateRequest": { + "type": "object", + "description": "수정할 Message 내용", + "properties": { + "newContent": { + "type": "string" + } + } + }, + "PublicChannelUpdateRequest": { + "type": "object", + "description": "수정할 Channel 정보", + "properties": { + "newName": { + "type": "string" + }, + "newDescription": { + "type": "string" + } + } + }, + "Pageable": { + "type": "object", + "properties": { + "page": { + "type": "integer", + "format": "int32", + "minimum": 0 + }, + "size": { + "type": "integer", + "format": "int32", + "minimum": 1 + }, + "sort": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "PageResponse": { + "type": "object", + "properties": { + "content": { + "type": "array", + "items": { + "type": "object" + } + }, + "nextCursor": { + "type": "object" + }, + "size": { + "type": "integer", + "format": "int32" + }, + "hasNext": { + "type": "boolean" + }, + "totalElements": { + "type": "integer", + "format": "int64" + } + } + } + } + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 1bd079966..31e297751 100644 --- a/build.gradle +++ b/build.gradle @@ -1,11 +1,12 @@ plugins { id 'java' - id 'org.springframework.boot' version '3.5.4' - id 'io.spring.dependency-management' version '1.1.7' + id 'org.springframework.boot' version '3.4.0' + id 'io.spring.dependency-management' version '1.1.6' + id 'jacoco' } group = 'com.sprint.mission' -version = '0.0.1-SNAPSHOT' +version = '2.1-M10' java { toolchain { @@ -17,6 +18,9 @@ configurations { compileOnly { extendsFrom annotationProcessor } + testCompileOnly { + extendsFrom testAnnotationProcessor + } } repositories { @@ -25,12 +29,41 @@ repositories { 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:9.37' + + 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' } 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 index 1b33c55ba..a4b76b953 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index d4081da47..e2847c820 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 23d15a936..f5feea6d6 100644 --- a/gradlew +++ b/gradlew @@ -86,7 +86,8 @@ done # 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\n' "$PWD" ) || exit +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 @@ -114,7 +115,7 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH="\\\"\\\"" +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -205,7 +206,7 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * 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. @@ -213,7 +214,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index db3a6ac20..9d21a2183 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -70,11 +70,11 @@ goto fail :execute @rem Setup the command line -set CLASSPATH= +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%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +"%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 diff --git a/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java b/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java index 9ded14b22..97115cbce 100644 --- a/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java +++ b/src/main/java/com/sprint/mission/discodeit/DiscodeitApplication.java @@ -6,9 +6,9 @@ @SpringBootApplication public class DiscodeitApplication { - public static void main(String[] args) { - SpringApplication.run(DiscodeitApplication.class, args); - // 테스트 접속용 - System.out.println("http://localhost:8080/"); - } + public static void main(String[] args) { + + SpringApplication.run(DiscodeitApplication.class, args); + System.out.println("localhost:8080"); + } } 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..3a8238411 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/AppConfig.java @@ -0,0 +1,10 @@ +package com.sprint.mission.discodeit.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableJpaAuditing +@EnableScheduling +public class AppConfig {} \ 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..cb18cc53a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/MDCLoggingInterceptor.java @@ -0,0 +1,52 @@ +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; + +@Slf4j +public class MDCLoggingInterceptor implements HandlerInterceptor { + + 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/SecurityConfig.java b/src/main/java/com/sprint/mission/discodeit/config/SecurityConfig.java new file mode 100644 index 000000000..6450809a1 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/SecurityConfig.java @@ -0,0 +1,134 @@ +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.CustomLoginFailureHandler; +import com.sprint.mission.discodeit.security.JsonUsernamePasswordAuthenticationFilter; +import com.sprint.mission.discodeit.security.SecurityMatchers; +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.JwtService; +import java.util.List; +import java.util.stream.IntStream; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.access.hierarchicalroles.RoleHierarchyAuthoritiesMapper; +import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +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.core.userdetails.UserDetailsService; +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.logout.HttpStatusReturningLogoutSuccessHandler; +import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; +import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; + +@Slf4j +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain filterChain( + HttpSecurity http, + ObjectMapper objectMapper, + DaoAuthenticationProvider daoAuthenticationProvider, + JwtService jwtService + ) + throws Exception { + http + .authenticationProvider(daoAuthenticationProvider) + .authorizeHttpRequests(authorize -> authorize + .requestMatchers(SecurityMatchers.PUBLIC_MATCHERS).permitAll() + .anyRequest().hasRole(Role.USER.name()) + ) + .csrf(csrf -> + csrf + .ignoringRequestMatchers(SecurityMatchers.LOGOUT) + .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) + .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) + .sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy()) + ) + .logout(logout -> + logout + .logoutRequestMatcher(SecurityMatchers.LOGOUT) + .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()) + .addLogoutHandler(new JwtLogoutHandler(jwtService)) + ) + .with( + new JsonUsernamePasswordAuthenticationFilter.Configurer(objectMapper), + configurer -> + configurer + .successHandler(new JwtLoginSuccessHandler(objectMapper, jwtService)) + .failureHandler(new CustomLoginFailureHandler(objectMapper)) + ) + .sessionManagement(session -> + session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .addFilterBefore(new JwtAuthenticationFilter(jwtService, objectMapper), + JsonUsernamePasswordAuthenticationFilter.class) + ; + + return http.build(); + } + + @Bean + public String debugFilterChain(SecurityFilterChain chain) { + log.debug("Debug Filter Chain..."); + int filterSize = chain.getFilters().size(); + IntStream.range(0, filterSize) + .forEach(idx -> { + log.debug("[{}/{}] {}", idx + 1, filterSize, chain.getFilters().get(idx)); + }); + return "debugFilterChain"; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider( + UserDetailsService userDetailsService, + PasswordEncoder passwordEncoder, + RoleHierarchy roleHierarchy + ) { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setUserDetailsService(userDetailsService); + provider.setPasswordEncoder(passwordEncoder); + provider.setAuthoritiesMapper(new RoleHierarchyAuthoritiesMapper(roleHierarchy)); + return provider; + } + + @Bean + public AuthenticationManager authenticationManager( + List authenticationProviders) { + return new ProviderManager(authenticationProviders); + } + + @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(); + } +} \ 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..4e36da4f9 --- /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.1") + ) + .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..2604e4146 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/config/WebMvcConfig.java @@ -0,0 +1,21 @@ +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; + +@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 index 3042d9540..cef3fa917 100644 --- a/src/main/java/com/sprint/mission/discodeit/controller/AuthController.java +++ b/src/main/java/com/sprint/mission/discodeit/controller/AuthController.java @@ -1,30 +1,81 @@ package com.sprint.mission.discodeit.controller; -import com.sprint.mission.discodeit.dto.request.LoginRequest; -import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.controller.api.AuthApi; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.security.jwt.JwtService; +import com.sprint.mission.discodeit.security.jwt.JwtSession; import com.sprint.mission.discodeit.service.AuthService; +import com.sprint.mission.discodeit.service.UserService; +import java.util.UUID; + +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.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.web.csrf.CsrfToken; +import org.springframework.web.bind.annotation.*; +@Slf4j +@RequiredArgsConstructor @RestController @RequestMapping("/api/auth") -public class AuthController { - private final AuthService authService; - public AuthController(AuthService authService) { - this.authService = authService; - } - - @RequestMapping( - method = RequestMethod.POST, - value = "/login" - ) - public ResponseEntity login(@RequestBody LoginRequest req) { - if (req == null || req.username() == null || req.password() == null) { - throw new IllegalArgumentException("Username or password is null"); - } - return ResponseEntity.ok(authService.login(req)); - } +public class AuthController implements AuthApi { + + private final AuthService authService; + private final JwtService jwtService; + + @GetMapping("csrf-token") + public ResponseEntity getCsrfToken(CsrfToken csrfToken) { + log.debug("CSRF 토큰 요청"); + + return ResponseEntity + .status(HttpStatus.OK) + .body(csrfToken); + } + + @GetMapping("me") + public ResponseEntity me( + @CookieValue(value = JwtService.REFRESH_TOKEN_COOKIE_NAME) String refreshToken) { + log.info("내 정보 조회 요청"); + JwtSession jwtSession = jwtService.getJwtSession(refreshToken); + return ResponseEntity + .status(HttpStatus.OK) + .body(jwtSession.getAccessToken()); + } + + @PutMapping("role") + public ResponseEntity updateRole(@RequestBody RoleUpdateRequest request) { + log.info("권한 수정 요청"); + UserDto userDto = authService.updateRole(request); + + return ResponseEntity + .status(HttpStatus.OK) + .body(userDto); + } + + @PostMapping("refresh") + public ResponseEntity refreshInfo( + @CookieValue(value = JwtService.REFRESH_TOKEN_COOKIE_NAME) String refreshToken, + HttpServletResponse response + ) { + log.info("토큰 재발급 요청"); + + JwtSession jwtSession = jwtService.refreshJwtSession(refreshToken); + + Cookie refreshTokenCookie = new Cookie( + JwtService.REFRESH_TOKEN_COOKIE_NAME, + jwtSession.getRefreshToken() + ); + refreshTokenCookie.setHttpOnly(true); + response.addCookie(refreshTokenCookie); + + return ResponseEntity + .status(HttpStatus.OK) + .body(jwtSession.getAccessToken()); + } } diff --git a/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java b/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java index 45e218bdc..a0b93ffde 100644 --- a/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java +++ b/src/main/java/com/sprint/mission/discodeit/controller/BinaryContentController.java @@ -1,37 +1,60 @@ package com.sprint.mission.discodeit.controller; -import com.sprint.mission.discodeit.entity.BinaryContent; +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; -import java.util.List; -import java.util.UUID; - +@Slf4j +@RequiredArgsConstructor @RestController -@RequestMapping("/api/binary") -public class BinaryContentController { - private final BinaryContentService binaryContentService; - public BinaryContentController(BinaryContentService binaryContentService) { - this.binaryContentService = binaryContentService; - } +@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); + } - @RequestMapping(path = "find") - public ResponseEntity find(@RequestParam("binaryContentId") UUID binaryContentId) { - BinaryContent binaryContent = binaryContentService.find(binaryContentId); - 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); + } - @RequestMapping(path = "findAll") - public ResponseEntity> findAll(@RequestParam("binaryContentId") UUID binaryContentId) { - List binaryContents = binaryContentService.findAllByIdIn(List.of(binaryContentId)); - 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 index 9e108a9ea..3c8424236 100644 --- a/src/main/java/com/sprint/mission/discodeit/controller/ChannelController.java +++ b/src/main/java/com/sprint/mission/discodeit/controller/ChannelController.java @@ -1,76 +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.entity.Channel; import com.sprint.mission.discodeit.service.ChannelService; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.net.URI; +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 { - private final ChannelService channelService; - public ChannelController(ChannelService channelService) { - this.channelService = channelService; - } +public class ChannelController implements ChannelApi { + + private final ChannelService channelService; - @RequestMapping( - method = RequestMethod.POST, - value = "/public", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity createPublic(@RequestBody PublicChannelCreateRequest req) { - if (req == null || req.name() == null) { - throw new IllegalArgumentException("name is empty"); - } - Channel channel = channelService.create(req); - return ResponseEntity.created(URI.create("/api/channels/" + channel.getId())).body(channel); - } + @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); + } - @RequestMapping( - method = RequestMethod.GET, - value = "/{channelId}", - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity find(@PathVariable UUID channelId) { - return ResponseEntity.ok(channelService.find(channelId)); - } + @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); + } - @RequestMapping( - method = RequestMethod.PUT, value = "/{channelId}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity update(@PathVariable UUID channelId, - @RequestBody PublicChannelUpdateRequest req) { - if (req == null) throw new IllegalArgumentException("Empty"); - Channel updated = channelService.update(channelId, req); - return ResponseEntity.ok(updated); - } + @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); + } - @RequestMapping( - method = RequestMethod.DELETE, - value = "/{channelId}" - ) - public ResponseEntity delete(@PathVariable UUID channelId) { - channelService.delete(channelId); - return ResponseEntity.noContent().build(); - } + @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(); + } - @RequestMapping( - method = RequestMethod.GET, - value = "/visible", - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity> findVisible(@RequestParam("userId") UUID userId) { - return ResponseEntity.ok(channelService.findAllByUserId(userId)); - } -} \ No newline at end of file + @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 index 7da765ac9..5f7777d02 100644 --- a/src/main/java/com/sprint/mission/discodeit/controller/MessageController.java +++ b/src/main/java/com/sprint/mission/discodeit/controller/MessageController.java @@ -1,69 +1,116 @@ package com.sprint.mission.discodeit.controller; -import com.sprint.mission.discodeit.dto.request.*; -import com.sprint.mission.discodeit.entity.Message; +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 org.springframework.http.*; -import org.springframework.web.bind.annotation.*; - -import java.net.URI; -import java.util.*; +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 { - private final MessageService messageService; - public MessageController(MessageService messageService) { - this.messageService = messageService; - } +public class MessageController implements MessageApi { - @RequestMapping( - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity create(@RequestBody MessageCreateRequest req) { - if (req == null || req.channelId() == null || req.authorId() == null) { - throw new IllegalArgumentException("channelId와 authorId는 필수"); - } - Message saved = messageService.create(req, List.of()); - return ResponseEntity.created(URI.create("/api/messages/" + saved.getId())).body(saved); - } + private final MessageService messageService; - @RequestMapping( - method = RequestMethod.GET, - value = "/{messageId}", - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity find(@PathVariable UUID messageId) { - return ResponseEntity.ok(messageService.find(messageId)); - } + @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); + } - @RequestMapping( - method = RequestMethod.GET, - value = "/by-channel/{channelId}", - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity> findByChannel(@PathVariable UUID channelId) { - return ResponseEntity.ok(messageService.findAllByChannelId(channelId)); - } + @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); + } - @RequestMapping( - method = RequestMethod.PUT, - value = "/{messageId}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity update(@PathVariable UUID messageId, - @RequestBody MessageUpdateRequest req) { - if (req == null) throw new IllegalArgumentException("Empty"); - Message updated = messageService.update(messageId, req); - return ResponseEntity.ok(updated); - } + @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(); + } - @RequestMapping(method = RequestMethod.DELETE, value = "/{messageId}") - public ResponseEntity delete(@PathVariable UUID messageId) { - messageService.delete(messageId); - return ResponseEntity.noContent().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/ReadStatusController.java b/src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java index db4fcf8ef..ac980c066 100644 --- a/src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java +++ b/src/main/java/com/sprint/mission/discodeit/controller/ReadStatusController.java @@ -1,70 +1,62 @@ package com.sprint.mission.discodeit.controller; -import com.sprint.mission.discodeit.dto.request.*; -import com.sprint.mission.discodeit.entity.ReadStatus; +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 org.springframework.http.*; -import org.springframework.web.bind.annotation.*; - -import java.net.URI; -import java.util.*; - +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/read-status") -public class ReadStatusController { - private final ReadStatusService readStatusService; - public ReadStatusController(ReadStatusService readStatusService) { this.readStatusService = readStatusService; } - - @RequestMapping( - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity create(@RequestBody ReadStatusCreateRequest req) { - if (req == null || req.userId() == null || req.channelId() == null) { - throw new IllegalArgumentException("userId와 channelId는 필수"); - } - ReadStatus saved = readStatusService.create(req); - return ResponseEntity.created(URI.create("/api/read-status/" + saved.getId())).body(saved); - } - - @RequestMapping( - method = RequestMethod.GET, - value = "/{readStatusId}", - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity find(@PathVariable UUID readStatusId) { - return ResponseEntity.ok(readStatusService.find(readStatusId)); - } - - @RequestMapping( - method = RequestMethod.GET, - value = "/by-user/{userId}", - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity> findAllByUser(@PathVariable UUID userId) { - return ResponseEntity.ok(readStatusService.findAllByUserId(userId)); - } - - @RequestMapping( - method = RequestMethod.PUT, - value = "/{readStatusId}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity update(@PathVariable UUID readStatusId, - @RequestBody ReadStatusUpdateRequest req) { - if (req == null) throw new IllegalArgumentException("Empty"); - ReadStatus updated = readStatusService.update(readStatusId, req); - return ResponseEntity.ok(updated); - } - - @RequestMapping( - method = RequestMethod.DELETE, - value = "/{readStatusId}" - ) - public ResponseEntity delete(@PathVariable UUID readStatusId) { - readStatusService.delete(readStatusId); - return ResponseEntity.noContent().build(); - } +@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 index 59d718f05..4cdf75dda 100644 --- a/src/main/java/com/sprint/mission/discodeit/controller/UserController.java +++ b/src/main/java/com/sprint/mission/discodeit/controller/UserController.java @@ -1,112 +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.UserStatusUpdateRequest; 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.entity.UserStatus; import com.sprint.mission.discodeit.service.UserService; -import com.sprint.mission.discodeit.service.UserStatusService; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - +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 { - private final UserService userService; - private final UserStatusService userStatusService; +public class UserController implements UserApi { - public UserController(UserService userService, UserStatusService userStatusService) { - this.userService = userService; - this.userStatusService = userStatusService; - } + private final UserService userService; - @RequestMapping( - path = "create", - method = RequestMethod.POST, - consumes = MediaType.MULTIPART_FORM_DATA_VALUE - ) - public ResponseEntity createUser( - @RequestPart UserCreateRequest userCreateRequest, - @RequestPart(required = false) MultipartFile profile - ) throws IOException { - Optional profileCreateRequest = Optional.empty(); - if (!profile.isEmpty()) { - BinaryContent.ContentType contentType = mapToContentType(profile.getContentType()); - profileCreateRequest = Optional.of(new BinaryContentCreateRequest( - profile.getOriginalFilename(), - contentType, - profile.getBytes() - )); - } - User user = userService.create(userCreateRequest, profileCreateRequest); + @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); + } - return ResponseEntity.status(201).body(user); - } + @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); + } - private static BinaryContent.ContentType mapToContentType(String contentType) { - if (contentType == null) { - return BinaryContent.ContentType.TEXT; - } - if (contentType.startsWith("image/")) { - return BinaryContent.ContentType.IMAGE; - } - if (contentType.startsWith("video/")) { - return BinaryContent.ContentType.VIDEO; - } - return BinaryContent.ContentType.TEXT; - } + @DeleteMapping(path = "{userId}") + @Override + public ResponseEntity delete(@PathVariable("userId") UUID userId) { + userService.delete(userId); + return ResponseEntity + .status(HttpStatus.NO_CONTENT) + .build(); + } - @RequestMapping(path = "find", method = RequestMethod.GET) - public ResponseEntity find(@PathVariable UUID userId) { - return ResponseEntity.ok(userService.find(userId)); - } - - @RequestMapping(path = "findAll", method = RequestMethod.GET) - public ResponseEntity> findAll() { - List users = userService.findAll(); - return ResponseEntity - .status(HttpStatus.OK) - .body(users); - } - - @RequestMapping( - method = RequestMethod.PUT, value = "/{userId}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity update(@PathVariable UUID userId, - @RequestBody UserUpdateRequest req) { - if (req == null) throw new IllegalArgumentException("Empty"); - User updated = userService.update(userId, req, Optional.empty()); - return ResponseEntity.ok(updated); - } - - @RequestMapping(method = RequestMethod.DELETE, value = "/{userId}") - public ResponseEntity delete(@PathVariable UUID userId) { - userService.delete(userId); - return ResponseEntity.noContent().build(); - } + @GetMapping + @Override + public ResponseEntity> findAll() { + List users = userService.findAll(); + return ResponseEntity + .status(HttpStatus.OK) + .body(users); + } - @RequestMapping( - method = RequestMethod.PATCH, value = "/{userId}/status", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public ResponseEntity updateStatus(@PathVariable UUID userId, - @RequestBody UserStatusUpdateRequest req) { - if (req == null) throw new IllegalArgumentException("Empty"); - return ResponseEntity.ok(userStatusService.updateByUserId(userId, req)); + 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..e62b545c3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/controller/api/AuthApi.java @@ -0,0 +1,63 @@ +package com.sprint.mission.discodeit.controller.api; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +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 = "200", + description = "토큰 발급 성공", + content = @Content(schema = @Schema(implementation = CsrfToken.class)) + ) + }) + ResponseEntity getCsrfToken(@Parameter(hidden = true) CsrfToken csrfToken); + + @Operation(summary = "RefreshToken으로 accessToken 조회") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "조회 성공", + content = @Content(schema = @Schema(implementation = String.class)) + ), + @ApiResponse(responseCode = "401", description = "Invalid refreshToken") + }) + ResponseEntity me(@Parameter(hidden = true) String refreshToken); + + @Operation(summary = "사용자 권한 수정") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "권한 변경 성공", + content = @Content(schema = @Schema(implementation = UserDto.class)) + ) + }) + ResponseEntity updateRole( + @Parameter(description = "권한 수정 요청 정보") RoleUpdateRequest request); + + @Operation(summary = "RefreshToken으로 accessToken 재발급") + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", description = "재발급 성공", + content = @Content(schema = @Schema(implementation = String.class)) + ), + @ApiResponse(responseCode = "401", description = "Invalid refreshToken") + }) + ResponseEntity refreshInfo( + @Parameter(hidden = true) 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..e486abc59 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/BinaryContentDto.java @@ -0,0 +1,10 @@ +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 index 2005105e1..cb0fadc4f 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/data/ChannelDto.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/ChannelDto.java @@ -1,17 +1,15 @@ 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 participantIds, - Instant lastMessageAt -) { -} + UUID id, + ChannelType type, + String name, + String description, + List participants, + Instant lastMessageAt +) {} 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..b64a70a34 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/MessageDto.java @@ -0,0 +1,15 @@ +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/ReadStatusDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/ReadStatusDto.java new file mode 100644 index 000000000..6a933ca5e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/ReadStatusDto.java @@ -0,0 +1,11 @@ +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 index 46881b9d4..5ebce6037 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/data/UserDto.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/UserDto.java @@ -1,15 +1,13 @@ package com.sprint.mission.discodeit.dto.data; -import java.time.Instant; +import com.sprint.mission.discodeit.entity.Role; import java.util.UUID; public record UserDto( - UUID id, - Instant createdAt, - Instant updatedAt, - String username, - String email, - UUID profileId, - Boolean online -) { -} + UUID id, + String username, + String email, + BinaryContentDto profile, + Boolean online, + Role role +) {} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/data/UserStatusDto.java b/src/main/java/com/sprint/mission/discodeit/dto/data/UserStatusDto.java new file mode 100644 index 000000000..21f54b54c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/data/UserStatusDto.java @@ -0,0 +1,10 @@ +package com.sprint.mission.discodeit.dto.data; + +import java.time.Instant; +import java.util.UUID; + +public record UserStatusDto( + UUID id, + UUID userId, + Instant lastActiveAt +) {} 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 index 9df046b36..2ace92e70 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/BinaryContentCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/BinaryContentCreateRequest.java @@ -1,9 +1,17 @@ package com.sprint.mission.discodeit.dto.request; -import com.sprint.mission.discodeit.entity.BinaryContent; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; public record BinaryContentCreateRequest( - String fileName, - BinaryContent.ContentType contentType, - byte[] bytes) { -} + @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 index 2ab978e2a..658231879 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/LoginRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/LoginRequest.java @@ -1,7 +1,11 @@ package com.sprint.mission.discodeit.dto.request; +import jakarta.validation.constraints.NotBlank; + public record LoginRequest( - String username, - String password -) { -} + @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 index dd8c3d24c..7f4b44a61 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/MessageCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/MessageCreateRequest.java @@ -1,10 +1,18 @@ 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( - String content, - UUID channelId, - UUID authorId -) { -} + @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 index d1830fbb9..8c8bf8391 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/MessageUpdateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/MessageUpdateRequest.java @@ -1,6 +1,10 @@ package com.sprint.mission.discodeit.dto.request; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + public record MessageUpdateRequest( - String newContent -) { -} + @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 index 6b203baa7..895ae30c9 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/PrivateChannelCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/PrivateChannelCreateRequest.java @@ -1,9 +1,14 @@ 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( - List participantIds -) { -} + @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 index c5b15cc33..8570027a5 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelCreateRequest.java @@ -1,7 +1,13 @@ package com.sprint.mission.discodeit.dto.request; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + public record PublicChannelCreateRequest( - String name, - String description -) { -} + @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 index 6c0234162..3cfb08875 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelUpdateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/PublicChannelUpdateRequest.java @@ -1,7 +1,11 @@ package com.sprint.mission.discodeit.dto.request; +import jakarta.validation.constraints.Size; + public record PublicChannelUpdateRequest( - String newName, - String newDescription -) { -} + @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 index f2d520af9..91db39a4b 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusCreateRequest.java @@ -1,11 +1,18 @@ 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( - UUID userId, - UUID channelId, - Instant lastReadAt -) { -} + @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 index 3921ffc75..9c71f0482 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusUpdateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/ReadStatusUpdateRequest.java @@ -1,8 +1,11 @@ package com.sprint.mission.discodeit.dto.request; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.PastOrPresent; import java.time.Instant; public record ReadStatusUpdateRequest( - Instant newLastReadAt -) { -} + @NotNull(message = "새로운 마지막 읽은 시간은 필수입니다") + @PastOrPresent(message = "마지막 읽은 시간은 현재 또는 과거 시간이어야 합니다") + Instant newLastReadAt +) {} 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..89101e6e4 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/RoleUpdateRequest.java @@ -0,0 +1,9 @@ +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 index f7d22091c..b7decb12a 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/UserCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/UserCreateRequest.java @@ -1,7 +1,23 @@ 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( - String username, - String email, - String password) { -} + @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/UserStatusCreateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusCreateRequest.java index 272a0d4c7..019729c6a 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusCreateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusCreateRequest.java @@ -1,10 +1,15 @@ 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 UserStatusCreateRequest( - UUID userId, - Instant lastActiveAt -) { -} + @NotNull(message = "사용자 ID는 필수입니다") + UUID userId, + + @NotNull(message = "마지막 활동 시간은 필수입니다") + @PastOrPresent(message = "마지막 활동 시간은 현재 또는 과거 시간이어야 합니다") + Instant lastActiveAt +) {} diff --git a/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusUpdateRequest.java b/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusUpdateRequest.java index 9a001937a..4de8af824 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusUpdateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/UserStatusUpdateRequest.java @@ -1,8 +1,11 @@ package com.sprint.mission.discodeit.dto.request; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.PastOrPresent; import java.time.Instant; public record UserStatusUpdateRequest( - Instant newLastActiveAt -) { -} + @NotNull(message = "마지막 활동 시간은 필수입니다") + @PastOrPresent(message = "마지막 활동 시간은 현재 또는 과거 시간이어야 합니다") + Instant newLastActiveAt +) {} 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 index d1da4c7a3..41f2ed270 100644 --- a/src/main/java/com/sprint/mission/discodeit/dto/request/UserUpdateRequest.java +++ b/src/main/java/com/sprint/mission/discodeit/dto/request/UserUpdateRequest.java @@ -1,8 +1,19 @@ 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( - String newUsername, - String newEmail, - String newPassword -) { -} + @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..9cc0fbd0d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/dto/response/PageResponse.java @@ -0,0 +1,11 @@ +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 index 9607e3105..88a096848 100644 --- a/src/main/java/com/sprint/mission/discodeit/entity/BinaryContent.java +++ b/src/main/java/com/sprint/mission/discodeit/entity/BinaryContent.java @@ -1,36 +1,29 @@ 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.Table; +import lombok.AccessLevel; import lombok.Getter; +import lombok.NoArgsConstructor; -import java.io.Serializable; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.UUID; - +@Entity +@Table(name = "binary_contents") @Getter -public class BinaryContent implements Serializable { - private static final long serialVersionUID = 1L; - - private final UUID id; - private final Instant createdAt; - - private String filename; - private ContentType contentType; - private Long size; - private byte[] bytes; - - - public BinaryContent(String fileName, Long size, ContentType contentType, byte[] bytes) { - this.id = UUID.randomUUID(); - this.filename = fileName; - this.contentType = contentType; - this.size = size; - this.createdAt = Instant.now().truncatedTo(ChronoUnit.SECONDS); - } - - public enum ContentType { // Entity에 따로 뺄지 BinaryContent 내부에 포함할 지 고민됩니다 - TEXT, - IMAGE, - VIDEO - } +@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; + + public BinaryContent(String fileName, Long size, String contentType) { + this.fileName = fileName; + this.size = size; + this.contentType = contentType; + } } diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Channel.java b/src/main/java/com/sprint/mission/discodeit/entity/Channel.java index 295a02cfb..101b737bd 100644 --- a/src/main/java/com/sprint/mission/discodeit/entity/Channel.java +++ b/src/main/java/com/sprint/mission/discodeit/entity/Channel.java @@ -1,44 +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; -import java.io.Serializable; -import java.time.Instant; -import java.util.UUID; - +@Entity +@Table(name = "channels") @Getter -public class Channel implements Serializable { - private static final long serialVersionUID = 1L; - private final UUID id; - private final Instant createdAt; - private Instant updatedAt; - - private final ChannelType type; - private String name; - private String description; - - public Channel(ChannelType type, String name, String description) { - this.id = UUID.randomUUID(); - this.createdAt = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); - - this.type = type; - this.name = name; - this.description = description; +@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; } - - public void update(String newName, String newDescription) { - boolean anyValueUpdated = false; - if (newName != null && !newName.equals(this.name)) { - this.name = newName; - anyValueUpdated = true; - } - if (newDescription != null && !newDescription.equals(this.description)) { - this.description = newDescription; - anyValueUpdated = true; - } - - if (anyValueUpdated) { - this.updatedAt = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); - } + 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 index e4bafb160..4fca37721 100644 --- a/src/main/java/com/sprint/mission/discodeit/entity/ChannelType.java +++ b/src/main/java/com/sprint/mission/discodeit/entity/ChannelType.java @@ -1,6 +1,6 @@ package com.sprint.mission.discodeit.entity; public enum ChannelType { - PUBLIC, - PRIVATE + 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 index 2e4502dfb..7fe8865ea 100644 --- a/src/main/java/com/sprint/mission/discodeit/entity/Message.java +++ b/src/main/java/com/sprint/mission/discodeit/entity/Message.java @@ -1,46 +1,55 @@ package com.sprint.mission.discodeit.entity; -import lombok.Getter; - -import java.io.Serializable; -import java.time.Instant; +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 java.util.UUID; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.BatchSize; +@Entity +@Table(name = "messages") @Getter -public class Message implements Serializable { - private static final long serialVersionUID = 1L; - - private final UUID id; - private final Instant createdAt; - private Instant updatedAt; - - private String content; - - private final UUID channelId; - private final UUID authorId; - - private List attachmentIds; // BinaryContent 참조 필드 - - public Message(String content, UUID channelId, UUID authorId, List attachmentIds) { - this.id = UUID.randomUUID(); - this.createdAt = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); - - this.content = content; - this.channelId = channelId; - this.authorId = authorId; - this.attachmentIds = attachmentIds; - } - - public void update(String newContent) { - boolean anyValueUpdated = false; - if (newContent != null && !newContent.equals(this.content)) { - this.content = newContent; - anyValueUpdated = true; - } - - if (anyValueUpdated) { - this.updatedAt = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); - } +@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/ReadStatus.java b/src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java index fe905bb68..d51448b96 100644 --- a/src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java +++ b/src/main/java/com/sprint/mission/discodeit/entity/ReadStatus.java @@ -1,46 +1,47 @@ package com.sprint.mission.discodeit.entity; -import lombok.EqualsAndHashCode; -import lombok.Getter; - -import java.io.Serializable; +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 java.time.temporal.ChronoUnit; -import java.util.Objects; -import java.util.UUID; - -@Getter -@EqualsAndHashCode(of = {"userId", "channelId"}) -public class ReadStatus implements Serializable { - private static final long serialVersionUID = 1L; - private final UUID id; - private final UUID userId; - private final UUID channelId; - - private Instant createdAt; - private Instant updatedAt; - - private Instant lastReadAt; - - public ReadStatus(UUID userId, UUID channelId, Instant lastReadAt) { // Clock 이용한 테스트용 - this.id = UUID.randomUUID(); - this.userId = Objects.requireNonNull(userId, "userId"); - this.channelId = Objects.requireNonNull(channelId, "channelId"); +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; - this.createdAt = Instant.now().truncatedTo(ChronoUnit.SECONDS); - this.updatedAt = createdAt; - this.lastReadAt = lastReadAt; +@Entity +@Table( + name = "read_statuses", + uniqueConstraints = { + @UniqueConstraint(columnNames = {"user_id", "channel_id"}) } - - public void update(Instant newLastReadAt) { - boolean anyValueUpdated = false; - if (newLastReadAt != null && !newLastReadAt.equals(this.lastReadAt)) { - this.lastReadAt = newLastReadAt; - anyValueUpdated = true; - } - - if (anyValueUpdated) { - this.updatedAt = Instant.now(); - } +) +@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; + + public ReadStatus(User user, Channel channel, Instant lastReadAt) { + this.user = user; + this.channel = channel; + this.lastReadAt = lastReadAt; + } + + public void update(Instant newLastReadAt) { + if (newLastReadAt != null && !newLastReadAt.equals(this.lastReadAt)) { + this.lastReadAt = newLastReadAt; } -} + } +} \ 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 index cf267cb60..eb43e170c 100644 --- a/src/main/java/com/sprint/mission/discodeit/entity/User.java +++ b/src/main/java/com/sprint/mission/discodeit/entity/User.java @@ -1,57 +1,57 @@ package com.sprint.mission.discodeit.entity; +import com.sprint.mission.discodeit.entity.base.BaseUpdatableEntity; +import jakarta.persistence.*; +import lombok.AccessLevel; import lombok.Getter; +import lombok.NoArgsConstructor; -import java.io.Serializable; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.UUID; - +@Entity +@Table(name = "users") @Getter -public class User implements Serializable { - private static final long serialVersionUID = 1L; - - private final UUID id; - private UUID profileId; // BinaryContent 참조 필드 - - private final Instant createdAt; - private Instant updatedAt; - - private String username; - private String email; - private String password; - - public User(String username, String email, String password, UUID profileId) { - this.id = UUID.randomUUID(); - this.profileId = profileId; - this.createdAt = Instant.now().truncatedTo(ChronoUnit.SECONDS); - - this.username = username; - this.email = email; - this.password = password; +@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; + + public User(String username, String email, String password, BinaryContent profile) { + this.username = username; + this.email = email; + this.password = password; + this.profile = profile; + this.role = Role.USER; + } + + 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 update(String newUsername, String newEmail, String newPassword, UUID newProfileId) { - boolean anyValueUpdated = false; - if (newUsername != null && !newUsername.equals(this.username)) { - this.username = newUsername; - anyValueUpdated = true; - } - if (newEmail != null && !newEmail.equals(this.email)) { - this.email = newEmail; - anyValueUpdated = true; - } - if (newPassword != null && !newPassword.equals(this.password)) { - this.password = newPassword; - anyValueUpdated = true; - } - if (newProfileId != null && !newProfileId.equals(this.profileId)) { - this.profileId = newProfileId; - anyValueUpdated = true; - } - - if (anyValueUpdated) { - this.updatedAt = Instant.now().truncatedTo(ChronoUnit.SECONDS); - } + public void updateRole(Role newRole) { + if (this.role != newRole) { + this.role = newRole; } + } } diff --git a/src/main/java/com/sprint/mission/discodeit/entity/UserStatus.java b/src/main/java/com/sprint/mission/discodeit/entity/UserStatus.java deleted file mode 100644 index ffc101bc7..000000000 --- a/src/main/java/com/sprint/mission/discodeit/entity/UserStatus.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.sprint.mission.discodeit.entity; - -import lombok.EqualsAndHashCode; -import lombok.Getter; - -import java.io.Serializable; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.UUID; - -@Getter -@EqualsAndHashCode(of = {"id", "userId"}) -public class UserStatus implements Serializable { - private static final long serialVersionUID = 1L; - - public static final Duration ONLINE_TIMEOUT = Duration.ofMinutes(5); - - private final UUID id; - private final UUID userId; - private Instant lastActiveAt; - - private final Instant createdAt; - private Instant updatedAt; - - public UserStatus(UUID userId, Instant lastActiveAt) { - this.id = UUID.randomUUID(); - this.userId = userId; - this.lastActiveAt = lastActiveAt; - - this.createdAt = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); - this.updatedAt = createdAt; - } - - public void update(Instant lastActiveAt) { - boolean anyValueUpdated = false; - if (lastActiveAt != null && !lastActiveAt.equals(this.lastActiveAt)) { - this.lastActiveAt = lastActiveAt; - anyValueUpdated = true; - } - - if (anyValueUpdated) { - this.updatedAt = Instant.now(); - } - } - - public Boolean isOnline() { - Instant instantFiveMinutesAgo = Instant.now().minus(ONLINE_TIMEOUT); - - return lastActiveAt.isAfter(instantFiveMinutesAgo); - } -} 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/exception/ApiError.java b/src/main/java/com/sprint/mission/discodeit/exception/ApiError.java deleted file mode 100644 index 37395c2ba..000000000 --- a/src/main/java/com/sprint/mission/discodeit/exception/ApiError.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.sprint.mission.discodeit.exception; - -import java.time.Instant; -import java.util.List; - -public record ApiError( - Instant timestamp, - int status, - String error, - String message, - String path, - List details -) { - public static ApiError of(int status, String error, String message, String path, List details) { - return new ApiError(Instant.now(), status, error, message, path, details); - } -} 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..765f6f21e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/DiscodeitException.java @@ -0,0 +1,43 @@ +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 DiscodeitException(ErrorCode errorCode, Map details) { + this(errorCode); + this.details.putAll(details); + } + + public DiscodeitException(ErrorCode errorCode, Map details, Throwable cause) { + this(errorCode, cause); + this.details.putAll(details); + } + + 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..498eea563 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/exception/ErrorCode.java @@ -0,0 +1,40 @@ +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("잘못된 요청입니다."), + + // 인증 및 인가 관련 에러 코드 + INVALID_TOKEN_SECRET("유효하지 않은 시크릿입니다."), + INVALID_TOKEN("유효하지 않은 토큰입니다."), + TOKEN_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 index 38977c94d..1c1e7ceab 100644 --- a/src/main/java/com/sprint/mission/discodeit/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/sprint/mission/discodeit/exception/GlobalExceptionHandler.java @@ -1,67 +1,90 @@ package com.sprint.mission.discodeit.exception; -import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + 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 java.util.List; -import java.util.NoSuchElementException; +import lombok.extern.slf4j.Slf4j; +@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { - @ExceptionHandler(NoSuchElementException.class) - public ResponseEntity handleNotFound( - NoSuchElementException e, HttpServletRequest req - ) { - ApiError body = ApiError.of( - HttpStatus.NOT_FOUND.value(), - "Not Found", - e.getMessage(), - req.getRequestURI(), - List.of()); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body); - } + @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) { + ErrorResponse response = new ErrorResponse(ex, HttpStatus.FORBIDDEN.value()); - @ExceptionHandler(IllegalArgumentException.class) - public ResponseEntity handleBadRequest( - Exception e, HttpServletRequest req - ) { - ApiError body = ApiError.of( - HttpStatus.BAD_REQUEST.value(), - "Bad Request", - e.getMessage(), - req.getRequestURI(), - List.of() - ); - return ResponseEntity.badRequest().body(body); - } + return ResponseEntity + .status(HttpStatus.FORBIDDEN) + .body(response); + } - @ExceptionHandler(IllegalStateException.class) - public ResponseEntity handleConflict( - IllegalStateException e, HttpServletRequest req - ) { - ApiError body = ApiError.of( - HttpStatus.CONFLICT.value(), - "Conflict", - e.getMessage(), - req.getRequestURI(), - List.of()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(body); - } + private HttpStatus determineHttpStatus(DiscodeitException exception) { + ErrorCode errorCode = exception.getErrorCode(); - @ExceptionHandler(Exception.class) - public ResponseEntity handleException( - Exception e, HttpServletRequest req - ) { - ApiError body = ApiError.of( - HttpStatus.INTERNAL_SERVER_ERROR.value(), - "Internal Server Error", - "예상되지 않은 오류가 발생했습니다.", - req.getRequestURI(), - List.of()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body); - } + return switch (errorCode) { + case USER_NOT_FOUND, CHANNEL_NOT_FOUND, MESSAGE_NOT_FOUND, BINARY_CONTENT_NOT_FOUND, + READ_STATUS_NOT_FOUND -> HttpStatus.NOT_FOUND; + case DUPLICATE_USER, DUPLICATE_READ_STATUS -> HttpStatus.CONFLICT; + case INVALID_USER_CREDENTIALS, INVALID_TOKEN, TOKEN_NOT_FOUND, + INVALID_TOKEN_SECRET -> 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/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/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..17548e031 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/mapper/UserMapper.java @@ -0,0 +1,16 @@ +package com.sprint.mission.discodeit.mapper; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.entity.User; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring", uses = {BinaryContentMapper.class}) +public interface UserMapper { + + @Mapping(target = "online", ignore = true) + UserDto toDto(User user); + + @Mapping(target = "online", expression = "java(online)") + UserDto toDto(User user, boolean online); +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java index 519523e1c..cbd8c79cf 100644 --- a/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java +++ b/src/main/java/com/sprint/mission/discodeit/repository/BinaryContentRepository.java @@ -1,15 +1,9 @@ package com.sprint.mission.discodeit.repository; import com.sprint.mission.discodeit.entity.BinaryContent; - -import java.util.List; -import java.util.Optional; import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface BinaryContentRepository extends JpaRepository { -public interface BinaryContentRepository { // 임의로 선언만 - BinaryContent save(BinaryContent binaryContent); - Optional findById(UUID id); - List findAllByIdIn(List ids); - boolean existsById(UUID id); - void deleteById(UUID id); } diff --git a/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java index 326a84f4b..e4b1fd235 100644 --- a/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java +++ b/src/main/java/com/sprint/mission/discodeit/repository/ChannelRepository.java @@ -1,15 +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.Optional; import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ChannelRepository extends JpaRepository { -public interface ChannelRepository { - Channel save(Channel channel); - Optional findById(UUID id); - List findAll(); - boolean existsById(UUID id); - void deleteById(UUID id); + 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 index 69547b222..6996c05e2 100644 --- a/src/main/java/com/sprint/mission/discodeit/repository/MessageRepository.java +++ b/src/main/java/com/sprint/mission/discodeit/repository/MessageRepository.java @@ -1,16 +1,31 @@ package com.sprint.mission.discodeit.repository; import com.sprint.mission.discodeit.entity.Message; - -import java.util.List; +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); -public interface MessageRepository { - Message save(Message message); - Optional findById(UUID id); - List findAllByChannelId(UUID channelId); - boolean existsById(UUID id); - void deleteById(UUID id); - void deleteAllByChannelId(UUID channelId); + void deleteAllByChannelId(UUID channelId); } diff --git a/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java index dcb909ddc..ae2a6491d 100644 --- a/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java +++ b/src/main/java/com/sprint/mission/discodeit/repository/ReadStatusRepository.java @@ -1,18 +1,24 @@ package com.sprint.mission.discodeit.repository; import com.sprint.mission.discodeit.entity.ReadStatus; - 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; +import org.springframework.data.repository.query.Param; -public interface ReadStatusRepository { // 임의로 선언만 - ReadStatus save(ReadStatus readStatus); - Optional findById(UUID id); - List findAllByUserId(UUID userId); - List findAllByChannelId(UUID channelId); - boolean existsById(UUID id); - void deleteById(UUID id); - void deleteAllByChannelId(UUID channelId); -} +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); +} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java index 75c52fa8a..4fdd8f3b6 100644 --- a/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java +++ b/src/main/java/com/sprint/mission/discodeit/repository/UserRepository.java @@ -1,18 +1,21 @@ package com.sprint.mission.discodeit.repository; import com.sprint.mission.discodeit.entity.User; - 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); -public interface UserRepository { - User save(User user); - Optional findById(UUID id); - Optional findByUsername(String username); - List findAll(); - boolean existsById(UUID id); - void deleteById(UUID id); - boolean existsByEmail(String email); - boolean existsByUsername(String username); + @Query("SELECT u FROM User u " + + "LEFT JOIN FETCH u.profile") + List findAllWithProfile(); } diff --git a/src/main/java/com/sprint/mission/discodeit/repository/UserStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/UserStatusRepository.java deleted file mode 100644 index e02ca5900..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/UserStatusRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.sprint.mission.discodeit.repository; - -import com.sprint.mission.discodeit.entity.UserStatus; - -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -public interface UserStatusRepository { // 임의로 선언만 - UserStatus save(UserStatus userStatus); - Optional findById(UUID id); - Optional findByUserId(UUID userId); - List findAll(); - boolean existsById(UUID id); - void deleteById(UUID id); - void deleteByUserId(UUID userId); -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/file/FileBinaryContentRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/file/FileBinaryContentRepository.java deleted file mode 100644 index 42a5861f3..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/file/FileBinaryContentRepository.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.sprint.mission.discodeit.repository.file; - -import com.sprint.mission.discodeit.entity.BinaryContent; -import com.sprint.mission.discodeit.repository.BinaryContentRepository; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Stream; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "file") -@Repository -public class FileBinaryContentRepository implements BinaryContentRepository { - private final Path DIRECTORY; - private final String EXTENSION = ".ser"; - - public FileBinaryContentRepository( - @Value("${discodeit.repository.file-directory:data}") String fileDirectory - ) { - this.DIRECTORY = Paths.get(System.getProperty("user.dir"), fileDirectory, BinaryContent.class.getSimpleName()); - if (Files.notExists(DIRECTORY)) { - try { - Files.createDirectories(DIRECTORY); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private Path resolvePath(UUID id) { - return DIRECTORY.resolve(id + EXTENSION); - } - - @Override - public BinaryContent save(BinaryContent binaryContent) { - Path path = resolvePath(binaryContent.getId()); - try ( - FileOutputStream fos = new FileOutputStream(path.toFile()); - ObjectOutputStream oos = new ObjectOutputStream(fos) - ) { - oos.writeObject(binaryContent); - } catch (IOException e) { - throw new RuntimeException(e); - } - return binaryContent; - } - - @Override - public Optional findById(UUID id) { - BinaryContent binaryContentNullable = null; - Path path = resolvePath(id); - if (Files.exists(path)) { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - binaryContentNullable = (BinaryContent) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - return Optional.ofNullable(binaryContentNullable); - } - - @Override - public List findAllByIdIn(List ids) { - try (Stream paths = Files.list(DIRECTORY)) { - return paths - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (BinaryContent) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .filter(content -> ids.contains(content.getId())) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsById(UUID id) { - Path path = resolvePath(id); - return Files.exists(path); - } - - @Override - public void deleteById(UUID id) { - Path path = resolvePath(id); - try { - Files.delete(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/file/FileChannelRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/file/FileChannelRepository.java deleted file mode 100644 index a345b967e..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/file/FileChannelRepository.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.sprint.mission.discodeit.repository.file; - -import com.sprint.mission.discodeit.entity.Channel; -import com.sprint.mission.discodeit.repository.ChannelRepository; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Stream; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "file") -@Repository -public class FileChannelRepository implements ChannelRepository { - private final Path DIRECTORY; - private final String EXTENSION = ".ser"; - - public FileChannelRepository( - @Value("${discodeit.repository.file-directory:data}") String fileDirectory - ) { - this.DIRECTORY = Paths.get(System.getProperty("user.dir"), fileDirectory, Channel.class.getSimpleName()); - if (Files.notExists(DIRECTORY)) { - try { - Files.createDirectories(DIRECTORY); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private Path resolvePath(UUID id) { - return DIRECTORY.resolve(id + EXTENSION); - } - - @Override - public Channel save(Channel channel) { - Path path = resolvePath(channel.getId()); - try ( - FileOutputStream fos = new FileOutputStream(path.toFile()); - ObjectOutputStream oos = new ObjectOutputStream(fos) - ) { - oos.writeObject(channel); - } catch (IOException e) { - throw new RuntimeException(e); - } - return channel; - } - - @Override - public Optional findById(UUID id) { - Channel channelNullable = null; - Path path = resolvePath(id); - if (Files.exists(path)) { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - channelNullable = (Channel) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - return Optional.ofNullable(channelNullable); - } - - @Override - public List findAll() { - try (Stream paths = Files.list(DIRECTORY)) { - return paths - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (Channel) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsById(UUID id) { - Path path = resolvePath(id); - return Files.exists(path); - } - - @Override - public void deleteById(UUID id) { - Path path = resolvePath(id); - try { - Files.delete(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/file/FileMessageRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/file/FileMessageRepository.java deleted file mode 100644 index 4452a0e76..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/file/FileMessageRepository.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.sprint.mission.discodeit.repository.file; - -import com.sprint.mission.discodeit.entity.Message; -import com.sprint.mission.discodeit.repository.MessageRepository; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Stream; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "file") -@Repository -public class FileMessageRepository implements MessageRepository { - private final Path DIRECTORY; - private final String EXTENSION = ".ser"; - - public FileMessageRepository( - @Value("${discodeit.repository.file-directory:data}") String fileDirectory - ) { - this.DIRECTORY = Paths.get(System.getProperty("user.dir"), fileDirectory, Message.class.getSimpleName()); - if (Files.notExists(DIRECTORY)) { - try { - Files.createDirectories(DIRECTORY); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private Path resolvePath(UUID id) { - return DIRECTORY.resolve(id + EXTENSION); - } - - @Override - public Message save(Message message) { - Path path = resolvePath(message.getId()); - try ( - FileOutputStream fos = new FileOutputStream(path.toFile()); - ObjectOutputStream oos = new ObjectOutputStream(fos) - ) { - oos.writeObject(message); - } catch (IOException e) { - throw new RuntimeException(e); - } - return message; - } - - @Override - public Optional findById(UUID id) { - Message messageNullable = null; - Path path = resolvePath(id); - if (Files.exists(path)) { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - messageNullable = (Message) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - return Optional.ofNullable(messageNullable); - } - - @Override - public List findAllByChannelId(UUID channelId) { - try (Stream paths = Files.list(DIRECTORY)) { - return paths - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (Message) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .filter(m -> m.getChannelId().equals(channelId)) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsById(UUID id) { - Path path = resolvePath(id); - return Files.exists(path); - } - - @Override - public void deleteById(UUID id) { - Path path = resolvePath(id); - try { - Files.delete(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void deleteAllByChannelId(UUID channelId) { - this.findAllByChannelId(channelId) - .forEach(message -> this.deleteById(message.getId())); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/file/FileReadStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/file/FileReadStatusRepository.java deleted file mode 100644 index ff456bcc5..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/file/FileReadStatusRepository.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.sprint.mission.discodeit.repository.file; - -import com.sprint.mission.discodeit.entity.ReadStatus; -import com.sprint.mission.discodeit.repository.ReadStatusRepository; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Stream; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "file") -@Repository -public class FileReadStatusRepository implements ReadStatusRepository { - private final Path DIRECTORY; - private final String EXTENSION = ".ser"; - - public FileReadStatusRepository( - @Value("${discodeit.repository.file-directory:data}") String fileDirectory - ) { - this.DIRECTORY = Paths.get(System.getProperty("user.dir"), fileDirectory, ReadStatus.class.getSimpleName()); - if (Files.notExists(DIRECTORY)) { - try { - Files.createDirectories(DIRECTORY); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private Path resolvePath(UUID id) { - return DIRECTORY.resolve(id + EXTENSION); - } - - @Override - public ReadStatus save(ReadStatus readStatus) { - Path path = resolvePath(readStatus.getId()); - try ( - FileOutputStream fos = new FileOutputStream(path.toFile()); - ObjectOutputStream oos = new ObjectOutputStream(fos) - ) { - oos.writeObject(readStatus); - } catch (IOException e) { - throw new RuntimeException(e); - } - return readStatus; - } - - @Override - public Optional findById(UUID id) { - ReadStatus readStatusNullable = null; - Path path = resolvePath(id); - if (Files.exists(path)) { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - readStatusNullable = (ReadStatus) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - return Optional.ofNullable(readStatusNullable); - } - - @Override - public List findAllByUserId(UUID userId) { - try (Stream paths = Files.list(DIRECTORY)) { - return paths - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (ReadStatus) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .filter(readStatus -> readStatus.getUserId().equals(userId)) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public List findAllByChannelId(UUID channelId) { - try { - return Files.list(DIRECTORY) - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (ReadStatus) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .filter(readStatus -> readStatus.getChannelId().equals(channelId)) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsById(UUID id) { - Path path = resolvePath(id); - return Files.exists(path); - } - - @Override - public void deleteById(UUID id) { - Path path = resolvePath(id); - try { - Files.delete(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void deleteAllByChannelId(UUID channelId) { - this.findAllByChannelId(channelId) - .forEach(readStatus -> this.deleteById(readStatus.getId())); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/file/FileUserRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/file/FileUserRepository.java deleted file mode 100644 index b7fa1c1b7..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/file/FileUserRepository.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.sprint.mission.discodeit.repository.file; - -import com.sprint.mission.discodeit.entity.User; -import com.sprint.mission.discodeit.repository.UserRepository; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Stream; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "file") -@Repository -public class FileUserRepository implements UserRepository { - private final Path DIRECTORY; - private final String EXTENSION = ".ser"; - - public FileUserRepository( - @Value("${discodeit.repository.file-directory:data}") String fileDirectory - ) { - this.DIRECTORY = Paths.get(System.getProperty("user.dir"), fileDirectory, User.class.getSimpleName()); - if (Files.notExists(DIRECTORY)) { - try { - Files.createDirectories(DIRECTORY); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private Path resolvePath(UUID id) { - return DIRECTORY.resolve(id + EXTENSION); - } - - @Override - public User save(User user) { - Path path = resolvePath(user.getId()); - try ( - FileOutputStream fos = new FileOutputStream(path.toFile()); - ObjectOutputStream oos = new ObjectOutputStream(fos) - ) { - oos.writeObject(user); - } catch (IOException e) { - throw new RuntimeException(e); - } - return user; - } - - @Override - public Optional findById(UUID id) { - User userNullable = null; - Path path = resolvePath(id); - if (Files.exists(path)) { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - userNullable = (User) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - return Optional.ofNullable(userNullable); - } - - @Override - public Optional findByUsername(String username) { - return this.findAll().stream() - .filter(user -> user.getUsername().equals(username)) - .findFirst(); - } - - @Override - public List findAll() { - try (Stream paths = Files.list(DIRECTORY)) { - return paths - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (User) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsById(UUID id) { - Path path = resolvePath(id); - return Files.exists(path); - } - - @Override - public void deleteById(UUID id) { - Path path = resolvePath(id); - try { - Files.delete(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsByEmail(String email) { - return this.findAll().stream() - .anyMatch(user -> user.getEmail().equals(email)); - } - - @Override - public boolean existsByUsername(String username) { - return this.findAll().stream() - .anyMatch(user -> user.getUsername().equals(username)); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/file/FileUserStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/file/FileUserStatusRepository.java deleted file mode 100644 index 732538dbd..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/file/FileUserStatusRepository.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.sprint.mission.discodeit.repository.file; - -import com.sprint.mission.discodeit.entity.UserStatus; -import com.sprint.mission.discodeit.repository.UserStatusRepository; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Stream; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "file") -@Repository -public class FileUserStatusRepository implements UserStatusRepository { - private final Path DIRECTORY; - private final String EXTENSION = ".ser"; - - public FileUserStatusRepository( - @Value("${discodeit.repository.file-directory:data}") String fileDirectory - ) { - this.DIRECTORY = Paths.get(System.getProperty("user.dir"), fileDirectory, UserStatus.class.getSimpleName()); - if (Files.notExists(DIRECTORY)) { - try { - Files.createDirectories(DIRECTORY); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private Path resolvePath(UUID id) { - return DIRECTORY.resolve(id + EXTENSION); - } - - @Override - public UserStatus save(UserStatus userStatus) { - Path path = resolvePath(userStatus.getId()); - try ( - FileOutputStream fos = new FileOutputStream(path.toFile()); - ObjectOutputStream oos = new ObjectOutputStream(fos) - ) { - oos.writeObject(userStatus); - } catch (IOException e) { - throw new RuntimeException(e); - } - return userStatus; - } - - @Override - public Optional findById(UUID id) { - UserStatus userStatusNullable = null; - Path path = resolvePath(id); - if (Files.exists(path)) { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - userStatusNullable = (UserStatus) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - return Optional.ofNullable(userStatusNullable); - } - - @Override - public Optional findByUserId(UUID userId) { - return findAll().stream() - .filter(userStatus -> userStatus.getUserId().equals(userId)) - .findFirst(); - } - - @Override - public List findAll() { - try (Stream paths = Files.list(DIRECTORY)) { - return paths - .filter(path -> path.toString().endsWith(EXTENSION)) - .map(path -> { - try ( - FileInputStream fis = new FileInputStream(path.toFile()); - ObjectInputStream ois = new ObjectInputStream(fis) - ) { - return (UserStatus) ois.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new RuntimeException(e); - } - }) - .toList(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean existsById(UUID id) { - Path path = resolvePath(id); - return Files.exists(path); - } - - @Override - public void deleteById(UUID id) { - Path path = resolvePath(id); - try { - Files.delete(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void deleteByUserId(UUID userId) { - this.findByUserId(userId) - .ifPresent(userStatus -> this.deleteById(userStatus.getId())); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFBinaryContentRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFBinaryContentRepository.java deleted file mode 100644 index 48f55a3ff..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFBinaryContentRepository.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.sprint.mission.discodeit.repository.jcf; - -import com.sprint.mission.discodeit.entity.BinaryContent; -import com.sprint.mission.discodeit.repository.BinaryContentRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.util.*; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "jcf", matchIfMissing = true) -@Repository -public class JCFBinaryContentRepository implements BinaryContentRepository { - private final Map data; - - public JCFBinaryContentRepository() { - this.data = new HashMap<>(); - } - - @Override - public BinaryContent save(BinaryContent binaryContent) { - this.data.put(binaryContent.getId(), binaryContent); - return binaryContent; - } - - @Override - public Optional findById(UUID id) { - return Optional.ofNullable(this.data.get(id)); - } - - @Override - public List findAllByIdIn(List ids) { - return this.data.values().stream() - .filter(content -> ids.contains(content.getId())) - .toList(); - } - - @Override - public boolean existsById(UUID id) { - return this.data.containsKey(id); - } - - @Override - public void deleteById(UUID id) { - this.data.remove(id); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFChannelRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFChannelRepository.java deleted file mode 100644 index 5e4ec9282..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFChannelRepository.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.sprint.mission.discodeit.repository.jcf; - -import com.sprint.mission.discodeit.entity.Channel; -import com.sprint.mission.discodeit.repository.ChannelRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.util.*; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "jcf", matchIfMissing = true) -@Repository -public class JCFChannelRepository implements ChannelRepository { - private final Map data; - - public JCFChannelRepository() { - this.data = new HashMap<>(); - } - - @Override - public Channel save(Channel channel) { - this.data.put(channel.getId(), channel); - return channel; - } - - @Override - public Optional findById(UUID id) { - return Optional.ofNullable(this.data.get(id)); - } - - @Override - public List findAll() { - return this.data.values().stream().toList(); - } - - @Override - public boolean existsById(UUID id) { - return this.data.containsKey(id); - } - - @Override - public void deleteById(UUID id) { - this.data.remove(id); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFMessageRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFMessageRepository.java deleted file mode 100644 index c5bdbc40c..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFMessageRepository.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.sprint.mission.discodeit.repository.jcf; - -import com.sprint.mission.discodeit.entity.Message; -import com.sprint.mission.discodeit.repository.MessageRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.util.*; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "jcf", matchIfMissing = true) -@Repository -public class JCFMessageRepository implements MessageRepository { - private final Map data; - - public JCFMessageRepository() { - this.data = new HashMap<>(); - } - - @Override - public Message save(Message message) { - this.data.put(message.getId(), message); - return message; - } - - @Override - public Optional findById(UUID id) { - return Optional.ofNullable(this.data.get(id)); - } - - @Override - public List findAllByChannelId(UUID channelId) { - return this.data.values().stream() - .filter(m -> m.getChannelId().equals(channelId)) - .toList(); - } - - @Override - public boolean existsById(UUID id) { - return this.data.containsKey(id); - } - - @Override - public void deleteById(UUID id) { - this.data.remove(id); - } - - @Override - public void deleteAllByChannelId(UUID channelId) { - this.findAllByChannelId(channelId) - .forEach(message -> this.deleteById(message.getId())); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFReadStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFReadStatusRepository.java deleted file mode 100644 index 9c483eeb9..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFReadStatusRepository.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.sprint.mission.discodeit.repository.jcf; - -import com.sprint.mission.discodeit.entity.ReadStatus; -import com.sprint.mission.discodeit.repository.ReadStatusRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.util.*; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "jcf", matchIfMissing = true) -@Repository -public class JCFReadStatusRepository implements ReadStatusRepository { - private final Map data; - - public JCFReadStatusRepository() { - this.data = new HashMap<>(); - } - - @Override - public ReadStatus save(ReadStatus readStatus) { - this.data.put(readStatus.getId(), readStatus); - return readStatus; - } - - @Override - public Optional findById(UUID id) { - return Optional.ofNullable(this.data.get(id)); - } - - @Override - public List findAllByUserId(UUID userId) { - return this.data.values().stream() - .filter(readStatus -> readStatus.getUserId().equals(userId)) - .toList(); - } - - @Override - public List findAllByChannelId(UUID channelId) { - return this.data.values().stream() - .filter(readStatus -> readStatus.getChannelId().equals(channelId)) - .toList(); - } - - @Override - public boolean existsById(UUID id) { - return this.data.containsKey(id); - } - - @Override - public void deleteById(UUID id) { - this.data.remove(id); - } - - @Override - public void deleteAllByChannelId(UUID channelId) { - this.findAllByChannelId(channelId) - .forEach(readStatus -> this.deleteById(readStatus.getId())); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFUserRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFUserRepository.java deleted file mode 100644 index ec1bc555f..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFUserRepository.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.sprint.mission.discodeit.repository.jcf; - -import com.sprint.mission.discodeit.entity.User; -import com.sprint.mission.discodeit.repository.UserRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.util.*; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "jcf", matchIfMissing = true) -@Repository -public class JCFUserRepository implements UserRepository { - private final Map data; - - public JCFUserRepository() { - this.data = new HashMap<>(); - } - - @Override - public User save(User user) { - this.data.put(user.getId(), user); - return user; - } - - @Override - public Optional findById(UUID id) { - return Optional.ofNullable(this.data.get(id)); - } - - @Override - public Optional findByUsername(String username) { - return this.findAll().stream() - .filter(user -> user.getUsername().equals(username)) - .findFirst(); - } - - @Override - public List findAll() { - return this.data.values().stream().toList(); - } - - @Override - public boolean existsById(UUID id) { - return this.data.containsKey(id); - } - - @Override - public void deleteById(UUID id) { - this.data.remove(id); - } - - @Override - public boolean existsByEmail(String email) { - return this.findAll().stream().anyMatch(user -> user.getEmail().equals(email)); - } - - @Override - public boolean existsByUsername(String username) { - return this.findAll().stream().anyMatch(user -> user.getUsername().equals(username)); - } -} diff --git a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFUserStatusRepository.java b/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFUserStatusRepository.java deleted file mode 100644 index da93ff68b..000000000 --- a/src/main/java/com/sprint/mission/discodeit/repository/jcf/JCFUserStatusRepository.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.sprint.mission.discodeit.repository.jcf; - -import com.sprint.mission.discodeit.entity.UserStatus; -import com.sprint.mission.discodeit.repository.UserStatusRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Repository; - -import java.util.*; - -@ConditionalOnProperty(name = "discodeit.repository.type", havingValue = "jcf", matchIfMissing = true) -@Repository -public class JCFUserStatusRepository implements UserStatusRepository { - private final Map data; - - public JCFUserStatusRepository() { - this.data = new HashMap<>(); - } - - @Override - public UserStatus save(UserStatus userStatus) { - this.data.put(userStatus.getId(), userStatus); - return userStatus; - } - - @Override - public Optional findById(UUID id) { - return Optional.ofNullable(this.data.get(id)); - } - - @Override - public Optional findByUserId(UUID userId) { - return this.findAll().stream() - .filter(userStatus -> userStatus.getUserId().equals(userId)) - .findFirst(); - } - - @Override - public List findAll() { - return this.data.values().stream().toList(); - } - - @Override - public boolean existsById(UUID id) { - return this.data.containsKey(id); - } - - @Override - public void deleteById(UUID id) { - this.data.remove(id); - } - - @Override - public void deleteByUserId(UUID userId) { - this.findByUserId(userId) - .ifPresent(userStatus -> this.deleteById(userStatus.getId())); - } -} 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..52ed46f33 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/AdminInitializer.java @@ -0,0 +1,21 @@ +package com.sprint.mission.discodeit.security; + +import com.sprint.mission.discodeit.service.AuthService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +@Slf4j +@RequiredArgsConstructor +@Component +public class AdminInitializer implements ApplicationRunner { + + private final AuthService authService; + + @Override + public void run(ApplicationArguments args) { + authService.initAdmin(); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/CustomLoginFailureHandler.java b/src/main/java/com/sprint/mission/discodeit/security/CustomLoginFailureHandler.java new file mode 100644 index 000000000..8887315a7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/CustomLoginFailureHandler.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 lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import java.io.IOException; + +@RequiredArgsConstructor +public class CustomLoginFailureHandler implements AuthenticationFailureHandler { + + private final ObjectMapper objectMapper; + + @Override + public void onAuthenticationFailure( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException exception + ) throws IOException, ServletException { + 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/CustomLoginSuccessHandler.java b/src/main/java/com/sprint/mission/discodeit/security/CustomLoginSuccessHandler.java new file mode 100644 index 000000000..2b7a5bb4b --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/CustomLoginSuccessHandler.java @@ -0,0 +1,33 @@ +package com.sprint.mission.discodeit.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +import java.io.IOException; + +@RequiredArgsConstructor +public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler { + + private final ObjectMapper objectMapper; + + @Override + public void onAuthenticationSuccess( + HttpServletRequest request, + HttpServletResponse response, + Authentication authentication + ) throws IOException, ServletException { + DiscodeitUserDetails principal = (DiscodeitUserDetails) authentication.getPrincipal(); + + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + + response.getWriter().write(objectMapper.writeValueAsString(principal.getUserDto())); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/CustomSessionInformationExpiredStrategy.java b/src/main/java/com/sprint/mission/discodeit/security/CustomSessionInformationExpiredStrategy.java new file mode 100644 index 000000000..42a00c561 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/CustomSessionInformationExpiredStrategy.java @@ -0,0 +1,38 @@ +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.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.web.authentication.session.SessionAuthenticationException; +import org.springframework.security.web.session.SessionInformationExpiredEvent; +import org.springframework.security.web.session.SessionInformationExpiredStrategy; + +import java.io.IOException; + +@RequiredArgsConstructor +public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy { + + private final ObjectMapper objectMapper; + + @Override + public void onExpiredSessionDetected( + SessionInformationExpiredEvent event + ) throws IOException, ServletException { + int status = HttpServletResponse.SC_UNAUTHORIZED; + HttpServletResponse response = event.getResponse(); + response.setStatus(status); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + + ErrorResponse errorResponse = new ErrorResponse( + new SessionAuthenticationException("Session is expired"), + status + ); + errorResponse.getDetails().put("sessionId", event.getSessionInformation().getSessionId()); + + response.setCharacterEncoding("UTF-8"); + response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); + } +} 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..223d1a49d --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetails.java @@ -0,0 +1,46 @@ +package com.sprint.mission.discodeit.security; + +import com.sprint.mission.discodeit.dto.data.UserDto; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +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; + +@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(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof DiscodeitUserDetails that)) return false; + return userDto.username().equals(that.userDto.username()); + } + + @Override + public int hashCode() { + return Objects.hash(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..345b7be7b --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/DiscodeitUserDetailsService.java @@ -0,0 +1,33 @@ +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)); + + return new DiscodeitUserDetails( + userMapper.toDto(user), + user.getPassword() + ); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/JsonUsernamePasswordAuthenticationFilter.java b/src/main/java/com/sprint/mission/discodeit/security/JsonUsernamePasswordAuthenticationFilter.java new file mode 100644 index 000000000..458e126f5 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/JsonUsernamePasswordAuthenticationFilter.java @@ -0,0 +1,92 @@ +package com.sprint.mission.discodeit.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.request.LoginRequest; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.RememberMeServices; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; + +@RequiredArgsConstructor +public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { + + private final ObjectMapper objectMapper; + + @Override + public Authentication attemptAuthentication( + HttpServletRequest request, + HttpServletResponse response + ) throws AuthenticationException { + if (!request.getMethod().equals("POST")) { + throw new AuthenticationServiceException( + "Authentication method not supported: " + request.getMethod() + ); + } + + try { + // JSON 요청 파싱 + LoginRequest loginRequest = objectMapper.readValue(request.getInputStream(), + LoginRequest.class); + + UsernamePasswordAuthenticationToken authRequest = + new UsernamePasswordAuthenticationToken(loginRequest.username(), loginRequest.password()); + + setDetails(request, authRequest); + return this.getAuthenticationManager().authenticate(authRequest); + } catch (IOException e) { + throw new AuthenticationServiceException("Request parsing failure", e); + } + } + + public static JsonUsernamePasswordAuthenticationFilter createDefault( + ObjectMapper objectMapper, + AuthenticationManager authenticationManager, + SessionAuthenticationStrategy sessionAuthenticationStrategy, + RememberMeServices rememberMeServices + ) { + JsonUsernamePasswordAuthenticationFilter filter = + new JsonUsernamePasswordAuthenticationFilter(objectMapper); + + filter.setRequiresAuthenticationRequestMatcher(SecurityMatchers.LOGIN); + filter.setAuthenticationManager(authenticationManager); + filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); + filter.setRememberMeServices(rememberMeServices); + filter.setAuthenticationSuccessHandler(new CustomLoginSuccessHandler(objectMapper)); + filter.setAuthenticationFailureHandler(new CustomLoginFailureHandler(objectMapper)); + filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository()); + return filter; + } + + public static class Configurer extends + AbstractAuthenticationFilterConfigurer { + + public Configurer(ObjectMapper objectMapper) { + super(new JsonUsernamePasswordAuthenticationFilter(objectMapper), SecurityMatchers.LOGIN_URL); + + } + + @Override + protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) { + return new AntPathRequestMatcher(loginProcessingUrl, HttpMethod.POST.name()); + } + + @Override + public void init(HttpSecurity http) throws Exception { + loginProcessingUrl(SecurityMatchers.LOGIN_URL); + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/SecurityMatchers.java b/src/main/java/com/sprint/mission/discodeit/security/SecurityMatchers.java new file mode 100644 index 000000000..460f9e79b --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/SecurityMatchers.java @@ -0,0 +1,38 @@ +package com.sprint.mission.discodeit.security; + +import org.springframework.http.HttpMethod; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.NegatedRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; + +public class SecurityMatchers { + + public static final RequestMatcher NON_API = new NegatedRequestMatcher( + new AntPathRequestMatcher("/api/**")); + + public static final RequestMatcher GET_CSRF_TOKEN = new AntPathRequestMatcher( + "/api/auth/csrf-token", HttpMethod.GET.name()); + + public static final RequestMatcher SIGN_UP = new AntPathRequestMatcher( + "/api/users", HttpMethod.POST.name()); + + public static final RequestMatcher LOGIN = new AntPathRequestMatcher( + "/api/auth/login", HttpMethod.POST.name()); + + public static final String LOGIN_URL = "/api/auth/login"; + + public static final RequestMatcher LOGOUT = new AntPathRequestMatcher( + "/api/auth/logout", HttpMethod.POST.name()); + + public static final RequestMatcher ME = new AntPathRequestMatcher( + "/api/auth/me", HttpMethod.GET.name() + ); + + public static final RequestMatcher REFRESH = new AntPathRequestMatcher( + "/api/auth/refresh", HttpMethod.POST.name() + ); + + public static final RequestMatcher[] PUBLIC_MATCHERS = new RequestMatcher[]{ + NON_API, GET_CSRF_TOKEN, SIGN_UP, LOGIN, LOGOUT, ME, REFRESH + }; +} 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..2b375327e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtAuthenticationFilter.java @@ -0,0 +1,87 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.exception.DiscodeitException; +import com.sprint.mission.discodeit.exception.ErrorCode; +import com.sprint.mission.discodeit.exception.ErrorResponse; +import com.sprint.mission.discodeit.security.DiscodeitUserDetails; +import com.sprint.mission.discodeit.security.SecurityMatchers; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +@Slf4j +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final ObjectMapper objectMapper; + private final JwtService jwtService; + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + Optional optionalAccessToken = resolveAccessToken(request); + if (optionalAccessToken.isPresent() && !isPermitAll(request)) { + String accessToken = optionalAccessToken.get(); + + if (jwtService.validate(accessToken)) { + UserDto userDto = jwtService.parse(accessToken).userDto(); + DiscodeitUserDetails userDetails = new DiscodeitUserDetails(userDto, null); + UsernamePasswordAuthenticationToken authenticationToken = + new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities() + ); + + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + + chain.doFilter(request, response); + } else { + jwtService.invalidateJwtSession(accessToken); + + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + + ErrorResponse errorResponse = new ErrorResponse( + new DiscodeitException(ErrorCode.INVALID_TOKEN, + Map.of("accessToken", accessToken)), HttpServletResponse.SC_UNAUTHORIZED + ); + } + } else { + chain.doFilter(request, response); + } + } + + private Optional resolveAccessToken(HttpServletRequest request) { + String prefix = "Bearer "; + + return Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION)) + .map(value -> { + if (value.startsWith(prefix)) { + return value.substring(prefix.length()); + } else { + return null; + } + }); + } + + private boolean isPermitAll(HttpServletRequest request) { + return Arrays.stream(SecurityMatchers.PUBLIC_MATCHERS) + .anyMatch(requestMatcher -> requestMatcher.matches(request)); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtBlacklist.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtBlacklist.java new file mode 100644 index 000000000..aa01eced4 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtBlacklist.java @@ -0,0 +1,32 @@ +package com.sprint.mission.discodeit.security.jwt; + +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +public class JwtBlacklist { + + // 블랙리스트를 저장하는 ConcurrentHashMap + // accessToken, 만료시간 형태로 저장 + private final Map blacklist = new ConcurrentHashMap<>(); + + // accessToken을 블랙리스트에 등록 + public void put(String accessToken, Instant expirationTime) { + blacklist.putIfAbsent(accessToken, expirationTime); // key가 이미 있을 시 기존 값 유지 + } + + // accessToken의 블랙리스트 등록 여부 확인 + public boolean contains(String accessToken) { + return blacklist.containsKey(accessToken); + } + + // 만료되어 블랙리스트 등록이 필요없는 토큰을 1시간 주기로 정리 + @Scheduled(fixedRate = 60 * 60 * 1000) + public void clean() { + // 만료 시간이 현재보다 과거인지 확인 후 제거 + blacklist.values().removeIf(expirationTime -> expirationTime.isBefore(Instant.now())); + } +} 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..0d673e5b6 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLoginSuccessHandler.java @@ -0,0 +1,51 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.fasterxml.jackson.databind.ObjectMapper; +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 org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +@RequiredArgsConstructor +public class JwtLoginSuccessHandler implements AuthenticationSuccessHandler { + + private final ObjectMapper objectMapper; + private final JwtService jwtService; + + // 인증 성공 시 실행되는 메서드 + @Override + public void onAuthenticationSuccess( + HttpServletRequest request, + HttpServletResponse response, + Authentication authentication // 인증 성공 후 결과 객체, 사용자 정보(principal) 포함 + ) throws IOException, ServletException { + DiscodeitUserDetails principal = (DiscodeitUserDetails) authentication.getPrincipal(); + + // 이전 세션 무효화 + jwtService.invalidateJwtSession(principal.getUserDto().id()); + + // 새로운 세션 등록 및 토큰 발급 + JwtSession jwtSession = jwtService.registerJwtSession(principal.getUserDto()); + + String refreshToken = jwtSession.getRefreshToken(); + Cookie refreshTokenCookie = new Cookie(JwtService.REFRESH_TOKEN_COOKIE_NAME, refreshToken); + + // RefreshToken 탈취 방지 보안 옵션 + refreshTokenCookie.setHttpOnly(true); + // refreshTokenCookie.setSecure(true); + refreshTokenCookie.setSecure(false); // 로컬 임시 테스트 + + response.addCookie(refreshTokenCookie); + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + response.getWriter().write(objectMapper.writeValueAsString(jwtSession.getAccessToken())); + + } +} 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..75275663f --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtLogoutHandler.java @@ -0,0 +1,51 @@ +package com.sprint.mission.discodeit.security.jwt; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutHandler; + +import java.util.Arrays; +import java.util.Optional; + +@RequiredArgsConstructor +public class JwtLogoutHandler implements LogoutHandler { + + private final JwtService jwtService; + + // Spring Security가 로그아웃 시 호출 + @Override + @SneakyThrows + public void logout( + HttpServletRequest request, + HttpServletResponse response, + Authentication authentication + ) { + // 로그아웃 시 요청 refreshToken 값을 바탕으로 JWT 세션 및 토큰 쿠키 무효화 + resolveRefreshToken(request) + .ifPresent(refreshToken -> { + jwtService.invalidateJwtSession(refreshToken); + invalidateRefreshTokenCookie(response); + }); + } + + // 요청에서 refreshTokenCookie만 찾아 Optional로 리턴 + private Optional resolveRefreshToken(HttpServletRequest request) { + return Arrays.stream(request.getCookies()) + .filter(cookie -> cookie.getName().equals(JwtService.REFRESH_TOKEN_COOKIE_NAME)) + .findFirst() + .map(Cookie::getValue); + } + + // 기존 refreshToken 쿠키 제거 + private void invalidateRefreshTokenCookie(HttpServletResponse response) { + Cookie refreshTokenCookie = new Cookie(JwtService.REFRESH_TOKEN_COOKIE_NAME, ""); + + refreshTokenCookie.setMaxAge(0); + refreshTokenCookie.setHttpOnly(true); + response.addCookie(refreshTokenCookie); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtObject.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtObject.java new file mode 100644 index 000000000..1e6025f83 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtObject.java @@ -0,0 +1,16 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.sprint.mission.discodeit.dto.data.UserDto; + +import java.time.Instant; + +public record JwtObject( + Instant issueTime, + Instant expirationTime, + UserDto userDto, + String token +) { + public boolean isExpired() { + return expirationTime.isBefore(Instant.now()); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtService.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtService.java new file mode 100644 index 000000000..12d1f87a8 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtService.java @@ -0,0 +1,193 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSObject; +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jose.Payload; +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.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 java.text.ParseException; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@RequiredArgsConstructor +@Service +public class JwtService { + + public static final String REFRESH_TOKEN_COOKIE_NAME = "refresh_token"; + + @Value("${security.jwt.secret}") + private String secret; + + @Value("${security.jwt.access-token-validity-seconds}") + private long accessTokenValiditySeconds; + + @Value("${security.jwt.refresh-token-validity-seconds}") + private long refreshTokenValiditySeconds; + + private final UserRepository userRepository; + private final UserMapper userMapper; + private final ObjectMapper objectMapper; + private final JwtSessionRepository jwtSessionRepository; + private final JwtBlacklist jwtBlacklist; + + @Transactional + public JwtSession registerJwtSession(UserDto userDto) { + JwtObject accessJwtObject = generateJwtObject(userDto, accessTokenValiditySeconds); + JwtObject refreshJwtObject = generateJwtObject(userDto, refreshTokenValiditySeconds); + + JwtSession jwtSession = new JwtSession(userDto.id(), accessJwtObject.token(), + refreshJwtObject.token(), accessJwtObject.expirationTime()); + jwtSessionRepository.save(jwtSession); + + return jwtSession; + } + + public boolean validate(String token) { + boolean verified; + + try { + JWSVerifier verifier = new MACVerifier(secret); + JWSObject jwsObject = JWSObject.parse(token); + verified = jwsObject.verify(verifier); + + if (verified) { + JwtObject jwtObject = parse(token); + verified = !jwtObject.isExpired(); + } + + if (verified) { + verified = !jwtBlacklist.contains(token); + } + } catch (JOSEException | ParseException e) { + log.error(e.getMessage()); + verified = false; + } + return verified; + } + + public JwtObject parse(String token) { + try { + JWSObject jwsObject = JWSObject.parse(token); + Payload payload = jwsObject.getPayload(); + Map jsonObject = payload.toJSONObject(); + + return new JwtObject( + objectMapper.convertValue(jsonObject.get("iat"), Instant.class), + objectMapper.convertValue(jsonObject.get("exp"), Instant.class), + objectMapper.convertValue(jsonObject.get("userDto"), UserDto.class), + token + ); + } catch (ParseException e) { + log.error(e.getMessage()); + throw new DiscodeitException(ErrorCode.INVALID_TOKEN, Map.of("token", token), e); + } + } + + @Transactional + public JwtSession refreshJwtSession(String refreshToken) { + if (!validate(refreshToken)) { + throw new DiscodeitException(ErrorCode.INVALID_TOKEN, Map.of("refreshToken", refreshToken)); + } + JwtSession session = jwtSessionRepository.findByRefreshToken(refreshToken) + .orElseThrow(() -> new DiscodeitException( + ErrorCode.TOKEN_NOT_FOUND, + Map.of("refreshToken", refreshToken)) + ); + + UUID userId = parse(refreshToken).userDto().id(); + UserDto userDto = userRepository.findById(userId) + .map(userMapper::toDto) + .orElseThrow(() -> UserNotFoundException.withId(userId)); + + JwtObject accessJwtObject = generateJwtObject(userDto, accessTokenValiditySeconds); + JwtObject refreshJwtObject = generateJwtObject(userDto, refreshTokenValiditySeconds); + + session.update( + accessJwtObject.token(), + refreshJwtObject.token(), + accessJwtObject.expirationTime() + ); + + return session; + } + + @Transactional + public void invalidateJwtSession(String refreshToken) { + jwtSessionRepository.findByRefreshToken(refreshToken) + .ifPresent(this::invalidate); + } + + @Transactional + public void invalidateJwtSession(UUID userId) { + jwtSessionRepository.findByUserId(userId) + .ifPresent(this::invalidate); + } + + public JwtSession getJwtSession(String refreshToken) { + return jwtSessionRepository.findByRefreshToken(refreshToken) + .orElseThrow(() -> new DiscodeitException( + ErrorCode.TOKEN_NOT_FOUND, + Map.of("refreshToken", refreshToken)) + ); + } + + public List getActiveJwtSessions() { + return jwtSessionRepository.findAllByExpirationTimeAfter(Instant.now()); + } + + private JwtObject generateJwtObject(UserDto userDto, long tokenValiditySeconds) { + Instant issueTime = Instant.now(); + Instant expirationTime = issueTime.plus(Duration.ofSeconds(tokenValiditySeconds)); + + JWTClaimsSet claimSet = new JWTClaimsSet.Builder() + .subject(userDto.username()) + .claim("userDto", userDto) + .issueTime(new Date(issueTime.toEpochMilli())) + .expirationTime(new Date(expirationTime.toEpochMilli())) + .build(); + + JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256); + SignedJWT signedJWT = new SignedJWT(jwsHeader, claimSet); + + try { + signedJWT.sign(new MACSigner(secret)); + } catch (JOSEException e) { + log.error(e.getMessage()); + throw new DiscodeitException(ErrorCode.INVALID_TOKEN, e); + } + + String token = signedJWT.serialize(); + + return new JwtObject(issueTime, expirationTime, userDto, token); + } + + private void invalidate(JwtSession jwtSession) { + jwtSessionRepository.delete(jwtSession); + + if (!jwtSession.isExpired()) { + jwtBlacklist.put(jwtSession.getAccessToken(), jwtSession.getExpirationTime()); + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtSession.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtSession.java new file mode 100644 index 000000000..32af0a956 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtSession.java @@ -0,0 +1,47 @@ +package com.sprint.mission.discodeit.security.jwt; + +import com.sprint.mission.discodeit.entity.base.BaseUpdatableEntity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.Instant; +import java.util.UUID; + +@Getter +@Entity +@Table(name = "jwt_sessions") +@NoArgsConstructor +public class JwtSession extends BaseUpdatableEntity { + + @Column(columnDefinition = "uuid", updatable = false, nullable = false) + private UUID userId; + + @Column(columnDefinition = "varchar(512)", nullable = false, unique = true) + private String accessToken; + + @Column(columnDefinition = "varchar(512)", nullable = false, unique = true) + private String refreshToken; + + @Column(columnDefinition = "timestamp with time zone", nullable = false) + private Instant expirationTime; + + public JwtSession(UUID userId, String accessToken, String refreshToken, Instant expirationTime) { + this.userId = userId; + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.expirationTime = expirationTime; + } + + public void update(String accessToken, String refreshToken, Instant expirationTime) { + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.expirationTime = expirationTime; + } + + public boolean isExpired() { + return this.expirationTime.isBefore(Instant.now()); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtSessionRepository.java b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtSessionRepository.java new file mode 100644 index 000000000..5f3ef3a68 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/security/jwt/JwtSessionRepository.java @@ -0,0 +1,17 @@ +package com.sprint.mission.discodeit.security.jwt; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface JwtSessionRepository extends JpaRepository { + + Optional findByRefreshToken(String refreshToken); + + Optional findByUserId(UUID userId); + + List findAllByExpirationTimeAfter(Instant after); +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/AuthService.java b/src/main/java/com/sprint/mission/discodeit/service/AuthService.java index fcc2b1af0..1db9a47ad 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/AuthService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/AuthService.java @@ -1,8 +1,11 @@ package com.sprint.mission.discodeit.service; -import com.sprint.mission.discodeit.dto.request.LoginRequest; -import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.dto.data.UserDto; +import com.sprint.mission.discodeit.dto.request.RoleUpdateRequest; public interface AuthService { - User login(LoginRequest loginRequest); + + UserDto updateRole(RoleUpdateRequest request); + + UserDto initAdmin(); } diff --git a/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java b/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java index 77d8358b7..23836a446 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/BinaryContentService.java @@ -1,14 +1,17 @@ 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.BinaryContent; - import java.util.List; import java.util.UUID; public interface BinaryContentService { - BinaryContent create(BinaryContentCreateRequest request); - BinaryContent find(UUID binaryContentId); - List findAllByIdIn(List binaryContentIds); - void delete(UUID binaryContentId); + + BinaryContentDto create(BinaryContentCreateRequest request); + + BinaryContentDto find(UUID binaryContentId); + + List findAllByIdIn(List binaryContentIds); + + void delete(UUID binaryContentId); } diff --git a/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java b/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java index 6bcd0903b..a082c9ff9 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java @@ -4,17 +4,20 @@ 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 java.util.List; import java.util.UUID; public interface ChannelService { - Channel create(PublicChannelCreateRequest request); - Channel create(PrivateChannelCreateRequest request); - ChannelDto find(UUID channelId); - List findAllByUserId(UUID userId); - Channel update(UUID channelId, PublicChannelUpdateRequest request); - void delete(UUID channelId); -} + + 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 index fa517ef91..8ac5ee924 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/MessageService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/MessageService.java @@ -1,17 +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.entity.Message; - +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 { - Message create(MessageCreateRequest messageCreateRequest, List binaryContentCreateRequests); - Message find(UUID messageId); - List findAllByChannelId(UUID channelId); - Message update(UUID messageId, MessageUpdateRequest request); - void delete(UUID messageId); + + 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/ReadStatusService.java b/src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java index fcbc82f99..8b0c80a31 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/ReadStatusService.java @@ -1,16 +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 com.sprint.mission.discodeit.entity.ReadStatus; - import java.util.List; import java.util.UUID; public interface ReadStatusService { - ReadStatus create(ReadStatusCreateRequest request); - ReadStatus find(UUID readStatusId); - List findAllByUserId(UUID userId); - ReadStatus update(UUID readStatusId, ReadStatusUpdateRequest request); - void delete(UUID readStatusId); + + 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 index d824a7806..444118780 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/UserService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/UserService.java @@ -4,16 +4,21 @@ 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.User; - import java.util.List; import java.util.Optional; import java.util.UUID; public interface UserService { - User create(UserCreateRequest userCreateRequest, Optional profileCreateRequest); - UserDto find(UUID userId); - List findAll(); - User update(UUID userId, UserUpdateRequest userUpdateRequest, Optional profileCreateRequest); - void delete(UUID userId); + + 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/UserStatusService.java b/src/main/java/com/sprint/mission/discodeit/service/UserStatusService.java index 47058277f..3c5c55e6e 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/UserStatusService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/UserStatusService.java @@ -1,17 +1,22 @@ package com.sprint.mission.discodeit.service; +import com.sprint.mission.discodeit.dto.data.UserStatusDto; import com.sprint.mission.discodeit.dto.request.UserStatusCreateRequest; import com.sprint.mission.discodeit.dto.request.UserStatusUpdateRequest; -import com.sprint.mission.discodeit.entity.UserStatus; - import java.util.List; import java.util.UUID; public interface UserStatusService { - UserStatus create(UserStatusCreateRequest request); - UserStatus find(UUID userStatusId); - List findAll(); - UserStatus update(UUID userStatusId, UserStatusUpdateRequest request); - UserStatus updateByUserId(UUID userId, UserStatusUpdateRequest request); - void delete(UUID userStatusId); + + UserStatusDto create(UserStatusCreateRequest request); + + UserStatusDto find(UUID userStatusId); + + List findAll(); + + UserStatusDto update(UUID userStatusId, UserStatusUpdateRequest request); + + UserStatusDto updateByUserId(UUID userId, UserStatusUpdateRequest request); + + void delete(UUID userStatusId); } 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 index 38f67f1c0..ca64f9593 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicAuthService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicAuthService.java @@ -1,31 +1,67 @@ package com.sprint.mission.discodeit.service.basic; -import com.sprint.mission.discodeit.dto.request.LoginRequest; +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.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.mapper.UserMapper; import com.sprint.mission.discodeit.repository.UserRepository; +import com.sprint.mission.discodeit.security.jwt.JwtService; import com.sprint.mission.discodeit.service.AuthService; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +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; -import java.util.NoSuchElementException; - +@Slf4j @RequiredArgsConstructor @Service public class BasicAuthService implements AuthService { - private final UserRepository userRepository; - @Override - public User login(LoginRequest loginRequest) { - String username = loginRequest.username(); - String password = loginRequest.password(); + @Value("${discodeit.admin.username}") + private String username; + @Value("${discodeit.admin.password}") + private String password; + @Value("${discodeit.admin.email}") + private String email; + private final UserRepository userRepository; + private final UserMapper userMapper; + private final PasswordEncoder passwordEncoder; + private final JwtService jwtService; - User user = userRepository.findByUsername(username) - .orElseThrow(() -> new NoSuchElementException("User with username " + username + " not found")); + @PreAuthorize("hasRole('ADMIN')") + @Transactional + @Override + public UserDto updateRole(RoleUpdateRequest request) { + UUID userId = request.userId(); + User user = userRepository.findById(userId) + .orElseThrow(() -> UserNotFoundException.withId(userId)); + user.updateRole(request.newRole()); - if (!user.getPassword().equals(password)) { - throw new IllegalArgumentException("Wrong password"); - } + jwtService.invalidateJwtSession(user.getId()); + return userMapper.toDto(user); + } - return user; + @Transactional + @Override + public UserDto initAdmin() { + if (userRepository.existsByEmail(email) || userRepository.existsByUsername(username)) { + log.warn("Alredy admin exists."); + return null; } + + String encodedPassword = passwordEncoder.encode(password); + User admin = new User(username, email, encodedPassword, null); + admin.updateRole(Role.ADMIN); + userRepository.save(admin); + + UserDto adminDto = userMapper.toDto(admin); + log.info("Admin is initialized. {}", adminDto); + return adminDto; + } } 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 index 62426634a..bd50ce57d 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicBinaryContentService.java @@ -1,52 +1,80 @@ 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.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 lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - +import com.sprint.mission.discodeit.storage.BinaryContentStorage; import java.util.List; -import java.util.NoSuchElementException; import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +@Slf4j @RequiredArgsConstructor @Service public class BasicBinaryContentService implements BinaryContentService { - private final BinaryContentRepository binaryContentRepository; - - @Override - public BinaryContent create(BinaryContentCreateRequest request) { - String fileName = request.fileName(); - byte[] bytes = request.bytes(); - BinaryContent.ContentType contentType = request.contentType(); - BinaryContent binaryContent = new BinaryContent( - fileName, - (long) bytes.length, - contentType, - bytes - ); - return binaryContentRepository.save(binaryContent); - } - @Override - public BinaryContent find(UUID binaryContentId) { - return binaryContentRepository.findById(binaryContentId) - .orElseThrow(() -> new NoSuchElementException("BinaryContent with id " + binaryContentId + " not found")); - } + private final BinaryContentRepository binaryContentRepository; + private final BinaryContentMapper binaryContentMapper; + private final BinaryContentStorage binaryContentStorage; - @Override - public List findAllByIdIn(List binaryContentIds) { - return binaryContentRepository.findAllByIdIn(binaryContentIds).stream() - .toList(); - } + @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); + binaryContentStorage.put(binaryContent.getId(), 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; + } - @Override - public void delete(UUID binaryContentId) { - if (!binaryContentRepository.existsById(binaryContentId)) { - throw new NoSuchElementException("BinaryContent with id " + binaryContentId + " not found"); - } - binaryContentRepository.deleteById(binaryContentId); + @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); + } } 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 index 7beb6e237..1c6952110 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicChannelService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicChannelService.java @@ -6,117 +6,117 @@ 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.Message; 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.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import lombok.extern.slf4j.Slf4j; -import java.time.Instant; -import java.util.*; - +@Slf4j @Service @RequiredArgsConstructor public class BasicChannelService implements ChannelService { - private final ChannelRepository channelRepository; - - private final ReadStatusRepository readStatusRepository; - private final MessageRepository messageRepository; - - @Override - public Channel create(PublicChannelCreateRequest request) { - String name = request.name(); - String description = request.description(); - Channel channel = new Channel(ChannelType.PUBLIC, name, description); - - return channelRepository.save(channel); - } - @Override - public Channel create(PrivateChannelCreateRequest request) { - Channel channel = new Channel(ChannelType.PRIVATE, null, null); - Channel createdChannel = channelRepository.save(channel); - - request.participantIds().stream() - .map(userId -> new ReadStatus(userId, createdChannel.getId(), Instant.MIN)) - .forEach(readStatusRepository::save); - - return createdChannel; + private final ChannelRepository channelRepository; + // + private final ReadStatusRepository readStatusRepository; + private final MessageRepository messageRepository; + private final UserRepository userRepository; + private final ChannelMapper channelMapper; + + @PreAuthorize("hasRole('CHANNEL_MANAGER')") + @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); + } + + @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())) + .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) + @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')") + @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); } - - @Override - public ChannelDto find(UUID channelId) { - return channelRepository.findById(channelId) - .map(this::toDto) - .orElseThrow(() -> new NoSuchElementException("Channel with id " + channelId + " not found")); + channel.update(newName, newDescription); + log.info("채널 수정 완료: id={}, name={}", channelId, channel.getName()); + return channelMapper.toDto(channel); + } + + @PreAuthorize("hasRole('CHANNEL_MANAGER')") + @Transactional + @Override + public void delete(UUID channelId) { + log.debug("채널 삭제 시작: id={}", channelId); + if (!channelRepository.existsById(channelId)) { + throw ChannelNotFoundException.withId(channelId); } - @Override - public List findAllByUserId(UUID userId) { - List mySubscribedChannelIds = readStatusRepository.findAllByUserId(userId).stream() - .map(ReadStatus::getChannelId) - .toList(); - - return channelRepository.findAll().stream() - .filter(channel -> - channel.getType().equals(ChannelType.PUBLIC) - || mySubscribedChannelIds.contains(channel.getId()) - ) - .map(this::toDto) - .toList(); - } + messageRepository.deleteAllByChannelId(channelId); + readStatusRepository.deleteAllByChannelId(channelId); - @Override - public Channel update(UUID channelId, PublicChannelUpdateRequest request) { - String newName = request.newName(); - String newDescription = request.newDescription(); - Channel channel = channelRepository.findById(channelId) - .orElseThrow(() -> new NoSuchElementException("Channel with id " + channelId + " not found")); - if (channel.getType().equals(ChannelType.PRIVATE)) { - throw new IllegalArgumentException("Private channel cannot be updated"); - } - channel.update(newName, newDescription); - return channelRepository.save(channel); - } - - @Override - public void delete(UUID channelId) { - Channel channel = channelRepository.findById(channelId) - .orElseThrow(() -> new NoSuchElementException("Channel with id " + channelId + " not found")); - - messageRepository.deleteAllByChannelId(channel.getId()); - readStatusRepository.deleteAllByChannelId(channel.getId()); - - channelRepository.deleteById(channelId); - } - - private ChannelDto toDto(Channel channel) { - Instant lastMessageAt = messageRepository.findAllByChannelId(channel.getId()) - .stream() - .sorted(Comparator.comparing(Message::getCreatedAt).reversed()) - .map(Message::getCreatedAt) - .limit(1) - .findFirst() - .orElse(Instant.MIN); - - List participantIds = new ArrayList<>(); - if (channel.getType().equals(ChannelType.PRIVATE)) { - readStatusRepository.findAllByChannelId(channel.getId()) - .stream() - .map(ReadStatus::getUserId) - .forEach(participantIds::add); - } - - return new ChannelDto( - channel.getId(), - channel.getType(), - channel.getName(), - channel.getDescription(), - participantIds, - lastMessageAt - ); - } + 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 index e0ce057c9..5bb604f15 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicMessageService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicMessageService.java @@ -1,95 +1,138 @@ 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.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 lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.time.Instant; import java.util.List; -import java.util.NoSuchElementException; import java.util.Optional; import java.util.UUID; +import lombok.RequiredArgsConstructor; +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 BinaryContentRepository binaryContentRepository; - - @Override - public Message create(MessageCreateRequest messageCreateRequest, List binaryContentCreateRequests) { - UUID channelId = messageCreateRequest.channelId(); - UUID authorId = messageCreateRequest.authorId(); - - if (!channelRepository.existsById(channelId)) { - throw new NoSuchElementException("Channel with id " + channelId + " does not exist"); - } - if (!userRepository.existsById(authorId)) { - throw new NoSuchElementException("Author with id " + authorId + " does not exist"); - } - - List attachmentIds = binaryContentCreateRequests.stream() - .map(attachmentRequest -> { - String fileName = attachmentRequest.fileName(); - BinaryContent.ContentType contentType = attachmentRequest.contentType(); - byte[] bytes = attachmentRequest.bytes(); - - BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, contentType, bytes); - BinaryContent createdBinaryContent = binaryContentRepository.save(binaryContent); - return createdBinaryContent.getId(); - }) - .toList(); - - String content = messageCreateRequest.content(); - Message message = new Message( - content, - channelId, - authorId, - attachmentIds - ); - return messageRepository.save(message); - } - @Override - public Message find(UUID messageId) { - return messageRepository.findById(messageId) - .orElseThrow(() -> new NoSuchElementException("Message with id " + messageId + " not found")); - } + 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; - @Override - public List findAllByChannelId(UUID channelId) { - return messageRepository.findAllByChannelId(channelId).stream() - .toList(); - } + @Transactional + @Override + public MessageDto create(MessageCreateRequest messageCreateRequest, + List binaryContentCreateRequests) { + log.debug("메시지 생성 시작: request={}", messageCreateRequest); + UUID channelId = messageCreateRequest.channelId(); + UUID authorId = messageCreateRequest.authorId(); - @Override - public Message update(UUID messageId, MessageUpdateRequest request) { - String newContent = request.newContent(); - Message message = messageRepository.findById(messageId) - .orElseThrow(() -> new NoSuchElementException("Message with id " + messageId + " not found")); - message.update(newContent); - return messageRepository.save(message); + 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); + binaryContentStorage.put(binaryContent.getId(), bytes); + return binaryContent; + }) + .toList(); + + String content = messageCreateRequest.content(); + Message message = new Message( + content, + channel, + author, + attachments + ); + + messageRepository.save(message); + 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(); } - @Override - public void delete(UUID messageId) { - Message message = messageRepository.findById(messageId) - .orElseThrow(() -> new NoSuchElementException("Message with id " + messageId + " not found")); + 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.getAttachmentIds() - .forEach(binaryContentRepository::deleteById); + message.update(request.newContent()); + log.info("메시지 수정 완료: id={}, channelId={}", messageId, message.getChannel().getId()); + return messageMapper.toDto(message); + } - messageRepository.deleteById(messageId); + @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/BasicReadStatusService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicReadStatusService.java new file mode 100644 index 000000000..d5787246c --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicReadStatusService.java @@ -0,0 +1,107 @@ +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.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); + 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()); + + 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 index c9e37d205..4f19b22e9 100644 --- a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserService.java +++ b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserService.java @@ -6,134 +6,161 @@ 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.entity.UserStatus; +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.repository.UserStatusRepository; +import com.sprint.mission.discodeit.security.jwt.JwtService; +import com.sprint.mission.discodeit.security.jwt.JwtSession; import com.sprint.mission.discodeit.service.UserService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.time.Instant; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; import java.util.List; -import java.util.NoSuchElementException; import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +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; -@Service +@Slf4j @RequiredArgsConstructor +@Service public class BasicUserService implements UserService { - private final UserRepository userRepository; - // - private final BinaryContentRepository binaryContentRepository; - private final UserStatusRepository userStatusRepository; + private final UserRepository userRepository; + private final UserMapper userMapper; + private final BinaryContentRepository binaryContentRepository; + private final BinaryContentStorage binaryContentStorage; + private final PasswordEncoder passwordEncoder; + private final JwtService jwtService; + + @Transactional @Override - public User create(UserCreateRequest userCreateRequest, Optional optionalProfileCreateRequest) { + public UserDto create(UserCreateRequest userCreateRequest, + Optional optionalProfileCreateRequest) { + log.debug("사용자 생성 시작: {}", userCreateRequest); + String username = userCreateRequest.username(); String email = userCreateRequest.email(); if (userRepository.existsByEmail(email)) { - throw new IllegalArgumentException("User with email " + email + " already exists"); + throw UserAlreadyExistsException.withEmail(email); } if (userRepository.existsByUsername(username)) { - throw new IllegalArgumentException("User with username " + username + " already exists"); + throw UserAlreadyExistsException.withUsername(username); } - UUID nullableProfileId = optionalProfileCreateRequest + BinaryContent nullableProfile = optionalProfileCreateRequest .map(profileRequest -> { String fileName = profileRequest.fileName(); - BinaryContent.ContentType contentType = profileRequest.contentType(); + String contentType = profileRequest.contentType(); byte[] bytes = profileRequest.bytes(); - BinaryContent binaryContent = new BinaryContent(fileName, (long)bytes.length, contentType, bytes); - return binaryContentRepository.save(binaryContent).getId(); + BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, + contentType); + binaryContentRepository.save(binaryContent); + binaryContentStorage.put(binaryContent.getId(), bytes); + return binaryContent; }) .orElse(null); String password = userCreateRequest.password(); - User user = new User(username, email, password, nullableProfileId); - User createdUser = userRepository.save(user); + String hashedPassword = passwordEncoder.encode(password); + User user = new User(username, email, hashedPassword, nullableProfile); - Instant now = Instant.now(); - UserStatus userStatus = new UserStatus(createdUser.getId(), now); - userStatusRepository.save(userStatus); - - return createdUser; + userRepository.save(user); + log.info("사용자 생성 완료: id={}, username={}", user.getId(), username); + return userMapper.toDto(user); } + @Transactional(readOnly = true) @Override public UserDto find(UUID userId) { - return userRepository.findById(userId) - .map(this::toDto) - .orElseThrow(() -> new NoSuchElementException("User with id " + userId + " not found")); + log.debug("사용자 조회 시작: id={}", userId); + UserDto userDto = userRepository.findById(userId) + .map(userMapper::toDto) + .orElseThrow(() -> UserNotFoundException.withId(userId)); + log.info("사용자 조회 완료: id={}", userId); + return userDto; } @Override public List findAll() { - return userRepository.findAll() + log.debug("모든 사용자 조회 시작"); + Set onlineUserIds = jwtService.getActiveJwtSessions().stream() + .map(JwtSession::getUserId) + .collect(Collectors.toSet()); + + List userDtos = userRepository.findAllWithProfile() .stream() - .map(this::toDto) + .map(user -> userMapper.toDto(user, onlineUserIds.contains(user.getId()))) .toList(); + log.info("모든 사용자 조회 완료: 총 {}명", userDtos.size()); + return userDtos; } + @PreAuthorize("hasRole('ADMIN') or principal.userDto.id == #userId") + @Transactional @Override - public User update(UUID userId, UserUpdateRequest userUpdateRequest, Optional optionalProfileCreateRequest) { + public UserDto update(UUID userId, UserUpdateRequest userUpdateRequest, + Optional optionalProfileCreateRequest) { + log.debug("사용자 수정 시작: id={}, request={}", userId, userUpdateRequest); + User user = userRepository.findById(userId) - .orElseThrow(() -> new NoSuchElementException("User with id " + userId + " not found")); + .orElseThrow(() -> { + UserNotFoundException exception = UserNotFoundException.withId(userId); + return exception; + }); String newUsername = userUpdateRequest.newUsername(); String newEmail = userUpdateRequest.newEmail(); + if (userRepository.existsByEmail(newEmail)) { - throw new IllegalArgumentException("User with email " + newEmail + " already exists"); + throw UserAlreadyExistsException.withEmail(newEmail); } + if (userRepository.existsByUsername(newUsername)) { - throw new IllegalArgumentException("User with username " + newUsername + " already exists"); + throw UserAlreadyExistsException.withUsername(newUsername); } - UUID nullableProfileId = optionalProfileCreateRequest + BinaryContent nullableProfile = optionalProfileCreateRequest .map(profileRequest -> { - Optional.ofNullable(user.getProfileId()) - .ifPresent(binaryContentRepository::deleteById); String fileName = profileRequest.fileName(); - BinaryContent.ContentType contentType = profileRequest.contentType(); + String contentType = profileRequest.contentType(); byte[] bytes = profileRequest.bytes(); - BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, contentType, bytes); - return binaryContentRepository.save(binaryContent).getId(); + BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, + contentType); + binaryContentRepository.save(binaryContent); + binaryContentStorage.put(binaryContent.getId(), bytes); + return binaryContent; }) .orElse(null); String newPassword = userUpdateRequest.newPassword(); - user.update(newUsername, newEmail, newPassword, nullableProfileId); + String hashedNewPassword = Optional.ofNullable(newPassword).map(passwordEncoder::encode) + .orElse(null); + user.update(newUsername, newEmail, hashedNewPassword, nullableProfile); - return userRepository.save(user); + log.info("사용자 수정 완료: id={}", userId); + return userMapper.toDto(user); } + @PreAuthorize("hasRole('ADMIN') or principal.userDto.id == #userId") + @Transactional @Override public void delete(UUID userId) { - User user = userRepository.findById(userId) - .orElseThrow(() -> new NoSuchElementException("User with id " + userId + " not found")); + log.debug("사용자 삭제 시작: id={}", userId); - Optional.ofNullable(user.getProfileId()) - .ifPresent(binaryContentRepository::deleteById); - userStatusRepository.deleteByUserId(userId); + if (!userRepository.existsById(userId)) { + throw UserNotFoundException.withId(userId); + } userRepository.deleteById(userId); - } - - private UserDto toDto(User user) { - Boolean online = userStatusRepository.findByUserId(user.getId()) - .map(UserStatus::isOnline) - .orElse(null); - - return new UserDto( - user.getId(), - user.getCreatedAt(), - user.getUpdatedAt(), - user.getUsername(), - user.getEmail(), - user.getProfileId(), - online - ); + log.info("사용자 삭제 완료: id={}", userId); } } diff --git a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserStatusService.java b/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserStatusService.java deleted file mode 100644 index 34f3d7151..000000000 --- a/src/main/java/com/sprint/mission/discodeit/service/basic/BasicUserStatusService.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.sprint.mission.discodeit.service.basic; - -import com.sprint.mission.discodeit.dto.request.UserStatusCreateRequest; -import com.sprint.mission.discodeit.dto.request.UserStatusUpdateRequest; -import com.sprint.mission.discodeit.entity.UserStatus; -import com.sprint.mission.discodeit.repository.UserRepository; -import com.sprint.mission.discodeit.repository.UserStatusRepository; -import com.sprint.mission.discodeit.service.UserStatusService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.time.Instant; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.UUID; - -@Service -@RequiredArgsConstructor -public class BasicUserStatusService implements UserStatusService { - private final UserStatusRepository userStatusRepository; - private final UserRepository userRepository; - - @Override - public UserStatus create(UserStatusCreateRequest request) { - UUID userId = request.userId(); - - if (!userRepository.existsById(userId)) { - throw new NoSuchElementException("User with id " + userId + " does not exist"); - } - if (userStatusRepository.findByUserId(userId).isPresent()) { - throw new IllegalArgumentException("UserStatus with id " + userId + " already exists"); - } - - Instant lastActiveAt = request.lastActiveAt(); - UserStatus userStatus = new UserStatus(userId, lastActiveAt); - return userStatusRepository.save(userStatus); - } - - @Override - public UserStatus find(UUID userStatusId) { - return userStatusRepository.findById(userStatusId) - .orElseThrow(() -> new NoSuchElementException("UserStatus with id " + userStatusId + " not found")); - } - - @Override - public List findAll() { - return userStatusRepository.findAll().stream() - .toList(); - } - - @Override - public UserStatus update(UUID userStatusId, UserStatusUpdateRequest request) { - Instant newLastActiveAt = request.newLastActiveAt(); - - UserStatus userStatus = userStatusRepository.findById(userStatusId) - .orElseThrow(() -> new NoSuchElementException("UserStatus with id " + userStatusId + " not found")); - userStatus.update(newLastActiveAt); - - return userStatusRepository.save(userStatus); - } - - @Override - public UserStatus updateByUserId(UUID userId, UserStatusUpdateRequest request) { - Instant newLastActiveAt = request.newLastActiveAt(); - - UserStatus userStatus = userStatusRepository.findByUserId(userId) - .orElseThrow(() -> new NoSuchElementException("UserStatus with userId " + userId + " not found")); - userStatus.update(newLastActiveAt); - - return userStatusRepository.save(userStatus); - } - - @Override - public void delete(UUID userStatusId) { - if (!userStatusRepository.existsById(userStatusId)) { - throw new NoSuchElementException("UserStatus with id " + userStatusId + " not found"); - } - userStatusRepository.deleteById(userStatusId); - } -} 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..8922903c0 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/storage/local/LocalBinaryContentStorage.java @@ -0,0 +1,89 @@ +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); + } catch (IOException e) { + throw new RuntimeException(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..31b4dc0f3 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/storage/s3/S3BinaryContentStorage.java @@ -0,0 +1,151 @@ +package com.sprint.mission.discodeit.storage.s3; + +import com.sprint.mission.discodeit.dto.data.BinaryContentDto; +import com.sprint.mission.discodeit.storage.BinaryContentStorage; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.time.Duration; +import java.util.NoSuchElementException; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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; + + @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 + ) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.region = region; + this.bucket = bucket; + } + + @Override + public UUID put(UUID binaryContentId, byte[] bytes) { + String key = binaryContentId.toString(); + try { + 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 new RuntimeException("S3에 파일 업로드 실패: " + key, 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(); + } +} \ 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..7b1addb62 --- /dev/null +++ b/src/main/resources/application-dev.yaml @@ -0,0 +1,27 @@ +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 \ 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 index 5ddfbb11a..1a5d18f65 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -1,8 +1,67 @@ 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: - repository: - type: file # jcf | file - file-directory: .discodeit \ No newline at end of file + 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} + +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 000000000..852a0869c Binary files /dev/null and b/src/main/resources/fe_bundle_1.2.3.zip differ 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..347b8c25e --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,111 @@ +-- 테이블 +-- 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, + file_name varchar(255) NOT NULL, + size bigint NOT NULL, + content_type varchar(100) NOT NULL +-- ,bytes bytea 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, + 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-COLcXNzv.js b/src/main/resources/static/assets/index-COLcXNzv.js new file mode 100644 index 000000000..af587fd74 --- /dev/null +++ b/src/main/resources/static/assets/index-COLcXNzv.js @@ -0,0 +1,1338 @@ +var Cg=Object.defineProperty;var Eg=(r,i,s)=>i in r?Cg(r,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[i]=s;var uf=(r,i,s)=>Eg(r,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 p of d.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).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 jg(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ca={exports:{}},xo={},Ea={exports:{}},pe={};/** + * @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 Ag(){if(cf)return pe;cf=1;var r=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"),p=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),j=Symbol.iterator;function R(k){return k===null||typeof k!="object"?null:(k=j&&k[j]||k["@@iterator"],typeof k=="function"?k:null)}var L={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T=Object.assign,N={};function _(k,D,ae){this.props=k,this.context=D,this.refs=N,this.updater=ae||L}_.prototype.isReactComponent={},_.prototype.setState=function(k,D){if(typeof k!="object"&&typeof k!="function"&&k!=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,k,D,"setState")},_.prototype.forceUpdate=function(k){this.updater.enqueueForceUpdate(this,k,"forceUpdate")};function V(){}V.prototype=_.prototype;function U(k,D,ae){this.props=k,this.context=D,this.refs=N,this.updater=ae||L}var B=U.prototype=new V;B.constructor=U,T(B,_.prototype),B.isPureReactComponent=!0;var W=Array.isArray,I=Object.prototype.hasOwnProperty,M={current:null},H={key:!0,ref:!0,__self:!0,__source:!0};function ie(k,D,ae){var ce,he={},fe=null,ke=null;if(D!=null)for(ce in D.ref!==void 0&&(ke=D.ref),D.key!==void 0&&(fe=""+D.key),D)I.call(D,ce)&&!H.hasOwnProperty(ce)&&(he[ce]=D[ce]);var ye=arguments.length-2;if(ye===1)he.children=ae;else if(1>>1,D=q[k];if(0>>1;kc(he,Q))fec(ke,he)?(q[k]=ke,q[fe]=Q,k=fe):(q[k]=he,q[ce]=Q,k=ce);else if(fec(ke,Q))q[k]=ke,q[fe]=Q,k=fe;else break e}}return ee}function c(q,ee){var Q=q.sortIndex-ee.sortIndex;return Q!==0?Q:q.id-ee.id}if(typeof performance=="object"&&typeof performance.now=="function"){var d=performance;r.unstable_now=function(){return d.now()}}else{var p=Date,m=p.now();r.unstable_now=function(){return p.now()-m}}var w=[],v=[],S=1,j=null,R=3,L=!1,T=!1,N=!1,_=typeof setTimeout=="function"?setTimeout:null,V=typeof clearTimeout=="function"?clearTimeout:null,U=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function B(q){for(var ee=s(v);ee!==null;){if(ee.callback===null)l(v);else if(ee.startTime<=q)l(v),ee.sortIndex=ee.expirationTime,i(w,ee);else break;ee=s(v)}}function W(q){if(N=!1,B(q),!T)if(s(w)!==null)T=!0,ge(I);else{var ee=s(v);ee!==null&&Ee(W,ee.startTime-q)}}function I(q,ee){T=!1,N&&(N=!1,V(ie),ie=-1),L=!0;var Q=R;try{for(B(ee),j=s(w);j!==null&&(!(j.expirationTime>ee)||q&&!ot());){var k=j.callback;if(typeof k=="function"){j.callback=null,R=j.priorityLevel;var D=k(j.expirationTime<=ee);ee=r.unstable_now(),typeof D=="function"?j.callback=D:j===s(w)&&l(w),B(ee)}else l(w);j=s(w)}if(j!==null)var ae=!0;else{var ce=s(v);ce!==null&&Ee(W,ce.startTime-ee),ae=!1}return ae}finally{j=null,R=Q,L=!1}}var M=!1,H=null,ie=-1,ve=5,Oe=-1;function ot(){return!(r.unstable_now()-Oeq||125k?(q.sortIndex=Q,i(v,q),s(w)===null&&q===s(v)&&(N?(V(ie),ie=-1):N=!0,Ee(W,Q-k))):(q.sortIndex=D,i(w,q),T||L||(T=!0,ge(I))),q},r.unstable_shouldYield=ot,r.unstable_wrapCallback=function(q){var ee=R;return function(){var Q=R;R=ee;try{return q.apply(this,arguments)}finally{R=Q}}}}(Ra)),Ra}var mf;function _g(){return mf||(mf=1,Aa.exports=Tg()),Aa.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 gf;function Ng(){if(gf)return ft;gf=1;var r=ou(),i=_g();function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),w=Object.prototype.hasOwnProperty,v=/^[: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 R(e){return w.call(j,e)?!0:w.call(S,e)?!1:v.test(e)?j[e]=!0:(S[e]=!0,!1)}function L(e,t,n,o){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function T(e,t,n,o){if(t===null||typeof t>"u"||L(e,t,n,o))return!0;if(o)return!1;if(n!==null)switch(n.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 N(e,t,n,o,a,u,f){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=u,this.removeEmptyString=f}var _={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){_[e]=new N(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 N(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){_[e]=new N(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){_[e]=new N(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 N(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){_[e]=new N(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){_[e]=new N(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){_[e]=new N(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){_[e]=new N(e,5,!1,e.toLowerCase(),null,!1,!1)});var V=/[\-:]([a-z])/g;function U(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(V,U);_[t]=new N(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(V,U);_[t]=new N(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(V,U);_[t]=new N(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){_[e]=new N(e,1,!1,e.toLowerCase(),null,!1,!1)}),_.xlinkHref=new N("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){_[e]=new N(e,1,!1,e.toLowerCase(),null,!0,!0)});function B(e,t,n,o){var a=_.hasOwnProperty(t)?_[t]:null;(a!==null?a.type!==0:o||!(2g||a[f]!==u[g]){var y=` +`+a[f].replace(" at new "," at ");return e.displayName&&y.includes("")&&(y=y.replace("",e.displayName)),y}while(1<=f&&0<=g);break}}}finally{ae=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?D(e):""}function he(e){switch(e.tag){case 5:return D(e.type);case 16:return D("Lazy");case 13:return D("Suspense");case 19:return D("SuspenseList");case 0:case 2:case 15:return e=ce(e.type,!1),e;case 11:return e=ce(e.type.render,!1),e;case 1:return e=ce(e.type,!0),e;default:return""}}function fe(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 H:return"Fragment";case M:return"Portal";case ve:return"Profiler";case ie:return"StrictMode";case le:return"Suspense";case me:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ot:return(e.displayName||"Context")+".Consumer";case Oe:return(e._context.displayName||"Context")+".Provider";case ne:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Re:return t=e.displayName||null,t!==null?t:fe(e.type)||"Memo";case ge:t=e._payload,e=e._init;try{return fe(e(t))}catch{}}return null}function ke(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 fe(t);case 8:return t===ie?"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 we(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Qe(e){var t=we(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,u=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(f){o=""+f,u.call(this,f)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return o},setValue:function(f){o=""+f},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function qt(e){e._valueTracker||(e._valueTracker=Qe(e))}function Tt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),o="";return e&&(o=we(e)?e.checked?"true":"false":e.value),e=o,e!==n?(t.setValue(e),!0):!1}function Bo(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 _s(e,t){var n=t.checked;return Q({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function mu(e,t){var n=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;n=ye(t.value!=null?t.value:n),e._wrapperState={initialChecked:o,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function gu(e,t){t=t.checked,t!=null&&B(e,"checked",t,!1)}function Ns(e,t){gu(e,t);var n=ye(t.value),o=t.type;if(n!=null)o==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Os(e,t.type,n):t.hasOwnProperty("defaultValue")&&Os(e,t.type,ye(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function yu(e,t,n){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,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Os(e,t,n){(t!=="number"||Bo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Mr=Array.isArray;function Qn(e,t,n,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Fo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Lr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ir={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},Ph=["Webkit","ms","Moz","O"];Object.keys(Ir).forEach(function(e){Ph.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ir[t]=Ir[e]})});function Cu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ir.hasOwnProperty(e)&&Ir[e]?(""+t).trim():t+"px"}function Eu(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var o=n.indexOf("--")===0,a=Cu(n,t[n],o);n==="float"&&(n="cssFloat"),o?e.setProperty(n,a):e[n]=a}}var Th=Q({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 Is(e,t){if(t){if(Th[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 Ds(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 zs=null;function $s(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Bs=null,Gn=null,Kn=null;function ju(e){if(e=ro(e)){if(typeof Bs!="function")throw Error(s(280));var t=e.stateNode;t&&(t=ui(t),Bs(e.stateNode,e.type,t))}}function Au(e){Gn?Kn?Kn.push(e):Kn=[e]:Gn=e}function Ru(){if(Gn){var e=Gn,t=Kn;if(Kn=Gn=null,ju(e),t)for(e=0;e>>=0,e===0?32:31-(Fh(e)/bh|0)|0}var Wo=64,qo=4194304;function Br(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 Yo(e,t){var n=e.pendingLanes;if(n===0)return 0;var o=0,a=e.suspendedLanes,u=e.pingedLanes,f=n&268435455;if(f!==0){var g=f&~a;g!==0?o=Br(g):(u&=f,u!==0&&(o=Br(u)))}else f=n&~a,f!==0?o=Br(f):u!==0&&(o=Br(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|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0n;n++)t.push(e);return t}function Fr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-_t(t),e[t]=n}function Wh(e,t){var n=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=Qr),tc=" ",nc=!1;function rc(e,t){switch(e){case"keyup":return xm.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function oc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Zn=!1;function Sm(e,t){switch(e){case"compositionend":return oc(t);case"keypress":return t.which!==32?null:(nc=!0,tc);case"textInput":return e=t.data,e===tc&&nc?null:e;default:return null}}function km(e,t){if(Zn)return e==="compositionend"||!rl&&rc(e,t)?(e=Gu(),Jo=Xs=an=null,Zn=!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:n,offset:t-e};e=o}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=dc(n)}}function pc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?pc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function hc(){for(var e=window,t=Bo();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Bo(e.document)}return t}function sl(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 Nm(e){var t=hc(),n=e.focusedElem,o=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&pc(n.ownerDocument.documentElement,n)){if(o!==null&&sl(n)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=n.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=fc(n,u);var f=fc(n,o);a&&f&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==f.node||e.focusOffset!==f.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),u>o?(e.addRange(t),e.extend(f.node,f.offset)):(t.setEnd(f.node,f.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,er=null,ll=null,Jr=null,al=!1;function mc(e,t,n){var o=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;al||er==null||er!==Bo(o)||(o=er,"selectionStart"in o&&sl(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}),Jr&&Xr(Jr,o)||(Jr=o,o=si(ll,"onSelect"),0ir||(e.current=wl[ir],wl[ir]=null,ir--)}function Ae(e,t){ir++,wl[ir]=e.current,e.current=t}var fn={},Xe=dn(fn),lt=dn(!1),Tn=fn;function sr(e,t){var n=e.type.contextTypes;if(!n)return fn;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},u;for(u in n)a[u]=t[u];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function at(e){return e=e.childContextTypes,e!=null}function ci(){Te(lt),Te(Xe)}function _c(e,t,n){if(Xe.current!==fn)throw Error(s(168));Ae(Xe,t),Ae(lt,n)}function Nc(e,t,n){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return n;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(s(108,ke(e)||"Unknown",a));return Q({},n,o)}function di(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||fn,Tn=Xe.current,Ae(Xe,e),Ae(lt,lt.current),!0}function Oc(e,t,n){var o=e.stateNode;if(!o)throw Error(s(169));n?(e=Nc(e,t,Tn),o.__reactInternalMemoizedMergedChildContext=e,Te(lt),Te(Xe),Ae(Xe,e)):Te(lt),Ae(lt,n)}var Qt=null,fi=!1,Sl=!1;function Mc(e){Qt===null?Qt=[e]:Qt.push(e)}function Hm(e){fi=!0,Mc(e)}function pn(){if(!Sl&&Qt!==null){Sl=!0;var e=0,t=je;try{var n=Qt;for(je=1;e>=f,a-=f,Gt=1<<32-_t(t)+a|n<se?(qe=oe,oe=null):qe=oe.sibling;var Se=z(E,oe,A[se],b);if(Se===null){oe===null&&(oe=qe);break}e&&oe&&Se.alternate===null&&t(E,oe),x=u(Se,x,se),re===null?te=Se:re.sibling=Se,re=Se,oe=qe}if(se===A.length)return n(E,oe),Ne&&Nn(E,se),te;if(oe===null){for(;sese?(qe=oe,oe=null):qe=oe.sibling;var kn=z(E,oe,Se.value,b);if(kn===null){oe===null&&(oe=qe);break}e&&oe&&kn.alternate===null&&t(E,oe),x=u(kn,x,se),re===null?te=kn:re.sibling=kn,re=kn,oe=qe}if(Se.done)return n(E,oe),Ne&&Nn(E,se),te;if(oe===null){for(;!Se.done;se++,Se=A.next())Se=F(E,Se.value,b),Se!==null&&(x=u(Se,x,se),re===null?te=Se:re.sibling=Se,re=Se);return Ne&&Nn(E,se),te}for(oe=o(E,oe);!Se.done;se++,Se=A.next())Se=G(oe,E,se,Se.value,b),Se!==null&&(e&&Se.alternate!==null&&oe.delete(Se.key===null?se:Se.key),x=u(Se,x,se),re===null?te=Se:re.sibling=Se,re=Se);return e&&oe.forEach(function(kg){return t(E,kg)}),Ne&&Nn(E,se),te}function ze(E,x,A,b){if(typeof A=="object"&&A!==null&&A.type===H&&A.key===null&&(A=A.props.children),typeof A=="object"&&A!==null){switch(A.$$typeof){case I:e:{for(var te=A.key,re=x;re!==null;){if(re.key===te){if(te=A.type,te===H){if(re.tag===7){n(E,re.sibling),x=a(re,A.props.children),x.return=E,E=x;break e}}else if(re.elementType===te||typeof te=="object"&&te!==null&&te.$$typeof===ge&&Bc(te)===re.type){n(E,re.sibling),x=a(re,A.props),x.ref=oo(E,re,A),x.return=E,E=x;break e}n(E,re);break}else t(E,re);re=re.sibling}A.type===H?(x=Bn(A.props.children,E.mode,b,A.key),x.return=E,E=x):(b=Fi(A.type,A.key,A.props,null,E.mode,b),b.ref=oo(E,x,A),b.return=E,E=b)}return f(E);case M:e:{for(re=A.key;x!==null;){if(x.key===re)if(x.tag===4&&x.stateNode.containerInfo===A.containerInfo&&x.stateNode.implementation===A.implementation){n(E,x.sibling),x=a(x,A.children||[]),x.return=E,E=x;break e}else{n(E,x);break}else t(E,x);x=x.sibling}x=va(A,E.mode,b),x.return=E,E=x}return f(E);case ge:return re=A._init,ze(E,x,re(A._payload),b)}if(Mr(A))return J(E,x,A,b);if(ee(A))return Z(E,x,A,b);gi(E,A)}return typeof A=="string"&&A!==""||typeof A=="number"?(A=""+A,x!==null&&x.tag===6?(n(E,x.sibling),x=a(x,A),x.return=E,E=x):(n(E,x),x=ya(A,E.mode,b),x.return=E,E=x),f(E)):n(E,x)}return ze}var cr=Fc(!0),bc=Fc(!1),yi=dn(null),vi=null,dr=null,Rl=null;function Pl(){Rl=dr=vi=null}function Tl(e){var t=yi.current;Te(yi),e._currentValue=t}function _l(e,t,n){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===n)break;e=e.return}}function fr(e,t){vi=e,Rl=dr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ut=!0),e.firstContext=null)}function Et(e){var t=e._currentValue;if(Rl!==e)if(e={context:e,memoizedValue:t,next:null},dr===null){if(vi===null)throw Error(s(308));dr=e,vi.dependencies={lanes:0,firstContext:e}}else dr=dr.next=e;return t}var On=null;function Nl(e){On===null?On=[e]:On.push(e)}function Uc(e,t,n,o){var a=t.interleaved;return a===null?(n.next=n,Nl(t)):(n.next=a.next,a.next=n),t.interleaved=n,Xt(e,o)}function Xt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var hn=!1;function Ol(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Hc(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 Jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function mn(e,t,n){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,xe&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Xt(e,n)}return a=o.interleaved,a===null?(t.next=t,Nl(o)):(t.next=a.next,a.next=t),o.interleaved=t,Xt(e,n)}function xi(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,qs(e,n)}}function Vc(e,t){var n=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,n===o)){var a=null,u=null;if(n=n.firstBaseUpdate,n!==null){do{var f={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};u===null?a=u=f:u=u.next=f,n=n.next}while(n!==null);u===null?a=u=t:u=u.next=t}else a=u=t;n={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:u,shared:o.shared,effects:o.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function wi(e,t,n,o){var a=e.updateQueue;hn=!1;var u=a.firstBaseUpdate,f=a.lastBaseUpdate,g=a.shared.pending;if(g!==null){a.shared.pending=null;var y=g,P=y.next;y.next=null,f===null?u=P:f.next=P,f=y;var $=e.alternate;$!==null&&($=$.updateQueue,g=$.lastBaseUpdate,g!==f&&(g===null?$.firstBaseUpdate=P:g.next=P,$.lastBaseUpdate=y))}if(u!==null){var F=a.baseState;f=0,$=P=y=null,g=u;do{var z=g.lane,G=g.eventTime;if((o&z)===z){$!==null&&($=$.next={eventTime:G,lane:0,tag:g.tag,payload:g.payload,callback:g.callback,next:null});e:{var J=e,Z=g;switch(z=t,G=n,Z.tag){case 1:if(J=Z.payload,typeof J=="function"){F=J.call(G,F,z);break e}F=J;break e;case 3:J.flags=J.flags&-65537|128;case 0:if(J=Z.payload,z=typeof J=="function"?J.call(G,F,z):J,z==null)break e;F=Q({},F,z);break e;case 2:hn=!0}}g.callback!==null&&g.lane!==0&&(e.flags|=64,z=a.effects,z===null?a.effects=[g]:z.push(g))}else G={eventTime:G,lane:z,tag:g.tag,payload:g.payload,callback:g.callback,next:null},$===null?(P=$=G,y=F):$=$.next=G,f|=z;if(g=g.next,g===null){if(g=a.shared.pending,g===null)break;z=g,g=z.next,z.next=null,a.lastBaseUpdate=z,a.shared.pending=null}}while(!0);if($===null&&(y=F),a.baseState=y,a.firstBaseUpdate=P,a.lastBaseUpdate=$,t=a.shared.interleaved,t!==null){a=t;do f|=a.lane,a=a.next;while(a!==t)}else u===null&&(a.shared.lanes=0);In|=f,e.lanes=f,e.memoizedState=F}}function Wc(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var o=zl.transition;zl.transition={};try{e(!1),t()}finally{je=n,zl.transition=o}}function cd(){return jt().memoizedState}function Ym(e,t,n){var o=xn(e);if(n={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null},dd(e))fd(t,n);else if(n=Uc(e,t,n,o),n!==null){var a=st();Dt(n,e,o,a),pd(n,t,o)}}function Qm(e,t,n){var o=xn(e),a={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null};if(dd(e))fd(t,a);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var f=t.lastRenderedState,g=u(f,n);if(a.hasEagerState=!0,a.eagerState=g,Nt(g,f)){var y=t.interleaved;y===null?(a.next=a,Nl(t)):(a.next=y.next,y.next=a),t.interleaved=a;return}}catch{}finally{}n=Uc(e,t,a,o),n!==null&&(a=st(),Dt(n,e,o,a),pd(n,t,o))}}function dd(e){var t=e.alternate;return e===Le||t!==null&&t===Le}function fd(e,t){ao=Ci=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function pd(e,t,n){if(n&4194240){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,qs(e,n)}}var Ai={readContext:Et,useCallback:Je,useContext:Je,useEffect:Je,useImperativeHandle:Je,useInsertionEffect:Je,useLayoutEffect:Je,useMemo:Je,useReducer:Je,useRef:Je,useState:Je,useDebugValue:Je,useDeferredValue:Je,useTransition:Je,useMutableSource:Je,useSyncExternalStore:Je,useId:Je,unstable_isNewReconciler:!1},Gm={readContext:Et,useCallback:function(e,t){return Ut().memoizedState=[e,t===void 0?null:t],e},useContext:Et,useEffect:nd,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ei(4194308,4,id.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ei(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ei(4,2,e,t)},useMemo:function(e,t){var n=Ut();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var o=Ut();return t=n!==void 0?n(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=Ym.bind(null,Le,e),[o.memoizedState,e]},useRef:function(e){var t=Ut();return e={current:e},t.memoizedState=e},useState:ed,useDebugValue:Vl,useDeferredValue:function(e){return Ut().memoizedState=e},useTransition:function(){var e=ed(!1),t=e[0];return e=qm.bind(null,e[1]),Ut().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var o=Le,a=Ut();if(Ne){if(n===void 0)throw Error(s(407));n=n()}else{if(n=t(),We===null)throw Error(s(349));Ln&30||Gc(o,t,n)}a.memoizedState=n;var u={value:n,getSnapshot:t};return a.queue=u,nd(Xc.bind(null,o,u,e),[e]),o.flags|=2048,fo(9,Kc.bind(null,o,u,n,t),void 0,null),n},useId:function(){var e=Ut(),t=We.identifierPrefix;if(Ne){var n=Kt,o=Gt;n=(o&~(1<<32-_t(o)-1)).toString(32)+n,t=":"+t+"R"+n,n=uo++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=f.createElement(n,{is:o.is}):(e=f.createElement(n),n==="select"&&(f=e,o.multiple?f.multiple=!0:o.size&&(f.size=o.size))):e=f.createElementNS(e,n),e[Ft]=t,e[no]=o,Md(e,t,!1,!1),t.stateNode=e;e:{switch(f=Ds(n,o),n){case"dialog":Pe("cancel",e),Pe("close",e),a=o;break;case"iframe":case"object":case"embed":Pe("load",e),a=o;break;case"video":case"audio":for(a=0;ayr&&(t.flags|=128,o=!0,po(u,!1),t.lanes=4194304)}else{if(!o)if(e=Si(f),e!==null){if(t.flags|=128,o=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),po(u,!0),u.tail===null&&u.tailMode==="hidden"&&!f.alternate&&!Ne)return Ze(t),null}else 2*De()-u.renderingStartTime>yr&&n!==1073741824&&(t.flags|=128,o=!0,po(u,!1),t.lanes=4194304);u.isBackwards?(f.sibling=t.child,t.child=f):(n=u.last,n!==null?n.sibling=f:t.child=f,u.last=f)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=De(),t.sibling=null,n=Me.current,Ae(Me,o?n&1|2:n&1),t):(Ze(t),null);case 22:case 23:return ha(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?yt&1073741824&&(Ze(t),t.subtreeFlags&6&&(t.flags|=8192)):Ze(t),null;case 24:return null;case 25:return null}throw Error(s(156,t.tag))}function rg(e,t){switch(Cl(t),t.tag){case 1:return at(t.type)&&ci(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return pr(),Te(lt),Te(Xe),Dl(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Ll(t),null;case 13:if(Te(Me),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));ur()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Te(Me),null;case 4:return pr(),null;case 10:return Tl(t.type._context),null;case 22:case 23:return ha(),null;case 24:return null;default:return null}}var _i=!1,et=!1,og=typeof WeakSet=="function"?WeakSet:Set,X=null;function mr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(o){Ie(e,t,o)}else n.current=null}function na(e,t,n){try{n()}catch(o){Ie(e,t,o)}}var Dd=!1;function ig(e,t){if(hl=Ko,e=hc(),sl(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var o=n.getSelection&&n.getSelection();if(o&&o.rangeCount!==0){n=o.anchorNode;var a=o.anchorOffset,u=o.focusNode;o=o.focusOffset;try{n.nodeType,u.nodeType}catch{n=null;break e}var f=0,g=-1,y=-1,P=0,$=0,F=e,z=null;t:for(;;){for(var G;F!==n||a!==0&&F.nodeType!==3||(g=f+a),F!==u||o!==0&&F.nodeType!==3||(y=f+o),F.nodeType===3&&(f+=F.nodeValue.length),(G=F.firstChild)!==null;)z=F,F=G;for(;;){if(F===e)break t;if(z===n&&++P===a&&(g=f),z===u&&++$===o&&(y=f),(G=F.nextSibling)!==null)break;F=z,z=F.parentNode}F=G}n=g===-1||y===-1?null:{start:g,end:y}}else n=null}n=n||{start:0,end:0}}else n=null;for(ml={focusedElem:e,selectionRange:n},Ko=!1,X=t;X!==null;)if(t=X,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,X=e;else for(;X!==null;){t=X;try{var J=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(J!==null){var Z=J.memoizedProps,ze=J.memoizedState,E=t.stateNode,x=E.getSnapshotBeforeUpdate(t.elementType===t.type?Z:Mt(t.type,Z),ze);E.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var A=t.stateNode.containerInfo;A.nodeType===1?A.textContent="":A.nodeType===9&&A.documentElement&&A.removeChild(A.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(s(163))}}catch(b){Ie(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,X=e;break}X=t.return}return J=Dd,Dd=!1,J}function ho(e,t,n){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&&na(t,n,u)}a=a.next}while(a!==o)}}function Ni(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var o=n.create;n.destroy=o()}n=n.next}while(n!==t)}}function ra(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function zd(e){var t=e.alternate;t!==null&&(e.alternate=null,zd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ft],delete t[no],delete t[xl],delete t[bm],delete t[Um])),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 $d(e){return e.tag===5||e.tag===3||e.tag===4}function Bd(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||$d(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 oa(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ai));else if(o!==4&&(e=e.child,e!==null))for(oa(e,t,n),e=e.sibling;e!==null;)oa(e,t,n),e=e.sibling}function ia(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(ia(e,t,n),e=e.sibling;e!==null;)ia(e,t,n),e=e.sibling}var Ge=null,Lt=!1;function gn(e,t,n){for(n=n.child;n!==null;)Fd(e,t,n),n=n.sibling}function Fd(e,t,n){if(Bt&&typeof Bt.onCommitFiberUnmount=="function")try{Bt.onCommitFiberUnmount(Vo,n)}catch{}switch(n.tag){case 5:et||mr(n,t);case 6:var o=Ge,a=Lt;Ge=null,gn(e,t,n),Ge=o,Lt=a,Ge!==null&&(Lt?(e=Ge,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ge.removeChild(n.stateNode));break;case 18:Ge!==null&&(Lt?(e=Ge,n=n.stateNode,e.nodeType===8?vl(e.parentNode,n):e.nodeType===1&&vl(e,n),Wr(e)):vl(Ge,n.stateNode));break;case 4:o=Ge,a=Lt,Ge=n.stateNode.containerInfo,Lt=!0,gn(e,t,n),Ge=o,Lt=a;break;case 0:case 11:case 14:case 15:if(!et&&(o=n.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var u=a,f=u.destroy;u=u.tag,f!==void 0&&(u&2||u&4)&&na(n,t,f),a=a.next}while(a!==o)}gn(e,t,n);break;case 1:if(!et&&(mr(n,t),o=n.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=n.memoizedProps,o.state=n.memoizedState,o.componentWillUnmount()}catch(g){Ie(n,t,g)}gn(e,t,n);break;case 21:gn(e,t,n);break;case 22:n.mode&1?(et=(o=et)||n.memoizedState!==null,gn(e,t,n),et=o):gn(e,t,n);break;default:gn(e,t,n)}}function bd(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new og),t.forEach(function(o){var a=hg.bind(null,e,o);n.has(o)||(n.add(o),o.then(a,a))})}}function It(e,t){var n=t.deletions;if(n!==null)for(var o=0;oa&&(a=f),o&=~u}if(o=a,o=De()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*lg(o/1960))-o,10e?16:e,vn===null)var o=!1;else{if(e=vn,vn=null,Di=0,xe&6)throw Error(s(331));var a=xe;for(xe|=4,X=e.current;X!==null;){var u=X,f=u.child;if(X.flags&16){var g=u.deletions;if(g!==null){for(var y=0;yDe()-aa?zn(e,0):la|=n),dt(e,t)}function ef(e,t){t===0&&(e.mode&1?(t=qo,qo<<=1,!(qo&130023424)&&(qo=4194304)):t=1);var n=st();e=Xt(e,t),e!==null&&(Fr(e,t,n),dt(e,n))}function pg(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ef(e,n)}function hg(e,t){var n=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(s(314))}o!==null&&o.delete(t),ef(e,n)}var tf;tf=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||lt.current)ut=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ut=!1,tg(e,t,n);ut=!!(e.flags&131072)}else ut=!1,Ne&&t.flags&1048576&&Lc(t,hi,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;Ti(e,t),e=t.pendingProps;var a=sr(t,Xe.current);fr(t,n),a=Bl(null,t,o,e,a,n);var u=Fl();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,at(o)?(u=!0,di(t)):u=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Ol(t),a.updater=Ri,t.stateNode=a,a._reactInternals=t,ql(t,o,e,n),t=Kl(null,t,o,!0,u,n)):(t.tag=0,Ne&&u&&kl(t),it(null,t,a,n),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=gg(o),e=Mt(o,e),a){case 0:t=Gl(null,t,o,e,n);break e;case 1:t=Rd(null,t,o,e,n);break e;case 11:t=kd(null,t,o,e,n);break e;case 14:t=Cd(null,t,o,Mt(o.type,e),n);break e}throw Error(s(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),Gl(e,t,o,a,n);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),Rd(e,t,o,a,n);case 3:e:{if(Pd(t),e===null)throw Error(s(387));o=t.pendingProps,u=t.memoizedState,a=u.element,Hc(e,t),wi(t,o,null,n);var f=t.memoizedState;if(o=f.element,u.isDehydrated)if(u={element:o,isDehydrated:!1,cache:f.cache,pendingSuspenseBoundaries:f.pendingSuspenseBoundaries,transitions:f.transitions},t.updateQueue.baseState=u,t.memoizedState=u,t.flags&256){a=hr(Error(s(423)),t),t=Td(e,t,o,n,a);break e}else if(o!==a){a=hr(Error(s(424)),t),t=Td(e,t,o,n,a);break e}else for(gt=cn(t.stateNode.containerInfo.firstChild),mt=t,Ne=!0,Ot=null,n=bc(t,null,o,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ur(),o===a){t=Zt(e,t,n);break e}it(e,t,o,n)}t=t.child}return t;case 5:return qc(t),e===null&&jl(t),o=t.type,a=t.pendingProps,u=e!==null?e.memoizedProps:null,f=a.children,gl(o,a)?f=null:u!==null&&gl(o,u)&&(t.flags|=32),Ad(e,t),it(e,t,f,n),t.child;case 6:return e===null&&jl(t),null;case 13:return _d(e,t,n);case 4:return Ml(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=cr(t,null,o,n):it(e,t,o,n),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),kd(e,t,o,a,n);case 7:return it(e,t,t.pendingProps,n),t.child;case 8:return it(e,t,t.pendingProps.children,n),t.child;case 12:return it(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,u=t.memoizedProps,f=a.value,Ae(yi,o._currentValue),o._currentValue=f,u!==null)if(Nt(u.value,f)){if(u.children===a.children&&!lt.current){t=Zt(e,t,n);break e}}else for(u=t.child,u!==null&&(u.return=t);u!==null;){var g=u.dependencies;if(g!==null){f=u.child;for(var y=g.firstContext;y!==null;){if(y.context===o){if(u.tag===1){y=Jt(-1,n&-n),y.tag=2;var P=u.updateQueue;if(P!==null){P=P.shared;var $=P.pending;$===null?y.next=y:(y.next=$.next,$.next=y),P.pending=y}}u.lanes|=n,y=u.alternate,y!==null&&(y.lanes|=n),_l(u.return,n,t),g.lanes|=n;break}y=y.next}}else if(u.tag===10)f=u.type===t.type?null:u.child;else if(u.tag===18){if(f=u.return,f===null)throw Error(s(341));f.lanes|=n,g=f.alternate,g!==null&&(g.lanes|=n),_l(f,n,t),f=u.sibling}else f=u.child;if(f!==null)f.return=u;else for(f=u;f!==null;){if(f===t){f=null;break}if(u=f.sibling,u!==null){u.return=f.return,f=u;break}f=f.return}u=f}it(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,fr(t,n),a=Et(a),o=o(a),t.flags|=1,it(e,t,o,n),t.child;case 14:return o=t.type,a=Mt(o,t.pendingProps),a=Mt(o.type,a),Cd(e,t,o,a,n);case 15:return Ed(e,t,t.type,t.pendingProps,n);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),Ti(e,t),t.tag=1,at(o)?(e=!0,di(t)):e=!1,fr(t,n),md(t,o,a),ql(t,o,a,n),Kl(null,t,o,!0,e,n);case 19:return Od(e,t,n);case 22:return jd(e,t,n)}throw Error(s(156,t.tag))};function nf(e,t){return Iu(e,t)}function mg(e,t,n,o){this.tag=e,this.key=n,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 Rt(e,t,n,o){return new mg(e,t,n,o)}function ga(e){return e=e.prototype,!(!e||!e.isReactComponent)}function gg(e){if(typeof e=="function")return ga(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ne)return 11;if(e===Re)return 14}return 2}function Sn(e,t){var n=e.alternate;return n===null?(n=Rt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Fi(e,t,n,o,a,u){var f=2;if(o=e,typeof e=="function")ga(e)&&(f=1);else if(typeof e=="string")f=5;else e:switch(e){case H:return Bn(n.children,a,u,t);case ie:f=8,a|=8;break;case ve:return e=Rt(12,n,t,a|2),e.elementType=ve,e.lanes=u,e;case le:return e=Rt(13,n,t,a),e.elementType=le,e.lanes=u,e;case me:return e=Rt(19,n,t,a),e.elementType=me,e.lanes=u,e;case Ee:return bi(n,a,u,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Oe:f=10;break e;case ot:f=9;break e;case ne:f=11;break e;case Re:f=14;break e;case ge:f=16,o=null;break e}throw Error(s(130,e==null?e:typeof e,""))}return t=Rt(f,n,t,a),t.elementType=e,t.type=o,t.lanes=u,t}function Bn(e,t,n,o){return e=Rt(7,e,o,t),e.lanes=n,e}function bi(e,t,n,o){return e=Rt(22,e,o,t),e.elementType=Ee,e.lanes=n,e.stateNode={isHidden:!1},e}function ya(e,t,n){return e=Rt(6,e,null,t),e.lanes=n,e}function va(e,t,n){return t=Rt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function yg(e,t,n,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=Ws(0),this.expirationTimes=Ws(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ws(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function xa(e,t,n,o,a,u,f,g,y){return e=new yg(e,t,n,g,y),t===1?(t=1,u===!0&&(t|=8)):t=0,u=Rt(3,null,null,t),e.current=u,u.stateNode=e,u.memoizedState={element:o,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ol(u),e}function vg(e,t,n){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(i){console.error(i)}}return r(),ja.exports=Ng(),ja.exports}var vf;function Mg(){if(vf)return Qi;vf=1;var r=Og();return Qi.createRoot=r.createRoot,Qi.hydrateRoot=r.hydrateRoot,Qi}var Lg=Mg(),nt=function(){return nt=Object.assign||function(i){for(var s,l=1,c=arguments.length;l0?Ye(Pr,--Pt):0,Er--,be===10&&(Er=1,xs--),be}function zt(){return be=Pt2||Ha(be)>3?"":" "}function Vg(r,i){for(;--i&&zt()&&!(be<48||be>102||be>57&&be<65||be>70&&be<97););return Ss(r,os()+(i<6&&Un()==32&&zt()==32))}function Va(r){for(;zt();)switch(be){case r:return Pt;case 34:case 39:r!==34&&r!==39&&Va(be);break;case 40:r===41&&Va(r);break;case 92:zt();break}return Pt}function Wg(r,i){for(;zt()&&r+be!==57;)if(r+be===84&&Un()===47)break;return"/*"+Ss(i,Pt-1)+"*"+su(r===47?r:zt())}function qg(r){for(;!Ha(Un());)zt();return Ss(r,Pt)}function Yg(r){return Ug(is("",null,null,null,[""],r=bg(r),0,[0],r))}function is(r,i,s,l,c,d,p,m,w){for(var v=0,S=0,j=p,R=0,L=0,T=0,N=1,_=1,V=1,U=0,B="",W=c,I=d,M=l,H=B;_;)switch(T=U,U=zt()){case 40:if(T!=108&&Ye(H,j-1)==58){rs(H+=de(Pa(U),"&","&\f"),"&\f",vp(v?m[v-1]:0))!=-1&&(V=-1);break}case 34:case 39:case 91:H+=Pa(U);break;case 9:case 10:case 13:case 32:H+=Hg(T);break;case 92:H+=Vg(os()-1,7);continue;case 47:switch(Un()){case 42:case 47:jo(Qg(Wg(zt(),os()),i,s,w),w);break;default:H+="/"}break;case 123*N:m[v++]=Wt(H)*V;case 125*N:case 59:case 0:switch(U){case 0:case 125:_=0;case 59+S:V==-1&&(H=de(H,/\f/g,"")),L>0&&Wt(H)-j&&jo(L>32?Sf(H+";",l,s,j-1,w):Sf(de(H," ","")+";",l,s,j-2,w),w);break;case 59:H+=";";default:if(jo(M=wf(H,i,s,v,S,c,m,B,W=[],I=[],j,d),d),U===123)if(S===0)is(H,i,M,M,W,d,j,m,I);else switch(R===99&&Ye(H,3)===110?100:R){case 100:case 108:case 109:case 115:is(r,M,M,l&&jo(wf(r,M,M,0,0,c,m,B,c,W=[],j,I),I),c,I,j,m,l?W:I);break;default:is(H,M,M,M,[""],I,0,m,I)}}v=S=L=0,N=V=1,B=H="",j=p;break;case 58:j=1+Wt(H),L=T;default:if(N<1){if(U==123)--N;else if(U==125&&N++==0&&Fg()==125)continue}switch(H+=su(U),U*N){case 38:V=S>0?1:(H+="\f",-1);break;case 44:m[v++]=(Wt(H)-1)*V,V=1;break;case 64:Un()===45&&(H+=Pa(zt())),R=Un(),S=j=Wt(B=H+=qg(os())),U++;break;case 45:T===45&&Wt(H)==2&&(N=0)}}return d}function wf(r,i,s,l,c,d,p,m,w,v,S,j){for(var R=c-1,L=c===0?d:[""],T=wp(L),N=0,_=0,V=0;N0?L[U]+" "+B:de(B,/&\f/g,L[U])))&&(w[V++]=W);return ws(r,i,s,c===0?vs:m,w,v,S,j)}function Qg(r,i,s,l){return ws(r,i,s,gp,su(Bg()),Cr(r,2,-2),0,l)}function Sf(r,i,s,l,c){return ws(r,i,s,iu,Cr(r,0,l),Cr(r,l+1,-1),l,c)}function kp(r,i,s){switch(zg(r,i)){case 5103:return Ce+"print-"+r+r;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 Ce+r+r;case 4789:return Ao+r+r;case 5349:case 4246:case 4810:case 6968:case 2756:return Ce+r+Ao+r+_e+r+r;case 5936:switch(Ye(r,i+11)){case 114:return Ce+r+_e+de(r,/[svh]\w+-[tblr]{2}/,"tb")+r;case 108:return Ce+r+_e+de(r,/[svh]\w+-[tblr]{2}/,"tb-rl")+r;case 45:return Ce+r+_e+de(r,/[svh]\w+-[tblr]{2}/,"lr")+r}case 6828:case 4268:case 2903:return Ce+r+_e+r+r;case 6165:return Ce+r+_e+"flex-"+r+r;case 5187:return Ce+r+de(r,/(\w+).+(:[^]+)/,Ce+"box-$1$2"+_e+"flex-$1$2")+r;case 5443:return Ce+r+_e+"flex-item-"+de(r,/flex-|-self/g,"")+(tn(r,/flex-|baseline/)?"":_e+"grid-row-"+de(r,/flex-|-self/g,""))+r;case 4675:return Ce+r+_e+"flex-line-pack"+de(r,/align-content|flex-|-self/g,"")+r;case 5548:return Ce+r+_e+de(r,"shrink","negative")+r;case 5292:return Ce+r+_e+de(r,"basis","preferred-size")+r;case 6060:return Ce+"box-"+de(r,"-grow","")+Ce+r+_e+de(r,"grow","positive")+r;case 4554:return Ce+de(r,/([^-])(transform)/g,"$1"+Ce+"$2")+r;case 6187:return de(de(de(r,/(zoom-|grab)/,Ce+"$1"),/(image-set)/,Ce+"$1"),r,"")+r;case 5495:case 3959:return de(r,/(image-set\([^]*)/,Ce+"$1$`$1");case 4968:return de(de(r,/(.+:)(flex-)?(.*)/,Ce+"box-pack:$3"+_e+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+Ce+r+r;case 4200:if(!tn(r,/flex-|baseline/))return _e+"grid-column-align"+Cr(r,i)+r;break;case 2592:case 3360:return _e+de(r,"template-","")+r;case 4384:case 3616:return s&&s.some(function(l,c){return i=c,tn(l.props,/grid-\w+-end/)})?~rs(r+(s=s[i].value),"span",0)?r:_e+de(r,"-start","")+r+_e+"grid-row-span:"+(~rs(s,"span",0)?tn(s,/\d+/):+tn(s,/\d+/)-+tn(r,/\d+/))+";":_e+de(r,"-start","")+r;case 4896:case 4128:return s&&s.some(function(l){return tn(l.props,/grid-\w+-start/)})?r:_e+de(de(r,"-end","-span"),"span ","")+r;case 4095:case 3583:case 4068:case 2532:return de(r,/(.+)-inline(.+)/,Ce+"$1$2")+r;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(r)-1-i>6)switch(Ye(r,i+1)){case 109:if(Ye(r,i+4)!==45)break;case 102:return de(r,/(.+:)(.+)-([^]+)/,"$1"+Ce+"$2-$3$1"+Ao+(Ye(r,i+3)==108?"$3":"$2-$3"))+r;case 115:return~rs(r,"stretch",0)?kp(de(r,"stretch","fill-available"),i,s)+r:r}break;case 5152:case 5920:return de(r,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(l,c,d,p,m,w,v){return _e+c+":"+d+v+(p?_e+c+"-span:"+(m?w:+w-+d)+v:"")+r});case 4949:if(Ye(r,i+6)===121)return de(r,":",":"+Ce)+r;break;case 6444:switch(Ye(r,Ye(r,14)===45?18:11)){case 120:return de(r,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+Ce+(Ye(r,14)===45?"inline-":"")+"box$3$1"+Ce+"$2$3$1"+_e+"$2box$3")+r;case 100:return de(r,":",":"+_e)+r}break;case 5719:case 2647:case 2135:case 3927:case 2391:return de(r,"scroll-","scroll-snap-")+r}return r}function fs(r,i){for(var s="",l=0;l-1&&!r.return)switch(r.type){case iu:r.return=kp(r.value,r.length,s);return;case yp:return fs([Cn(r,{value:de(r.value,"@","@"+Ce)})],l);case vs:if(r.length)return $g(s=r.props,function(c){switch(tn(c,l=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":xr(Cn(r,{props:[de(c,/:(read-\w+)/,":"+Ao+"$1")]})),xr(Cn(r,{props:[c]})),Ua(r,{props:xf(s,l)});break;case"::placeholder":xr(Cn(r,{props:[de(c,/:(plac\w+)/,":"+Ce+"input-$1")]})),xr(Cn(r,{props:[de(c,/:(plac\w+)/,":"+Ao+"$1")]})),xr(Cn(r,{props:[de(c,/:(plac\w+)/,_e+"input-$1")]})),xr(Cn(r,{props:[c]})),Ua(r,{props:xf(s,l)});break}return""})}}var Zg={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},vt={},jr=typeof process<"u"&&vt!==void 0&&(vt.REACT_APP_SC_ATTR||vt.SC_ATTR)||"data-styled",Cp="active",Ep="data-styled-version",ks="6.1.14",lu=`/*!sc*/ +`,ps=typeof window<"u"&&"HTMLElement"in window,ey=!!(typeof SC_DISABLE_SPEEDY=="boolean"?SC_DISABLE_SPEEDY:typeof process<"u"&&vt!==void 0&&vt.REACT_APP_SC_DISABLE_SPEEDY!==void 0&&vt.REACT_APP_SC_DISABLE_SPEEDY!==""?vt.REACT_APP_SC_DISABLE_SPEEDY!=="false"&&vt.REACT_APP_SC_DISABLE_SPEEDY:typeof process<"u"&&vt!==void 0&&vt.SC_DISABLE_SPEEDY!==void 0&&vt.SC_DISABLE_SPEEDY!==""&&vt.SC_DISABLE_SPEEDY!=="false"&&vt.SC_DISABLE_SPEEDY),Cs=Object.freeze([]),Ar=Object.freeze({});function ty(r,i,s){return s===void 0&&(s=Ar),r.theme!==s.theme&&r.theme||i||s.theme}var jp=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"]),ny=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,ry=/(^-|-$)/g;function kf(r){return r.replace(ny,"-").replace(ry,"")}var oy=/(a)(d)/gi,Gi=52,Cf=function(r){return String.fromCharCode(r+(r>25?39:97))};function Wa(r){var i,s="";for(i=Math.abs(r);i>Gi;i=i/Gi|0)s=Cf(i%Gi)+s;return(Cf(i%Gi)+s).replace(oy,"$1-$2")}var Ta,Ap=5381,wr=function(r,i){for(var s=i.length;s;)r=33*r^i.charCodeAt(--s);return r},Rp=function(r){return wr(Ap,r)};function iy(r){return Wa(Rp(r)>>>0)}function sy(r){return r.displayName||r.name||"Component"}function _a(r){return typeof r=="string"&&!0}var Pp=typeof Symbol=="function"&&Symbol.for,Tp=Pp?Symbol.for("react.memo"):60115,ly=Pp?Symbol.for("react.forward_ref"):60112,ay={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},uy={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},_p={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},cy=((Ta={})[ly]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Ta[Tp]=_p,Ta);function Ef(r){return("type"in(i=r)&&i.type.$$typeof)===Tp?_p:"$$typeof"in r?cy[r.$$typeof]:ay;var i}var dy=Object.defineProperty,fy=Object.getOwnPropertyNames,jf=Object.getOwnPropertySymbols,py=Object.getOwnPropertyDescriptor,hy=Object.getPrototypeOf,Af=Object.prototype;function Np(r,i,s){if(typeof i!="string"){if(Af){var l=hy(i);l&&l!==Af&&Np(r,l,s)}var c=fy(i);jf&&(c=c.concat(jf(i)));for(var d=Ef(r),p=Ef(i),m=0;m0?" Args: ".concat(i.join(", ")):""))}var my=function(){function r(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}return r.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 p=c;p=this.length||this.groupSizes[i]===0)return s;for(var l=this.groupSizes[i],c=this.indexOfGroup(i),d=c+l,p=c;p=0){var l=document.createTextNode(s);return this.element.insertBefore(l,this.nodes[i]||null),this.length++,!0}return!1},r.prototype.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},r.prototype.getRule=function(i){return i0&&(_+="".concat(V,","))}),w+="".concat(T).concat(N,'{content:"').concat(_,'"}').concat(lu)},S=0;S0?".".concat(i):R},S=w.slice();S.push(function(R){R.type===vs&&R.value.includes("&")&&(R.props[0]=R.props[0].replace(Ay,s).replace(l,v))}),p.prefix&&S.push(Jg),S.push(Gg);var j=function(R,L,T,N){L===void 0&&(L=""),T===void 0&&(T=""),N===void 0&&(N="&"),i=N,s=L,l=new RegExp("\\".concat(s,"\\b"),"g");var _=R.replace(Ry,""),V=Yg(T||L?"".concat(T," ").concat(L," { ").concat(_," }"):_);p.namespace&&(V=Lp(V,p.namespace));var U=[];return fs(V,Kg(S.concat(Xg(function(B){return U.push(B)})))),U};return j.hash=w.length?w.reduce(function(R,L){return L.name||qn(15),wr(R,L.name)},Ap).toString():"",j}var Ty=new Mp,Ya=Py(),Ip=xt.createContext({shouldForwardProp:void 0,styleSheet:Ty,stylis:Ya});Ip.Consumer;xt.createContext(void 0);function _f(){return K.useContext(Ip)}var _y=function(){function r(i,s){var l=this;this.inject=function(c,d){d===void 0&&(d=Ya);var p=l.name+d.hash;c.hasNameForId(l.id,p)||c.insertRules(l.id,p,d(l.rules,p,"@keyframes"))},this.name=i,this.id="sc-keyframes-".concat(i),this.rules=s,uu(this,function(){throw qn(12,String(l.name))})}return r.prototype.getName=function(i){return i===void 0&&(i=Ya),this.name+i.hash},r}(),Ny=function(r){return r>="A"&&r<="Z"};function Nf(r){for(var i="",s=0;s>>0);if(!s.hasNameForId(this.componentId,p)){var m=l(d,".".concat(p),void 0,this.componentId);s.insertRules(this.componentId,p,m)}c=Fn(c,p),this.staticRulesId=p}else{for(var w=wr(this.baseHash,l.hash),v="",S=0;S>>0);s.hasNameForId(this.componentId,L)||s.insertRules(this.componentId,L,l(v,".".concat(L),void 0,this.componentId)),c=Fn(c,L)}}return c},r}(),ms=xt.createContext(void 0);ms.Consumer;function Of(r){var i=xt.useContext(ms),s=K.useMemo(function(){return function(l,c){if(!l)throw qn(14);if(Wn(l)){var d=l(c);return d}if(Array.isArray(l)||typeof l!="object")throw qn(8);return c?nt(nt({},c),l):l}(r.theme,i)},[r.theme,i]);return r.children?xt.createElement(ms.Provider,{value:s},r.children):null}var Na={};function Iy(r,i,s){var l=au(r),c=r,d=!_a(r),p=i.attrs,m=p===void 0?Cs:p,w=i.componentId,v=w===void 0?function(W,I){var M=typeof W!="string"?"sc":kf(W);Na[M]=(Na[M]||0)+1;var H="".concat(M,"-").concat(iy(ks+M+Na[M]));return I?"".concat(I,"-").concat(H):H}(i.displayName,i.parentComponentId):w,S=i.displayName,j=S===void 0?function(W){return _a(W)?"styled.".concat(W):"Styled(".concat(sy(W),")")}(r):S,R=i.displayName&&i.componentId?"".concat(kf(i.displayName),"-").concat(i.componentId):i.componentId||v,L=l&&c.attrs?c.attrs.concat(m).filter(Boolean):m,T=i.shouldForwardProp;if(l&&c.shouldForwardProp){var N=c.shouldForwardProp;if(i.shouldForwardProp){var _=i.shouldForwardProp;T=function(W,I){return N(W,I)&&_(W,I)}}else T=N}var V=new Ly(s,R,l?c.componentStyle:void 0);function U(W,I){return function(M,H,ie){var ve=M.attrs,Oe=M.componentStyle,ot=M.defaultProps,ne=M.foldedComponentIds,le=M.styledComponentId,me=M.target,Re=xt.useContext(ms),ge=_f(),Ee=M.shouldForwardProp||ge.shouldForwardProp,q=ty(H,Re,ot)||Ar,ee=function(he,fe,ke){for(var ye,we=nt(nt({},fe),{className:void 0,theme:ke}),Qe=0;Qe{let i;const s=new Set,l=(v,S)=>{const j=typeof v=="function"?v(i):v;if(!Object.is(j,i)){const R=i;i=S??(typeof j!="object"||j===null)?j:Object.assign({},i,j),s.forEach(L=>L(i,R))}},c=()=>i,m={setState:l,getState:c,getInitialState:()=>w,subscribe:v=>(s.add(v),()=>s.delete(v))},w=i=r(l,c,m);return m},zy=r=>r?If(r):If,$y=r=>r;function By(r,i=$y){const s=xt.useSyncExternalStore(r.subscribe,()=>i(r.getState()),()=>i(r.getInitialState()));return xt.useDebugValue(s),s}const Df=r=>{const i=zy(r),s=l=>By(i,l);return Object.assign(s,i),s},Tr=r=>r?Df(r):Df;function Bp(r,i){return function(){return r.apply(i,arguments)}}const{toString:Fy}=Object.prototype,{getPrototypeOf:cu}=Object,Es=(r=>i=>{const s=Fy.call(i);return r[s]||(r[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),$t=r=>(r=r.toLowerCase(),i=>Es(i)===r),js=r=>i=>typeof i===r,{isArray:_r}=Array,Mo=js("undefined");function by(r){return r!==null&&!Mo(r)&&r.constructor!==null&&!Mo(r.constructor)&&wt(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const Fp=$t("ArrayBuffer");function Uy(r){let i;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?i=ArrayBuffer.isView(r):i=r&&r.buffer&&Fp(r.buffer),i}const Hy=js("string"),wt=js("function"),bp=js("number"),As=r=>r!==null&&typeof r=="object",Vy=r=>r===!0||r===!1,as=r=>{if(Es(r)!=="object")return!1;const i=cu(r);return(i===null||i===Object.prototype||Object.getPrototypeOf(i)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},Wy=$t("Date"),qy=$t("File"),Yy=$t("Blob"),Qy=$t("FileList"),Gy=r=>As(r)&&wt(r.pipe),Ky=r=>{let i;return r&&(typeof FormData=="function"&&r instanceof FormData||wt(r.append)&&((i=Es(r))==="formdata"||i==="object"&&wt(r.toString)&&r.toString()==="[object FormData]"))},Xy=$t("URLSearchParams"),[Jy,Zy,e0,t0]=["ReadableStream","Request","Response","Headers"].map($t),n0=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Io(r,i,{allOwnKeys:s=!1}={}){if(r===null||typeof r>"u")return;let l,c;if(typeof r!="object"&&(r=[r]),_r(r))for(l=0,c=r.length;l0;)if(c=s[l],i===c.toLowerCase())return c;return null}const bn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Hp=r=>!Mo(r)&&r!==bn;function Ga(){const{caseless:r}=Hp(this)&&this||{},i={},s=(l,c)=>{const d=r&&Up(i,c)||c;as(i[d])&&as(l)?i[d]=Ga(i[d],l):as(l)?i[d]=Ga({},l):_r(l)?i[d]=l.slice():i[d]=l};for(let l=0,c=arguments.length;l(Io(i,(c,d)=>{s&&wt(c)?r[d]=Bp(c,s):r[d]=c},{allOwnKeys:l}),r),o0=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),i0=(r,i,s,l)=>{r.prototype=Object.create(i.prototype,l),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:i.prototype}),s&&Object.assign(r.prototype,s)},s0=(r,i,s,l)=>{let c,d,p;const m={};if(i=i||{},r==null)return i;do{for(c=Object.getOwnPropertyNames(r),d=c.length;d-- >0;)p=c[d],(!l||l(p,r,i))&&!m[p]&&(i[p]=r[p],m[p]=!0);r=s!==!1&&cu(r)}while(r&&(!s||s(r,i))&&r!==Object.prototype);return i},l0=(r,i,s)=>{r=String(r),(s===void 0||s>r.length)&&(s=r.length),s-=i.length;const l=r.indexOf(i,s);return l!==-1&&l===s},a0=r=>{if(!r)return null;if(_r(r))return r;let i=r.length;if(!bp(i))return null;const s=new Array(i);for(;i-- >0;)s[i]=r[i];return s},u0=(r=>i=>r&&i instanceof r)(typeof Uint8Array<"u"&&cu(Uint8Array)),c0=(r,i)=>{const l=(r&&r[Symbol.iterator]).call(r);let c;for(;(c=l.next())&&!c.done;){const d=c.value;i.call(r,d[0],d[1])}},d0=(r,i)=>{let s;const l=[];for(;(s=r.exec(i))!==null;)l.push(s);return l},f0=$t("HTMLFormElement"),p0=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,l,c){return l.toUpperCase()+c}),zf=(({hasOwnProperty:r})=>(i,s)=>r.call(i,s))(Object.prototype),h0=$t("RegExp"),Vp=(r,i)=>{const s=Object.getOwnPropertyDescriptors(r),l={};Io(s,(c,d)=>{let p;(p=i(c,d,r))!==!1&&(l[d]=p||c)}),Object.defineProperties(r,l)},m0=r=>{Vp(r,(i,s)=>{if(wt(r)&&["arguments","caller","callee"].indexOf(s)!==-1)return!1;const l=r[s];if(wt(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+"'")})}})},g0=(r,i)=>{const s={},l=c=>{c.forEach(d=>{s[d]=!0})};return _r(r)?l(r):l(String(r).split(i)),s},y0=()=>{},v0=(r,i)=>r!=null&&Number.isFinite(r=+r)?r:i,Oa="abcdefghijklmnopqrstuvwxyz",$f="0123456789",Wp={DIGIT:$f,ALPHA:Oa,ALPHA_DIGIT:Oa+Oa.toUpperCase()+$f},x0=(r=16,i=Wp.ALPHA_DIGIT)=>{let s="";const{length:l}=i;for(;r--;)s+=i[Math.random()*l|0];return s};function w0(r){return!!(r&&wt(r.append)&&r[Symbol.toStringTag]==="FormData"&&r[Symbol.iterator])}const S0=r=>{const i=new Array(10),s=(l,c)=>{if(As(l)){if(i.indexOf(l)>=0)return;if(!("toJSON"in l)){i[c]=l;const d=_r(l)?[]:{};return Io(l,(p,m)=>{const w=s(p,c+1);!Mo(w)&&(d[m]=w)}),i[c]=void 0,d}}return l};return s(r,0)},k0=$t("AsyncFunction"),C0=r=>r&&(As(r)||wt(r))&&wt(r.then)&&wt(r.catch),qp=((r,i)=>r?setImmediate:i?((s,l)=>(bn.addEventListener("message",({source:c,data:d})=>{c===bn&&d===s&&l.length&&l.shift()()},!1),c=>{l.push(c),bn.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",wt(bn.postMessage)),E0=typeof queueMicrotask<"u"?queueMicrotask.bind(bn):typeof process<"u"&&process.nextTick||qp,O={isArray:_r,isArrayBuffer:Fp,isBuffer:by,isFormData:Ky,isArrayBufferView:Uy,isString:Hy,isNumber:bp,isBoolean:Vy,isObject:As,isPlainObject:as,isReadableStream:Jy,isRequest:Zy,isResponse:e0,isHeaders:t0,isUndefined:Mo,isDate:Wy,isFile:qy,isBlob:Yy,isRegExp:h0,isFunction:wt,isStream:Gy,isURLSearchParams:Xy,isTypedArray:u0,isFileList:Qy,forEach:Io,merge:Ga,extend:r0,trim:n0,stripBOM:o0,inherits:i0,toFlatObject:s0,kindOf:Es,kindOfTest:$t,endsWith:l0,toArray:a0,forEachEntry:c0,matchAll:d0,isHTMLForm:f0,hasOwnProperty:zf,hasOwnProp:zf,reduceDescriptors:Vp,freezeMethods:m0,toObjectSet:g0,toCamelCase:p0,noop:y0,toFiniteNumber:v0,findKey:Up,global:bn,isContextDefined:Hp,ALPHABET:Wp,generateString:x0,isSpecCompliantForm:w0,toJSONObject:S0,isAsyncFn:k0,isThenable:C0,setImmediate:qp,asap:E0};function ue(r,i,s,l,c){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,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(ue,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 Yp=ue.prototype,Qp={};["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(r=>{Qp[r]={value:r}});Object.defineProperties(ue,Qp);Object.defineProperty(Yp,"isAxiosError",{value:!0});ue.from=(r,i,s,l,c,d)=>{const p=Object.create(Yp);return O.toFlatObject(r,p,function(w){return w!==Error.prototype},m=>m!=="isAxiosError"),ue.call(p,r.message,i,s,l,c),p.cause=r,p.name=r.name,d&&Object.assign(p,d),p};const j0=null;function Ka(r){return O.isPlainObject(r)||O.isArray(r)}function Gp(r){return O.endsWith(r,"[]")?r.slice(0,-2):r}function Bf(r,i,s){return r?r.concat(i).map(function(c,d){return c=Gp(c),!s&&d?"["+c+"]":c}).join(s?".":""):i}function A0(r){return O.isArray(r)&&!r.some(Ka)}const R0=O.toFlatObject(O,{},null,function(i){return/^is[A-Z]/.test(i)});function Rs(r,i,s){if(!O.isObject(r))throw new TypeError("target must be an object");i=i||new FormData,s=O.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(N,_){return!O.isUndefined(_[N])});const l=s.metaTokens,c=s.visitor||S,d=s.dots,p=s.indexes,w=(s.Blob||typeof Blob<"u"&&Blob)&&O.isSpecCompliantForm(i);if(!O.isFunction(c))throw new TypeError("visitor must be a function");function v(T){if(T===null)return"";if(O.isDate(T))return T.toISOString();if(!w&&O.isBlob(T))throw new ue("Blob is not supported. Use a Buffer instead.");return O.isArrayBuffer(T)||O.isTypedArray(T)?w&&typeof Blob=="function"?new Blob([T]):Buffer.from(T):T}function S(T,N,_){let V=T;if(T&&!_&&typeof T=="object"){if(O.endsWith(N,"{}"))N=l?N:N.slice(0,-2),T=JSON.stringify(T);else if(O.isArray(T)&&A0(T)||(O.isFileList(T)||O.endsWith(N,"[]"))&&(V=O.toArray(T)))return N=Gp(N),V.forEach(function(B,W){!(O.isUndefined(B)||B===null)&&i.append(p===!0?Bf([N],W,d):p===null?N:N+"[]",v(B))}),!1}return Ka(T)?!0:(i.append(Bf(_,N,d),v(T)),!1)}const j=[],R=Object.assign(R0,{defaultVisitor:S,convertValue:v,isVisitable:Ka});function L(T,N){if(!O.isUndefined(T)){if(j.indexOf(T)!==-1)throw Error("Circular reference detected in "+N.join("."));j.push(T),O.forEach(T,function(V,U){(!(O.isUndefined(V)||V===null)&&c.call(i,V,O.isString(U)?U.trim():U,N,R))===!0&&L(V,N?N.concat(U):[U])}),j.pop()}}if(!O.isObject(r))throw new TypeError("data must be an object");return L(r),i}function Ff(r){const i={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(l){return i[l]})}function du(r,i){this._pairs=[],r&&Rs(r,this,i)}const Kp=du.prototype;Kp.append=function(i,s){this._pairs.push([i,s])};Kp.toString=function(i){const s=i?function(l){return i.call(this,l,Ff)}:Ff;return this._pairs.map(function(c){return s(c[0])+"="+s(c[1])},"").join("&")};function P0(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Xp(r,i,s){if(!i)return r;const l=s&&s.encode||P0;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 du(i,s).toString(l),d){const p=r.indexOf("#");p!==-1&&(r=r.slice(0,p)),r+=(r.indexOf("?")===-1?"?":"&")+d}return r}class bf{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 Jp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},T0=typeof URLSearchParams<"u"?URLSearchParams:du,_0=typeof FormData<"u"?FormData:null,N0=typeof Blob<"u"?Blob:null,O0={isBrowser:!0,classes:{URLSearchParams:T0,FormData:_0,Blob:N0},protocols:["http","https","file","blob","url","data"]},fu=typeof window<"u"&&typeof document<"u",Xa=typeof navigator=="object"&&navigator||void 0,M0=fu&&(!Xa||["ReactNative","NativeScript","NS"].indexOf(Xa.product)<0),L0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",I0=fu&&window.location.href||"http://localhost",D0=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:fu,hasStandardBrowserEnv:M0,hasStandardBrowserWebWorkerEnv:L0,navigator:Xa,origin:I0},Symbol.toStringTag,{value:"Module"})),tt={...D0,...O0};function z0(r,i){return Rs(r,new tt.classes.URLSearchParams,Object.assign({visitor:function(s,l,c,d){return tt.isNode&&O.isBuffer(s)?(this.append(l,s.toString("base64")),!1):d.defaultVisitor.apply(this,arguments)}},i))}function $0(r){return O.matchAll(/\w+|\[(\w*)]/g,r).map(i=>i[0]==="[]"?"":i[1]||i[0])}function B0(r){const i={},s=Object.keys(r);let l;const c=s.length;let d;for(l=0;l=s.length;return p=!p&&O.isArray(c)?c.length:p,w?(O.hasOwnProp(c,p)?c[p]=[c[p],l]:c[p]=l,!m):((!c[p]||!O.isObject(c[p]))&&(c[p]=[]),i(s,l,c[p],d)&&O.isArray(c[p])&&(c[p]=B0(c[p])),!m)}if(O.isFormData(r)&&O.isFunction(r.entries)){const s={};return O.forEachEntry(r,(l,c)=>{i($0(l),c,s,0)}),s}return null}function F0(r,i,s){if(O.isString(r))try{return(i||JSON.parse)(r),O.trim(r)}catch(l){if(l.name!=="SyntaxError")throw l}return(0,JSON.stringify)(r)}const Do={transitional:Jp,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(Zp(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 z0(i,this.formSerializer).toString();if((m=O.isFileList(i))||l.indexOf("multipart/form-data")>-1){const w=this.env&&this.env.FormData;return Rs(m?{"files[]":i}:i,w&&new w,this.formSerializer)}}return d||c?(s.setContentType("application/json",!1),F0(i)):i}],transformResponse:[function(i){const s=this.transitional||Do.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 p=!(s&&s.silentJSONParsing)&&c;try{return JSON.parse(i)}catch(m){if(p)throw m.name==="SyntaxError"?ue.from(m,ue.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:tt.classes.FormData,Blob:tt.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"],r=>{Do.headers[r]={}});const b0=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"]),U0=r=>{const i={};let s,l,c;return r&&r.split(` +`).forEach(function(p){c=p.indexOf(":"),s=p.substring(0,c).trim().toLowerCase(),l=p.substring(c+1).trim(),!(!s||i[s]&&b0[s])&&(s==="set-cookie"?i[s]?i[s].push(l):i[s]=[l]:i[s]=i[s]?i[s]+", "+l:l)}),i},Uf=Symbol("internals");function wo(r){return r&&String(r).trim().toLowerCase()}function us(r){return r===!1||r==null?r:O.isArray(r)?r.map(us):String(r)}function H0(r){const i=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let l;for(;l=s.exec(r);)i[l[1]]=l[2];return i}const V0=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function Ma(r,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 W0(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(i,s,l)=>s.toUpperCase()+l)}function q0(r,i){const s=O.toCamelCase(" "+i);["get","set","has"].forEach(l=>{Object.defineProperty(r,l+s,{value:function(c,d,p){return this[l].call(this,i,c,d,p)},configurable:!0})})}class pt{constructor(i){i&&this.set(i)}set(i,s,l){const c=this;function d(m,w,v){const S=wo(w);if(!S)throw new Error("header name must be a non-empty string");const j=O.findKey(c,S);(!j||c[j]===void 0||v===!0||v===void 0&&c[j]!==!1)&&(c[j||w]=us(m))}const p=(m,w)=>O.forEach(m,(v,S)=>d(v,S,w));if(O.isPlainObject(i)||i instanceof this.constructor)p(i,s);else if(O.isString(i)&&(i=i.trim())&&!V0(i))p(U0(i),s);else if(O.isHeaders(i))for(const[m,w]of i.entries())d(w,m,l);else i!=null&&d(s,i,l);return this}get(i,s){if(i=wo(i),i){const l=O.findKey(this,i);if(l){const c=this[l];if(!s)return c;if(s===!0)return H0(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=wo(i),i){const l=O.findKey(this,i);return!!(l&&this[l]!==void 0&&(!s||Ma(this,this[l],l,s)))}return!1}delete(i,s){const l=this;let c=!1;function d(p){if(p=wo(p),p){const m=O.findKey(l,p);m&&(!s||Ma(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||Ma(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 p=O.findKey(l,d);if(p){s[p]=us(c),delete s[d];return}const m=i?W0(d):String(d).trim();m!==d&&delete s[d],s[m]=us(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[Uf]=this[Uf]={accessors:{}}).accessors,c=this.prototype;function d(p){const m=wo(p);l[m]||(q0(c,p),l[m]=!0)}return O.isArray(i)?i.forEach(d):d(i),this}}pt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);O.reduceDescriptors(pt.prototype,({value:r},i)=>{let s=i[0].toUpperCase()+i.slice(1);return{get:()=>r,set(l){this[s]=l}}});O.freezeMethods(pt);function La(r,i){const s=this||Do,l=i||s,c=pt.from(l.headers);let d=l.data;return O.forEach(r,function(m){d=m.call(s,d,c.normalize(),i?i.status:void 0)}),c.normalize(),d}function eh(r){return!!(r&&r.__CANCEL__)}function Nr(r,i,s){ue.call(this,r??"canceled",ue.ERR_CANCELED,i,s),this.name="CanceledError"}O.inherits(Nr,ue,{__CANCEL__:!0});function th(r,i,s){const l=s.config.validateStatus;!s.status||!l||l(s.status)?r(s):i(new ue("Request failed with status code "+s.status,[ue.ERR_BAD_REQUEST,ue.ERR_BAD_RESPONSE][Math.floor(s.status/100)-4],s.config,s.request,s))}function Y0(r){const i=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return i&&i[1]||""}function Q0(r,i){r=r||10;const s=new Array(r),l=new Array(r);let c=0,d=0,p;return i=i!==void 0?i:1e3,function(w){const v=Date.now(),S=l[d];p||(p=v),s[c]=w,l[c]=v;let j=d,R=0;for(;j!==c;)R+=s[j++],j=j%r;if(c=(c+1)%r,c===d&&(d=(d+1)%r),v-p{s=S,c=null,d&&(clearTimeout(d),d=null),r.apply(null,v)};return[(...v)=>{const S=Date.now(),j=S-s;j>=l?p(v,S):(c=v,d||(d=setTimeout(()=>{d=null,p(c)},l-j)))},()=>c&&p(c)]}const gs=(r,i,s=3)=>{let l=0;const c=Q0(50,250);return G0(d=>{const p=d.loaded,m=d.lengthComputable?d.total:void 0,w=p-l,v=c(w),S=p<=m;l=p;const j={loaded:p,total:m,progress:m?p/m:void 0,bytes:w,rate:v||void 0,estimated:v&&m&&S?(m-p)/v:void 0,event:d,lengthComputable:m!=null,[i?"download":"upload"]:!0};r(j)},s)},Hf=(r,i)=>{const s=r!=null;return[l=>i[0]({lengthComputable:s,total:r,loaded:l}),i[1]]},Vf=r=>(...i)=>O.asap(()=>r(...i)),K0=tt.hasStandardBrowserEnv?((r,i)=>s=>(s=new URL(s,tt.origin),r.protocol===s.protocol&&r.host===s.host&&(i||r.port===s.port)))(new URL(tt.origin),tt.navigator&&/(msie|trident)/i.test(tt.navigator.userAgent)):()=>!0,X0=tt.hasStandardBrowserEnv?{write(r,i,s,l,c,d){const p=[r+"="+encodeURIComponent(i)];O.isNumber(s)&&p.push("expires="+new Date(s).toGMTString()),O.isString(l)&&p.push("path="+l),O.isString(c)&&p.push("domain="+c),d===!0&&p.push("secure"),document.cookie=p.join("; ")},read(r){const i=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return i?decodeURIComponent(i[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function J0(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function Z0(r,i){return i?r.replace(/\/?\/$/,"")+"/"+i.replace(/^\/+/,""):r}function nh(r,i){return r&&!J0(i)?Z0(r,i):i}const Wf=r=>r instanceof pt?{...r}:r;function Yn(r,i){i=i||{};const s={};function l(v,S,j,R){return O.isPlainObject(v)&&O.isPlainObject(S)?O.merge.call({caseless:R},v,S):O.isPlainObject(S)?O.merge({},S):O.isArray(S)?S.slice():S}function c(v,S,j,R){if(O.isUndefined(S)){if(!O.isUndefined(v))return l(void 0,v,j,R)}else return l(v,S,j,R)}function d(v,S){if(!O.isUndefined(S))return l(void 0,S)}function p(v,S){if(O.isUndefined(S)){if(!O.isUndefined(v))return l(void 0,v)}else return l(void 0,S)}function m(v,S,j){if(j in i)return l(v,S);if(j in r)return l(void 0,v)}const w={url:d,method:d,data:d,baseURL:p,transformRequest:p,transformResponse:p,paramsSerializer:p,timeout:p,timeoutMessage:p,withCredentials:p,withXSRFToken:p,adapter:p,responseType:p,xsrfCookieName:p,xsrfHeaderName:p,onUploadProgress:p,onDownloadProgress:p,decompress:p,maxContentLength:p,maxBodyLength:p,beforeRedirect:p,transport:p,httpAgent:p,httpsAgent:p,cancelToken:p,socketPath:p,responseEncoding:p,validateStatus:m,headers:(v,S,j)=>c(Wf(v),Wf(S),j,!0)};return O.forEach(Object.keys(Object.assign({},r,i)),function(S){const j=w[S]||c,R=j(r[S],i[S],S);O.isUndefined(R)&&j!==m||(s[S]=R)}),s}const rh=r=>{const i=Yn({},r);let{data:s,withXSRFToken:l,xsrfHeaderName:c,xsrfCookieName:d,headers:p,auth:m}=i;i.headers=p=pt.from(p),i.url=Xp(nh(i.baseURL,i.url),r.params,r.paramsSerializer),m&&p.set("Authorization","Basic "+btoa((m.username||"")+":"+(m.password?unescape(encodeURIComponent(m.password)):"")));let w;if(O.isFormData(s)){if(tt.hasStandardBrowserEnv||tt.hasStandardBrowserWebWorkerEnv)p.setContentType(void 0);else if((w=p.getContentType())!==!1){const[v,...S]=w?w.split(";").map(j=>j.trim()).filter(Boolean):[];p.setContentType([v||"multipart/form-data",...S].join("; "))}}if(tt.hasStandardBrowserEnv&&(l&&O.isFunction(l)&&(l=l(i)),l||l!==!1&&K0(i.url))){const v=c&&d&&X0.read(d);v&&p.set(c,v)}return i},ev=typeof XMLHttpRequest<"u",tv=ev&&function(r){return new Promise(function(s,l){const c=rh(r);let d=c.data;const p=pt.from(c.headers).normalize();let{responseType:m,onUploadProgress:w,onDownloadProgress:v}=c,S,j,R,L,T;function N(){L&&L(),T&&T(),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 V(){if(!_)return;const B=pt.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),I={data:!m||m==="text"||m==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:B,config:r,request:_};th(function(H){s(H),N()},function(H){l(H),N()},I),_=null}"onloadend"in _?_.onloadend=V:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.indexOf("file:")===0)||setTimeout(V)},_.onabort=function(){_&&(l(new ue("Request aborted",ue.ECONNABORTED,r,_)),_=null)},_.onerror=function(){l(new ue("Network Error",ue.ERR_NETWORK,r,_)),_=null},_.ontimeout=function(){let W=c.timeout?"timeout of "+c.timeout+"ms exceeded":"timeout exceeded";const I=c.transitional||Jp;c.timeoutErrorMessage&&(W=c.timeoutErrorMessage),l(new ue(W,I.clarifyTimeoutError?ue.ETIMEDOUT:ue.ECONNABORTED,r,_)),_=null},d===void 0&&p.setContentType(null),"setRequestHeader"in _&&O.forEach(p.toJSON(),function(W,I){_.setRequestHeader(I,W)}),O.isUndefined(c.withCredentials)||(_.withCredentials=!!c.withCredentials),m&&m!=="json"&&(_.responseType=c.responseType),v&&([R,T]=gs(v,!0),_.addEventListener("progress",R)),w&&_.upload&&([j,L]=gs(w),_.upload.addEventListener("progress",j),_.upload.addEventListener("loadend",L)),(c.cancelToken||c.signal)&&(S=B=>{_&&(l(!B||B.type?new Nr(null,r,_):B),_.abort(),_=null)},c.cancelToken&&c.cancelToken.subscribe(S),c.signal&&(c.signal.aborted?S():c.signal.addEventListener("abort",S)));const U=Y0(c.url);if(U&&tt.protocols.indexOf(U)===-1){l(new ue("Unsupported protocol "+U+":",ue.ERR_BAD_REQUEST,r));return}_.send(d||null)})},nv=(r,i)=>{const{length:s}=r=r?r.filter(Boolean):[];if(i||s){let l=new AbortController,c;const d=function(v){if(!c){c=!0,m();const S=v instanceof Error?v:this.reason;l.abort(S instanceof ue?S:new Nr(S instanceof Error?S.message:S))}};let p=i&&setTimeout(()=>{p=null,d(new ue(`timeout ${i} of ms exceeded`,ue.ETIMEDOUT))},i);const m=()=>{r&&(p&&clearTimeout(p),p=null,r.forEach(v=>{v.unsubscribe?v.unsubscribe(d):v.removeEventListener("abort",d)}),r=null)};r.forEach(v=>v.addEventListener("abort",d));const{signal:w}=l;return w.unsubscribe=()=>O.asap(m),w}},rv=function*(r,i){let s=r.byteLength;if(s{const c=ov(r,i);let d=0,p,m=w=>{p||(p=!0,l&&l(w))};return new ReadableStream({async pull(w){try{const{done:v,value:S}=await c.next();if(v){m(),w.close();return}let j=S.byteLength;if(s){let R=d+=j;s(R)}w.enqueue(new Uint8Array(S))}catch(v){throw m(v),v}},cancel(w){return m(w),c.return()}},{highWaterMark:2})},Ps=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",oh=Ps&&typeof ReadableStream=="function",sv=Ps&&(typeof TextEncoder=="function"?(r=>i=>r.encode(i))(new TextEncoder):async r=>new Uint8Array(await new Response(r).arrayBuffer())),ih=(r,...i)=>{try{return!!r(...i)}catch{return!1}},lv=oh&&ih(()=>{let r=!1;const i=new Request(tt.origin,{body:new ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type");return r&&!i}),Yf=64*1024,Ja=oh&&ih(()=>O.isReadableStream(new Response("").body)),ys={stream:Ja&&(r=>r.body)};Ps&&(r=>{["text","arrayBuffer","blob","formData","stream"].forEach(i=>{!ys[i]&&(ys[i]=O.isFunction(r[i])?s=>s[i]():(s,l)=>{throw new ue(`Response type '${i}' is not supported`,ue.ERR_NOT_SUPPORT,l)})})})(new Response);const av=async r=>{if(r==null)return 0;if(O.isBlob(r))return r.size;if(O.isSpecCompliantForm(r))return(await new Request(tt.origin,{method:"POST",body:r}).arrayBuffer()).byteLength;if(O.isArrayBufferView(r)||O.isArrayBuffer(r))return r.byteLength;if(O.isURLSearchParams(r)&&(r=r+""),O.isString(r))return(await sv(r)).byteLength},uv=async(r,i)=>{const s=O.toFiniteNumber(r.getContentLength());return s??av(i)},cv=Ps&&(async r=>{let{url:i,method:s,data:l,signal:c,cancelToken:d,timeout:p,onDownloadProgress:m,onUploadProgress:w,responseType:v,headers:S,withCredentials:j="same-origin",fetchOptions:R}=rh(r);v=v?(v+"").toLowerCase():"text";let L=nv([c,d&&d.toAbortSignal()],p),T;const N=L&&L.unsubscribe&&(()=>{L.unsubscribe()});let _;try{if(w&&lv&&s!=="get"&&s!=="head"&&(_=await uv(S,l))!==0){let I=new Request(i,{method:"POST",body:l,duplex:"half"}),M;if(O.isFormData(l)&&(M=I.headers.get("content-type"))&&S.setContentType(M),I.body){const[H,ie]=Hf(_,gs(Vf(w)));l=qf(I.body,Yf,H,ie)}}O.isString(j)||(j=j?"include":"omit");const V="credentials"in Request.prototype;T=new Request(i,{...R,signal:L,method:s.toUpperCase(),headers:S.normalize().toJSON(),body:l,duplex:"half",credentials:V?j:void 0});let U=await fetch(T);const B=Ja&&(v==="stream"||v==="response");if(Ja&&(m||B&&N)){const I={};["status","statusText","headers"].forEach(ve=>{I[ve]=U[ve]});const M=O.toFiniteNumber(U.headers.get("content-length")),[H,ie]=m&&Hf(M,gs(Vf(m),!0))||[];U=new Response(qf(U.body,Yf,H,()=>{ie&&ie(),N&&N()}),I)}v=v||"text";let W=await ys[O.findKey(ys,v)||"text"](U,r);return!B&&N&&N(),await new Promise((I,M)=>{th(I,M,{data:W,headers:pt.from(U.headers),status:U.status,statusText:U.statusText,config:r,request:T})})}catch(V){throw N&&N(),V&&V.name==="TypeError"&&/fetch/i.test(V.message)?Object.assign(new ue("Network Error",ue.ERR_NETWORK,r,T),{cause:V.cause||V}):ue.from(V,V&&V.code,r,T)}}),Za={http:j0,xhr:tv,fetch:cv};O.forEach(Za,(r,i)=>{if(r){try{Object.defineProperty(r,"name",{value:i})}catch{}Object.defineProperty(r,"adapterName",{value:i})}});const Qf=r=>`- ${r}`,dv=r=>O.isFunction(r)||r===null||r===!1,sh={getAdapter:r=>{r=O.isArray(r)?r:[r];const{length:i}=r;let s,l;const c={};for(let d=0;d`adapter ${m} `+(w===!1?"is not supported by the environment":"is not available in the build"));let p=i?d.length>1?`since : +`+d.map(Qf).join(` +`):" "+Qf(d[0]):"as no adapter specified";throw new ue("There is no suitable adapter to dispatch the request "+p,"ERR_NOT_SUPPORT")}return l},adapters:Za};function Ia(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Nr(null,r)}function Gf(r){return Ia(r),r.headers=pt.from(r.headers),r.data=La.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),sh.getAdapter(r.adapter||Do.adapter)(r).then(function(l){return Ia(r),l.data=La.call(r,r.transformResponse,l),l.headers=pt.from(l.headers),l},function(l){return eh(l)||(Ia(r),l&&l.response&&(l.response.data=La.call(r,r.transformResponse,l.response),l.response.headers=pt.from(l.response.headers))),Promise.reject(l)})}const lh="1.7.9",Ts={};["object","boolean","number","function","string","symbol"].forEach((r,i)=>{Ts[r]=function(l){return typeof l===r||"a"+(i<1?"n ":" ")+r}});const Kf={};Ts.transitional=function(i,s,l){function c(d,p){return"[Axios v"+lh+"] Transitional option '"+d+"'"+p+(l?". "+l:"")}return(d,p,m)=>{if(i===!1)throw new ue(c(p," has been removed"+(s?" in "+s:"")),ue.ERR_DEPRECATED);return s&&!Kf[p]&&(Kf[p]=!0,console.warn(c(p," has been deprecated since v"+s+" and will be removed in the near future"))),i?i(d,p,m):!0}};Ts.spelling=function(i){return(s,l)=>(console.warn(`${l} is likely a misspelling of ${i}`),!0)};function fv(r,i,s){if(typeof r!="object")throw new ue("options must be an object",ue.ERR_BAD_OPTION_VALUE);const l=Object.keys(r);let c=l.length;for(;c-- >0;){const d=l[c],p=i[d];if(p){const m=r[d],w=m===void 0||p(m,d,r);if(w!==!0)throw new ue("option "+d+" must be "+w,ue.ERR_BAD_OPTION_VALUE);continue}if(s!==!0)throw new ue("Unknown option "+d,ue.ERR_BAD_OPTION)}}const cs={assertOptions:fv,validators:Ts},Vt=cs.validators;class Vn{constructor(i){this.defaults=i,this.interceptors={request:new bf,response:new bf}}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=Yn(this.defaults,s);const{transitional:l,paramsSerializer:c,headers:d}=s;l!==void 0&&cs.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}:cs.assertOptions(c,{encode:Vt.function,serialize:Vt.function},!0)),cs.assertOptions(s,{baseUrl:Vt.spelling("baseURL"),withXsrfToken:Vt.spelling("withXSRFToken")},!0),s.method=(s.method||this.defaults.method||"get").toLowerCase();let p=d&&O.merge(d.common,d[s.method]);d&&O.forEach(["delete","get","head","post","put","patch","common"],T=>{delete d[T]}),s.headers=pt.concat(p,d);const m=[];let w=!0;this.interceptors.request.forEach(function(N){typeof N.runWhen=="function"&&N.runWhen(s)===!1||(w=w&&N.synchronous,m.unshift(N.fulfilled,N.rejected))});const v=[];this.interceptors.response.forEach(function(N){v.push(N.fulfilled,N.rejected)});let S,j=0,R;if(!w){const T=[Gf.bind(this),void 0];for(T.unshift.apply(T,m),T.push.apply(T,v),R=T.length,S=Promise.resolve(s);j{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 p=new Promise(m=>{l.subscribe(m),d=m}).then(c);return p.cancel=function(){l.unsubscribe(d)},p},i(function(d,p,m){l.reason||(l.reason=new Nr(d,p,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 pu(function(c){i=c}),cancel:i}}}function pv(r){return function(s){return r.apply(null,s)}}function hv(r){return O.isObject(r)&&r.isAxiosError===!0}const eu={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(eu).forEach(([r,i])=>{eu[i]=r});function ah(r){const i=new Vn(r),s=Bp(Vn.prototype.request,i);return O.extend(s,Vn.prototype,i,{allOwnKeys:!0}),O.extend(s,i,null,{allOwnKeys:!0}),s.create=function(c){return ah(Yn(r,c))},s}const Be=ah(Do);Be.Axios=Vn;Be.CanceledError=Nr;Be.CancelToken=pu;Be.isCancel=eh;Be.VERSION=lh;Be.toFormData=Rs;Be.AxiosError=ue;Be.Cancel=Be.CanceledError;Be.all=function(i){return Promise.all(i)};Be.spread=pv;Be.isAxiosError=hv;Be.mergeConfig=Yn;Be.AxiosHeaders=pt;Be.formToJSON=r=>Zp(O.isHTMLForm(r)?new FormData(r):r);Be.getAdapter=sh.getAdapter;Be.HttpStatusCode=eu;Be.default=Be;const uh={apiBaseUrl:"/api"};class mv{constructor(){uf(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 Sr=new mv,gv=async(r,i)=>{const s=new FormData;return s.append("username",r),s.append("password",i),(await zo.post("/auth/login",s,{headers:{"Content-Type":"multipart/form-data"}})).data},yv=async r=>(await zo.post("/users",r,{headers:{"Content-Type":"multipart/form-data"}})).data,vv=async()=>{await zo.get("/auth/csrf-token")},xv=async()=>{await zo.post("/auth/logout")},wv=async()=>(await zo.post("/auth/refresh")).data,Sv=async(r,i)=>{const s={userId:r,newRole:i};return(await $e.put("/auth/role",s)).data},rt=Tr((r,i)=>({currentUser:null,accessToken:null,login:async(s,l)=>{const{userDto:c,accessToken:d}=await gv(s,l);await i().fetchCsrfToken(),r({currentUser:c,accessToken:d})},logout:async()=>{await xv(),i().clear(),i().fetchCsrfToken()},fetchCsrfToken:async()=>{await vv()},refreshToken:async()=>{i().clear();const{userDto:s,accessToken:l}=await wv();r({currentUser:s,accessToken:l})},clear:()=>{r({currentUser:null,accessToken:null})},updateUserRole:async(s,l)=>{await Sv(s,l)}}));let So=[],Xi=!1;const $e=Be.create({baseURL:uh.apiBaseUrl,headers:{"Content-Type":"application/json"},withCredentials:!0}),zo=Be.create({baseURL:uh.apiBaseUrl,headers:{"Content-Type":"application/json"},withCredentials:!0});$e.interceptors.request.use(r=>{const i=rt.getState().accessToken;return i&&(r.headers.Authorization=`Bearer ${i}`),r},r=>Promise.reject(r));$e.interceptors.response.use(r=>r,async r=>{var s,l,c,d;const i=(s=r.response)==null?void 0:s.data;if(i){const p=(c=(l=r.response)==null?void 0:l.headers)==null?void 0:c["discodeit-request-id"];p&&(i.requestId=p),r.response.data=i}if(console.log({error:r,errorResponse:i}),Sr.emit("api-error",{error:r,alert:((d=r.response)==null?void 0:d.status)===403}),r.response&&r.response.status===401){const p=r.config;if(p&&p.headers&&p.headers._retry)return Sr.emit("auth-error"),Promise.reject(r);if(Xi&&p)return new Promise((m,w)=>{So.push({config:p,resolve:m,reject:w})});if(p){Xi=!0;try{return await rt.getState().refreshToken(),So.forEach(({config:m,resolve:w,reject:v})=>{m.headers=m.headers||{},m.headers._retry="true",$e(m).then(w).catch(v)}),p.headers=p.headers||{},p.headers._retry="true",So=[],Xi=!1,$e(p)}catch(m){return So.forEach(({reject:w})=>w(m)),So=[],Xi=!1,Sr.emit("auth-error"),Promise.reject(m)}}}return Promise.reject(r)});const kv=async(r,i)=>(await $e.patch(`/users/${r}`,i,{headers:{"Content-Type":"multipart/form-data"}})).data,Cv=async()=>(await $e.get("/users")).data,Rr=Tr(r=>({users:[],fetchUsers:async()=>{try{const i=await Cv();r({users:i})}catch(i){console.error("사용자 목록 조회 실패:",i)}}})),Y={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"}}},ch=C.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; +`,dh=C.div` + background: ${Y.colors.background.primary}; + padding: 32px; + border-radius: 8px; + width: 440px; + + h2 { + color: ${Y.colors.text.primary}; + margin-bottom: 24px; + font-size: 24px; + font-weight: bold; + } + + form { + display: flex; + flex-direction: column; + gap: 16px; + } +`,Ro=C.input` + width: 100%; + padding: 10px; + border-radius: 4px; + background: ${Y.colors.background.input}; + border: none; + color: ${Y.colors.text.primary}; + font-size: 16px; + + &::placeholder { + color: ${Y.colors.text.muted}; + } + + &:focus { + outline: none; + } +`;C.input.attrs({type:"checkbox"})` + width: 16px; + height: 16px; + padding: 0; + border-radius: 4px; + background: ${Y.colors.background.input}; + border: none; + color: ${Y.colors.text.primary}; + cursor: pointer; + + &:focus { + outline: none; + } + + &:checked { + background: ${Y.colors.brand.primary}; + } +`;const fh=C.button` + width: 100%; + padding: 12px; + border-radius: 4px; + background: ${Y.colors.brand.primary}; + color: white; + font-size: 16px; + font-weight: 500; + border: none; + cursor: pointer; + transition: background-color 0.2s; + + &:hover { + background: ${Y.colors.brand.hover}; + } +`,ph=C.div` + color: ${Y.colors.status.error}; + font-size: 14px; + text-align: center; +`,Ev=C.p` + text-align: center; + margin-top: 16px; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 14px; +`,jv=C.span` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,Ji=C.div` + margin-bottom: 20px; +`,Zi=C.label` + display: block; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,Da=C.span` + color: ${({theme:r})=>r.colors.status.error}; +`,Av=C.div` + display: flex; + flex-direction: column; + align-items: center; + margin: 10px 0; +`,Rv=C.img` + width: 80px; + height: 80px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,Pv=C.input` + display: none; +`,Tv=C.label` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,_v=C.span` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,Nv=C(_v)` + display: block; + text-align: center; + margin-top: 16px; +`,St="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAACXBIWXMAACE4AAAhOAFFljFgAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAw2SURBVHgB7d3PT1XpHcfxBy5g6hipSMolGViACThxJDbVRZ2FXejKlf9h/4GmC1fTRdkwC8fE0JgyJuICFkCjEA04GeZe6P0cPC0698I95zzPc57v5f1K6DSto3A8n/v9nufXGfrr338+dgBMGnYAzCLAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwbcTDvyuWh//33w1/1dexwMRBgYxTW5vVh9/vxYTcxPpR9jY0OffZrdt8fu82ttlvfbLv9j4R5kBHgxCmcE1eH3NfTDTc7PfxZte3lJNgjbmlxxK3+1HKrr1oOg4kAJ0pVdnG+4ZqTw7+psEUoxF91Qv/Di1+db/q+ZpvD7g+T6gb04XLyv6mF3//osuqvTmDn3RGdQCAEOCG6+W/ONdzNTnCrhPZLN2Yb2T99hVhdwOLcSOf37f7hknUN4yedgLoGeb3Rdv/qdAIE2S8CnIDzAuGDQrzXeTZee1OtndaHy9LCSOHvU3++vv693nLPX9LS+0KAa6QQLC2o4sb5a1A7rYGtMqPU+l7v3hpx85+qeVnfdH7W2c7z/Pcrh1RjD5gHromq2JOHY9HCK2Ojzk1dL1fhH90fqxzenDoO/X79DMjhbAQ4Mg1OPXl4KauGodrls6j6FaXKq+dZn/IQ13ENBgkBjiRvQR99V2/lmZos9lc+PxOuxdd1uL3gp6pfVDwDR6Ab9cG9Me9VLAZ1CiHpmXhz6yibakJxVODAZpoN9/iBzfCq+sboFkJ/SAwyrlxAujE1WJWSIiO/sYKlxSpTnbEBqnBxVOBA9LybWnjloM8An6ysitc1NCe5FcvgqgVw/85o1OmhItY32n39uqnJuC3/FAEuhavmmcLra77UN7XP2322qRNX494aqvgojqvmUcrhFa1+6tdXkae6tMiEhR3FEWBPNOCTcni1rZCli4OHAHuQ4mjzaewJHlxMI1Wked5Uw7v99ijbwqd/FnVQQ7WmQyiOAFegZ7a736ZzCU820h+7nbfHbnO7XSq4p3+vmHbfMwdcBgGuoO4dNQrZxtaR+08nqNueT73Y2D7qTIW5aLRXGcUR4JL03FtHeBXa9Y2jyhX2PHudiqg/K9ZuoY3t/uan8TkCXIKCG/u5V2Fae9N2a+vtKO2tjqfVnxfj5zw5O4sWugwCXIJa51hiB/e0tfVWdkZX6CrMCHl5BLigWDt0RCc6rrxo1XZQu6rw6qt2tq47FD0G9Lu8E79FgAvIWucIO3QU2B9ftpK4sVWFZ5rDQTYbqHUOcdztRcJCjgLUToauvrqpny4fJlWVlp/5P4BOH1IcbFcdAe6Tght6h5FeiaLwpnZTq5VW2HzN1eYfUoS3OgLcp9sL4cOrkKT6YrI8dFUHnDQYR3j94Rm4D9kLxQLuV009vKdpXbXae00vFdm8UWVZJ3ojwH3QcS+hnn1VifSMaemVoPqeVzqDT6rG2oivQS5dH33l70ZS262w7n04yhae8MrTMAhwH0KNPFsfyNH3vd+pxkwD1Ydn4HOodQ5VfTXHyrMgqiDA55ibCbNJX1VLc6xAFQT4HCEGr9Q6s3wQPhDgM4RqnzWVQusMHwjwGTS66puCS/WFLwT4DCHOKia88IkA96BjTkOcVbzDQgZ4RIB7CBFejTzz7AufCHAPWn3lGwse4BsB7uGa5wqcLS3k7XvwjAD3cOWy84pnX4RAgHvw/QzMLhyEQIC7CLF4Y4+DyxEAAe4iRIB3PzD6DP8IcBejnncPagCL/bAIgQB34fsc5P2PtM8IgwBHcMjJqQiEAHfBm+JhBQGO4IDlkwiEAHdx2PIbuFhv+MPFQ4C7ODx0Xo2OOiAIAhwBz9QIhQB34XvOlhYaoRDgLg5+dl7pcACqMEIgwF2EWDV1bZwAwz8C3IVOzfAd4omrXGr4x13Vg++jb6YmudTwj7uqh733fgOsM6YZzIJvBLiH3Q/+NyDMB3pNCy4u3k7Yw+57/wNZM9PDbu2NGwjqJiauDrmvpxufXiv6+f+v63fw8SjrZDgLLBwC3INO0NBAls+2V220jurZNXw6h8K6ODfibsye/UjQnNR/nnQcGk/IX/DNsbp+EeAetAVQVaQ56fe5dXGu4X54YTPASwsj7uZ8o/CHmkJ/Y7aRfb3eaBNkj3gGPsNOgNZPN7G1RR36fh8/uJS96LxqR6Kf/9H9MRa2eEKAz7C5FaZS3l6w0/goaArchMeFKPkHwrVxbr+quIJn0LNqiFZPVSjEmx98U7UNVS016PWXe6NU4ooI8DnWN8O8DuX+H0eTnxdeWgjb7uv3/vMd9lpWQYDPEep9Rrp5by+kOy+s7+/mfPhWXyPzFrqRVHHlzpFPgYTwTScg87NphjhmZdTgGMohwH1YexPupdx3b40mN5ij6tuMuHabKlweV60PGo0OdTB7ioM5WjEWW5PNHqVw1fq09ibcu33zqZpUQjzTjN/Ws1urHK5an9bWW0Ffj5JSiOv4HiaYEy6Fq9YnLa1cfRWuCku+wOHmXL2DOnUEmGOHyiHABagKh17Dqxv57rcj7k+3RpKfJ0b9CHBBKy/ivOhIU0yPH4xdqD3EV37HB1ZRBLignc6c8MZW2FY6p5ZSK7b0bNyMOM3CTiE7CHAJz1+2or7vV1Msj74by4IcoyKHOMygH4fhptsHFgEuQRXqx5fx7zYFWRX5ycNL2UqpUFV5512cDuNLvAS9ONawlaQ10jpSJsZ64S+d3iCvm3777XGntW9nx9fsfqh+JK5+Nq0Qi43WvTgCXMHqq5abma53g75Gqmen9fX/alz1CBtNmenfj7k6yvIxQ3Wiha5AN/r3K4fJtX55hVarvVTy8AB9OMV0GGdwf+AQ4IpU4f75LN27Tzt9HtwbKzynrNF2zXvHsvOWClwGAfZAN18dg1r9UnuthSFF6WeK1doS4HIIsCeqVrHbziLUUpdZornc6S5iDC5p8A3FEWCPVn9KO8RlTpVUeJ8u/xLsUAPR780UUjkE2LOUQ6x11jPN4n/l+WDdaqDznEOdO3YREOAAFOJUn4mrTA3p51KQNU/sM8g8/5bHPHAgeibWAND9O2mdtlF147yCm2/o0IeBXlyuAwDKfjDotBMWcJRHBQ5IlUUVa1Bv0O1squnkVSllvd5kAXQVBDiwfBAo5pyqFbo2od5+cVEQ4Ag0CKRnYrWedVfjlLqBlEfsrSDAEWnwJx8Eqsve+zQCrA+SOq/DoCDAkeWDQE+X63k23txKIzRUXz8IcE00Qv23f/wSta3Odim9q/+Zc6Pz3Ev19YNppJrpRtaXXrGinUMhp5zUvqfg+Uu2HvlCgBORB1nzqYtzDTc77ffoHC3CSGEAS4N5zPv6Q4ATo7lVfV253MoWXegMrKob6xWaFKax9PzNdJpfBDhRqlL7n6qy2mqFWeuY9QaDfttsfRCoXd1NYOS5rnPEBh0BNuB0mGVifOgk1Ncb2VJGbVLIdxnp12qqaHO7HXQHURH6ngZ5RVqdCLBBqqj62jCwiknbBJefEd5QCDCCUWgV3hRa+EFFgBEEbXMcBBjeabR55UWLUzYiIMDwRoHVK1iZKoqHAMMLqm49CDAqyxefID42MwCGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhv0XZkN9IbEGbp4AAAAASUVORK5CYII=",Ov=({isOpen:r,onClose:i})=>{const[s,l]=K.useState(""),[c,d]=K.useState(""),[p,m]=K.useState(""),[w,v]=K.useState(null),[S,j]=K.useState(null),[R,L]=K.useState(""),{fetchCsrfToken:T}=rt(),N=K.useCallback(()=>{S&&URL.revokeObjectURL(S),j(null),v(null),l(""),d(""),m(""),L("")},[S]),_=K.useCallback(()=>{N(),i()},[]),V=B=>{var I;const W=(I=B.target.files)==null?void 0:I[0];if(W){v(W);const M=new FileReader;M.onloadend=()=>{j(M.result)},M.readAsDataURL(W)}},U=async B=>{B.preventDefault(),L("");try{const W=new FormData;W.append("userCreateRequest",new Blob([JSON.stringify({email:s,username:c,password:p})],{type:"application/json"})),w&&W.append("profile",w),await yv(W),await T(),i()}catch{L("회원가입에 실패했습니다.")}};return r?h.jsx(ch,{children:h.jsxs(dh,{children:[h.jsx("h2",{children:"계정 만들기"}),h.jsxs("form",{onSubmit:U,children:[h.jsxs(Ji,{children:[h.jsxs(Zi,{children:["이메일 ",h.jsx(Da,{children:"*"})]}),h.jsx(Ro,{type:"email",value:s,onChange:B=>l(B.target.value),required:!0})]}),h.jsxs(Ji,{children:[h.jsxs(Zi,{children:["사용자명 ",h.jsx(Da,{children:"*"})]}),h.jsx(Ro,{type:"text",value:c,onChange:B=>d(B.target.value),required:!0})]}),h.jsxs(Ji,{children:[h.jsxs(Zi,{children:["비밀번호 ",h.jsx(Da,{children:"*"})]}),h.jsx(Ro,{type:"password",value:p,onChange:B=>m(B.target.value),required:!0})]}),h.jsxs(Ji,{children:[h.jsx(Zi,{children:"프로필 이미지"}),h.jsxs(Av,{children:[h.jsx(Rv,{src:S||St,alt:"profile"}),h.jsx(Pv,{type:"file",accept:"image/*",onChange:V,id:"profile-image"}),h.jsx(Tv,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),R&&h.jsx(ph,{children:R}),h.jsx(fh,{type:"submit",children:"계속하기"}),h.jsx(Nv,{onClick:_,children:"이미 계정이 있으신가요?"})]})]})}):null},Mv=({isOpen:r,onClose:i})=>{const[s,l]=K.useState(""),[c,d]=K.useState(""),[p,m]=K.useState(""),[w,v]=K.useState(!1),{login:S}=rt(),{fetchUsers:j}=Rr(),R=K.useCallback(()=>{l(""),d(""),m(""),v(!1)},[]),L=K.useCallback(()=>{R(),v(!0)},[R,i]),T=async()=>{var N;try{await S(s,c),await j(),R(),i()}catch(_){console.error("로그인 에러:",_),((N=_.response)==null?void 0:N.status)===401?m("아이디 또는 비밀번호가 올바르지 않습니다."):m("로그인에 실패했습니다.")}};return r?h.jsxs(h.Fragment,{children:[h.jsx(ch,{children:h.jsxs(dh,{children:[h.jsx("h2",{children:"돌아오신 것을 환영해요!"}),h.jsxs("form",{onSubmit:N=>{N.preventDefault(),T()},children:[h.jsx(Ro,{type:"text",placeholder:"사용자 이름",value:s,onChange:N=>l(N.target.value)}),h.jsx(Ro,{type:"password",placeholder:"비밀번호",value:c,onChange:N=>d(N.target.value)}),p&&h.jsx(ph,{children:p}),h.jsx(fh,{type:"submit",children:"로그인"})]}),h.jsxs(Ev,{children:["계정이 필요한가요? ",h.jsx(jv,{onClick:L,children:"가입하기"})]})]})}),h.jsx(Ov,{isOpen:w,onClose:()=>v(!1)})]}):null},Lv=async r=>(await $e.get(`/channels?userId=${r}`)).data,Iv=async r=>(await $e.post("/channels/public",r)).data,Dv=async r=>{const i={participantIds:r};return(await $e.post("/channels/private",i)).data},zv=async(r,i)=>(await $e.patch(`/channels/${r}`,i)).data,$v=async r=>{await $e.delete(`/channels/${r}`)},Bv=async r=>(await $e.get("/readStatuses",{params:{userId:r}})).data,Fv=async(r,i)=>{const s={newLastReadAt:i};return(await $e.patch(`/readStatuses/${r}`,s)).data},bv=async(r,i,s)=>{const l={userId:r,channelId:i,lastReadAt:s};return(await $e.post("/readStatuses",l)).data},Po=Tr((r,i)=>({readStatuses:{},fetchReadStatuses:async()=>{try{const{currentUser:s}=rt.getState();if(!s)return;const c=(await Bv(s.id)).reduce((d,p)=>(d[p.channelId]={id:p.id,lastReadAt:p.lastReadAt},d),{});r({readStatuses:c})}catch(s){console.error("읽음 상태 조회 실패:",s)}},updateReadStatus:async s=>{try{const{currentUser:l}=rt.getState();if(!l)return;const c=i().readStatuses[s];let d;c?d=await Fv(c.id,new Date().toISOString()):d=await bv(l.id,s,new Date().toISOString()),r(p=>({readStatuses:{...p.readStatuses,[s]:{id:d.id,lastReadAt:d.lastReadAt}}}))}catch(l){console.error("읽음 상태 업데이트 실패:",l)}},hasUnreadMessages:(s,l)=>{const c=i().readStatuses[s],d=c==null?void 0:c.lastReadAt;return!d||new Date(l)>new Date(d)}})),jn=Tr((r,i)=>({channels:[],pollingInterval:null,loading:!1,error:null,fetchChannels:async s=>{r({loading:!0,error:null});try{const l=await Lv(s);r(d=>{const p=new Set(d.channels.map(S=>S.id)),m=l.filter(S=>!p.has(S.id));return{channels:[...d.channels.filter(S=>l.some(j=>j.id===S.id)),...m],loading:!1}});const{fetchReadStatuses:c}=Po.getState();return c(),l}catch(l){return r({error:l,loading:!1}),[]}},startPolling:s=>{const l=i().pollingInterval;l&&clearInterval(l);const c=setInterval(()=>{i().fetchChannels(s)},3e3);r({pollingInterval:c})},stopPolling:()=>{const s=i().pollingInterval;s&&(clearInterval(s),r({pollingInterval:null}))},createPublicChannel:async s=>{try{const l=await Iv(s);return r(c=>c.channels.some(p=>p.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 Dv(s);return r(c=>c.channels.some(p=>p.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 zv(s,l);return r(d=>({channels:d.channels.map(p=>p.id===s?{...p,...c}:p)})),c}catch(c){throw console.error("채널 수정 실패:",c),c}},deleteChannel:async s=>{try{await $v(s),r(l=>({channels:l.channels.filter(c=>c.id!==s)}))}catch(l){throw console.error("채널 삭제 실패:",l),l}}})),Uv=async r=>(await $e.get(`/binaryContents/${r}`)).data,Hv=async r=>({blob:(await $e.get(`/binaryContents/${r}/download`,{responseType:"blob"})).data}),An=Tr((r,i)=>({binaryContents:{},fetchBinaryContent:async s=>{if(i().binaryContents[s])return i().binaryContents[s];try{const l=await Uv(s),{contentType:c,fileName:d,size:p}=l,m=await Hv(s),w=URL.createObjectURL(m.blob),v={url:w,contentType:c,fileName:d,size:p,revokeUrl:()=>URL.revokeObjectURL(w)};return r(S=>({binaryContents:{...S.binaryContents,[s]:v}})),v}catch(l){return console.error("첨부파일 정보 조회 실패:",l),null}},clearBinaryContent:s=>{const{binaryContents:l}=i(),c=l[s];c!=null&&c.revokeUrl&&(c.revokeUrl(),r(d=>{const{[s]:p,...m}=d.binaryContents;return{binaryContents:m}}))},clearBinaryContents:s=>{const{binaryContents:l}=i(),c=[];s.forEach(d=>{const p=l[d];p&&(p.revokeUrl&&p.revokeUrl(),c.push(d))}),c.length>0&&r(d=>{const p={...d.binaryContents};return c.forEach(m=>{delete p[m]}),{binaryContents:p}})},clearAllBinaryContents:()=>{const{binaryContents:s}=i();Object.values(s).forEach(l=>{l.revokeUrl&&l.revokeUrl()}),r({binaryContents:{}})}})),$o=C.div` + position: absolute; + bottom: -3px; + right: -3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: ${r=>r.$online?Y.colors.status.online:Y.colors.status.offline}; + border: 4px solid ${r=>r.$background||Y.colors.background.secondary}; +`;C.div` + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + background: ${r=>Y.colors.status[r.status||"offline"]||Y.colors.status.offline}; +`;const Or=C.div` + position: relative; + width: ${r=>r.$size||"32px"}; + height: ${r=>r.$size||"32px"}; + flex-shrink: 0; + margin: ${r=>r.$margin||"0"}; +`,nn=C.img` + width: 100%; + height: 100%; + border-radius: 50%; + object-fit: cover; + border: ${r=>r.$border||"none"}; +`;function Vv({isOpen:r,onClose:i,user:s}){var M,H;const[l,c]=K.useState(s.username),[d,p]=K.useState(s.email),[m,w]=K.useState(""),[v,S]=K.useState(null),[j,R]=K.useState(""),[L,T]=K.useState(null),{binaryContents:N,fetchBinaryContent:_}=An(),{logout:V,refreshToken:U}=rt();K.useEffect(()=>{var ie;(ie=s.profile)!=null&&ie.id&&!N[s.profile.id]&&_(s.profile.id)},[s.profile,N,_]);const B=()=>{c(s.username),p(s.email),w(""),S(null),T(null),R(""),i()},W=ie=>{var Oe;const ve=(Oe=ie.target.files)==null?void 0:Oe[0];if(ve){S(ve);const ot=new FileReader;ot.onloadend=()=>{T(ot.result)},ot.readAsDataURL(ve)}},I=async ie=>{ie.preventDefault(),R("");try{const ve=new FormData,Oe={};l!==s.username&&(Oe.newUsername=l),d!==s.email&&(Oe.newEmail=d),m&&(Oe.newPassword=m),(Object.keys(Oe).length>0||v)&&(ve.append("userUpdateRequest",new Blob([JSON.stringify(Oe)],{type:"application/json"})),v&&ve.append("profile",v),await kv(s.id,ve),await U()),i()}catch{R("사용자 정보 수정에 실패했습니다.")}};return r?h.jsx(Wv,{children:h.jsxs(qv,{children:[h.jsx("h2",{children:"프로필 수정"}),h.jsxs("form",{onSubmit:I,children:[h.jsxs(es,{children:[h.jsx(ts,{children:"프로필 이미지"}),h.jsxs(Qv,{children:[h.jsx(Gv,{src:L||((M=s.profile)!=null&&M.id?(H=N[s.profile.id])==null?void 0:H.url:void 0)||St,alt:"profile"}),h.jsx(Kv,{type:"file",accept:"image/*",onChange:W,id:"profile-image"}),h.jsx(Xv,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),h.jsxs(es,{children:[h.jsxs(ts,{children:["사용자명 ",h.jsx(Jf,{children:"*"})]}),h.jsx(za,{type:"text",value:l,onChange:ie=>c(ie.target.value),required:!0})]}),h.jsxs(es,{children:[h.jsxs(ts,{children:["이메일 ",h.jsx(Jf,{children:"*"})]}),h.jsx(za,{type:"email",value:d,onChange:ie=>p(ie.target.value),required:!0})]}),h.jsxs(es,{children:[h.jsx(ts,{children:"새 비밀번호"}),h.jsx(za,{type:"password",placeholder:"변경하지 않으려면 비워두세요",value:m,onChange:ie=>w(ie.target.value)})]}),j&&h.jsx(Yv,{children:j}),h.jsxs(Jv,{children:[h.jsx(Xf,{type:"button",onClick:B,$secondary:!0,children:"취소"}),h.jsx(Xf,{type:"submit",children:"저장"})]})]}),h.jsx(Zv,{onClick:V,children:"로그아웃"})]})}):null}const Wv=C.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; +`,qv=C.div` + background: ${({theme:r})=>r.colors.background.secondary}; + padding: 32px; + border-radius: 5px; + width: 100%; + max-width: 480px; + + h2 { + color: ${({theme:r})=>r.colors.text.primary}; + margin-bottom: 24px; + text-align: center; + font-size: 24px; + } +`,za=C.input` + width: 100%; + padding: 10px; + margin-bottom: 10px; + border: none; + border-radius: 4px; + background: ${({theme:r})=>r.colors.background.input}; + color: ${({theme:r})=>r.colors.text.primary}; + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${({theme:r})=>r.colors.brand.primary}; + } +`,Xf=C.button` + width: 100%; + padding: 10px; + border: none; + border-radius: 4px; + background: ${({$secondary:r,theme:i})=>r?"transparent":i.colors.brand.primary}; + color: ${({theme:r})=>r.colors.text.primary}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({$secondary:r,theme:i})=>r?i.colors.background.hover:i.colors.brand.hover}; + } +`,Yv=C.div` + color: ${({theme:r})=>r.colors.status.error}; + font-size: 14px; + margin-bottom: 10px; +`,Qv=C.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 20px; +`,Gv=C.img` + width: 100px; + height: 100px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,Kv=C.input` + display: none; +`,Xv=C.label` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,Jv=C.div` + display: flex; + gap: 10px; + margin-top: 20px; +`,Zv=C.button` + width: 100%; + padding: 10px; + margin-top: 16px; + border: none; + border-radius: 4px; + background: transparent; + color: ${({theme:r})=>r.colors.status.error}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({theme:r})=>r.colors.status.error}20; + } +`,es=C.div` + margin-bottom: 20px; +`,ts=C.label` + display: block; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,Jf=C.span` + color: ${({theme:r})=>r.colors.status.error}; +`,ex=C.div` + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.5rem 0.75rem; + background-color: ${({theme:r})=>r.colors.background.tertiary}; + width: 100%; + height: 52px; +`,tx=C(Or)``;C(nn)``;const nx=C.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; +`,rx=C.div` + font-weight: 500; + color: ${({theme:r})=>r.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.875rem; + line-height: 1.2; +`,ox=C.div` + font-size: 0.75rem; + color: ${({theme:r})=>r.colors.text.secondary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.2; +`,ix=C.div` + display: flex; + align-items: center; + flex-shrink: 0; +`,sx=C.button` + background: none; + border: none; + padding: 0.25rem; + cursor: pointer; + color: ${({theme:r})=>r.colors.text.secondary}; + font-size: 18px; + + &:hover { + color: ${({theme:r})=>r.colors.text.primary}; + } +`;function lx({user:r}){var d,p;const[i,s]=K.useState(!1),{binaryContents:l,fetchBinaryContent:c}=An();return K.useEffect(()=>{var m;(m=r.profile)!=null&&m.id&&!l[r.profile.id]&&c(r.profile.id)},[r.profile,l,c]),h.jsxs(h.Fragment,{children:[h.jsxs(ex,{children:[h.jsxs(tx,{children:[h.jsx(nn,{src:(d=r.profile)!=null&&d.id?(p=l[r.profile.id])==null?void 0:p.url:St,alt:r.username}),h.jsx($o,{$online:!0})]}),h.jsxs(nx,{children:[h.jsx(rx,{children:r.username}),h.jsx(ox,{children:"온라인"})]}),h.jsx(ix,{children:h.jsx(sx,{onClick:()=>s(!0),children:"⚙️"})})]}),h.jsx(Vv,{isOpen:i,onClose:()=>s(!1),user:r})]})}const ax=C.div` + width: 240px; + background: ${Y.colors.background.secondary}; + border-right: 1px solid ${Y.colors.border.primary}; + display: flex; + flex-direction: column; +`,ux=C.div` + flex: 1; + overflow-y: auto; +`,cx=C.div` + padding: 16px; + font-size: 16px; + font-weight: bold; + color: ${Y.colors.text.primary}; +`,hu=C.div` + height: 34px; + padding: 0 8px; + margin: 1px 8px; + display: flex; + align-items: center; + gap: 6px; + color: ${r=>r.$hasUnread?r.theme.colors.text.primary:r.theme.colors.text.muted}; + font-weight: ${r=>r.$hasUnread?"600":"normal"}; + cursor: pointer; + background: ${r=>r.$isActive?r.theme.colors.background.hover:"transparent"}; + border-radius: 4px; + + &:hover { + background: ${r=>r.theme.colors.background.hover}; + color: ${r=>r.theme.colors.text.primary}; + } +`,Zf=C.div` + margin-bottom: 8px; +`,tu=C.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${Y.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: ${Y.colors.text.primary}; + } +`,ep=C.span` + margin-right: 4px; + font-size: 10px; + transition: transform 0.2s; + transform: rotate(${r=>r.$folded?"-90deg":"0deg"}); +`,tp=C.div` + display: ${r=>r.$folded?"none":"block"}; +`,nu=C(hu)` + height: ${r=>r.hasSubtext?"42px":"34px"}; +`,dx=C(Or)` + width: 32px; + height: 32px; + margin: 0 8px; +`,np=C.div` + font-size: 16px; + line-height: 18px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: ${r=>r.$isActive||r.$hasUnread?r.theme.colors.text.primary:r.theme.colors.text.muted}; + font-weight: ${r=>r.$hasUnread?"600":"normal"}; +`;C($o)` + border-color: ${Y.colors.background.primary}; +`;const rp=C.button` + background: none; + border: none; + color: ${Y.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; + + ${tu}:hover & { + opacity: 1; + } + + &:hover { + color: ${Y.colors.text.primary}; + } +`,fx=C(Or)` + width: 40px; + height: 24px; + margin: 0 8px; +`,px=C.div` + font-size: 12px; + line-height: 13px; + color: ${Y.colors.text.muted}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,op=C.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; +`,hh=C.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; +`,mh=C.div` + background: ${Y.colors.background.primary}; + border-radius: 4px; + width: 440px; + max-width: 90%; +`,gh=C.div` + padding: 16px; + display: flex; + justify-content: space-between; + align-items: center; +`,yh=C.h2` + color: ${Y.colors.text.primary}; + font-size: 20px; + font-weight: 600; + margin: 0; +`,vh=C.div` + padding: 0 16px 16px; +`,xh=C.form` + display: flex; + flex-direction: column; + gap: 16px; +`,To=C.div` + display: flex; + flex-direction: column; + gap: 8px; +`,_o=C.label` + color: ${Y.colors.text.primary}; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; +`,wh=C.p` + color: ${Y.colors.text.muted}; + font-size: 14px; + margin: -4px 0 0; +`,Lo=C.input` + padding: 10px; + background: ${Y.colors.background.tertiary}; + border: none; + border-radius: 3px; + color: ${Y.colors.text.primary}; + font-size: 16px; + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${Y.colors.status.online}; + } + + &::placeholder { + color: ${Y.colors.text.muted}; + } +`,Sh=C.button` + margin-top: 8px; + padding: 12px; + background: ${Y.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; + } +`,kh=C.button` + background: none; + border: none; + color: ${Y.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px; + line-height: 1; + + &:hover { + color: ${Y.colors.text.primary}; + } +`,hx=C(Lo)` + margin-bottom: 8px; +`,mx=C.div` + max-height: 300px; + overflow-y: auto; + background: ${Y.colors.background.tertiary}; + border-radius: 4px; +`,gx=C.div` + display: flex; + align-items: center; + padding: 8px 12px; + cursor: pointer; + transition: background 0.2s; + + &:hover { + background: ${Y.colors.background.hover}; + } + + & + & { + border-top: 1px solid ${Y.colors.border.primary}; + } +`,yx=C.input` + margin-right: 12px; + width: 16px; + height: 16px; + cursor: pointer; +`,ip=C.img` + width: 32px; + height: 32px; + border-radius: 50%; + margin-right: 12px; +`,vx=C.div` + flex: 1; + min-width: 0; +`,xx=C.div` + color: ${Y.colors.text.primary}; + font-size: 14px; + font-weight: 500; +`,wx=C.div` + color: ${Y.colors.text.muted}; + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,Sx=C.div` + padding: 16px; + text-align: center; + color: ${Y.colors.text.muted}; +`,Ch=C.div` + color: ${Y.colors.status.error}; + font-size: 14px; + padding: 8px 0; + text-align: center; + background-color: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 4px; + margin-bottom: 8px; +`,$a=C.div` + position: relative; + margin-left: auto; + z-index: 99999; +`,Ba=C.button` + background: none; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.background.hover}; + color: ${({theme:r})=>r.colors.text.primary}; + } + + ${hu}:hover &, + ${nu}:hover & { + opacity: 1; + } +`,Fa=C.div` + position: absolute; + top: 100%; + right: 0; + background: ${({theme:r})=>r.colors.background.primary}; + border: 1px solid ${({theme:r})=>r.colors.border.primary}; + border-radius: 4px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); + min-width: 120px; + z-index: 100000; +`,ns=C.div` + padding: 8px 12px; + color: ${({theme:r})=>r.colors.text.primary}; + cursor: pointer; + font-size: 14px; + display: flex; + align-items: center; + gap: 8px; + + &:hover { + background: ${({theme:r})=>r.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 kx(){return h.jsx(cx,{children:"채널 목록"})}var En=(r=>(r.USER="USER",r.CHANNEL_MANAGER="CHANNEL_MANAGER",r.ADMIN="ADMIN",r))(En||{});function Cx({isOpen:r,channel:i,onClose:s,onUpdateSuccess:l}){const[c,d]=K.useState({name:"",description:""}),[p,m]=K.useState(""),[w,v]=K.useState(!1),{updatePublicChannel:S}=jn();K.useEffect(()=>{i&&r&&(d({name:i.name||"",description:i.description||""}),m(""))},[i,r]);const j=L=>{const{name:T,value:N}=L.target;d(_=>({..._,[T]:N}))},R=async L=>{var T,N;if(L.preventDefault(),!!i){m(""),v(!0);try{if(!c.name.trim()){m("채널 이름을 입력해주세요."),v(!1);return}const _={newName:c.name.trim(),newDescription:c.description.trim()},V=await S(i.id,_);l(V)}catch(_){console.error("채널 수정 실패:",_),m(((N=(T=_.response)==null?void 0:T.data)==null?void 0:N.message)||"채널 수정에 실패했습니다. 다시 시도해주세요.")}finally{v(!1)}}};return!r||!i||i.type!=="PUBLIC"?null:h.jsx(hh,{onClick:s,children:h.jsxs(mh,{onClick:L=>L.stopPropagation(),children:[h.jsxs(gh,{children:[h.jsx(yh,{children:"채널 수정"}),h.jsx(kh,{onClick:s,children:"×"})]}),h.jsx(vh,{children:h.jsxs(xh,{onSubmit:R,children:[p&&h.jsx(Ch,{children:p}),h.jsxs(To,{children:[h.jsx(_o,{children:"채널 이름"}),h.jsx(Lo,{name:"name",value:c.name,onChange:j,placeholder:"새로운-채널",required:!0,disabled:w})]}),h.jsxs(To,{children:[h.jsx(_o,{children:"채널 설명"}),h.jsx(wh,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Lo,{name:"description",value:c.description,onChange:j,placeholder:"채널 설명을 입력하세요",disabled:w})]}),h.jsx(Sh,{type:"submit",disabled:w,children:w?"수정 중...":"채널 수정"})]})})]})})}function sp({channel:r,isActive:i,onClick:s,hasUnread:l}){var U;const{currentUser:c}=rt(),{binaryContents:d}=An(),{deleteChannel:p}=jn(),[m,w]=K.useState(null),[v,S]=K.useState(!1),j=(c==null?void 0:c.role)===En.ADMIN||(c==null?void 0:c.role)===En.CHANNEL_MANAGER;K.useEffect(()=>{const B=()=>{m&&w(null)};if(m)return document.addEventListener("click",B),()=>document.removeEventListener("click",B)},[m]);const R=B=>{w(m===B?null:B)},L=()=>{w(null),S(!0)},T=B=>{S(!1),console.log("Channel updated successfully:",B)},N=()=>{S(!1)},_=async B=>{var I;w(null);const W=r.type==="PUBLIC"?r.name:r.type==="PRIVATE"&&r.participants.length>2?`그룹 채팅 (멤버 ${r.participants.length}명)`:((I=r.participants.filter(M=>M.id!==(c==null?void 0:c.id))[0])==null?void 0:I.username)||"1:1 채팅";if(confirm(`"${W}" 채널을 삭제하시겠습니까?`))try{await p(B),console.log("Channel deleted successfully:",B)}catch(M){console.error("Channel delete failed:",M),alert("채널 삭제에 실패했습니다. 다시 시도해주세요.")}};let V;if(r.type==="PUBLIC")V=h.jsxs(hu,{$isActive:i,onClick:s,$hasUnread:l,children:["# ",r.name,j&&h.jsxs($a,{children:[h.jsx(Ba,{onClick:B=>{B.stopPropagation(),R(r.id)},children:"⋯"}),m===r.id&&h.jsxs(Fa,{onClick:B=>B.stopPropagation(),children:[h.jsx(ns,{onClick:()=>L(),children:"✏️ 수정"}),h.jsx(ns,{onClick:()=>_(r.id),children:"🗑️ 삭제"})]})]})]});else{const B=r.participants;if(B.length>2){const W=B.filter(I=>I.id!==(c==null?void 0:c.id)).map(I=>I.username).join(", ");V=h.jsxs(nu,{$isActive:i,onClick:s,children:[h.jsx(fx,{children:B.filter(I=>I.id!==(c==null?void 0:c.id)).slice(0,2).map((I,M)=>{var H;return h.jsx(nn,{src:I.profile?(H=d[I.profile.id])==null?void 0:H.url:St,style:{position:"absolute",left:M*16,zIndex:2-M,width:"24px",height:"24px",border:"2px solid #2a2a2a"}},I.id)})}),h.jsxs(op,{children:[h.jsx(np,{$hasUnread:l,children:W}),h.jsxs(px,{children:["멤버 ",B.length,"명"]})]}),j&&h.jsxs($a,{children:[h.jsx(Ba,{onClick:I=>{I.stopPropagation(),R(r.id)},children:"⋯"}),m===r.id&&h.jsx(Fa,{onClick:I=>I.stopPropagation(),children:h.jsx(ns,{onClick:()=>_(r.id),children:"🗑️ 삭제"})})]})]})}else{const W=B.filter(I=>I.id!==(c==null?void 0:c.id))[0];V=W?h.jsxs(nu,{$isActive:i,onClick:s,children:[h.jsxs(dx,{children:[h.jsx(nn,{src:W.profile?(U=d[W.profile.id])==null?void 0:U.url:St,alt:"profile"}),h.jsx($o,{$online:W.online})]}),h.jsx(op,{children:h.jsx(np,{$hasUnread:l,children:W.username})}),j&&h.jsxs($a,{children:[h.jsx(Ba,{onClick:I=>{I.stopPropagation(),R(r.id)},children:"⋯"}),m===r.id&&h.jsx(Fa,{onClick:I=>I.stopPropagation(),children:h.jsx(ns,{onClick:()=>_(r.id),children:"🗑️ 삭제"})})]})]}):h.jsx("div",{})}}return h.jsxs(h.Fragment,{children:[V,h.jsx(Cx,{isOpen:v,channel:r,onClose:N,onUpdateSuccess:T})]})}function Ex({isOpen:r,type:i,onClose:s,onCreateSuccess:l}){const[c,d]=K.useState({name:"",description:""}),[p,m]=K.useState(""),[w,v]=K.useState([]),[S,j]=K.useState(""),R=Rr(I=>I.users),L=An(I=>I.binaryContents),{currentUser:T}=rt(),N=K.useMemo(()=>R.filter(I=>I.id!==(T==null?void 0:T.id)).filter(I=>I.username.toLowerCase().includes(p.toLowerCase())||I.email.toLowerCase().includes(p.toLowerCase())),[p,R,T]),_=jn(I=>I.createPublicChannel),V=jn(I=>I.createPrivateChannel),U=I=>{const{name:M,value:H}=I.target;d(ie=>({...ie,[M]:H}))},B=I=>{v(M=>M.includes(I)?M.filter(H=>H!==I):[...M,I])},W=async I=>{var M,H;I.preventDefault(),j("");try{let ie;if(i==="PUBLIC"){if(!c.name.trim()){j("채널 이름을 입력해주세요.");return}const ve={name:c.name,description:c.description};ie=await _(ve)}else{if(w.length===0){j("대화 상대를 선택해주세요.");return}const ve=(T==null?void 0:T.id)&&[...w,T.id]||w;ie=await V(ve)}l(ie)}catch(ie){console.error("채널 생성 실패:",ie),j(((H=(M=ie.response)==null?void 0:M.data)==null?void 0:H.message)||"채널 생성에 실패했습니다. 다시 시도해주세요.")}};return r?h.jsx(hh,{onClick:s,children:h.jsxs(mh,{onClick:I=>I.stopPropagation(),children:[h.jsxs(gh,{children:[h.jsx(yh,{children:i==="PUBLIC"?"채널 만들기":"개인 메시지 시작하기"}),h.jsx(kh,{onClick:s,children:"×"})]}),h.jsx(vh,{children:h.jsxs(xh,{onSubmit:W,children:[S&&h.jsx(Ch,{children:S}),i==="PUBLIC"?h.jsxs(h.Fragment,{children:[h.jsxs(To,{children:[h.jsx(_o,{children:"채널 이름"}),h.jsx(Lo,{name:"name",value:c.name,onChange:U,placeholder:"새로운-채널",required:!0})]}),h.jsxs(To,{children:[h.jsx(_o,{children:"채널 설명"}),h.jsx(wh,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Lo,{name:"description",value:c.description,onChange:U,placeholder:"채널 설명을 입력하세요"})]})]}):h.jsxs(To,{children:[h.jsx(_o,{children:"사용자 검색"}),h.jsx(hx,{type:"text",value:p,onChange:I=>m(I.target.value),placeholder:"사용자명 또는 이메일로 검색"}),h.jsx(mx,{children:N.length>0?N.map(I=>h.jsxs(gx,{children:[h.jsx(yx,{type:"checkbox",checked:w.includes(I.id),onChange:()=>B(I.id)}),I.profile?h.jsx(ip,{src:L[I.profile.id].url}):h.jsx(ip,{src:St}),h.jsxs(vx,{children:[h.jsx(xx,{children:I.username}),h.jsx(wx,{children:I.email})]})]},I.id)):h.jsx(Sx,{children:"검색 결과가 없습니다."})})]}),h.jsx(Sh,{type:"submit",children:i==="PUBLIC"?"채널 만들기":"대화 시작하기"})]})})]})}):null}function jx({currentUser:r,activeChannel:i,onChannelSelect:s}){var W,I;const[l,c]=K.useState({PUBLIC:!1,PRIVATE:!1}),[d,p]=K.useState({isOpen:!1,type:null}),m=jn(M=>M.channels),w=jn(M=>M.fetchChannels),v=jn(M=>M.startPolling),S=jn(M=>M.stopPolling),j=Po(M=>M.fetchReadStatuses),R=Po(M=>M.updateReadStatus),L=Po(M=>M.hasUnreadMessages);K.useEffect(()=>{if(r)return w(r.id),j(),v(r.id),()=>{S()}},[r,w,j,v,S]);const T=M=>{c(H=>({...H,[M]:!H[M]}))},N=(M,H)=>{H.stopPropagation(),p({isOpen:!0,type:M})},_=()=>{p({isOpen:!1,type:null})},V=async M=>{try{const ie=(await w(r.id)).find(ve=>ve.id===M.id);ie&&s(ie),_()}catch(H){console.error("채널 생성 실패:",H)}},U=M=>{s(M),R(M.id)},B=m.reduce((M,H)=>(M[H.type]||(M[H.type]=[]),M[H.type].push(H),M),{});return h.jsxs(ax,{children:[h.jsx(kx,{}),h.jsxs(ux,{children:[h.jsxs(Zf,{children:[h.jsxs(tu,{onClick:()=>T("PUBLIC"),children:[h.jsx(ep,{$folded:l.PUBLIC,children:"▼"}),h.jsx("span",{children:"일반 채널"}),h.jsx(rp,{onClick:M=>N("PUBLIC",M),children:"+"})]}),h.jsx(tp,{$folded:l.PUBLIC,children:(W=B.PUBLIC)==null?void 0:W.map(M=>h.jsx(sp,{channel:M,isActive:(i==null?void 0:i.id)===M.id,hasUnread:L(M.id,M.lastMessageAt),onClick:()=>U(M)},M.id))})]}),h.jsxs(Zf,{children:[h.jsxs(tu,{onClick:()=>T("PRIVATE"),children:[h.jsx(ep,{$folded:l.PRIVATE,children:"▼"}),h.jsx("span",{children:"개인 메시지"}),h.jsx(rp,{onClick:M=>N("PRIVATE",M),children:"+"})]}),h.jsx(tp,{$folded:l.PRIVATE,children:(I=B.PRIVATE)==null?void 0:I.map(M=>h.jsx(sp,{channel:M,isActive:(i==null?void 0:i.id)===M.id,hasUnread:L(M.id,M.lastMessageAt),onClick:()=>U(M)},M.id))})]})]}),h.jsx(Ax,{children:h.jsx(lx,{user:r})}),h.jsx(Ex,{isOpen:d.isOpen,type:d.type,onClose:_,onCreateSuccess:V})]})}const Ax=C.div` + margin-top: auto; + border-top: 1px solid ${({theme:r})=>r.colors.border.primary}; + background-color: ${({theme:r})=>r.colors.background.tertiary}; +`,Rx=C.div` + flex: 1; + display: flex; + flex-direction: column; + background: ${({theme:r})=>r.colors.background.primary}; +`,Px=C.div` + display: flex; + flex-direction: column; + height: 100%; + background: ${({theme:r})=>r.colors.background.primary}; +`,Tx=C(Px)` + justify-content: center; + align-items: center; + flex: 1; + padding: 0 20px; +`,_x=C.div` + text-align: center; + max-width: 400px; + padding: 20px; + margin-bottom: 80px; +`,Nx=C.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); } + } +`,Ox=C.h2` + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 28px; + font-weight: 700; + margin-bottom: 16px; +`,Mx=C.p` + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 16px; + line-height: 1.6; + word-break: keep-all; +`,lp=C.div` + height: 48px; + padding: 0 16px; + background: ${Y.colors.background.primary}; + border-bottom: 1px solid ${Y.colors.border.primary}; + display: flex; + align-items: center; +`,ap=C.div` + display: flex; + align-items: center; + gap: 8px; + height: 100%; +`,Lx=C.div` + display: flex; + align-items: center; + gap: 12px; + height: 100%; +`,Ix=C(Or)` + width: 24px; + height: 24px; +`;C.img` + width: 24px; + height: 24px; + border-radius: 50%; +`;const Dx=C.div` + position: relative; + width: 40px; + height: 24px; + flex-shrink: 0; +`,zx=C($o)` + border-color: ${Y.colors.background.primary}; + bottom: -3px; + right: -3px; +`,$x=C.div` + font-size: 12px; + color: ${Y.colors.text.muted}; + line-height: 13px; +`,up=C.div` + font-weight: bold; + color: ${Y.colors.text.primary}; + line-height: 20px; + font-size: 16px; +`,Bx=C.div` + flex: 1; + display: flex; + flex-direction: column-reverse; + overflow-y: auto; + position: relative; +`,Fx=C.div` + padding: 16px; + display: flex; + flex-direction: column; +`,Eh=C.div` + margin-bottom: 16px; + display: flex; + align-items: flex-start; + position: relative; + z-index: 1; +`,bx=C(Or)` + margin-right: 16px; + width: 40px; + height: 40px; +`;C.img` + width: 40px; + height: 40px; + border-radius: 50%; +`;const Ux=C.div` + display: flex; + align-items: center; + margin-bottom: 4px; + position: relative; +`,Hx=C.span` + font-weight: bold; + color: ${Y.colors.text.primary}; + margin-right: 8px; +`,Vx=C.span` + font-size: 0.75rem; + color: ${Y.colors.text.muted}; +`,Wx=C.div` + color: ${Y.colors.text.secondary}; + margin-top: 4px; +`,qx=C.form` + display: flex; + align-items: center; + gap: 8px; + padding: 16px; + background: ${({theme:r})=>r.colors.background.secondary}; + position: relative; + z-index: 1; +`,Yx=C.textarea` + flex: 1; + padding: 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border: none; + border-radius: 4px; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + resize: none; + min-height: 44px; + max-height: 144px; + + &:focus { + outline: none; + } + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } +`,Qx=C.button` + background: none; + border: none; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px 8px; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + color: ${({theme:r})=>r.colors.text.primary}; + } +`;C.div` + flex: 1; + display: flex; + align-items: center; + justify-content: center; + color: ${Y.colors.text.muted}; + font-size: 16px; + font-weight: 500; + padding: 20px; + text-align: center; +`;const cp=C.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; + width: 100%; +`,Gx=C.a` + display: block; + border-radius: 4px; + overflow: hidden; + max-width: 300px; + + img { + width: 100%; + height: auto; + display: block; + } +`,Kx=C.a` + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 8px; + text-decoration: none; + width: fit-content; + + &:hover { + background: ${({theme:r})=>r.colors.background.hover}; + } +`,Xx=C.div` + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + font-size: 40px; + color: #0B93F6; +`,Jx=C.div` + display: flex; + flex-direction: column; + gap: 2px; +`,Zx=C.span` + font-size: 14px; + color: #0B93F6; + font-weight: 500; +`,e1=C.span` + font-size: 13px; + color: ${({theme:r})=>r.colors.text.muted}; +`,t1=C.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px 0; +`,jh=C.div` + position: relative; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 4px; + max-width: 300px; +`,n1=C(jh)` + padding: 0; + overflow: hidden; + width: 200px; + height: 120px; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } +`,r1=C.div` + color: #0B93F6; + font-size: 20px; +`,o1=C.div` + font-size: 13px; + color: ${({theme:r})=>r.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,dp=C.button` + position: absolute; + top: -6px; + right: -6px; + width: 20px; + height: 20px; + border-radius: 50%; + background: ${({theme:r})=>r.colors.background.secondary}; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.text.primary}; + } +`,i1=C.div` + position: relative; + margin-left: auto; + z-index: 99999; +`,s1=C.button` + background: none; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.text.primary}; + background: ${({theme:r})=>r.colors.background.hover}; + } + + ${Eh}:hover & { + opacity: 1; + } +`,l1=C.div` + position: absolute; + top: 0; + background: ${({theme:r})=>r.colors.background.primary}; + border: 1px solid ${({theme:r})=>r.colors.border.primary}; + border-radius: 6px; + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15); + width: 80px; + z-index: 99999; + overflow: hidden; +`,fp=C.button` + display: flex; + align-items: center; + gap: 8px; + width: fit-content; + background: none; + border: none; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + cursor: pointer; + text-align: center ; + + &:hover { + background: ${({theme:r})=>r.colors.background.hover}; + } + + &:first-child { + border-radius: 6px 6px 0 0; + } + + &:last-child { + border-radius: 0 0 6px 6px; + } +`,a1=C.div` + margin-top: 4px; +`,u1=C.textarea` + width: 100%; + max-width: 600px; + min-height: 80px; + padding: 12px 16px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border: 1px solid ${({theme:r})=>r.colors.border.primary}; + border-radius: 4px; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + font-family: inherit; + resize: vertical; + outline: none; + box-sizing: border-box; + + &:focus { + border-color: ${({theme:r})=>r.colors.primary}; + } + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } +`,c1=C.div` + display: flex; + gap: 8px; + margin-top: 8px; +`,pp=C.button` + padding: 6px 12px; + border-radius: 4px; + font-size: 12px; + font-weight: 500; + cursor: pointer; + border: none; + transition: background-color 0.2s ease; + + ${({variant:r,theme:i})=>r==="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}; + } + `} +`;function d1({channel:r}){var w;const{currentUser:i}=rt(),s=Rr(v=>v.users),l=An(v=>v.binaryContents);if(!r)return null;if(r.type==="PUBLIC")return h.jsx(lp,{children:h.jsx(ap,{children:h.jsxs(up,{children:["# ",r.name]})})});const c=r.participants.map(v=>s.find(S=>S.id===v.id)).filter(Boolean),d=c.filter(v=>v.id!==(i==null?void 0:i.id)),p=c.length>2,m=c.filter(v=>v.id!==(i==null?void 0:i.id)).map(v=>v.username).join(", ");return h.jsx(lp,{children:h.jsx(ap,{children:h.jsxs(Lx,{children:[p?h.jsx(Dx,{children:d.slice(0,2).map((v,S)=>{var j;return h.jsx(nn,{src:v.profile?(j=l[v.profile.id])==null?void 0:j.url:St,style:{position:"absolute",left:S*16,zIndex:2-S,width:"24px",height:"24px"}},v.id)})}):h.jsxs(Ix,{children:[h.jsx(nn,{src:d[0].profile?(w=l[d[0].profile.id])==null?void 0:w.url:St}),h.jsx(zx,{$online:d[0].online})]}),h.jsxs("div",{children:[h.jsx(up,{children:m}),p&&h.jsxs($x,{children:["멤버 ",c.length,"명"]})]})]})})})}const f1=async(r,i,s)=>{var c;return(await $e.get("/messages",{params:{channelId:r,cursor:i,size:s.size,sort:(c=s.sort)==null?void 0:c.join(",")}})).data},p1=async(r,i)=>{const s=new FormData,l={content:r.content,channelId:r.channelId,authorId:r.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 $e.post("/messages",s,{headers:{"Content-Type":"multipart/form-data"}})).data},h1=async(r,i)=>(await $e.patch(`/messages/${r}`,i)).data,m1=async r=>{await $e.delete(`/messages/${r}`)},ba={size:50,sort:["createdAt,desc"]},Ah=Tr((r,i)=>({messages:[],pollingIntervals:{},lastMessageId:null,pagination:{nextCursor:null,pageSize:50,hasNext:!1},fetchMessages:async(s,l,c=ba)=>{try{const d=await f1(s,l,c),p=d.content,m=p.length>0?p[0]:null,w=(m==null?void 0:m.id)!==i().lastMessageId;return r(v=>{var N;const S=!l,j=s!==((N=v.messages[0])==null?void 0:N.channelId),R=S&&(v.messages.length===0||j);let L=[],T={...v.pagination};if(R)L=p,T={nextCursor:d.nextCursor,pageSize:d.size,hasNext:d.hasNext};else if(S){const _=new Set(v.messages.map(U=>U.id));L=[...p.filter(U=>!_.has(U.id)&&(v.messages.length===0||U.createdAt>v.messages[0].createdAt)),...v.messages]}else{const _=new Set(v.messages.map(U=>U.id)),V=p.filter(U=>!_.has(U.id));L=[...v.messages,...V],T={nextCursor:d.nextCursor,pageSize:d.size,hasNext:d.hasNext}}return{messages:L,lastMessageId:(m==null?void 0:m.id)||null,pagination:T}}),w}catch(d){return console.error("메시지 목록 조회 실패:",d),!1}},loadMoreMessages:async s=>{const{pagination:l}=i();l.hasNext&&await i().fetchMessages(s,l.nextCursor,{...ba})},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;r(m=>({pollingIntervals:{...m.pollingIntervals,[s]:!0}}));const p=async()=>{const m=i();if(!m.pollingIntervals[s])return;const w=await m.fetchMessages(s,null,ba);if(!(i().messages.length==0)&&w?c=300:c=Math.min(c*1.5,d),i().pollingIntervals[s]){const S=setTimeout(p,c);r(j=>({pollingIntervals:{...j.pollingIntervals,[s]:S}}))}};p()},stopPolling:s=>{const{pollingIntervals:l}=i();if(l[s]){const c=l[s];typeof c=="number"&&clearTimeout(c),r(d=>{const p={...d.pollingIntervals};return delete p[s],{pollingIntervals:p}})}},createMessage:async(s,l)=>{try{const c=await p1(s,l),d=Po.getState().updateReadStatus;return await d(s.channelId),r(p=>p.messages.some(w=>w.id===c.id)?p:{messages:[c,...p.messages],lastMessageId:c.id}),c}catch(c){throw console.error("메시지 생성 실패:",c),c}},updateMessage:async(s,l)=>{try{const c=await h1(s,{newContent:l});return r(d=>({messages:d.messages.map(p=>p.id===s?{...p,content:l}:p)})),c}catch(c){throw console.error("메시지 업데이트 실패:",c),c}},deleteMessage:async s=>{try{await m1(s),r(l=>({messages:l.messages.filter(c=>c.id!==s)}))}catch(l){throw console.error("메시지 삭제 실패:",l),l}}}));function g1({channel:r}){const[i,s]=K.useState(""),[l,c]=K.useState([]),d=Ah(R=>R.createMessage),{currentUser:p}=rt(),m=async R=>{if(R.preventDefault(),!(!i.trim()&&l.length===0))try{await d({content:i.trim(),channelId:r.id,authorId:(p==null?void 0:p.id)??""},l),s(""),c([])}catch(L){console.error("메시지 전송 실패:",L)}},w=R=>{const L=Array.from(R.target.files||[]);c(T=>[...T,...L]),R.target.value=""},v=R=>{c(L=>L.filter((T,N)=>N!==R))},S=R=>{if(R.key==="Enter"&&!R.shiftKey){if(console.log("Enter key pressed"),R.preventDefault(),R.nativeEvent.isComposing)return;m(R)}},j=(R,L)=>R.type.startsWith("image/")?h.jsxs(n1,{children:[h.jsx("img",{src:URL.createObjectURL(R),alt:R.name}),h.jsx(dp,{onClick:()=>v(L),children:"×"})]},L):h.jsxs(jh,{children:[h.jsx(r1,{children:"📎"}),h.jsx(o1,{children:R.name}),h.jsx(dp,{onClick:()=>v(L),children:"×"})]},L);return K.useEffect(()=>()=>{l.forEach(R=>{R.type.startsWith("image/")&&URL.revokeObjectURL(URL.createObjectURL(R))})},[l]),r?h.jsxs(h.Fragment,{children:[l.length>0&&h.jsx(t1,{children:l.map((R,L)=>j(R,L))}),h.jsxs(qx,{onSubmit:m,children:[h.jsxs(Qx,{as:"label",children:["+",h.jsx("input",{type:"file",multiple:!0,onChange:w,style:{display:"none"}})]}),h.jsx(Yx,{value:i,onChange:R=>s(R.target.value),onKeyDown:S,placeholder:r.type==="PUBLIC"?`#${r.name}에 메시지 보내기`:"메시지 보내기"})]})]}):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 ru=function(r,i){return ru=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])},ru(r,i)};function y1(r,i){ru(r,i);function s(){this.constructor=r}r.prototype=i===null?Object.create(i):(s.prototype=i.prototype,new s)}var No=function(){return No=Object.assign||function(i){for(var s,l=1,c=arguments.length;lr?L():i!==!0&&(c=setTimeout(l?T:L,l===void 0?r-j:r))}return v.cancel=w,v}var kr={Pixel:"Pixel",Percent:"Percent"},hp={unit:kr.Percent,value:.8};function mp(r){return typeof r=="number"?{unit:kr.Percent,value:r*100}:typeof r=="string"?r.match(/^(\d*(\.\d+)?)px$/)?{unit:kr.Pixel,value:parseFloat(r)}:r.match(/^(\d*(\.\d+)?)%$/)?{unit:kr.Percent,value:parseFloat(r)}:(console.warn('scrollThreshold format is invalid. Valid formats: "120px", "50%"...'),hp):(console.warn("scrollThreshold should be string or number"),hp)}var x1=function(r){y1(i,r);function i(s){var l=r.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 p=l.props.inverse?l.isElementAtTop(d,l.props.scrollThreshold):l.isElementAtBottom(d,l.props.scrollThreshold);p&&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=v1(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?No(No({},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=mp(l);return d.unit===kr.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=mp(l);return d.unit===kr.Pixel?s.scrollTop+c>=s.scrollHeight-d.value:s.scrollTop+c>=d.value/100*s.scrollHeight},i.prototype.render=function(){var s=this,l=No({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 xt.createElement("div",{style:d,className:"infinite-scroll-component__outerdiv"},xt.createElement("div",{className:"infinite-scroll-component "+(this.props.className||""),ref:function(p){return s._infScroll=p},style:l},this.props.pullDownToRefresh&&xt.createElement("div",{style:{position:"relative"},ref:function(p){return s._pullDown=p}},xt.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}(K.Component);const w1=r=>r<1024?r+" B":r<1024*1024?(r/1024).toFixed(2)+" KB":r<1024*1024*1024?(r/(1024*1024)).toFixed(2)+" MB":(r/(1024*1024*1024)).toFixed(2)+" GB";function S1({channel:r}){const{messages:i,fetchMessages:s,loadMoreMessages:l,pagination:c,startPolling:d,stopPolling:p,updateMessage:m,deleteMessage:w}=Ah(),{binaryContents:v,fetchBinaryContent:S,clearBinaryContents:j}=An(),{currentUser:R}=rt(),[L,T]=K.useState(null),[N,_]=K.useState(null),[V,U]=K.useState("");K.useEffect(()=>{if(r!=null&&r.id)return s(r.id,null),d(r.id),()=>{p(r.id)}},[r==null?void 0:r.id,s,d,p]),K.useEffect(()=>{i.forEach(ne=>{var le;(le=ne.attachments)==null||le.forEach(me=>{v[me.id]||S(me.id)})})},[i,v,S]),K.useEffect(()=>()=>{const ne=i.map(le=>{var me;return(me=le.attachments)==null?void 0:me.map(Re=>Re.id)}).flat();j(ne)},[j]),K.useEffect(()=>{const ne=()=>{L&&T(null)};if(L)return document.addEventListener("click",ne),()=>document.removeEventListener("click",ne)},[L]);const B=async ne=>{try{const{url:le,fileName:me}=ne,Re=document.createElement("a");Re.href=le,Re.download=me,Re.style.display="none",document.body.appendChild(Re);try{const Ee=await(await window.showSaveFilePicker({suggestedName:ne.fileName,types:[{description:"Files",accept:{"*/*":[".txt",".pdf",".doc",".docx",".xls",".xlsx",".jpg",".jpeg",".png",".gif"]}}]})).createWritable(),ee=await(await fetch(le)).blob();await Ee.write(ee),await Ee.close()}catch(ge){ge.name!=="AbortError"&&Re.click()}document.body.removeChild(Re),window.URL.revokeObjectURL(le)}catch(le){console.error("파일 다운로드 실패:",le)}},W=ne=>ne!=null&&ne.length?ne.map(le=>{const me=v[le.id];return me?me.contentType.startsWith("image/")?h.jsx(cp,{children:h.jsx(Gx,{href:"#",onClick:ge=>{ge.preventDefault(),B(me)},children:h.jsx("img",{src:me.url,alt:me.fileName})})},me.url):h.jsx(cp,{children:h.jsxs(Kx,{href:"#",onClick:ge=>{ge.preventDefault(),B(me)},children:[h.jsx(Xx,{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(Jx,{children:[h.jsx(Zx,{children:me.fileName}),h.jsx(e1,{children:w1(me.size)})]})]})},me.url):null}):null,I=ne=>new Date(ne).toLocaleTimeString(),M=()=>{r!=null&&r.id&&l(r.id)},H=ne=>{T(L===ne?null:ne)},ie=ne=>{T(null);const le=i.find(me=>me.id===ne);le&&(_(ne),U(le.content))},ve=ne=>{m(ne,V).catch(le=>{console.error("메시지 수정 실패:",le),Sr.emit("api-error",{error:le,alert:!0})}),_(null),U("")},Oe=()=>{_(null),U("")},ot=ne=>{T(null),w(ne)};return h.jsx(Bx,{children:h.jsx("div",{id:"scrollableDiv",style:{height:"100%",overflow:"auto",display:"flex",flexDirection:"column-reverse"},children:h.jsx(x1,{dataLength:i.length,next:M,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(Fx,{children:[...i].reverse().map(ne=>{var Re;const le=ne.author,me=R&&le&&le.id===R.id;return h.jsxs(Eh,{children:[h.jsx(bx,{children:h.jsx(nn,{src:le&&le.profile?(Re=v[le.profile.id])==null?void 0:Re.url:St,alt:le&&le.username||"알 수 없음"})}),h.jsxs("div",{children:[h.jsxs(Ux,{children:[h.jsx(Hx,{children:le&&le.username||"알 수 없음"}),h.jsx(Vx,{children:I(ne.createdAt)}),me&&h.jsxs(i1,{children:[h.jsx(s1,{onClick:ge=>{ge.stopPropagation(),H(ne.id)},children:"⋯"}),L===ne.id&&h.jsxs(l1,{onClick:ge=>ge.stopPropagation(),children:[h.jsx(fp,{onClick:()=>ie(ne.id),children:"✏️ 수정"}),h.jsx(fp,{onClick:()=>ot(ne.id),children:"🗑️ 삭제"})]})]})]}),N===ne.id?h.jsxs(a1,{children:[h.jsx(u1,{value:V,onChange:ge=>U(ge.target.value),onKeyDown:ge=>{ge.key==="Escape"?Oe():ge.key==="Enter"&&(ge.ctrlKey||ge.metaKey)&&(ge.preventDefault(),ve(ne.id))},placeholder:"메시지를 입력하세요..."}),h.jsxs(c1,{children:[h.jsx(pp,{variant:"secondary",onClick:Oe,children:"취소"}),h.jsx(pp,{variant:"primary",onClick:()=>ve(ne.id),children:"저장"})]})]}):h.jsx(Wx,{children:ne.content}),W(ne.attachments)]})]},ne.id)})})})})})}function k1({channel:r}){return r?h.jsxs(Rx,{children:[h.jsx(d1,{channel:r}),h.jsx(S1,{channel:r}),h.jsx(g1,{channel:r})]}):h.jsx(Tx,{children:h.jsxs(_x,{children:[h.jsx(Nx,{children:"👋"}),h.jsx(Ox,{children:"채널을 선택해주세요"}),h.jsxs(Mx,{children:["왼쪽의 채널 목록에서 채널을 선택하여",h.jsx("br",{}),"대화를 시작하세요."]})]})})}function C1(r,i="yyyy-MM-dd HH:mm:ss"){if(!r||!(r instanceof Date)||isNaN(r.getTime()))return"";const s=r.getFullYear(),l=String(r.getMonth()+1).padStart(2,"0"),c=String(r.getDate()).padStart(2,"0"),d=String(r.getHours()).padStart(2,"0"),p=String(r.getMinutes()).padStart(2,"0"),m=String(r.getSeconds()).padStart(2,"0");return i.replace("yyyy",s.toString()).replace("MM",l).replace("dd",c).replace("HH",d).replace("mm",p).replace("ss",m)}const E1=C.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; +`,j1=C.div` + background: ${({theme:r})=>r.colors.background.primary}; + border-radius: 8px; + width: 500px; + max-width: 90%; + padding: 24px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); +`,A1=C.div` + display: flex; + align-items: center; + margin-bottom: 16px; +`,R1=C.div` + color: ${({theme:r})=>r.colors.status.error}; + font-size: 24px; + margin-right: 12px; +`,P1=C.h3` + color: ${({theme:r})=>r.colors.text.primary}; + margin: 0; + font-size: 18px; +`,T1=C.div` + background: ${({theme:r})=>r.colors.background.tertiary}; + color: ${({theme:r})=>r.colors.text.muted}; + padding: 2px 8px; + border-radius: 4px; + font-size: 14px; + margin-left: auto; +`,_1=C.p` + color: ${({theme:r})=>r.colors.text.secondary}; + margin-bottom: 20px; + line-height: 1.5; + font-weight: 500; +`,N1=C.div` + margin-bottom: 20px; + background: ${({theme:r})=>r.colors.background.secondary}; + border-radius: 6px; + padding: 12px; +`,ko=C.div` + display: flex; + margin-bottom: 8px; + font-size: 14px; +`,Co=C.span` + color: ${({theme:r})=>r.colors.text.muted}; + min-width: 100px; +`,Eo=C.span` + color: ${({theme:r})=>r.colors.text.secondary}; + word-break: break-word; +`,O1=C.button` + background: ${({theme:r})=>r.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:r})=>r.colors.brand.hover}; + } +`;function M1({isOpen:r,onClose:i,error:s}){var R,L;if(!r)return null;console.log({error:s});const l=(R=s==null?void 0:s.response)==null?void 0:R.data,c=(l==null?void 0:l.status)||((L=s==null?void 0:s.response)==null?void 0:L.status)||"오류",d=(l==null?void 0:l.code)||"",p=(l==null?void 0:l.message)||(s==null?void 0:s.message)||"알 수 없는 오류가 발생했습니다.",m=l!=null&&l.timestamp?new Date(l.timestamp):new Date,w=C1(m),v=(l==null?void 0:l.exceptionType)||"",S=(l==null?void 0:l.details)||{},j=(l==null?void 0:l.requestId)||"";return h.jsx(E1,{onClick:i,children:h.jsxs(j1,{onClick:T=>T.stopPropagation(),children:[h.jsxs(A1,{children:[h.jsx(R1,{children:"⚠️"}),h.jsx(P1,{children:"오류가 발생했습니다"}),h.jsxs(T1,{children:[c,d?` (${d})`:""]})]}),h.jsx(_1,{children:p}),h.jsxs(N1,{children:[h.jsxs(ko,{children:[h.jsx(Co,{children:"시간:"}),h.jsx(Eo,{children:w})]}),j&&h.jsxs(ko,{children:[h.jsx(Co,{children:"요청 ID:"}),h.jsx(Eo,{children:j})]}),d&&h.jsxs(ko,{children:[h.jsx(Co,{children:"에러 코드:"}),h.jsx(Eo,{children:d})]}),v&&h.jsxs(ko,{children:[h.jsx(Co,{children:"예외 유형:"}),h.jsx(Eo,{children:v})]}),Object.keys(S).length>0&&h.jsxs(ko,{children:[h.jsx(Co,{children:"상세 정보:"}),h.jsx(Eo,{children:Object.entries(S).map(([T,N])=>h.jsxs("div",{children:[T,": ",String(N)]},T))})]})]}),h.jsx(O1,{onClick:i,children:"확인"})]})})}const L1=C.div` + width: 240px; + background: ${Y.colors.background.secondary}; + border-left: 1px solid ${Y.colors.border.primary}; +`,I1=C.div` + padding: 16px; + font-size: 14px; + font-weight: bold; + color: ${Y.colors.text.muted}; + text-transform: uppercase; +`,D1=C.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${Y.colors.text.muted}; + &:hover { + background: ${Y.colors.background.primary}; + cursor: pointer; + } +`,z1=C(Or)` + margin-right: 12px; +`;C(nn)``;const $1=C.div` + display: flex; + align-items: center; +`;function B1({member:r}){var l,c,d;const{binaryContents:i,fetchBinaryContent:s}=An();return K.useEffect(()=>{var p;(p=r.profile)!=null&&p.id&&!i[r.profile.id]&&s(r.profile.id)},[(l=r.profile)==null?void 0:l.id,i,s]),h.jsxs(D1,{children:[h.jsxs(z1,{children:[h.jsx(nn,{src:(c=r.profile)!=null&&c.id&&((d=i[r.profile.id])==null?void 0:d.url)||St,alt:r.username}),h.jsx($o,{$online:r.online})]}),h.jsx($1,{children:r.username})]})}function F1({member:r,onClose:i}){var L,T,N;const{binaryContents:s,fetchBinaryContent:l}=An(),{currentUser:c,updateUserRole:d}=rt(),[p,m]=K.useState(r.role),[w,v]=K.useState(!1);K.useEffect(()=>{var _;(_=r.profile)!=null&&_.id&&!s[r.profile.id]&&l(r.profile.id)},[(L=r.profile)==null?void 0:L.id,s,l]);const S={[En.USER]:{name:"사용자",color:"#2ed573"},[En.CHANNEL_MANAGER]:{name:"채널 관리자",color:"#ff4757"},[En.ADMIN]:{name:"어드민",color:"#0097e6"}},j=_=>{m(_),v(!0)},R=()=>{d(r.id,p),v(!1)};return h.jsx(H1,{onClick:i,children:h.jsxs(V1,{onClick:_=>_.stopPropagation(),children:[h.jsx("h2",{children:"사용자 정보"}),h.jsxs(W1,{children:[h.jsx(q1,{src:(T=r.profile)!=null&&T.id&&((N=s[r.profile.id])==null?void 0:N.url)||St,alt:r.username}),h.jsx(Y1,{children:r.username}),h.jsx(Q1,{children:r.email}),h.jsx(G1,{$online:r.online,children:r.online?"온라인":"오프라인"}),(c==null?void 0:c.role)===En.ADMIN?h.jsx(U1,{value:p,onChange:_=>j(_.target.value),children:Object.entries(S).map(([_,V])=>h.jsx("option",{value:_,style:{marginTop:"8px",textAlign:"center"},children:V.name},_))}):h.jsx(b1,{style:{backgroundColor:S[r.role].color},children:S[r.role].name})]}),h.jsx(K1,{children:(c==null?void 0:c.role)===En.ADMIN&&w&&h.jsx(X1,{onClick:R,disabled:!w,$secondary:!w,children:"저장"})})]})})}const b1=C.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; +`,U1=C.select` + padding: 10px 16px; + border-radius: 8px; + border: 1.5px solid ${Y.colors.border.primary}; + background: ${Y.colors.background.primary}; + color: ${Y.colors.text.primary}; + font-size: 14px; + width: 140px; + cursor: pointer; + transition: all 0.2s ease; + margin-top: 12px; + font-weight: 500; + + &:hover { + border-color: ${Y.colors.brand.primary}; + } + + &:focus { + outline: none; + border-color: ${Y.colors.brand.primary}; + box-shadow: 0 0 0 2px ${Y.colors.brand.primary}20; + } + + option { + background: ${Y.colors.background.primary}; + color: ${Y.colors.text.primary}; + padding: 12px; + } +`,H1=C.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; +`,V1=C.div` + background: ${Y.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: ${Y.colors.text.primary}; + margin-bottom: 32px; + text-align: center; + font-size: 26px; + font-weight: 600; + letter-spacing: -0.5px; + } +`,W1=C.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 32px; + padding: 24px; + background: ${Y.colors.background.primary}; + border-radius: 12px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); +`,q1=C.img` + width: 140px; + height: 140px; + border-radius: 50%; + margin-bottom: 20px; + object-fit: cover; + border: 4px solid ${Y.colors.background.secondary}; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); +`,Y1=C.div` + font-size: 22px; + font-weight: 600; + color: ${Y.colors.text.primary}; + margin-bottom: 8px; + letter-spacing: -0.3px; +`,Q1=C.div` + font-size: 14px; + color: ${Y.colors.text.muted}; + margin-bottom: 16px; + font-weight: 500; +`,G1=C.div` + padding: 6px 16px; + border-radius: 20px; + font-size: 13px; + font-weight: 600; + background-color: ${({$online:r,theme:i})=>r?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; +`,K1=C.div` + display: flex; + gap: 12px; + margin-top: 24px; +`,X1=C.button` + width: 100%; + padding: 12px; + border: none; + border-radius: 8px; + background: ${({$secondary:r,theme:i})=>r?"transparent":i.colors.brand.primary}; + color: ${({$secondary:r,theme:i})=>r?i.colors.text.primary:"white"}; + cursor: pointer; + font-weight: 600; + font-size: 15px; + transition: all 0.2s ease; + border: ${({$secondary:r,theme:i})=>r?`1.5px solid ${i.colors.border.primary}`:"none"}; + + &:hover { + background: ${({$secondary:r,theme:i})=>r?i.colors.background.hover:i.colors.brand.hover}; + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } +`;function J1(){const r=Rr(p=>p.users),i=Rr(p=>p.fetchUsers),{currentUser:s}=rt(),[l,c]=K.useState(null);K.useEffect(()=>{i()},[i]);const d=[...r].sort((p,m)=>p.id===(s==null?void 0:s.id)?-1:m.id===(s==null?void 0:s.id)?1:p.online&&!m.online?-1:!p.online&&m.online?1:p.username.localeCompare(m.username));return h.jsxs(L1,{children:[h.jsxs(I1,{children:["멤버 목록 - ",r.length]}),d.map(p=>h.jsx("div",{onClick:()=>c(p),children:h.jsx(B1,{member:p},p.id)},p.id)),l&&h.jsx(F1,{member:l,onClose:()=>c(null)})]})}function Z1(){const{logout:r,fetchCsrfToken:i,refreshToken:s}=rt(),{fetchUsers:l}=Rr(),[c,d]=K.useState(null),[p,m]=K.useState(null),[w,v]=K.useState(!1),[S,j]=K.useState(!0),{currentUser:R}=rt();K.useEffect(()=>{i(),s()},[]),K.useEffect(()=>{(async()=>{try{if(R)try{await l()}catch(N){console.warn("사용자 상태 업데이트 실패. 로그아웃합니다.",N),r()}}catch(N){console.error("초기화 오류:",N)}finally{j(!1)}})()},[R,l,r]),K.useEffect(()=>{const T=U=>{U!=null&&U.error&&m(U.error),U!=null&&U.alert&&v(!0)},N=()=>{r()},_=Sr.on("api-error",T),V=Sr.on("auth-error",N);return()=>{_("api-error",T),V("auth-error",N)}},[r]),K.useEffect(()=>{if(R){const T=setInterval(()=>{l()},6e4);return()=>{clearInterval(T)}}},[R,l]);const L=()=>{v(!1),m(null)};return S?h.jsx(Of,{theme:Y,children:h.jsx(tw,{children:h.jsx(nw,{})})}):h.jsxs(Of,{theme:Y,children:[R?h.jsxs(ew,{children:[h.jsx(jx,{currentUser:R,activeChannel:c,onChannelSelect:d}),h.jsx(k1,{channel:c}),h.jsx(J1,{})]}):h.jsx(Mv,{isOpen:!0,onClose:()=>{}}),h.jsx(M1,{isOpen:w,onClose:L,error:p})]})}const ew=C.div` + display: flex; + height: 100vh; + width: 100vw; + position: relative; +`,tw=C.div` + display: flex; + justify-content: center; + align-items: center; + height: 100vh; + width: 100vw; + background-color: ${({theme:r})=>r.colors.background.primary}; +`,nw=C.div` + width: 40px; + height: 40px; + border: 4px solid ${({theme:r})=>r.colors.background.tertiary}; + border-top: 4px solid ${({theme:r})=>r.colors.brand.primary}; + border-radius: 50%; + animation: spin 1s linear infinite; + + @keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } + } +`,Rh=document.getElementById("root");if(!Rh)throw new Error("Root element not found");Lg.createRoot(Rh).render(h.jsx(K.StrictMode,{children:h.jsx(Z1,{})})); diff --git a/src/main/resources/static/assets/index-DRjprt8D.js b/src/main/resources/static/assets/index-DRjprt8D.js new file mode 100644 index 000000000..40695b51e --- /dev/null +++ b/src/main/resources/static/assets/index-DRjprt8D.js @@ -0,0 +1,1015 @@ +var rg=Object.defineProperty;var og=(r,i,s)=>i in r?rg(r,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[i]=s;var ed=(r,i,s)=>og(r,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 f of c)if(f.type==="childList")for(const p of f.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).observe(document,{childList:!0,subtree:!0});function s(c){const f={};return c.integrity&&(f.integrity=c.integrity),c.referrerPolicy&&(f.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?f.credentials="include":c.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function l(c){if(c.ep)return;c.ep=!0;const f=s(c);fetch(c.href,f)}})();function ig(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var mu={exports:{}},yo={},gu={exports:{}},fe={};/** + * @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 td;function sg(){if(td)return fe;td=1;var r=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"),f=Symbol.for("react.provider"),p=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),A=Symbol.iterator;function T(E){return E===null||typeof E!="object"?null:(E=A&&E[A]||E["@@iterator"],typeof E=="function"?E:null)}var I={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},R=Object.assign,C={};function N(E,D,se){this.props=E,this.context=D,this.refs=C,this.updater=se||I}N.prototype.isReactComponent={},N.prototype.setState=function(E,D){if(typeof E!="object"&&typeof E!="function"&&E!=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,E,D,"setState")},N.prototype.forceUpdate=function(E){this.updater.enqueueForceUpdate(this,E,"forceUpdate")};function H(){}H.prototype=N.prototype;function U(E,D,se){this.props=E,this.context=D,this.refs=C,this.updater=se||I}var V=U.prototype=new H;V.constructor=U,R(V,N.prototype),V.isPureReactComponent=!0;var Q=Array.isArray,$=Object.prototype.hasOwnProperty,L={current:null},b={key:!0,ref:!0,__self:!0,__source:!0};function re(E,D,se){var ue,de={},ce=null,ve=null;if(D!=null)for(ue in D.ref!==void 0&&(ve=D.ref),D.key!==void 0&&(ce=""+D.key),D)$.call(D,ue)&&!b.hasOwnProperty(ue)&&(de[ue]=D[ue]);var pe=arguments.length-2;if(pe===1)de.children=se;else if(1>>1,D=W[E];if(0>>1;Ec(de,Y))cec(ve,de)?(W[E]=ve,W[ce]=Y,E=ce):(W[E]=de,W[ue]=Y,E=ue);else if(cec(ve,Y))W[E]=ve,W[ce]=Y,E=ce;else break e}}return Z}function c(W,Z){var Y=W.sortIndex-Z.sortIndex;return Y!==0?Y:W.id-Z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var f=performance;r.unstable_now=function(){return f.now()}}else{var p=Date,g=p.now();r.unstable_now=function(){return p.now()-g}}var x=[],v=[],S=1,A=null,T=3,I=!1,R=!1,C=!1,N=typeof setTimeout=="function"?setTimeout:null,H=typeof clearTimeout=="function"?clearTimeout:null,U=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function V(W){for(var Z=s(v);Z!==null;){if(Z.callback===null)l(v);else if(Z.startTime<=W)l(v),Z.sortIndex=Z.expirationTime,i(x,Z);else break;Z=s(v)}}function Q(W){if(C=!1,V(W),!R)if(s(x)!==null)R=!0,We($);else{var Z=s(v);Z!==null&&Se(Q,Z.startTime-W)}}function $(W,Z){R=!1,C&&(C=!1,H(re),re=-1),I=!0;var Y=T;try{for(V(Z),A=s(x);A!==null&&(!(A.expirationTime>Z)||W&&!at());){var E=A.callback;if(typeof E=="function"){A.callback=null,T=A.priorityLevel;var D=E(A.expirationTime<=Z);Z=r.unstable_now(),typeof D=="function"?A.callback=D:A===s(x)&&l(x),V(Z)}else l(x);A=s(x)}if(A!==null)var se=!0;else{var ue=s(v);ue!==null&&Se(Q,ue.startTime-Z),se=!1}return se}finally{A=null,T=Y,I=!1}}var L=!1,b=null,re=-1,ye=5,Ne=-1;function at(){return!(r.unstable_now()-NeW||125E?(W.sortIndex=Y,i(v,W),s(x)===null&&W===s(v)&&(C?(H(re),re=-1):C=!0,Se(Q,Y-E))):(W.sortIndex=D,i(x,W),R||I||(R=!0,We($))),W},r.unstable_shouldYield=at,r.unstable_wrapCallback=function(W){var Z=T;return function(){var Y=T;T=Z;try{return W.apply(this,arguments)}finally{T=Y}}}}(wu)),wu}var sd;function cg(){return sd||(sd=1,vu.exports=ag()),vu.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 ld;function fg(){if(ld)return lt;ld=1;var r=Ku(),i=cg();function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),x=Object.prototype.hasOwnProperty,v=/^[: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={},A={};function T(e){return x.call(A,e)?!0:x.call(S,e)?!1:v.test(e)?A[e]=!0:(S[e]=!0,!1)}function I(e,t,n,o){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function R(e,t,n,o){if(t===null||typeof t>"u"||I(e,t,n,o))return!0;if(o)return!1;if(n!==null)switch(n.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 C(e,t,n,o,u,a,d){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=u,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=d}var N={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){N[e]=new C(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];N[t]=new C(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){N[e]=new C(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){N[e]=new C(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){N[e]=new C(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){N[e]=new C(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){N[e]=new C(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){N[e]=new C(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){N[e]=new C(e,5,!1,e.toLowerCase(),null,!1,!1)});var H=/[\-:]([a-z])/g;function U(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(H,U);N[t]=new C(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(H,U);N[t]=new C(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(H,U);N[t]=new C(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){N[e]=new C(e,1,!1,e.toLowerCase(),null,!1,!1)}),N.xlinkHref=new C("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){N[e]=new C(e,1,!1,e.toLowerCase(),null,!0,!0)});function V(e,t,n,o){var u=N.hasOwnProperty(t)?N[t]:null;(u!==null?u.type!==0:o||!(2m||u[d]!==a[m]){var y=` +`+u[d].replace(" at new "," at ");return e.displayName&&y.includes("")&&(y=y.replace("",e.displayName)),y}while(1<=d&&0<=m);break}}}finally{se=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?D(e):""}function de(e){switch(e.tag){case 5:return D(e.type);case 16:return D("Lazy");case 13:return D("Suspense");case 19:return D("SuspenseList");case 0:case 2:case 15:return e=ue(e.type,!1),e;case 11:return e=ue(e.type.render,!1),e;case 1:return e=ue(e.type,!0),e;default:return""}}function ce(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 b:return"Fragment";case L:return"Portal";case ye:return"Profiler";case re:return"StrictMode";case Ze:return"Suspense";case ct:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case at:return(e.displayName||"Context")+".Consumer";case Ne:return(e._context.displayName||"Context")+".Provider";case wt:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case xt:return t=e.displayName||null,t!==null?t:ce(e.type)||"Memo";case We:t=e._payload,e=e._init;try{return ce(e(t))}catch{}}return null}function ve(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 ce(t);case 8:return t===re?"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 pe(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function me(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function He(e){var t=me(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var u=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return u.call(this)},set:function(d){o=""+d,a.call(this,d)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return o},setValue:function(d){o=""+d},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Yt(e){e._valueTracker||(e._valueTracker=He(e))}function Pt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),o="";return e&&(o=me(e)?e.checked?"true":"false":e.value),e=o,e!==n?(t.setValue(e),!0):!1}function No(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 Es(e,t){var n=t.checked;return Y({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function sa(e,t){var n=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;n=pe(t.value!=null?t.value:n),e._wrapperState={initialChecked:o,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function la(e,t){t=t.checked,t!=null&&V(e,"checked",t,!1)}function Cs(e,t){la(e,t);var n=pe(t.value),o=t.type;if(n!=null)o==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ks(e,t.type,n):t.hasOwnProperty("defaultValue")&&ks(e,t.type,pe(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ua(e,t,n){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,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ks(e,t,n){(t!=="number"||No(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ir=Array.isArray;function qn(e,t,n,o){if(e=e.options,t){t={};for(var u=0;u"+t.valueOf().toString()+"",t=Oo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Nr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Or={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},uh=["Webkit","ms","Moz","O"];Object.keys(Or).forEach(function(e){uh.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Or[t]=Or[e]})});function ha(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Or.hasOwnProperty(e)&&Or[e]?(""+t).trim():t+"px"}function ma(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var o=n.indexOf("--")===0,u=ha(n,t[n],o);n==="float"&&(n="cssFloat"),o?e.setProperty(n,u):e[n]=u}}var ah=Y({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 Rs(e,t){if(t){if(ah[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 Ps(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 _s=null;function Ts(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Is=null,Qn=null,Gn=null;function ga(e){if(e=to(e)){if(typeof Is!="function")throw Error(s(280));var t=e.stateNode;t&&(t=ni(t),Is(e.stateNode,e.type,t))}}function ya(e){Qn?Gn?Gn.push(e):Gn=[e]:Qn=e}function va(){if(Qn){var e=Qn,t=Gn;if(Gn=Qn=null,ga(e),t)for(e=0;e>>=0,e===0?32:31-(xh(e)/Sh|0)|0}var Uo=64,Fo=4194304;function zr(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 Bo(e,t){var n=e.pendingLanes;if(n===0)return 0;var o=0,u=e.suspendedLanes,a=e.pingedLanes,d=n&268435455;if(d!==0){var m=d&~u;m!==0?o=zr(m):(a&=d,a!==0&&(o=zr(a)))}else d=n&~u,d!==0?o=zr(d):a!==0&&(o=zr(a));if(o===0)return 0;if(t!==0&&t!==o&&!(t&u)&&(u=o&-o,a=t&-t,u>=a||u===16&&(a&4194240)!==0))return t;if(o&4&&(o|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0n;n++)t.push(e);return t}function Ur(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-_t(t),e[t]=n}function jh(e,t){var n=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=Yr),Ya=" ",qa=!1;function Qa(e,t){switch(e){case"keyup":return Zh.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ga(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Jn=!1;function tm(e,t){switch(e){case"compositionend":return Ga(t);case"keypress":return t.which!==32?null:(qa=!0,Ya);case"textInput":return e=t.data,e===Ya&&qa?null:e;default:return null}}function nm(e,t){if(Jn)return e==="compositionend"||!Gs&&Qa(e,t)?(e=Ba(),Wo=bs=an=null,Jn=!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:n,offset:t-e};e=o}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=nc(n)}}function oc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?oc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ic(){for(var e=window,t=No();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=No(e.document)}return t}function Js(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 fm(e){var t=ic(),n=e.focusedElem,o=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&oc(n.ownerDocument.documentElement,n)){if(o!==null&&Js(n)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var u=n.textContent.length,a=Math.min(o.start,u);o=o.end===void 0?a:Math.min(o.end,u),!e.extend&&a>o&&(u=o,o=a,a=u),u=rc(n,a);var d=rc(n,o);u&&d&&(e.rangeCount!==1||e.anchorNode!==u.node||e.anchorOffset!==u.offset||e.focusNode!==d.node||e.focusOffset!==d.offset)&&(t=t.createRange(),t.setStart(u.node,u.offset),e.removeAllRanges(),a>o?(e.addRange(t),e.extend(d.node,d.offset)):(t.setEnd(d.node,d.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Zn=null,Zs=null,Kr=null,el=!1;function sc(e,t,n){var o=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;el||Zn==null||Zn!==No(o)||(o=Zn,"selectionStart"in o&&Js(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}),Kr&&Gr(Kr,o)||(Kr=o,o=Zo(Zs,"onSelect"),0or||(e.current=dl[or],dl[or]=null,or--)}function Ee(e,t){or++,dl[or]=e.current,e.current=t}var pn={},Ye=dn(pn),nt=dn(!1),Rn=pn;function ir(e,t){var n=e.type.contextTypes;if(!n)return pn;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var u={},a;for(a in n)u[a]=t[a];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=u),u}function rt(e){return e=e.childContextTypes,e!=null}function ri(){ke(nt),ke(Ye)}function Sc(e,t,n){if(Ye.current!==pn)throw Error(s(168));Ee(Ye,t),Ee(nt,n)}function Ec(e,t,n){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return n;o=o.getChildContext();for(var u in o)if(!(u in t))throw Error(s(108,ve(e)||"Unknown",u));return Y({},n,o)}function oi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||pn,Rn=Ye.current,Ee(Ye,e),Ee(nt,nt.current),!0}function Cc(e,t,n){var o=e.stateNode;if(!o)throw Error(s(169));n?(e=Ec(e,t,Rn),o.__reactInternalMemoizedMergedChildContext=e,ke(nt),ke(Ye),Ee(Ye,e)):ke(nt),Ee(nt,n)}var Qt=null,ii=!1,pl=!1;function kc(e){Qt===null?Qt=[e]:Qt.push(e)}function Cm(e){ii=!0,kc(e)}function hn(){if(!pl&&Qt!==null){pl=!0;var e=0,t=xe;try{var n=Qt;for(xe=1;e>=d,u-=d,Gt=1<<32-_t(t)+u|n<oe?(Be=ne,ne=null):Be=ne.sibling;var ge=M(k,ne,j[oe],B);if(ge===null){ne===null&&(ne=Be);break}e&&ne&&ge.alternate===null&&t(k,ne),w=a(ge,w,oe),te===null?J=ge:te.sibling=ge,te=ge,ne=Be}if(oe===j.length)return n(k,ne),Ae&&_n(k,oe),J;if(ne===null){for(;oeoe?(Be=ne,ne=null):Be=ne.sibling;var Cn=M(k,ne,ge.value,B);if(Cn===null){ne===null&&(ne=Be);break}e&&ne&&Cn.alternate===null&&t(k,ne),w=a(Cn,w,oe),te===null?J=Cn:te.sibling=Cn,te=Cn,ne=Be}if(ge.done)return n(k,ne),Ae&&_n(k,oe),J;if(ne===null){for(;!ge.done;oe++,ge=j.next())ge=F(k,ge.value,B),ge!==null&&(w=a(ge,w,oe),te===null?J=ge:te.sibling=ge,te=ge);return Ae&&_n(k,oe),J}for(ne=o(k,ne);!ge.done;oe++,ge=j.next())ge=q(ne,k,oe,ge.value,B),ge!==null&&(e&&ge.alternate!==null&&ne.delete(ge.key===null?oe:ge.key),w=a(ge,w,oe),te===null?J=ge:te.sibling=ge,te=ge);return e&&ne.forEach(function(ng){return t(k,ng)}),Ae&&_n(k,oe),J}function Ie(k,w,j,B){if(typeof j=="object"&&j!==null&&j.type===b&&j.key===null&&(j=j.props.children),typeof j=="object"&&j!==null){switch(j.$$typeof){case $:e:{for(var J=j.key,te=w;te!==null;){if(te.key===J){if(J=j.type,J===b){if(te.tag===7){n(k,te.sibling),w=u(te,j.props.children),w.return=k,k=w;break e}}else if(te.elementType===J||typeof J=="object"&&J!==null&&J.$$typeof===We&&Tc(J)===te.type){n(k,te.sibling),w=u(te,j.props),w.ref=no(k,te,j),w.return=k,k=w;break e}n(k,te);break}else t(k,te);te=te.sibling}j.type===b?(w=zn(j.props.children,k.mode,B,j.key),w.return=k,k=w):(B=Oi(j.type,j.key,j.props,null,k.mode,B),B.ref=no(k,w,j),B.return=k,k=B)}return d(k);case L:e:{for(te=j.key;w!==null;){if(w.key===te)if(w.tag===4&&w.stateNode.containerInfo===j.containerInfo&&w.stateNode.implementation===j.implementation){n(k,w.sibling),w=u(w,j.children||[]),w.return=k,k=w;break e}else{n(k,w);break}else t(k,w);w=w.sibling}w=cu(j,k.mode,B),w.return=k,k=w}return d(k);case We:return te=j._init,Ie(k,w,te(j._payload),B)}if(Ir(j))return K(k,w,j,B);if(Z(j))return X(k,w,j,B);ai(k,j)}return typeof j=="string"&&j!==""||typeof j=="number"?(j=""+j,w!==null&&w.tag===6?(n(k,w.sibling),w=u(w,j),w.return=k,k=w):(n(k,w),w=au(j,k.mode,B),w.return=k,k=w),d(k)):n(k,w)}return Ie}var ar=Ic(!0),Nc=Ic(!1),ci=dn(null),fi=null,cr=null,wl=null;function xl(){wl=cr=fi=null}function Sl(e){var t=ci.current;ke(ci),e._currentValue=t}function El(e,t,n){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===n)break;e=e.return}}function fr(e,t){fi=e,wl=cr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ot=!0),e.firstContext=null)}function Ct(e){var t=e._currentValue;if(wl!==e)if(e={context:e,memoizedValue:t,next:null},cr===null){if(fi===null)throw Error(s(308));cr=e,fi.dependencies={lanes:0,firstContext:e}}else cr=cr.next=e;return t}var Tn=null;function Cl(e){Tn===null?Tn=[e]:Tn.push(e)}function Oc(e,t,n,o){var u=t.interleaved;return u===null?(n.next=n,Cl(t)):(n.next=u.next,u.next=n),t.interleaved=n,Xt(e,o)}function Xt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var mn=!1;function kl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Lc(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 Jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gn(e,t,n){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,he&2){var u=o.pending;return u===null?t.next=t:(t.next=u.next,u.next=t),o.pending=t,Xt(e,n)}return u=o.interleaved,u===null?(t.next=t,Cl(o)):(t.next=u.next,u.next=t),o.interleaved=t,Xt(e,n)}function di(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,Us(e,n)}}function Dc(e,t){var n=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,n===o)){var u=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var d={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?u=a=d:a=a.next=d,n=n.next}while(n!==null);a===null?u=a=t:a=a.next=t}else u=a=t;n={baseState:o.baseState,firstBaseUpdate:u,lastBaseUpdate:a,shared:o.shared,effects:o.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function pi(e,t,n,o){var u=e.updateQueue;mn=!1;var a=u.firstBaseUpdate,d=u.lastBaseUpdate,m=u.shared.pending;if(m!==null){u.shared.pending=null;var y=m,P=y.next;y.next=null,d===null?a=P:d.next=P,d=y;var z=e.alternate;z!==null&&(z=z.updateQueue,m=z.lastBaseUpdate,m!==d&&(m===null?z.firstBaseUpdate=P:m.next=P,z.lastBaseUpdate=y))}if(a!==null){var F=u.baseState;d=0,z=P=y=null,m=a;do{var M=m.lane,q=m.eventTime;if((o&M)===M){z!==null&&(z=z.next={eventTime:q,lane:0,tag:m.tag,payload:m.payload,callback:m.callback,next:null});e:{var K=e,X=m;switch(M=t,q=n,X.tag){case 1:if(K=X.payload,typeof K=="function"){F=K.call(q,F,M);break e}F=K;break e;case 3:K.flags=K.flags&-65537|128;case 0:if(K=X.payload,M=typeof K=="function"?K.call(q,F,M):K,M==null)break e;F=Y({},F,M);break e;case 2:mn=!0}}m.callback!==null&&m.lane!==0&&(e.flags|=64,M=u.effects,M===null?u.effects=[m]:M.push(m))}else q={eventTime:q,lane:M,tag:m.tag,payload:m.payload,callback:m.callback,next:null},z===null?(P=z=q,y=F):z=z.next=q,d|=M;if(m=m.next,m===null){if(m=u.shared.pending,m===null)break;M=m,m=M.next,M.next=null,u.lastBaseUpdate=M,u.shared.pending=null}}while(!0);if(z===null&&(y=F),u.baseState=y,u.firstBaseUpdate=P,u.lastBaseUpdate=z,t=u.shared.interleaved,t!==null){u=t;do d|=u.lane,u=u.next;while(u!==t)}else a===null&&(u.shared.lanes=0);On|=d,e.lanes=d,e.memoizedState=F}}function Mc(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var o=_l.transition;_l.transition={};try{e(!1),t()}finally{xe=n,_l.transition=o}}function tf(){return kt().memoizedState}function Rm(e,t,n){var o=xn(e);if(n={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null},nf(e))rf(t,n);else if(n=Oc(e,t,n,o),n!==null){var u=tt();Dt(n,e,o,u),of(n,t,o)}}function Pm(e,t,n){var o=xn(e),u={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null};if(nf(e))rf(t,u);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var d=t.lastRenderedState,m=a(d,n);if(u.hasEagerState=!0,u.eagerState=m,Tt(m,d)){var y=t.interleaved;y===null?(u.next=u,Cl(t)):(u.next=y.next,y.next=u),t.interleaved=u;return}}catch{}finally{}n=Oc(e,t,u,o),n!==null&&(u=tt(),Dt(n,e,o,u),of(n,t,o))}}function nf(e){var t=e.alternate;return e===Pe||t!==null&&t===Pe}function rf(e,t){so=gi=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function of(e,t,n){if(n&4194240){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,Us(e,n)}}var wi={readContext:Ct,useCallback:qe,useContext:qe,useEffect:qe,useImperativeHandle:qe,useInsertionEffect:qe,useLayoutEffect:qe,useMemo:qe,useReducer:qe,useRef:qe,useState:qe,useDebugValue:qe,useDeferredValue:qe,useTransition:qe,useMutableSource:qe,useSyncExternalStore:qe,useId:qe,unstable_isNewReconciler:!1},_m={readContext:Ct,useCallback:function(e,t){return Ht().memoizedState=[e,t===void 0?null:t],e},useContext:Ct,useEffect:qc,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,yi(4194308,4,Kc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return yi(4194308,4,e,t)},useInsertionEffect:function(e,t){return yi(4,2,e,t)},useMemo:function(e,t){var n=Ht();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var o=Ht();return t=n!==void 0?n(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=Rm.bind(null,Pe,e),[o.memoizedState,e]},useRef:function(e){var t=Ht();return e={current:e},t.memoizedState=e},useState:Wc,useDebugValue:Ml,useDeferredValue:function(e){return Ht().memoizedState=e},useTransition:function(){var e=Wc(!1),t=e[0];return e=Am.bind(null,e[1]),Ht().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var o=Pe,u=Ht();if(Ae){if(n===void 0)throw Error(s(407));n=n()}else{if(n=t(),Fe===null)throw Error(s(349));Nn&30||Bc(o,t,n)}u.memoizedState=n;var a={value:n,getSnapshot:t};return u.queue=a,qc(Hc.bind(null,o,a,e),[e]),o.flags|=2048,ao(9,$c.bind(null,o,a,n,t),void 0,null),n},useId:function(){var e=Ht(),t=Fe.identifierPrefix;if(Ae){var n=Kt,o=Gt;n=(o&~(1<<32-_t(o)-1)).toString(32)+n,t=":"+t+"R"+n,n=lo++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=d.createElement(n,{is:o.is}):(e=d.createElement(n),n==="select"&&(d=e,o.multiple?d.multiple=!0:o.size&&(d.size=o.size))):e=d.createElementNS(e,n),e[Bt]=t,e[eo]=o,jf(e,t,!1,!1),t.stateNode=e;e:{switch(d=Ps(n,o),n){case"dialog":Ce("cancel",e),Ce("close",e),u=o;break;case"iframe":case"object":case"embed":Ce("load",e),u=o;break;case"video":case"audio":for(u=0;ugr&&(t.flags|=128,o=!0,co(a,!1),t.lanes=4194304)}else{if(!o)if(e=hi(d),e!==null){if(t.flags|=128,o=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),co(a,!0),a.tail===null&&a.tailMode==="hidden"&&!d.alternate&&!Ae)return Qe(t),null}else 2*Te()-a.renderingStartTime>gr&&n!==1073741824&&(t.flags|=128,o=!0,co(a,!1),t.lanes=4194304);a.isBackwards?(d.sibling=t.child,t.child=d):(n=a.last,n!==null?n.sibling=d:t.child=d,a.last=d)}return a.tail!==null?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=Te(),t.sibling=null,n=Re.current,Ee(Re,o?n&1|2:n&1),t):(Qe(t),null);case 22:case 23:return su(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?ht&1073741824&&(Qe(t),t.subtreeFlags&6&&(t.flags|=8192)):Qe(t),null;case 24:return null;case 25:return null}throw Error(s(156,t.tag))}function zm(e,t){switch(ml(t),t.tag){case 1:return rt(t.type)&&ri(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return dr(),ke(nt),ke(Ye),Pl(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Al(t),null;case 13:if(ke(Re),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));ur()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ke(Re),null;case 4:return dr(),null;case 10:return Sl(t.type._context),null;case 22:case 23:return su(),null;case 24:return null;default:return null}}var Ci=!1,Ge=!1,Um=typeof WeakSet=="function"?WeakSet:Set,G=null;function hr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(o){_e(e,t,o)}else n.current=null}function Ql(e,t,n){try{n()}catch(o){_e(e,t,o)}}var Pf=!1;function Fm(e,t){if(sl=bo,e=ic(),Js(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var o=n.getSelection&&n.getSelection();if(o&&o.rangeCount!==0){n=o.anchorNode;var u=o.anchorOffset,a=o.focusNode;o=o.focusOffset;try{n.nodeType,a.nodeType}catch{n=null;break e}var d=0,m=-1,y=-1,P=0,z=0,F=e,M=null;t:for(;;){for(var q;F!==n||u!==0&&F.nodeType!==3||(m=d+u),F!==a||o!==0&&F.nodeType!==3||(y=d+o),F.nodeType===3&&(d+=F.nodeValue.length),(q=F.firstChild)!==null;)M=F,F=q;for(;;){if(F===e)break t;if(M===n&&++P===u&&(m=d),M===a&&++z===o&&(y=d),(q=F.nextSibling)!==null)break;F=M,M=F.parentNode}F=q}n=m===-1||y===-1?null:{start:m,end:y}}else n=null}n=n||{start:0,end:0}}else n=null;for(ll={focusedElem:e,selectionRange:n},bo=!1,G=t;G!==null;)if(t=G,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,G=e;else for(;G!==null;){t=G;try{var K=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(K!==null){var X=K.memoizedProps,Ie=K.memoizedState,k=t.stateNode,w=k.getSnapshotBeforeUpdate(t.elementType===t.type?X:Nt(t.type,X),Ie);k.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var j=t.stateNode.containerInfo;j.nodeType===1?j.textContent="":j.nodeType===9&&j.documentElement&&j.removeChild(j.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(s(163))}}catch(B){_e(t,t.return,B)}if(e=t.sibling,e!==null){e.return=t.return,G=e;break}G=t.return}return K=Pf,Pf=!1,K}function fo(e,t,n){var o=t.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var u=o=o.next;do{if((u.tag&e)===e){var a=u.destroy;u.destroy=void 0,a!==void 0&&Ql(t,n,a)}u=u.next}while(u!==o)}}function ki(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var o=n.create;n.destroy=o()}n=n.next}while(n!==t)}}function Gl(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function _f(e){var t=e.alternate;t!==null&&(e.alternate=null,_f(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Bt],delete t[eo],delete t[fl],delete t[Sm],delete t[Em])),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 Tf(e){return e.tag===5||e.tag===3||e.tag===4}function If(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Tf(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 Kl(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ti));else if(o!==4&&(e=e.child,e!==null))for(Kl(e,t,n),e=e.sibling;e!==null;)Kl(e,t,n),e=e.sibling}function Xl(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(Xl(e,t,n),e=e.sibling;e!==null;)Xl(e,t,n),e=e.sibling}var be=null,Ot=!1;function yn(e,t,n){for(n=n.child;n!==null;)Nf(e,t,n),n=n.sibling}function Nf(e,t,n){if(Ft&&typeof Ft.onCommitFiberUnmount=="function")try{Ft.onCommitFiberUnmount(zo,n)}catch{}switch(n.tag){case 5:Ge||hr(n,t);case 6:var o=be,u=Ot;be=null,yn(e,t,n),be=o,Ot=u,be!==null&&(Ot?(e=be,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):be.removeChild(n.stateNode));break;case 18:be!==null&&(Ot?(e=be,n=n.stateNode,e.nodeType===8?cl(e.parentNode,n):e.nodeType===1&&cl(e,n),br(e)):cl(be,n.stateNode));break;case 4:o=be,u=Ot,be=n.stateNode.containerInfo,Ot=!0,yn(e,t,n),be=o,Ot=u;break;case 0:case 11:case 14:case 15:if(!Ge&&(o=n.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){u=o=o.next;do{var a=u,d=a.destroy;a=a.tag,d!==void 0&&(a&2||a&4)&&Ql(n,t,d),u=u.next}while(u!==o)}yn(e,t,n);break;case 1:if(!Ge&&(hr(n,t),o=n.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=n.memoizedProps,o.state=n.memoizedState,o.componentWillUnmount()}catch(m){_e(n,t,m)}yn(e,t,n);break;case 21:yn(e,t,n);break;case 22:n.mode&1?(Ge=(o=Ge)||n.memoizedState!==null,yn(e,t,n),Ge=o):yn(e,t,n);break;default:yn(e,t,n)}}function Of(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Um),t.forEach(function(o){var u=Qm.bind(null,e,o);n.has(o)||(n.add(o),o.then(u,u))})}}function Lt(e,t){var n=t.deletions;if(n!==null)for(var o=0;ou&&(u=d),o&=~a}if(o=u,o=Te()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*$m(o/1960))-o,10e?16:e,wn===null)var o=!1;else{if(e=wn,wn=null,_i=0,he&6)throw Error(s(331));var u=he;for(he|=4,G=e.current;G!==null;){var a=G,d=a.child;if(G.flags&16){var m=a.deletions;if(m!==null){for(var y=0;yTe()-eu?Dn(e,0):Zl|=n),st(e,t)}function Yf(e,t){t===0&&(e.mode&1?(t=Fo,Fo<<=1,!(Fo&130023424)&&(Fo=4194304)):t=1);var n=tt();e=Xt(e,t),e!==null&&(Ur(e,t,n),st(e,n))}function qm(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Yf(e,n)}function Qm(e,t){var n=0;switch(e.tag){case 13:var o=e.stateNode,u=e.memoizedState;u!==null&&(n=u.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(s(314))}o!==null&&o.delete(t),Yf(e,n)}var qf;qf=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||nt.current)ot=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ot=!1,Dm(e,t,n);ot=!!(e.flags&131072)}else ot=!1,Ae&&t.flags&1048576&&jc(t,li,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;Ei(e,t),e=t.pendingProps;var u=ir(t,Ye.current);fr(t,n),u=Il(null,t,o,e,u,n);var a=Nl();return t.flags|=1,typeof u=="object"&&u!==null&&typeof u.render=="function"&&u.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,rt(o)?(a=!0,oi(t)):a=!1,t.memoizedState=u.state!==null&&u.state!==void 0?u.state:null,kl(t),u.updater=xi,t.stateNode=u,u._reactInternals=t,Ul(t,o,e,n),t=Hl(null,t,o,!0,a,n)):(t.tag=0,Ae&&a&&hl(t),et(null,t,u,n),t=t.child),t;case 16:o=t.elementType;e:{switch(Ei(e,t),e=t.pendingProps,u=o._init,o=u(o._payload),t.type=o,u=t.tag=Km(o),e=Nt(o,e),u){case 0:t=$l(null,t,o,e,n);break e;case 1:t=wf(null,t,o,e,n);break e;case 11:t=hf(null,t,o,e,n);break e;case 14:t=mf(null,t,o,Nt(o.type,e),n);break e}throw Error(s(306,o,""))}return t;case 0:return o=t.type,u=t.pendingProps,u=t.elementType===o?u:Nt(o,u),$l(e,t,o,u,n);case 1:return o=t.type,u=t.pendingProps,u=t.elementType===o?u:Nt(o,u),wf(e,t,o,u,n);case 3:e:{if(xf(t),e===null)throw Error(s(387));o=t.pendingProps,a=t.memoizedState,u=a.element,Lc(e,t),pi(t,o,null,n);var d=t.memoizedState;if(o=d.element,a.isDehydrated)if(a={element:o,isDehydrated:!1,cache:d.cache,pendingSuspenseBoundaries:d.pendingSuspenseBoundaries,transitions:d.transitions},t.updateQueue.baseState=a,t.memoizedState=a,t.flags&256){u=pr(Error(s(423)),t),t=Sf(e,t,o,n,u);break e}else if(o!==u){u=pr(Error(s(424)),t),t=Sf(e,t,o,n,u);break e}else for(pt=fn(t.stateNode.containerInfo.firstChild),dt=t,Ae=!0,It=null,n=Nc(t,null,o,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ur(),o===u){t=Zt(e,t,n);break e}et(e,t,o,n)}t=t.child}return t;case 5:return zc(t),e===null&&yl(t),o=t.type,u=t.pendingProps,a=e!==null?e.memoizedProps:null,d=u.children,ul(o,u)?d=null:a!==null&&ul(o,a)&&(t.flags|=32),vf(e,t),et(e,t,d,n),t.child;case 6:return e===null&&yl(t),null;case 13:return Ef(e,t,n);case 4:return jl(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=ar(t,null,o,n):et(e,t,o,n),t.child;case 11:return o=t.type,u=t.pendingProps,u=t.elementType===o?u:Nt(o,u),hf(e,t,o,u,n);case 7:return et(e,t,t.pendingProps,n),t.child;case 8:return et(e,t,t.pendingProps.children,n),t.child;case 12:return et(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(o=t.type._context,u=t.pendingProps,a=t.memoizedProps,d=u.value,Ee(ci,o._currentValue),o._currentValue=d,a!==null)if(Tt(a.value,d)){if(a.children===u.children&&!nt.current){t=Zt(e,t,n);break e}}else for(a=t.child,a!==null&&(a.return=t);a!==null;){var m=a.dependencies;if(m!==null){d=a.child;for(var y=m.firstContext;y!==null;){if(y.context===o){if(a.tag===1){y=Jt(-1,n&-n),y.tag=2;var P=a.updateQueue;if(P!==null){P=P.shared;var z=P.pending;z===null?y.next=y:(y.next=z.next,z.next=y),P.pending=y}}a.lanes|=n,y=a.alternate,y!==null&&(y.lanes|=n),El(a.return,n,t),m.lanes|=n;break}y=y.next}}else if(a.tag===10)d=a.type===t.type?null:a.child;else if(a.tag===18){if(d=a.return,d===null)throw Error(s(341));d.lanes|=n,m=d.alternate,m!==null&&(m.lanes|=n),El(d,n,t),d=a.sibling}else d=a.child;if(d!==null)d.return=a;else for(d=a;d!==null;){if(d===t){d=null;break}if(a=d.sibling,a!==null){a.return=d.return,d=a;break}d=d.return}a=d}et(e,t,u.children,n),t=t.child}return t;case 9:return u=t.type,o=t.pendingProps.children,fr(t,n),u=Ct(u),o=o(u),t.flags|=1,et(e,t,o,n),t.child;case 14:return o=t.type,u=Nt(o,t.pendingProps),u=Nt(o.type,u),mf(e,t,o,u,n);case 15:return gf(e,t,t.type,t.pendingProps,n);case 17:return o=t.type,u=t.pendingProps,u=t.elementType===o?u:Nt(o,u),Ei(e,t),t.tag=1,rt(o)?(e=!0,oi(t)):e=!1,fr(t,n),lf(t,o,u),Ul(t,o,u,n),Hl(null,t,o,!0,e,n);case 19:return kf(e,t,n);case 22:return yf(e,t,n)}throw Error(s(156,t.tag))};function Qf(e,t){return Aa(e,t)}function Gm(e,t,n,o){this.tag=e,this.key=n,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 At(e,t,n,o){return new Gm(e,t,n,o)}function uu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Km(e){if(typeof e=="function")return uu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===wt)return 11;if(e===xt)return 14}return 2}function En(e,t){var n=e.alternate;return n===null?(n=At(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Oi(e,t,n,o,u,a){var d=2;if(o=e,typeof e=="function")uu(e)&&(d=1);else if(typeof e=="string")d=5;else e:switch(e){case b:return zn(n.children,u,a,t);case re:d=8,u|=8;break;case ye:return e=At(12,n,t,u|2),e.elementType=ye,e.lanes=a,e;case Ze:return e=At(13,n,t,u),e.elementType=Ze,e.lanes=a,e;case ct:return e=At(19,n,t,u),e.elementType=ct,e.lanes=a,e;case Se:return Li(n,u,a,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Ne:d=10;break e;case at:d=9;break e;case wt:d=11;break e;case xt:d=14;break e;case We:d=16,o=null;break e}throw Error(s(130,e==null?e:typeof e,""))}return t=At(d,n,t,u),t.elementType=e,t.type=o,t.lanes=a,t}function zn(e,t,n,o){return e=At(7,e,o,t),e.lanes=n,e}function Li(e,t,n,o){return e=At(22,e,o,t),e.elementType=Se,e.lanes=n,e.stateNode={isHidden:!1},e}function au(e,t,n){return e=At(6,e,null,t),e.lanes=n,e}function cu(e,t,n){return t=At(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Xm(e,t,n,o,u){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=zs(0),this.expirationTimes=zs(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zs(0),this.identifierPrefix=o,this.onRecoverableError=u,this.mutableSourceEagerHydrationData=null}function fu(e,t,n,o,u,a,d,m,y){return e=new Xm(e,t,n,m,y),t===1?(t=1,a===!0&&(t|=8)):t=0,a=At(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:o,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kl(a),e}function Jm(e,t,n){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(i){console.error(i)}}return r(),yu.exports=fg(),yu.exports}var ad;function pg(){if(ad)return $i;ad=1;var r=dg();return $i.createRoot=r.createRoot,$i.hydrateRoot=r.hydrateRoot,$i}var hg=pg(),Xe=function(){return Xe=Object.assign||function(i){for(var s,l=1,c=arguments.length;l0?$e(Ar,--Rt):0,Cr--,Le===10&&(Cr=1,fs--),Le}function Mt(){return Le=Rt2||Lu(Le)>3?"":" "}function kg(r,i){for(;--i&&Mt()&&!(Le<48||Le>102||Le>57&&Le<65||Le>70&&Le<97););return ps(r,Gi()+(i<6&&Bn()==32&&Mt()==32))}function Du(r){for(;Mt();)switch(Le){case r:return Rt;case 34:case 39:r!==34&&r!==39&&Du(Le);break;case 40:r===41&&Du(r);break;case 92:Mt();break}return Rt}function jg(r,i){for(;Mt()&&r+Le!==57;)if(r+Le===84&&Bn()===47)break;return"/*"+ps(i,Rt-1)+"*"+Ju(r===47?r:Mt())}function Ag(r){for(;!Lu(Bn());)Mt();return ps(r,Rt)}function Rg(r){return Eg(Ki("",null,null,null,[""],r=Sg(r),0,[0],r))}function Ki(r,i,s,l,c,f,p,g,x){for(var v=0,S=0,A=p,T=0,I=0,R=0,C=1,N=1,H=1,U=0,V="",Q=c,$=f,L=l,b=V;N;)switch(R=U,U=Mt()){case 40:if(R!=108&&$e(b,A-1)==58){Qi(b+=ae(xu(U),"&","&\f"),"&\f",up(v?g[v-1]:0))!=-1&&(H=-1);break}case 34:case 39:case 91:b+=xu(U);break;case 9:case 10:case 13:case 32:b+=Cg(R);break;case 92:b+=kg(Gi()-1,7);continue;case 47:switch(Bn()){case 42:case 47:Eo(Pg(jg(Mt(),Gi()),i,s,x),x);break;default:b+="/"}break;case 123*C:g[v++]=Wt(b)*H;case 125*C:case 59:case 0:switch(U){case 0:case 125:N=0;case 59+S:H==-1&&(b=ae(b,/\f/g,"")),I>0&&Wt(b)-A&&Eo(I>32?dd(b+";",l,s,A-1,x):dd(ae(b," ","")+";",l,s,A-2,x),x);break;case 59:b+=";";default:if(Eo(L=fd(b,i,s,v,S,c,g,V,Q=[],$=[],A,f),f),U===123)if(S===0)Ki(b,i,L,L,Q,f,A,g,$);else switch(T===99&&$e(b,3)===110?100:T){case 100:case 108:case 109:case 115:Ki(r,L,L,l&&Eo(fd(r,L,L,0,0,c,g,V,c,Q=[],A,$),$),c,$,A,g,l?Q:$);break;default:Ki(b,L,L,L,[""],$,0,g,$)}}v=S=I=0,C=H=1,V=b="",A=p;break;case 58:A=1+Wt(b),I=R;default:if(C<1){if(U==123)--C;else if(U==125&&C++==0&&xg()==125)continue}switch(b+=Ju(U),U*C){case 38:H=S>0?1:(b+="\f",-1);break;case 44:g[v++]=(Wt(b)-1)*H,H=1;break;case 64:Bn()===45&&(b+=xu(Mt())),T=Bn(),S=A=Wt(V=b+=Ag(Gi())),U++;break;case 45:R===45&&Wt(b)==2&&(C=0)}}return f}function fd(r,i,s,l,c,f,p,g,x,v,S,A){for(var T=c-1,I=c===0?f:[""],R=cp(I),C=0,N=0,H=0;C0?I[U]+" "+V:ae(V,/&\f/g,I[U])))&&(x[H++]=Q);return ds(r,i,s,c===0?cs:g,x,v,S,A)}function Pg(r,i,s,l){return ds(r,i,s,sp,Ju(wg()),Er(r,2,-2),0,l)}function dd(r,i,s,l,c){return ds(r,i,s,Xu,Er(r,0,l),Er(r,l+1,-1),l,c)}function dp(r,i,s){switch(yg(r,i)){case 5103:return we+"print-"+r+r;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 we+r+r;case 4789:return Co+r+r;case 5349:case 4246:case 4810:case 6968:case 2756:return we+r+Co+r+je+r+r;case 5936:switch($e(r,i+11)){case 114:return we+r+je+ae(r,/[svh]\w+-[tblr]{2}/,"tb")+r;case 108:return we+r+je+ae(r,/[svh]\w+-[tblr]{2}/,"tb-rl")+r;case 45:return we+r+je+ae(r,/[svh]\w+-[tblr]{2}/,"lr")+r}case 6828:case 4268:case 2903:return we+r+je+r+r;case 6165:return we+r+je+"flex-"+r+r;case 5187:return we+r+ae(r,/(\w+).+(:[^]+)/,we+"box-$1$2"+je+"flex-$1$2")+r;case 5443:return we+r+je+"flex-item-"+ae(r,/flex-|-self/g,"")+(tn(r,/flex-|baseline/)?"":je+"grid-row-"+ae(r,/flex-|-self/g,""))+r;case 4675:return we+r+je+"flex-line-pack"+ae(r,/align-content|flex-|-self/g,"")+r;case 5548:return we+r+je+ae(r,"shrink","negative")+r;case 5292:return we+r+je+ae(r,"basis","preferred-size")+r;case 6060:return we+"box-"+ae(r,"-grow","")+we+r+je+ae(r,"grow","positive")+r;case 4554:return we+ae(r,/([^-])(transform)/g,"$1"+we+"$2")+r;case 6187:return ae(ae(ae(r,/(zoom-|grab)/,we+"$1"),/(image-set)/,we+"$1"),r,"")+r;case 5495:case 3959:return ae(r,/(image-set\([^]*)/,we+"$1$`$1");case 4968:return ae(ae(r,/(.+:)(flex-)?(.*)/,we+"box-pack:$3"+je+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+we+r+r;case 4200:if(!tn(r,/flex-|baseline/))return je+"grid-column-align"+Er(r,i)+r;break;case 2592:case 3360:return je+ae(r,"template-","")+r;case 4384:case 3616:return s&&s.some(function(l,c){return i=c,tn(l.props,/grid-\w+-end/)})?~Qi(r+(s=s[i].value),"span",0)?r:je+ae(r,"-start","")+r+je+"grid-row-span:"+(~Qi(s,"span",0)?tn(s,/\d+/):+tn(s,/\d+/)-+tn(r,/\d+/))+";":je+ae(r,"-start","")+r;case 4896:case 4128:return s&&s.some(function(l){return tn(l.props,/grid-\w+-start/)})?r:je+ae(ae(r,"-end","-span"),"span ","")+r;case 4095:case 3583:case 4068:case 2532:return ae(r,/(.+)-inline(.+)/,we+"$1$2")+r;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(r)-1-i>6)switch($e(r,i+1)){case 109:if($e(r,i+4)!==45)break;case 102:return ae(r,/(.+:)(.+)-([^]+)/,"$1"+we+"$2-$3$1"+Co+($e(r,i+3)==108?"$3":"$2-$3"))+r;case 115:return~Qi(r,"stretch",0)?dp(ae(r,"stretch","fill-available"),i,s)+r:r}break;case 5152:case 5920:return ae(r,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(l,c,f,p,g,x,v){return je+c+":"+f+v+(p?je+c+"-span:"+(g?x:+x-+f)+v:"")+r});case 4949:if($e(r,i+6)===121)return ae(r,":",":"+we)+r;break;case 6444:switch($e(r,$e(r,14)===45?18:11)){case 120:return ae(r,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+we+($e(r,14)===45?"inline-":"")+"box$3$1"+we+"$2$3$1"+je+"$2box$3")+r;case 100:return ae(r,":",":"+je)+r}break;case 5719:case 2647:case 2135:case 3927:case 2391:return ae(r,"scroll-","scroll-snap-")+r}return r}function rs(r,i){for(var s="",l=0;l-1&&!r.return)switch(r.type){case Xu:r.return=dp(r.value,r.length,s);return;case lp:return rs([kn(r,{value:ae(r.value,"@","@"+we)})],l);case cs:if(r.length)return vg(s=r.props,function(c){switch(tn(c,l=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":vr(kn(r,{props:[ae(c,/:(read-\w+)/,":"+Co+"$1")]})),vr(kn(r,{props:[c]})),Ou(r,{props:cd(s,l)});break;case"::placeholder":vr(kn(r,{props:[ae(c,/:(plac\w+)/,":"+we+"input-$1")]})),vr(kn(r,{props:[ae(c,/:(plac\w+)/,":"+Co+"$1")]})),vr(kn(r,{props:[ae(c,/:(plac\w+)/,je+"input-$1")]})),vr(kn(r,{props:[c]})),Ou(r,{props:cd(s,l)});break}return""})}}var Og={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},mt={},kr=typeof process<"u"&&mt!==void 0&&(mt.REACT_APP_SC_ATTR||mt.SC_ATTR)||"data-styled",pp="active",hp="data-styled-version",hs="6.1.14",Zu=`/*!sc*/ +`,os=typeof window<"u"&&"HTMLElement"in window,Lg=!!(typeof SC_DISABLE_SPEEDY=="boolean"?SC_DISABLE_SPEEDY:typeof process<"u"&&mt!==void 0&&mt.REACT_APP_SC_DISABLE_SPEEDY!==void 0&&mt.REACT_APP_SC_DISABLE_SPEEDY!==""?mt.REACT_APP_SC_DISABLE_SPEEDY!=="false"&&mt.REACT_APP_SC_DISABLE_SPEEDY:typeof process<"u"&&mt!==void 0&&mt.SC_DISABLE_SPEEDY!==void 0&&mt.SC_DISABLE_SPEEDY!==""&&mt.SC_DISABLE_SPEEDY!=="false"&&mt.SC_DISABLE_SPEEDY),ms=Object.freeze([]),jr=Object.freeze({});function Dg(r,i,s){return s===void 0&&(s=jr),r.theme!==s.theme&&r.theme||i||s.theme}var mp=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"]),Mg=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,zg=/(^-|-$)/g;function pd(r){return r.replace(Mg,"-").replace(zg,"")}var Ug=/(a)(d)/gi,Hi=52,hd=function(r){return String.fromCharCode(r+(r>25?39:97))};function Mu(r){var i,s="";for(i=Math.abs(r);i>Hi;i=i/Hi|0)s=hd(i%Hi)+s;return(hd(i%Hi)+s).replace(Ug,"$1-$2")}var Su,gp=5381,wr=function(r,i){for(var s=i.length;s;)r=33*r^i.charCodeAt(--s);return r},yp=function(r){return wr(gp,r)};function Fg(r){return Mu(yp(r)>>>0)}function Bg(r){return r.displayName||r.name||"Component"}function Eu(r){return typeof r=="string"&&!0}var vp=typeof Symbol=="function"&&Symbol.for,wp=vp?Symbol.for("react.memo"):60115,$g=vp?Symbol.for("react.forward_ref"):60112,Hg={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},bg={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},xp={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Vg=((Su={})[$g]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Su[wp]=xp,Su);function md(r){return("type"in(i=r)&&i.type.$$typeof)===wp?xp:"$$typeof"in r?Vg[r.$$typeof]:Hg;var i}var Wg=Object.defineProperty,Yg=Object.getOwnPropertyNames,gd=Object.getOwnPropertySymbols,qg=Object.getOwnPropertyDescriptor,Qg=Object.getPrototypeOf,yd=Object.prototype;function Sp(r,i,s){if(typeof i!="string"){if(yd){var l=Qg(i);l&&l!==yd&&Sp(r,l,s)}var c=Yg(i);gd&&(c=c.concat(gd(i)));for(var f=md(r),p=md(i),g=0;g0?" Args: ".concat(i.join(", ")):""))}var Gg=function(){function r(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}return r.prototype.indexOfGroup=function(i){for(var s=0,l=0;l=this.groupSizes.length){for(var l=this.groupSizes,c=l.length,f=c;i>=f;)if((f<<=1)<0)throw Vn(16,"".concat(i));this.groupSizes=new Uint32Array(f),this.groupSizes.set(l),this.length=f;for(var p=c;p=this.length||this.groupSizes[i]===0)return s;for(var l=this.groupSizes[i],c=this.indexOfGroup(i),f=c+l,p=c;p=0){var l=document.createTextNode(s);return this.element.insertBefore(l,this.nodes[i]||null),this.length++,!0}return!1},r.prototype.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},r.prototype.getRule=function(i){return i0&&(N+="".concat(H,","))}),x+="".concat(R).concat(C,'{content:"').concat(N,'"}').concat(Zu)},S=0;S0?".".concat(i):T},S=x.slice();S.push(function(T){T.type===cs&&T.value.includes("&")&&(T.props[0]=T.props[0].replace(sy,s).replace(l,v))}),p.prefix&&S.push(Ng),S.push(_g);var A=function(T,I,R,C){I===void 0&&(I=""),R===void 0&&(R=""),C===void 0&&(C="&"),i=C,s=I,l=new RegExp("\\".concat(s,"\\b"),"g");var N=T.replace(ly,""),H=Rg(R||I?"".concat(R," ").concat(I," { ").concat(N," }"):N);p.namespace&&(H=kp(H,p.namespace));var U=[];return rs(H,Tg(S.concat(Ig(function(V){return U.push(V)})))),U};return A.hash=x.length?x.reduce(function(T,I){return I.name||Vn(15),wr(T,I.name)},gp).toString():"",A}var ay=new Cp,Uu=uy(),jp=gt.createContext({shouldForwardProp:void 0,styleSheet:ay,stylis:Uu});jp.Consumer;gt.createContext(void 0);function Sd(){return ie.useContext(jp)}var cy=function(){function r(i,s){var l=this;this.inject=function(c,f){f===void 0&&(f=Uu);var p=l.name+f.hash;c.hasNameForId(l.id,p)||c.insertRules(l.id,p,f(l.rules,p,"@keyframes"))},this.name=i,this.id="sc-keyframes-".concat(i),this.rules=s,ta(this,function(){throw Vn(12,String(l.name))})}return r.prototype.getName=function(i){return i===void 0&&(i=Uu),this.name+i.hash},r}(),fy=function(r){return r>="A"&&r<="Z"};function Ed(r){for(var i="",s=0;s>>0);if(!s.hasNameForId(this.componentId,p)){var g=l(f,".".concat(p),void 0,this.componentId);s.insertRules(this.componentId,p,g)}c=Un(c,p),this.staticRulesId=p}else{for(var x=wr(this.baseHash,l.hash),v="",S=0;S>>0);s.hasNameForId(this.componentId,I)||s.insertRules(this.componentId,I,l(v,".".concat(I),void 0,this.componentId)),c=Un(c,I)}}return c},r}(),ss=gt.createContext(void 0);ss.Consumer;function Cd(r){var i=gt.useContext(ss),s=ie.useMemo(function(){return function(l,c){if(!l)throw Vn(14);if(bn(l)){var f=l(c);return f}if(Array.isArray(l)||typeof l!="object")throw Vn(8);return c?Xe(Xe({},c),l):l}(r.theme,i)},[r.theme,i]);return r.children?gt.createElement(ss.Provider,{value:s},r.children):null}var Cu={};function my(r,i,s){var l=ea(r),c=r,f=!Eu(r),p=i.attrs,g=p===void 0?ms:p,x=i.componentId,v=x===void 0?function(Q,$){var L=typeof Q!="string"?"sc":pd(Q);Cu[L]=(Cu[L]||0)+1;var b="".concat(L,"-").concat(Fg(hs+L+Cu[L]));return $?"".concat($,"-").concat(b):b}(i.displayName,i.parentComponentId):x,S=i.displayName,A=S===void 0?function(Q){return Eu(Q)?"styled.".concat(Q):"Styled(".concat(Bg(Q),")")}(r):S,T=i.displayName&&i.componentId?"".concat(pd(i.displayName),"-").concat(i.componentId):i.componentId||v,I=l&&c.attrs?c.attrs.concat(g).filter(Boolean):g,R=i.shouldForwardProp;if(l&&c.shouldForwardProp){var C=c.shouldForwardProp;if(i.shouldForwardProp){var N=i.shouldForwardProp;R=function(Q,$){return C(Q,$)&&N(Q,$)}}else R=C}var H=new hy(s,T,l?c.componentStyle:void 0);function U(Q,$){return function(L,b,re){var ye=L.attrs,Ne=L.componentStyle,at=L.defaultProps,wt=L.foldedComponentIds,Ze=L.styledComponentId,ct=L.target,xt=gt.useContext(ss),We=Sd(),Se=L.shouldForwardProp||We.shouldForwardProp,W=Dg(b,xt,at)||jr,Z=function(de,ce,ve){for(var pe,me=Xe(Xe({},ce),{className:void 0,theme:ve}),He=0;Hei=>{const s=yy.call(i);return r[s]||(r[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),Ut=r=>(r=r.toLowerCase(),i=>gs(i)===r),ys=r=>i=>typeof i===r,{isArray:Rr}=Array,Po=ys("undefined");function vy(r){return r!==null&&!Po(r)&&r.constructor!==null&&!Po(r.constructor)&&yt(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const Tp=Ut("ArrayBuffer");function wy(r){let i;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?i=ArrayBuffer.isView(r):i=r&&r.buffer&&Tp(r.buffer),i}const xy=ys("string"),yt=ys("function"),Ip=ys("number"),vs=r=>r!==null&&typeof r=="object",Sy=r=>r===!0||r===!1,Zi=r=>{if(gs(r)!=="object")return!1;const i=na(r);return(i===null||i===Object.prototype||Object.getPrototypeOf(i)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},Ey=Ut("Date"),Cy=Ut("File"),ky=Ut("Blob"),jy=Ut("FileList"),Ay=r=>vs(r)&&yt(r.pipe),Ry=r=>{let i;return r&&(typeof FormData=="function"&&r instanceof FormData||yt(r.append)&&((i=gs(r))==="formdata"||i==="object"&&yt(r.toString)&&r.toString()==="[object FormData]"))},Py=Ut("URLSearchParams"),[_y,Ty,Iy,Ny]=["ReadableStream","Request","Response","Headers"].map(Ut),Oy=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function _o(r,i,{allOwnKeys:s=!1}={}){if(r===null||typeof r>"u")return;let l,c;if(typeof r!="object"&&(r=[r]),Rr(r))for(l=0,c=r.length;l0;)if(c=s[l],i===c.toLowerCase())return c;return null}const Fn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Op=r=>!Po(r)&&r!==Fn;function Bu(){const{caseless:r}=Op(this)&&this||{},i={},s=(l,c)=>{const f=r&&Np(i,c)||c;Zi(i[f])&&Zi(l)?i[f]=Bu(i[f],l):Zi(l)?i[f]=Bu({},l):Rr(l)?i[f]=l.slice():i[f]=l};for(let l=0,c=arguments.length;l(_o(i,(c,f)=>{s&&yt(c)?r[f]=_p(c,s):r[f]=c},{allOwnKeys:l}),r),Dy=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),My=(r,i,s,l)=>{r.prototype=Object.create(i.prototype,l),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:i.prototype}),s&&Object.assign(r.prototype,s)},zy=(r,i,s,l)=>{let c,f,p;const g={};if(i=i||{},r==null)return i;do{for(c=Object.getOwnPropertyNames(r),f=c.length;f-- >0;)p=c[f],(!l||l(p,r,i))&&!g[p]&&(i[p]=r[p],g[p]=!0);r=s!==!1&&na(r)}while(r&&(!s||s(r,i))&&r!==Object.prototype);return i},Uy=(r,i,s)=>{r=String(r),(s===void 0||s>r.length)&&(s=r.length),s-=i.length;const l=r.indexOf(i,s);return l!==-1&&l===s},Fy=r=>{if(!r)return null;if(Rr(r))return r;let i=r.length;if(!Ip(i))return null;const s=new Array(i);for(;i-- >0;)s[i]=r[i];return s},By=(r=>i=>r&&i instanceof r)(typeof Uint8Array<"u"&&na(Uint8Array)),$y=(r,i)=>{const l=(r&&r[Symbol.iterator]).call(r);let c;for(;(c=l.next())&&!c.done;){const f=c.value;i.call(r,f[0],f[1])}},Hy=(r,i)=>{let s;const l=[];for(;(s=r.exec(i))!==null;)l.push(s);return l},by=Ut("HTMLFormElement"),Vy=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,l,c){return l.toUpperCase()+c}),Ad=(({hasOwnProperty:r})=>(i,s)=>r.call(i,s))(Object.prototype),Wy=Ut("RegExp"),Lp=(r,i)=>{const s=Object.getOwnPropertyDescriptors(r),l={};_o(s,(c,f)=>{let p;(p=i(c,f,r))!==!1&&(l[f]=p||c)}),Object.defineProperties(r,l)},Yy=r=>{Lp(r,(i,s)=>{if(yt(r)&&["arguments","caller","callee"].indexOf(s)!==-1)return!1;const l=r[s];if(yt(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+"'")})}})},qy=(r,i)=>{const s={},l=c=>{c.forEach(f=>{s[f]=!0})};return Rr(r)?l(r):l(String(r).split(i)),s},Qy=()=>{},Gy=(r,i)=>r!=null&&Number.isFinite(r=+r)?r:i,ku="abcdefghijklmnopqrstuvwxyz",Rd="0123456789",Dp={DIGIT:Rd,ALPHA:ku,ALPHA_DIGIT:ku+ku.toUpperCase()+Rd},Ky=(r=16,i=Dp.ALPHA_DIGIT)=>{let s="";const{length:l}=i;for(;r--;)s+=i[Math.random()*l|0];return s};function Xy(r){return!!(r&&yt(r.append)&&r[Symbol.toStringTag]==="FormData"&&r[Symbol.iterator])}const Jy=r=>{const i=new Array(10),s=(l,c)=>{if(vs(l)){if(i.indexOf(l)>=0)return;if(!("toJSON"in l)){i[c]=l;const f=Rr(l)?[]:{};return _o(l,(p,g)=>{const x=s(p,c+1);!Po(x)&&(f[g]=x)}),i[c]=void 0,f}}return l};return s(r,0)},Zy=Ut("AsyncFunction"),ev=r=>r&&(vs(r)||yt(r))&&yt(r.then)&&yt(r.catch),Mp=((r,i)=>r?setImmediate:i?((s,l)=>(Fn.addEventListener("message",({source:c,data:f})=>{c===Fn&&f===s&&l.length&&l.shift()()},!1),c=>{l.push(c),Fn.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",yt(Fn.postMessage)),tv=typeof queueMicrotask<"u"?queueMicrotask.bind(Fn):typeof process<"u"&&process.nextTick||Mp,O={isArray:Rr,isArrayBuffer:Tp,isBuffer:vy,isFormData:Ry,isArrayBufferView:wy,isString:xy,isNumber:Ip,isBoolean:Sy,isObject:vs,isPlainObject:Zi,isReadableStream:_y,isRequest:Ty,isResponse:Iy,isHeaders:Ny,isUndefined:Po,isDate:Ey,isFile:Cy,isBlob:ky,isRegExp:Wy,isFunction:yt,isStream:Ay,isURLSearchParams:Py,isTypedArray:By,isFileList:jy,forEach:_o,merge:Bu,extend:Ly,trim:Oy,stripBOM:Dy,inherits:My,toFlatObject:zy,kindOf:gs,kindOfTest:Ut,endsWith:Uy,toArray:Fy,forEachEntry:$y,matchAll:Hy,isHTMLForm:by,hasOwnProperty:Ad,hasOwnProp:Ad,reduceDescriptors:Lp,freezeMethods:Yy,toObjectSet:qy,toCamelCase:Vy,noop:Qy,toFiniteNumber:Gy,findKey:Np,global:Fn,isContextDefined:Op,ALPHABET:Dp,generateString:Ky,isSpecCompliantForm:Xy,toJSONObject:Jy,isAsyncFn:Zy,isThenable:ev,setImmediate:Mp,asap:tv};function le(r,i,s,l,c){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,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(le,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 zp=le.prototype,Up={};["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(r=>{Up[r]={value:r}});Object.defineProperties(le,Up);Object.defineProperty(zp,"isAxiosError",{value:!0});le.from=(r,i,s,l,c,f)=>{const p=Object.create(zp);return O.toFlatObject(r,p,function(x){return x!==Error.prototype},g=>g!=="isAxiosError"),le.call(p,r.message,i,s,l,c),p.cause=r,p.name=r.name,f&&Object.assign(p,f),p};const nv=null;function $u(r){return O.isPlainObject(r)||O.isArray(r)}function Fp(r){return O.endsWith(r,"[]")?r.slice(0,-2):r}function Pd(r,i,s){return r?r.concat(i).map(function(c,f){return c=Fp(c),!s&&f?"["+c+"]":c}).join(s?".":""):i}function rv(r){return O.isArray(r)&&!r.some($u)}const ov=O.toFlatObject(O,{},null,function(i){return/^is[A-Z]/.test(i)});function ws(r,i,s){if(!O.isObject(r))throw new TypeError("target must be an object");i=i||new FormData,s=O.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,N){return!O.isUndefined(N[C])});const l=s.metaTokens,c=s.visitor||S,f=s.dots,p=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 v(R){if(R===null)return"";if(O.isDate(R))return R.toISOString();if(!x&&O.isBlob(R))throw new le("Blob is not supported. Use a Buffer instead.");return O.isArrayBuffer(R)||O.isTypedArray(R)?x&&typeof Blob=="function"?new Blob([R]):Buffer.from(R):R}function S(R,C,N){let H=R;if(R&&!N&&typeof R=="object"){if(O.endsWith(C,"{}"))C=l?C:C.slice(0,-2),R=JSON.stringify(R);else if(O.isArray(R)&&rv(R)||(O.isFileList(R)||O.endsWith(C,"[]"))&&(H=O.toArray(R)))return C=Fp(C),H.forEach(function(V,Q){!(O.isUndefined(V)||V===null)&&i.append(p===!0?Pd([C],Q,f):p===null?C:C+"[]",v(V))}),!1}return $u(R)?!0:(i.append(Pd(N,C,f),v(R)),!1)}const A=[],T=Object.assign(ov,{defaultVisitor:S,convertValue:v,isVisitable:$u});function I(R,C){if(!O.isUndefined(R)){if(A.indexOf(R)!==-1)throw Error("Circular reference detected in "+C.join("."));A.push(R),O.forEach(R,function(H,U){(!(O.isUndefined(H)||H===null)&&c.call(i,H,O.isString(U)?U.trim():U,C,T))===!0&&I(H,C?C.concat(U):[U])}),A.pop()}}if(!O.isObject(r))throw new TypeError("data must be an object");return I(r),i}function _d(r){const i={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(l){return i[l]})}function ra(r,i){this._pairs=[],r&&ws(r,this,i)}const Bp=ra.prototype;Bp.append=function(i,s){this._pairs.push([i,s])};Bp.toString=function(i){const s=i?function(l){return i.call(this,l,_d)}:_d;return this._pairs.map(function(c){return s(c[0])+"="+s(c[1])},"").join("&")};function iv(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function $p(r,i,s){if(!i)return r;const l=s&&s.encode||iv;O.isFunction(s)&&(s={serialize:s});const c=s&&s.serialize;let f;if(c?f=c(i,s):f=O.isURLSearchParams(i)?i.toString():new ra(i,s).toString(l),f){const p=r.indexOf("#");p!==-1&&(r=r.slice(0,p)),r+=(r.indexOf("?")===-1?"?":"&")+f}return r}class Td{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 Hp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},sv=typeof URLSearchParams<"u"?URLSearchParams:ra,lv=typeof FormData<"u"?FormData:null,uv=typeof Blob<"u"?Blob:null,av={isBrowser:!0,classes:{URLSearchParams:sv,FormData:lv,Blob:uv},protocols:["http","https","file","blob","url","data"]},oa=typeof window<"u"&&typeof document<"u",Hu=typeof navigator=="object"&&navigator||void 0,cv=oa&&(!Hu||["ReactNative","NativeScript","NS"].indexOf(Hu.product)<0),fv=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",dv=oa&&window.location.href||"http://localhost",pv=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:oa,hasStandardBrowserEnv:cv,hasStandardBrowserWebWorkerEnv:fv,navigator:Hu,origin:dv},Symbol.toStringTag,{value:"Module"})),Ke={...pv,...av};function hv(r,i){return ws(r,new Ke.classes.URLSearchParams,Object.assign({visitor:function(s,l,c,f){return Ke.isNode&&O.isBuffer(s)?(this.append(l,s.toString("base64")),!1):f.defaultVisitor.apply(this,arguments)}},i))}function mv(r){return O.matchAll(/\w+|\[(\w*)]/g,r).map(i=>i[0]==="[]"?"":i[1]||i[0])}function gv(r){const i={},s=Object.keys(r);let l;const c=s.length;let f;for(l=0;l=s.length;return p=!p&&O.isArray(c)?c.length:p,x?(O.hasOwnProp(c,p)?c[p]=[c[p],l]:c[p]=l,!g):((!c[p]||!O.isObject(c[p]))&&(c[p]=[]),i(s,l,c[p],f)&&O.isArray(c[p])&&(c[p]=gv(c[p])),!g)}if(O.isFormData(r)&&O.isFunction(r.entries)){const s={};return O.forEachEntry(r,(l,c)=>{i(mv(l),c,s,0)}),s}return null}function yv(r,i,s){if(O.isString(r))try{return(i||JSON.parse)(r),O.trim(r)}catch(l){if(l.name!=="SyntaxError")throw l}return(0,JSON.stringify)(r)}const To={transitional:Hp,adapter:["xhr","http","fetch"],transformRequest:[function(i,s){const l=s.getContentType()||"",c=l.indexOf("application/json")>-1,f=O.isObject(i);if(f&&O.isHTMLForm(i)&&(i=new FormData(i)),O.isFormData(i))return c?JSON.stringify(bp(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 g;if(f){if(l.indexOf("application/x-www-form-urlencoded")>-1)return hv(i,this.formSerializer).toString();if((g=O.isFileList(i))||l.indexOf("multipart/form-data")>-1){const x=this.env&&this.env.FormData;return ws(g?{"files[]":i}:i,x&&new x,this.formSerializer)}}return f||c?(s.setContentType("application/json",!1),yv(i)):i}],transformResponse:[function(i){const s=this.transitional||To.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 p=!(s&&s.silentJSONParsing)&&c;try{return JSON.parse(i)}catch(g){if(p)throw g.name==="SyntaxError"?le.from(g,le.ERR_BAD_RESPONSE,this,null,this.response):g}}return i}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ke.classes.FormData,Blob:Ke.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"],r=>{To.headers[r]={}});const vv=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"]),wv=r=>{const i={};let s,l,c;return r&&r.split(` +`).forEach(function(p){c=p.indexOf(":"),s=p.substring(0,c).trim().toLowerCase(),l=p.substring(c+1).trim(),!(!s||i[s]&&vv[s])&&(s==="set-cookie"?i[s]?i[s].push(l):i[s]=[l]:i[s]=i[s]?i[s]+", "+l:l)}),i},Id=Symbol("internals");function vo(r){return r&&String(r).trim().toLowerCase()}function es(r){return r===!1||r==null?r:O.isArray(r)?r.map(es):String(r)}function xv(r){const i=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let l;for(;l=s.exec(r);)i[l[1]]=l[2];return i}const Sv=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function ju(r,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 Ev(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(i,s,l)=>s.toUpperCase()+l)}function Cv(r,i){const s=O.toCamelCase(" "+i);["get","set","has"].forEach(l=>{Object.defineProperty(r,l+s,{value:function(c,f,p){return this[l].call(this,i,c,f,p)},configurable:!0})})}class ut{constructor(i){i&&this.set(i)}set(i,s,l){const c=this;function f(g,x,v){const S=vo(x);if(!S)throw new Error("header name must be a non-empty string");const A=O.findKey(c,S);(!A||c[A]===void 0||v===!0||v===void 0&&c[A]!==!1)&&(c[A||x]=es(g))}const p=(g,x)=>O.forEach(g,(v,S)=>f(v,S,x));if(O.isPlainObject(i)||i instanceof this.constructor)p(i,s);else if(O.isString(i)&&(i=i.trim())&&!Sv(i))p(wv(i),s);else if(O.isHeaders(i))for(const[g,x]of i.entries())f(x,g,l);else i!=null&&f(s,i,l);return this}get(i,s){if(i=vo(i),i){const l=O.findKey(this,i);if(l){const c=this[l];if(!s)return c;if(s===!0)return xv(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=vo(i),i){const l=O.findKey(this,i);return!!(l&&this[l]!==void 0&&(!s||ju(this,this[l],l,s)))}return!1}delete(i,s){const l=this;let c=!1;function f(p){if(p=vo(p),p){const g=O.findKey(l,p);g&&(!s||ju(l,l[g],g,s))&&(delete l[g],c=!0)}}return O.isArray(i)?i.forEach(f):f(i),c}clear(i){const s=Object.keys(this);let l=s.length,c=!1;for(;l--;){const f=s[l];(!i||ju(this,this[f],f,i,!0))&&(delete this[f],c=!0)}return c}normalize(i){const s=this,l={};return O.forEach(this,(c,f)=>{const p=O.findKey(l,f);if(p){s[p]=es(c),delete s[f];return}const g=i?Ev(f):String(f).trim();g!==f&&delete s[f],s[g]=es(c),l[g]=!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[Id]=this[Id]={accessors:{}}).accessors,c=this.prototype;function f(p){const g=vo(p);l[g]||(Cv(c,p),l[g]=!0)}return O.isArray(i)?i.forEach(f):f(i),this}}ut.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);O.reduceDescriptors(ut.prototype,({value:r},i)=>{let s=i[0].toUpperCase()+i.slice(1);return{get:()=>r,set(l){this[s]=l}}});O.freezeMethods(ut);function Au(r,i){const s=this||To,l=i||s,c=ut.from(l.headers);let f=l.data;return O.forEach(r,function(g){f=g.call(s,f,c.normalize(),i?i.status:void 0)}),c.normalize(),f}function Vp(r){return!!(r&&r.__CANCEL__)}function Pr(r,i,s){le.call(this,r??"canceled",le.ERR_CANCELED,i,s),this.name="CanceledError"}O.inherits(Pr,le,{__CANCEL__:!0});function Wp(r,i,s){const l=s.config.validateStatus;!s.status||!l||l(s.status)?r(s):i(new le("Request failed with status code "+s.status,[le.ERR_BAD_REQUEST,le.ERR_BAD_RESPONSE][Math.floor(s.status/100)-4],s.config,s.request,s))}function kv(r){const i=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return i&&i[1]||""}function jv(r,i){r=r||10;const s=new Array(r),l=new Array(r);let c=0,f=0,p;return i=i!==void 0?i:1e3,function(x){const v=Date.now(),S=l[f];p||(p=v),s[c]=x,l[c]=v;let A=f,T=0;for(;A!==c;)T+=s[A++],A=A%r;if(c=(c+1)%r,c===f&&(f=(f+1)%r),v-p{s=S,c=null,f&&(clearTimeout(f),f=null),r.apply(null,v)};return[(...v)=>{const S=Date.now(),A=S-s;A>=l?p(v,S):(c=v,f||(f=setTimeout(()=>{f=null,p(c)},l-A)))},()=>c&&p(c)]}const ls=(r,i,s=3)=>{let l=0;const c=jv(50,250);return Av(f=>{const p=f.loaded,g=f.lengthComputable?f.total:void 0,x=p-l,v=c(x),S=p<=g;l=p;const A={loaded:p,total:g,progress:g?p/g:void 0,bytes:x,rate:v||void 0,estimated:v&&g&&S?(g-p)/v:void 0,event:f,lengthComputable:g!=null,[i?"download":"upload"]:!0};r(A)},s)},Nd=(r,i)=>{const s=r!=null;return[l=>i[0]({lengthComputable:s,total:r,loaded:l}),i[1]]},Od=r=>(...i)=>O.asap(()=>r(...i)),Rv=Ke.hasStandardBrowserEnv?((r,i)=>s=>(s=new URL(s,Ke.origin),r.protocol===s.protocol&&r.host===s.host&&(i||r.port===s.port)))(new URL(Ke.origin),Ke.navigator&&/(msie|trident)/i.test(Ke.navigator.userAgent)):()=>!0,Pv=Ke.hasStandardBrowserEnv?{write(r,i,s,l,c,f){const p=[r+"="+encodeURIComponent(i)];O.isNumber(s)&&p.push("expires="+new Date(s).toGMTString()),O.isString(l)&&p.push("path="+l),O.isString(c)&&p.push("domain="+c),f===!0&&p.push("secure"),document.cookie=p.join("; ")},read(r){const i=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return i?decodeURIComponent(i[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _v(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function Tv(r,i){return i?r.replace(/\/?\/$/,"")+"/"+i.replace(/^\/+/,""):r}function Yp(r,i){return r&&!_v(i)?Tv(r,i):i}const Ld=r=>r instanceof ut?{...r}:r;function Wn(r,i){i=i||{};const s={};function l(v,S,A,T){return O.isPlainObject(v)&&O.isPlainObject(S)?O.merge.call({caseless:T},v,S):O.isPlainObject(S)?O.merge({},S):O.isArray(S)?S.slice():S}function c(v,S,A,T){if(O.isUndefined(S)){if(!O.isUndefined(v))return l(void 0,v,A,T)}else return l(v,S,A,T)}function f(v,S){if(!O.isUndefined(S))return l(void 0,S)}function p(v,S){if(O.isUndefined(S)){if(!O.isUndefined(v))return l(void 0,v)}else return l(void 0,S)}function g(v,S,A){if(A in i)return l(v,S);if(A in r)return l(void 0,v)}const x={url:f,method:f,data:f,baseURL:p,transformRequest:p,transformResponse:p,paramsSerializer:p,timeout:p,timeoutMessage:p,withCredentials:p,withXSRFToken:p,adapter:p,responseType:p,xsrfCookieName:p,xsrfHeaderName:p,onUploadProgress:p,onDownloadProgress:p,decompress:p,maxContentLength:p,maxBodyLength:p,beforeRedirect:p,transport:p,httpAgent:p,httpsAgent:p,cancelToken:p,socketPath:p,responseEncoding:p,validateStatus:g,headers:(v,S,A)=>c(Ld(v),Ld(S),A,!0)};return O.forEach(Object.keys(Object.assign({},r,i)),function(S){const A=x[S]||c,T=A(r[S],i[S],S);O.isUndefined(T)&&A!==g||(s[S]=T)}),s}const qp=r=>{const i=Wn({},r);let{data:s,withXSRFToken:l,xsrfHeaderName:c,xsrfCookieName:f,headers:p,auth:g}=i;i.headers=p=ut.from(p),i.url=$p(Yp(i.baseURL,i.url),r.params,r.paramsSerializer),g&&p.set("Authorization","Basic "+btoa((g.username||"")+":"+(g.password?unescape(encodeURIComponent(g.password)):"")));let x;if(O.isFormData(s)){if(Ke.hasStandardBrowserEnv||Ke.hasStandardBrowserWebWorkerEnv)p.setContentType(void 0);else if((x=p.getContentType())!==!1){const[v,...S]=x?x.split(";").map(A=>A.trim()).filter(Boolean):[];p.setContentType([v||"multipart/form-data",...S].join("; "))}}if(Ke.hasStandardBrowserEnv&&(l&&O.isFunction(l)&&(l=l(i)),l||l!==!1&&Rv(i.url))){const v=c&&f&&Pv.read(f);v&&p.set(c,v)}return i},Iv=typeof XMLHttpRequest<"u",Nv=Iv&&function(r){return new Promise(function(s,l){const c=qp(r);let f=c.data;const p=ut.from(c.headers).normalize();let{responseType:g,onUploadProgress:x,onDownloadProgress:v}=c,S,A,T,I,R;function C(){I&&I(),R&&R(),c.cancelToken&&c.cancelToken.unsubscribe(S),c.signal&&c.signal.removeEventListener("abort",S)}let N=new XMLHttpRequest;N.open(c.method.toUpperCase(),c.url,!0),N.timeout=c.timeout;function H(){if(!N)return;const V=ut.from("getAllResponseHeaders"in N&&N.getAllResponseHeaders()),$={data:!g||g==="text"||g==="json"?N.responseText:N.response,status:N.status,statusText:N.statusText,headers:V,config:r,request:N};Wp(function(b){s(b),C()},function(b){l(b),C()},$),N=null}"onloadend"in N?N.onloadend=H:N.onreadystatechange=function(){!N||N.readyState!==4||N.status===0&&!(N.responseURL&&N.responseURL.indexOf("file:")===0)||setTimeout(H)},N.onabort=function(){N&&(l(new le("Request aborted",le.ECONNABORTED,r,N)),N=null)},N.onerror=function(){l(new le("Network Error",le.ERR_NETWORK,r,N)),N=null},N.ontimeout=function(){let Q=c.timeout?"timeout of "+c.timeout+"ms exceeded":"timeout exceeded";const $=c.transitional||Hp;c.timeoutErrorMessage&&(Q=c.timeoutErrorMessage),l(new le(Q,$.clarifyTimeoutError?le.ETIMEDOUT:le.ECONNABORTED,r,N)),N=null},f===void 0&&p.setContentType(null),"setRequestHeader"in N&&O.forEach(p.toJSON(),function(Q,$){N.setRequestHeader($,Q)}),O.isUndefined(c.withCredentials)||(N.withCredentials=!!c.withCredentials),g&&g!=="json"&&(N.responseType=c.responseType),v&&([T,R]=ls(v,!0),N.addEventListener("progress",T)),x&&N.upload&&([A,I]=ls(x),N.upload.addEventListener("progress",A),N.upload.addEventListener("loadend",I)),(c.cancelToken||c.signal)&&(S=V=>{N&&(l(!V||V.type?new Pr(null,r,N):V),N.abort(),N=null)},c.cancelToken&&c.cancelToken.subscribe(S),c.signal&&(c.signal.aborted?S():c.signal.addEventListener("abort",S)));const U=kv(c.url);if(U&&Ke.protocols.indexOf(U)===-1){l(new le("Unsupported protocol "+U+":",le.ERR_BAD_REQUEST,r));return}N.send(f||null)})},Ov=(r,i)=>{const{length:s}=r=r?r.filter(Boolean):[];if(i||s){let l=new AbortController,c;const f=function(v){if(!c){c=!0,g();const S=v instanceof Error?v:this.reason;l.abort(S instanceof le?S:new Pr(S instanceof Error?S.message:S))}};let p=i&&setTimeout(()=>{p=null,f(new le(`timeout ${i} of ms exceeded`,le.ETIMEDOUT))},i);const g=()=>{r&&(p&&clearTimeout(p),p=null,r.forEach(v=>{v.unsubscribe?v.unsubscribe(f):v.removeEventListener("abort",f)}),r=null)};r.forEach(v=>v.addEventListener("abort",f));const{signal:x}=l;return x.unsubscribe=()=>O.asap(g),x}},Lv=function*(r,i){let s=r.byteLength;if(s{const c=Dv(r,i);let f=0,p,g=x=>{p||(p=!0,l&&l(x))};return new ReadableStream({async pull(x){try{const{done:v,value:S}=await c.next();if(v){g(),x.close();return}let A=S.byteLength;if(s){let T=f+=A;s(T)}x.enqueue(new Uint8Array(S))}catch(v){throw g(v),v}},cancel(x){return g(x),c.return()}},{highWaterMark:2})},xs=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Qp=xs&&typeof ReadableStream=="function",zv=xs&&(typeof TextEncoder=="function"?(r=>i=>r.encode(i))(new TextEncoder):async r=>new Uint8Array(await new Response(r).arrayBuffer())),Gp=(r,...i)=>{try{return!!r(...i)}catch{return!1}},Uv=Qp&&Gp(()=>{let r=!1;const i=new Request(Ke.origin,{body:new ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type");return r&&!i}),Md=64*1024,bu=Qp&&Gp(()=>O.isReadableStream(new Response("").body)),us={stream:bu&&(r=>r.body)};xs&&(r=>{["text","arrayBuffer","blob","formData","stream"].forEach(i=>{!us[i]&&(us[i]=O.isFunction(r[i])?s=>s[i]():(s,l)=>{throw new le(`Response type '${i}' is not supported`,le.ERR_NOT_SUPPORT,l)})})})(new Response);const Fv=async r=>{if(r==null)return 0;if(O.isBlob(r))return r.size;if(O.isSpecCompliantForm(r))return(await new Request(Ke.origin,{method:"POST",body:r}).arrayBuffer()).byteLength;if(O.isArrayBufferView(r)||O.isArrayBuffer(r))return r.byteLength;if(O.isURLSearchParams(r)&&(r=r+""),O.isString(r))return(await zv(r)).byteLength},Bv=async(r,i)=>{const s=O.toFiniteNumber(r.getContentLength());return s??Fv(i)},$v=xs&&(async r=>{let{url:i,method:s,data:l,signal:c,cancelToken:f,timeout:p,onDownloadProgress:g,onUploadProgress:x,responseType:v,headers:S,withCredentials:A="same-origin",fetchOptions:T}=qp(r);v=v?(v+"").toLowerCase():"text";let I=Ov([c,f&&f.toAbortSignal()],p),R;const C=I&&I.unsubscribe&&(()=>{I.unsubscribe()});let N;try{if(x&&Uv&&s!=="get"&&s!=="head"&&(N=await Bv(S,l))!==0){let $=new Request(i,{method:"POST",body:l,duplex:"half"}),L;if(O.isFormData(l)&&(L=$.headers.get("content-type"))&&S.setContentType(L),$.body){const[b,re]=Nd(N,ls(Od(x)));l=Dd($.body,Md,b,re)}}O.isString(A)||(A=A?"include":"omit");const H="credentials"in Request.prototype;R=new Request(i,{...T,signal:I,method:s.toUpperCase(),headers:S.normalize().toJSON(),body:l,duplex:"half",credentials:H?A:void 0});let U=await fetch(R);const V=bu&&(v==="stream"||v==="response");if(bu&&(g||V&&C)){const $={};["status","statusText","headers"].forEach(ye=>{$[ye]=U[ye]});const L=O.toFiniteNumber(U.headers.get("content-length")),[b,re]=g&&Nd(L,ls(Od(g),!0))||[];U=new Response(Dd(U.body,Md,b,()=>{re&&re(),C&&C()}),$)}v=v||"text";let Q=await us[O.findKey(us,v)||"text"](U,r);return!V&&C&&C(),await new Promise(($,L)=>{Wp($,L,{data:Q,headers:ut.from(U.headers),status:U.status,statusText:U.statusText,config:r,request:R})})}catch(H){throw C&&C(),H&&H.name==="TypeError"&&/fetch/i.test(H.message)?Object.assign(new le("Network Error",le.ERR_NETWORK,r,R),{cause:H.cause||H}):le.from(H,H&&H.code,r,R)}}),Vu={http:nv,xhr:Nv,fetch:$v};O.forEach(Vu,(r,i)=>{if(r){try{Object.defineProperty(r,"name",{value:i})}catch{}Object.defineProperty(r,"adapterName",{value:i})}});const zd=r=>`- ${r}`,Hv=r=>O.isFunction(r)||r===null||r===!1,Kp={getAdapter:r=>{r=O.isArray(r)?r:[r];const{length:i}=r;let s,l;const c={};for(let f=0;f`adapter ${g} `+(x===!1?"is not supported by the environment":"is not available in the build"));let p=i?f.length>1?`since : +`+f.map(zd).join(` +`):" "+zd(f[0]):"as no adapter specified";throw new le("There is no suitable adapter to dispatch the request "+p,"ERR_NOT_SUPPORT")}return l},adapters:Vu};function Ru(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Pr(null,r)}function Ud(r){return Ru(r),r.headers=ut.from(r.headers),r.data=Au.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Kp.getAdapter(r.adapter||To.adapter)(r).then(function(l){return Ru(r),l.data=Au.call(r,r.transformResponse,l),l.headers=ut.from(l.headers),l},function(l){return Vp(l)||(Ru(r),l&&l.response&&(l.response.data=Au.call(r,r.transformResponse,l.response),l.response.headers=ut.from(l.response.headers))),Promise.reject(l)})}const Xp="1.7.9",Ss={};["object","boolean","number","function","string","symbol"].forEach((r,i)=>{Ss[r]=function(l){return typeof l===r||"a"+(i<1?"n ":" ")+r}});const Fd={};Ss.transitional=function(i,s,l){function c(f,p){return"[Axios v"+Xp+"] Transitional option '"+f+"'"+p+(l?". "+l:"")}return(f,p,g)=>{if(i===!1)throw new le(c(p," has been removed"+(s?" in "+s:"")),le.ERR_DEPRECATED);return s&&!Fd[p]&&(Fd[p]=!0,console.warn(c(p," has been deprecated since v"+s+" and will be removed in the near future"))),i?i(f,p,g):!0}};Ss.spelling=function(i){return(s,l)=>(console.warn(`${l} is likely a misspelling of ${i}`),!0)};function bv(r,i,s){if(typeof r!="object")throw new le("options must be an object",le.ERR_BAD_OPTION_VALUE);const l=Object.keys(r);let c=l.length;for(;c-- >0;){const f=l[c],p=i[f];if(p){const g=r[f],x=g===void 0||p(g,f,r);if(x!==!0)throw new le("option "+f+" must be "+x,le.ERR_BAD_OPTION_VALUE);continue}if(s!==!0)throw new le("Unknown option "+f,le.ERR_BAD_OPTION)}}const ts={assertOptions:bv,validators:Ss},Vt=ts.validators;class Hn{constructor(i){this.defaults=i,this.interceptors={request:new Td,response:new Td}}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 f=c.stack?c.stack.replace(/^.+\n/,""):"";try{l.stack?f&&!String(l.stack).endsWith(f.replace(/^.+\n.+\n/,""))&&(l.stack+=` +`+f):l.stack=f}catch{}}throw l}}_request(i,s){typeof i=="string"?(s=s||{},s.url=i):s=i||{},s=Wn(this.defaults,s);const{transitional:l,paramsSerializer:c,headers:f}=s;l!==void 0&&ts.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}:ts.assertOptions(c,{encode:Vt.function,serialize:Vt.function},!0)),ts.assertOptions(s,{baseUrl:Vt.spelling("baseURL"),withXsrfToken:Vt.spelling("withXSRFToken")},!0),s.method=(s.method||this.defaults.method||"get").toLowerCase();let p=f&&O.merge(f.common,f[s.method]);f&&O.forEach(["delete","get","head","post","put","patch","common"],R=>{delete f[R]}),s.headers=ut.concat(p,f);const g=[];let x=!0;this.interceptors.request.forEach(function(C){typeof C.runWhen=="function"&&C.runWhen(s)===!1||(x=x&&C.synchronous,g.unshift(C.fulfilled,C.rejected))});const v=[];this.interceptors.response.forEach(function(C){v.push(C.fulfilled,C.rejected)});let S,A=0,T;if(!x){const R=[Ud.bind(this),void 0];for(R.unshift.apply(R,g),R.push.apply(R,v),T=R.length,S=Promise.resolve(s);A{if(!l._listeners)return;let f=l._listeners.length;for(;f-- >0;)l._listeners[f](c);l._listeners=null}),this.promise.then=c=>{let f;const p=new Promise(g=>{l.subscribe(g),f=g}).then(c);return p.cancel=function(){l.unsubscribe(f)},p},i(function(f,p,g){l.reason||(l.reason=new Pr(f,p,g),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 ia(function(c){i=c}),cancel:i}}}function Vv(r){return function(s){return r.apply(null,s)}}function Wv(r){return O.isObject(r)&&r.isAxiosError===!0}const Wu={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(Wu).forEach(([r,i])=>{Wu[i]=r});function Jp(r){const i=new Hn(r),s=_p(Hn.prototype.request,i);return O.extend(s,Hn.prototype,i,{allOwnKeys:!0}),O.extend(s,i,null,{allOwnKeys:!0}),s.create=function(c){return Jp(Wn(r,c))},s}const De=Jp(To);De.Axios=Hn;De.CanceledError=Pr;De.CancelToken=ia;De.isCancel=Vp;De.VERSION=Xp;De.toFormData=ws;De.AxiosError=le;De.Cancel=De.CanceledError;De.all=function(i){return Promise.all(i)};De.spread=Vv;De.isAxiosError=Wv;De.mergeConfig=Wn;De.AxiosHeaders=ut;De.formToJSON=r=>bp(O.isHTMLForm(r)?new FormData(r):r);De.getAdapter=Kp.getAdapter;De.HttpStatusCode=Wu;De.default=De;const Yv={apiBaseUrl:"/api"};class qv{constructor(){ed(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 as=new qv,Je=De.create({baseURL:Yv.apiBaseUrl,headers:{"Content-Type":"application/json"}});Je.interceptors.response.use(r=>r,r=>{var s,l,c;const i=(s=r.response)==null?void 0:s.data;if(i){const f=(c=(l=r.response)==null?void 0:l.headers)==null?void 0:c["discodeit-request-id"];f&&(i.requestId=f),r.response.data=i}return as.emit("api-error",r),r.response&&r.response.status===401&&as.emit("auth-error"),Promise.reject(r)});const Qv=()=>Je.defaults.baseURL,Gv=async(r,i)=>{const s={username:r,password:i};return(await Je.post("/auth/login",s)).data},Kv=async r=>(await Je.post("/users",r,{headers:{"Content-Type":"multipart/form-data"}})).data,Bd=r=>{let i;const s=new Set,l=(v,S)=>{const A=typeof v=="function"?v(i):v;if(!Object.is(A,i)){const T=i;i=S??(typeof A!="object"||A===null)?A:Object.assign({},i,A),s.forEach(I=>I(i,T))}},c=()=>i,g={setState:l,getState:c,getInitialState:()=>x,subscribe:v=>(s.add(v),()=>s.delete(v))},x=i=r(l,c,g);return g},Xv=r=>r?Bd(r):Bd,Jv=r=>r;function Zv(r,i=Jv){const s=gt.useSyncExternalStore(r.subscribe,()=>i(r.getState()),()=>i(r.getInitialState()));return gt.useDebugValue(s),s}const $d=r=>{const i=Xv(r),s=l=>Zv(i,l);return Object.assign(s,i),s},_r=r=>r?$d(r):$d,e0=async(r,i)=>(await Je.patch(`/users/${r}`,i,{headers:{"Content-Type":"multipart/form-data"}})).data,t0=async()=>(await Je.get("/users")).data,n0=async r=>(await Je.patch(`/users/${r}/userStatus`,{newLastActiveAt:new Date().toISOString()})).data,nn=_r(r=>({users:[],fetchUsers:async()=>{try{const i=await t0();r({users:i})}catch(i){console.error("사용자 목록 조회 실패:",i)}},updateUserStatus:async i=>{try{await n0(i)}catch(s){console.error("사용자 상태 업데이트 실패:",s)}}}));function Zp(r,i){let s;try{s=r()}catch{return}return{getItem:c=>{var f;const p=x=>x===null?null:JSON.parse(x,void 0),g=(f=s.getItem(c))!=null?f:null;return g instanceof Promise?g.then(p):p(g)},setItem:(c,f)=>s.setItem(c,JSON.stringify(f,void 0)),removeItem:c=>s.removeItem(c)}}const Yu=r=>i=>{try{const s=r(i);return s instanceof Promise?s:{then(l){return Yu(l)(s)},catch(l){return this}}}catch(s){return{then(l){return this},catch(l){return Yu(l)(s)}}}},r0=(r,i)=>(s,l,c)=>{let f={storage:Zp(()=>localStorage),partialize:C=>C,version:0,merge:(C,N)=>({...N,...C}),...i},p=!1;const g=new Set,x=new Set;let v=f.storage;if(!v)return r((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${f.name}', the given storage is currently unavailable.`),s(...C)},l,c);const S=()=>{const C=f.partialize({...l()});return v.setItem(f.name,{state:C,version:f.version})},A=c.setState;c.setState=(C,N)=>{A(C,N),S()};const T=r((...C)=>{s(...C),S()},l,c);c.getInitialState=()=>T;let I;const R=()=>{var C,N;if(!v)return;p=!1,g.forEach(U=>{var V;return U((V=l())!=null?V:T)});const H=((N=f.onRehydrateStorage)==null?void 0:N.call(f,(C=l())!=null?C:T))||void 0;return Yu(v.getItem.bind(v))(f.name).then(U=>{if(U)if(typeof U.version=="number"&&U.version!==f.version){if(f.migrate){const V=f.migrate(U.state,U.version);return V instanceof Promise?V.then(Q=>[!0,Q]):[!0,V]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,U.state];return[!1,void 0]}).then(U=>{var V;const[Q,$]=U;if(I=f.merge($,(V=l())!=null?V:T),s(I,!0),Q)return S()}).then(()=>{H==null||H(I,void 0),I=l(),p=!0,x.forEach(U=>U(I))}).catch(U=>{H==null||H(void 0,U)})};return c.persist={setOptions:C=>{f={...f,...C},C.storage&&(v=C.storage)},clearStorage:()=>{v==null||v.removeItem(f.name)},getOptions:()=>f,rehydrate:()=>R(),hasHydrated:()=>p,onHydrate:C=>(g.add(C),()=>{g.delete(C)}),onFinishHydration:C=>(x.add(C),()=>{x.delete(C)})},f.skipHydration||R(),I||T},o0=r0,vt=_r()(o0(r=>({currentUserId:null,setCurrentUser:i=>r({currentUserId:i.id}),logout:()=>{const i=vt.getState().currentUserId;i&&nn.getState().updateUserStatus(i),r({currentUserId:null})},updateUser:async(i,s)=>{try{const l=await e0(i,s);return await nn.getState().fetchUsers(),l}catch(l){throw console.error("사용자 정보 수정 실패:",l),l}}}),{name:"user-storage",storage:Zp(()=>sessionStorage)})),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"}}},eh=_.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; +`,th=_.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; + } +`,ko=_.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; + } +`,nh=_.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}; + } +`,rh=_.div` + color: ${ee.colors.status.error}; + font-size: 14px; + text-align: center; +`,i0=_.p` + text-align: center; + margin-top: 16px; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 14px; +`,s0=_.span` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,Vi=_.div` + margin-bottom: 20px; +`,Wi=_.label` + display: block; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,Pu=_.span` + color: ${({theme:r})=>r.colors.status.error}; +`,l0=_.div` + display: flex; + flex-direction: column; + align-items: center; + margin: 10px 0; +`,u0=_.img` + width: 80px; + height: 80px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,a0=_.input` + display: none; +`,c0=_.label` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,f0=_.span` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,d0=_(f0)` + display: block; + text-align: center; + margin-top: 16px; +`,zt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAACXBIWXMAACE4AAAhOAFFljFgAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAw2SURBVHgB7d3PT1XpHcfxBy5g6hipSMolGViACThxJDbVRZ2FXejKlf9h/4GmC1fTRdkwC8fE0JgyJuICFkCjEA04GeZe6P0cPC0698I95zzPc57v5f1K6DSto3A8n/v9nufXGfrr338+dgBMGnYAzCLAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwbcTDvyuWh//33w1/1dexwMRBgYxTW5vVh9/vxYTcxPpR9jY0OffZrdt8fu82ttlvfbLv9j4R5kBHgxCmcE1eH3NfTDTc7PfxZte3lJNgjbmlxxK3+1HKrr1oOg4kAJ0pVdnG+4ZqTw7+psEUoxF91Qv/Di1+db/q+ZpvD7g+T6gb04XLyv6mF3//osuqvTmDn3RGdQCAEOCG6+W/ONdzNTnCrhPZLN2Yb2T99hVhdwOLcSOf37f7hknUN4yedgLoGeb3Rdv/qdAIE2S8CnIDzAuGDQrzXeTZee1OtndaHy9LCSOHvU3++vv693nLPX9LS+0KAa6QQLC2o4sb5a1A7rYGtMqPU+l7v3hpx85+qeVnfdH7W2c7z/Pcrh1RjD5gHromq2JOHY9HCK2Ojzk1dL1fhH90fqxzenDoO/X79DMjhbAQ4Mg1OPXl4KauGodrls6j6FaXKq+dZn/IQ13ENBgkBjiRvQR99V2/lmZos9lc+PxOuxdd1uL3gp6pfVDwDR6Ab9cG9Me9VLAZ1CiHpmXhz6yibakJxVODAZpoN9/iBzfCq+sboFkJ/SAwyrlxAujE1WJWSIiO/sYKlxSpTnbEBqnBxVOBA9LybWnjloM8An6ysitc1NCe5FcvgqgVw/85o1OmhItY32n39uqnJuC3/FAEuhavmmcLra77UN7XP2322qRNX494aqvgojqvmUcrhFa1+6tdXkae6tMiEhR3FEWBPNOCTcni1rZCli4OHAHuQ4mjzaewJHlxMI1Wked5Uw7v99ijbwqd/FnVQQ7WmQyiOAFegZ7a736ZzCU820h+7nbfHbnO7XSq4p3+vmHbfMwdcBgGuoO4dNQrZxtaR+08nqNueT73Y2D7qTIW5aLRXGcUR4JL03FtHeBXa9Y2jyhX2PHudiqg/K9ZuoY3t/uan8TkCXIKCG/u5V2Fae9N2a+vtKO2tjqfVnxfj5zw5O4sWugwCXIJa51hiB/e0tfVWdkZX6CrMCHl5BLigWDt0RCc6rrxo1XZQu6rw6qt2tq47FD0G9Lu8E79FgAvIWucIO3QU2B9ftpK4sVWFZ5rDQTYbqHUOcdztRcJCjgLUToauvrqpny4fJlWVlp/5P4BOH1IcbFcdAe6Tght6h5FeiaLwpnZTq5VW2HzN1eYfUoS3OgLcp9sL4cOrkKT6YrI8dFUHnDQYR3j94Rm4D9kLxQLuV009vKdpXbXae00vFdm8UWVZJ3ojwH3QcS+hnn1VifSMaemVoPqeVzqDT6rG2oivQS5dH33l70ZS262w7n04yhae8MrTMAhwH0KNPFsfyNH3vd+pxkwD1Ydn4HOodQ5VfTXHyrMgqiDA55ibCbNJX1VLc6xAFQT4HCEGr9Q6s3wQPhDgM4RqnzWVQusMHwjwGTS66puCS/WFLwT4DCHOKia88IkA96BjTkOcVbzDQgZ4RIB7CBFejTzz7AufCHAPWn3lGwse4BsB7uGa5wqcLS3k7XvwjAD3cOWy84pnX4RAgHvw/QzMLhyEQIC7CLF4Y4+DyxEAAe4iRIB3PzD6DP8IcBejnncPagCL/bAIgQB34fsc5P2PtM8IgwBHcMjJqQiEAHfBm+JhBQGO4IDlkwiEAHdx2PIbuFhv+MPFQ4C7ODx0Xo2OOiAIAhwBz9QIhQB34XvOlhYaoRDgLg5+dl7pcACqMEIgwF2EWDV1bZwAwz8C3IVOzfAd4omrXGr4x13Vg++jb6YmudTwj7uqh733fgOsM6YZzIJvBLiH3Q/+NyDMB3pNCy4u3k7Yw+57/wNZM9PDbu2NGwjqJiauDrmvpxufXiv6+f+v63fw8SjrZDgLLBwC3INO0NBAls+2V220jurZNXw6h8K6ODfibsye/UjQnNR/nnQcGk/IX/DNsbp+EeAetAVQVaQ56fe5dXGu4X54YTPASwsj7uZ8o/CHmkJ/Y7aRfb3eaBNkj3gGPsNOgNZPN7G1RR36fh8/uJS96LxqR6Kf/9H9MRa2eEKAz7C5FaZS3l6w0/goaArchMeFKPkHwrVxbr+quIJn0LNqiFZPVSjEmx98U7UNVS016PWXe6NU4ooI8DnWN8O8DuX+H0eTnxdeWgjb7uv3/vMd9lpWQYDPEep9Rrp5by+kOy+s7+/mfPhWXyPzFrqRVHHlzpFPgYTwTScg87NphjhmZdTgGMohwH1YexPupdx3b40mN5ij6tuMuHabKlweV60PGo0OdTB7ioM5WjEWW5PNHqVw1fq09ibcu33zqZpUQjzTjN/Ws1urHK5an9bWW0Ffj5JSiOv4HiaYEy6Fq9YnLa1cfRWuCku+wOHmXL2DOnUEmGOHyiHABagKh17Dqxv57rcj7k+3RpKfJ0b9CHBBKy/ivOhIU0yPH4xdqD3EV37HB1ZRBLignc6c8MZW2FY6p5ZSK7b0bNyMOM3CTiE7CHAJz1+2or7vV1Msj74by4IcoyKHOMygH4fhptsHFgEuQRXqx5fx7zYFWRX5ycNL2UqpUFV5512cDuNLvAS9ONawlaQ10jpSJsZ64S+d3iCvm3777XGntW9nx9fsfqh+JK5+Nq0Qi43WvTgCXMHqq5abma53g75Gqmen9fX/alz1CBtNmenfj7k6yvIxQ3Wiha5AN/r3K4fJtX55hVarvVTy8AB9OMV0GGdwf+AQ4IpU4f75LN27Tzt9HtwbKzynrNF2zXvHsvOWClwGAfZAN18dg1r9UnuthSFF6WeK1doS4HIIsCeqVrHbziLUUpdZornc6S5iDC5p8A3FEWCPVn9KO8RlTpVUeJ8u/xLsUAPR780UUjkE2LOUQ6x11jPN4n/l+WDdaqDznEOdO3YREOAAFOJUn4mrTA3p51KQNU/sM8g8/5bHPHAgeibWAND9O2mdtlF147yCm2/o0IeBXlyuAwDKfjDotBMWcJRHBQ5IlUUVa1Bv0O1squnkVSllvd5kAXQVBDiwfBAo5pyqFbo2od5+cVEQ4Ag0CKRnYrWedVfjlLqBlEfsrSDAEWnwJx8Eqsve+zQCrA+SOq/DoCDAkeWDQE+X63k23txKIzRUXz8IcE00Qv23f/wSta3Odim9q/+Zc6Pz3Ev19YNppJrpRtaXXrGinUMhp5zUvqfg+Uu2HvlCgBORB1nzqYtzDTc77ffoHC3CSGEAS4N5zPv6Q4ATo7lVfV253MoWXegMrKob6xWaFKax9PzNdJpfBDhRqlL7n6qy2mqFWeuY9QaDfttsfRCoXd1NYOS5rnPEBh0BNuB0mGVifOgk1Ncb2VJGbVLIdxnp12qqaHO7HXQHURH6ngZ5RVqdCLBBqqj62jCwiknbBJefEd5QCDCCUWgV3hRa+EFFgBEEbXMcBBjeabR55UWLUzYiIMDwRoHVK1iZKoqHAMMLqm49CDAqyxefID42MwCGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhv0XZkN9IbEGbp4AAAAASUVORK5CYII=",p0=({isOpen:r,onClose:i})=>{const[s,l]=ie.useState(""),[c,f]=ie.useState(""),[p,g]=ie.useState(""),[x,v]=ie.useState(null),[S,A]=ie.useState(null),[T,I]=ie.useState(""),R=vt(H=>H.setCurrentUser),C=H=>{var V;const U=(V=H.target.files)==null?void 0:V[0];if(U){v(U);const Q=new FileReader;Q.onloadend=()=>{A(Q.result)},Q.readAsDataURL(U)}},N=async H=>{H.preventDefault(),I("");try{const U=new FormData;U.append("userCreateRequest",new Blob([JSON.stringify({email:s,username:c,password:p})],{type:"application/json"})),x&&U.append("profile",x);const V=await Kv(U);R(V),i()}catch{I("회원가입에 실패했습니다.")}};return r?h.jsx(eh,{children:h.jsxs(th,{children:[h.jsx("h2",{children:"계정 만들기"}),h.jsxs("form",{onSubmit:N,children:[h.jsxs(Vi,{children:[h.jsxs(Wi,{children:["이메일 ",h.jsx(Pu,{children:"*"})]}),h.jsx(ko,{type:"email",value:s,onChange:H=>l(H.target.value),required:!0})]}),h.jsxs(Vi,{children:[h.jsxs(Wi,{children:["사용자명 ",h.jsx(Pu,{children:"*"})]}),h.jsx(ko,{type:"text",value:c,onChange:H=>f(H.target.value),required:!0})]}),h.jsxs(Vi,{children:[h.jsxs(Wi,{children:["비밀번호 ",h.jsx(Pu,{children:"*"})]}),h.jsx(ko,{type:"password",value:p,onChange:H=>g(H.target.value),required:!0})]}),h.jsxs(Vi,{children:[h.jsx(Wi,{children:"프로필 이미지"}),h.jsxs(l0,{children:[h.jsx(u0,{src:S||zt,alt:"profile"}),h.jsx(a0,{type:"file",accept:"image/*",onChange:C,id:"profile-image"}),h.jsx(c0,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),T&&h.jsx(rh,{children:T}),h.jsx(nh,{type:"submit",children:"계속하기"}),h.jsx(d0,{onClick:i,children:"이미 계정이 있으신가요?"})]})]})}):null},h0=({isOpen:r,onClose:i})=>{const[s,l]=ie.useState(""),[c,f]=ie.useState(""),[p,g]=ie.useState(""),[x,v]=ie.useState(!1),S=vt(I=>I.setCurrentUser),{fetchUsers:A}=nn(),T=async()=>{var I;try{const R=await Gv(s,c);await A(),S(R),g(""),i()}catch(R){console.error("로그인 에러:",R),((I=R.response)==null?void 0:I.status)===401?g("아이디 또는 비밀번호가 올바르지 않습니다."):g("로그인에 실패했습니다.")}};return r?h.jsxs(h.Fragment,{children:[h.jsx(eh,{children:h.jsxs(th,{children:[h.jsx("h2",{children:"돌아오신 것을 환영해요!"}),h.jsxs("form",{onSubmit:I=>{I.preventDefault(),T()},children:[h.jsx(ko,{type:"text",placeholder:"사용자 이름",value:s,onChange:I=>l(I.target.value)}),h.jsx(ko,{type:"password",placeholder:"비밀번호",value:c,onChange:I=>f(I.target.value)}),p&&h.jsx(rh,{children:p}),h.jsx(nh,{type:"submit",children:"로그인"})]}),h.jsxs(i0,{children:["계정이 필요한가요? ",h.jsx(s0,{onClick:()=>v(!0),children:"가입하기"})]})]})}),h.jsx(p0,{isOpen:x,onClose:()=>v(!1)})]}):null},m0=async r=>(await Je.get(`/channels?userId=${r}`)).data,g0=async r=>(await Je.post("/channels/public",r)).data,y0=async r=>{const i={participantIds:r};return(await Je.post("/channels/private",i)).data},v0=async r=>(await Je.get("/readStatuses",{params:{userId:r}})).data,w0=async(r,i)=>{const s={newLastReadAt:i};return(await Je.patch(`/readStatuses/${r}`,s)).data},x0=async(r,i,s)=>{const l={userId:r,channelId:i,lastReadAt:s};return(await Je.post("/readStatuses",l)).data},jo=_r((r,i)=>({readStatuses:{},fetchReadStatuses:async()=>{try{const s=vt.getState().currentUserId;if(!s)return;const c=(await v0(s)).reduce((f,p)=>(f[p.channelId]={id:p.id,lastReadAt:p.lastReadAt},f),{});r({readStatuses:c})}catch(s){console.error("읽음 상태 조회 실패:",s)}},updateReadStatus:async s=>{try{const l=vt.getState().currentUserId;if(!l)return;const c=i().readStatuses[s];let f;c?f=await w0(c.id,new Date().toISOString()):f=await x0(l,s,new Date().toISOString()),r(p=>({readStatuses:{...p.readStatuses,[s]:{id:f.id,lastReadAt:f.lastReadAt}}}))}catch(l){console.error("읽음 상태 업데이트 실패:",l)}},hasUnreadMessages:(s,l)=>{const c=i().readStatuses[s],f=c==null?void 0:c.lastReadAt;return!f||new Date(l)>new Date(f)}})),xr=_r((r,i)=>({channels:[],pollingInterval:null,loading:!1,error:null,fetchChannels:async s=>{r({loading:!0,error:null});try{const l=await m0(s);r(f=>{const p=new Set(f.channels.map(S=>S.id)),g=l.filter(S=>!p.has(S.id));return{channels:[...f.channels.filter(S=>l.some(A=>A.id===S.id)),...g],loading:!1}});const{fetchReadStatuses:c}=jo.getState();return c(),l}catch(l){return r({error:l,loading:!1}),[]}},startPolling:s=>{const l=i().pollingInterval;l&&clearInterval(l);const c=setInterval(()=>{i().fetchChannels(s)},3e3);r({pollingInterval:c})},stopPolling:()=>{const s=i().pollingInterval;s&&(clearInterval(s),r({pollingInterval:null}))},createPublicChannel:async s=>{try{const l=await g0(s);return r(c=>c.channels.some(p=>p.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 y0(s);return r(c=>c.channels.some(p=>p.id===l.id)?c:{channels:[...c.channels,{...l,participantIds:s,lastMessageAt:new Date().toISOString()}]}),l}catch(l){throw console.error("비공개 채널 생성 실패:",l),l}}})),S0=async r=>(await Je.get(`/binaryContents/${r}`)).data,E0=r=>`${Qv()}/binaryContents/${r}/download`,Yn=_r((r,i)=>({binaryContents:{},fetchBinaryContent:async s=>{if(i().binaryContents[s])return i().binaryContents[s];try{const l=await S0(s),{contentType:c,fileName:f,size:p}=l,x={url:E0(s),contentType:c,fileName:f,size:p};return r(v=>({binaryContents:{...v.binaryContents,[s]:x}})),x}catch(l){return console.error("첨부파일 정보 조회 실패:",l),null}}})),Io=_.div` + position: absolute; + bottom: -3px; + right: -3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: ${r=>r.$online?ee.colors.status.online:ee.colors.status.offline}; + border: 4px solid ${r=>r.$background||ee.colors.background.secondary}; +`;_.div` + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + background: ${r=>ee.colors.status[r.status||"offline"]||ee.colors.status.offline}; +`;const Tr=_.div` + position: relative; + width: ${r=>r.$size||"32px"}; + height: ${r=>r.$size||"32px"}; + flex-shrink: 0; + margin: ${r=>r.$margin||"0"}; +`,rn=_.img` + width: 100%; + height: 100%; + border-radius: 50%; + object-fit: cover; + border: ${r=>r.$border||"none"}; +`;function C0({isOpen:r,onClose:i,user:s}){var L,b;const[l,c]=ie.useState(s.username),[f,p]=ie.useState(s.email),[g,x]=ie.useState(""),[v,S]=ie.useState(null),[A,T]=ie.useState(""),[I,R]=ie.useState(null),{binaryContents:C,fetchBinaryContent:N}=Yn(),{logout:H,updateUser:U}=vt();ie.useEffect(()=>{var re;(re=s.profile)!=null&&re.id&&!C[s.profile.id]&&N(s.profile.id)},[s.profile,C,N]);const V=()=>{c(s.username),p(s.email),x(""),S(null),R(null),T(""),i()},Q=re=>{var Ne;const ye=(Ne=re.target.files)==null?void 0:Ne[0];if(ye){S(ye);const at=new FileReader;at.onloadend=()=>{R(at.result)},at.readAsDataURL(ye)}},$=async re=>{re.preventDefault(),T("");try{const ye=new FormData,Ne={};l!==s.username&&(Ne.newUsername=l),f!==s.email&&(Ne.newEmail=f),g&&(Ne.newPassword=g),(Object.keys(Ne).length>0||v)&&(ye.append("userUpdateRequest",new Blob([JSON.stringify(Ne)],{type:"application/json"})),v&&ye.append("profile",v),await U(s.id,ye)),i()}catch{T("사용자 정보 수정에 실패했습니다.")}};return r?h.jsx(k0,{children:h.jsxs(j0,{children:[h.jsx("h2",{children:"프로필 수정"}),h.jsxs("form",{onSubmit:$,children:[h.jsxs(Yi,{children:[h.jsx(qi,{children:"프로필 이미지"}),h.jsxs(R0,{children:[h.jsx(P0,{src:I||((L=s.profile)!=null&&L.id?(b=C[s.profile.id])==null?void 0:b.url:void 0)||zt,alt:"profile"}),h.jsx(_0,{type:"file",accept:"image/*",onChange:Q,id:"profile-image"}),h.jsx(T0,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),h.jsxs(Yi,{children:[h.jsxs(qi,{children:["사용자명 ",h.jsx(bd,{children:"*"})]}),h.jsx(_u,{type:"text",value:l,onChange:re=>c(re.target.value),required:!0})]}),h.jsxs(Yi,{children:[h.jsxs(qi,{children:["이메일 ",h.jsx(bd,{children:"*"})]}),h.jsx(_u,{type:"email",value:f,onChange:re=>p(re.target.value),required:!0})]}),h.jsxs(Yi,{children:[h.jsx(qi,{children:"새 비밀번호"}),h.jsx(_u,{type:"password",placeholder:"변경하지 않으려면 비워두세요",value:g,onChange:re=>x(re.target.value)})]}),A&&h.jsx(A0,{children:A}),h.jsxs(I0,{children:[h.jsx(Hd,{type:"button",onClick:V,$secondary:!0,children:"취소"}),h.jsx(Hd,{type:"submit",children:"저장"})]})]}),h.jsx(N0,{onClick:H,children:"로그아웃"})]})}):null}const k0=_.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; +`,j0=_.div` + background: ${({theme:r})=>r.colors.background.secondary}; + padding: 32px; + border-radius: 5px; + width: 100%; + max-width: 480px; + + h2 { + color: ${({theme:r})=>r.colors.text.primary}; + margin-bottom: 24px; + text-align: center; + font-size: 24px; + } +`,_u=_.input` + width: 100%; + padding: 10px; + margin-bottom: 10px; + border: none; + border-radius: 4px; + background: ${({theme:r})=>r.colors.background.input}; + color: ${({theme:r})=>r.colors.text.primary}; + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${({theme:r})=>r.colors.brand.primary}; + } +`,Hd=_.button` + width: 100%; + padding: 10px; + border: none; + border-radius: 4px; + background: ${({$secondary:r,theme:i})=>r?"transparent":i.colors.brand.primary}; + color: ${({theme:r})=>r.colors.text.primary}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({$secondary:r,theme:i})=>r?i.colors.background.hover:i.colors.brand.hover}; + } +`,A0=_.div` + color: ${({theme:r})=>r.colors.status.error}; + font-size: 14px; + margin-bottom: 10px; +`,R0=_.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 20px; +`,P0=_.img` + width: 100px; + height: 100px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,_0=_.input` + display: none; +`,T0=_.label` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,I0=_.div` + display: flex; + gap: 10px; + margin-top: 20px; +`,N0=_.button` + width: 100%; + padding: 10px; + margin-top: 16px; + border: none; + border-radius: 4px; + background: transparent; + color: ${({theme:r})=>r.colors.status.error}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({theme:r})=>r.colors.status.error}20; + } +`,Yi=_.div` + margin-bottom: 20px; +`,qi=_.label` + display: block; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,bd=_.span` + color: ${({theme:r})=>r.colors.status.error}; +`,O0=_.div` + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.5rem 0.75rem; + background-color: ${({theme:r})=>r.colors.background.tertiary}; + width: 100%; + height: 52px; +`,L0=_(Tr)``;_(rn)``;const D0=_.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; +`,M0=_.div` + font-weight: 500; + color: ${({theme:r})=>r.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.875rem; + line-height: 1.2; +`,z0=_.div` + font-size: 0.75rem; + color: ${({theme:r})=>r.colors.text.secondary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.2; +`,U0=_.div` + display: flex; + align-items: center; + flex-shrink: 0; +`,F0=_.button` + background: none; + border: none; + padding: 0.25rem; + cursor: pointer; + color: ${({theme:r})=>r.colors.text.secondary}; + font-size: 18px; + + &:hover { + color: ${({theme:r})=>r.colors.text.primary}; + } +`;function B0({user:r}){var f,p;const[i,s]=ie.useState(!1),{binaryContents:l,fetchBinaryContent:c}=Yn();return ie.useEffect(()=>{var g;(g=r.profile)!=null&&g.id&&!l[r.profile.id]&&c(r.profile.id)},[r.profile,l,c]),h.jsxs(h.Fragment,{children:[h.jsxs(O0,{children:[h.jsxs(L0,{children:[h.jsx(rn,{src:(f=r.profile)!=null&&f.id?(p=l[r.profile.id])==null?void 0:p.url:zt,alt:r.username}),h.jsx(Io,{$online:!0})]}),h.jsxs(D0,{children:[h.jsx(M0,{children:r.username}),h.jsx(z0,{children:"온라인"})]}),h.jsx(U0,{children:h.jsx(F0,{onClick:()=>s(!0),children:"⚙️"})})]}),h.jsx(C0,{isOpen:i,onClose:()=>s(!1),user:r})]})}const $0=_.div` + width: 240px; + background: ${ee.colors.background.secondary}; + border-right: 1px solid ${ee.colors.border.primary}; + display: flex; + flex-direction: column; +`,H0=_.div` + flex: 1; + overflow-y: auto; +`,b0=_.div` + padding: 16px; + font-size: 16px; + font-weight: bold; + color: ${ee.colors.text.primary}; +`,oh=_.div` + height: 34px; + padding: 0 8px; + margin: 1px 8px; + display: flex; + align-items: center; + gap: 6px; + color: ${r=>r.$hasUnread?r.theme.colors.text.primary:r.theme.colors.text.muted}; + font-weight: ${r=>r.$hasUnread?"600":"normal"}; + cursor: pointer; + background: ${r=>r.$isActive?r.theme.colors.background.hover:"transparent"}; + border-radius: 4px; + + &:hover { + background: ${r=>r.theme.colors.background.hover}; + color: ${r=>r.theme.colors.text.primary}; + } +`,Vd=_.div` + margin-bottom: 8px; +`,qu=_.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}; + } +`,Wd=_.span` + margin-right: 4px; + font-size: 10px; + transition: transform 0.2s; + transform: rotate(${r=>r.$folded?"-90deg":"0deg"}); +`,Yd=_.div` + display: ${r=>r.$folded?"none":"block"}; +`,qd=_(oh)` + height: ${r=>r.hasSubtext?"42px":"34px"}; +`,V0=_(Tr)` + width: 32px; + height: 32px; + margin: 0 8px; +`,Qd=_.div` + font-size: 16px; + line-height: 18px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: ${r=>r.$isActive||r.$hasUnread?r.theme.colors.text.primary:r.theme.colors.text.muted}; + font-weight: ${r=>r.$hasUnread?"600":"normal"}; +`;_(Io)` + border-color: ${ee.colors.background.primary}; +`;const Gd=_.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; + + ${qu}:hover & { + opacity: 1; + } + + &:hover { + color: ${ee.colors.text.primary}; + } +`,W0=_(Tr)` + width: 40px; + height: 24px; + margin: 0 8px; +`,Y0=_.div` + font-size: 12px; + line-height: 13px; + color: ${ee.colors.text.muted}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,Kd=_.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; +`,q0=_.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; +`,Q0=_.div` + background: ${ee.colors.background.primary}; + border-radius: 4px; + width: 440px; + max-width: 90%; +`,G0=_.div` + padding: 16px; + display: flex; + justify-content: space-between; + align-items: center; +`,K0=_.h2` + color: ${ee.colors.text.primary}; + font-size: 20px; + font-weight: 600; + margin: 0; +`,X0=_.div` + padding: 0 16px 16px; +`,J0=_.form` + display: flex; + flex-direction: column; + gap: 16px; +`,Tu=_.div` + display: flex; + flex-direction: column; + gap: 8px; +`,Iu=_.label` + color: ${ee.colors.text.primary}; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; +`,Z0=_.p` + color: ${ee.colors.text.muted}; + font-size: 14px; + margin: -4px 0 0; +`,Qu=_.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}; + } +`,e1=_.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; + } +`,t1=_.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}; + } +`,n1=_(Qu)` + margin-bottom: 8px; +`,r1=_.div` + max-height: 300px; + overflow-y: auto; + background: ${ee.colors.background.tertiary}; + border-radius: 4px; +`,o1=_.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}; + } +`,i1=_.input` + margin-right: 12px; + width: 16px; + height: 16px; + cursor: pointer; +`,Xd=_.img` + width: 32px; + height: 32px; + border-radius: 50%; + margin-right: 12px; +`,s1=_.div` + flex: 1; + min-width: 0; +`,l1=_.div` + color: ${ee.colors.text.primary}; + font-size: 14px; + font-weight: 500; +`,u1=_.div` + color: ${ee.colors.text.muted}; + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,a1=_.div` + padding: 16px; + text-align: center; + color: ${ee.colors.text.muted}; +`,c1=_.div` + color: ${ee.colors.status.error}; + font-size: 14px; + padding: 8px 0; + text-align: center; + background-color: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 4px; + margin-bottom: 8px; +`;function f1(){return h.jsx(b0,{children:"채널 목록"})}function Jd({channel:r,isActive:i,onClick:s,hasUnread:l}){var x;const c=vt(v=>v.currentUserId),{binaryContents:f}=Yn();if(r.type==="PUBLIC")return h.jsxs(oh,{$isActive:i,onClick:s,$hasUnread:l,children:["# ",r.name]});const p=r.participants;if(p.length>2){const v=p.filter(S=>S.id!==c).map(S=>S.username).join(", ");return h.jsxs(qd,{$isActive:i,onClick:s,children:[h.jsx(W0,{children:p.filter(S=>S.id!==c).slice(0,2).map((S,A)=>{var T;return h.jsx(rn,{src:S.profile?(T=f[S.profile.id])==null?void 0:T.url:zt,style:{position:"absolute",left:A*16,zIndex:2-A,width:"24px",height:"24px",border:"2px solid #2a2a2a"}},S.id)})}),h.jsxs(Kd,{children:[h.jsx(Qd,{$hasUnread:l,children:v}),h.jsxs(Y0,{children:["멤버 ",p.length,"명"]})]})]})}const g=p.filter(v=>v.id!==c)[0];return g&&h.jsxs(qd,{$isActive:i,onClick:s,children:[h.jsxs(V0,{children:[h.jsx(rn,{src:g.profile?(x=f[g.profile.id])==null?void 0:x.url:zt,alt:"profile"}),h.jsx(Io,{$online:g.online})]}),h.jsx(Kd,{children:h.jsx(Qd,{$hasUnread:l,children:g.username})})]})}function d1({isOpen:r,type:i,onClose:s,onCreateSuccess:l}){const[c,f]=ie.useState({name:"",description:""}),[p,g]=ie.useState(""),[x,v]=ie.useState([]),[S,A]=ie.useState(""),T=nn($=>$.users),I=Yn($=>$.binaryContents),R=vt($=>$.currentUserId),C=ie.useMemo(()=>T.filter($=>$.id!==R).filter($=>$.username.toLowerCase().includes(p.toLowerCase())||$.email.toLowerCase().includes(p.toLowerCase())),[p,T,R]),N=xr($=>$.createPublicChannel),H=xr($=>$.createPrivateChannel),U=$=>{const{name:L,value:b}=$.target;f(re=>({...re,[L]:b}))},V=$=>{v(L=>L.includes($)?L.filter(b=>b!==$):[...L,$])},Q=async $=>{var L,b;$.preventDefault(),A("");try{let re;if(i==="PUBLIC"){if(!c.name.trim()){A("채널 이름을 입력해주세요.");return}const ye={name:c.name,description:c.description};re=await N(ye)}else{if(x.length===0){A("대화 상대를 선택해주세요.");return}const ye=R&&[...x,R]||x;re=await H(ye)}l(re)}catch(re){console.error("채널 생성 실패:",re),A(((b=(L=re.response)==null?void 0:L.data)==null?void 0:b.message)||"채널 생성에 실패했습니다. 다시 시도해주세요.")}};return r?h.jsx(q0,{onClick:s,children:h.jsxs(Q0,{onClick:$=>$.stopPropagation(),children:[h.jsxs(G0,{children:[h.jsx(K0,{children:i==="PUBLIC"?"채널 만들기":"개인 메시지 시작하기"}),h.jsx(t1,{onClick:s,children:"×"})]}),h.jsx(X0,{children:h.jsxs(J0,{onSubmit:Q,children:[S&&h.jsx(c1,{children:S}),i==="PUBLIC"?h.jsxs(h.Fragment,{children:[h.jsxs(Tu,{children:[h.jsx(Iu,{children:"채널 이름"}),h.jsx(Qu,{name:"name",value:c.name,onChange:U,placeholder:"새로운-채널",required:!0})]}),h.jsxs(Tu,{children:[h.jsx(Iu,{children:"채널 설명"}),h.jsx(Z0,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Qu,{name:"description",value:c.description,onChange:U,placeholder:"채널 설명을 입력하세요"})]})]}):h.jsxs(Tu,{children:[h.jsx(Iu,{children:"사용자 검색"}),h.jsx(n1,{type:"text",value:p,onChange:$=>g($.target.value),placeholder:"사용자명 또는 이메일로 검색"}),h.jsx(r1,{children:C.length>0?C.map($=>h.jsxs(o1,{children:[h.jsx(i1,{type:"checkbox",checked:x.includes($.id),onChange:()=>V($.id)}),$.profile?h.jsx(Xd,{src:I[$.profile.id].url}):h.jsx(Xd,{src:zt}),h.jsxs(s1,{children:[h.jsx(l1,{children:$.username}),h.jsx(u1,{children:$.email})]})]},$.id)):h.jsx(a1,{children:"검색 결과가 없습니다."})})]}),h.jsx(e1,{type:"submit",children:i==="PUBLIC"?"채널 만들기":"대화 시작하기"})]})})]})}):null}function p1({currentUser:r,activeChannel:i,onChannelSelect:s}){var Q,$;const[l,c]=ie.useState({PUBLIC:!1,PRIVATE:!1}),[f,p]=ie.useState({isOpen:!1,type:null}),g=xr(L=>L.channels),x=xr(L=>L.fetchChannels),v=xr(L=>L.startPolling),S=xr(L=>L.stopPolling),A=jo(L=>L.fetchReadStatuses),T=jo(L=>L.updateReadStatus),I=jo(L=>L.hasUnreadMessages);ie.useEffect(()=>{if(r)return x(r.id),A(),v(r.id),()=>{S()}},[r,x,A,v,S]);const R=L=>{c(b=>({...b,[L]:!b[L]}))},C=(L,b)=>{b.stopPropagation(),p({isOpen:!0,type:L})},N=()=>{p({isOpen:!1,type:null})},H=async L=>{try{const re=(await x(r.id)).find(ye=>ye.id===L.id);re&&s(re),N()}catch(b){console.error("채널 생성 실패:",b)}},U=L=>{s(L),T(L.id)},V=g.reduce((L,b)=>(L[b.type]||(L[b.type]=[]),L[b.type].push(b),L),{});return h.jsxs($0,{children:[h.jsx(f1,{}),h.jsxs(H0,{children:[h.jsxs(Vd,{children:[h.jsxs(qu,{onClick:()=>R("PUBLIC"),children:[h.jsx(Wd,{$folded:l.PUBLIC,children:"▼"}),h.jsx("span",{children:"일반 채널"}),h.jsx(Gd,{onClick:L=>C("PUBLIC",L),children:"+"})]}),h.jsx(Yd,{$folded:l.PUBLIC,children:(Q=V.PUBLIC)==null?void 0:Q.map(L=>h.jsx(Jd,{channel:L,isActive:(i==null?void 0:i.id)===L.id,hasUnread:I(L.id,L.lastMessageAt),onClick:()=>U(L)},L.id))})]}),h.jsxs(Vd,{children:[h.jsxs(qu,{onClick:()=>R("PRIVATE"),children:[h.jsx(Wd,{$folded:l.PRIVATE,children:"▼"}),h.jsx("span",{children:"개인 메시지"}),h.jsx(Gd,{onClick:L=>C("PRIVATE",L),children:"+"})]}),h.jsx(Yd,{$folded:l.PRIVATE,children:($=V.PRIVATE)==null?void 0:$.map(L=>h.jsx(Jd,{channel:L,isActive:(i==null?void 0:i.id)===L.id,hasUnread:I(L.id,L.lastMessageAt),onClick:()=>U(L)},L.id))})]})]}),h.jsx(h1,{children:h.jsx(B0,{user:r})}),h.jsx(d1,{isOpen:f.isOpen,type:f.type,onClose:N,onCreateSuccess:H})]})}const h1=_.div` + margin-top: auto; + border-top: 1px solid ${({theme:r})=>r.colors.border.primary}; + background-color: ${({theme:r})=>r.colors.background.tertiary}; +`,m1=_.div` + flex: 1; + display: flex; + flex-direction: column; + background: ${({theme:r})=>r.colors.background.primary}; +`,g1=_.div` + display: flex; + flex-direction: column; + height: 100%; + background: ${({theme:r})=>r.colors.background.primary}; +`,y1=_(g1)` + justify-content: center; + align-items: center; + flex: 1; + padding: 0 20px; +`,v1=_.div` + text-align: center; + max-width: 400px; + padding: 20px; + margin-bottom: 80px; +`,w1=_.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); } + } +`,x1=_.h2` + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 28px; + font-weight: 700; + margin-bottom: 16px; +`,S1=_.p` + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 16px; + line-height: 1.6; + word-break: keep-all; +`,Zd=_.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=_.div` + display: flex; + align-items: center; + gap: 8px; + height: 100%; +`,E1=_.div` + display: flex; + align-items: center; + gap: 12px; + height: 100%; +`,C1=_(Tr)` + width: 24px; + height: 24px; +`;_.img` + width: 24px; + height: 24px; + border-radius: 50%; +`;const k1=_.div` + position: relative; + width: 40px; + height: 24px; + flex-shrink: 0; +`,j1=_(Io)` + border-color: ${ee.colors.background.primary}; + bottom: -3px; + right: -3px; +`,A1=_.div` + font-size: 12px; + color: ${ee.colors.text.muted}; + line-height: 13px; +`,tp=_.div` + font-weight: bold; + color: ${ee.colors.text.primary}; + line-height: 20px; + font-size: 16px; +`,R1=_.div` + flex: 1; + display: flex; + flex-direction: column-reverse; + overflow-y: auto; +`,P1=_.div` + padding: 16px; + display: flex; + flex-direction: column; +`,_1=_.div` + margin-bottom: 16px; + display: flex; + align-items: flex-start; +`,T1=_(Tr)` + margin-right: 16px; + width: 40px; + height: 40px; +`;_.img` + width: 40px; + height: 40px; + border-radius: 50%; +`;const I1=_.div` + display: flex; + align-items: center; + margin-bottom: 4px; +`,N1=_.span` + font-weight: bold; + color: ${ee.colors.text.primary}; + margin-right: 8px; +`,O1=_.span` + font-size: 0.75rem; + color: ${ee.colors.text.muted}; +`,L1=_.div` + color: ${ee.colors.text.secondary}; + margin-top: 4px; +`,D1=_.form` + display: flex; + align-items: center; + gap: 8px; + padding: 16px; + background: ${({theme:r})=>r.colors.background.secondary}; +`,M1=_.textarea` + flex: 1; + padding: 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border: none; + border-radius: 4px; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + resize: none; + min-height: 44px; + max-height: 144px; + + &:focus { + outline: none; + } + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } +`,z1=_.button` + background: none; + border: none; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px 8px; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + color: ${({theme:r})=>r.colors.text.primary}; + } +`;_.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 np=_.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; + width: 100%; +`,U1=_.a` + display: block; + border-radius: 4px; + overflow: hidden; + max-width: 300px; + + img { + width: 100%; + height: auto; + display: block; + } +`,F1=_.a` + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 8px; + text-decoration: none; + width: fit-content; + + &:hover { + background: ${({theme:r})=>r.colors.background.hover}; + } +`,B1=_.div` + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + font-size: 40px; + color: #0B93F6; +`,$1=_.div` + display: flex; + flex-direction: column; + gap: 2px; +`,H1=_.span` + font-size: 14px; + color: #0B93F6; + font-weight: 500; +`,b1=_.span` + font-size: 13px; + color: ${({theme:r})=>r.colors.text.muted}; +`,V1=_.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px 0; +`,ih=_.div` + position: relative; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 4px; + max-width: 300px; +`,W1=_(ih)` + padding: 0; + overflow: hidden; + width: 200px; + height: 120px; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } +`,Y1=_.div` + color: #0B93F6; + font-size: 20px; +`,q1=_.div` + font-size: 13px; + color: ${({theme:r})=>r.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,rp=_.button` + position: absolute; + top: -6px; + right: -6px; + width: 20px; + height: 20px; + border-radius: 50%; + background: ${({theme:r})=>r.colors.background.secondary}; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.text.primary}; + } +`;function Q1({channel:r}){var x;const i=vt(v=>v.currentUserId),s=nn(v=>v.users),l=Yn(v=>v.binaryContents);if(!r)return null;if(r.type==="PUBLIC")return h.jsx(Zd,{children:h.jsx(ep,{children:h.jsxs(tp,{children:["# ",r.name]})})});const c=r.participants.map(v=>s.find(S=>S.id===v.id)).filter(Boolean),f=c.filter(v=>v.id!==i),p=c.length>2,g=c.filter(v=>v.id!==i).map(v=>v.username).join(", ");return h.jsx(Zd,{children:h.jsx(ep,{children:h.jsxs(E1,{children:[p?h.jsx(k1,{children:f.slice(0,2).map((v,S)=>{var A;return h.jsx(rn,{src:v.profile?(A=l[v.profile.id])==null?void 0:A.url:zt,style:{position:"absolute",left:S*16,zIndex:2-S,width:"24px",height:"24px"}},v.id)})}):h.jsxs(C1,{children:[h.jsx(rn,{src:f[0].profile?(x=l[f[0].profile.id])==null?void 0:x.url:zt}),h.jsx(j1,{$online:f[0].online})]}),h.jsxs("div",{children:[h.jsx(tp,{children:g}),p&&h.jsxs(A1,{children:["멤버 ",c.length,"명"]})]})]})})})}const G1=async(r,i,s)=>{var c;return(await Je.get("/messages",{params:{channelId:r,cursor:i,size:s.size,sort:(c=s.sort)==null?void 0:c.join(",")}})).data},K1=async(r,i)=>{const s=new FormData,l={content:r.content,channelId:r.channelId,authorId:r.authorId};return s.append("messageCreateRequest",new Blob([JSON.stringify(l)],{type:"application/json"})),i&&i.length>0&&i.forEach(f=>{s.append("attachments",f)}),(await Je.post("/messages",s,{headers:{"Content-Type":"multipart/form-data"}})).data},Nu={size:50,sort:["createdAt,desc"]},sh=_r((r,i)=>({messages:[],pollingIntervals:{},lastMessageId:null,pagination:{nextCursor:null,pageSize:50,hasNext:!1},fetchMessages:async(s,l,c=Nu)=>{try{const f=await G1(s,l,c),p=f.content,g=p.length>0?p[0]:null,x=(g==null?void 0:g.id)!==i().lastMessageId;return r(v=>{var C;const S=!l,A=s!==((C=v.messages[0])==null?void 0:C.channelId),T=S&&(v.messages.length===0||A);let I=[],R={...v.pagination};if(T)I=p,R={nextCursor:f.nextCursor,pageSize:f.size,hasNext:f.hasNext};else if(S){const N=new Set(v.messages.map(U=>U.id));I=[...p.filter(U=>!N.has(U.id)&&(v.messages.length===0||U.createdAt>v.messages[0].createdAt)),...v.messages]}else{const N=new Set(v.messages.map(U=>U.id)),H=p.filter(U=>!N.has(U.id));I=[...v.messages,...H],R={nextCursor:f.nextCursor,pageSize:f.size,hasNext:f.hasNext}}return{messages:I,lastMessageId:(g==null?void 0:g.id)||null,pagination:R}}),x}catch(f){return console.error("메시지 목록 조회 실패:",f),!1}},loadMoreMessages:async s=>{const{pagination:l}=i();l.hasNext&&await i().fetchMessages(s,l.nextCursor,{...Nu})},startPolling:s=>{const l=i();if(l.pollingIntervals[s]){const g=l.pollingIntervals[s];typeof g=="number"&&clearTimeout(g)}let c=300;const f=3e3;r(g=>({pollingIntervals:{...g.pollingIntervals,[s]:!0}}));const p=async()=>{const g=i();if(!g.pollingIntervals[s])return;if(await g.fetchMessages(s,null,Nu)?c=300:c=Math.min(c*1.5,f),i().pollingIntervals[s]){const v=setTimeout(p,c);r(S=>({pollingIntervals:{...S.pollingIntervals,[s]:v}}))}};p()},stopPolling:s=>{const{pollingIntervals:l}=i();if(l[s]){const c=l[s];typeof c=="number"&&clearTimeout(c),r(f=>{const p={...f.pollingIntervals};return delete p[s],{pollingIntervals:p}})}},createMessage:async(s,l)=>{try{const c=await K1(s,l),f=jo.getState().updateReadStatus;return await f(s.channelId),r(p=>p.messages.some(x=>x.id===c.id)?p:{messages:[c,...p.messages],lastMessageId:c.id}),c}catch(c){throw console.error("메시지 생성 실패:",c),c}}}));function X1({channel:r}){const[i,s]=ie.useState(""),[l,c]=ie.useState([]),f=sh(T=>T.createMessage),p=vt(T=>T.currentUserId),g=async T=>{if(T.preventDefault(),!(!i.trim()&&l.length===0))try{await f({content:i.trim(),channelId:r.id,authorId:p??""},l),s(""),c([])}catch(I){console.error("메시지 전송 실패:",I)}},x=T=>{const I=Array.from(T.target.files||[]);c(R=>[...R,...I]),T.target.value=""},v=T=>{c(I=>I.filter((R,C)=>C!==T))},S=T=>{if(T.key==="Enter"&&!T.shiftKey){if(console.log("Enter key pressed"),T.preventDefault(),T.nativeEvent.isComposing)return;g(T)}},A=(T,I)=>T.type.startsWith("image/")?h.jsxs(W1,{children:[h.jsx("img",{src:URL.createObjectURL(T),alt:T.name}),h.jsx(rp,{onClick:()=>v(I),children:"×"})]},I):h.jsxs(ih,{children:[h.jsx(Y1,{children:"📎"}),h.jsx(q1,{children:T.name}),h.jsx(rp,{onClick:()=>v(I),children:"×"})]},I);return ie.useEffect(()=>()=>{l.forEach(T=>{T.type.startsWith("image/")&&URL.revokeObjectURL(URL.createObjectURL(T))})},[l]),r?h.jsxs(h.Fragment,{children:[l.length>0&&h.jsx(V1,{children:l.map((T,I)=>A(T,I))}),h.jsxs(D1,{onSubmit:g,children:[h.jsxs(z1,{as:"label",children:["+",h.jsx("input",{type:"file",multiple:!0,onChange:x,style:{display:"none"}})]}),h.jsx(M1,{value:i,onChange:T=>s(T.target.value),onKeyDown:S,placeholder:r.type==="PUBLIC"?`#${r.name}에 메시지 보내기`:"메시지 보내기"})]})]}):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 Gu=function(r,i){return Gu=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])},Gu(r,i)};function J1(r,i){Gu(r,i);function s(){this.constructor=r}r.prototype=i===null?Object.create(i):(s.prototype=i.prototype,new s)}var Ao=function(){return Ao=Object.assign||function(i){for(var s,l=1,c=arguments.length;lr?I():i!==!0&&(c=setTimeout(l?R:I,l===void 0?r-A:r))}return v.cancel=x,v}var Sr={Pixel:"Pixel",Percent:"Percent"},op={unit:Sr.Percent,value:.8};function ip(r){return typeof r=="number"?{unit:Sr.Percent,value:r*100}:typeof r=="string"?r.match(/^(\d*(\.\d+)?)px$/)?{unit:Sr.Pixel,value:parseFloat(r)}:r.match(/^(\d*(\.\d+)?)%$/)?{unit:Sr.Percent,value:parseFloat(r)}:(console.warn('scrollThreshold format is invalid. Valid formats: "120px", "50%"...'),op):(console.warn("scrollThreshold should be string or number"),op)}var ew=function(r){J1(i,r);function i(s){var l=r.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 f=l.props.height||l._scrollableNode?c.target:document.documentElement.scrollTop?document.documentElement:document.body;if(!l.actionTriggered){var p=l.props.inverse?l.isElementAtTop(f,l.props.scrollThreshold):l.isElementAtBottom(f,l.props.scrollThreshold);p&&l.props.hasMore&&(l.actionTriggered=!0,l.setState({showLoader:!0}),l.props.next&&l.props.next()),l.lastScrollTop=f.scrollTop}},l.state={showLoader:!1,pullToRefreshThresholdBreached:!1,prevDataLength:s.dataLength},l.throttledOnScrollListener=Z1(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?Ao(Ao({},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,f=ip(l);return f.unit===Sr.Pixel?s.scrollTop<=f.value+c-s.scrollHeight+1:s.scrollTop<=f.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,f=ip(l);return f.unit===Sr.Pixel?s.scrollTop+c>=s.scrollHeight-f.value:s.scrollTop+c>=f.value/100*s.scrollHeight},i.prototype.render=function(){var s=this,l=Ao({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),f=this.props.pullDownToRefresh&&this.props.height?{overflow:"auto"}:{};return gt.createElement("div",{style:f,className:"infinite-scroll-component__outerdiv"},gt.createElement("div",{className:"infinite-scroll-component "+(this.props.className||""),ref:function(p){return s._infScroll=p},style:l},this.props.pullDownToRefresh&>.createElement("div",{style:{position:"relative"},ref:function(p){return s._pullDown=p}},gt.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}(ie.Component);const tw=r=>r<1024?r+" B":r<1024*1024?(r/1024).toFixed(2)+" KB":r<1024*1024*1024?(r/(1024*1024)).toFixed(2)+" MB":(r/(1024*1024*1024)).toFixed(2)+" GB";function nw({channel:r}){const{messages:i,fetchMessages:s,loadMoreMessages:l,pagination:c,startPolling:f,stopPolling:p}=sh(),{binaryContents:g,fetchBinaryContent:x}=Yn();ie.useEffect(()=>{if(r!=null&&r.id)return s(r.id,null),f(r.id),()=>{p(r.id)}},[r==null?void 0:r.id,s,f,p]),ie.useEffect(()=>{i.forEach(I=>{var R;(R=I.attachments)==null||R.forEach(C=>{g[C.id]||x(C.id)})})},[i,g,x]);const v=async I=>{try{const{url:R,fileName:C}=I,N=document.createElement("a");N.href=R,N.download=C,N.style.display="none",document.body.appendChild(N);try{const U=await(await window.showSaveFilePicker({suggestedName:I.fileName,types:[{description:"Files",accept:{"*/*":[".txt",".pdf",".doc",".docx",".xls",".xlsx",".jpg",".jpeg",".png",".gif"]}}]})).createWritable(),Q=await(await fetch(R)).blob();await U.write(Q),await U.close()}catch(H){H.name!=="AbortError"&&N.click()}document.body.removeChild(N),window.URL.revokeObjectURL(R)}catch(R){console.error("파일 다운로드 실패:",R)}},S=I=>I!=null&&I.length?I.map(R=>{const C=g[R.id];return C?C.contentType.startsWith("image/")?h.jsx(np,{children:h.jsx(U1,{href:"#",onClick:H=>{H.preventDefault(),v(C)},children:h.jsx("img",{src:C.url,alt:C.fileName})})},C.url):h.jsx(np,{children:h.jsxs(F1,{href:"#",onClick:H=>{H.preventDefault(),v(C)},children:[h.jsx(B1,{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($1,{children:[h.jsx(H1,{children:C.fileName}),h.jsx(b1,{children:tw(C.size)})]})]})},C.url):null}):null,A=I=>new Date(I).toLocaleTimeString(),T=()=>{r!=null&&r.id&&l(r.id)};return h.jsx(R1,{children:h.jsx("div",{id:"scrollableDiv",style:{height:"100%",overflow:"auto",display:"flex",flexDirection:"column-reverse"},children:h.jsx(ew,{dataLength:i.length,next:T,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(P1,{children:[...i].reverse().map(I=>{var C;const R=I.author;return h.jsxs(_1,{children:[h.jsx(T1,{children:h.jsx(rn,{src:R&&R.profile?(C=g[R.profile.id])==null?void 0:C.url:zt,alt:R&&R.username||"알 수 없음"})}),h.jsxs("div",{children:[h.jsxs(I1,{children:[h.jsx(N1,{children:R&&R.username||"알 수 없음"}),h.jsx(O1,{children:A(I.createdAt)})]}),h.jsx(L1,{children:I.content}),S(I.attachments)]})]},I.id)})})})})})}function rw({channel:r}){return r?h.jsxs(m1,{children:[h.jsx(Q1,{channel:r}),h.jsx(nw,{channel:r}),h.jsx(X1,{channel:r})]}):h.jsx(y1,{children:h.jsxs(v1,{children:[h.jsx(w1,{children:"👋"}),h.jsx(x1,{children:"채널을 선택해주세요"}),h.jsxs(S1,{children:["왼쪽의 채널 목록에서 채널을 선택하여",h.jsx("br",{}),"대화를 시작하세요."]})]})})}function ow(r,i="yyyy-MM-dd HH:mm:ss"){if(!r||!(r instanceof Date)||isNaN(r.getTime()))return"";const s=r.getFullYear(),l=String(r.getMonth()+1).padStart(2,"0"),c=String(r.getDate()).padStart(2,"0"),f=String(r.getHours()).padStart(2,"0"),p=String(r.getMinutes()).padStart(2,"0"),g=String(r.getSeconds()).padStart(2,"0");return i.replace("yyyy",s.toString()).replace("MM",l).replace("dd",c).replace("HH",f).replace("mm",p).replace("ss",g)}const iw=_.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; +`,sw=_.div` + background: ${({theme:r})=>r.colors.background.primary}; + border-radius: 8px; + width: 500px; + max-width: 90%; + padding: 24px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); +`,lw=_.div` + display: flex; + align-items: center; + margin-bottom: 16px; +`,uw=_.div` + color: ${({theme:r})=>r.colors.status.error}; + font-size: 24px; + margin-right: 12px; +`,aw=_.h3` + color: ${({theme:r})=>r.colors.text.primary}; + margin: 0; + font-size: 18px; +`,cw=_.div` + background: ${({theme:r})=>r.colors.background.tertiary}; + color: ${({theme:r})=>r.colors.text.muted}; + padding: 2px 8px; + border-radius: 4px; + font-size: 14px; + margin-left: auto; +`,fw=_.p` + color: ${({theme:r})=>r.colors.text.secondary}; + margin-bottom: 20px; + line-height: 1.5; + font-weight: 500; +`,dw=_.div` + margin-bottom: 20px; + background: ${({theme:r})=>r.colors.background.secondary}; + border-radius: 6px; + padding: 12px; +`,wo=_.div` + display: flex; + margin-bottom: 8px; + font-size: 14px; +`,xo=_.span` + color: ${({theme:r})=>r.colors.text.muted}; + min-width: 100px; +`,So=_.span` + color: ${({theme:r})=>r.colors.text.secondary}; + word-break: break-word; +`,pw=_.button` + background: ${({theme:r})=>r.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:r})=>r.colors.brand.hover}; + } +`;function hw({isOpen:r,onClose:i,error:s}){var T,I;if(!r)return null;const l=(T=s==null?void 0:s.response)==null?void 0:T.data,c=(l==null?void 0:l.status)||((I=s==null?void 0:s.response)==null?void 0:I.status)||"오류",f=(l==null?void 0:l.code)||"",p=(l==null?void 0:l.message)||(s==null?void 0:s.message)||"알 수 없는 오류가 발생했습니다.",g=l!=null&&l.timestamp?new Date(l.timestamp):new Date,x=ow(g),v=(l==null?void 0:l.exceptionType)||"",S=(l==null?void 0:l.details)||{},A=(l==null?void 0:l.requestId)||"";return h.jsx(iw,{onClick:i,children:h.jsxs(sw,{onClick:R=>R.stopPropagation(),children:[h.jsxs(lw,{children:[h.jsx(uw,{children:"⚠️"}),h.jsx(aw,{children:"오류가 발생했습니다"}),h.jsxs(cw,{children:[c,f?` (${f})`:""]})]}),h.jsx(fw,{children:p}),h.jsxs(dw,{children:[h.jsxs(wo,{children:[h.jsx(xo,{children:"시간:"}),h.jsx(So,{children:x})]}),A&&h.jsxs(wo,{children:[h.jsx(xo,{children:"요청 ID:"}),h.jsx(So,{children:A})]}),f&&h.jsxs(wo,{children:[h.jsx(xo,{children:"에러 코드:"}),h.jsx(So,{children:f})]}),v&&h.jsxs(wo,{children:[h.jsx(xo,{children:"예외 유형:"}),h.jsx(So,{children:v})]}),Object.keys(S).length>0&&h.jsxs(wo,{children:[h.jsx(xo,{children:"상세 정보:"}),h.jsx(So,{children:Object.entries(S).map(([R,C])=>h.jsxs("div",{children:[R,": ",String(C)]},R))})]})]}),h.jsx(pw,{onClick:i,children:"확인"})]})})}const mw=_.div` + width: 240px; + background: ${ee.colors.background.secondary}; + border-left: 1px solid ${ee.colors.border.primary}; +`,gw=_.div` + padding: 16px; + font-size: 14px; + font-weight: bold; + color: ${ee.colors.text.muted}; + text-transform: uppercase; +`,yw=_.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${ee.colors.text.muted}; +`,vw=_(Tr)` + margin-right: 12px; +`;_(rn)``;const ww=_.div` + display: flex; + align-items: center; +`;function xw({member:r}){var l,c,f;const{binaryContents:i,fetchBinaryContent:s}=Yn();return ie.useEffect(()=>{var p;(p=r.profile)!=null&&p.id&&!i[r.profile.id]&&s(r.profile.id)},[(l=r.profile)==null?void 0:l.id,i,s]),h.jsxs(yw,{children:[h.jsxs(vw,{children:[h.jsx(rn,{src:(c=r.profile)!=null&&c.id&&((f=i[r.profile.id])==null?void 0:f.url)||zt,alt:r.username}),h.jsx(Io,{$online:r.online})]}),h.jsx(ww,{children:r.username})]})}function Sw(){const r=nn(c=>c.users),i=nn(c=>c.fetchUsers),s=vt(c=>c.currentUserId);ie.useEffect(()=>{i()},[i]);const l=[...r].sort((c,f)=>c.id===s?-1:f.id===s?1:c.online&&!f.online?-1:!c.online&&f.online?1:c.username.localeCompare(f.username));return h.jsxs(mw,{children:[h.jsxs(gw,{children:["멤버 목록 - ",r.length]}),l.map(c=>h.jsx(xw,{member:c},c.id))]})}function Ew(){const r=vt(C=>C.currentUserId),i=vt(C=>C.logout),s=nn(C=>C.users),{fetchUsers:l,updateUserStatus:c}=nn(),[f,p]=ie.useState(null),[g,x]=ie.useState(null),[v,S]=ie.useState(!1),[A,T]=ie.useState(!0),I=r?s.find(C=>C.id===r):null;ie.useEffect(()=>{(async()=>{try{if(r)try{await c(r),await l()}catch(N){console.warn("사용자 상태 업데이트 실패. 로그아웃합니다.",N),i()}}catch(N){console.error("초기화 오류:",N)}finally{T(!1)}})()},[r,c,l,i]),ie.useEffect(()=>{const C=V=>{x(V),S(!0)},N=()=>{i()},H=as.on("api-error",C),U=as.on("auth-error",N);return()=>{H("api-error",C),U("auth-error",N)}},[i]),ie.useEffect(()=>{let C;if(r){c(r),C=setInterval(()=>{c(r)},3e4);const N=setInterval(()=>{l()},6e4);return()=>{clearInterval(C),clearInterval(N)}}},[r,l,c]);const R=()=>{S(!1),x(null)};return A?h.jsx(Cd,{theme:ee,children:h.jsx(kw,{children:h.jsx(jw,{})})}):h.jsxs(Cd,{theme:ee,children:[I?h.jsxs(Cw,{children:[h.jsx(p1,{currentUser:I,activeChannel:f,onChannelSelect:p}),h.jsx(rw,{channel:f}),h.jsx(Sw,{})]}):h.jsx(h0,{isOpen:!0,onClose:()=>{}}),h.jsx(hw,{isOpen:v,onClose:R,error:g})]})}const Cw=_.div` + display: flex; + height: 100vh; + width: 100vw; + position: relative; +`,kw=_.div` + display: flex; + justify-content: center; + align-items: center; + height: 100vh; + width: 100vw; + background-color: ${({theme:r})=>r.colors.background.primary}; +`,jw=_.div` + width: 40px; + height: 40px; + border: 4px solid ${({theme:r})=>r.colors.background.tertiary}; + border-top: 4px solid ${({theme:r})=>r.colors.brand.primary}; + border-radius: 50%; + animation: spin 1s linear infinite; + + @keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } + } +`,lh=document.getElementById("root");if(!lh)throw new Error("Root element not found");hg.createRoot(lh).render(h.jsx(ie.StrictMode,{children:h.jsx(Ew,{})})); 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/assets/index-pvm8va9e.js b/src/main/resources/static/assets/index-pvm8va9e.js new file mode 100644 index 000000000..b43a85536 --- /dev/null +++ b/src/main/resources/static/assets/index-pvm8va9e.js @@ -0,0 +1,1349 @@ +var xg=Object.defineProperty;var wg=(r,i,s)=>i in r?xg(r,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[i]=s;var sf=(r,i,s)=>wg(r,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 p of d.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).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 Sg(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var wa={exports:{}},vo={},Sa={exports:{}},pe={};/** + * @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 lf;function Cg(){if(lf)return pe;lf=1;var r=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"),p=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),j=Symbol.iterator;function R(C){return C===null||typeof C!="object"?null:(C=j&&C[j]||C["@@iterator"],typeof C=="function"?C:null)}var L={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T=Object.assign,O={};function _(C,D,le){this.props=C,this.context=D,this.refs=O,this.updater=le||L}_.prototype.isReactComponent={},_.prototype.setState=function(C,D){if(typeof C!="object"&&typeof C!="function"&&C!=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,C,D,"setState")},_.prototype.forceUpdate=function(C){this.updater.enqueueForceUpdate(this,C,"forceUpdate")};function b(){}b.prototype=_.prototype;function U(C,D,le){this.props=C,this.context=D,this.refs=O,this.updater=le||L}var B=U.prototype=new b;B.constructor=U,T(B,_.prototype),B.isPureReactComponent=!0;var W=Array.isArray,I=Object.prototype.hasOwnProperty,M={current:null},V={key:!0,ref:!0,__self:!0,__source:!0};function ne(C,D,le){var ue,he={},fe=null,Ce=null;if(D!=null)for(ue in D.ref!==void 0&&(Ce=D.ref),D.key!==void 0&&(fe=""+D.key),D)I.call(D,ue)&&!V.hasOwnProperty(ue)&&(he[ue]=D[ue]);var ge=arguments.length-2;if(ge===1)he.children=le;else if(1>>1,D=Y[C];if(0>>1;Cc(he,Q))fec(Ce,he)?(Y[C]=Ce,Y[fe]=Q,C=fe):(Y[C]=he,Y[ue]=Q,C=ue);else if(fec(Ce,Q))Y[C]=Ce,Y[fe]=Q,C=fe;else break e}}return te}function c(Y,te){var Q=Y.sortIndex-te.sortIndex;return Q!==0?Q:Y.id-te.id}if(typeof performance=="object"&&typeof performance.now=="function"){var d=performance;r.unstable_now=function(){return d.now()}}else{var p=Date,g=p.now();r.unstable_now=function(){return p.now()-g}}var w=[],v=[],S=1,j=null,R=3,L=!1,T=!1,O=!1,_=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,U=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function B(Y){for(var te=s(v);te!==null;){if(te.callback===null)l(v);else if(te.startTime<=Y)l(v),te.sortIndex=te.expirationTime,i(w,te);else break;te=s(v)}}function W(Y){if(O=!1,B(Y),!T)if(s(w)!==null)T=!0,Ue(I);else{var te=s(v);te!==null&&je(W,te.startTime-Y)}}function I(Y,te){T=!1,O&&(O=!1,b(ne),ne=-1),L=!0;var Q=R;try{for(B(te),j=s(w);j!==null&&(!(j.expirationTime>te)||Y&&!ie());){var C=j.callback;if(typeof C=="function"){j.callback=null,R=j.priorityLevel;var D=C(j.expirationTime<=te);te=r.unstable_now(),typeof D=="function"?j.callback=D:j===s(w)&&l(w),B(te)}else l(w);j=s(w)}if(j!==null)var le=!0;else{var ue=s(v);ue!==null&&je(W,ue.startTime-te),le=!1}return le}finally{j=null,R=Q,L=!1}}var M=!1,V=null,ne=-1,ye=5,Ie=-1;function ie(){return!(r.unstable_now()-IeY||125C?(Y.sortIndex=Q,i(v,Y),s(w)===null&&Y===s(v)&&(O?(b(ne),ne=-1):O=!0,je(W,Q-C))):(Y.sortIndex=D,i(w,Y),T||L||(T=!0,Ue(I))),Y},r.unstable_shouldYield=ie,r.unstable_wrapCallback=function(Y){var te=R;return function(){var Q=R;R=te;try{return Y.apply(this,arguments)}finally{R=Q}}}}(Ea)),Ea}var ff;function Ag(){return ff||(ff=1,ka.exports=jg()),ka.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 pf;function Rg(){if(pf)return dt;pf=1;var r=tu(),i=Ag();function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),w=Object.prototype.hasOwnProperty,v=/^[: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 R(e){return w.call(j,e)?!0:w.call(S,e)?!1:v.test(e)?j[e]=!0:(S[e]=!0,!1)}function L(e,t,n,o){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function T(e,t,n,o){if(t===null||typeof t>"u"||L(e,t,n,o))return!0;if(o)return!1;if(n!==null)switch(n.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 O(e,t,n,o,a,u,f){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=u,this.removeEmptyString=f}var _={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){_[e]=new O(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 O(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){_[e]=new O(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){_[e]=new O(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 O(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){_[e]=new O(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){_[e]=new O(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){_[e]=new O(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){_[e]=new O(e,5,!1,e.toLowerCase(),null,!1,!1)});var b=/[\-:]([a-z])/g;function U(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(b,U);_[t]=new O(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(b,U);_[t]=new O(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(b,U);_[t]=new O(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){_[e]=new O(e,1,!1,e.toLowerCase(),null,!1,!1)}),_.xlinkHref=new O("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){_[e]=new O(e,1,!1,e.toLowerCase(),null,!0,!0)});function B(e,t,n,o){var a=_.hasOwnProperty(t)?_[t]:null;(a!==null?a.type!==0:o||!(2m||a[f]!==u[m]){var y=` +`+a[f].replace(" at new "," at ");return e.displayName&&y.includes("")&&(y=y.replace("",e.displayName)),y}while(1<=f&&0<=m);break}}}finally{le=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?D(e):""}function he(e){switch(e.tag){case 5:return D(e.type);case 16:return D("Lazy");case 13:return D("Suspense");case 19:return D("SuspenseList");case 0:case 2:case 15:return e=ue(e.type,!1),e;case 11:return e=ue(e.type.render,!1),e;case 1:return e=ue(e.type,!0),e;default:return""}}function fe(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 V:return"Fragment";case M:return"Portal";case ye:return"Profiler";case ne:return"StrictMode";case me:return"Suspense";case _e:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ie:return(e.displayName||"Context")+".Consumer";case Ie:return(e._context.displayName||"Context")+".Provider";case de:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Se:return t=e.displayName||null,t!==null?t:fe(e.type)||"Memo";case Ue:t=e._payload,e=e._init;try{return fe(e(t))}catch{}}return null}function Ce(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 fe(t);case 8:return t===ne?"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 ge(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 Ge(e){var t=xe(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,u=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(f){o=""+f,u.call(this,f)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return o},setValue:function(f){o=""+f},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Yt(e){e._valueTracker||(e._valueTracker=Ge(e))}function Tt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),o="";return e&&(o=xe(e)?e.checked?"true":"false":e.value),e=o,e!==n?(t.setValue(e),!0):!1}function zo(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 Rs(e,t){var n=t.checked;return Q({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function fu(e,t){var n=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;n=ge(t.value!=null?t.value:n),e._wrapperState={initialChecked:o,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function pu(e,t){t=t.checked,t!=null&&B(e,"checked",t,!1)}function Ps(e,t){pu(e,t);var n=ge(t.value),o=t.type;if(n!=null)o==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ts(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ts(e,t.type,ge(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function hu(e,t,n){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,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ts(e,t,n){(t!=="number"||zo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Or=Array.isArray;function Qn(e,t,n,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=$o.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Mr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Lr={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},Eh=["Webkit","ms","Moz","O"];Object.keys(Lr).forEach(function(e){Eh.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Lr[t]=Lr[e]})});function wu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Lr.hasOwnProperty(e)&&Lr[e]?(""+t).trim():t+"px"}function Su(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var o=n.indexOf("--")===0,a=wu(n,t[n],o);n==="float"&&(n="cssFloat"),o?e.setProperty(n,a):e[n]=a}}var jh=Q({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 Os(e,t){if(t){if(jh[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 Ms(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 Ls=null;function Is(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ds=null,Gn=null,Kn=null;function Cu(e){if(e=no(e)){if(typeof Ds!="function")throw Error(s(280));var t=e.stateNode;t&&(t=li(t),Ds(e.stateNode,e.type,t))}}function ku(e){Gn?Kn?Kn.push(e):Kn=[e]:Gn=e}function Eu(){if(Gn){var e=Gn,t=Kn;if(Kn=Gn=null,Cu(e),t)for(e=0;e>>=0,e===0?32:31-(Dh(e)/zh|0)|0}var Ho=64,Vo=4194304;function $r(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 Wo(e,t){var n=e.pendingLanes;if(n===0)return 0;var o=0,a=e.suspendedLanes,u=e.pingedLanes,f=n&268435455;if(f!==0){var m=f&~a;m!==0?o=$r(m):(u&=f,u!==0&&(o=$r(u)))}else f=n&~a,f!==0?o=$r(f):u!==0&&(o=$r(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|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0n;n++)t.push(e);return t}function Fr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-_t(t),e[t]=n}function bh(e,t){var n=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=qr),Ju=" ",Zu=!1;function ec(e,t){switch(e){case"keyup":return mm.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function tc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Zn=!1;function ym(e,t){switch(e){case"compositionend":return tc(t);case"keypress":return t.which!==32?null:(Zu=!0,Ju);case"textInput":return e=t.data,e===Ju&&Zu?null:e;default:return null}}function vm(e,t){if(Zn)return e==="compositionend"||!el&&ec(e,t)?(e=Yu(),Ko=Qs=an=null,Zn=!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:n,offset:t-e};e=o}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=ac(n)}}function cc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?cc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function dc(){for(var e=window,t=zo();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=zo(e.document)}return t}function rl(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 Rm(e){var t=dc(),n=e.focusedElem,o=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&cc(n.ownerDocument.documentElement,n)){if(o!==null&&rl(n)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=n.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=uc(n,u);var f=uc(n,o);a&&f&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==f.node||e.focusOffset!==f.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),u>o?(e.addRange(t),e.extend(f.node,f.offset)):(t.setEnd(f.node,f.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,er=null,ol=null,Xr=null,il=!1;function fc(e,t,n){var o=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;il||er==null||er!==zo(o)||(o=er,"selectionStart"in o&&rl(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}),Xr&&Kr(Xr,o)||(Xr=o,o=oi(ol,"onSelect"),0ir||(e.current=yl[ir],yl[ir]=null,ir--)}function Ae(e,t){ir++,yl[ir]=e.current,e.current=t}var fn={},Je=dn(fn),st=dn(!1),Tn=fn;function sr(e,t){var n=e.type.contextTypes;if(!n)return fn;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},u;for(u in n)a[u]=t[u];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function lt(e){return e=e.childContextTypes,e!=null}function ai(){Pe(st),Pe(Je)}function Rc(e,t,n){if(Je.current!==fn)throw Error(s(168));Ae(Je,t),Ae(st,n)}function Pc(e,t,n){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return n;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(s(108,Ce(e)||"Unknown",a));return Q({},n,o)}function ui(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||fn,Tn=Je.current,Ae(Je,e),Ae(st,st.current),!0}function Tc(e,t,n){var o=e.stateNode;if(!o)throw Error(s(169));n?(e=Pc(e,t,Tn),o.__reactInternalMemoizedMergedChildContext=e,Pe(st),Pe(Je),Ae(Je,e)):Pe(st),Ae(st,n)}var Qt=null,ci=!1,vl=!1;function _c(e){Qt===null?Qt=[e]:Qt.push(e)}function Fm(e){ci=!0,_c(e)}function pn(){if(!vl&&Qt!==null){vl=!0;var e=0,t=Ee;try{var n=Qt;for(Ee=1;e>=f,a-=f,Gt=1<<32-_t(t)+a|n<se?(qe=oe,oe=null):qe=oe.sibling;var we=z(E,oe,A[se],H);if(we===null){oe===null&&(oe=qe);break}e&&oe&&we.alternate===null&&t(E,oe),x=u(we,x,se),re===null?ee=we:re.sibling=we,re=we,oe=qe}if(se===A.length)return n(E,oe),Ne&&Nn(E,se),ee;if(oe===null){for(;sese?(qe=oe,oe=null):qe=oe.sibling;var Cn=z(E,oe,we.value,H);if(Cn===null){oe===null&&(oe=qe);break}e&&oe&&Cn.alternate===null&&t(E,oe),x=u(Cn,x,se),re===null?ee=Cn:re.sibling=Cn,re=Cn,oe=qe}if(we.done)return n(E,oe),Ne&&Nn(E,se),ee;if(oe===null){for(;!we.done;se++,we=A.next())we=F(E,we.value,H),we!==null&&(x=u(we,x,se),re===null?ee=we:re.sibling=we,re=we);return Ne&&Nn(E,se),ee}for(oe=o(E,oe);!we.done;se++,we=A.next())we=G(oe,E,se,we.value,H),we!==null&&(e&&we.alternate!==null&&oe.delete(we.key===null?se:we.key),x=u(we,x,se),re===null?ee=we:re.sibling=we,re=we);return e&&oe.forEach(function(vg){return t(E,vg)}),Ne&&Nn(E,se),ee}function $e(E,x,A,H){if(typeof A=="object"&&A!==null&&A.type===V&&A.key===null&&(A=A.props.children),typeof A=="object"&&A!==null){switch(A.$$typeof){case I:e:{for(var ee=A.key,re=x;re!==null;){if(re.key===ee){if(ee=A.type,ee===V){if(re.tag===7){n(E,re.sibling),x=a(re,A.props.children),x.return=E,E=x;break e}}else if(re.elementType===ee||typeof ee=="object"&&ee!==null&&ee.$$typeof===Ue&&Dc(ee)===re.type){n(E,re.sibling),x=a(re,A.props),x.ref=ro(E,re,A),x.return=E,E=x;break e}n(E,re);break}else t(E,re);re=re.sibling}A.type===V?(x=Fn(A.props.children,E.mode,H,A.key),x.return=E,E=x):(H=$i(A.type,A.key,A.props,null,E.mode,H),H.ref=ro(E,x,A),H.return=E,E=H)}return f(E);case M:e:{for(re=A.key;x!==null;){if(x.key===re)if(x.tag===4&&x.stateNode.containerInfo===A.containerInfo&&x.stateNode.implementation===A.implementation){n(E,x.sibling),x=a(x,A.children||[]),x.return=E,E=x;break e}else{n(E,x);break}else t(E,x);x=x.sibling}x=ma(A,E.mode,H),x.return=E,E=x}return f(E);case Ue:return re=A._init,$e(E,x,re(A._payload),H)}if(Or(A))return J(E,x,A,H);if(te(A))return Z(E,x,A,H);hi(E,A)}return typeof A=="string"&&A!==""||typeof A=="number"?(A=""+A,x!==null&&x.tag===6?(n(E,x.sibling),x=a(x,A),x.return=E,E=x):(n(E,x),x=ha(A,E.mode,H),x.return=E,E=x),f(E)):n(E,x)}return $e}var cr=zc(!0),$c=zc(!1),mi=dn(null),gi=null,dr=null,El=null;function jl(){El=dr=gi=null}function Al(e){var t=mi.current;Pe(mi),e._currentValue=t}function Rl(e,t,n){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===n)break;e=e.return}}function fr(e,t){gi=e,El=dr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(at=!0),e.firstContext=null)}function Et(e){var t=e._currentValue;if(El!==e)if(e={context:e,memoizedValue:t,next:null},dr===null){if(gi===null)throw Error(s(308));dr=e,gi.dependencies={lanes:0,firstContext:e}}else dr=dr.next=e;return t}var On=null;function Pl(e){On===null?On=[e]:On.push(e)}function Fc(e,t,n,o){var a=t.interleaved;return a===null?(n.next=n,Pl(t)):(n.next=a.next,a.next=n),t.interleaved=n,Xt(e,o)}function Xt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var hn=!1;function Tl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Bc(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 Jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function mn(e,t,n){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,ve&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Xt(e,n)}return a=o.interleaved,a===null?(t.next=t,Pl(o)):(t.next=a.next,a.next=t),o.interleaved=t,Xt(e,n)}function yi(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,Hs(e,n)}}function bc(e,t){var n=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,n===o)){var a=null,u=null;if(n=n.firstBaseUpdate,n!==null){do{var f={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};u===null?a=u=f:u=u.next=f,n=n.next}while(n!==null);u===null?a=u=t:u=u.next=t}else a=u=t;n={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:u,shared:o.shared,effects:o.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function vi(e,t,n,o){var a=e.updateQueue;hn=!1;var u=a.firstBaseUpdate,f=a.lastBaseUpdate,m=a.shared.pending;if(m!==null){a.shared.pending=null;var y=m,P=y.next;y.next=null,f===null?u=P:f.next=P,f=y;var $=e.alternate;$!==null&&($=$.updateQueue,m=$.lastBaseUpdate,m!==f&&(m===null?$.firstBaseUpdate=P:m.next=P,$.lastBaseUpdate=y))}if(u!==null){var F=a.baseState;f=0,$=P=y=null,m=u;do{var z=m.lane,G=m.eventTime;if((o&z)===z){$!==null&&($=$.next={eventTime:G,lane:0,tag:m.tag,payload:m.payload,callback:m.callback,next:null});e:{var J=e,Z=m;switch(z=t,G=n,Z.tag){case 1:if(J=Z.payload,typeof J=="function"){F=J.call(G,F,z);break e}F=J;break e;case 3:J.flags=J.flags&-65537|128;case 0:if(J=Z.payload,z=typeof J=="function"?J.call(G,F,z):J,z==null)break e;F=Q({},F,z);break e;case 2:hn=!0}}m.callback!==null&&m.lane!==0&&(e.flags|=64,z=a.effects,z===null?a.effects=[m]:z.push(m))}else G={eventTime:G,lane:z,tag:m.tag,payload:m.payload,callback:m.callback,next:null},$===null?(P=$=G,y=F):$=$.next=G,f|=z;if(m=m.next,m===null){if(m=a.shared.pending,m===null)break;z=m,m=z.next,z.next=null,a.lastBaseUpdate=z,a.shared.pending=null}}while(!0);if($===null&&(y=F),a.baseState=y,a.firstBaseUpdate=P,a.lastBaseUpdate=$,t=a.shared.interleaved,t!==null){a=t;do f|=a.lane,a=a.next;while(a!==t)}else u===null&&(a.shared.lanes=0);In|=f,e.lanes=f,e.memoizedState=F}}function Uc(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var o=Ll.transition;Ll.transition={};try{e(!1),t()}finally{Ee=n,Ll.transition=o}}function ld(){return jt().memoizedState}function Hm(e,t,n){var o=xn(e);if(n={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null},ad(e))ud(t,n);else if(n=Fc(e,t,n,o),n!==null){var a=it();Dt(n,e,o,a),cd(n,t,o)}}function Vm(e,t,n){var o=xn(e),a={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null};if(ad(e))ud(t,a);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var f=t.lastRenderedState,m=u(f,n);if(a.hasEagerState=!0,a.eagerState=m,Nt(m,f)){var y=t.interleaved;y===null?(a.next=a,Pl(t)):(a.next=y.next,y.next=a),t.interleaved=a;return}}catch{}finally{}n=Fc(e,t,a,o),n!==null&&(a=it(),Dt(n,e,o,a),cd(n,t,o))}}function ad(e){var t=e.alternate;return e===Le||t!==null&&t===Le}function ud(e,t){lo=Si=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function cd(e,t,n){if(n&4194240){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,Hs(e,n)}}var Ei={readContext:Et,useCallback:Ze,useContext:Ze,useEffect:Ze,useImperativeHandle:Ze,useInsertionEffect:Ze,useLayoutEffect:Ze,useMemo:Ze,useReducer:Ze,useRef:Ze,useState:Ze,useDebugValue:Ze,useDeferredValue:Ze,useTransition:Ze,useMutableSource:Ze,useSyncExternalStore:Ze,useId:Ze,unstable_isNewReconciler:!1},Wm={readContext:Et,useCallback:function(e,t){return Ut().memoizedState=[e,t===void 0?null:t],e},useContext:Et,useEffect:Zc,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ci(4194308,4,nd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ci(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ci(4,2,e,t)},useMemo:function(e,t){var n=Ut();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var o=Ut();return t=n!==void 0?n(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=Hm.bind(null,Le,e),[o.memoizedState,e]},useRef:function(e){var t=Ut();return e={current:e},t.memoizedState=e},useState:Xc,useDebugValue:bl,useDeferredValue:function(e){return Ut().memoizedState=e},useTransition:function(){var e=Xc(!1),t=e[0];return e=Um.bind(null,e[1]),Ut().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var o=Le,a=Ut();if(Ne){if(n===void 0)throw Error(s(407));n=n()}else{if(n=t(),Ye===null)throw Error(s(349));Ln&30||Yc(o,t,n)}a.memoizedState=n;var u={value:n,getSnapshot:t};return a.queue=u,Zc(Qc.bind(null,o,u,e),[e]),o.flags|=2048,co(9,qc.bind(null,o,u,n,t),void 0,null),n},useId:function(){var e=Ut(),t=Ye.identifierPrefix;if(Ne){var n=Kt,o=Gt;n=(o&~(1<<32-_t(o)-1)).toString(32)+n,t=":"+t+"R"+n,n=ao++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=f.createElement(n,{is:o.is}):(e=f.createElement(n),n==="select"&&(f=e,o.multiple?f.multiple=!0:o.size&&(f.size=o.size))):e=f.createElementNS(e,n),e[Bt]=t,e[to]=o,_d(e,t,!1,!1),t.stateNode=e;e:{switch(f=Ms(n,o),n){case"dialog":Re("cancel",e),Re("close",e),a=o;break;case"iframe":case"object":case"embed":Re("load",e),a=o;break;case"video":case"audio":for(a=0;ayr&&(t.flags|=128,o=!0,fo(u,!1),t.lanes=4194304)}else{if(!o)if(e=xi(f),e!==null){if(t.flags|=128,o=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),fo(u,!0),u.tail===null&&u.tailMode==="hidden"&&!f.alternate&&!Ne)return et(t),null}else 2*ze()-u.renderingStartTime>yr&&n!==1073741824&&(t.flags|=128,o=!0,fo(u,!1),t.lanes=4194304);u.isBackwards?(f.sibling=t.child,t.child=f):(n=u.last,n!==null?n.sibling=f:t.child=f,u.last=f)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=ze(),t.sibling=null,n=Me.current,Ae(Me,o?n&1|2:n&1),t):(et(t),null);case 22:case 23:return da(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?yt&1073741824&&(et(t),t.subtreeFlags&6&&(t.flags|=8192)):et(t),null;case 24:return null;case 25:return null}throw Error(s(156,t.tag))}function Zm(e,t){switch(wl(t),t.tag){case 1:return lt(t.type)&&ai(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return pr(),Pe(st),Pe(Je),Ml(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Nl(t),null;case 13:if(Pe(Me),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));ur()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Pe(Me),null;case 4:return pr(),null;case 10:return Al(t.type._context),null;case 22:case 23:return da(),null;case 24:return null;default:return null}}var Pi=!1,tt=!1,eg=typeof WeakSet=="function"?WeakSet:Set,X=null;function mr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(o){De(e,t,o)}else n.current=null}function Zl(e,t,n){try{n()}catch(o){De(e,t,o)}}var Md=!1;function tg(e,t){if(dl=Qo,e=dc(),rl(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var o=n.getSelection&&n.getSelection();if(o&&o.rangeCount!==0){n=o.anchorNode;var a=o.anchorOffset,u=o.focusNode;o=o.focusOffset;try{n.nodeType,u.nodeType}catch{n=null;break e}var f=0,m=-1,y=-1,P=0,$=0,F=e,z=null;t:for(;;){for(var G;F!==n||a!==0&&F.nodeType!==3||(m=f+a),F!==u||o!==0&&F.nodeType!==3||(y=f+o),F.nodeType===3&&(f+=F.nodeValue.length),(G=F.firstChild)!==null;)z=F,F=G;for(;;){if(F===e)break t;if(z===n&&++P===a&&(m=f),z===u&&++$===o&&(y=f),(G=F.nextSibling)!==null)break;F=z,z=F.parentNode}F=G}n=m===-1||y===-1?null:{start:m,end:y}}else n=null}n=n||{start:0,end:0}}else n=null;for(fl={focusedElem:e,selectionRange:n},Qo=!1,X=t;X!==null;)if(t=X,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,X=e;else for(;X!==null;){t=X;try{var J=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(J!==null){var Z=J.memoizedProps,$e=J.memoizedState,E=t.stateNode,x=E.getSnapshotBeforeUpdate(t.elementType===t.type?Z:Mt(t.type,Z),$e);E.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var A=t.stateNode.containerInfo;A.nodeType===1?A.textContent="":A.nodeType===9&&A.documentElement&&A.removeChild(A.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(s(163))}}catch(H){De(t,t.return,H)}if(e=t.sibling,e!==null){e.return=t.return,X=e;break}X=t.return}return J=Md,Md=!1,J}function po(e,t,n){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&&Zl(t,n,u)}a=a.next}while(a!==o)}}function Ti(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var o=n.create;n.destroy=o()}n=n.next}while(n!==t)}}function ea(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ld(e){var t=e.alternate;t!==null&&(e.alternate=null,Ld(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Bt],delete t[to],delete t[gl],delete t[zm],delete t[$m])),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 Id(e){return e.tag===5||e.tag===3||e.tag===4}function Dd(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Id(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 ta(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=si));else if(o!==4&&(e=e.child,e!==null))for(ta(e,t,n),e=e.sibling;e!==null;)ta(e,t,n),e=e.sibling}function na(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(na(e,t,n),e=e.sibling;e!==null;)na(e,t,n),e=e.sibling}var Ke=null,Lt=!1;function gn(e,t,n){for(n=n.child;n!==null;)zd(e,t,n),n=n.sibling}function zd(e,t,n){if(Ft&&typeof Ft.onCommitFiberUnmount=="function")try{Ft.onCommitFiberUnmount(Uo,n)}catch{}switch(n.tag){case 5:tt||mr(n,t);case 6:var o=Ke,a=Lt;Ke=null,gn(e,t,n),Ke=o,Lt=a,Ke!==null&&(Lt?(e=Ke,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ke.removeChild(n.stateNode));break;case 18:Ke!==null&&(Lt?(e=Ke,n=n.stateNode,e.nodeType===8?ml(e.parentNode,n):e.nodeType===1&&ml(e,n),Vr(e)):ml(Ke,n.stateNode));break;case 4:o=Ke,a=Lt,Ke=n.stateNode.containerInfo,Lt=!0,gn(e,t,n),Ke=o,Lt=a;break;case 0:case 11:case 14:case 15:if(!tt&&(o=n.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var u=a,f=u.destroy;u=u.tag,f!==void 0&&(u&2||u&4)&&Zl(n,t,f),a=a.next}while(a!==o)}gn(e,t,n);break;case 1:if(!tt&&(mr(n,t),o=n.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=n.memoizedProps,o.state=n.memoizedState,o.componentWillUnmount()}catch(m){De(n,t,m)}gn(e,t,n);break;case 21:gn(e,t,n);break;case 22:n.mode&1?(tt=(o=tt)||n.memoizedState!==null,gn(e,t,n),tt=o):gn(e,t,n);break;default:gn(e,t,n)}}function $d(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new eg),t.forEach(function(o){var a=cg.bind(null,e,o);n.has(o)||(n.add(o),o.then(a,a))})}}function It(e,t){var n=t.deletions;if(n!==null)for(var o=0;oa&&(a=f),o&=~u}if(o=a,o=ze()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*rg(o/1960))-o,10e?16:e,vn===null)var o=!1;else{if(e=vn,vn=null,Li=0,ve&6)throw Error(s(331));var a=ve;for(ve|=4,X=e.current;X!==null;){var u=X,f=u.child;if(X.flags&16){var m=u.deletions;if(m!==null){for(var y=0;yze()-ia?zn(e,0):oa|=n),ct(e,t)}function Xd(e,t){t===0&&(e.mode&1?(t=Vo,Vo<<=1,!(Vo&130023424)&&(Vo=4194304)):t=1);var n=it();e=Xt(e,t),e!==null&&(Fr(e,t,n),ct(e,n))}function ug(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Xd(e,n)}function cg(e,t){var n=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(s(314))}o!==null&&o.delete(t),Xd(e,n)}var Jd;Jd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||st.current)at=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return at=!1,Xm(e,t,n);at=!!(e.flags&131072)}else at=!1,Ne&&t.flags&1048576&&Nc(t,fi,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;Ri(e,t),e=t.pendingProps;var a=sr(t,Je.current);fr(t,n),a=Dl(null,t,o,e,a,n);var u=zl();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,lt(o)?(u=!0,ui(t)):u=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Tl(t),a.updater=ji,t.stateNode=a,a._reactInternals=t,Hl(t,o,e,n),t=ql(null,t,o,!0,u,n)):(t.tag=0,Ne&&u&&xl(t),ot(null,t,a,n),t=t.child),t;case 16:o=t.elementType;e:{switch(Ri(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=fg(o),e=Mt(o,e),a){case 0:t=Yl(null,t,o,e,n);break e;case 1:t=Ed(null,t,o,e,n);break e;case 11:t=xd(null,t,o,e,n);break e;case 14:t=wd(null,t,o,Mt(o.type,e),n);break e}throw Error(s(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),Yl(e,t,o,a,n);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),Ed(e,t,o,a,n);case 3:e:{if(jd(t),e===null)throw Error(s(387));o=t.pendingProps,u=t.memoizedState,a=u.element,Bc(e,t),vi(t,o,null,n);var f=t.memoizedState;if(o=f.element,u.isDehydrated)if(u={element:o,isDehydrated:!1,cache:f.cache,pendingSuspenseBoundaries:f.pendingSuspenseBoundaries,transitions:f.transitions},t.updateQueue.baseState=u,t.memoizedState=u,t.flags&256){a=hr(Error(s(423)),t),t=Ad(e,t,o,n,a);break e}else if(o!==a){a=hr(Error(s(424)),t),t=Ad(e,t,o,n,a);break e}else for(gt=cn(t.stateNode.containerInfo.firstChild),mt=t,Ne=!0,Ot=null,n=$c(t,null,o,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ur(),o===a){t=Zt(e,t,n);break e}ot(e,t,o,n)}t=t.child}return t;case 5:return Hc(t),e===null&&Cl(t),o=t.type,a=t.pendingProps,u=e!==null?e.memoizedProps:null,f=a.children,pl(o,a)?f=null:u!==null&&pl(o,u)&&(t.flags|=32),kd(e,t),ot(e,t,f,n),t.child;case 6:return e===null&&Cl(t),null;case 13:return Rd(e,t,n);case 4:return _l(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=cr(t,null,o,n):ot(e,t,o,n),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),xd(e,t,o,a,n);case 7:return ot(e,t,t.pendingProps,n),t.child;case 8:return ot(e,t,t.pendingProps.children,n),t.child;case 12:return ot(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,u=t.memoizedProps,f=a.value,Ae(mi,o._currentValue),o._currentValue=f,u!==null)if(Nt(u.value,f)){if(u.children===a.children&&!st.current){t=Zt(e,t,n);break e}}else for(u=t.child,u!==null&&(u.return=t);u!==null;){var m=u.dependencies;if(m!==null){f=u.child;for(var y=m.firstContext;y!==null;){if(y.context===o){if(u.tag===1){y=Jt(-1,n&-n),y.tag=2;var P=u.updateQueue;if(P!==null){P=P.shared;var $=P.pending;$===null?y.next=y:(y.next=$.next,$.next=y),P.pending=y}}u.lanes|=n,y=u.alternate,y!==null&&(y.lanes|=n),Rl(u.return,n,t),m.lanes|=n;break}y=y.next}}else if(u.tag===10)f=u.type===t.type?null:u.child;else if(u.tag===18){if(f=u.return,f===null)throw Error(s(341));f.lanes|=n,m=f.alternate,m!==null&&(m.lanes|=n),Rl(f,n,t),f=u.sibling}else f=u.child;if(f!==null)f.return=u;else for(f=u;f!==null;){if(f===t){f=null;break}if(u=f.sibling,u!==null){u.return=f.return,f=u;break}f=f.return}u=f}ot(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,fr(t,n),a=Et(a),o=o(a),t.flags|=1,ot(e,t,o,n),t.child;case 14:return o=t.type,a=Mt(o,t.pendingProps),a=Mt(o.type,a),wd(e,t,o,a,n);case 15:return Sd(e,t,t.type,t.pendingProps,n);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Mt(o,a),Ri(e,t),t.tag=1,lt(o)?(e=!0,ui(t)):e=!1,fr(t,n),fd(t,o,a),Hl(t,o,a,n),ql(null,t,o,!0,e,n);case 19:return Td(e,t,n);case 22:return Cd(e,t,n)}throw Error(s(156,t.tag))};function Zd(e,t){return Ou(e,t)}function dg(e,t,n,o){this.tag=e,this.key=n,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 Rt(e,t,n,o){return new dg(e,t,n,o)}function pa(e){return e=e.prototype,!(!e||!e.isReactComponent)}function fg(e){if(typeof e=="function")return pa(e)?1:0;if(e!=null){if(e=e.$$typeof,e===de)return 11;if(e===Se)return 14}return 2}function Sn(e,t){var n=e.alternate;return n===null?(n=Rt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function $i(e,t,n,o,a,u){var f=2;if(o=e,typeof e=="function")pa(e)&&(f=1);else if(typeof e=="string")f=5;else e:switch(e){case V:return Fn(n.children,a,u,t);case ne:f=8,a|=8;break;case ye:return e=Rt(12,n,t,a|2),e.elementType=ye,e.lanes=u,e;case me:return e=Rt(13,n,t,a),e.elementType=me,e.lanes=u,e;case _e:return e=Rt(19,n,t,a),e.elementType=_e,e.lanes=u,e;case je:return Fi(n,a,u,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Ie:f=10;break e;case ie:f=9;break e;case de:f=11;break e;case Se:f=14;break e;case Ue:f=16,o=null;break e}throw Error(s(130,e==null?e:typeof e,""))}return t=Rt(f,n,t,a),t.elementType=e,t.type=o,t.lanes=u,t}function Fn(e,t,n,o){return e=Rt(7,e,o,t),e.lanes=n,e}function Fi(e,t,n,o){return e=Rt(22,e,o,t),e.elementType=je,e.lanes=n,e.stateNode={isHidden:!1},e}function ha(e,t,n){return e=Rt(6,e,null,t),e.lanes=n,e}function ma(e,t,n){return t=Rt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function pg(e,t,n,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=Us(0),this.expirationTimes=Us(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Us(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function ga(e,t,n,o,a,u,f,m,y){return e=new pg(e,t,n,m,y),t===1?(t=1,u===!0&&(t|=8)):t=0,u=Rt(3,null,null,t),e.current=u,u.stateNode=e,u.memoizedState={element:o,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tl(u),e}function hg(e,t,n){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(i){console.error(i)}}return r(),Ca.exports=Rg(),Ca.exports}var mf;function Tg(){if(mf)return Yi;mf=1;var r=Pg();return Yi.createRoot=r.createRoot,Yi.hydrateRoot=r.hydrateRoot,Yi}var _g=Tg(),rt=function(){return rt=Object.assign||function(i){for(var s,l=1,c=arguments.length;l0?Qe(Rr,--Pt):0,kr--,Be===10&&(kr=1,gs--),Be}function zt(){return Be=Pt2||Ba(Be)>3?"":" "}function Bg(r,i){for(;--i&&zt()&&!(Be<48||Be>102||Be>57&&Be<65||Be>70&&Be<97););return vs(r,ts()+(i<6&&Un()==32&&zt()==32))}function ba(r){for(;zt();)switch(Be){case r:return Pt;case 34:case 39:r!==34&&r!==39&&ba(Be);break;case 40:r===41&&ba(r);break;case 92:zt();break}return Pt}function bg(r,i){for(;zt()&&r+Be!==57;)if(r+Be===84&&Un()===47)break;return"/*"+vs(i,Pt-1)+"*"+ru(r===47?r:zt())}function Ug(r){for(;!Ba(Un());)zt();return vs(r,Pt)}function Hg(r){return $g(ns("",null,null,null,[""],r=zg(r),0,[0],r))}function ns(r,i,s,l,c,d,p,g,w){for(var v=0,S=0,j=p,R=0,L=0,T=0,O=1,_=1,b=1,U=0,B="",W=c,I=d,M=l,V=B;_;)switch(T=U,U=zt()){case 40:if(T!=108&&Qe(V,j-1)==58){es(V+=ce(ja(U),"&","&\f"),"&\f",mp(v?g[v-1]:0))!=-1&&(b=-1);break}case 34:case 39:case 91:V+=ja(U);break;case 9:case 10:case 13:case 32:V+=Fg(T);break;case 92:V+=Bg(ts()-1,7);continue;case 47:switch(Un()){case 42:case 47:ko(Vg(bg(zt(),ts()),i,s,w),w);break;default:V+="/"}break;case 123*O:g[v++]=Wt(V)*b;case 125*O:case 59:case 0:switch(U){case 0:case 125:_=0;case 59+S:b==-1&&(V=ce(V,/\f/g,"")),L>0&&Wt(V)-j&&ko(L>32?vf(V+";",l,s,j-1,w):vf(ce(V," ","")+";",l,s,j-2,w),w);break;case 59:V+=";";default:if(ko(M=yf(V,i,s,v,S,c,g,B,W=[],I=[],j,d),d),U===123)if(S===0)ns(V,i,M,M,W,d,j,g,I);else switch(R===99&&Qe(V,3)===110?100:R){case 100:case 108:case 109:case 115:ns(r,M,M,l&&ko(yf(r,M,M,0,0,c,g,B,c,W=[],j,I),I),c,I,j,g,l?W:I);break;default:ns(V,M,M,M,[""],I,0,g,I)}}v=S=L=0,O=b=1,B=V="",j=p;break;case 58:j=1+Wt(V),L=T;default:if(O<1){if(U==123)--O;else if(U==125&&O++==0&&Dg()==125)continue}switch(V+=ru(U),U*O){case 38:b=S>0?1:(V+="\f",-1);break;case 44:g[v++]=(Wt(V)-1)*b,b=1;break;case 64:Un()===45&&(V+=ja(zt())),R=Un(),S=j=Wt(B=V+=Ug(ts())),U++;break;case 45:T===45&&Wt(V)==2&&(O=0)}}return d}function yf(r,i,s,l,c,d,p,g,w,v,S,j){for(var R=c-1,L=c===0?d:[""],T=yp(L),O=0,_=0,b=0;O0?L[U]+" "+B:ce(B,/&\f/g,L[U])))&&(w[b++]=W);return ys(r,i,s,c===0?ms:g,w,v,S,j)}function Vg(r,i,s,l){return ys(r,i,s,pp,ru(Ig()),Cr(r,2,-2),0,l)}function vf(r,i,s,l,c){return ys(r,i,s,nu,Cr(r,0,l),Cr(r,l+1,-1),l,c)}function xp(r,i,s){switch(Mg(r,i)){case 5103:return ke+"print-"+r+r;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 ke+r+r;case 4789:return Eo+r+r;case 5349:case 4246:case 4810:case 6968:case 2756:return ke+r+Eo+r+Te+r+r;case 5936:switch(Qe(r,i+11)){case 114:return ke+r+Te+ce(r,/[svh]\w+-[tblr]{2}/,"tb")+r;case 108:return ke+r+Te+ce(r,/[svh]\w+-[tblr]{2}/,"tb-rl")+r;case 45:return ke+r+Te+ce(r,/[svh]\w+-[tblr]{2}/,"lr")+r}case 6828:case 4268:case 2903:return ke+r+Te+r+r;case 6165:return ke+r+Te+"flex-"+r+r;case 5187:return ke+r+ce(r,/(\w+).+(:[^]+)/,ke+"box-$1$2"+Te+"flex-$1$2")+r;case 5443:return ke+r+Te+"flex-item-"+ce(r,/flex-|-self/g,"")+(tn(r,/flex-|baseline/)?"":Te+"grid-row-"+ce(r,/flex-|-self/g,""))+r;case 4675:return ke+r+Te+"flex-line-pack"+ce(r,/align-content|flex-|-self/g,"")+r;case 5548:return ke+r+Te+ce(r,"shrink","negative")+r;case 5292:return ke+r+Te+ce(r,"basis","preferred-size")+r;case 6060:return ke+"box-"+ce(r,"-grow","")+ke+r+Te+ce(r,"grow","positive")+r;case 4554:return ke+ce(r,/([^-])(transform)/g,"$1"+ke+"$2")+r;case 6187:return ce(ce(ce(r,/(zoom-|grab)/,ke+"$1"),/(image-set)/,ke+"$1"),r,"")+r;case 5495:case 3959:return ce(r,/(image-set\([^]*)/,ke+"$1$`$1");case 4968:return ce(ce(r,/(.+:)(flex-)?(.*)/,ke+"box-pack:$3"+Te+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+ke+r+r;case 4200:if(!tn(r,/flex-|baseline/))return Te+"grid-column-align"+Cr(r,i)+r;break;case 2592:case 3360:return Te+ce(r,"template-","")+r;case 4384:case 3616:return s&&s.some(function(l,c){return i=c,tn(l.props,/grid-\w+-end/)})?~es(r+(s=s[i].value),"span",0)?r:Te+ce(r,"-start","")+r+Te+"grid-row-span:"+(~es(s,"span",0)?tn(s,/\d+/):+tn(s,/\d+/)-+tn(r,/\d+/))+";":Te+ce(r,"-start","")+r;case 4896:case 4128:return s&&s.some(function(l){return tn(l.props,/grid-\w+-start/)})?r:Te+ce(ce(r,"-end","-span"),"span ","")+r;case 4095:case 3583:case 4068:case 2532:return ce(r,/(.+)-inline(.+)/,ke+"$1$2")+r;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(r)-1-i>6)switch(Qe(r,i+1)){case 109:if(Qe(r,i+4)!==45)break;case 102:return ce(r,/(.+:)(.+)-([^]+)/,"$1"+ke+"$2-$3$1"+Eo+(Qe(r,i+3)==108?"$3":"$2-$3"))+r;case 115:return~es(r,"stretch",0)?xp(ce(r,"stretch","fill-available"),i,s)+r:r}break;case 5152:case 5920:return ce(r,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(l,c,d,p,g,w,v){return Te+c+":"+d+v+(p?Te+c+"-span:"+(g?w:+w-+d)+v:"")+r});case 4949:if(Qe(r,i+6)===121)return ce(r,":",":"+ke)+r;break;case 6444:switch(Qe(r,Qe(r,14)===45?18:11)){case 120:return ce(r,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+ke+(Qe(r,14)===45?"inline-":"")+"box$3$1"+ke+"$2$3$1"+Te+"$2box$3")+r;case 100:return ce(r,":",":"+Te)+r}break;case 5719:case 2647:case 2135:case 3927:case 2391:return ce(r,"scroll-","scroll-snap-")+r}return r}function us(r,i){for(var s="",l=0;l-1&&!r.return)switch(r.type){case nu:r.return=xp(r.value,r.length,s);return;case hp:return us([kn(r,{value:ce(r.value,"@","@"+ke)})],l);case ms:if(r.length)return Lg(s=r.props,function(c){switch(tn(c,l=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":xr(kn(r,{props:[ce(c,/:(read-\w+)/,":"+Eo+"$1")]})),xr(kn(r,{props:[c]})),Fa(r,{props:gf(s,l)});break;case"::placeholder":xr(kn(r,{props:[ce(c,/:(plac\w+)/,":"+ke+"input-$1")]})),xr(kn(r,{props:[ce(c,/:(plac\w+)/,":"+Eo+"$1")]})),xr(kn(r,{props:[ce(c,/:(plac\w+)/,Te+"input-$1")]})),xr(kn(r,{props:[c]})),Fa(r,{props:gf(s,l)});break}return""})}}var Gg={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},vt={},Er=typeof process<"u"&&vt!==void 0&&(vt.REACT_APP_SC_ATTR||vt.SC_ATTR)||"data-styled",wp="active",Sp="data-styled-version",xs="6.1.14",ou=`/*!sc*/ +`,cs=typeof window<"u"&&"HTMLElement"in window,Kg=!!(typeof SC_DISABLE_SPEEDY=="boolean"?SC_DISABLE_SPEEDY:typeof process<"u"&&vt!==void 0&&vt.REACT_APP_SC_DISABLE_SPEEDY!==void 0&&vt.REACT_APP_SC_DISABLE_SPEEDY!==""?vt.REACT_APP_SC_DISABLE_SPEEDY!=="false"&&vt.REACT_APP_SC_DISABLE_SPEEDY:typeof process<"u"&&vt!==void 0&&vt.SC_DISABLE_SPEEDY!==void 0&&vt.SC_DISABLE_SPEEDY!==""&&vt.SC_DISABLE_SPEEDY!=="false"&&vt.SC_DISABLE_SPEEDY),ws=Object.freeze([]),jr=Object.freeze({});function Xg(r,i,s){return s===void 0&&(s=jr),r.theme!==s.theme&&r.theme||i||s.theme}var Cp=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"]),Jg=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,Zg=/(^-|-$)/g;function xf(r){return r.replace(Jg,"-").replace(Zg,"")}var ey=/(a)(d)/gi,qi=52,wf=function(r){return String.fromCharCode(r+(r>25?39:97))};function Ua(r){var i,s="";for(i=Math.abs(r);i>qi;i=i/qi|0)s=wf(i%qi)+s;return(wf(i%qi)+s).replace(ey,"$1-$2")}var Aa,kp=5381,wr=function(r,i){for(var s=i.length;s;)r=33*r^i.charCodeAt(--s);return r},Ep=function(r){return wr(kp,r)};function ty(r){return Ua(Ep(r)>>>0)}function ny(r){return r.displayName||r.name||"Component"}function Ra(r){return typeof r=="string"&&!0}var jp=typeof Symbol=="function"&&Symbol.for,Ap=jp?Symbol.for("react.memo"):60115,ry=jp?Symbol.for("react.forward_ref"):60112,oy={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},iy={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Rp={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},sy=((Aa={})[ry]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Aa[Ap]=Rp,Aa);function Sf(r){return("type"in(i=r)&&i.type.$$typeof)===Ap?Rp:"$$typeof"in r?sy[r.$$typeof]:oy;var i}var ly=Object.defineProperty,ay=Object.getOwnPropertyNames,Cf=Object.getOwnPropertySymbols,uy=Object.getOwnPropertyDescriptor,cy=Object.getPrototypeOf,kf=Object.prototype;function Pp(r,i,s){if(typeof i!="string"){if(kf){var l=cy(i);l&&l!==kf&&Pp(r,l,s)}var c=ay(i);Cf&&(c=c.concat(Cf(i)));for(var d=Sf(r),p=Sf(i),g=0;g0?" Args: ".concat(i.join(", ")):""))}var dy=function(){function r(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}return r.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 Yn(16,"".concat(i));this.groupSizes=new Uint32Array(d),this.groupSizes.set(l),this.length=d;for(var p=c;p=this.length||this.groupSizes[i]===0)return s;for(var l=this.groupSizes[i],c=this.indexOfGroup(i),d=c+l,p=c;p=0){var l=document.createTextNode(s);return this.element.insertBefore(l,this.nodes[i]||null),this.length++,!0}return!1},r.prototype.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},r.prototype.getRule=function(i){return i0&&(_+="".concat(b,","))}),w+="".concat(T).concat(O,'{content:"').concat(_,'"}').concat(ou)},S=0;S0?".".concat(i):R},S=w.slice();S.push(function(R){R.type===ms&&R.value.includes("&")&&(R.props[0]=R.props[0].replace(Cy,s).replace(l,v))}),p.prefix&&S.push(Qg),S.push(Wg);var j=function(R,L,T,O){L===void 0&&(L=""),T===void 0&&(T=""),O===void 0&&(O="&"),i=O,s=L,l=new RegExp("\\".concat(s,"\\b"),"g");var _=R.replace(ky,""),b=Hg(T||L?"".concat(T," ").concat(L," { ").concat(_," }"):_);p.namespace&&(b=Np(b,p.namespace));var U=[];return us(b,Yg(S.concat(qg(function(B){return U.push(B)})))),U};return j.hash=w.length?w.reduce(function(R,L){return L.name||Yn(15),wr(R,L.name)},kp).toString():"",j}var jy=new _p,Va=Ey(),Op=xt.createContext({shouldForwardProp:void 0,styleSheet:jy,stylis:Va});Op.Consumer;xt.createContext(void 0);function Rf(){return K.useContext(Op)}var Ay=function(){function r(i,s){var l=this;this.inject=function(c,d){d===void 0&&(d=Va);var p=l.name+d.hash;c.hasNameForId(l.id,p)||c.insertRules(l.id,p,d(l.rules,p,"@keyframes"))},this.name=i,this.id="sc-keyframes-".concat(i),this.rules=s,su(this,function(){throw Yn(12,String(l.name))})}return r.prototype.getName=function(i){return i===void 0&&(i=Va),this.name+i.hash},r}(),Ry=function(r){return r>="A"&&r<="Z"};function Pf(r){for(var i="",s=0;s>>0);if(!s.hasNameForId(this.componentId,p)){var g=l(d,".".concat(p),void 0,this.componentId);s.insertRules(this.componentId,p,g)}c=Bn(c,p),this.staticRulesId=p}else{for(var w=wr(this.baseHash,l.hash),v="",S=0;S>>0);s.hasNameForId(this.componentId,L)||s.insertRules(this.componentId,L,l(v,".".concat(L),void 0,this.componentId)),c=Bn(c,L)}}return c},r}(),fs=xt.createContext(void 0);fs.Consumer;function Tf(r){var i=xt.useContext(fs),s=K.useMemo(function(){return function(l,c){if(!l)throw Yn(14);if(Wn(l)){var d=l(c);return d}if(Array.isArray(l)||typeof l!="object")throw Yn(8);return c?rt(rt({},c),l):l}(r.theme,i)},[r.theme,i]);return r.children?xt.createElement(fs.Provider,{value:s},r.children):null}var Pa={};function Ny(r,i,s){var l=iu(r),c=r,d=!Ra(r),p=i.attrs,g=p===void 0?ws:p,w=i.componentId,v=w===void 0?function(W,I){var M=typeof W!="string"?"sc":xf(W);Pa[M]=(Pa[M]||0)+1;var V="".concat(M,"-").concat(ty(xs+M+Pa[M]));return I?"".concat(I,"-").concat(V):V}(i.displayName,i.parentComponentId):w,S=i.displayName,j=S===void 0?function(W){return Ra(W)?"styled.".concat(W):"Styled(".concat(ny(W),")")}(r):S,R=i.displayName&&i.componentId?"".concat(xf(i.displayName),"-").concat(i.componentId):i.componentId||v,L=l&&c.attrs?c.attrs.concat(g).filter(Boolean):g,T=i.shouldForwardProp;if(l&&c.shouldForwardProp){var O=c.shouldForwardProp;if(i.shouldForwardProp){var _=i.shouldForwardProp;T=function(W,I){return O(W,I)&&_(W,I)}}else T=O}var b=new _y(s,R,l?c.componentStyle:void 0);function U(W,I){return function(M,V,ne){var ye=M.attrs,Ie=M.componentStyle,ie=M.defaultProps,de=M.foldedComponentIds,me=M.styledComponentId,_e=M.target,Se=xt.useContext(fs),Ue=Rf(),je=M.shouldForwardProp||Ue.shouldForwardProp,Y=Xg(V,Se,ie)||jr,te=function(he,fe,Ce){for(var ge,xe=rt(rt({},fe),{className:void 0,theme:Ce}),Ge=0;Ge{let i;const s=new Set,l=(v,S)=>{const j=typeof v=="function"?v(i):v;if(!Object.is(j,i)){const R=i;i=S??(typeof j!="object"||j===null)?j:Object.assign({},i,j),s.forEach(L=>L(i,R))}},c=()=>i,g={setState:l,getState:c,getInitialState:()=>w,subscribe:v=>(s.add(v),()=>s.delete(v))},w=i=r(l,c,g);return g},My=r=>r?Of(r):Of,Ly=r=>r;function Iy(r,i=Ly){const s=xt.useSyncExternalStore(r.subscribe,()=>i(r.getState()),()=>i(r.getInitialState()));return xt.useDebugValue(s),s}const Mf=r=>{const i=My(r),s=l=>Iy(i,l);return Object.assign(s,i),s},Pr=r=>r?Mf(r):Mf;function Dp(r,i){return function(){return r.apply(i,arguments)}}const{toString:Dy}=Object.prototype,{getPrototypeOf:lu}=Object,Ss=(r=>i=>{const s=Dy.call(i);return r[s]||(r[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),$t=r=>(r=r.toLowerCase(),i=>Ss(i)===r),Cs=r=>i=>typeof i===r,{isArray:Tr}=Array,No=Cs("undefined");function zy(r){return r!==null&&!No(r)&&r.constructor!==null&&!No(r.constructor)&&wt(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const zp=$t("ArrayBuffer");function $y(r){let i;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?i=ArrayBuffer.isView(r):i=r&&r.buffer&&zp(r.buffer),i}const Fy=Cs("string"),wt=Cs("function"),$p=Cs("number"),ks=r=>r!==null&&typeof r=="object",By=r=>r===!0||r===!1,is=r=>{if(Ss(r)!=="object")return!1;const i=lu(r);return(i===null||i===Object.prototype||Object.getPrototypeOf(i)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},by=$t("Date"),Uy=$t("File"),Hy=$t("Blob"),Vy=$t("FileList"),Wy=r=>ks(r)&&wt(r.pipe),Yy=r=>{let i;return r&&(typeof FormData=="function"&&r instanceof FormData||wt(r.append)&&((i=Ss(r))==="formdata"||i==="object"&&wt(r.toString)&&r.toString()==="[object FormData]"))},qy=$t("URLSearchParams"),[Qy,Gy,Ky,Xy]=["ReadableStream","Request","Response","Headers"].map($t),Jy=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Lo(r,i,{allOwnKeys:s=!1}={}){if(r===null||typeof r>"u")return;let l,c;if(typeof r!="object"&&(r=[r]),Tr(r))for(l=0,c=r.length;l0;)if(c=s[l],i===c.toLowerCase())return c;return null}const bn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Bp=r=>!No(r)&&r!==bn;function Ya(){const{caseless:r}=Bp(this)&&this||{},i={},s=(l,c)=>{const d=r&&Fp(i,c)||c;is(i[d])&&is(l)?i[d]=Ya(i[d],l):is(l)?i[d]=Ya({},l):Tr(l)?i[d]=l.slice():i[d]=l};for(let l=0,c=arguments.length;l(Lo(i,(c,d)=>{s&&wt(c)?r[d]=Dp(c,s):r[d]=c},{allOwnKeys:l}),r),e0=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),t0=(r,i,s,l)=>{r.prototype=Object.create(i.prototype,l),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:i.prototype}),s&&Object.assign(r.prototype,s)},n0=(r,i,s,l)=>{let c,d,p;const g={};if(i=i||{},r==null)return i;do{for(c=Object.getOwnPropertyNames(r),d=c.length;d-- >0;)p=c[d],(!l||l(p,r,i))&&!g[p]&&(i[p]=r[p],g[p]=!0);r=s!==!1&&lu(r)}while(r&&(!s||s(r,i))&&r!==Object.prototype);return i},r0=(r,i,s)=>{r=String(r),(s===void 0||s>r.length)&&(s=r.length),s-=i.length;const l=r.indexOf(i,s);return l!==-1&&l===s},o0=r=>{if(!r)return null;if(Tr(r))return r;let i=r.length;if(!$p(i))return null;const s=new Array(i);for(;i-- >0;)s[i]=r[i];return s},i0=(r=>i=>r&&i instanceof r)(typeof Uint8Array<"u"&&lu(Uint8Array)),s0=(r,i)=>{const l=(r&&r[Symbol.iterator]).call(r);let c;for(;(c=l.next())&&!c.done;){const d=c.value;i.call(r,d[0],d[1])}},l0=(r,i)=>{let s;const l=[];for(;(s=r.exec(i))!==null;)l.push(s);return l},a0=$t("HTMLFormElement"),u0=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,l,c){return l.toUpperCase()+c}),Lf=(({hasOwnProperty:r})=>(i,s)=>r.call(i,s))(Object.prototype),c0=$t("RegExp"),bp=(r,i)=>{const s=Object.getOwnPropertyDescriptors(r),l={};Lo(s,(c,d)=>{let p;(p=i(c,d,r))!==!1&&(l[d]=p||c)}),Object.defineProperties(r,l)},d0=r=>{bp(r,(i,s)=>{if(wt(r)&&["arguments","caller","callee"].indexOf(s)!==-1)return!1;const l=r[s];if(wt(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+"'")})}})},f0=(r,i)=>{const s={},l=c=>{c.forEach(d=>{s[d]=!0})};return Tr(r)?l(r):l(String(r).split(i)),s},p0=()=>{},h0=(r,i)=>r!=null&&Number.isFinite(r=+r)?r:i,Ta="abcdefghijklmnopqrstuvwxyz",If="0123456789",Up={DIGIT:If,ALPHA:Ta,ALPHA_DIGIT:Ta+Ta.toUpperCase()+If},m0=(r=16,i=Up.ALPHA_DIGIT)=>{let s="";const{length:l}=i;for(;r--;)s+=i[Math.random()*l|0];return s};function g0(r){return!!(r&&wt(r.append)&&r[Symbol.toStringTag]==="FormData"&&r[Symbol.iterator])}const y0=r=>{const i=new Array(10),s=(l,c)=>{if(ks(l)){if(i.indexOf(l)>=0)return;if(!("toJSON"in l)){i[c]=l;const d=Tr(l)?[]:{};return Lo(l,(p,g)=>{const w=s(p,c+1);!No(w)&&(d[g]=w)}),i[c]=void 0,d}}return l};return s(r,0)},v0=$t("AsyncFunction"),x0=r=>r&&(ks(r)||wt(r))&&wt(r.then)&&wt(r.catch),Hp=((r,i)=>r?setImmediate:i?((s,l)=>(bn.addEventListener("message",({source:c,data:d})=>{c===bn&&d===s&&l.length&&l.shift()()},!1),c=>{l.push(c),bn.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",wt(bn.postMessage)),w0=typeof queueMicrotask<"u"?queueMicrotask.bind(bn):typeof process<"u"&&process.nextTick||Hp,N={isArray:Tr,isArrayBuffer:zp,isBuffer:zy,isFormData:Yy,isArrayBufferView:$y,isString:Fy,isNumber:$p,isBoolean:By,isObject:ks,isPlainObject:is,isReadableStream:Qy,isRequest:Gy,isResponse:Ky,isHeaders:Xy,isUndefined:No,isDate:by,isFile:Uy,isBlob:Hy,isRegExp:c0,isFunction:wt,isStream:Wy,isURLSearchParams:qy,isTypedArray:i0,isFileList:Vy,forEach:Lo,merge:Ya,extend:Zy,trim:Jy,stripBOM:e0,inherits:t0,toFlatObject:n0,kindOf:Ss,kindOfTest:$t,endsWith:r0,toArray:o0,forEachEntry:s0,matchAll:l0,isHTMLForm:a0,hasOwnProperty:Lf,hasOwnProp:Lf,reduceDescriptors:bp,freezeMethods:d0,toObjectSet:f0,toCamelCase:u0,noop:p0,toFiniteNumber:h0,findKey:Fp,global:bn,isContextDefined:Bp,ALPHABET:Up,generateString:m0,isSpecCompliantForm:g0,toJSONObject:y0,isAsyncFn:v0,isThenable:x0,setImmediate:Hp,asap:w0};function ae(r,i,s,l,c){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,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)}N.inherits(ae,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:N.toJSONObject(this.config),code:this.code,status:this.status}}});const Vp=ae.prototype,Wp={};["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(r=>{Wp[r]={value:r}});Object.defineProperties(ae,Wp);Object.defineProperty(Vp,"isAxiosError",{value:!0});ae.from=(r,i,s,l,c,d)=>{const p=Object.create(Vp);return N.toFlatObject(r,p,function(w){return w!==Error.prototype},g=>g!=="isAxiosError"),ae.call(p,r.message,i,s,l,c),p.cause=r,p.name=r.name,d&&Object.assign(p,d),p};const S0=null;function qa(r){return N.isPlainObject(r)||N.isArray(r)}function Yp(r){return N.endsWith(r,"[]")?r.slice(0,-2):r}function Df(r,i,s){return r?r.concat(i).map(function(c,d){return c=Yp(c),!s&&d?"["+c+"]":c}).join(s?".":""):i}function C0(r){return N.isArray(r)&&!r.some(qa)}const k0=N.toFlatObject(N,{},null,function(i){return/^is[A-Z]/.test(i)});function Es(r,i,s){if(!N.isObject(r))throw new TypeError("target must be an object");i=i||new FormData,s=N.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(O,_){return!N.isUndefined(_[O])});const l=s.metaTokens,c=s.visitor||S,d=s.dots,p=s.indexes,w=(s.Blob||typeof Blob<"u"&&Blob)&&N.isSpecCompliantForm(i);if(!N.isFunction(c))throw new TypeError("visitor must be a function");function v(T){if(T===null)return"";if(N.isDate(T))return T.toISOString();if(!w&&N.isBlob(T))throw new ae("Blob is not supported. Use a Buffer instead.");return N.isArrayBuffer(T)||N.isTypedArray(T)?w&&typeof Blob=="function"?new Blob([T]):Buffer.from(T):T}function S(T,O,_){let b=T;if(T&&!_&&typeof T=="object"){if(N.endsWith(O,"{}"))O=l?O:O.slice(0,-2),T=JSON.stringify(T);else if(N.isArray(T)&&C0(T)||(N.isFileList(T)||N.endsWith(O,"[]"))&&(b=N.toArray(T)))return O=Yp(O),b.forEach(function(B,W){!(N.isUndefined(B)||B===null)&&i.append(p===!0?Df([O],W,d):p===null?O:O+"[]",v(B))}),!1}return qa(T)?!0:(i.append(Df(_,O,d),v(T)),!1)}const j=[],R=Object.assign(k0,{defaultVisitor:S,convertValue:v,isVisitable:qa});function L(T,O){if(!N.isUndefined(T)){if(j.indexOf(T)!==-1)throw Error("Circular reference detected in "+O.join("."));j.push(T),N.forEach(T,function(b,U){(!(N.isUndefined(b)||b===null)&&c.call(i,b,N.isString(U)?U.trim():U,O,R))===!0&&L(b,O?O.concat(U):[U])}),j.pop()}}if(!N.isObject(r))throw new TypeError("data must be an object");return L(r),i}function zf(r){const i={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(l){return i[l]})}function au(r,i){this._pairs=[],r&&Es(r,this,i)}const qp=au.prototype;qp.append=function(i,s){this._pairs.push([i,s])};qp.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 E0(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Qp(r,i,s){if(!i)return r;const l=s&&s.encode||E0;N.isFunction(s)&&(s={serialize:s});const c=s&&s.serialize;let d;if(c?d=c(i,s):d=N.isURLSearchParams(i)?i.toString():new au(i,s).toString(l),d){const p=r.indexOf("#");p!==-1&&(r=r.slice(0,p)),r+=(r.indexOf("?")===-1?"?":"&")+d}return r}class $f{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){N.forEach(this.handlers,function(l){l!==null&&i(l)})}}const Gp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},j0=typeof URLSearchParams<"u"?URLSearchParams:au,A0=typeof FormData<"u"?FormData:null,R0=typeof Blob<"u"?Blob:null,P0={isBrowser:!0,classes:{URLSearchParams:j0,FormData:A0,Blob:R0},protocols:["http","https","file","blob","url","data"]},uu=typeof window<"u"&&typeof document<"u",Qa=typeof navigator=="object"&&navigator||void 0,T0=uu&&(!Qa||["ReactNative","NativeScript","NS"].indexOf(Qa.product)<0),_0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",N0=uu&&window.location.href||"http://localhost",O0=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:uu,hasStandardBrowserEnv:T0,hasStandardBrowserWebWorkerEnv:_0,navigator:Qa,origin:N0},Symbol.toStringTag,{value:"Module"})),nt={...O0,...P0};function M0(r,i){return Es(r,new nt.classes.URLSearchParams,Object.assign({visitor:function(s,l,c,d){return nt.isNode&&N.isBuffer(s)?(this.append(l,s.toString("base64")),!1):d.defaultVisitor.apply(this,arguments)}},i))}function L0(r){return N.matchAll(/\w+|\[(\w*)]/g,r).map(i=>i[0]==="[]"?"":i[1]||i[0])}function I0(r){const i={},s=Object.keys(r);let l;const c=s.length;let d;for(l=0;l=s.length;return p=!p&&N.isArray(c)?c.length:p,w?(N.hasOwnProp(c,p)?c[p]=[c[p],l]:c[p]=l,!g):((!c[p]||!N.isObject(c[p]))&&(c[p]=[]),i(s,l,c[p],d)&&N.isArray(c[p])&&(c[p]=I0(c[p])),!g)}if(N.isFormData(r)&&N.isFunction(r.entries)){const s={};return N.forEachEntry(r,(l,c)=>{i(L0(l),c,s,0)}),s}return null}function D0(r,i,s){if(N.isString(r))try{return(i||JSON.parse)(r),N.trim(r)}catch(l){if(l.name!=="SyntaxError")throw l}return(0,JSON.stringify)(r)}const Io={transitional:Gp,adapter:["xhr","http","fetch"],transformRequest:[function(i,s){const l=s.getContentType()||"",c=l.indexOf("application/json")>-1,d=N.isObject(i);if(d&&N.isHTMLForm(i)&&(i=new FormData(i)),N.isFormData(i))return c?JSON.stringify(Kp(i)):i;if(N.isArrayBuffer(i)||N.isBuffer(i)||N.isStream(i)||N.isFile(i)||N.isBlob(i)||N.isReadableStream(i))return i;if(N.isArrayBufferView(i))return i.buffer;if(N.isURLSearchParams(i))return s.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),i.toString();let g;if(d){if(l.indexOf("application/x-www-form-urlencoded")>-1)return M0(i,this.formSerializer).toString();if((g=N.isFileList(i))||l.indexOf("multipart/form-data")>-1){const w=this.env&&this.env.FormData;return Es(g?{"files[]":i}:i,w&&new w,this.formSerializer)}}return d||c?(s.setContentType("application/json",!1),D0(i)):i}],transformResponse:[function(i){const s=this.transitional||Io.transitional,l=s&&s.forcedJSONParsing,c=this.responseType==="json";if(N.isResponse(i)||N.isReadableStream(i))return i;if(i&&N.isString(i)&&(l&&!this.responseType||c)){const p=!(s&&s.silentJSONParsing)&&c;try{return JSON.parse(i)}catch(g){if(p)throw g.name==="SyntaxError"?ae.from(g,ae.ERR_BAD_RESPONSE,this,null,this.response):g}}return i}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:nt.classes.FormData,Blob:nt.classes.Blob},validateStatus:function(i){return i>=200&&i<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};N.forEach(["delete","get","head","post","put","patch"],r=>{Io.headers[r]={}});const z0=N.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"]),$0=r=>{const i={};let s,l,c;return r&&r.split(` +`).forEach(function(p){c=p.indexOf(":"),s=p.substring(0,c).trim().toLowerCase(),l=p.substring(c+1).trim(),!(!s||i[s]&&z0[s])&&(s==="set-cookie"?i[s]?i[s].push(l):i[s]=[l]:i[s]=i[s]?i[s]+", "+l:l)}),i},Ff=Symbol("internals");function xo(r){return r&&String(r).trim().toLowerCase()}function ss(r){return r===!1||r==null?r:N.isArray(r)?r.map(ss):String(r)}function F0(r){const i=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let l;for(;l=s.exec(r);)i[l[1]]=l[2];return i}const B0=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function _a(r,i,s,l,c){if(N.isFunction(l))return l.call(this,i,s);if(c&&(i=s),!!N.isString(i)){if(N.isString(l))return i.indexOf(l)!==-1;if(N.isRegExp(l))return l.test(i)}}function b0(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(i,s,l)=>s.toUpperCase()+l)}function U0(r,i){const s=N.toCamelCase(" "+i);["get","set","has"].forEach(l=>{Object.defineProperty(r,l+s,{value:function(c,d,p){return this[l].call(this,i,c,d,p)},configurable:!0})})}class ft{constructor(i){i&&this.set(i)}set(i,s,l){const c=this;function d(g,w,v){const S=xo(w);if(!S)throw new Error("header name must be a non-empty string");const j=N.findKey(c,S);(!j||c[j]===void 0||v===!0||v===void 0&&c[j]!==!1)&&(c[j||w]=ss(g))}const p=(g,w)=>N.forEach(g,(v,S)=>d(v,S,w));if(N.isPlainObject(i)||i instanceof this.constructor)p(i,s);else if(N.isString(i)&&(i=i.trim())&&!B0(i))p($0(i),s);else if(N.isHeaders(i))for(const[g,w]of i.entries())d(w,g,l);else i!=null&&d(s,i,l);return this}get(i,s){if(i=xo(i),i){const l=N.findKey(this,i);if(l){const c=this[l];if(!s)return c;if(s===!0)return F0(c);if(N.isFunction(s))return s.call(this,c,l);if(N.isRegExp(s))return s.exec(c);throw new TypeError("parser must be boolean|regexp|function")}}}has(i,s){if(i=xo(i),i){const l=N.findKey(this,i);return!!(l&&this[l]!==void 0&&(!s||_a(this,this[l],l,s)))}return!1}delete(i,s){const l=this;let c=!1;function d(p){if(p=xo(p),p){const g=N.findKey(l,p);g&&(!s||_a(l,l[g],g,s))&&(delete l[g],c=!0)}}return N.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||_a(this,this[d],d,i,!0))&&(delete this[d],c=!0)}return c}normalize(i){const s=this,l={};return N.forEach(this,(c,d)=>{const p=N.findKey(l,d);if(p){s[p]=ss(c),delete s[d];return}const g=i?b0(d):String(d).trim();g!==d&&delete s[d],s[g]=ss(c),l[g]=!0}),this}concat(...i){return this.constructor.concat(this,...i)}toJSON(i){const s=Object.create(null);return N.forEach(this,(l,c)=>{l!=null&&l!==!1&&(s[c]=i&&N.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[Ff]=this[Ff]={accessors:{}}).accessors,c=this.prototype;function d(p){const g=xo(p);l[g]||(U0(c,p),l[g]=!0)}return N.isArray(i)?i.forEach(d):d(i),this}}ft.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);N.reduceDescriptors(ft.prototype,({value:r},i)=>{let s=i[0].toUpperCase()+i.slice(1);return{get:()=>r,set(l){this[s]=l}}});N.freezeMethods(ft);function Na(r,i){const s=this||Io,l=i||s,c=ft.from(l.headers);let d=l.data;return N.forEach(r,function(g){d=g.call(s,d,c.normalize(),i?i.status:void 0)}),c.normalize(),d}function Xp(r){return!!(r&&r.__CANCEL__)}function _r(r,i,s){ae.call(this,r??"canceled",ae.ERR_CANCELED,i,s),this.name="CanceledError"}N.inherits(_r,ae,{__CANCEL__:!0});function Jp(r,i,s){const l=s.config.validateStatus;!s.status||!l||l(s.status)?r(s):i(new ae("Request failed with status code "+s.status,[ae.ERR_BAD_REQUEST,ae.ERR_BAD_RESPONSE][Math.floor(s.status/100)-4],s.config,s.request,s))}function H0(r){const i=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return i&&i[1]||""}function V0(r,i){r=r||10;const s=new Array(r),l=new Array(r);let c=0,d=0,p;return i=i!==void 0?i:1e3,function(w){const v=Date.now(),S=l[d];p||(p=v),s[c]=w,l[c]=v;let j=d,R=0;for(;j!==c;)R+=s[j++],j=j%r;if(c=(c+1)%r,c===d&&(d=(d+1)%r),v-p{s=S,c=null,d&&(clearTimeout(d),d=null),r.apply(null,v)};return[(...v)=>{const S=Date.now(),j=S-s;j>=l?p(v,S):(c=v,d||(d=setTimeout(()=>{d=null,p(c)},l-j)))},()=>c&&p(c)]}const ps=(r,i,s=3)=>{let l=0;const c=V0(50,250);return W0(d=>{const p=d.loaded,g=d.lengthComputable?d.total:void 0,w=p-l,v=c(w),S=p<=g;l=p;const j={loaded:p,total:g,progress:g?p/g:void 0,bytes:w,rate:v||void 0,estimated:v&&g&&S?(g-p)/v:void 0,event:d,lengthComputable:g!=null,[i?"download":"upload"]:!0};r(j)},s)},Bf=(r,i)=>{const s=r!=null;return[l=>i[0]({lengthComputable:s,total:r,loaded:l}),i[1]]},bf=r=>(...i)=>N.asap(()=>r(...i)),Y0=nt.hasStandardBrowserEnv?((r,i)=>s=>(s=new URL(s,nt.origin),r.protocol===s.protocol&&r.host===s.host&&(i||r.port===s.port)))(new URL(nt.origin),nt.navigator&&/(msie|trident)/i.test(nt.navigator.userAgent)):()=>!0,q0=nt.hasStandardBrowserEnv?{write(r,i,s,l,c,d){const p=[r+"="+encodeURIComponent(i)];N.isNumber(s)&&p.push("expires="+new Date(s).toGMTString()),N.isString(l)&&p.push("path="+l),N.isString(c)&&p.push("domain="+c),d===!0&&p.push("secure"),document.cookie=p.join("; ")},read(r){const i=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return i?decodeURIComponent(i[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Q0(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function G0(r,i){return i?r.replace(/\/?\/$/,"")+"/"+i.replace(/^\/+/,""):r}function Zp(r,i){return r&&!Q0(i)?G0(r,i):i}const Uf=r=>r instanceof ft?{...r}:r;function qn(r,i){i=i||{};const s={};function l(v,S,j,R){return N.isPlainObject(v)&&N.isPlainObject(S)?N.merge.call({caseless:R},v,S):N.isPlainObject(S)?N.merge({},S):N.isArray(S)?S.slice():S}function c(v,S,j,R){if(N.isUndefined(S)){if(!N.isUndefined(v))return l(void 0,v,j,R)}else return l(v,S,j,R)}function d(v,S){if(!N.isUndefined(S))return l(void 0,S)}function p(v,S){if(N.isUndefined(S)){if(!N.isUndefined(v))return l(void 0,v)}else return l(void 0,S)}function g(v,S,j){if(j in i)return l(v,S);if(j in r)return l(void 0,v)}const w={url:d,method:d,data:d,baseURL:p,transformRequest:p,transformResponse:p,paramsSerializer:p,timeout:p,timeoutMessage:p,withCredentials:p,withXSRFToken:p,adapter:p,responseType:p,xsrfCookieName:p,xsrfHeaderName:p,onUploadProgress:p,onDownloadProgress:p,decompress:p,maxContentLength:p,maxBodyLength:p,beforeRedirect:p,transport:p,httpAgent:p,httpsAgent:p,cancelToken:p,socketPath:p,responseEncoding:p,validateStatus:g,headers:(v,S,j)=>c(Uf(v),Uf(S),j,!0)};return N.forEach(Object.keys(Object.assign({},r,i)),function(S){const j=w[S]||c,R=j(r[S],i[S],S);N.isUndefined(R)&&j!==g||(s[S]=R)}),s}const eh=r=>{const i=qn({},r);let{data:s,withXSRFToken:l,xsrfHeaderName:c,xsrfCookieName:d,headers:p,auth:g}=i;i.headers=p=ft.from(p),i.url=Qp(Zp(i.baseURL,i.url),r.params,r.paramsSerializer),g&&p.set("Authorization","Basic "+btoa((g.username||"")+":"+(g.password?unescape(encodeURIComponent(g.password)):"")));let w;if(N.isFormData(s)){if(nt.hasStandardBrowserEnv||nt.hasStandardBrowserWebWorkerEnv)p.setContentType(void 0);else if((w=p.getContentType())!==!1){const[v,...S]=w?w.split(";").map(j=>j.trim()).filter(Boolean):[];p.setContentType([v||"multipart/form-data",...S].join("; "))}}if(nt.hasStandardBrowserEnv&&(l&&N.isFunction(l)&&(l=l(i)),l||l!==!1&&Y0(i.url))){const v=c&&d&&q0.read(d);v&&p.set(c,v)}return i},K0=typeof XMLHttpRequest<"u",X0=K0&&function(r){return new Promise(function(s,l){const c=eh(r);let d=c.data;const p=ft.from(c.headers).normalize();let{responseType:g,onUploadProgress:w,onDownloadProgress:v}=c,S,j,R,L,T;function O(){L&&L(),T&&T(),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 b(){if(!_)return;const B=ft.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),I={data:!g||g==="text"||g==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:B,config:r,request:_};Jp(function(V){s(V),O()},function(V){l(V),O()},I),_=null}"onloadend"in _?_.onloadend=b:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.indexOf("file:")===0)||setTimeout(b)},_.onabort=function(){_&&(l(new ae("Request aborted",ae.ECONNABORTED,r,_)),_=null)},_.onerror=function(){l(new ae("Network Error",ae.ERR_NETWORK,r,_)),_=null},_.ontimeout=function(){let W=c.timeout?"timeout of "+c.timeout+"ms exceeded":"timeout exceeded";const I=c.transitional||Gp;c.timeoutErrorMessage&&(W=c.timeoutErrorMessage),l(new ae(W,I.clarifyTimeoutError?ae.ETIMEDOUT:ae.ECONNABORTED,r,_)),_=null},d===void 0&&p.setContentType(null),"setRequestHeader"in _&&N.forEach(p.toJSON(),function(W,I){_.setRequestHeader(I,W)}),N.isUndefined(c.withCredentials)||(_.withCredentials=!!c.withCredentials),g&&g!=="json"&&(_.responseType=c.responseType),v&&([R,T]=ps(v,!0),_.addEventListener("progress",R)),w&&_.upload&&([j,L]=ps(w),_.upload.addEventListener("progress",j),_.upload.addEventListener("loadend",L)),(c.cancelToken||c.signal)&&(S=B=>{_&&(l(!B||B.type?new _r(null,r,_):B),_.abort(),_=null)},c.cancelToken&&c.cancelToken.subscribe(S),c.signal&&(c.signal.aborted?S():c.signal.addEventListener("abort",S)));const U=H0(c.url);if(U&&nt.protocols.indexOf(U)===-1){l(new ae("Unsupported protocol "+U+":",ae.ERR_BAD_REQUEST,r));return}_.send(d||null)})},J0=(r,i)=>{const{length:s}=r=r?r.filter(Boolean):[];if(i||s){let l=new AbortController,c;const d=function(v){if(!c){c=!0,g();const S=v instanceof Error?v:this.reason;l.abort(S instanceof ae?S:new _r(S instanceof Error?S.message:S))}};let p=i&&setTimeout(()=>{p=null,d(new ae(`timeout ${i} of ms exceeded`,ae.ETIMEDOUT))},i);const g=()=>{r&&(p&&clearTimeout(p),p=null,r.forEach(v=>{v.unsubscribe?v.unsubscribe(d):v.removeEventListener("abort",d)}),r=null)};r.forEach(v=>v.addEventListener("abort",d));const{signal:w}=l;return w.unsubscribe=()=>N.asap(g),w}},Z0=function*(r,i){let s=r.byteLength;if(s{const c=ev(r,i);let d=0,p,g=w=>{p||(p=!0,l&&l(w))};return new ReadableStream({async pull(w){try{const{done:v,value:S}=await c.next();if(v){g(),w.close();return}let j=S.byteLength;if(s){let R=d+=j;s(R)}w.enqueue(new Uint8Array(S))}catch(v){throw g(v),v}},cancel(w){return g(w),c.return()}},{highWaterMark:2})},js=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",th=js&&typeof ReadableStream=="function",nv=js&&(typeof TextEncoder=="function"?(r=>i=>r.encode(i))(new TextEncoder):async r=>new Uint8Array(await new Response(r).arrayBuffer())),nh=(r,...i)=>{try{return!!r(...i)}catch{return!1}},rv=th&&nh(()=>{let r=!1;const i=new Request(nt.origin,{body:new ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type");return r&&!i}),Vf=64*1024,Ga=th&&nh(()=>N.isReadableStream(new Response("").body)),hs={stream:Ga&&(r=>r.body)};js&&(r=>{["text","arrayBuffer","blob","formData","stream"].forEach(i=>{!hs[i]&&(hs[i]=N.isFunction(r[i])?s=>s[i]():(s,l)=>{throw new ae(`Response type '${i}' is not supported`,ae.ERR_NOT_SUPPORT,l)})})})(new Response);const ov=async r=>{if(r==null)return 0;if(N.isBlob(r))return r.size;if(N.isSpecCompliantForm(r))return(await new Request(nt.origin,{method:"POST",body:r}).arrayBuffer()).byteLength;if(N.isArrayBufferView(r)||N.isArrayBuffer(r))return r.byteLength;if(N.isURLSearchParams(r)&&(r=r+""),N.isString(r))return(await nv(r)).byteLength},iv=async(r,i)=>{const s=N.toFiniteNumber(r.getContentLength());return s??ov(i)},sv=js&&(async r=>{let{url:i,method:s,data:l,signal:c,cancelToken:d,timeout:p,onDownloadProgress:g,onUploadProgress:w,responseType:v,headers:S,withCredentials:j="same-origin",fetchOptions:R}=eh(r);v=v?(v+"").toLowerCase():"text";let L=J0([c,d&&d.toAbortSignal()],p),T;const O=L&&L.unsubscribe&&(()=>{L.unsubscribe()});let _;try{if(w&&rv&&s!=="get"&&s!=="head"&&(_=await iv(S,l))!==0){let I=new Request(i,{method:"POST",body:l,duplex:"half"}),M;if(N.isFormData(l)&&(M=I.headers.get("content-type"))&&S.setContentType(M),I.body){const[V,ne]=Bf(_,ps(bf(w)));l=Hf(I.body,Vf,V,ne)}}N.isString(j)||(j=j?"include":"omit");const b="credentials"in Request.prototype;T=new Request(i,{...R,signal:L,method:s.toUpperCase(),headers:S.normalize().toJSON(),body:l,duplex:"half",credentials:b?j:void 0});let U=await fetch(T);const B=Ga&&(v==="stream"||v==="response");if(Ga&&(g||B&&O)){const I={};["status","statusText","headers"].forEach(ye=>{I[ye]=U[ye]});const M=N.toFiniteNumber(U.headers.get("content-length")),[V,ne]=g&&Bf(M,ps(bf(g),!0))||[];U=new Response(Hf(U.body,Vf,V,()=>{ne&&ne(),O&&O()}),I)}v=v||"text";let W=await hs[N.findKey(hs,v)||"text"](U,r);return!B&&O&&O(),await new Promise((I,M)=>{Jp(I,M,{data:W,headers:ft.from(U.headers),status:U.status,statusText:U.statusText,config:r,request:T})})}catch(b){throw O&&O(),b&&b.name==="TypeError"&&/fetch/i.test(b.message)?Object.assign(new ae("Network Error",ae.ERR_NETWORK,r,T),{cause:b.cause||b}):ae.from(b,b&&b.code,r,T)}}),Ka={http:S0,xhr:X0,fetch:sv};N.forEach(Ka,(r,i)=>{if(r){try{Object.defineProperty(r,"name",{value:i})}catch{}Object.defineProperty(r,"adapterName",{value:i})}});const Wf=r=>`- ${r}`,lv=r=>N.isFunction(r)||r===null||r===!1,rh={getAdapter:r=>{r=N.isArray(r)?r:[r];const{length:i}=r;let s,l;const c={};for(let d=0;d`adapter ${g} `+(w===!1?"is not supported by the environment":"is not available in the build"));let p=i?d.length>1?`since : +`+d.map(Wf).join(` +`):" "+Wf(d[0]):"as no adapter specified";throw new ae("There is no suitable adapter to dispatch the request "+p,"ERR_NOT_SUPPORT")}return l},adapters:Ka};function Oa(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new _r(null,r)}function Yf(r){return Oa(r),r.headers=ft.from(r.headers),r.data=Na.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),rh.getAdapter(r.adapter||Io.adapter)(r).then(function(l){return Oa(r),l.data=Na.call(r,r.transformResponse,l),l.headers=ft.from(l.headers),l},function(l){return Xp(l)||(Oa(r),l&&l.response&&(l.response.data=Na.call(r,r.transformResponse,l.response),l.response.headers=ft.from(l.response.headers))),Promise.reject(l)})}const oh="1.7.9",As={};["object","boolean","number","function","string","symbol"].forEach((r,i)=>{As[r]=function(l){return typeof l===r||"a"+(i<1?"n ":" ")+r}});const qf={};As.transitional=function(i,s,l){function c(d,p){return"[Axios v"+oh+"] Transitional option '"+d+"'"+p+(l?". "+l:"")}return(d,p,g)=>{if(i===!1)throw new ae(c(p," has been removed"+(s?" in "+s:"")),ae.ERR_DEPRECATED);return s&&!qf[p]&&(qf[p]=!0,console.warn(c(p," has been deprecated since v"+s+" and will be removed in the near future"))),i?i(d,p,g):!0}};As.spelling=function(i){return(s,l)=>(console.warn(`${l} is likely a misspelling of ${i}`),!0)};function av(r,i,s){if(typeof r!="object")throw new ae("options must be an object",ae.ERR_BAD_OPTION_VALUE);const l=Object.keys(r);let c=l.length;for(;c-- >0;){const d=l[c],p=i[d];if(p){const g=r[d],w=g===void 0||p(g,d,r);if(w!==!0)throw new ae("option "+d+" must be "+w,ae.ERR_BAD_OPTION_VALUE);continue}if(s!==!0)throw new ae("Unknown option "+d,ae.ERR_BAD_OPTION)}}const ls={assertOptions:av,validators:As},Vt=ls.validators;class Vn{constructor(i){this.defaults=i,this.interceptors={request:new $f,response:new $f}}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=qn(this.defaults,s);const{transitional:l,paramsSerializer:c,headers:d}=s;l!==void 0&&ls.assertOptions(l,{silentJSONParsing:Vt.transitional(Vt.boolean),forcedJSONParsing:Vt.transitional(Vt.boolean),clarifyTimeoutError:Vt.transitional(Vt.boolean)},!1),c!=null&&(N.isFunction(c)?s.paramsSerializer={serialize:c}:ls.assertOptions(c,{encode:Vt.function,serialize:Vt.function},!0)),ls.assertOptions(s,{baseUrl:Vt.spelling("baseURL"),withXsrfToken:Vt.spelling("withXSRFToken")},!0),s.method=(s.method||this.defaults.method||"get").toLowerCase();let p=d&&N.merge(d.common,d[s.method]);d&&N.forEach(["delete","get","head","post","put","patch","common"],T=>{delete d[T]}),s.headers=ft.concat(p,d);const g=[];let w=!0;this.interceptors.request.forEach(function(O){typeof O.runWhen=="function"&&O.runWhen(s)===!1||(w=w&&O.synchronous,g.unshift(O.fulfilled,O.rejected))});const v=[];this.interceptors.response.forEach(function(O){v.push(O.fulfilled,O.rejected)});let S,j=0,R;if(!w){const T=[Yf.bind(this),void 0];for(T.unshift.apply(T,g),T.push.apply(T,v),R=T.length,S=Promise.resolve(s);j{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 p=new Promise(g=>{l.subscribe(g),d=g}).then(c);return p.cancel=function(){l.unsubscribe(d)},p},i(function(d,p,g){l.reason||(l.reason=new _r(d,p,g),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 cu(function(c){i=c}),cancel:i}}}function uv(r){return function(s){return r.apply(null,s)}}function cv(r){return N.isObject(r)&&r.isAxiosError===!0}const Xa={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(Xa).forEach(([r,i])=>{Xa[i]=r});function ih(r){const i=new Vn(r),s=Dp(Vn.prototype.request,i);return N.extend(s,Vn.prototype,i,{allOwnKeys:!0}),N.extend(s,i,null,{allOwnKeys:!0}),s.create=function(c){return ih(qn(r,c))},s}const be=ih(Io);be.Axios=Vn;be.CanceledError=_r;be.CancelToken=cu;be.isCancel=Xp;be.VERSION=oh;be.toFormData=Es;be.AxiosError=ae;be.Cancel=be.CanceledError;be.all=function(i){return Promise.all(i)};be.spread=uv;be.isAxiosError=cv;be.mergeConfig=qn;be.AxiosHeaders=ft;be.formToJSON=r=>Kp(N.isHTMLForm(r)?new FormData(r):r);be.getAdapter=rh.getAdapter;be.HttpStatusCode=Xa;be.default=be;const dv={apiBaseUrl:"/api"};class fv{constructor(){sf(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 Oo=new fv,Oe=be.create({baseURL:dv.apiBaseUrl,headers:{"Content-Type":"application/json"},withCredentials:!0});Oe.interceptors.request.use(r=>r,r=>Promise.reject(r));Oe.interceptors.response.use(r=>r,r=>{var s,l,c,d;const i=(s=r.response)==null?void 0:s.data;if(i){const p=(c=(l=r.response)==null?void 0:l.headers)==null?void 0:c["discodeit-request-id"];p&&(i.requestId=p),r.response.data=i}return console.log({error:r,errorResponse:i}),Oo.emit("api-error",{error:r,alert:((d=r.response)==null?void 0:d.status)===403}),r.response&&r.response.status===401&&Oo.emit("auth-error"),Promise.reject(r)});const pv=()=>Oe.defaults.baseURL,hv=async(r,i)=>(await Oe.patch(`/users/${r}`,i,{headers:{"Content-Type":"multipart/form-data"}})).data,mv=async()=>(await Oe.get("/users")).data,Ar=Pr(r=>({users:[],fetchUsers:async()=>{try{const i=await mv();r({users:i})}catch(i){console.error("사용자 목록 조회 실패:",i)}}})),gv=async(r,i,s)=>{const l=new FormData;return l.append("username",r),l.append("password",i),(await Oe.post("/auth/login",l,{params:{"remember-me":s?"true":"false"},headers:{"Content-Type":"multipart/form-data"}})).data},yv=async r=>(await Oe.post("/users",r,{headers:{"Content-Type":"multipart/form-data"}})).data,vv=async()=>{await Oe.get("/auth/csrf-token")},xv=async()=>(await Oe.get("/auth/me")).data,wv=async()=>{await Oe.post("/auth/logout")},Sv=async(r,i)=>{const s={userId:r,newRole:i};return(await Oe.put("/auth/role",s)).data},pt=Pr((r,i)=>({currentUser:null,login:async(s,l,c=!1)=>{const d=await gv(s,l,c);await i().fetchCsrfToken(),r({currentUser:d})},logout:async()=>{await wv(),i().clear(),i().fetchCsrfToken()},fetchCsrfToken:async()=>{await vv()},fetchMe:async()=>{const s=await xv();r({currentUser:s})},clear:()=>{r({currentUser:null})},updateUserRole:async(s,l)=>{await Sv(s,l)}})),q={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"}}},sh=k.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; +`,lh=k.div` + background: ${q.colors.background.primary}; + padding: 32px; + border-radius: 8px; + width: 440px; + + h2 { + color: ${q.colors.text.primary}; + margin-bottom: 24px; + font-size: 24px; + font-weight: bold; + } + + form { + display: flex; + flex-direction: column; + gap: 16px; + } +`,jo=k.input` + width: 100%; + padding: 10px; + border-radius: 4px; + background: ${q.colors.background.input}; + border: none; + color: ${q.colors.text.primary}; + font-size: 16px; + + &::placeholder { + color: ${q.colors.text.muted}; + } + + &:focus { + outline: none; + } +`,Cv=k.input.attrs({type:"checkbox"})` + width: 16px; + height: 16px; + padding: 0; + border-radius: 4px; + background: ${q.colors.background.input}; + border: none; + color: ${q.colors.text.primary}; + cursor: pointer; + + &:focus { + outline: none; + } + + &:checked { + background: ${q.colors.brand.primary}; + } +`,ah=k.button` + width: 100%; + padding: 12px; + border-radius: 4px; + background: ${q.colors.brand.primary}; + color: white; + font-size: 16px; + font-weight: 500; + border: none; + cursor: pointer; + transition: background-color 0.2s; + + &:hover { + background: ${q.colors.brand.hover}; + } +`,uh=k.div` + color: ${q.colors.status.error}; + font-size: 14px; + text-align: center; +`,kv=k.p` + text-align: center; + margin-top: 16px; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 14px; +`,Ev=k.span` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,Gi=k.div` + margin-bottom: 20px; +`,Ki=k.label` + display: block; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,Ma=k.span` + color: ${({theme:r})=>r.colors.status.error}; +`,jv=k.div` + display: flex; + flex-direction: column; + align-items: center; + margin: 10px 0; +`,Av=k.img` + width: 80px; + height: 80px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,Rv=k.input` + display: none; +`,Pv=k.label` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,Tv=k.span` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +`,_v=k(Tv)` + display: block; + text-align: center; + margin-top: 16px; +`,St="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAACXBIWXMAACE4AAAhOAFFljFgAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAw2SURBVHgB7d3PT1XpHcfxBy5g6hipSMolGViACThxJDbVRZ2FXejKlf9h/4GmC1fTRdkwC8fE0JgyJuICFkCjEA04GeZe6P0cPC0698I95zzPc57v5f1K6DSto3A8n/v9nufXGfrr338+dgBMGnYAzCLAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwbcTDvyuWh//33w1/1dexwMRBgYxTW5vVh9/vxYTcxPpR9jY0OffZrdt8fu82ttlvfbLv9j4R5kBHgxCmcE1eH3NfTDTc7PfxZte3lJNgjbmlxxK3+1HKrr1oOg4kAJ0pVdnG+4ZqTw7+psEUoxF91Qv/Di1+db/q+ZpvD7g+T6gb04XLyv6mF3//osuqvTmDn3RGdQCAEOCG6+W/ONdzNTnCrhPZLN2Yb2T99hVhdwOLcSOf37f7hknUN4yedgLoGeb3Rdv/qdAIE2S8CnIDzAuGDQrzXeTZee1OtndaHy9LCSOHvU3++vv693nLPX9LS+0KAa6QQLC2o4sb5a1A7rYGtMqPU+l7v3hpx85+qeVnfdH7W2c7z/Pcrh1RjD5gHromq2JOHY9HCK2Ojzk1dL1fhH90fqxzenDoO/X79DMjhbAQ4Mg1OPXl4KauGodrls6j6FaXKq+dZn/IQ13ENBgkBjiRvQR99V2/lmZos9lc+PxOuxdd1uL3gp6pfVDwDR6Ab9cG9Me9VLAZ1CiHpmXhz6yibakJxVODAZpoN9/iBzfCq+sboFkJ/SAwyrlxAujE1WJWSIiO/sYKlxSpTnbEBqnBxVOBA9LybWnjloM8An6ysitc1NCe5FcvgqgVw/85o1OmhItY32n39uqnJuC3/FAEuhavmmcLra77UN7XP2322qRNX494aqvgojqvmUcrhFa1+6tdXkae6tMiEhR3FEWBPNOCTcni1rZCli4OHAHuQ4mjzaewJHlxMI1Wked5Uw7v99ijbwqd/FnVQQ7WmQyiOAFegZ7a736ZzCU820h+7nbfHbnO7XSq4p3+vmHbfMwdcBgGuoO4dNQrZxtaR+08nqNueT73Y2D7qTIW5aLRXGcUR4JL03FtHeBXa9Y2jyhX2PHudiqg/K9ZuoY3t/uan8TkCXIKCG/u5V2Fae9N2a+vtKO2tjqfVnxfj5zw5O4sWugwCXIJa51hiB/e0tfVWdkZX6CrMCHl5BLigWDt0RCc6rrxo1XZQu6rw6qt2tq47FD0G9Lu8E79FgAvIWucIO3QU2B9ftpK4sVWFZ5rDQTYbqHUOcdztRcJCjgLUToauvrqpny4fJlWVlp/5P4BOH1IcbFcdAe6Tght6h5FeiaLwpnZTq5VW2HzN1eYfUoS3OgLcp9sL4cOrkKT6YrI8dFUHnDQYR3j94Rm4D9kLxQLuV009vKdpXbXae00vFdm8UWVZJ3ojwH3QcS+hnn1VifSMaemVoPqeVzqDT6rG2oivQS5dH33l70ZS262w7n04yhae8MrTMAhwH0KNPFsfyNH3vd+pxkwD1Ydn4HOodQ5VfTXHyrMgqiDA55ibCbNJX1VLc6xAFQT4HCEGr9Q6s3wQPhDgM4RqnzWVQusMHwjwGTS66puCS/WFLwT4DCHOKia88IkA96BjTkOcVbzDQgZ4RIB7CBFejTzz7AufCHAPWn3lGwse4BsB7uGa5wqcLS3k7XvwjAD3cOWy84pnX4RAgHvw/QzMLhyEQIC7CLF4Y4+DyxEAAe4iRIB3PzD6DP8IcBejnncPagCL/bAIgQB34fsc5P2PtM8IgwBHcMjJqQiEAHfBm+JhBQGO4IDlkwiEAHdx2PIbuFhv+MPFQ4C7ODx0Xo2OOiAIAhwBz9QIhQB34XvOlhYaoRDgLg5+dl7pcACqMEIgwF2EWDV1bZwAwz8C3IVOzfAd4omrXGr4x13Vg++jb6YmudTwj7uqh733fgOsM6YZzIJvBLiH3Q/+NyDMB3pNCy4u3k7Yw+57/wNZM9PDbu2NGwjqJiauDrmvpxufXiv6+f+v63fw8SjrZDgLLBwC3INO0NBAls+2V220jurZNXw6h8K6ODfibsye/UjQnNR/nnQcGk/IX/DNsbp+EeAetAVQVaQ56fe5dXGu4X54YTPASwsj7uZ8o/CHmkJ/Y7aRfb3eaBNkj3gGPsNOgNZPN7G1RR36fh8/uJS96LxqR6Kf/9H9MRa2eEKAz7C5FaZS3l6w0/goaArchMeFKPkHwrVxbr+quIJn0LNqiFZPVSjEmx98U7UNVS016PWXe6NU4ooI8DnWN8O8DuX+H0eTnxdeWgjb7uv3/vMd9lpWQYDPEep9Rrp5by+kOy+s7+/mfPhWXyPzFrqRVHHlzpFPgYTwTScg87NphjhmZdTgGMohwH1YexPupdx3b40mN5ij6tuMuHabKlweV60PGo0OdTB7ioM5WjEWW5PNHqVw1fq09ibcu33zqZpUQjzTjN/Ws1urHK5an9bWW0Ffj5JSiOv4HiaYEy6Fq9YnLa1cfRWuCku+wOHmXL2DOnUEmGOHyiHABagKh17Dqxv57rcj7k+3RpKfJ0b9CHBBKy/ivOhIU0yPH4xdqD3EV37HB1ZRBLignc6c8MZW2FY6p5ZSK7b0bNyMOM3CTiE7CHAJz1+2or7vV1Msj74by4IcoyKHOMygH4fhptsHFgEuQRXqx5fx7zYFWRX5ycNL2UqpUFV5512cDuNLvAS9ONawlaQ10jpSJsZ64S+d3iCvm3777XGntW9nx9fsfqh+JK5+Nq0Qi43WvTgCXMHqq5abma53g75Gqmen9fX/alz1CBtNmenfj7k6yvIxQ3Wiha5AN/r3K4fJtX55hVarvVTy8AB9OMV0GGdwf+AQ4IpU4f75LN27Tzt9HtwbKzynrNF2zXvHsvOWClwGAfZAN18dg1r9UnuthSFF6WeK1doS4HIIsCeqVrHbziLUUpdZornc6S5iDC5p8A3FEWCPVn9KO8RlTpVUeJ8u/xLsUAPR780UUjkE2LOUQ6x11jPN4n/l+WDdaqDznEOdO3YREOAAFOJUn4mrTA3p51KQNU/sM8g8/5bHPHAgeibWAND9O2mdtlF147yCm2/o0IeBXlyuAwDKfjDotBMWcJRHBQ5IlUUVa1Bv0O1squnkVSllvd5kAXQVBDiwfBAo5pyqFbo2od5+cVEQ4Ag0CKRnYrWedVfjlLqBlEfsrSDAEWnwJx8Eqsve+zQCrA+SOq/DoCDAkeWDQE+X63k23txKIzRUXz8IcE00Qv23f/wSta3Odim9q/+Zc6Pz3Ev19YNppJrpRtaXXrGinUMhp5zUvqfg+Uu2HvlCgBORB1nzqYtzDTc77ffoHC3CSGEAS4N5zPv6Q4ATo7lVfV253MoWXegMrKob6xWaFKax9PzNdJpfBDhRqlL7n6qy2mqFWeuY9QaDfttsfRCoXd1NYOS5rnPEBh0BNuB0mGVifOgk1Ncb2VJGbVLIdxnp12qqaHO7HXQHURH6ngZ5RVqdCLBBqqj62jCwiknbBJefEd5QCDCCUWgV3hRa+EFFgBEEbXMcBBjeabR55UWLUzYiIMDwRoHVK1iZKoqHAMMLqm49CDAqyxefID42MwCGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhhFgwDACDBhGgAHDCDBgGAEGDCPAgGEEGDCMAAOGEWDAMAIMGEaAAcMIMGAYAQYMI8CAYQQYMIwAA4YRYMAwAgwYRoABwwgwYBgBBgwjwIBhBBgwjAADhv0XZkN9IbEGbp4AAAAASUVORK5CYII=",Nv=({isOpen:r,onClose:i})=>{const[s,l]=K.useState(""),[c,d]=K.useState(""),[p,g]=K.useState(""),[w,v]=K.useState(null),[S,j]=K.useState(null),[R,L]=K.useState(""),{fetchCsrfToken:T}=pt(),O=K.useCallback(()=>{S&&URL.revokeObjectURL(S),j(null),v(null),l(""),d(""),g(""),L("")},[S]),_=K.useCallback(()=>{O(),i()},[]),b=B=>{var I;const W=(I=B.target.files)==null?void 0:I[0];if(W){v(W);const M=new FileReader;M.onloadend=()=>{j(M.result)},M.readAsDataURL(W)}},U=async B=>{B.preventDefault(),L("");try{const W=new FormData;W.append("userCreateRequest",new Blob([JSON.stringify({email:s,username:c,password:p})],{type:"application/json"})),w&&W.append("profile",w),await yv(W),await T(),i()}catch{L("회원가입에 실패했습니다.")}};return r?h.jsx(sh,{children:h.jsxs(lh,{children:[h.jsx("h2",{children:"계정 만들기"}),h.jsxs("form",{onSubmit:U,children:[h.jsxs(Gi,{children:[h.jsxs(Ki,{children:["이메일 ",h.jsx(Ma,{children:"*"})]}),h.jsx(jo,{type:"email",value:s,onChange:B=>l(B.target.value),required:!0})]}),h.jsxs(Gi,{children:[h.jsxs(Ki,{children:["사용자명 ",h.jsx(Ma,{children:"*"})]}),h.jsx(jo,{type:"text",value:c,onChange:B=>d(B.target.value),required:!0})]}),h.jsxs(Gi,{children:[h.jsxs(Ki,{children:["비밀번호 ",h.jsx(Ma,{children:"*"})]}),h.jsx(jo,{type:"password",value:p,onChange:B=>g(B.target.value),required:!0})]}),h.jsxs(Gi,{children:[h.jsx(Ki,{children:"프로필 이미지"}),h.jsxs(jv,{children:[h.jsx(Av,{src:S||St,alt:"profile"}),h.jsx(Rv,{type:"file",accept:"image/*",onChange:b,id:"profile-image"}),h.jsx(Pv,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),R&&h.jsx(uh,{children:R}),h.jsx(ah,{type:"submit",children:"계속하기"}),h.jsx(_v,{onClick:_,children:"이미 계정이 있으신가요?"})]})]})}):null},Ov=({isOpen:r,onClose:i})=>{const[s,l]=K.useState(""),[c,d]=K.useState(""),[p,g]=K.useState(""),[w,v]=K.useState(!1),[S,j]=K.useState(!1),{login:R}=pt(),{fetchUsers:L}=Ar(),T=K.useCallback(()=>{l(""),d(""),g(""),j(!1),v(!1)},[]),O=K.useCallback(()=>{T(),v(!0)},[T,i]),_=async()=>{var b;try{await R(s,c,S),await L(),T(),i()}catch(U){console.error("로그인 에러:",U),((b=U.response)==null?void 0:b.status)===401?g("아이디 또는 비밀번호가 올바르지 않습니다."):g("로그인에 실패했습니다.")}};return r?h.jsxs(h.Fragment,{children:[h.jsx(sh,{children:h.jsxs(lh,{children:[h.jsx("h2",{children:"돌아오신 것을 환영해요!"}),h.jsxs("form",{onSubmit:b=>{b.preventDefault(),_()},children:[h.jsx(jo,{type:"text",placeholder:"사용자 이름",value:s,onChange:b=>l(b.target.value)}),h.jsx(jo,{type:"password",placeholder:"비밀번호",value:c,onChange:b=>d(b.target.value)}),h.jsxs(Mv,{children:[h.jsx(Cv,{id:"rememberMe",checked:S,onChange:b=>j(b.target.checked)}),h.jsx(Lv,{htmlFor:"rememberMe",children:"로그인 유지"})]}),p&&h.jsx(uh,{children:p}),h.jsx(ah,{type:"submit",children:"로그인"})]}),h.jsxs(kv,{children:["계정이 필요한가요? ",h.jsx(Ev,{onClick:O,children:"가입하기"})]})]})}),h.jsx(Nv,{isOpen:w,onClose:()=>v(!1)})]}):null},Mv=k.div` + display: flex; + align-items: center; + margin: 10px 0; + justify-content: flex-start; +`,Lv=k.label` + margin-left: 8px; + font-size: 14px; + color: #666; + cursor: pointer; + text-align: left; +`,Iv=async r=>(await Oe.get(`/channels?userId=${r}`)).data,Dv=async r=>(await Oe.post("/channels/public",r)).data,zv=async r=>{const i={participantIds:r};return(await Oe.post("/channels/private",i)).data},$v=async(r,i)=>(await Oe.patch(`/channels/${r}`,i)).data,Fv=async r=>{await Oe.delete(`/channels/${r}`)},Bv=async r=>(await Oe.get("/readStatuses",{params:{userId:r}})).data,bv=async(r,i)=>{const s={newLastReadAt:i};return(await Oe.patch(`/readStatuses/${r}`,s)).data},Uv=async(r,i,s)=>{const l={userId:r,channelId:i,lastReadAt:s};return(await Oe.post("/readStatuses",l)).data},Ao=Pr((r,i)=>({readStatuses:{},fetchReadStatuses:async()=>{try{const{currentUser:s}=pt.getState();if(!s)return;const c=(await Bv(s.id)).reduce((d,p)=>(d[p.channelId]={id:p.id,lastReadAt:p.lastReadAt},d),{});r({readStatuses:c})}catch(s){console.error("읽음 상태 조회 실패:",s)}},updateReadStatus:async s=>{try{const{currentUser:l}=pt.getState();if(!l)return;const c=i().readStatuses[s];let d;c?d=await bv(c.id,new Date().toISOString()):d=await Uv(l.id,s,new Date().toISOString()),r(p=>({readStatuses:{...p.readStatuses,[s]:{id:d.id,lastReadAt:d.lastReadAt}}}))}catch(l){console.error("읽음 상태 업데이트 실패:",l)}},hasUnreadMessages:(s,l)=>{const c=i().readStatuses[s],d=c==null?void 0:c.lastReadAt;return!d||new Date(l)>new Date(d)}})),jn=Pr((r,i)=>({channels:[],pollingInterval:null,loading:!1,error:null,fetchChannels:async s=>{r({loading:!0,error:null});try{const l=await Iv(s);r(d=>{const p=new Set(d.channels.map(S=>S.id)),g=l.filter(S=>!p.has(S.id));return{channels:[...d.channels.filter(S=>l.some(j=>j.id===S.id)),...g],loading:!1}});const{fetchReadStatuses:c}=Ao.getState();return c(),l}catch(l){return r({error:l,loading:!1}),[]}},startPolling:s=>{const l=i().pollingInterval;l&&clearInterval(l);const c=setInterval(()=>{i().fetchChannels(s)},3e3);r({pollingInterval:c})},stopPolling:()=>{const s=i().pollingInterval;s&&(clearInterval(s),r({pollingInterval:null}))},createPublicChannel:async s=>{try{const l=await Dv(s);return r(c=>c.channels.some(p=>p.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 zv(s);return r(c=>c.channels.some(p=>p.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 $v(s,l);return r(d=>({channels:d.channels.map(p=>p.id===s?{...p,...c}:p)})),c}catch(c){throw console.error("채널 수정 실패:",c),c}},deleteChannel:async s=>{try{await Fv(s),r(l=>({channels:l.channels.filter(c=>c.id!==s)}))}catch(l){throw console.error("채널 삭제 실패:",l),l}}})),Hv=async r=>(await Oe.get(`/binaryContents/${r}`)).data,Vv=r=>`${pv()}/binaryContents/${r}/download`,An=Pr((r,i)=>({binaryContents:{},fetchBinaryContent:async s=>{if(i().binaryContents[s])return i().binaryContents[s];try{const l=await Hv(s),{contentType:c,fileName:d,size:p}=l,w={url:Vv(s),contentType:c,fileName:d,size:p};return r(v=>({binaryContents:{...v.binaryContents,[s]:w}})),w}catch(l){return console.error("첨부파일 정보 조회 실패:",l),null}}})),Do=k.div` + position: absolute; + bottom: -3px; + right: -3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: ${r=>r.$online?q.colors.status.online:q.colors.status.offline}; + border: 4px solid ${r=>r.$background||q.colors.background.secondary}; +`;k.div` + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + background: ${r=>q.colors.status[r.status||"offline"]||q.colors.status.offline}; +`;const Nr=k.div` + position: relative; + width: ${r=>r.$size||"32px"}; + height: ${r=>r.$size||"32px"}; + flex-shrink: 0; + margin: ${r=>r.$margin||"0"}; +`,nn=k.img` + width: 100%; + height: 100%; + border-radius: 50%; + object-fit: cover; + border: ${r=>r.$border||"none"}; +`;function Wv({isOpen:r,onClose:i,user:s}){var M,V;const[l,c]=K.useState(s.username),[d,p]=K.useState(s.email),[g,w]=K.useState(""),[v,S]=K.useState(null),[j,R]=K.useState(""),[L,T]=K.useState(null),{binaryContents:O,fetchBinaryContent:_}=An(),{logout:b,fetchMe:U}=pt();K.useEffect(()=>{var ne;(ne=s.profile)!=null&&ne.id&&!O[s.profile.id]&&_(s.profile.id)},[s.profile,O,_]);const B=()=>{c(s.username),p(s.email),w(""),S(null),T(null),R(""),i()},W=ne=>{var Ie;const ye=(Ie=ne.target.files)==null?void 0:Ie[0];if(ye){S(ye);const ie=new FileReader;ie.onloadend=()=>{T(ie.result)},ie.readAsDataURL(ye)}},I=async ne=>{ne.preventDefault(),R("");try{const ye=new FormData,Ie={};l!==s.username&&(Ie.newUsername=l),d!==s.email&&(Ie.newEmail=d),g&&(Ie.newPassword=g),(Object.keys(Ie).length>0||v)&&(ye.append("userUpdateRequest",new Blob([JSON.stringify(Ie)],{type:"application/json"})),v&&ye.append("profile",v),await hv(s.id,ye),await U()),i()}catch{R("사용자 정보 수정에 실패했습니다.")}};return r?h.jsx(Yv,{children:h.jsxs(qv,{children:[h.jsx("h2",{children:"프로필 수정"}),h.jsxs("form",{onSubmit:I,children:[h.jsxs(Xi,{children:[h.jsx(Ji,{children:"프로필 이미지"}),h.jsxs(Gv,{children:[h.jsx(Kv,{src:L||((M=s.profile)!=null&&M.id?(V=O[s.profile.id])==null?void 0:V.url:void 0)||St,alt:"profile"}),h.jsx(Xv,{type:"file",accept:"image/*",onChange:W,id:"profile-image"}),h.jsx(Jv,{htmlFor:"profile-image",children:"이미지 변경"})]})]}),h.jsxs(Xi,{children:[h.jsxs(Ji,{children:["사용자명 ",h.jsx(Gf,{children:"*"})]}),h.jsx(La,{type:"text",value:l,onChange:ne=>c(ne.target.value),required:!0})]}),h.jsxs(Xi,{children:[h.jsxs(Ji,{children:["이메일 ",h.jsx(Gf,{children:"*"})]}),h.jsx(La,{type:"email",value:d,onChange:ne=>p(ne.target.value),required:!0})]}),h.jsxs(Xi,{children:[h.jsx(Ji,{children:"새 비밀번호"}),h.jsx(La,{type:"password",placeholder:"변경하지 않으려면 비워두세요",value:g,onChange:ne=>w(ne.target.value)})]}),j&&h.jsx(Qv,{children:j}),h.jsxs(Zv,{children:[h.jsx(Qf,{type:"button",onClick:B,$secondary:!0,children:"취소"}),h.jsx(Qf,{type:"submit",children:"저장"})]})]}),h.jsx(ex,{onClick:b,children:"로그아웃"})]})}):null}const Yv=k.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; +`,qv=k.div` + background: ${({theme:r})=>r.colors.background.secondary}; + padding: 32px; + border-radius: 5px; + width: 100%; + max-width: 480px; + + h2 { + color: ${({theme:r})=>r.colors.text.primary}; + margin-bottom: 24px; + text-align: center; + font-size: 24px; + } +`,La=k.input` + width: 100%; + padding: 10px; + margin-bottom: 10px; + border: none; + border-radius: 4px; + background: ${({theme:r})=>r.colors.background.input}; + color: ${({theme:r})=>r.colors.text.primary}; + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${({theme:r})=>r.colors.brand.primary}; + } +`,Qf=k.button` + width: 100%; + padding: 10px; + border: none; + border-radius: 4px; + background: ${({$secondary:r,theme:i})=>r?"transparent":i.colors.brand.primary}; + color: ${({theme:r})=>r.colors.text.primary}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({$secondary:r,theme:i})=>r?i.colors.background.hover:i.colors.brand.hover}; + } +`,Qv=k.div` + color: ${({theme:r})=>r.colors.status.error}; + font-size: 14px; + margin-bottom: 10px; +`,Gv=k.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 20px; +`,Kv=k.img` + width: 100px; + height: 100px; + border-radius: 50%; + margin-bottom: 10px; + object-fit: cover; +`,Xv=k.input` + display: none; +`,Jv=k.label` + color: ${({theme:r})=>r.colors.brand.primary}; + cursor: pointer; + font-size: 14px; + + &:hover { + text-decoration: underline; + } +`,Zv=k.div` + display: flex; + gap: 10px; + margin-top: 20px; +`,ex=k.button` + width: 100%; + padding: 10px; + margin-top: 16px; + border: none; + border-radius: 4px; + background: transparent; + color: ${({theme:r})=>r.colors.status.error}; + cursor: pointer; + font-weight: 500; + + &:hover { + background: ${({theme:r})=>r.colors.status.error}20; + } +`,Xi=k.div` + margin-bottom: 20px; +`,Ji=k.label` + display: block; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 12px; + font-weight: 700; + margin-bottom: 8px; +`,Gf=k.span` + color: ${({theme:r})=>r.colors.status.error}; +`,tx=k.div` + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.5rem 0.75rem; + background-color: ${({theme:r})=>r.colors.background.tertiary}; + width: 100%; + height: 52px; +`,nx=k(Nr)``;k(nn)``;const rx=k.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; +`,ox=k.div` + font-weight: 500; + color: ${({theme:r})=>r.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.875rem; + line-height: 1.2; +`,ix=k.div` + font-size: 0.75rem; + color: ${({theme:r})=>r.colors.text.secondary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.2; +`,sx=k.div` + display: flex; + align-items: center; + flex-shrink: 0; +`,lx=k.button` + background: none; + border: none; + padding: 0.25rem; + cursor: pointer; + color: ${({theme:r})=>r.colors.text.secondary}; + font-size: 18px; + + &:hover { + color: ${({theme:r})=>r.colors.text.primary}; + } +`;function ax({user:r}){var d,p;const[i,s]=K.useState(!1),{binaryContents:l,fetchBinaryContent:c}=An();return K.useEffect(()=>{var g;(g=r.profile)!=null&&g.id&&!l[r.profile.id]&&c(r.profile.id)},[r.profile,l,c]),h.jsxs(h.Fragment,{children:[h.jsxs(tx,{children:[h.jsxs(nx,{children:[h.jsx(nn,{src:(d=r.profile)!=null&&d.id?(p=l[r.profile.id])==null?void 0:p.url:St,alt:r.username}),h.jsx(Do,{$online:!0})]}),h.jsxs(rx,{children:[h.jsx(ox,{children:r.username}),h.jsx(ix,{children:"온라인"})]}),h.jsx(sx,{children:h.jsx(lx,{onClick:()=>s(!0),children:"⚙️"})})]}),h.jsx(Wv,{isOpen:i,onClose:()=>s(!1),user:r})]})}const ux=k.div` + width: 240px; + background: ${q.colors.background.secondary}; + border-right: 1px solid ${q.colors.border.primary}; + display: flex; + flex-direction: column; +`,cx=k.div` + flex: 1; + overflow-y: auto; +`,dx=k.div` + padding: 16px; + font-size: 16px; + font-weight: bold; + color: ${q.colors.text.primary}; +`,du=k.div` + height: 34px; + padding: 0 8px; + margin: 1px 8px; + display: flex; + align-items: center; + gap: 6px; + color: ${r=>r.$hasUnread?r.theme.colors.text.primary:r.theme.colors.text.muted}; + font-weight: ${r=>r.$hasUnread?"600":"normal"}; + cursor: pointer; + background: ${r=>r.$isActive?r.theme.colors.background.hover:"transparent"}; + border-radius: 4px; + + &:hover { + background: ${r=>r.theme.colors.background.hover}; + color: ${r=>r.theme.colors.text.primary}; + } +`,Kf=k.div` + margin-bottom: 8px; +`,Ja=k.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${q.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: ${q.colors.text.primary}; + } +`,Xf=k.span` + margin-right: 4px; + font-size: 10px; + transition: transform 0.2s; + transform: rotate(${r=>r.$folded?"-90deg":"0deg"}); +`,Jf=k.div` + display: ${r=>r.$folded?"none":"block"}; +`,Za=k(du)` + height: ${r=>r.hasSubtext?"42px":"34px"}; +`,fx=k(Nr)` + width: 32px; + height: 32px; + margin: 0 8px; +`,Zf=k.div` + font-size: 16px; + line-height: 18px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: ${r=>r.$isActive||r.$hasUnread?r.theme.colors.text.primary:r.theme.colors.text.muted}; + font-weight: ${r=>r.$hasUnread?"600":"normal"}; +`;k(Do)` + border-color: ${q.colors.background.primary}; +`;const ep=k.button` + background: none; + border: none; + color: ${q.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; + + ${Ja}:hover & { + opacity: 1; + } + + &:hover { + color: ${q.colors.text.primary}; + } +`,px=k(Nr)` + width: 40px; + height: 24px; + margin: 0 8px; +`,hx=k.div` + font-size: 12px; + line-height: 13px; + color: ${q.colors.text.muted}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,tp=k.div` + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; +`,ch=k.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; +`,dh=k.div` + background: ${q.colors.background.primary}; + border-radius: 4px; + width: 440px; + max-width: 90%; +`,fh=k.div` + padding: 16px; + display: flex; + justify-content: space-between; + align-items: center; +`,ph=k.h2` + color: ${q.colors.text.primary}; + font-size: 20px; + font-weight: 600; + margin: 0; +`,hh=k.div` + padding: 0 16px 16px; +`,mh=k.form` + display: flex; + flex-direction: column; + gap: 16px; +`,Ro=k.div` + display: flex; + flex-direction: column; + gap: 8px; +`,Po=k.label` + color: ${q.colors.text.primary}; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; +`,gh=k.p` + color: ${q.colors.text.muted}; + font-size: 14px; + margin: -4px 0 0; +`,Mo=k.input` + padding: 10px; + background: ${q.colors.background.tertiary}; + border: none; + border-radius: 3px; + color: ${q.colors.text.primary}; + font-size: 16px; + + &:focus { + outline: none; + box-shadow: 0 0 0 2px ${q.colors.status.online}; + } + + &::placeholder { + color: ${q.colors.text.muted}; + } +`,yh=k.button` + margin-top: 8px; + padding: 12px; + background: ${q.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; + } +`,vh=k.button` + background: none; + border: none; + color: ${q.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px; + line-height: 1; + + &:hover { + color: ${q.colors.text.primary}; + } +`,mx=k(Mo)` + margin-bottom: 8px; +`,gx=k.div` + max-height: 300px; + overflow-y: auto; + background: ${q.colors.background.tertiary}; + border-radius: 4px; +`,yx=k.div` + display: flex; + align-items: center; + padding: 8px 12px; + cursor: pointer; + transition: background 0.2s; + + &:hover { + background: ${q.colors.background.hover}; + } + + & + & { + border-top: 1px solid ${q.colors.border.primary}; + } +`,vx=k.input` + margin-right: 12px; + width: 16px; + height: 16px; + cursor: pointer; +`,np=k.img` + width: 32px; + height: 32px; + border-radius: 50%; + margin-right: 12px; +`,xx=k.div` + flex: 1; + min-width: 0; +`,wx=k.div` + color: ${q.colors.text.primary}; + font-size: 14px; + font-weight: 500; +`,Sx=k.div` + color: ${q.colors.text.muted}; + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,Cx=k.div` + padding: 16px; + text-align: center; + color: ${q.colors.text.muted}; +`,xh=k.div` + color: ${q.colors.status.error}; + font-size: 14px; + padding: 8px 0; + text-align: center; + background-color: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 4px; + margin-bottom: 8px; +`,Ia=k.div` + position: relative; + margin-left: auto; + z-index: 99999; +`,Da=k.button` + background: none; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.background.hover}; + color: ${({theme:r})=>r.colors.text.primary}; + } + + ${du}:hover &, + ${Za}:hover & { + opacity: 1; + } +`,za=k.div` + position: absolute; + top: 100%; + right: 0; + background: ${({theme:r})=>r.colors.background.primary}; + border: 1px solid ${({theme:r})=>r.colors.border.primary}; + border-radius: 4px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); + min-width: 120px; + z-index: 100000; +`,Zi=k.div` + padding: 8px 12px; + color: ${({theme:r})=>r.colors.text.primary}; + cursor: pointer; + font-size: 14px; + display: flex; + align-items: center; + gap: 8px; + + &:hover { + background: ${({theme:r})=>r.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 kx(){return h.jsx(dx,{children:"채널 목록"})}var En=(r=>(r.USER="USER",r.CHANNEL_MANAGER="CHANNEL_MANAGER",r.ADMIN="ADMIN",r))(En||{});function Ex({isOpen:r,channel:i,onClose:s,onUpdateSuccess:l}){const[c,d]=K.useState({name:"",description:""}),[p,g]=K.useState(""),[w,v]=K.useState(!1),{updatePublicChannel:S}=jn();K.useEffect(()=>{i&&r&&(d({name:i.name||"",description:i.description||""}),g(""))},[i,r]);const j=L=>{const{name:T,value:O}=L.target;d(_=>({..._,[T]:O}))},R=async L=>{var T,O;if(L.preventDefault(),!!i){g(""),v(!0);try{if(!c.name.trim()){g("채널 이름을 입력해주세요."),v(!1);return}const _={newName:c.name.trim(),newDescription:c.description.trim()},b=await S(i.id,_);l(b)}catch(_){console.error("채널 수정 실패:",_),g(((O=(T=_.response)==null?void 0:T.data)==null?void 0:O.message)||"채널 수정에 실패했습니다. 다시 시도해주세요.")}finally{v(!1)}}};return!r||!i||i.type!=="PUBLIC"?null:h.jsx(ch,{onClick:s,children:h.jsxs(dh,{onClick:L=>L.stopPropagation(),children:[h.jsxs(fh,{children:[h.jsx(ph,{children:"채널 수정"}),h.jsx(vh,{onClick:s,children:"×"})]}),h.jsx(hh,{children:h.jsxs(mh,{onSubmit:R,children:[p&&h.jsx(xh,{children:p}),h.jsxs(Ro,{children:[h.jsx(Po,{children:"채널 이름"}),h.jsx(Mo,{name:"name",value:c.name,onChange:j,placeholder:"새로운-채널",required:!0,disabled:w})]}),h.jsxs(Ro,{children:[h.jsx(Po,{children:"채널 설명"}),h.jsx(gh,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Mo,{name:"description",value:c.description,onChange:j,placeholder:"채널 설명을 입력하세요",disabled:w})]}),h.jsx(yh,{type:"submit",disabled:w,children:w?"수정 중...":"채널 수정"})]})})]})})}function rp({channel:r,isActive:i,onClick:s,hasUnread:l}){var U;const{currentUser:c}=pt(),{binaryContents:d}=An(),{deleteChannel:p}=jn(),[g,w]=K.useState(null),[v,S]=K.useState(!1),j=(c==null?void 0:c.role)===En.ADMIN||(c==null?void 0:c.role)===En.CHANNEL_MANAGER;K.useEffect(()=>{const B=()=>{g&&w(null)};if(g)return document.addEventListener("click",B),()=>document.removeEventListener("click",B)},[g]);const R=B=>{w(g===B?null:B)},L=()=>{w(null),S(!0)},T=B=>{S(!1),console.log("Channel updated successfully:",B)},O=()=>{S(!1)},_=async B=>{var I;w(null);const W=r.type==="PUBLIC"?r.name:r.type==="PRIVATE"&&r.participants.length>2?`그룹 채팅 (멤버 ${r.participants.length}명)`:((I=r.participants.filter(M=>M.id!==(c==null?void 0:c.id))[0])==null?void 0:I.username)||"1:1 채팅";if(confirm(`"${W}" 채널을 삭제하시겠습니까?`))try{await p(B),console.log("Channel deleted successfully:",B)}catch(M){console.error("Channel delete failed:",M),alert("채널 삭제에 실패했습니다. 다시 시도해주세요.")}};let b;if(r.type==="PUBLIC")b=h.jsxs(du,{$isActive:i,onClick:s,$hasUnread:l,children:["# ",r.name,j&&h.jsxs(Ia,{children:[h.jsx(Da,{onClick:B=>{B.stopPropagation(),R(r.id)},children:"⋯"}),g===r.id&&h.jsxs(za,{onClick:B=>B.stopPropagation(),children:[h.jsx(Zi,{onClick:()=>L(),children:"✏️ 수정"}),h.jsx(Zi,{onClick:()=>_(r.id),children:"🗑️ 삭제"})]})]})]});else{const B=r.participants;if(B.length>2){const W=B.filter(I=>I.id!==(c==null?void 0:c.id)).map(I=>I.username).join(", ");b=h.jsxs(Za,{$isActive:i,onClick:s,children:[h.jsx(px,{children:B.filter(I=>I.id!==(c==null?void 0:c.id)).slice(0,2).map((I,M)=>{var V;return h.jsx(nn,{src:I.profile?(V=d[I.profile.id])==null?void 0:V.url:St,style:{position:"absolute",left:M*16,zIndex:2-M,width:"24px",height:"24px",border:"2px solid #2a2a2a"}},I.id)})}),h.jsxs(tp,{children:[h.jsx(Zf,{$hasUnread:l,children:W}),h.jsxs(hx,{children:["멤버 ",B.length,"명"]})]}),j&&h.jsxs(Ia,{children:[h.jsx(Da,{onClick:I=>{I.stopPropagation(),R(r.id)},children:"⋯"}),g===r.id&&h.jsx(za,{onClick:I=>I.stopPropagation(),children:h.jsx(Zi,{onClick:()=>_(r.id),children:"🗑️ 삭제"})})]})]})}else{const W=B.filter(I=>I.id!==(c==null?void 0:c.id))[0];b=W?h.jsxs(Za,{$isActive:i,onClick:s,children:[h.jsxs(fx,{children:[h.jsx(nn,{src:W.profile?(U=d[W.profile.id])==null?void 0:U.url:St,alt:"profile"}),h.jsx(Do,{$online:W.online})]}),h.jsx(tp,{children:h.jsx(Zf,{$hasUnread:l,children:W.username})}),j&&h.jsxs(Ia,{children:[h.jsx(Da,{onClick:I=>{I.stopPropagation(),R(r.id)},children:"⋯"}),g===r.id&&h.jsx(za,{onClick:I=>I.stopPropagation(),children:h.jsx(Zi,{onClick:()=>_(r.id),children:"🗑️ 삭제"})})]})]}):h.jsx("div",{})}}return h.jsxs(h.Fragment,{children:[b,h.jsx(Ex,{isOpen:v,channel:r,onClose:O,onUpdateSuccess:T})]})}function jx({isOpen:r,type:i,onClose:s,onCreateSuccess:l}){const[c,d]=K.useState({name:"",description:""}),[p,g]=K.useState(""),[w,v]=K.useState([]),[S,j]=K.useState(""),R=Ar(I=>I.users),L=An(I=>I.binaryContents),{currentUser:T}=pt(),O=K.useMemo(()=>R.filter(I=>I.id!==(T==null?void 0:T.id)).filter(I=>I.username.toLowerCase().includes(p.toLowerCase())||I.email.toLowerCase().includes(p.toLowerCase())),[p,R,T]),_=jn(I=>I.createPublicChannel),b=jn(I=>I.createPrivateChannel),U=I=>{const{name:M,value:V}=I.target;d(ne=>({...ne,[M]:V}))},B=I=>{v(M=>M.includes(I)?M.filter(V=>V!==I):[...M,I])},W=async I=>{var M,V;I.preventDefault(),j("");try{let ne;if(i==="PUBLIC"){if(!c.name.trim()){j("채널 이름을 입력해주세요.");return}const ye={name:c.name,description:c.description};ne=await _(ye)}else{if(w.length===0){j("대화 상대를 선택해주세요.");return}const ye=(T==null?void 0:T.id)&&[...w,T.id]||w;ne=await b(ye)}l(ne)}catch(ne){console.error("채널 생성 실패:",ne),j(((V=(M=ne.response)==null?void 0:M.data)==null?void 0:V.message)||"채널 생성에 실패했습니다. 다시 시도해주세요.")}};return r?h.jsx(ch,{onClick:s,children:h.jsxs(dh,{onClick:I=>I.stopPropagation(),children:[h.jsxs(fh,{children:[h.jsx(ph,{children:i==="PUBLIC"?"채널 만들기":"개인 메시지 시작하기"}),h.jsx(vh,{onClick:s,children:"×"})]}),h.jsx(hh,{children:h.jsxs(mh,{onSubmit:W,children:[S&&h.jsx(xh,{children:S}),i==="PUBLIC"?h.jsxs(h.Fragment,{children:[h.jsxs(Ro,{children:[h.jsx(Po,{children:"채널 이름"}),h.jsx(Mo,{name:"name",value:c.name,onChange:U,placeholder:"새로운-채널",required:!0})]}),h.jsxs(Ro,{children:[h.jsx(Po,{children:"채널 설명"}),h.jsx(gh,{children:"이 채널의 주제를 설명해주세요."}),h.jsx(Mo,{name:"description",value:c.description,onChange:U,placeholder:"채널 설명을 입력하세요"})]})]}):h.jsxs(Ro,{children:[h.jsx(Po,{children:"사용자 검색"}),h.jsx(mx,{type:"text",value:p,onChange:I=>g(I.target.value),placeholder:"사용자명 또는 이메일로 검색"}),h.jsx(gx,{children:O.length>0?O.map(I=>h.jsxs(yx,{children:[h.jsx(vx,{type:"checkbox",checked:w.includes(I.id),onChange:()=>B(I.id)}),I.profile?h.jsx(np,{src:L[I.profile.id].url}):h.jsx(np,{src:St}),h.jsxs(xx,{children:[h.jsx(wx,{children:I.username}),h.jsx(Sx,{children:I.email})]})]},I.id)):h.jsx(Cx,{children:"검색 결과가 없습니다."})})]}),h.jsx(yh,{type:"submit",children:i==="PUBLIC"?"채널 만들기":"대화 시작하기"})]})})]})}):null}function Ax({currentUser:r,activeChannel:i,onChannelSelect:s}){var W,I;const[l,c]=K.useState({PUBLIC:!1,PRIVATE:!1}),[d,p]=K.useState({isOpen:!1,type:null}),g=jn(M=>M.channels),w=jn(M=>M.fetchChannels),v=jn(M=>M.startPolling),S=jn(M=>M.stopPolling),j=Ao(M=>M.fetchReadStatuses),R=Ao(M=>M.updateReadStatus),L=Ao(M=>M.hasUnreadMessages);K.useEffect(()=>{if(r)return w(r.id),j(),v(r.id),()=>{S()}},[r,w,j,v,S]);const T=M=>{c(V=>({...V,[M]:!V[M]}))},O=(M,V)=>{V.stopPropagation(),p({isOpen:!0,type:M})},_=()=>{p({isOpen:!1,type:null})},b=async M=>{try{const ne=(await w(r.id)).find(ye=>ye.id===M.id);ne&&s(ne),_()}catch(V){console.error("채널 생성 실패:",V)}},U=M=>{s(M),R(M.id)},B=g.reduce((M,V)=>(M[V.type]||(M[V.type]=[]),M[V.type].push(V),M),{});return h.jsxs(ux,{children:[h.jsx(kx,{}),h.jsxs(cx,{children:[h.jsxs(Kf,{children:[h.jsxs(Ja,{onClick:()=>T("PUBLIC"),children:[h.jsx(Xf,{$folded:l.PUBLIC,children:"▼"}),h.jsx("span",{children:"일반 채널"}),h.jsx(ep,{onClick:M=>O("PUBLIC",M),children:"+"})]}),h.jsx(Jf,{$folded:l.PUBLIC,children:(W=B.PUBLIC)==null?void 0:W.map(M=>h.jsx(rp,{channel:M,isActive:(i==null?void 0:i.id)===M.id,hasUnread:L(M.id,M.lastMessageAt),onClick:()=>U(M)},M.id))})]}),h.jsxs(Kf,{children:[h.jsxs(Ja,{onClick:()=>T("PRIVATE"),children:[h.jsx(Xf,{$folded:l.PRIVATE,children:"▼"}),h.jsx("span",{children:"개인 메시지"}),h.jsx(ep,{onClick:M=>O("PRIVATE",M),children:"+"})]}),h.jsx(Jf,{$folded:l.PRIVATE,children:(I=B.PRIVATE)==null?void 0:I.map(M=>h.jsx(rp,{channel:M,isActive:(i==null?void 0:i.id)===M.id,hasUnread:L(M.id,M.lastMessageAt),onClick:()=>U(M)},M.id))})]})]}),h.jsx(Rx,{children:h.jsx(ax,{user:r})}),h.jsx(jx,{isOpen:d.isOpen,type:d.type,onClose:_,onCreateSuccess:b})]})}const Rx=k.div` + margin-top: auto; + border-top: 1px solid ${({theme:r})=>r.colors.border.primary}; + background-color: ${({theme:r})=>r.colors.background.tertiary}; +`,Px=k.div` + flex: 1; + display: flex; + flex-direction: column; + background: ${({theme:r})=>r.colors.background.primary}; +`,Tx=k.div` + display: flex; + flex-direction: column; + height: 100%; + background: ${({theme:r})=>r.colors.background.primary}; +`,_x=k(Tx)` + justify-content: center; + align-items: center; + flex: 1; + padding: 0 20px; +`,Nx=k.div` + text-align: center; + max-width: 400px; + padding: 20px; + margin-bottom: 80px; +`,Ox=k.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); } + } +`,Mx=k.h2` + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 28px; + font-weight: 700; + margin-bottom: 16px; +`,Lx=k.p` + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 16px; + line-height: 1.6; + word-break: keep-all; +`,op=k.div` + height: 48px; + padding: 0 16px; + background: ${q.colors.background.primary}; + border-bottom: 1px solid ${q.colors.border.primary}; + display: flex; + align-items: center; +`,ip=k.div` + display: flex; + align-items: center; + gap: 8px; + height: 100%; +`,Ix=k.div` + display: flex; + align-items: center; + gap: 12px; + height: 100%; +`,Dx=k(Nr)` + width: 24px; + height: 24px; +`;k.img` + width: 24px; + height: 24px; + border-radius: 50%; +`;const zx=k.div` + position: relative; + width: 40px; + height: 24px; + flex-shrink: 0; +`,$x=k(Do)` + border-color: ${q.colors.background.primary}; + bottom: -3px; + right: -3px; +`,Fx=k.div` + font-size: 12px; + color: ${q.colors.text.muted}; + line-height: 13px; +`,sp=k.div` + font-weight: bold; + color: ${q.colors.text.primary}; + line-height: 20px; + font-size: 16px; +`,Bx=k.div` + flex: 1; + display: flex; + flex-direction: column-reverse; + overflow-y: auto; + position: relative; +`,bx=k.div` + padding: 16px; + display: flex; + flex-direction: column; +`,wh=k.div` + margin-bottom: 16px; + display: flex; + align-items: flex-start; + position: relative; + z-index: 1; +`,Ux=k(Nr)` + margin-right: 16px; + width: 40px; + height: 40px; +`;k.img` + width: 40px; + height: 40px; + border-radius: 50%; +`;const Hx=k.div` + display: flex; + align-items: center; + margin-bottom: 4px; + position: relative; +`,Vx=k.span` + font-weight: bold; + color: ${q.colors.text.primary}; + margin-right: 8px; +`,Wx=k.span` + font-size: 0.75rem; + color: ${q.colors.text.muted}; +`,Yx=k.div` + color: ${q.colors.text.secondary}; + margin-top: 4px; +`,qx=k.form` + display: flex; + align-items: center; + gap: 8px; + padding: 16px; + background: ${({theme:r})=>r.colors.background.secondary}; + position: relative; + z-index: 1; +`,Qx=k.textarea` + flex: 1; + padding: 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border: none; + border-radius: 4px; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + resize: none; + min-height: 44px; + max-height: 144px; + + &:focus { + outline: none; + } + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } +`,Gx=k.button` + background: none; + border: none; + color: ${({theme:r})=>r.colors.text.muted}; + font-size: 24px; + cursor: pointer; + padding: 4px 8px; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + color: ${({theme:r})=>r.colors.text.primary}; + } +`;k.div` + flex: 1; + display: flex; + align-items: center; + justify-content: center; + color: ${q.colors.text.muted}; + font-size: 16px; + font-weight: 500; + padding: 20px; + text-align: center; +`;const lp=k.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; + width: 100%; +`,Kx=k.a` + display: block; + border-radius: 4px; + overflow: hidden; + max-width: 300px; + + img { + width: 100%; + height: auto; + display: block; + } +`,Xx=k.a` + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 8px; + text-decoration: none; + width: fit-content; + + &:hover { + background: ${({theme:r})=>r.colors.background.hover}; + } +`,Jx=k.div` + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + font-size: 40px; + color: #0B93F6; +`,Zx=k.div` + display: flex; + flex-direction: column; + gap: 2px; +`,e1=k.span` + font-size: 14px; + color: #0B93F6; + font-weight: 500; +`,t1=k.span` + font-size: 13px; + color: ${({theme:r})=>r.colors.text.muted}; +`,n1=k.div` + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px 0; +`,Sh=k.div` + position: relative; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border-radius: 4px; + max-width: 300px; +`,r1=k(Sh)` + padding: 0; + overflow: hidden; + width: 200px; + height: 120px; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } +`,o1=k.div` + color: #0B93F6; + font-size: 20px; +`,i1=k.div` + font-size: 13px; + color: ${({theme:r})=>r.colors.text.primary}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +`,ap=k.button` + position: absolute; + top: -6px; + right: -6px; + width: 20px; + height: 20px; + border-radius: 50%; + background: ${({theme:r})=>r.colors.background.secondary}; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.text.primary}; + } +`,s1=k.div` + position: relative; + margin-left: auto; + z-index: 99999; +`,l1=k.button` + background: none; + border: none; + color: ${({theme:r})=>r.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:r})=>r.colors.text.primary}; + background: ${({theme:r})=>r.colors.background.hover}; + } + + ${wh}:hover & { + opacity: 1; + } +`,a1=k.div` + position: absolute; + top: 0; + background: ${({theme:r})=>r.colors.background.primary}; + border: 1px solid ${({theme:r})=>r.colors.border.primary}; + border-radius: 6px; + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15); + width: 80px; + z-index: 99999; + overflow: hidden; +`,up=k.button` + display: flex; + align-items: center; + gap: 8px; + width: fit-content; + background: none; + border: none; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + cursor: pointer; + text-align: center ; + + &:hover { + background: ${({theme:r})=>r.colors.background.hover}; + } + + &:first-child { + border-radius: 6px 6px 0 0; + } + + &:last-child { + border-radius: 0 0 6px 6px; + } +`,u1=k.div` + margin-top: 4px; +`,c1=k.textarea` + width: 100%; + max-width: 600px; + min-height: 80px; + padding: 12px 16px; + background: ${({theme:r})=>r.colors.background.tertiary}; + border: 1px solid ${({theme:r})=>r.colors.border.primary}; + border-radius: 4px; + color: ${({theme:r})=>r.colors.text.primary}; + font-size: 14px; + font-family: inherit; + resize: vertical; + outline: none; + box-sizing: border-box; + + &:focus { + border-color: ${({theme:r})=>r.colors.primary}; + } + + &::placeholder { + color: ${({theme:r})=>r.colors.text.muted}; + } +`,d1=k.div` + display: flex; + gap: 8px; + margin-top: 8px; +`,cp=k.button` + padding: 6px 12px; + border-radius: 4px; + font-size: 12px; + font-weight: 500; + cursor: pointer; + border: none; + transition: background-color 0.2s ease; + + ${({variant:r,theme:i})=>r==="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}; + } + `} +`;function f1({channel:r}){var w;const{currentUser:i}=pt(),s=Ar(v=>v.users),l=An(v=>v.binaryContents);if(!r)return null;if(r.type==="PUBLIC")return h.jsx(op,{children:h.jsx(ip,{children:h.jsxs(sp,{children:["# ",r.name]})})});const c=r.participants.map(v=>s.find(S=>S.id===v.id)).filter(Boolean),d=c.filter(v=>v.id!==(i==null?void 0:i.id)),p=c.length>2,g=c.filter(v=>v.id!==(i==null?void 0:i.id)).map(v=>v.username).join(", ");return h.jsx(op,{children:h.jsx(ip,{children:h.jsxs(Ix,{children:[p?h.jsx(zx,{children:d.slice(0,2).map((v,S)=>{var j;return h.jsx(nn,{src:v.profile?(j=l[v.profile.id])==null?void 0:j.url:St,style:{position:"absolute",left:S*16,zIndex:2-S,width:"24px",height:"24px"}},v.id)})}):h.jsxs(Dx,{children:[h.jsx(nn,{src:d[0].profile?(w=l[d[0].profile.id])==null?void 0:w.url:St}),h.jsx($x,{$online:d[0].online})]}),h.jsxs("div",{children:[h.jsx(sp,{children:g}),p&&h.jsxs(Fx,{children:["멤버 ",c.length,"명"]})]})]})})})}const p1=async(r,i,s)=>{var c;return(await Oe.get("/messages",{params:{channelId:r,cursor:i,size:s.size,sort:(c=s.sort)==null?void 0:c.join(",")}})).data},h1=async(r,i)=>{const s=new FormData,l={content:r.content,channelId:r.channelId,authorId:r.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 Oe.post("/messages",s,{headers:{"Content-Type":"multipart/form-data"}})).data},m1=async(r,i)=>(await Oe.patch(`/messages/${r}`,i)).data,g1=async r=>{await Oe.delete(`/messages/${r}`)},$a={size:50,sort:["createdAt,desc"]},Ch=Pr((r,i)=>({messages:[],pollingIntervals:{},lastMessageId:null,pagination:{nextCursor:null,pageSize:50,hasNext:!1},fetchMessages:async(s,l,c=$a)=>{try{const d=await p1(s,l,c),p=d.content,g=p.length>0?p[0]:null,w=(g==null?void 0:g.id)!==i().lastMessageId;return r(v=>{var O;const S=!l,j=s!==((O=v.messages[0])==null?void 0:O.channelId),R=S&&(v.messages.length===0||j);let L=[],T={...v.pagination};if(R)L=p,T={nextCursor:d.nextCursor,pageSize:d.size,hasNext:d.hasNext};else if(S){const _=new Set(v.messages.map(U=>U.id));L=[...p.filter(U=>!_.has(U.id)&&(v.messages.length===0||U.createdAt>v.messages[0].createdAt)),...v.messages]}else{const _=new Set(v.messages.map(U=>U.id)),b=p.filter(U=>!_.has(U.id));L=[...v.messages,...b],T={nextCursor:d.nextCursor,pageSize:d.size,hasNext:d.hasNext}}return{messages:L,lastMessageId:(g==null?void 0:g.id)||null,pagination:T}}),w}catch(d){return console.error("메시지 목록 조회 실패:",d),!1}},loadMoreMessages:async s=>{const{pagination:l}=i();l.hasNext&&await i().fetchMessages(s,l.nextCursor,{...$a})},startPolling:s=>{const l=i();if(l.pollingIntervals[s]){const g=l.pollingIntervals[s];typeof g=="number"&&clearTimeout(g)}let c=300;const d=3e3;r(g=>({pollingIntervals:{...g.pollingIntervals,[s]:!0}}));const p=async()=>{const g=i();if(!g.pollingIntervals[s])return;const w=await g.fetchMessages(s,null,$a);if(!(i().messages.length==0)&&w?c=300:c=Math.min(c*1.5,d),i().pollingIntervals[s]){const S=setTimeout(p,c);r(j=>({pollingIntervals:{...j.pollingIntervals,[s]:S}}))}};p()},stopPolling:s=>{const{pollingIntervals:l}=i();if(l[s]){const c=l[s];typeof c=="number"&&clearTimeout(c),r(d=>{const p={...d.pollingIntervals};return delete p[s],{pollingIntervals:p}})}},createMessage:async(s,l)=>{try{const c=await h1(s,l),d=Ao.getState().updateReadStatus;return await d(s.channelId),r(p=>p.messages.some(w=>w.id===c.id)?p:{messages:[c,...p.messages],lastMessageId:c.id}),c}catch(c){throw console.error("메시지 생성 실패:",c),c}},updateMessage:async(s,l)=>{try{const c=await m1(s,{newContent:l});return r(d=>({messages:d.messages.map(p=>p.id===s?{...p,content:l}:p)})),c}catch(c){throw console.error("메시지 업데이트 실패:",c),c}},deleteMessage:async s=>{try{await g1(s),r(l=>({messages:l.messages.filter(c=>c.id!==s)}))}catch(l){throw console.error("메시지 삭제 실패:",l),l}}}));function y1({channel:r}){const[i,s]=K.useState(""),[l,c]=K.useState([]),d=Ch(R=>R.createMessage),{currentUser:p}=pt(),g=async R=>{if(R.preventDefault(),!(!i.trim()&&l.length===0))try{await d({content:i.trim(),channelId:r.id,authorId:(p==null?void 0:p.id)??""},l),s(""),c([])}catch(L){console.error("메시지 전송 실패:",L)}},w=R=>{const L=Array.from(R.target.files||[]);c(T=>[...T,...L]),R.target.value=""},v=R=>{c(L=>L.filter((T,O)=>O!==R))},S=R=>{if(R.key==="Enter"&&!R.shiftKey){if(console.log("Enter key pressed"),R.preventDefault(),R.nativeEvent.isComposing)return;g(R)}},j=(R,L)=>R.type.startsWith("image/")?h.jsxs(r1,{children:[h.jsx("img",{src:URL.createObjectURL(R),alt:R.name}),h.jsx(ap,{onClick:()=>v(L),children:"×"})]},L):h.jsxs(Sh,{children:[h.jsx(o1,{children:"📎"}),h.jsx(i1,{children:R.name}),h.jsx(ap,{onClick:()=>v(L),children:"×"})]},L);return K.useEffect(()=>()=>{l.forEach(R=>{R.type.startsWith("image/")&&URL.revokeObjectURL(URL.createObjectURL(R))})},[l]),r?h.jsxs(h.Fragment,{children:[l.length>0&&h.jsx(n1,{children:l.map((R,L)=>j(R,L))}),h.jsxs(qx,{onSubmit:g,children:[h.jsxs(Gx,{as:"label",children:["+",h.jsx("input",{type:"file",multiple:!0,onChange:w,style:{display:"none"}})]}),h.jsx(Qx,{value:i,onChange:R=>s(R.target.value),onKeyDown:S,placeholder:r.type==="PUBLIC"?`#${r.name}에 메시지 보내기`:"메시지 보내기"})]})]}):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 eu=function(r,i){return eu=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])},eu(r,i)};function v1(r,i){eu(r,i);function s(){this.constructor=r}r.prototype=i===null?Object.create(i):(s.prototype=i.prototype,new s)}var To=function(){return To=Object.assign||function(i){for(var s,l=1,c=arguments.length;lr?L():i!==!0&&(c=setTimeout(l?T:L,l===void 0?r-j:r))}return v.cancel=w,v}var Sr={Pixel:"Pixel",Percent:"Percent"},dp={unit:Sr.Percent,value:.8};function fp(r){return typeof r=="number"?{unit:Sr.Percent,value:r*100}:typeof r=="string"?r.match(/^(\d*(\.\d+)?)px$/)?{unit:Sr.Pixel,value:parseFloat(r)}:r.match(/^(\d*(\.\d+)?)%$/)?{unit:Sr.Percent,value:parseFloat(r)}:(console.warn('scrollThreshold format is invalid. Valid formats: "120px", "50%"...'),dp):(console.warn("scrollThreshold should be string or number"),dp)}var w1=function(r){v1(i,r);function i(s){var l=r.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 p=l.props.inverse?l.isElementAtTop(d,l.props.scrollThreshold):l.isElementAtBottom(d,l.props.scrollThreshold);p&&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=x1(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?To(To({},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=fp(l);return d.unit===Sr.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=fp(l);return d.unit===Sr.Pixel?s.scrollTop+c>=s.scrollHeight-d.value:s.scrollTop+c>=d.value/100*s.scrollHeight},i.prototype.render=function(){var s=this,l=To({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 xt.createElement("div",{style:d,className:"infinite-scroll-component__outerdiv"},xt.createElement("div",{className:"infinite-scroll-component "+(this.props.className||""),ref:function(p){return s._infScroll=p},style:l},this.props.pullDownToRefresh&&xt.createElement("div",{style:{position:"relative"},ref:function(p){return s._pullDown=p}},xt.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}(K.Component);const S1=r=>r<1024?r+" B":r<1024*1024?(r/1024).toFixed(2)+" KB":r<1024*1024*1024?(r/(1024*1024)).toFixed(2)+" MB":(r/(1024*1024*1024)).toFixed(2)+" GB";function C1({channel:r}){const{messages:i,fetchMessages:s,loadMoreMessages:l,pagination:c,startPolling:d,stopPolling:p,updateMessage:g,deleteMessage:w}=Ch(),{binaryContents:v,fetchBinaryContent:S}=An(),{currentUser:j}=pt(),[R,L]=K.useState(null),[T,O]=K.useState(null),[_,b]=K.useState("");K.useEffect(()=>{if(r!=null&&r.id)return s(r.id,null),d(r.id),()=>{p(r.id)}},[r==null?void 0:r.id,s,d,p]),K.useEffect(()=>{i.forEach(ie=>{var de;(de=ie.attachments)==null||de.forEach(me=>{v[me.id]||S(me.id)})})},[i,v,S]),K.useEffect(()=>{const ie=()=>{R&&L(null)};if(R)return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[R]);const U=async ie=>{try{const{url:de,fileName:me}=ie,_e=document.createElement("a");_e.href=de,_e.download=me,_e.style.display="none",document.body.appendChild(_e);try{const Ue=await(await window.showSaveFilePicker({suggestedName:ie.fileName,types:[{description:"Files",accept:{"*/*":[".txt",".pdf",".doc",".docx",".xls",".xlsx",".jpg",".jpeg",".png",".gif"]}}]})).createWritable(),Y=await(await fetch(de)).blob();await Ue.write(Y),await Ue.close()}catch(Se){Se.name!=="AbortError"&&_e.click()}document.body.removeChild(_e),window.URL.revokeObjectURL(de)}catch(de){console.error("파일 다운로드 실패:",de)}},B=ie=>ie!=null&&ie.length?ie.map(de=>{const me=v[de.id];return me?me.contentType.startsWith("image/")?h.jsx(lp,{children:h.jsx(Kx,{href:"#",onClick:Se=>{Se.preventDefault(),U(me)},children:h.jsx("img",{src:me.url,alt:me.fileName})})},me.url):h.jsx(lp,{children:h.jsxs(Xx,{href:"#",onClick:Se=>{Se.preventDefault(),U(me)},children:[h.jsx(Jx,{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(Zx,{children:[h.jsx(e1,{children:me.fileName}),h.jsx(t1,{children:S1(me.size)})]})]})},me.url):null}):null,W=ie=>new Date(ie).toLocaleTimeString(),I=()=>{r!=null&&r.id&&l(r.id)},M=ie=>{L(R===ie?null:ie)},V=ie=>{L(null);const de=i.find(me=>me.id===ie);de&&(O(ie),b(de.content))},ne=ie=>{g(ie,_).catch(de=>{console.error("메시지 수정 실패:",de),Oo.emit("api-error",{error:de,alert:!0})}),O(null),b("")},ye=()=>{O(null),b("")},Ie=ie=>{L(null),w(ie)};return h.jsx(Bx,{children:h.jsx("div",{id:"scrollableDiv",style:{height:"100%",overflow:"auto",display:"flex",flexDirection:"column-reverse"},children:h.jsx(w1,{dataLength:i.length,next:I,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(bx,{children:[...i].reverse().map(ie=>{var _e;const de=ie.author,me=j&&de&&de.id===j.id;return h.jsxs(wh,{children:[h.jsx(Ux,{children:h.jsx(nn,{src:de&&de.profile?(_e=v[de.profile.id])==null?void 0:_e.url:St,alt:de&&de.username||"알 수 없음"})}),h.jsxs("div",{children:[h.jsxs(Hx,{children:[h.jsx(Vx,{children:de&&de.username||"알 수 없음"}),h.jsx(Wx,{children:W(ie.createdAt)}),me&&h.jsxs(s1,{children:[h.jsx(l1,{onClick:Se=>{Se.stopPropagation(),M(ie.id)},children:"⋯"}),R===ie.id&&h.jsxs(a1,{onClick:Se=>Se.stopPropagation(),children:[h.jsx(up,{onClick:()=>V(ie.id),children:"✏️ 수정"}),h.jsx(up,{onClick:()=>Ie(ie.id),children:"🗑️ 삭제"})]})]})]}),T===ie.id?h.jsxs(u1,{children:[h.jsx(c1,{value:_,onChange:Se=>b(Se.target.value),onKeyDown:Se=>{Se.key==="Escape"?ye():Se.key==="Enter"&&(Se.ctrlKey||Se.metaKey)&&(Se.preventDefault(),ne(ie.id))},placeholder:"메시지를 입력하세요..."}),h.jsxs(d1,{children:[h.jsx(cp,{variant:"secondary",onClick:ye,children:"취소"}),h.jsx(cp,{variant:"primary",onClick:()=>ne(ie.id),children:"저장"})]})]}):h.jsx(Yx,{children:ie.content}),B(ie.attachments)]})]},ie.id)})})})})})}function k1({channel:r}){return r?h.jsxs(Px,{children:[h.jsx(f1,{channel:r}),h.jsx(C1,{channel:r}),h.jsx(y1,{channel:r})]}):h.jsx(_x,{children:h.jsxs(Nx,{children:[h.jsx(Ox,{children:"👋"}),h.jsx(Mx,{children:"채널을 선택해주세요"}),h.jsxs(Lx,{children:["왼쪽의 채널 목록에서 채널을 선택하여",h.jsx("br",{}),"대화를 시작하세요."]})]})})}function E1(r,i="yyyy-MM-dd HH:mm:ss"){if(!r||!(r instanceof Date)||isNaN(r.getTime()))return"";const s=r.getFullYear(),l=String(r.getMonth()+1).padStart(2,"0"),c=String(r.getDate()).padStart(2,"0"),d=String(r.getHours()).padStart(2,"0"),p=String(r.getMinutes()).padStart(2,"0"),g=String(r.getSeconds()).padStart(2,"0");return i.replace("yyyy",s.toString()).replace("MM",l).replace("dd",c).replace("HH",d).replace("mm",p).replace("ss",g)}const j1=k.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; +`,A1=k.div` + background: ${({theme:r})=>r.colors.background.primary}; + border-radius: 8px; + width: 500px; + max-width: 90%; + padding: 24px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); +`,R1=k.div` + display: flex; + align-items: center; + margin-bottom: 16px; +`,P1=k.div` + color: ${({theme:r})=>r.colors.status.error}; + font-size: 24px; + margin-right: 12px; +`,T1=k.h3` + color: ${({theme:r})=>r.colors.text.primary}; + margin: 0; + font-size: 18px; +`,_1=k.div` + background: ${({theme:r})=>r.colors.background.tertiary}; + color: ${({theme:r})=>r.colors.text.muted}; + padding: 2px 8px; + border-radius: 4px; + font-size: 14px; + margin-left: auto; +`,N1=k.p` + color: ${({theme:r})=>r.colors.text.secondary}; + margin-bottom: 20px; + line-height: 1.5; + font-weight: 500; +`,O1=k.div` + margin-bottom: 20px; + background: ${({theme:r})=>r.colors.background.secondary}; + border-radius: 6px; + padding: 12px; +`,wo=k.div` + display: flex; + margin-bottom: 8px; + font-size: 14px; +`,So=k.span` + color: ${({theme:r})=>r.colors.text.muted}; + min-width: 100px; +`,Co=k.span` + color: ${({theme:r})=>r.colors.text.secondary}; + word-break: break-word; +`,M1=k.button` + background: ${({theme:r})=>r.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:r})=>r.colors.brand.hover}; + } +`;function L1({isOpen:r,onClose:i,error:s}){var R,L;if(!r)return null;console.log({error:s});const l=(R=s==null?void 0:s.response)==null?void 0:R.data,c=(l==null?void 0:l.status)||((L=s==null?void 0:s.response)==null?void 0:L.status)||"오류",d=(l==null?void 0:l.code)||"",p=(l==null?void 0:l.message)||(s==null?void 0:s.message)||"알 수 없는 오류가 발생했습니다.",g=l!=null&&l.timestamp?new Date(l.timestamp):new Date,w=E1(g),v=(l==null?void 0:l.exceptionType)||"",S=(l==null?void 0:l.details)||{},j=(l==null?void 0:l.requestId)||"";return h.jsx(j1,{onClick:i,children:h.jsxs(A1,{onClick:T=>T.stopPropagation(),children:[h.jsxs(R1,{children:[h.jsx(P1,{children:"⚠️"}),h.jsx(T1,{children:"오류가 발생했습니다"}),h.jsxs(_1,{children:[c,d?` (${d})`:""]})]}),h.jsx(N1,{children:p}),h.jsxs(O1,{children:[h.jsxs(wo,{children:[h.jsx(So,{children:"시간:"}),h.jsx(Co,{children:w})]}),j&&h.jsxs(wo,{children:[h.jsx(So,{children:"요청 ID:"}),h.jsx(Co,{children:j})]}),d&&h.jsxs(wo,{children:[h.jsx(So,{children:"에러 코드:"}),h.jsx(Co,{children:d})]}),v&&h.jsxs(wo,{children:[h.jsx(So,{children:"예외 유형:"}),h.jsx(Co,{children:v})]}),Object.keys(S).length>0&&h.jsxs(wo,{children:[h.jsx(So,{children:"상세 정보:"}),h.jsx(Co,{children:Object.entries(S).map(([T,O])=>h.jsxs("div",{children:[T,": ",String(O)]},T))})]})]}),h.jsx(M1,{onClick:i,children:"확인"})]})})}const I1=k.div` + width: 240px; + background: ${q.colors.background.secondary}; + border-left: 1px solid ${q.colors.border.primary}; +`,D1=k.div` + padding: 16px; + font-size: 14px; + font-weight: bold; + color: ${q.colors.text.muted}; + text-transform: uppercase; +`,z1=k.div` + padding: 8px 16px; + display: flex; + align-items: center; + color: ${q.colors.text.muted}; + &:hover { + background: ${q.colors.background.primary}; + cursor: pointer; + } +`,$1=k(Nr)` + margin-right: 12px; +`;k(nn)``;const F1=k.div` + display: flex; + align-items: center; +`;function B1({member:r}){var l,c,d;const{binaryContents:i,fetchBinaryContent:s}=An();return K.useEffect(()=>{var p;(p=r.profile)!=null&&p.id&&!i[r.profile.id]&&s(r.profile.id)},[(l=r.profile)==null?void 0:l.id,i,s]),h.jsxs(z1,{children:[h.jsxs($1,{children:[h.jsx(nn,{src:(c=r.profile)!=null&&c.id&&((d=i[r.profile.id])==null?void 0:d.url)||St,alt:r.username}),h.jsx(Do,{$online:r.online})]}),h.jsx(F1,{children:r.username})]})}function b1({member:r,onClose:i}){var L,T,O;const{binaryContents:s,fetchBinaryContent:l}=An(),{currentUser:c,updateUserRole:d}=pt(),[p,g]=K.useState(r.role),[w,v]=K.useState(!1);K.useEffect(()=>{var _;(_=r.profile)!=null&&_.id&&!s[r.profile.id]&&l(r.profile.id)},[(L=r.profile)==null?void 0:L.id,s,l]);const S={[En.USER]:{name:"사용자",color:"#2ed573"},[En.CHANNEL_MANAGER]:{name:"채널 관리자",color:"#ff4757"},[En.ADMIN]:{name:"어드민",color:"#0097e6"}},j=_=>{g(_),v(!0)},R=()=>{d(r.id,p),v(!1)};return h.jsx(V1,{onClick:i,children:h.jsxs(W1,{onClick:_=>_.stopPropagation(),children:[h.jsx("h2",{children:"사용자 정보"}),h.jsxs(Y1,{children:[h.jsx(q1,{src:(T=r.profile)!=null&&T.id&&((O=s[r.profile.id])==null?void 0:O.url)||St,alt:r.username}),h.jsx(Q1,{children:r.username}),h.jsx(G1,{children:r.email}),h.jsx(K1,{$online:r.online,children:r.online?"온라인":"오프라인"}),(c==null?void 0:c.role)===En.ADMIN?h.jsx(H1,{value:p,onChange:_=>j(_.target.value),children:Object.entries(S).map(([_,b])=>h.jsx("option",{value:_,style:{marginTop:"8px",textAlign:"center"},children:b.name},_))}):h.jsx(U1,{style:{backgroundColor:S[r.role].color},children:S[r.role].name})]}),h.jsx(X1,{children:(c==null?void 0:c.role)===En.ADMIN&&w&&h.jsx(J1,{onClick:R,disabled:!w,$secondary:!w,children:"저장"})})]})})}const U1=k.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; +`,H1=k.select` + padding: 10px 16px; + border-radius: 8px; + border: 1.5px solid ${q.colors.border.primary}; + background: ${q.colors.background.primary}; + color: ${q.colors.text.primary}; + font-size: 14px; + width: 140px; + cursor: pointer; + transition: all 0.2s ease; + margin-top: 12px; + font-weight: 500; + + &:hover { + border-color: ${q.colors.brand.primary}; + } + + &:focus { + outline: none; + border-color: ${q.colors.brand.primary}; + box-shadow: 0 0 0 2px ${q.colors.brand.primary}20; + } + + option { + background: ${q.colors.background.primary}; + color: ${q.colors.text.primary}; + padding: 12px; + } +`,V1=k.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; +`,W1=k.div` + background: ${q.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: ${q.colors.text.primary}; + margin-bottom: 32px; + text-align: center; + font-size: 26px; + font-weight: 600; + letter-spacing: -0.5px; + } +`,Y1=k.div` + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 32px; + padding: 24px; + background: ${q.colors.background.primary}; + border-radius: 12px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); +`,q1=k.img` + width: 140px; + height: 140px; + border-radius: 50%; + margin-bottom: 20px; + object-fit: cover; + border: 4px solid ${q.colors.background.secondary}; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); +`,Q1=k.div` + font-size: 22px; + font-weight: 600; + color: ${q.colors.text.primary}; + margin-bottom: 8px; + letter-spacing: -0.3px; +`,G1=k.div` + font-size: 14px; + color: ${q.colors.text.muted}; + margin-bottom: 16px; + font-weight: 500; +`,K1=k.div` + padding: 6px 16px; + border-radius: 20px; + font-size: 13px; + font-weight: 600; + background-color: ${({$online:r,theme:i})=>r?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; +`,X1=k.div` + display: flex; + gap: 12px; + margin-top: 24px; +`,J1=k.button` + width: 100%; + padding: 12px; + border: none; + border-radius: 8px; + background: ${({$secondary:r,theme:i})=>r?"transparent":i.colors.brand.primary}; + color: ${({$secondary:r,theme:i})=>r?i.colors.text.primary:"white"}; + cursor: pointer; + font-weight: 600; + font-size: 15px; + transition: all 0.2s ease; + border: ${({$secondary:r,theme:i})=>r?`1.5px solid ${i.colors.border.primary}`:"none"}; + + &:hover { + background: ${({$secondary:r,theme:i})=>r?i.colors.background.hover:i.colors.brand.hover}; + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } +`;function Z1(){const r=Ar(p=>p.users),i=Ar(p=>p.fetchUsers),{currentUser:s}=pt(),[l,c]=K.useState(null);K.useEffect(()=>{i()},[i]);const d=[...r].sort((p,g)=>p.id===(s==null?void 0:s.id)?-1:g.id===(s==null?void 0:s.id)?1:p.online&&!g.online?-1:!p.online&&g.online?1:p.username.localeCompare(g.username));return h.jsxs(I1,{children:[h.jsxs(D1,{children:["멤버 목록 - ",r.length]}),d.map(p=>h.jsx("div",{onClick:()=>c(p),children:h.jsx(B1,{member:p},p.id)},p.id)),l&&h.jsx(b1,{member:l,onClose:()=>c(null)})]})}function ew(){const{logout:r,fetchCsrfToken:i,fetchMe:s}=pt(),{fetchUsers:l}=Ar(),[c,d]=K.useState(null),[p,g]=K.useState(null),[w,v]=K.useState(!1),[S,j]=K.useState(!0),{currentUser:R}=pt();K.useEffect(()=>{i(),s()},[]),K.useEffect(()=>{(async()=>{try{if(R)try{await l()}catch(O){console.warn("사용자 상태 업데이트 실패. 로그아웃합니다.",O),r()}}catch(O){console.error("초기화 오류:",O)}finally{j(!1)}})()},[R,l,r]),K.useEffect(()=>{const T=U=>{U!=null&&U.error&&g(U.error),U!=null&&U.alert&&v(!0)},O=()=>{r()},_=Oo.on("api-error",T),b=Oo.on("auth-error",O);return()=>{_("api-error",T),b("auth-error",O)}},[r]),K.useEffect(()=>{if(R){const T=setInterval(()=>{l()},6e4);return()=>{clearInterval(T)}}},[R,l]);const L=()=>{v(!1),g(null)};return S?h.jsx(Tf,{theme:q,children:h.jsx(nw,{children:h.jsx(rw,{})})}):h.jsxs(Tf,{theme:q,children:[R?h.jsxs(tw,{children:[h.jsx(Ax,{currentUser:R,activeChannel:c,onChannelSelect:d}),h.jsx(k1,{channel:c}),h.jsx(Z1,{})]}):h.jsx(Ov,{isOpen:!0,onClose:()=>{}}),h.jsx(L1,{isOpen:w,onClose:L,error:p})]})}const tw=k.div` + display: flex; + height: 100vh; + width: 100vw; + position: relative; +`,nw=k.div` + display: flex; + justify-content: center; + align-items: center; + height: 100vh; + width: 100vw; + background-color: ${({theme:r})=>r.colors.background.primary}; +`,rw=k.div` + width: 40px; + height: 40px; + border: 4px solid ${({theme:r})=>r.colors.background.tertiary}; + border-top: 4px solid ${({theme:r})=>r.colors.brand.primary}; + border-radius: 50%; + animation: spin 1s linear infinite; + + @keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } + } +`,kh=document.getElementById("root");if(!kh)throw new Error("Root element not found");_g.createRoot(kh).render(h.jsx(K.StrictMode,{children:h.jsx(ew,{})})); diff --git a/src/main/resources/static/favicon.ico b/src/main/resources/static/favicon.ico new file mode 100644 index 000000000..479bed6a3 Binary files /dev/null and b/src/main/resources/static/favicon.ico differ diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 000000000..f4fcc0e9f --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,26 @@ + + + + + + Discodeit + + + + + +
+ + diff --git a/src/test/java/com/sprint/mission/discodeit/ApplicationTests.java b/src/test/java/com/sprint/mission/discodeit/DiscodeitApplicationTests.java similarity index 69% rename from src/test/java/com/sprint/mission/discodeit/ApplicationTests.java rename to src/test/java/com/sprint/mission/discodeit/DiscodeitApplicationTests.java index b2eafef21..3a987a214 100644 --- a/src/test/java/com/sprint/mission/discodeit/ApplicationTests.java +++ b/src/test/java/com/sprint/mission/discodeit/DiscodeitApplicationTests.java @@ -4,10 +4,10 @@ import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class ApplicationTests { +class DiscodeitApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } 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..d23a59e59 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/AuthControllerTest.java @@ -0,0 +1,121 @@ +package com.sprint.mission.discodeit.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +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.UserDto; +import com.sprint.mission.discodeit.dto.request.LoginRequest; +import com.sprint.mission.discodeit.exception.user.InvalidCredentialsException; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.service.AuthService; +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.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(AuthController.class) +class AuthControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private AuthService authService; + + @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, + true + ); + + given(authService.login(any(LoginRequest.class))).willReturn(loggedInUser); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(userId.toString())) + .andExpect(jsonPath("$.username").value("testuser")) + .andExpect(jsonPath("$.email").value("test@example.com")) + .andExpect(jsonPath("$.online").value(true)); + } + + @Test + @DisplayName("로그인 실패 테스트 - 존재하지 않는 사용자") + void login_Failure_UserNotFound() throws Exception { + // Given + LoginRequest loginRequest = new LoginRequest( + "nonexistentuser", + "Password1!" + ); + + given(authService.login(any(LoginRequest.class))) + .willThrow(UserNotFoundException.withUsername("nonexistentuser")); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("로그인 실패 테스트 - 잘못된 비밀번호") + void login_Failure_InvalidCredentials() throws Exception { + // Given + LoginRequest loginRequest = new LoginRequest( + "testuser", + "WrongPassword1!" + ); + + given(authService.login(any(LoginRequest.class))) + .willThrow(InvalidCredentialsException.wrongPassword()); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isUnauthorized()); + } + + @Test + @DisplayName("로그인 실패 테스트 - 유효하지 않은 요청") + void login_Failure_InvalidRequest() throws Exception { + // Given + LoginRequest invalidRequest = new LoginRequest( + "", // 사용자 이름 비어있음 (NotBlank 위반) + "" // 비밀번호 비어있음 (NotBlank 위반) + ); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(invalidRequest))) + .andExpect(status().isBadRequest()); + } +} \ 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..a8451d370 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/BinaryContentControllerTest.java @@ -0,0 +1,149 @@ +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.WebMvcTest; +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(BinaryContentController.class) +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..facad5130 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/ChannelControllerTest.java @@ -0,0 +1,274 @@ +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.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.post; +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.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.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.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(ChannelController.class) +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))) + .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))) + .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)); + } + + 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))) + .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))) + .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))) + .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))) + .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)) + .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)) + .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)), + 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..3330e6b08 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/MessageControllerTest.java @@ -0,0 +1,304 @@ +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.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.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.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.WebMvcTest; +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(MessageController.class) +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 + ); + + 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)) + .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)) + .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 + ); + + 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))) + .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))) + .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)) + .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)) + .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 + ); + + 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..91772c33c --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/ReadStatusControllerTest.java @@ -0,0 +1,172 @@ +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.willThrow; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +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.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.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(ReadStatusController.class) +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))) + .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))) + .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))) + .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))) + .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..1082b638f --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/controller/UserControllerTest.java @@ -0,0 +1,342 @@ +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.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.content; +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.data.UserStatusDto; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserStatusUpdateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.service.UserService; +import java.time.Instant; +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.WebMvcTest; +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(UserController.class) +class UserControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockitoBean + private UserService userService; + + @MockitoBean + private UserStatusService userStatusService; + + @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 + ); + + 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)) + .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)) + .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 + ); + + UserDto user2 = new UserDto( + userId2, + "user2", + "user2@example.com", + null, + false + ); + + 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 + ); + + 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; + })) + .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; + })) + .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)) + .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)) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("사용자 상태 업데이트 성공 테스트") + void updateUserStatus_Success() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + UUID statusId = UUID.randomUUID(); + Instant lastActiveAt = Instant.now(); + + UserStatusUpdateRequest updateRequest = new UserStatusUpdateRequest(lastActiveAt); + UserStatusDto updatedStatus = new UserStatusDto(statusId, userId, lastActiveAt); + + given(userStatusService.updateByUserId(eq(userId), any(UserStatusUpdateRequest.class))) + .willReturn(updatedStatus); + + // When & Then + mockMvc.perform(patch("/api/users/{userId}/userStatus", userId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(statusId.toString())) + .andExpect(jsonPath("$.userId").value(userId.toString())) + .andExpect(content().json(objectMapper.writeValueAsString(updatedStatus))); + } + + @Test + @DisplayName("사용자 상태 업데이트 실패 테스트 - 존재하지 않는 사용자 상태") + void updateUserStatus_Failure_UserStatusNotFound() throws Exception { + // Given + UUID userId = UUID.randomUUID(); + Instant lastActiveAt = Instant.now(); + + UserStatusUpdateRequest updateRequest = new UserStatusUpdateRequest(lastActiveAt); + + given(userStatusService.updateByUserId(eq(userId), any(UserStatusUpdateRequest.class))) + .willThrow(UserNotFoundException.withId(userId)); + + // When & Then + mockMvc.perform(patch("/api/users/{userId}/userStatus", userId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequest))) + .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..2dfed05bc --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/AuthApiIntegrationTest.java @@ -0,0 +1,133 @@ +package com.sprint.mission.discodeit.integration; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +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.request.LoginRequest; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.service.UserService; +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.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class AuthApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @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!" + ); + + String requestBody = objectMapper.writeValueAsString(loginRequest); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.username", is("loginuser"))) + .andExpect(jsonPath("$.email", is("login@example.com"))); + } + + @Test + @DisplayName("로그인 API 통합 테스트 - 실패 (존재하지 않는 사용자)") + void login_Failure_UserNotFound() throws Exception { + // Given + LoginRequest loginRequest = new LoginRequest( + "nonexistentuser", + "Password1!" + ); + + String requestBody = objectMapper.writeValueAsString(loginRequest); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isNotFound()); + } + + @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!" + ); + + String requestBody = objectMapper.writeValueAsString(loginRequest); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isUnauthorized()); + } + + @Test + @DisplayName("로그인 API 통합 테스트 - 실패 (유효하지 않은 요청)") + void login_Failure_InvalidRequest() throws Exception { + // Given + LoginRequest invalidRequest = new LoginRequest( + "", // 사용자 이름 비어있음 (NotBlank 위반) + "" // 비밀번호 비어있음 (NotBlank 위반) + ); + + String requestBody = objectMapper.writeValueAsString(invalidRequest); + + // When & Then + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()); + } +} \ 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..871296eaa --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/BinaryContentApiIntegrationTest.java @@ -0,0 +1,209 @@ +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.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +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 + @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 + @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 + @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 + @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 + @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..5917b4d02 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/ChannelApiIntegrationTest.java @@ -0,0 +1,269 @@ +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.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.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class ChannelApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private ChannelService channelService; + + @Autowired + private UserService userService; + + @Test + @DisplayName("공개 채널 생성 API 통합 테스트") + 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)) + .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 통합 테스트 - 유효하지 않은 요청") + 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)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("비공개 채널 생성 API 통합 테스트") + 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)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(jsonPath("$.type", is(ChannelType.PRIVATE.name()))) + .andExpect(jsonPath("$.participants", hasSize(2))); + } + + @Test + @DisplayName("사용자별 채널 목록 조회 API 통합 테스트") + 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 통합 테스트") + 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)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(channelId.toString()))) + .andExpect(jsonPath("$.name", is("수정된 채널"))) + .andExpect(jsonPath("$.description", is("수정된 채널 설명입니다."))); + } + + @Test + @DisplayName("채널 업데이트 실패 API 통합 테스트 - 존재하지 않는 채널") + 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)) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("채널 삭제 API 통합 테스트") + 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)) + .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 통합 테스트 - 존재하지 않는 채널") + void deleteChannel_Failure_ChannelNotFound() throws Exception { + // Given + UUID nonExistentChannelId = UUID.randomUUID(); + + // When & Then + mockMvc.perform(delete("/api/channels/{channelId}", nonExistentChannelId)) + .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..092575de3 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/MessageApiIntegrationTest.java @@ -0,0 +1,307 @@ +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.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.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.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class MessageApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private MessageService messageService; + + @Autowired + private ChannelService channelService; + + @Autowired + private UserService userService; + + @Test + @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)) + .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 + @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)) + .andExpect(status().isBadRequest()); + } + + @Test + @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 + @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()); + + // 메시지 생성 + 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)) + .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(); + + MessageUpdateRequest updateRequest = new MessageUpdateRequest( + "수정된 메시지 내용입니다." + ); + + String requestBody = objectMapper.writeValueAsString(updateRequest); + + // When & Then + mockMvc.perform(patch("/api/messages/{messageId}", nonExistentMessageId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isNotFound()); + } + + @Test + @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()); + + // 메시지 생성 + 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)) + .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(); + + // When & Then + mockMvc.perform(delete("/api/messages/{messageId}", nonExistentMessageId)) + .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..8a93c8831 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/integration/ReadStatusApiIntegrationTest.java @@ -0,0 +1,266 @@ +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 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.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class ReadStatusApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private ReadStatusService readStatusService; + + @Autowired + private UserService userService; + + @Autowired + private ChannelService channelService; + + @Test + @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)) + .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 + @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)) + .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)) + .andExpect(status().isConflict()); + } + + @Test + @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)) + .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 + @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)) + .andExpect(status().isNotFound()); + } + + @Test + @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..61d7895bf --- /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.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +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.UserDto; +import com.sprint.mission.discodeit.dto.request.UserCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserStatusUpdateRequest; +import com.sprint.mission.discodeit.dto.request.UserUpdateRequest; +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.mock.web.MockMultipartFile; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class UserApiIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private UserService userService; + + + @Test + @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)) + .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(true))); + } + + @Test + @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)) + .andExpect(status().isBadRequest()); + } + + @Test + @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(2))) + .andExpect(jsonPath("$[0].username", is("user1"))) + .andExpect(jsonPath("$[0].email", is("user1@example.com"))) + .andExpect(jsonPath("$[1].username", is("user2"))) + .andExpect(jsonPath("$[1].email", is("user2@example.com"))); + } + + @Test + @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(); + + 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; + })) + .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 nonExistentUserId = UUID.randomUUID(); + 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; + })) + .andExpect(status().isNotFound()); + } + + @Test + @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(); + + // When & Then + mockMvc.perform(delete("/api/users/{userId}", userId)) + .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 nonExistentUserId = UUID.randomUUID(); + + // When & Then + mockMvc.perform(delete("/api/users/{userId}", nonExistentUserId)) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("사용자 상태 업데이트 API 통합 테스트") + void updateUserStatus_Success() throws Exception { + // Given + // 테스트 사용자 생성 - Service를 통해 초기화 + UserCreateRequest createRequest = new UserCreateRequest( + "statususer", + "status@example.com", + "Password1!" + ); + + UserDto createdUser = userService.create(createRequest, Optional.empty()); + UUID userId = createdUser.id(); + + Instant newLastActiveAt = Instant.now(); + UserStatusUpdateRequest statusUpdateRequest = new UserStatusUpdateRequest( + newLastActiveAt + ); + String requestBody = objectMapper.writeValueAsString(statusUpdateRequest); + + // When & Then + mockMvc.perform(patch("/api/users/{userId}/userStatus", userId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.lastActiveAt", is(newLastActiveAt.toString()))); + } + + @Test + @DisplayName("사용자 상태 업데이트 실패 API 통합 테스트 - 존재하지 않는 사용자") + void updateUserStatus_Failure_UserNotFound() throws Exception { + // Given + UUID nonExistentUserId = UUID.randomUUID(); + UserStatusUpdateRequest statusUpdateRequest = new UserStatusUpdateRequest( + Instant.now() + ); + String requestBody = objectMapper.writeValueAsString(statusUpdateRequest); + + // When & Then + mockMvc.perform(patch("/api/users/{userId}/userStatus", nonExistentUserId) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .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..24c37225d --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/MessageRepositoryTest.java @@ -0,0 +1,220 @@ +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); + // UserStatus 생성 및 연결 + UserStatus status = new UserStatus(user, Instant.now()); + 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().getStatus())).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..9bda0fe42 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/ReadStatusRepositoryTest.java @@ -0,0 +1,200 @@ +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); + // UserStatus 생성 및 연결 + UserStatus status = new UserStatus(user, Instant.now()); + 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().getStatus())).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..9650aed52 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/UserRepositoryTest.java @@ -0,0 +1,137 @@ +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.time.Instant; +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); + // UserStatus 생성 및 연결 + UserStatus status = new UserStatus(user, Instant.now()); + 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.findAllWithProfileAndStatus(); + + // 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(foundUser1.getStatus())).isTrue(); + assertThat(Hibernate.isInitialized(foundUser2.getProfile())).isTrue(); + assertThat(Hibernate.isInitialized(foundUser2.getStatus())).isTrue(); + } +} \ No newline at end of file diff --git a/src/test/java/com/sprint/mission/discodeit/repository/UserStatusRepositoryTest.java b/src/test/java/com/sprint/mission/discodeit/repository/UserStatusRepositoryTest.java new file mode 100644 index 000000000..5c837fc3c --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/repository/UserStatusRepositoryTest.java @@ -0,0 +1,116 @@ +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.time.Instant; +import java.time.temporal.ChronoUnit; +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.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; + +/** + * UserStatusRepository 슬라이스 테스트 + */ +@DataJpaTest +@EnableJpaAuditing +@ActiveProfiles("test") +class UserStatusRepositoryTest { + + @Autowired + private UserStatusRepository userStatusRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private TestEntityManager entityManager; + + /** + * TestFixture: 테스트용 사용자와 상태 생성 + */ + private User createTestUserWithStatus(String username, String email, Instant lastActiveAt) { + BinaryContent profile = new BinaryContent("profile.jpg", 1024L, "image/jpeg"); + User user = new User(username, email, "password123!@#", profile); + UserStatus status = new UserStatus(user, lastActiveAt); + return userRepository.save(user); + } + + @Test + @DisplayName("사용자 ID로 상태 정보를 찾을 수 있다") + void findByUserId_ExistingUserId_ReturnsUserStatus() { + // given + Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS); + User user = createTestUserWithStatus("testUser", "test@example.com", now); + UUID userId = user.getId(); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + Optional foundStatus = userStatusRepository.findByUserId(userId); + + // then + assertThat(foundStatus).isPresent(); + assertThat(foundStatus.get().getUser().getId()).isEqualTo(userId); + } + + @Test + @DisplayName("존재하지 않는 사용자 ID로 검색하면 빈 Optional을 반환한다") + void findByUserId_NonExistingUserId_ReturnsEmptyOptional() { + // given + UUID nonExistingUserId = UUID.randomUUID(); + + // when + Optional foundStatus = userStatusRepository.findByUserId(nonExistingUserId); + + // then + assertThat(foundStatus).isEmpty(); + } + + @Test + @DisplayName("UserStatus의 isOnline 메서드는 최근 활동 시간이 5분 이내일 때 true를 반환한다") + void isOnline_LastActiveWithinFiveMinutes_ReturnsTrue() { + // given + Instant now = Instant.now(); + User user = createTestUserWithStatus("testUser", "test@example.com", now); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + Optional foundStatus = userStatusRepository.findByUserId(user.getId()); + + // then + assertThat(foundStatus).isPresent(); + assertThat(foundStatus.get().isOnline()).isTrue(); + } + + @Test + @DisplayName("UserStatus의 isOnline 메서드는 최근 활동 시간이 5분보다 이전일 때 false를 반환한다") + void isOnline_LastActiveBeforeFiveMinutes_ReturnsFalse() { + // given + Instant sixMinutesAgo = Instant.now().minus(6, ChronoUnit.MINUTES); + User user = createTestUserWithStatus("testUser", "test@example.com", sixMinutesAgo); + + // 영속성 컨텍스트 초기화 + entityManager.flush(); + entityManager.clear(); + + // when + Optional foundStatus = userStatusRepository.findByUserId(user.getId()); + + // then + assertThat(foundStatus).isPresent(); + assertThat(foundStatus.get().isOnline()).isFalse(); + } +} \ 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..9c1befeb3 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/security/LoginTest.java @@ -0,0 +1,137 @@ +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("$.id").value(userId.toString())) + .andExpect(jsonPath("$.username").value("testuser")) + .andExpect(jsonPath("$.email").value("test@example.com")) + .andExpect(jsonPath("$.online").value(false)); + } + + @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/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..c00150bab --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicMessageServiceTest.java @@ -0,0 +1,365 @@ +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.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), + 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), + List.of(attachmentDto) + ); + + MessageDto messageDto2 = new MessageDto( + message2.getId(), + message2CreatedAt, + message2CreatedAt, + content + "2", + channelId, + new UserDto(authorId, "testUser", "test@example.com", null, true), + 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), + 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..d165fb710 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserServiceTest.java @@ -0,0 +1,184 @@ +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.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.test.util.ReflectionTestUtils; + +@ExtendWith(MockitoExtension.class) +class BasicUserServiceTest { + + @Mock + private UserRepository userRepository; + + @Mock + private UserMapper userMapper; + + @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); + } + + @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/service/basic/BasicUserStatusServiceTest.java b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserStatusServiceTest.java new file mode 100644 index 000000000..c0b0234e6 --- /dev/null +++ b/src/test/java/com/sprint/mission/discodeit/service/basic/BasicUserStatusServiceTest.java @@ -0,0 +1,239 @@ +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.UserStatusDto; +import com.sprint.mission.discodeit.dto.request.UserStatusCreateRequest; +import com.sprint.mission.discodeit.dto.request.UserStatusUpdateRequest; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.exception.user.UserNotFoundException; +import com.sprint.mission.discodeit.exception.userstatus.DuplicateUserStatusException; +import com.sprint.mission.discodeit.exception.userstatus.UserStatusNotFoundException; +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 BasicUserStatusServiceTest { + + @Mock + private UserStatusRepository userStatusRepository; + + @Mock + private UserRepository userRepository; + + @Mock + private UserStatusMapper userStatusMapper; + + @InjectMocks + private BasicUserStatusService userStatusService; + + private UUID userStatusId; + private UUID userId; + private Instant lastActiveAt; + private User user; + private UserStatus userStatus; + private UserStatusDto userStatusDto; + + @BeforeEach + void setUp() { + userStatusId = UUID.randomUUID(); + userId = UUID.randomUUID(); + lastActiveAt = Instant.now(); + + user = new User("testUser", "test@example.com", "password", null); + ReflectionTestUtils.setField(user, "id", userId); + + userStatus = new UserStatus(user, lastActiveAt); + ReflectionTestUtils.setField(userStatus, "id", userStatusId); + + userStatusDto = new UserStatusDto(userStatusId, userId, lastActiveAt); + } + + @Test + @DisplayName("사용자 상태 생성 성공") + void createUserStatus_Success() { + // given + UserStatusCreateRequest request = new UserStatusCreateRequest(userId, lastActiveAt); + given(userRepository.findById(eq(userId))).willReturn(Optional.of(user)); + given(userStatusMapper.toDto(any(UserStatus.class))).willReturn(userStatusDto); + + // 사용자에게 기존 상태가 없어야 함 + ReflectionTestUtils.setField(user, "status", null); + + // when + UserStatusDto result = userStatusService.create(request); + + // then + assertThat(result).isEqualTo(userStatusDto); + verify(userStatusRepository).save(any(UserStatus.class)); + } + + @Test + @DisplayName("이미 상태가 있는 사용자에 대한 상태 생성 시도 시 실패") + void createUserStatus_WithExistingStatus_ThrowsException() { + // given + UserStatusCreateRequest request = new UserStatusCreateRequest(userId, lastActiveAt); + given(userRepository.findById(eq(userId))).willReturn(Optional.of(user)); + + // 사용자에게 이미 상태가 있음 + ReflectionTestUtils.setField(user, "status", userStatus); + + // when & then + assertThatThrownBy(() -> userStatusService.create(request)) + .isInstanceOf(DuplicateUserStatusException.class); + } + + @Test + @DisplayName("존재하지 않는 사용자에 대한 상태 생성 시도 시 실패") + void createUserStatus_WithNonExistentUser_ThrowsException() { + // given + UserStatusCreateRequest request = new UserStatusCreateRequest(userId, lastActiveAt); + given(userRepository.findById(eq(userId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> userStatusService.create(request)) + .isInstanceOf(UserNotFoundException.class); + } + + @Test + @DisplayName("사용자 상태 조회 성공") + void findUserStatus_Success() { + // given + given(userStatusRepository.findById(eq(userStatusId))).willReturn(Optional.of(userStatus)); + given(userStatusMapper.toDto(any(UserStatus.class))).willReturn(userStatusDto); + + // when + UserStatusDto result = userStatusService.find(userStatusId); + + // then + assertThat(result).isEqualTo(userStatusDto); + } + + @Test + @DisplayName("존재하지 않는 사용자 상태 조회 시 실패") + void findUserStatus_WithNonExistentId_ThrowsException() { + // given + given(userStatusRepository.findById(eq(userStatusId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> userStatusService.find(userStatusId)) + .isInstanceOf(UserStatusNotFoundException.class); + } + + @Test + @DisplayName("전체 사용자 상태 목록 조회 성공") + void findAllUserStatuses_Success() { + // given + given(userStatusRepository.findAll()).willReturn(List.of(userStatus)); + given(userStatusMapper.toDto(any(UserStatus.class))).willReturn(userStatusDto); + + // when + List result = userStatusService.findAll(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0)).isEqualTo(userStatusDto); + } + + @Test + @DisplayName("사용자 상태 수정 성공") + void updateUserStatus_Success() { + // given + Instant newLastActiveAt = Instant.now().plusSeconds(60); + UserStatusUpdateRequest request = new UserStatusUpdateRequest(newLastActiveAt); + + given(userStatusRepository.findById(eq(userStatusId))).willReturn(Optional.of(userStatus)); + given(userStatusMapper.toDto(any(UserStatus.class))).willReturn(userStatusDto); + + // when + UserStatusDto result = userStatusService.update(userStatusId, request); + + // then + assertThat(result).isEqualTo(userStatusDto); + } + + @Test + @DisplayName("존재하지 않는 사용자 상태 수정 시도 시 실패") + void updateUserStatus_WithNonExistentId_ThrowsException() { + // given + Instant newLastActiveAt = Instant.now().plusSeconds(60); + UserStatusUpdateRequest request = new UserStatusUpdateRequest(newLastActiveAt); + + given(userStatusRepository.findById(eq(userStatusId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> userStatusService.update(userStatusId, request)) + .isInstanceOf(UserStatusNotFoundException.class); + } + + @Test + @DisplayName("사용자 ID로 상태 수정 성공") + void updateUserStatusByUserId_Success() { + // given + Instant newLastActiveAt = Instant.now().plusSeconds(60); + UserStatusUpdateRequest request = new UserStatusUpdateRequest(newLastActiveAt); + + given(userStatusRepository.findByUserId(eq(userId))).willReturn(Optional.of(userStatus)); + given(userStatusMapper.toDto(any(UserStatus.class))).willReturn(userStatusDto); + + // when + UserStatusDto result = userStatusService.updateByUserId(userId, request); + + // then + assertThat(result).isEqualTo(userStatusDto); + } + + @Test + @DisplayName("존재하지 않는 사용자 ID로 상태 수정 시도 시 실패") + void updateUserStatusByUserId_WithNonExistentUserId_ThrowsException() { + // given + Instant newLastActiveAt = Instant.now().plusSeconds(60); + UserStatusUpdateRequest request = new UserStatusUpdateRequest(newLastActiveAt); + + given(userStatusRepository.findByUserId(eq(userId))).willReturn(Optional.empty()); + + // when & then + assertThatThrownBy(() -> userStatusService.updateByUserId(userId, request)) + .isInstanceOf(UserStatusNotFoundException.class); + } + + @Test + @DisplayName("사용자 상태 삭제 성공") + void deleteUserStatus_Success() { + // given + given(userStatusRepository.existsById(eq(userStatusId))).willReturn(true); + + // when + userStatusService.delete(userStatusId); + + // then + verify(userStatusRepository).deleteById(eq(userStatusId)); + } + + @Test + @DisplayName("존재하지 않는 사용자 상태 삭제 시도 시 실패") + void deleteUserStatus_WithNonExistentId_ThrowsException() { + // given + given(userStatusRepository.existsById(eq(userStatusId))).willReturn(false); + + // when & then + assertThatThrownBy(() -> userStatusService.delete(userStatusId)) + .isInstanceOf(UserStatusNotFoundException.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..7df254a4c --- /dev/null +++ b/src/test/resources/application-test.yaml @@ -0,0 +1,19 @@ +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 + +logging: + level: + com.sprint.mission.discodeit: debug + org.hibernate.SQL: debug + org.hibernate.orm.jdbc.bind: trace \ No newline at end of file