Skip to content

Commit

Permalink
Merge pull request #64 from SWM-SMART/feat/#63
Browse files Browse the repository at this point in the history
답변 저장 기능 구현 및 수정
  • Loading branch information
noparamin authored Nov 18, 2023
2 parents 5c4b201 + 85ae4f2 commit 8c94330
Show file tree
Hide file tree
Showing 14 changed files with 229 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,15 @@ public class JwtAuthenticationProcessingFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserRepository userRepository;

private static final String NO_CHECK_URL = "/login";
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (request.getRequestURI().equals(NO_CHECK_URL)) {
filterChain.doFilter(request, response);
return; // return으로 이후 현재 필터 진행 막기 (안해주면 아래로 내려가서 계속 필터 진행시킴)
}
// 사용자 요청 헤더에서 RefreshToken 추출
// -> RefreshToken이 없거나 유효하지 않다면(DB에 저장된 RefreshToken과 다르다면) null을 반환
// 사용자의 요청 헤더에 RefreshToken이 있는 경우는, AccessToken이 만료되어 요청한 경우밖에 없다.
Expand Down
22 changes: 12 additions & 10 deletions src/main/java/com/smart/watchboard/common/support/PdfConverter.java
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
package com.smart.watchboard.common.support;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class PdfConverter {
public static File convertStringToPdf(String content, String fileName) throws DocumentException, IOException {
Document document = new Document();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

try {
BaseFont objBaseFont = BaseFont.createFont("src/main/resources/templates/NanumGothic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font objFont = new Font(objBaseFont, 12);
//Font koreanFont = FontFactory.getFont("NanumGothic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
document.add(new Paragraph(content));
document.add(new Paragraph(content, objFont));
} finally {
document.close();
}
Expand All @@ -31,11 +35,9 @@ public static File convertStringToPdf(String content, String fileName) throws Do

public static File saveByteArrayToFile(byte[] bytes, String fileName) throws IOException {
File outputFile = new File(fileName);
System.out.println(outputFile.getName());
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
fos.write(bytes);
}
System.out.println(outputFile);
return outputFile;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ CorsConfigurationSource corsConfigurationSource() {
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.setAllowedOrigins(Arrays.asList("https://8485-182-228-41-227.ngrok-free.app")); // 추후 수정
configuration.setAllowedOrigins(Arrays.asList("https://4988-221-148-248-129.ngrok-free.app")); // 추후 수정
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,21 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

import static com.smart.watchboard.common.support.PdfConverter.*;


@RestController
@RequestMapping("/documents")
Expand All @@ -29,7 +36,7 @@ public class AudioFileController {
private final AwsS3Uploader awsS3Uploader;
private final NoteService noteService;
private final LectureNoteService lectureNoteService;
private final RequestService requestService;
//private final RequestService requestService;
private final STTService sttService;
private final SummaryService summaryService;
private final FileService fileService;
Expand Down Expand Up @@ -91,33 +98,55 @@ public ResponseEntity<?> getAudioFile(@PathVariable(value = "documentID") long d

@PostMapping("/testffff")
public ResponseEntity<?> test(@RequestHeader("Authorization") String accessToken) throws UnsupportedAudioFileException, IOException, DocumentException {
String body = """
{"keywords":["eatssss","food","today"]}
""";
String path = "https://watchboard-record-bucket.s3.ap-northeast-2.amazonaws.com/audio/mp4/26.1.m4a";
ResponseEntity<String> responseEntity = sttService.getSTT(path);
//System.out.println(responseEntity.getBody().toString());
List<SttData> sttData = sttService.getSTTData(responseEntity);
String text = sttService.getText(responseEntity);
System.out.println(text);
// String sttResult = "안녕하세요 Hello!!!!";
// String sttFileName = "sttResult.pdf";
// File textPdfFile = convertStringToPdf(sttResult, sttFileName);
// String contentType = "application/pdf";
// String originalFilename = textPdfFile.getName();
// String name = textPdfFile.getName();
//
//
// FileInputStream fileInputStream = new FileInputStream(textPdfFile);
// MultipartFile multipartFile = new MockMultipartFile(name, originalFilename, contentType, fileInputStream);
// S3Dto s3Dto = new S3Dto(multipartFile, 26L);
// String path = awsS3Uploader.uploadTextPdfFile(s3Dto);
// System.out.println(path);
// String body = """
// {"keywords":["eatssss","food","today"]}
// """;
// String path = "https://watchboard-record-bucket.s3.ap-northeast-2.amazonaws.com/audio/mp4/26.1.m4a";
// ResponseEntity<String> responseEntity = sttService.getSTT(path);
// //System.out.println(responseEntity.getBody().toString());
// List<SttData> sttData = sttService.getSTTData(responseEntity);
// String text = sttService.getText(responseEntity);
// System.out.println(text);
String sttResult = "안녕하세요 Hello!!!!";
String sttFileName = "sttResult.pdf";
File textPdfFile = convertStringToPdf(sttResult, sttFileName);
String contentType = "application/pdf";
String originalFilename = textPdfFile.getName();
String name = textPdfFile.getName();


FileInputStream fileInputStream = new FileInputStream(textPdfFile);
MultipartFile multipartFile = new MockMultipartFile(name, originalFilename, contentType, fileInputStream);
S3Dto s3Dto = new S3Dto(multipartFile, 26L, 7L, "pdf");
String path = awsS3Uploader.uploadTextPdfFile(s3Dto);
System.out.println(path);

// String path = "https://s3.ap-northeast-2.amazonaws.com/watchboard-record-bucket/application/pdf/감정분류.pdf";
// ResponseEntity<SummaryDto> responseEntity = requestService.requestPdfSummary(path);
// System.out.println(responseEntity.getBody().getSummary());
return new ResponseEntity<>(responseEntity.getBody(), HttpStatus.OK);

// String sttResult = "안녕하세요";
// String sttFileName = "hello" + ".txt";
// File textFile = createTextFile(sttResult, sttFileName);
// String contentType = "text/plain";
// String originalFilename = textFile.getName();
// String name = textFile.getName();
//
// FileInputStream fileInputStream = new FileInputStream(textFile);
// MultipartFile multipartFile = createMockMultipartFile(name, originalFilename, textFile);
// //MultipartFile multipartFile = new MockMultipartFile(name, originalFilename, contentType, fileInputStream);
// //System.out.println(multipartFile.getInputStream().read());
// S3Dto s3DtoForSTT = new S3Dto(multipartFile, 26L, 7L, "txt");
// String textPdfPath = awsS3Uploader.uploadTextPdfFile(s3DtoForSTT);
// System.out.println(textPdfPath);
// try (InputStream inputStream = multipartFile.getInputStream()) {
// // InputStream에서 데이터를 읽어와서 콘솔에 출력
// int byteRead;
// while ((byteRead = inputStream.read()) != -1) {
// System.out.print((char) byteRead);
// }
// }
return new ResponseEntity<>(HttpStatus.OK);
}

}
61 changes: 34 additions & 27 deletions src/main/java/com/smart/watchboard/controller/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.io.UnsupportedEncodingException;
import java.net.URI;
Expand All @@ -24,31 +25,37 @@ public class AuthController {

private final JwtService jwtService;

@GetMapping("/users/auth/kakao/callback")
@Operation(summary = "카카오 로그인", description = "인가코드를 받아 이후 작업을 진행하고 로그인을 완료한다.")
public ResponseEntity<?> oauthLoginCallback(@RequestParam("code") String code) {
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create("/"));

List<ResponseCookie> cookies = new ArrayList<>();
cookies.add(ResponseCookie.from("accessToken", "asdasdqweqwe")
.httpOnly(true)
.secure(true)
.path("/")
.build());
cookies.add(ResponseCookie.from("refreshToken", "asdklj123")
.httpOnly(true)
.secure(true)
.path("/")
.build());

// 쿠키들을 하나씩 HttpHeaders에 추가
for (ResponseCookie cookie : cookies) {
headers.add(HttpHeaders.SET_COOKIE, cookie.toString());
}

return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
}
// @GetMapping("/users/auth/kakao/callback")
// @Operation(summary = "카카오 로그인", description = "인가코드를 받아 이후 작업을 진행하고 로그인을 완료한다.")
// public RedirectView oauthLoginCallback(@RequestParam("code") String code) {
// RedirectView redirectView = new RedirectView();
// redirectView.setUrl("https://watchboard.me");
// redirectView.setStatusCode(HttpStatus.FOUND);
//
// HttpHeaders headers = new HttpHeaders();
// headers.setLocation(URI.create("/"));
//
// List<ResponseCookie> cookies = new ArrayList<>();
// cookies.add(ResponseCookie.from("accessToken", "asdasdqweqwe")
// .httpOnly(true)
// .secure(true)
// .path("/")
// .build());
// cookies.add(ResponseCookie.from("refreshToken", "asdklj123")
// .httpOnly(true)
// .secure(true)
// .path("/")
// .build());
//
// // 쿠키들을 하나씩 HttpHeaders에 추가
// for (ResponseCookie cookie : cookies) {
// headers.add(HttpHeaders.SET_COOKIE, cookie.toString());
// }
// return redirectView;
//
// //return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
//
// }

@GetMapping("/users/token")
@Operation(summary = "로그인 후 토큰 전달", description = "로그인 후 request로 받은 리프레시 토큰 검증 후 액세스 토큰과 리프레시 토큰 전달")
Expand All @@ -62,9 +69,9 @@ public ResponseEntity<HttpHeaders> getTokens(@CookieValue("refreshToken") String
@Operation(summary = "로그아웃", description = "로그아웃을 위해 refreshToken 쿠키 만료")
public ResponseEntity<?> logout(@RequestHeader("Authorization") String accessToken) {
HttpHeaders headers = jwtService.createHeaderWithDeletedCookie(accessToken);
headers.setLocation(URI.create("/"));
//headers.setLocation(URI.create("/"));

return new ResponseEntity<>(headers, HttpStatus.FOUND);
return new ResponseEntity<>(headers, HttpStatus.OK);
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.smart.watchboard.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.smart.watchboard.domain.Answer;
import com.smart.watchboard.domain.Document;
import com.smart.watchboard.domain.Keyword;
import com.smart.watchboard.dto.AnswerDto;
Expand Down Expand Up @@ -37,6 +38,7 @@ public class GraphController {
private final SseService sseService;
private final KeywordService keywordService;
private final JwtService jwtService;
private final QuestionService questionService;
@PostMapping("/graph/{documentID}")
@Operation(summary = "마인드맵 생성", description = "ai 서버에 마인드맵 요청한다.")
public void createMindmap(@PathVariable(value = "documentID") long documentId, @RequestBody KeywordsBodyDto keywordsBodyDto, @RequestHeader("Authorization") String accessToken) throws JsonProcessingException {
Expand Down Expand Up @@ -94,11 +96,14 @@ public ResponseEntity<?> updateKeywords(@PathVariable(value = "documentID") long

@GetMapping("/documents/{documentID}/mindmap/keyword/{keywordLabel}")
@Operation(summary = "키워드 질문", description = "키워드 AI에 질문")
public ResponseEntity<?> getAnswer(@PathVariable(value = "documentID") long documentId, @PathVariable String keywordLabel, @RequestHeader("Authorization") String accessToken) throws JsonProcessingException {
//ResponseEntity<AnswerDto> responseEntity = requestService.requestAnswer(documentId, keywordLabel);
sseService.notifyAnswer(documentId, keywordLabel);
public ResponseEntity<AnswerDto> getAnswer(@PathVariable(value = "documentID") long documentId, @PathVariable String keywordLabel, @RequestHeader("Authorization") String accessToken) throws JsonProcessingException {
AnswerDto answerDto = questionService.getAnswer(documentId, keywordLabel);
if (answerDto == null) {
sseService.notifyAnswer(documentId, keywordLabel);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}

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

@GetMapping(value = "documents/{documentID}/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Expand Down
29 changes: 29 additions & 0 deletions src/main/java/com/smart/watchboard/domain/Answer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.smart.watchboard.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.time.Instant;
import java.util.List;
import java.util.Map;

@AllArgsConstructor
@Getter
@Setter
@Builder
@Document("answer")
public class Answer {
@Id
private ObjectId objectId;

private Long documentId;

private String keyword;

private String text;
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
String refreshToken = jwtService.createRefreshToken(oAuth2User.getUserId());
ResponseCookie cookie = jwtService.setCookieRefreshToken(refreshToken);
response.setHeader("Set-Cookie", cookie.toString());
response.sendRedirect("oauth2/sign-up"); // 추후 수정
response.sendRedirect("https://4988-221-148-248-129.ngrok-free.app"); // 추후 수정
User findUser = userRepository.findByEmail(oAuth2User.getEmail())
.orElseThrow(() -> new IllegalArgumentException("이메일에 해당하는 유저가 없습니다."));
findUser.authorizeUser();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.smart.watchboard.repository;

import com.smart.watchboard.domain.Answer;
import com.smart.watchboard.domain.Keyword;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.Optional;

public interface AnswerRepository extends MongoRepository<Answer, Long> {
Optional<Answer> findByDocumentIdAndKeyword(Long documentId, String keyword);
}
2 changes: 1 addition & 1 deletion src/main/java/com/smart/watchboard/service/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public ResponseCookie setCookieRefreshToken(String refreshToken) throws Unsuppor
public ResponseCookie deleteCookieRefreshToken() {
ResponseCookie cookie = ResponseCookie.from("refreshToken", "")
.maxAge(0)
.path("/")
.path("/users/token")
.secure(true)
.sameSite("None")
.httpOnly(true)
Expand Down
Loading

0 comments on commit 8c94330

Please sign in to comment.