Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package net.revature.project1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

@Configuration
public class AwsConfig {
@Bean
public S3Client s3Client() {
return S3Client.builder()
.region(Region.US_EAST_2)
.credentialsProvider(DefaultCredentialsProvider.create())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public SecurityFilterChain filterChain(HttpSecurity http, JwtAuthenticationFilte
.requestMatchers("/api/v1/user/username/**").permitAll()
.requestMatchers("/api/v1/user/getSearchDto/**").permitAll()
.requestMatchers("/api/v1/user/{id}/follow/{user}").permitAll()
.requestMatchers("/api/v1/user/following/**").permitAll()
.requestMatchers("/api/v1/user/{id}/followers/**").permitAll()
.requestMatchers("/api/v1/auth/verify-captcha").permitAll()
.requestMatchers("/api/v1/auth/verify-token").permitAll()
.requestMatchers("/api/v1/user/check/username/{username}").permitAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ResponseEntity<List<PostResponseDto>> getComments(@PathVariable Long id)
}

@PostMapping("/create")
public ResponseEntity<?> createPost(@RequestBody PostCreateDto post,
public ResponseEntity<?> createPost(@ModelAttribute PostCreateRequestDto post,
@RequestHeader("Authorization") String token){
if(post == null){
return ResponseEntity.badRequest().body("Invalid post");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,6 @@ public ResponseEntity<String> checkUsername(@PathVariable String username) {
return ResponseEntity.ok("This username is available.");
}

@PutMapping("/{id}/email")
public ResponseEntity<String> updateUserEmail(@PathVariable Long id,
@RequestBody AppUser appUser) {
UserEnum result = userService.updateEmail(id, appUser);
return resultResponse(result);
}

@PostMapping("/check/email")
public ResponseEntity<String> checkEmail(@RequestBody EmailData emailData) {
boolean isNotAvailable = userService.existsByEmail(emailData.email());
Expand All @@ -74,15 +67,15 @@ public ResponseEntity<String> checkEmail(@RequestBody EmailData emailData) {
}

@PutMapping("/settings/update")
public ResponseEntity<AppUser> updateUserDetails(@RequestBody AppUser appUser, @RequestHeader("Authorization") String receivedToken){

public ResponseEntity<UserUpdateResponseDto> updateUserDetails(@ModelAttribute UserUpdateRequestDto userUpdateRequestDto,
@RequestHeader("Authorization") String receivedToken){
String token = receivedToken.substring(7);
AppUser receivedAppUser = userService.updateAppUser(appUser, token);
if (receivedAppUser == null){
UserUpdateResponseDto responseDto = userService.updateAppUser(userUpdateRequestDto, token);
if (responseDto == null){
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);

}
return new ResponseEntity<>(appUser, HttpStatus.OK);
return new ResponseEntity<>(responseDto, HttpStatus.OK);
}

@PutMapping("/{id}/update/{username}")
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package net.revature.project1.dto;

import org.springframework.web.multipart.MultipartFile;

public record PostCreateRequestDto(Long userId, Long postParent, String comment, MultipartFile media) { }
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package net.revature.project1.dto;

import org.springframework.web.multipart.MultipartFile;

public record UserUpdateRequestDto(Long id, String displayName, MultipartFile profilePic,
MultipartFile bannerPic, String biography ) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package net.revature.project1.dto;

public class UserUpdateResponseDto {
public String bannerPic;
public String profilePic;
public String displayName;
public String biography;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import net.revature.project1.enumerator.FileType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
Expand All @@ -16,13 +18,13 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

@Service
public class FileService {
private static final Logger logger = LoggerFactory.getLogger(FileService.class);
private final S3Client s3Client;

@Value("${s3.bucket}")
private String s3Bucket;
Expand All @@ -39,6 +41,10 @@ public class FileService {
"video/mp4", "video/m4a", "video/m4b", "video/webm", "video/mov", "video/gif"
);

public FileService(S3Client s3Client) {
this.s3Client = s3Client;
}

/**
* Upload a file to the server.
* @param fileType The type of file to upload.
Expand Down Expand Up @@ -100,10 +106,7 @@ public String uploadFile(FileType fileType, String filePath, String fileName) th
return null;
}

try (S3Client s3Client = S3Client.builder()
.region(Region.US_EAST_2)
.credentialsProvider(DefaultCredentialsProvider.create())
.build())
try (s3Client)
{
PutObjectRequest putOb = PutObjectRequest.builder()
.bucket(s3Bucket)
Expand All @@ -121,49 +124,56 @@ public String uploadFile(FileType fileType, String filePath, String fileName) th
}

/**
* Create a new file and a temporary file based on a base64 encoding.
* @param post Take in the post to set the new media URL.
* Create a new file and a temporary file from multipart file.
* @param file Take in the file to set the new media URL.
* @throws IOException If it fails to create a file it throws the exception.
*/
public String createFile(String post) throws IOException {
if(post == null || post.isEmpty()){
public String createFile(MultipartFile file) throws IOException {
if(file == null || file.isEmpty()){
return "";
}

String[] parts = post.split(",");
String originalFilename = file.getOriginalFilename();
String extension = originalFilename.substring(originalFilename.lastIndexOf(".") - 1);
String uniqueFileName = UUID.randomUUID() + "." + extension;
String imageType = file.getContentType();

String imageType = parts[0].split(";")[0].split(":")[1];
byte[] imageBytes = Base64.getDecoder().decode(parts[1]);
Path tempFile = Files.createTempFile(uniqueFileName, "." + extension);

String extension = getExtensionFromMimeType(imageType);
String tempFileName = UUID.randomUUID() + "." + extension;

Path tempPath = Paths.get(System.getProperty("java.io.tmpdir"), tempFileName);
Files.write(tempPath, imageBytes);
FileType fileType = imageType.startsWith("video/") ? FileType.VIDEO : FileType.IMAGE;

String mediaUrl = uploadFile(fileType, tempPath.toString(), tempFileName);
try{
file.transferTo(tempFile.toFile());
} catch (IOException e) {
logger.error("Error while moving multipart file: ", e);
}

assert imageType != null;
if(imageType.isEmpty()){
logger.error("Image type cannot be empty");
return "";
}

Files.deleteIfExists(tempPath);
FileType fileType = imageType.startsWith("video/") ? FileType.VIDEO : FileType.IMAGE;
String mediaUrl = uploadFile(fileType, tempFile.toFile().getPath(), uniqueFileName);

Files.deleteIfExists(tempFile);
return mediaUrl;
}

/**
* Used to delete objects from the S3 Bucket.
* @param filePath Take in a file path to find to create an object key.
* @return {@Code True} if the was successful in deleting and {@Code False} if it failed to delete.
*
* @param urlPath Take in a file path to find to create an object key.
*/
public boolean deleteFile(String filePath) {
String[] parts = filePath.split("/");
public void deleteFile(String urlPath) {
if(urlPath == null || urlPath.isEmpty()){
return;
}

String[] parts = urlPath.split("/");
final int length = parts.length;
String objectKey = filePath.split("/")[length - 1];
String objectKey = urlPath.split("/")[length - 1];

try (S3Client s3Client = S3Client.builder()
.region(Region.US_EAST_2)
.credentialsProvider(DefaultCredentialsProvider.create())
.build())
try (s3Client)
{
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
.bucket(s3Bucket)
Expand All @@ -173,19 +183,7 @@ public boolean deleteFile(String filePath) {
}
catch (RuntimeException e) {
logger.error("Error while deleting file: ", e);
return false;
}
return true;

}

private String getExtensionFromMimeType(String mimeType) {
return switch (mimeType) {
case "image/jpeg" -> "jpg";
case "image/png" -> "png";
case "image/gif" -> "gif";
case "video/mp4" -> "mp4";
default -> "jpg"; // Default to jpg if unknown
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,20 @@ public PostFeedResponse getUserFeed(PostFeedRequest request, Integer chunkSize){
* @param postDto The post to be created.
* @return The created post.
*/
public PostResult createPost(PostCreateDto postDto, String token) {
public PostResult createPost(PostCreateRequestDto postDto, String token) {
Post post = new Post();
post.setComment(postDto.comment());
post.setMedia(postDto.media());
String url = "";

if(post.getMedia() != null && !post.getMedia().isEmpty() && !post.getMedia().contains("youtube")){
try{
url = fileService.createFile(postDto.media());
} catch (IOException e) {
logger.error(e.getMessage());
return new PostResult(PostEnum.INVALID_POST, "Media failed to upload.", null);
}
post.setMedia(url);
}

if(postDto.postParent() != null){
Optional<Post> postParentOptional = postRepo.findById(postDto.postParent());
Expand Down Expand Up @@ -150,13 +160,6 @@ public PostResult createPost(PostCreateDto postDto, String token) {
return new PostResult(PostEnum.INVALID_POST, "User and post are not the same", null);
}

if(post.getMedia() != null && !post.getMedia().isEmpty() && !post.getMedia().contains("youtube")){
try{
post.setMedia(fileService.createFile(post.getMedia()));
} catch (IOException e) {
return new PostResult(PostEnum.INVALID_POST, "File could not be created.", null);
}
}
post.setPostAt(Timestamp.from(Instant.now()));
postRepo.save(post);

Expand Down
Loading