Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Weekly/11] Image/delete #110

Merged
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ out/
.vscode/

### static images
/src/main/resources/staticimages/
/src/main/resources/static/images/

### env file
.env
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package org.ktc2.cokaen.wouldyouin.Image.api.dto;

import java.nio.file.Paths;
import java.time.LocalDateTime;
import lombok.Builder;
import lombok.Getter;
import org.ktc2.cokaen.wouldyouin.Image.persist.Image;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;

@Getter
@Builder
Expand All @@ -16,10 +16,10 @@ public class ImageResponse {
private String extension;
private LocalDateTime createdDate;

public static ImageResponse from(Image image, String apiUrlHeader) {
public static ImageResponse from(Image image, String path) {
return ImageResponse.builder()
.id(image.getId())
.url(Paths.get(apiUrlHeader, image.getUrl()).toString())
.url(UriUtil.assembleFullUrl(path, image.getName()))
.size(image.getSize())
.extension(image.getExtension())
.createdDate(image.getCreatedDate())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ protected AdvertisementImage toEntity(ImageRequest imageRequest) {
return AdvertisementImage.builder()
.name(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected CurationImage toEntity(ImageRequest imageRequest) {
return CurationImage.builder()
.url(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected EventImage toEntity(ImageRequest imageRequest) {
return EventImage.builder()
.url(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.ktc2.cokaen.wouldyouin.Image.persist.Image;
import org.ktc2.cokaen.wouldyouin.Image.persist.ImageRepository;
import org.ktc2.cokaen.wouldyouin._common.exception.EntityNotFoundException;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand All @@ -32,20 +33,6 @@ public abstract class ImageService<T extends Image> {

protected abstract T toEntity(ImageRequest imageRequest);

public T getById(Long id) {
return getImageRepository().findById(id)
.orElseThrow(() -> new EntityNotFoundException(getImageDomain().name() + " ์ด๋ฏธ์ง€๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."));
}

protected ImageResponse create(ImageRequest imageRequest) {
return ImageResponse.from(getImageRepository().save(toEntity(imageRequest)), apiUrl);
}

protected void delete(Long id) {
getById(id);
getImageRepository().deleteById(id);
}

@Transactional
public List<ImageResponse> saveImages(List<MultipartFile> images) {
return images.stream()
Expand All @@ -57,6 +44,20 @@ public List<ImageResponse> saveImages(List<MultipartFile> images) {
public void deleteImage(Long id) {
T image = getById(id);
delete(id);
imageStorageService.delete(image.getUrl());
imageStorageService.delete(getChildPath(), image.getName());
}

public T getById(Long id) {
return getImageRepository().findById(id)
.orElseThrow(() -> new EntityNotFoundException(getImageDomain().name() + " ์ด๋ฏธ์ง€๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."));
}

protected ImageResponse create(ImageRequest imageRequest) {
return ImageResponse.from(getImageRepository().save(toEntity(imageRequest)), UriUtil.assembleFullUrl(apiUrl, getChildPath()));
}

protected void delete(Long id) {
getById(id);
getImageRepository().deleteById(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,32 @@ public class ImageStorageService {
private String parentPath;
private final RestClientUtil client;

public byte[] readFromDirectory(Path path) {
return FileUtil.readFile(Paths.get(parentPath).resolve(path));
public byte[] readFromDirectory(Path childPath) {
return FileUtil.readFile(Paths.get(parentPath).resolve(childPath));
}

public ImageRequest saveToDirectory(MultipartFile image, String subPath) {
public ImageRequest saveToDirectory(MultipartFile image, String childPath) {
String extension = FileUtil.getExtension(image);
String fileName = FileUtil.generateUuidName() + "." + extension;
String relativeFilePath = Paths.get(subPath, fileName).toString();
Path absoluteFilePath = Paths.get(parentPath, relativeFilePath);
FileUtil.saveFile(image, absoluteFilePath);
return ImageRequest.of(relativeFilePath, image.getSize(), FileUtil.getExtension(image));
String fileName = FileUtil.createRandomFileName(extension);
FileUtil.saveFile(image, Path.of(parentPath, childPath, fileName));
return ImageRequest.of(fileName, image.getSize(), extension);
}

public ImageRequest saveToDirectory(String imageUrl, String subPath) {
public ImageRequest saveToDirectory(String imageUrl, String childPath) {
byte[] response = client.get(byte[].class, imageUrl, new HttpHeaders(),
(req, rsp) -> { throw new FailedToUploadImageException("์ด๋ฏธ์ง€ URL์— ๋Œ€ํ•œ ์š”์ฒญ์„ ์‹คํŒจํ•˜์˜€์Šต๋‹ˆ๋‹ค."); }
);
Optional.ofNullable(response).orElseThrow(
() -> new FailedToUploadImageException("์‘๋‹ต ๋ณธ๋ฌธ์ด ๋น„์–ด์žˆ์–ด ์ด๋ฏธ์ง€๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."));
() -> new FailedToUploadImageException("์‘๋‹ต ๋ณธ๋ฌธ์ด ๋น„์–ด์žˆ์–ด ์ด๋ฏธ์ง€๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
);
String extension = FileUtil.getExtension(imageUrl);
String fileName = FileUtil.generateUuidName() + "." + extension;
String relativeFilePath = Paths.get(subPath, fileName).toString();
Path absoluteFilePath = Paths.get(parentPath, relativeFilePath);
FileUtil.saveFile(response, absoluteFilePath);
return ImageRequest.of(relativeFilePath, (long) response.length, extension);
String fileName = FileUtil.createRandomFileName(extension);
Path path = Path.of(parentPath, childPath, fileName);
FileUtil.saveFile(response, path);
return ImageRequest.of(fileName, (long) response.length, extension);
}

public void delete(String imagePath) {
FileUtil.deleteFile(Paths.get(imagePath));
public void delete(String childPath, String fileName) {
FileUtil.deleteFile(Path.of(parentPath, childPath, fileName));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected MemberImage toEntity(ImageRequest imageRequest) {
return MemberImage.builder()
.url(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public abstract class Image {
protected Long id;

@NotNull
@Column(name = "url")
protected String url;
@Column(name = "name")
protected String name;

@Column(name = "size")
private Long size;
Expand All @@ -42,8 +42,8 @@ public abstract class Image {
@Column(name = "created_date")
private LocalDateTime createdDate;

protected Image(String url, Long size, String extension) {
this.url = url;
protected Image(String name, Long size, String extension) {
this.name = name;
this.size = size;
this.extension = extension;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
@Getter
public enum ErrorCode {

// TODO: status,code, message ์ˆ˜์ •

UNEXPECTED(HttpStatus.BAD_REQUEST.value(), "-1", "์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค."),

ENTITY_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "-10404", "์—”ํ‹ฐํ‹ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public static void deleteFile(Path path) {
}
}

public static String generateUuidName() {
return UUID.randomUUID().toString().replace("-", "");
public static String createRandomFileName(String extension) {
return UUID.randomUUID().toString().replace("-", "") + "." + extension;
}

public static String getExtension(MultipartFile file) {
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/org/ktc2/cokaen/wouldyouin/_common/util/UriUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.ktc2.cokaen.wouldyouin._common.util;

import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

public class UriUtil {

public static String buildUrl(String scheme, String host, String path, MultiValueMap<String, String> params) {
return UriComponentsBuilder.newInstance()
.scheme(scheme)
.host(host)
.path(path)
.queryParams(params)
.build()
.toString();
}

public static String buildUrl(String scheme, String host, String path) {
return UriComponentsBuilder.newInstance()
.scheme(scheme)
.host(host)
.path(path)
.build()
.toString();
}

public static String assembleFullUrl(String baseUrl, String... paths) {
String joinedPath = String.join("/", paths);
return UriComponentsBuilder.fromHttpUrl(baseUrl)
.path("/" + joinedPath)
.build()
.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@
public class Location {
Double longitude;
Double latitude;
String detailAddress;
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static AdvertisementResponse from(Advertisement advertisement) {
return AdvertisementResponse.builder()
.id(advertisement.getId())
.title(advertisement.getTitle())
.imageUrl(advertisement.getAdvertisementImage().getUrl())
.imageUrl(advertisement.getAdvertisementImage().getName())
.startTime(advertisement.getStartTime())
.endTime(advertisement.getEndTime())
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.Objects;
import org.ktc2.cokaen.wouldyouin._common.util.RestClientUtil;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.AccessTokenResponse;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthRequest;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthResourcesResponse;
Expand All @@ -12,7 +13,6 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class GoogleRequestService extends OauthRequestService {
Expand Down Expand Up @@ -44,22 +44,10 @@ public class GoogleRequestService extends OauthRequestService {
private final HttpHeaders loginRequestHeaders;

public GoogleRequestService(RestClientUtil restClientUtil) {

this.client = restClientUtil;

loginRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(loginRequestHost)
.path(loginRequestPath)
.build(true)
.toString();

accessRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(accessRequestHost)
.path(accessRequestPath)
.build(true)
.toString();
loginRequestUri = UriUtil.buildUrl("https", loginRequestHost, loginRequestPath);
accessRequestUri = UriUtil.buildUrl("https", accessRequestHost, accessRequestPath);

loginRequestHeaders = new HttpHeaders();
loginRequestHeaders.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.ktc2.cokaen.wouldyouin._common.util.RestClientUtil;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.AccessTokenResponse;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthRequest;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthResourcesResponse;
Expand All @@ -14,7 +15,8 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

@Service
public class KakaoRequestService extends OauthRequestService {
Expand Down Expand Up @@ -53,29 +55,23 @@ protected AccountType getAccountType() {
public KakaoRequestService(RestClientUtil restClientUtil) {
this.client = restClientUtil;

OauthRequest request = getOauthRequestBase();
loginRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(loginRequestHost)
.path(loginRequestPath)
.queryParam("grant_type", request.getGrantType())
.queryParam("client_id", request.getClientId())
.queryParam("client_secret", request.getClientSecret())
.queryParam("code", request.getCode())
.build(true)
.toString();

accessRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(accessRequestHost)
.path(accessRequestPath)
.build(true)
.toString();
loginRequestUri = UriUtil.buildUrl("https", loginRequestHost, loginRequestPath, getLoginRequestQueryParams());
accessRequestUri = UriUtil.buildUrl("https", accessRequestHost, accessRequestPath);

loginRequestHeaders = new HttpHeaders();
loginRequestHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
}

protected MultiValueMap<String, String> getLoginRequestQueryParams() {
OauthRequest request = getOauthRequestBase();
var queries = new LinkedMultiValueMap<String, String>();
queries.add("grant_type", request.getGrantType());
queries.add("client_id", request.getClientId());
queries.add("client_secret", request.getClientSecret());
queries.add("code", request.getCode());
return queries;
}

protected HttpHeaders getAccessRequestHeaders(AccessTokenResponse authenticationResponse) {
HttpHeaders accessRequestHeaders = new HttpHeaders();
accessRequestHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static CurationCardResponse from(CurationCard curationCard) {
.content(curationCard.getContent())
.imageUrls(
curationCard.getCurationImages().stream()
.map(CurationImage::getUrl)
.map(CurationImage::getName)
.toList()
)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class CurationCreateRequest {
@NotNull(message = "์ง€์—ญ์€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค.")
private Area area;

private List<String> hashTag;
private List<String> hashTags;

private List<Long> eventIds;

Expand All @@ -49,7 +49,7 @@ public Curation toEntity(Curator curator, List<CurationCard> curationCards, List
.content(this.content)
.curationCards(curationCards)
.area(this.area)
.hashTag(this.hashTag)
.hashTags(this.hashTags)
.events(events)
.build();
}
Expand Down
Loading
Loading