Skip to content

Commit

Permalink
Merge pull request #23 from Team-Walkie/mvc/seungmin
Browse files Browse the repository at this point in the history
community upload api 수정
  • Loading branch information
bngsh authored Sep 6, 2023
2 parents 2aeee7c + efe1a70 commit d3ff2c7
Show file tree
Hide file tree
Showing 10 changed files with 158 additions and 85 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ dependencies {
implementation "com.querydsl:querydsl-jpa:${queryDslVersion}"
annotationProcessor "com.querydsl:querydsl-apt:${queryDslVersion}"

implementation group: 'com.google.firebase', name: 'firebase-admin', version: '8.1.0'
}

tasks.named('test') {
Expand Down
Binary file added src/main/.DS_Store
Binary file not shown.
25 changes: 25 additions & 0 deletions src/main/java/com/whyranoid/walkie/ApiBaseUrlSingleton.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.whyranoid.walkie;

public class ApiBaseUrlSingleton {
private static ApiBaseUrlSingleton instance;
private String baseUrl;

private ApiBaseUrlSingleton() {
// private 생성자로 외부에서 인스턴스를 생성하지 못하도록 함
}

public static ApiBaseUrlSingleton getInstance() {
if (instance == null) {
instance = new ApiBaseUrlSingleton();
}
return instance;
}

public String getBaseUrl() {
return baseUrl;
}

public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
}
35 changes: 35 additions & 0 deletions src/main/java/com/whyranoid/walkie/FirebaseInitializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.whyranoid.walkie;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Slf4j
@Service
public class FirebaseInitializer {
@Value("${app.firebase-configuration-file}")
private String firebaseConfigPath;

@PostConstruct
public void initialize() {
try {
ApiBaseUrlSingleton.getInstance().setBaseUrl("https://walkie-5bfb3.appspot.com");
FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(
GoogleCredentials.fromStream(
new ClassPathResource(firebaseConfigPath).getInputStream())).build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
log.info("Firebase application has been initialized");
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.whyranoid.walkie.controller;

import com.whyranoid.walkie.dto.request.PostRequest;
import com.google.firebase.auth.FirebaseAuthException;
import com.whyranoid.walkie.service.CommunityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
Expand All @@ -12,9 +13,12 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
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 org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Tag(name = "community", description = "커뮤니티 API")
@RestController
Expand All @@ -24,13 +28,23 @@ public class CommunityController {
HttpHeaders httpHeaders = new HttpHeaders();

private final CommunityService communityService;
@Operation(summary = "게시글 올리기", description = "커뮤니티에 게시글을 업로드합니다.")
@ApiResponse(responseCode = "200", description = "업로드 성공", content = @Content(array = @ArraySchema(schema = @Schema(implementation = com.whyranoid.walkie.dto.response.ApiResponse.class))))
@PostMapping("/upload-post")
@Operation(summary = "게시글 올리기", description = "커뮤니티에 게시글을 업로드합니다. colorMode는 글자색으로 다음과 같이 표현합니다. -> (0: 검정색, 1: 흰색) historyContent는 history 정보를 표현합니다. 없으면 null 넘겨주시면 돼요")
@ApiResponse(responseCode = "200", description = "업로드 성공", content = @Content(schema = @Schema(implementation = com.whyranoid.walkie.dto.response.ApiResponse.class)))
@Parameters({
@Parameter(name = "image", description = "업로드할 이미지 multipart", example = "image.jpg"),
@Parameter(name = "walkieId", description = "유저 아이디", example = "123"),
@Parameter(name = "content", description = "유저가 쓴 글의 내용", example = "아 상쾌하게 달렸다!"),
@Parameter(name = "colorMode", description = "글자색 카테고리(0은 검정, 1은 흰색)", example = "1"),
@Parameter(name = "historyContent", description = "운동기록 정보", example = "7.51km 01:03:45 08'29\"")
})
@PostMapping(value = "/upload-post")
public ResponseEntity uploadPost(
@RequestBody PostRequest postRequest
) {
return ResponseEntity.ok(communityService.uploadPost(postRequest));
@RequestParam("image")MultipartFile image,
@RequestParam("walkieId")Long walkieId,
@RequestParam("content")String content,
@RequestParam("colorMode")Integer colorMode,
@RequestParam("historyContent")String historyContent
) throws IOException, FirebaseAuthException {
return ResponseEntity.ok(communityService.uploadPost(image, walkieId, content, colorMode, historyContent));
}

}
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
package com.whyranoid.walkie.controller;

import com.whyranoid.walkie.dto.response.HistoryResponse;
import com.whyranoid.walkie.service.HistoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
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.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "history", description = "운동기록 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/history")
public class HistoryController {
HttpHeaders httpHeaders = new HttpHeaders();
private final HistoryService historyService;

@Operation(summary = "운동기록 가져오기", description = "해당 유저의 운동기록을 가져옵니다.")
@ApiResponse(responseCode = "200", description = "호출 성공", content = @Content(array = @ArraySchema(schema = @Schema(implementation = HistoryResponse.class))))
@GetMapping("/my-history")
public ResponseEntity getHistory(
@RequestParam Long walkieId
) {
return new ResponseEntity<>(historyService.getHistory(walkieId), httpHeaders, HttpStatus.OK);
}
}
//package com.whyranoid.walkie.controller;
//
//import com.whyranoid.walkie.dto.response.HistoryResponse;
//import com.whyranoid.walkie.service.HistoryService;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.media.ArraySchema;
//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.tags.Tag;
//import lombok.RequiredArgsConstructor;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//@Tag(name = "history", description = "운동기록 API")
//@RestController
//@RequiredArgsConstructor
//@RequestMapping("/api/history")
//public class HistoryController {
// HttpHeaders httpHeaders = new HttpHeaders();
// private final HistoryService historyService;
//
// @Operation(summary = "운동기록 가져오기", description = "해당 유저의 운동기록을 가져옵니다.")
// @ApiResponse(responseCode = "200", description = "호출 성공", content = @Content(array = @ArraySchema(schema = @Schema(implementation = HistoryResponse.class))))
// @GetMapping("/my-history")
// public ResponseEntity getHistory(
// @RequestParam Long walkieId
// ) {
// return new ResponseEntity<>(historyService.getHistory(walkieId), httpHeaders, HttpStatus.OK);
// }
//}
8 changes: 8 additions & 0 deletions src/main/java/com/whyranoid/walkie/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ public class Post {
@Column(name = "date", nullable = false)
private String date;

@NotNull
@Column(name = "color_mode", nullable = false)
private Integer colorMode;

@NotNull
@Column(name = "history_content", nullable = true)
private String historyContent;

@ManyToOne
@JoinColumn(name = "user_id", nullable = false) // referencedColumnName는 디폴트가 pk
private Walkie user;
Expand Down
32 changes: 0 additions & 32 deletions src/main/java/com/whyranoid/walkie/dto/request/PostRequest.java

This file was deleted.

34 changes: 28 additions & 6 deletions src/main/java/com/whyranoid/walkie/service/CommunityService.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
package com.whyranoid.walkie.service;

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.cloud.StorageClient;
import com.whyranoid.walkie.ApiBaseUrlSingleton;
import com.whyranoid.walkie.domain.Post;
import com.whyranoid.walkie.dto.request.PostRequest;
import com.whyranoid.walkie.dto.response.ApiResponse;
import com.whyranoid.walkie.repository.CommunityRepository;
import com.whyranoid.walkie.repository.WalkieRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
@Transactional
Expand All @@ -18,20 +28,32 @@ public class CommunityService {
private final CommunityRepository communityRepository;
private final WalkieRepository walkieRepository;

public ApiResponse uploadPost(PostRequest postRequest) {
@Value("${app.firebase-bucket-name}")
private String firebaseBucket;

public ApiResponse uploadPost(MultipartFile image, Long walkieId, String content, Integer colorMode, String historyContent) throws IOException, FirebaseAuthException {
String imageUrl = "post/" + UUID.randomUUID() + ".jpg";
Post post = new Post();
Long walkieId = postRequest.getWalkieId();
String photo = postRequest.getPhoto();
String content = postRequest.getContent();
post.setPhoto(photo);
post.setContent(content);
post.setDate(LocalDateTime.now().toString());
post.setColorMode(colorMode);
post.setHistoryContent(historyContent);
// 어떤 에러 던져야 할 지 논의해봐야 할 듯
post.setUser(walkieRepository.findByUserId(walkieId).orElseThrow());
uploadImage(image, imageUrl);
post.setPhoto(ApiBaseUrlSingleton.getInstance().getBaseUrl()+ '/' + imageUrl);
communityRepository.uploadPost(post);
return ApiResponse.builder()
.status(200)
.message("게시글 업로드 완료!")
.build();
}

public String uploadImage(MultipartFile image, String nameFile)
throws IOException, FirebaseAuthException {
Bucket bucket = StorageClient.getInstance().bucket(firebaseBucket);
InputStream content = new ByteArrayInputStream(image.getBytes());
Blob blob = bucket.create(nameFile, content, image.getContentType());
return blob.getMediaLink();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public Long startWalking(WalkingDto walkingDto) {
Walkie walkie = walkieRepository.findById(walkingDto.getWalkieId()).orElseThrow(EntityNotFoundException::new);

History input = History.builder()
.startTime(walkingDto.getStartTime())
.startTime(walkingDto.getStartTime().toString())
.user(walkie)
.build();

Expand Down

0 comments on commit d3ff2c7

Please sign in to comment.