diff --git a/src/backend/file_server/.gitattributes b/src/backend/file_server/.gitattributes new file mode 100644 index 00000000..8af972cd --- /dev/null +++ b/src/backend/file_server/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/src/backend/file_server/.gitignore b/src/backend/file_server/.gitignore new file mode 100644 index 00000000..31f83be8 --- /dev/null +++ b/src/backend/file_server/.gitignore @@ -0,0 +1,38 @@ +HELP.md +.gradle +build/ +local.env +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/src/backend/file_server/build.gradle b/src/backend/file_server/build.gradle new file mode 100644 index 00000000..23040886 --- /dev/null +++ b/src/backend/file_server/build.gradle @@ -0,0 +1,46 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.2' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.jootalkpia' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'org.postgresql:postgresql' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + implementation(platform("software.amazon.awssdk:bom:2.27.21")) + implementation 'software.amazon.awssdk:s3' + + implementation 'org.apache.tika:tika-core:2.8.0' + + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'commons-fileupload:commons-fileupload:1.4' + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/src/backend/file_server/gradle/wrapper/gradle-wrapper.jar b/src/backend/file_server/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..a4b76b95 Binary files /dev/null and b/src/backend/file_server/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src/backend/file_server/gradle/wrapper/gradle-wrapper.properties b/src/backend/file_server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..e18bc253 --- /dev/null +++ b/src/backend/file_server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/src/backend/file_server/gradlew b/src/backend/file_server/gradlew new file mode 100755 index 00000000..f5feea6d --- /dev/null +++ b/src/backend/file_server/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/src/backend/file_server/gradlew.bat b/src/backend/file_server/gradlew.bat new file mode 100644 index 00000000..9d21a218 --- /dev/null +++ b/src/backend/file_server/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/backend/file_server/local.env b/src/backend/file_server/local.env new file mode 100644 index 00000000..e69de29b diff --git a/src/backend/file_server/settings.gradle b/src/backend/file_server/settings.gradle new file mode 100644 index 00000000..41f961be --- /dev/null +++ b/src/backend/file_server/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'file_server' diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/FileServerApplication.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/FileServerApplication.java new file mode 100644 index 00000000..9ceb45c4 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/FileServerApplication.java @@ -0,0 +1,13 @@ +package com.jootalkpia.file_server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FileServerApplication { + + public static void main(String[] args) { + SpringApplication.run(FileServerApplication.class, args); + } + +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/config/S3Config.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/config/S3Config.java new file mode 100644 index 00000000..e0e9bb19 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/config/S3Config.java @@ -0,0 +1,32 @@ +package com.jootalkpia.file_server.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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; + +@Configuration +public class S3Config { + + @Value("${spring.cloud.aws.region.static}") + private String region; + + @Value("${spring.cloud.aws.credentials.access-key}") + private String accessKey; + + @Value("${spring.cloud.aws.credentials.secret-key}") + private String secretKey; + + @Bean + public S3Client s3Client() { + return S3Client.builder() + .region(Region.of(region)) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey) + )) + .build(); + } +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/controller/FileController.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/controller/FileController.java new file mode 100644 index 00000000..1f5852d2 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/controller/FileController.java @@ -0,0 +1,51 @@ +package com.jootalkpia.file_server.controller; + +import com.jootalkpia.file_server.dto.UploadFileRequestDto; +import com.jootalkpia.file_server.dto.UploadFileResponseDto; +import com.jootalkpia.file_server.service.FileService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +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.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping("/api/v1") +@RequiredArgsConstructor +@Slf4j +public class FileController { + private final FileService fileService; + private final Long userId = 1L;//JootalkpiaAuthenticationContext.getUserInfo().userId(); + + @GetMapping("/test") + public ResponseEntity testEndpoint() { + log.info("Test endpoint hit"); + return ResponseEntity.ok("Test successful"); + } + + @PostMapping("/workspace/{workspaceId}/channel/{channelId}") + public ResponseEntity uploadFiles( + @PathVariable Long workspaceId, + @PathVariable Long channelId, + @RequestParam("files") MultipartFile[] files, + @RequestParam("thumbnails") MultipartFile[] thumbnails) { + log.info("ids: {}", workspaceId); + log.info("Files: {}", files != null ? files.length : "null"); + log.info("Thumbnails: {}", thumbnails != null ? thumbnails.length : "null"); + + UploadFileRequestDto uploadFileRequest = new UploadFileRequestDto(); + uploadFileRequest.setWorkspaceId(workspaceId); + uploadFileRequest.setChannelId(channelId); + uploadFileRequest.setFiles(files); + uploadFileRequest.setThumbnails(thumbnails); + + UploadFileResponseDto response = fileService.uploadFiles(1L, uploadFileRequest); + return ResponseEntity.ok(response); + } + +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/dto/UploadFileRequestDto.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/dto/UploadFileRequestDto.java new file mode 100644 index 00000000..31b6b996 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/dto/UploadFileRequestDto.java @@ -0,0 +1,14 @@ +package com.jootalkpia.file_server.dto; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.web.multipart.MultipartFile; + +@Getter +@Setter +public class UploadFileRequestDto { + private Long workspaceId; + private Long channelId; + private MultipartFile[] files; + private MultipartFile[] thumbnails; +} \ No newline at end of file diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/dto/UploadFileResponseDto.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/dto/UploadFileResponseDto.java new file mode 100644 index 00000000..dd59e860 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/dto/UploadFileResponseDto.java @@ -0,0 +1,14 @@ +package com.jootalkpia.file_server.dto; + +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@AllArgsConstructor +public class UploadFileResponseDto { + private List fileTypes; // IMAGE, VIDEO, THUMBNAIL + private List fileIds; +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/entity/Files.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/entity/Files.java new file mode 100644 index 00000000..098b403a --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/entity/Files.java @@ -0,0 +1,26 @@ +package com.jootalkpia.file_server.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; + +@Entity +@Getter +@Setter +public class Files { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long fileId; + + private String url; + private String urlThumbnail; + private String fileType; + private Long fileSize; + private String mimeType; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/repository/FileRepository.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/repository/FileRepository.java new file mode 100644 index 00000000..d1826565 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/repository/FileRepository.java @@ -0,0 +1,9 @@ +package com.jootalkpia.file_server.repository; + +import com.jootalkpia.file_server.entity.Files; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FileRepository extends JpaRepository { +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/FileService.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/FileService.java new file mode 100644 index 00000000..fd62b8cb --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/FileService.java @@ -0,0 +1,85 @@ +package com.jootalkpia.file_server.service; + +import com.jootalkpia.file_server.dto.UploadFileRequestDto; +import com.jootalkpia.file_server.dto.UploadFileResponseDto; +import com.jootalkpia.file_server.entity.Files; +import com.jootalkpia.file_server.repository.FileRepository; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.util.ArrayList; +import java.util.List; + +@Service +@Slf4j +@RequiredArgsConstructor +public class FileService { + + private final FileRepository fileRepository; + private final S3Service s3Service; + + @Transactional + public UploadFileResponseDto uploadFiles(Long userId, UploadFileRequestDto uploadFileRequestDto) { + MultipartFile[] files = uploadFileRequestDto.getFiles(); + MultipartFile[] thumbnails = uploadFileRequestDto.getThumbnails(); + + List fileTypes = new ArrayList<>(); + List fileIds = new ArrayList<>(); + + try { + if (files != null && files.length > 0) { + for (int i = 0; i < files.length; i++) { + Long fileId = null; + Files filesEntity = new Files(); + fileRepository.save(filesEntity); + fileId = filesEntity.getFileId(); + + MultipartFile file = files[i]; + + // 파일 타입 결정 + String fileType = FileTypeDetector.detectFileTypeFromMultipartFile(file); + + // S3에 업로드 + String s3Url = s3Service.uploadFile(file, fileType, fileId); + + // DB에 파일 저장 + filesEntity.setUrl(s3Url); + filesEntity.setFileType(fileType); + filesEntity.setMimeType(file.getContentType()); + filesEntity.setFileSize(file.getSize()); + fileRepository.save(filesEntity); + + fileIds.add(filesEntity.getFileId()); + fileTypes.add(filesEntity.getFileType()); + + // 영상 파일일 경우 썸네일 처리 + if ("VIDEO".equalsIgnoreCase(fileType) && thumbnails != null && i < thumbnails.length && thumbnails[i] != null) { + fileId = null; + filesEntity = new Files(); + fileRepository.save(filesEntity); + fileId = filesEntity.getFileId(); + + MultipartFile thumbnail = thumbnails[i]; + String thumbnailUrl = s3Service.uploadFile(thumbnail, "THUMBNAIL", fileId); + + filesEntity.setUrlThumbnail(thumbnailUrl); + + fileRepository.save(filesEntity); + +// fileIds.add(filesEntity.getFileId()); +// fileTypes.add("THUMBNAIL"); + } + } + } + + return new UploadFileResponseDto(fileTypes, fileIds); + + } catch (Exception e) { + log.error("파일 업로드 중 오류 발생: {}", e.getMessage(), e); + throw new RuntimeException("파일 업로드 중 오류가 발생했습니다."); + } + } +} diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/FileTypeDetector.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/FileTypeDetector.java new file mode 100644 index 00000000..65bd22a2 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/FileTypeDetector.java @@ -0,0 +1,39 @@ +package com.jootalkpia.file_server.service; + +import java.io.IOException; +import org.apache.tika.Tika; +import org.apache.tika.mime.MimeTypeException; +import org.apache.tika.mime.MimeTypes; +import org.springframework.web.multipart.MultipartFile; + +public class FileTypeDetector { + + private static final Tika tika = new Tika(); + + public static String detectFileType(byte[] fileBytes) { + try { + // 파일의 MIME 타입 추출 + String mimeType = tika.detect(fileBytes); + + if (mimeType.startsWith("image/")) { + return "IMAGE"; + } else if (mimeType.startsWith("video/")) { + return "VIDEO"; + } else { + return "UNKNOWN"; + } + } catch (Exception e) { + throw new RuntimeException("파일 타입 분석 중 오류 발생: " + e.getMessage(), e); + } + } + + public static String detectFileTypeFromMultipartFile(MultipartFile file) { + try { + // MultipartFile로부터 바이트 배열 추출 + return detectFileType(file.getBytes()); + } catch (IOException e) { + throw new RuntimeException("파일 분석 중 오류 발생: " + e.getMessage(), e); + } + } +} + diff --git a/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/S3Service.java b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/S3Service.java new file mode 100644 index 00000000..3860a5d1 --- /dev/null +++ b/src/backend/file_server/src/main/java/com/jootalkpia/file_server/service/S3Service.java @@ -0,0 +1,74 @@ +package com.jootalkpia.file_server.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +@Service +@Slf4j +@RequiredArgsConstructor +public class S3Service { + + private final S3Client s3Client; + + @Value("${spring.cloud.aws.s3.bucket}") + private String bucketName; + + public String uploadFile(MultipartFile file, String fileType, Long fileId) { + Path tempFile = null; + try { + // 폴더 경로 설정 + String folder; + if ("IMAGE".equalsIgnoreCase(fileType)) { + folder = "images/"; + } else if ("VIDEO".equalsIgnoreCase(fileType)) { + folder = "videos/"; + } else if ("THUMBNAIL".equalsIgnoreCase(fileType)) { + folder = "thumbnails/"; + } else { + throw new IllegalArgumentException("Unsupported file type: " + fileType); + } + + // S3에 저장될 파일 키 생성 + String key = folder + fileId; + + // 임시 파일 생성 + tempFile = Files.createTempFile("temp-", ".tmp"); + file.transferTo(tempFile.toFile()); // MultipartFile -> 임시 파일 저장 + + // S3에 업로드 + s3Client.putObject( + PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .contentType(file.getContentType()) + .build(), + tempFile); + + log.info("파일 업로드 완료 - S3 Key: {}", key); + return "https://" + bucketName + ".s3.amazonaws.com/" + key; + + } catch (IOException e) { + log.error("파일 업로드 중 오류 발생: {}", e.getMessage(), e); + throw new RuntimeException("파일 업로드 중 오류가 발생했습니다."); + } finally { + // 임시 파일 삭제 + try { + if (tempFile != null && Files.exists(tempFile)) { + Files.delete(tempFile); + log.info("임시 파일 삭제 완료: {}", tempFile); + } + } catch (IOException e) { + log.warn("임시 파일 삭제 실패: {}", e.getMessage(), e); + } + } + } +} diff --git a/src/backend/file_server/src/main/resources/application.yml b/src/backend/file_server/src/main/resources/application.yml new file mode 100644 index 00000000..e0c8d3fe --- /dev/null +++ b/src/backend/file_server/src/main/resources/application.yml @@ -0,0 +1,40 @@ +server: + port: 8080 + tomcat: + max-swallow-size: -1 +spring: + application: + name: file_server + datasource: + url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:jootalkpia_file} + username: ${DB_USER} + password: ${DB_PASSWORD} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: + properties: + hibernate: + dialect: org.hibernate.dialect.PostgreSQLDialect + logging: + level: + org.hibernate.SQL: DEBUG + org.hibernate.type.descriptor.sql: TRACE + servlet: + multipart: + enabled: true + max-file-size: 1000MB # 개별 파일 최대 크기 + max-request-size: 1000MB # 전체 요청 최대 크기 + cloud: + aws: + credentials: + access-key: ${AWS_ACCESS_KEY} + secret-key: ${AWS_SECRET_KEY} + s3: + bucket: ${S3_BUCKET_NAME} + region: + static: ${AWS_REGION} + stack: + auto: false + + diff --git a/src/backend/file_server/src/test/java/com/jootalkpia/file_server/FileServerApplicationTests.java b/src/backend/file_server/src/test/java/com/jootalkpia/file_server/FileServerApplicationTests.java new file mode 100644 index 00000000..242c962f --- /dev/null +++ b/src/backend/file_server/src/test/java/com/jootalkpia/file_server/FileServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.jootalkpia.file_server; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class FileServerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/.idea/.gitignore b/src/infra/.idea/.gitignore similarity index 100% rename from src/.idea/.gitignore rename to src/infra/.idea/.gitignore diff --git a/src/.idea/src.iml b/src/infra/.idea/infra.iml similarity index 100% rename from src/.idea/src.iml rename to src/infra/.idea/infra.iml diff --git a/src/.idea/misc.xml b/src/infra/.idea/misc.xml similarity index 100% rename from src/.idea/misc.xml rename to src/infra/.idea/misc.xml diff --git a/src/.idea/modules.xml b/src/infra/.idea/modules.xml similarity index 59% rename from src/.idea/modules.xml rename to src/infra/.idea/modules.xml index f669a0e5..a785a536 100644 --- a/src/.idea/modules.xml +++ b/src/infra/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/src/.idea/vcs.xml b/src/infra/.idea/vcs.xml similarity index 68% rename from src/.idea/vcs.xml rename to src/infra/.idea/vcs.xml index 6c0b8635..b2bdec2d 100644 --- a/src/.idea/vcs.xml +++ b/src/infra/.idea/vcs.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/src/infra/Dockerfile b/src/infra/Dockerfile index 724eeb5e..2b00bbd6 100644 --- a/src/infra/Dockerfile +++ b/src/infra/Dockerfile @@ -2,6 +2,7 @@ FROM postgres:15 # 초기화 스크립트 복사 + ARG CACHE_BUST=3 COPY init.sql /docker-entrypoint-initdb.d/ diff --git a/src/infra/init.sql b/src/infra/init.sql index 212e4d3b..4d606d16 100644 --- a/src/infra/init.sql +++ b/src/infra/init.sql @@ -1,3 +1,4 @@ + -- Users 테이블 생성 CREATE TABLE IF NOT EXISTS users ( user_id SERIAL PRIMARY KEY, @@ -73,3 +74,4 @@ BEGIN ('한화에어로스페이스 워크스페이스', '한화에어로스페이스'); END IF; END $$; +