Skip to content

Commit

Permalink
게시판 완료 (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
limehee authored Jul 24, 2024
1 parent 5b5be5a commit 0342573
Show file tree
Hide file tree
Showing 34 changed files with 670 additions and 16 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ dependencies {
compileOnly 'org.projectlombok:lombok' // 롬복
annotationProcessor 'org.projectlombok:lombok' // 롬복
implementation 'com.google.code.gson:gson:2.10.1' // JSON 라이브러리
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0' // Swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' // Swagger
implementation 'commons-io:commons-io:2.16.1' // Apache Commons IO
implementation 'com.google.guava:guava:33.2.1-jre' // Google Core Libraries For Java

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
Expand All @@ -21,6 +22,25 @@ public class FileHandler {
@Value("${resource.file.path}")
private String filePath;

public void init() {
filePath = filePath.replace("/", File.separator).replace("\\", File.separator);
}

public String saveFile(MultipartFile multipartFile, String category) throws IOException {
init();
String originalFilename = multipartFile.getOriginalFilename();
String extension = FilenameUtils.getExtension(originalFilename);

String saveFilename = makeFileName(extension);
String savePath = filePath + File.separator + category + File.separator + saveFilename;

File file = new File(savePath);
ensureParentDirectoryExists(file);
multipartFile.transferTo(file);
setFilePermissions(file, savePath, extension);
return savePath;
}

public String saveFile(File file) throws IOException {
String originalFilename = file.getName();
String extension = FilenameUtils.getExtension(originalFilename);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.stempo.api.domain.application.service;

import com.stempo.api.domain.domain.model.BoardCategory;
import com.stempo.api.domain.presentation.dto.request.BoardRequestDto;
import com.stempo.api.domain.presentation.dto.request.BoardUpdateRequestDto;
import com.stempo.api.domain.presentation.dto.response.BoardResponseDto;

import java.util.List;

public interface BoardService {

Long registerBoard(BoardRequestDto requestDto);

List<BoardResponseDto> getBoardsByCategory(BoardCategory category);

Long updateBoard(Long boardId, BoardUpdateRequestDto requestDto);

Long deleteBoard(Long boardId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.stempo.api.domain.application.service;

import com.stempo.api.domain.domain.model.Board;
import com.stempo.api.domain.domain.model.BoardCategory;
import com.stempo.api.domain.domain.model.User;
import com.stempo.api.domain.domain.repository.BoardRepository;
import com.stempo.api.domain.presentation.dto.request.BoardRequestDto;
import com.stempo.api.domain.presentation.dto.request.BoardUpdateRequestDto;
import com.stempo.api.domain.presentation.dto.response.BoardResponseDto;
import com.stempo.api.global.exception.PermissionDeniedException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class BoardServiceImpl implements BoardService {

private final UserService userService;
private final BoardRepository repository;

@Override
public Long registerBoard(BoardRequestDto requestDto) {
User user = userService.getCurrentUser();
Board board = BoardRequestDto.toDomain(requestDto, user.getDeviceTag());
board.validateAccessPermissionForNotice(user);
return repository.save(board).getId();
}

@Override
public List<BoardResponseDto> getBoardsByCategory(BoardCategory category) {
validateAccessPermissionForSuggestion(category);
List<Board> boards = repository.findByCategory(category);
return boards.stream()
.map(BoardResponseDto::toDto)
.toList();
}

@Override
public Long updateBoard(Long boardId, BoardUpdateRequestDto requestDto) {
User user = userService.getCurrentUser();
Board board = repository.findByIdOrThrow(boardId);
board.validateAccessPermission(user);
board.update(requestDto);
return repository.save(board).getId();
}

@Override
public Long deleteBoard(Long boardId) {
User user = userService.getCurrentUser();
Board board = repository.findByIdOrThrow(boardId);
board.validateAccessPermission(user);
board.delete();
return repository.save(board).getId();
}

private void validateAccessPermissionForSuggestion(BoardCategory category) {
User user = userService.getCurrentUser();
if (category.equals(BoardCategory.SUGGESTION) && !user.isAdmin()) {
throw new PermissionDeniedException("건의하기는 관리자만 조회할 수 있습니다.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,49 @@
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class FileService {

private final FileHandler fileHandler;
private final BoardService boardService;
private final UploadedFileService uploadedFileService;
private final FileHandler fileHandler;

@Value("${resource.file.url}")
private String fileURL;

public List<String> saveFiles(List<MultipartFile> multipartFiles, String path) throws IOException {
List<String> filePaths = new ArrayList<>();
for (MultipartFile multipartFile : multipartFiles) {
String filePath = saveFile(multipartFile, path);
filePaths.add(filePath);
}
return filePaths;
}

public String saveFile(MultipartFile multipartFile, String path) throws IOException {
String savedFilePath = fileHandler.saveFile(multipartFile, path);
String fileName = new File(savedFilePath).getName();
String url = fileURL + "/" + path.replace(File.separator, "/") + "/" + fileName;

UploadedFile uploadedFile = UploadedFile.create(multipartFile.getOriginalFilename(), fileName, savedFilePath, url, multipartFile.getSize());
uploadedFileService.saveUploadedFile(uploadedFile);
return uploadedFile.getUrl();
}

public String saveFile(File file) throws IOException {
String savedFilePath = fileHandler.saveFile(file);
String fileName = new File(savedFilePath).getName();
String url = fileURL + "/" + fileName;

UploadedFile uploadedFile = UploadedFile.create(file.getName(), fileName, savedFilePath, url, file.length(), null);
UploadedFile uploadedFile = UploadedFile.create(file.getName(), fileName, savedFilePath, url, file.length());
uploadedFileService.saveUploadedFile(uploadedFile);
return url;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
Expand All @@ -29,9 +30,26 @@ public String record(RecordRequestDto requestDto) {
public List<RecordResponseDto> getRecordsByDateRange(LocalDate startDate, LocalDate endDate) {
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atStartOfDay().plusDays(1);

// startDateTime 이전의 가장 최신 데이터 가져오기
Record latestBeforeStartDate = recordRepository.findLatestBeforeStartDate(startDateTime);

// startDateTime과 endDateTime 사이의 데이터 가져오기
List<Record> records = recordRepository.findByDateBetween(startDateTime, endDateTime);
return records.stream()

// 결과 합치기
List<RecordResponseDto> combinedRecords = new ArrayList<>();
if (latestBeforeStartDate != null) {
combinedRecords.add(RecordResponseDto.toDto(latestBeforeStartDate));
}
combinedRecords.addAll(records.stream()
.map(RecordResponseDto::toDto)
.toList();
.toList());

// 데이터가 없을 경우 오늘 날짜로 값을 0으로 설정하여 반환
if (combinedRecords.isEmpty()) {
combinedRecords.add(RecordResponseDto.createDefault());
}
return combinedRecords;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public class RhythmServiceImpl implements RhythmService {
@Override
public String createRhythm(int bpm) {
try {
validateBpmRange(bpm);
String outputFilename = "rhythm_" + bpm + "_bpm.wav";

Optional<UploadedFile> uploadedFile = uploadedFileService.getUploadedFileByOriginalFileName(outputFilename);
Expand All @@ -43,6 +44,14 @@ public String createRhythm(int bpm) {
}
}

private void validateBpmRange(int bpm) {
int minBpm = 10;
int maxBpm = 200;
if (bpm < minBpm || bpm > maxBpm) {
throw new RhythmGenerationException("BPM must be between " + minBpm + " and " + maxBpm);
}
}

private Path generateRhythmFile(int bpm, String outputFilename) throws Exception {
Path projectRoot = Paths.get("").toAbsolutePath();
Path venvPythonPath = projectRoot.resolve(venvPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ public interface UserService {
boolean existsById(String id);

String getCurrentDeviceTag();

User getCurrentUser();
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

private final UserRepository userRepository;
private final UserRepository repository;
private final PasswordService passwordService;
private final PasswordUtil passwordUtil;

Expand All @@ -23,21 +23,27 @@ public User registerUser(String deviceTag, String password) {
User user = User.create(deviceTag, rawPassword);
String encodedPassword = passwordService.encodePassword(user.getPassword());
user.updatePassword(encodedPassword);
return userRepository.save(user);
return repository.save(user);
}

@Override
public Optional<User> findById(String id) {
return userRepository.findById(id);
return repository.findById(id);
}

@Override
public boolean existsById(String id) {
return userRepository.existsById(id);
return repository.existsById(id);
}

@Override
public String getCurrentDeviceTag() {
return AuthUtil.getAuthenticationInfoDeviceTag();
}

@Override
public User getCurrentUser() {
String deviceTag = getCurrentDeviceTag();
return repository.findByIdOrThrow(deviceTag);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class Article {
private String thumbnailUrl;
private String articleUrl;
private LocalDateTime createdAt;
private boolean deleted = false;
private boolean deleted;

public void update(ArticleUpdateRequestDto requestDto) {
Optional.ofNullable(requestDto.getTitle()).ifPresent(this::setTitle);
Expand Down
61 changes: 61 additions & 0 deletions src/main/java/com/stempo/api/domain/domain/model/Board.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.stempo.api.domain.domain.model;

import com.stempo.api.domain.presentation.dto.request.BoardUpdateRequestDto;
import com.stempo.api.global.exception.PermissionDeniedException;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Getter
@Setter
@Builder
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Board {

private Long id;
private String deviceTag;
private BoardCategory category;
private String title;
private String content;
private List<String> fileUrls;
private LocalDateTime createdAt;
private boolean deleted;

public void update(BoardUpdateRequestDto requestDto) {
Optional.ofNullable(requestDto.getCategory()).ifPresent(category -> this.category = category);
Optional.ofNullable(requestDto.getTitle()).ifPresent(title -> this.title = title);
Optional.ofNullable(requestDto.getContent()).ifPresent(content -> this.content = content);
}

public void delete() {
setDeleted(true);
}

public boolean isOwner(User user) {
return this.deviceTag.equals(user.getDeviceTag());
}

public void validateAccessPermission(User user) {
if (!(isOwner(user) || user.isAdmin())) {
throw new PermissionDeniedException("게시글을 수정/삭제할 권한이 없습니다.");
}
}

public void validateAccessPermissionForNotice(User user) {
if (isNotice() && !user.isAdmin()) {
throw new PermissionDeniedException("공지사항 관리 권한이 없습니다.");
}
}

public boolean isNotice() {
return category.equals(BoardCategory.NOTICE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class UploadedFile {
private Long fileSize;
private LocalDateTime createdAt;

public static UploadedFile create(String originalFileName, String saveFileName, String savedPath, String url, Long fileSize, String contentType) {
public static UploadedFile create(String originalFileName, String saveFileName, String savedPath, String url, Long fileSize) {
return UploadedFile.builder()
.originalFileName(originalFileName)
.saveFileName(saveFileName)
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/stempo/api/domain/domain/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,8 @@ public static User create(String deviceTag, String password) {
public void updatePassword(String encodedPassword) {
setPassword(encodedPassword);
}

public boolean isAdmin() {
return role.equals(Role.ADMIN);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.stempo.api.domain.domain.repository;

import com.stempo.api.domain.domain.model.Board;
import com.stempo.api.domain.domain.model.BoardCategory;

import java.util.List;

public interface BoardRepository {

Board save(Board board);

List<Board> findByCategory(BoardCategory category);

Board findByIdOrThrow(Long boardId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public interface RecordRepository {
Record save(Record record);

List<Record> findByDateBetween(LocalDateTime startDateTime, LocalDateTime endDateTime);

Record findLatestBeforeStartDate(LocalDateTime startDateTime);
}
Loading

0 comments on commit 0342573

Please sign in to comment.