mirror of
https://github.com/headporter81/specialsource-homepage-backend.git
synced 2026-12-06 07:41:09 +09:00
feat : 자료실 파일 받기·글 수정 API 추가
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 1m4s
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 1m4s
- GET /api/media-posts/files/..?dl=1 : attachment로 응답 (원래 파일명 유지, 이어받기 지원)
- 상세 응답 파일에 size(바이트) 추가
- PUT /api/media-posts/{id} : 제목·분류 수정 (본인 글만, 제목 필수, 분류 비우면 미분류)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4521cab2a5
commit
4d8d1cfff6
3 files changed
+80
-7
No files matched your search
@@ -72,10 +72,12 @@ public class MediaPostController {
|
|||||||
|
|
||||||
public record CreateRequest(String url, String title, String category) {}
|
public record CreateRequest(String url, String title, String category) {}
|
||||||
|
|
||||||
|
public record UpdateRequest(String title, String category) {}
|
||||||
|
|
||||||
// result: VIDEO / IMAGE / FAIL = 끝남, PROGRESS = 받는 중 (progress %, speed)
|
// result: VIDEO / IMAGE / FAIL = 끝남, PROGRESS = 받는 중 (progress %, speed)
|
||||||
public record CallbackRequest(String folder, String result, Integer progress, String speed) {}
|
public record CallbackRequest(String folder, String result, Integer progress, String speed) {}
|
||||||
|
|
||||||
public record FileItem(String name, String type, String url) {}
|
public record FileItem(String name, String type, long size, String url) {} // size: 바이트
|
||||||
|
|
||||||
public record MediaPostResponse(Long id, String title, String sourceUrl, String category, MediaPost.Status status,
|
public record MediaPostResponse(Long id, String title, String sourceUrl, String category, MediaPost.Status status,
|
||||||
Integer progress, String speed, String author, LocalDateTime createdAt,
|
Integer progress, String speed, String author, LocalDateTime createdAt,
|
||||||
@@ -92,8 +94,7 @@ public class MediaPostController {
|
|||||||
}
|
}
|
||||||
String title = request.title() == null || request.title().isBlank() ? url : request.title().trim();
|
String title = request.title() == null || request.title().isBlank() ? url : request.title().trim();
|
||||||
if (title.length() > 500) title = title.substring(0, 500);
|
if (title.length() > 500) title = title.substring(0, 500);
|
||||||
String category = request.category() == null || request.category().isBlank() ? null : request.category().trim();
|
String category = normalizeCategory(request.category());
|
||||||
if (category != null && category.length() > 50) category = category.substring(0, 50);
|
|
||||||
|
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
MediaPost post = repository.save(MediaPost.builder()
|
MediaPost post = repository.save(MediaPost.builder()
|
||||||
@@ -173,6 +174,31 @@ public class MediaPostController {
|
|||||||
.orElse(ResponseEntity.notFound().build());
|
.orElse(ResponseEntity.notFound().build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 수정: 제목·분류만 (링크를 바꾸려면 다시 받아야 하므로 삭제 후 새로 등록). 본인 글만, 이유는 delete와 같이 400
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ResponseEntity<?> update(@PathVariable Long id, @RequestBody UpdateRequest request, Principal principal) {
|
||||||
|
MediaPost post = repository.findById(id).orElse(null);
|
||||||
|
if (post == null) return ResponseEntity.notFound().build();
|
||||||
|
if (!post.getAuthor().equals(principal.getName())) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("error", "본인이 등록한 글만 수정할 수 있습니다"));
|
||||||
|
}
|
||||||
|
if (request.title() == null || request.title().isBlank()) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("error", "제목을 입력하세요"));
|
||||||
|
}
|
||||||
|
String title = request.title().trim();
|
||||||
|
post.setTitle(title.length() > 500 ? title.substring(0, 500) : title);
|
||||||
|
post.setCategory(normalizeCategory(request.category()));
|
||||||
|
repository.save(post);
|
||||||
|
return ResponseEntity.ok(toResponse(post, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 분류: 앞뒤 공백 제거, 비우면 미분류(null), 최대 50자
|
||||||
|
private static String normalizeCategory(String category) {
|
||||||
|
if (category == null || category.isBlank()) return null;
|
||||||
|
String c = category.trim();
|
||||||
|
return c.length() > 50 ? c.substring(0, 50) : c;
|
||||||
|
}
|
||||||
|
|
||||||
// 삭제: 글 + 폴더(파일) 함께. 본인 글만
|
// 삭제: 글 + 폴더(파일) 함께. 본인 글만
|
||||||
// (403은 프론트가 "로그인 만료"로 처리해 로그아웃되므로 400 + 이유로 응답)
|
// (403은 프론트가 "로그인 만료"로 처리해 로그아웃되므로 400 + 이유로 응답)
|
||||||
// ponytail: 받는 중에 지우면 봇이 폴더를 다시 만들어 파일이 남을 수 있음. 문제 되면 DOWNLOADING 중 삭제 막기
|
// ponytail: 받는 중에 지우면 봇이 폴더를 다시 만들어 파일이 남을 수 있음. 문제 되면 DOWNLOADING 중 삭제 막기
|
||||||
@@ -193,9 +219,11 @@ public class MediaPostController {
|
|||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 파일 전송 (<video>/<img> src). 로그인 헤더 대신 ?t= 토큰 검사. Range 요청(영상 탐색) 자동 지원
|
// 파일 전송 (<video>/<img> src). 로그인 헤더 대신 ?t= 토큰 검사. Range 요청(영상 탐색·이어받기) 자동 지원
|
||||||
|
// dl=1 이면 브라우저가 재생하지 않고 파일로 저장 (attachment)
|
||||||
@GetMapping("/files/{folder}/{index}")
|
@GetMapping("/files/{folder}/{index}")
|
||||||
public ResponseEntity<Resource> file(@PathVariable String folder, @PathVariable int index, @RequestParam String t) {
|
public ResponseEntity<Resource> file(@PathVariable String folder, @PathVariable int index, @RequestParam String t,
|
||||||
|
@RequestParam(defaultValue = "false") boolean dl) {
|
||||||
if (!jwtTokenProvider.validateMediaToken(t, folder)) {
|
if (!jwtTokenProvider.validateMediaToken(t, folder)) {
|
||||||
return ResponseEntity.status(403).build();
|
return ResponseEntity.status(403).build();
|
||||||
}
|
}
|
||||||
@@ -207,7 +235,8 @@ public class MediaPostController {
|
|||||||
String name = file.getFileName().toString();
|
String name = file.getFileName().toString();
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaTypeFactory.getMediaType(name).orElse(MediaType.APPLICATION_OCTET_STREAM))
|
.contentType(MediaTypeFactory.getMediaType(name).orElse(MediaType.APPLICATION_OCTET_STREAM))
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline().filename(name, StandardCharsets.UTF_8).build().toString())
|
.header(HttpHeaders.CONTENT_DISPOSITION, (dl ? ContentDisposition.attachment() : ContentDisposition.inline())
|
||||||
|
.filename(name, StandardCharsets.UTF_8).build().toString())
|
||||||
.body(new FileSystemResource(file));
|
.body(new FileSystemResource(file));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,7 +285,13 @@ public class MediaPostController {
|
|||||||
for (int i = 0; i < files.size(); i++) {
|
for (int i = 0; i < files.size(); i++) {
|
||||||
String name = files.get(i).getFileName().toString();
|
String name = files.get(i).getFileName().toString();
|
||||||
String type = MediaTypeFactory.getMediaType(name).map(MediaType::getType).orElse("file"); // video / image / ...
|
String type = MediaTypeFactory.getMediaType(name).map(MediaType::getType).orElse("file"); // video / image / ...
|
||||||
items.add(new FileItem(name, type, "/api/media-posts/files/" + post.getFolder() + "/" + i + "?t=" + token));
|
long size;
|
||||||
|
try {
|
||||||
|
size = Files.size(files.get(i));
|
||||||
|
} catch (IOException e) {
|
||||||
|
size = -1; // 그 사이 지워졌으면 크기만 모름
|
||||||
|
}
|
||||||
|
items.add(new FileItem(name, type, size, "/api/media-posts/files/" + post.getFolder() + "/" + i + "?t=" + token));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getCategory(),
|
return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getCategory(),
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ public class MediaPost {
|
|||||||
@Column(name = "created_at", nullable = false)
|
@Column(name = "created_at", nullable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@Setter
|
||||||
@Column(length = 50)
|
@Column(length = 50)
|
||||||
private String category; // 자료실 분류. null = 미분류. 목록은 글들에서 자동으로 모음
|
private String category; // 자료실 분류. null = 미분류. 목록은 글들에서 자동으로 모음
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import static org.mockito.Mockito.when;
|
|||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||||
|
|
||||||
// DB 없이 다운로드 게시판의 보안 경계만 검증: 로그인/미디어 토큰 분리, 파일 전송, 콜백 인증
|
// DB 없이 다운로드 게시판의 보안 경계만 검증: 로그인/미디어 토큰 분리, 파일 전송, 콜백 인증
|
||||||
@@ -83,6 +84,7 @@ class MediaPostControllerTest {
|
|||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(jsonPath("$.files.length()").value(1))
|
.andExpect(jsonPath("$.files.length()").value(1))
|
||||||
.andExpect(jsonPath("$.files[0].type").value("video"))
|
.andExpect(jsonPath("$.files[0].type").value("video"))
|
||||||
|
.andExpect(jsonPath("$.files[0].size").value(10))
|
||||||
.andExpect(jsonPath("$.files[0].url").value(org.hamcrest.Matchers.startsWith("/api/media-posts/files/" + FOLDER + "/0?t=")));
|
.andExpect(jsonPath("$.files[0].url").value(org.hamcrest.Matchers.startsWith("/api/media-posts/files/" + FOLDER + "/0?t=")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,6 +99,14 @@ class MediaPostControllerTest {
|
|||||||
.andExpect(status().isPartialContent())
|
.andExpect(status().isPartialContent())
|
||||||
.andExpect(content().string("234"))
|
.andExpect(content().string("234"))
|
||||||
.andExpect(content().contentType("video/mp4"));
|
.andExpect(content().contentType("video/mp4"));
|
||||||
|
// 기본은 재생(inline), dl=1 이면 저장(attachment) + 한글 파일명 유지(RFC 5987 filename*)
|
||||||
|
mvc.perform(get("/api/media-posts/files/" + FOLDER + "/0").param("t", t))
|
||||||
|
.andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("inline")));
|
||||||
|
mvc.perform(get("/api/media-posts/files/" + FOLDER + "/0").param("t", t).param("dl", "1"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.allOf(
|
||||||
|
org.hamcrest.Matchers.startsWith("attachment"),
|
||||||
|
org.hamcrest.Matchers.containsString("filename*=UTF-8''%EC%98%81%EC%83%81"))));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -194,4 +204,31 @@ class MediaPostControllerTest {
|
|||||||
mvc.perform(get("/api/media-posts").header("Authorization", auth).param("from", "11/01/2026"))
|
mvc.perform(get("/api/media-posts").header("Authorization", auth).param("from", "11/01/2026"))
|
||||||
.andExpect(status().isBadRequest());
|
.andExpect(status().isBadRequest());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 수정은_본인_글만_제목_필수_분류는_비우면_미분류() throws Exception {
|
||||||
|
MediaPost p = samplePost(); // FOLDER, author=admin
|
||||||
|
when(repository.findById(1L)).thenReturn(Optional.of(p));
|
||||||
|
String admin = "Bearer " + jwt.createToken("admin");
|
||||||
|
|
||||||
|
mvc.perform(put("/api/media-posts/1").header("Authorization", "Bearer " + jwt.createToken("someone"))
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{\"title\":\"남의 수정\",\"category\":\"x\"}"))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
mvc.perform(put("/api/media-posts/1").header("Authorization", admin)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{\"title\":\" \",\"category\":\"x\"}"))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals("https://youtu.be/x", p.getTitle());
|
||||||
|
|
||||||
|
mvc.perform(put("/api/media-posts/1").header("Authorization", admin)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{\"title\":\" 새 제목 \",\"category\":\" 주짓수 \"}"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.title").value("새 제목"))
|
||||||
|
.andExpect(jsonPath("$.category").value("주짓수"))
|
||||||
|
.andExpect(jsonPath("$.files.length()").value(1)); // 수정 후 화면을 바로 다시 그릴 수 있게 파일 포함
|
||||||
|
|
||||||
|
mvc.perform(put("/api/media-posts/1").header("Authorization", admin)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{\"title\":\"새 제목\",\"category\":\"\"}"))
|
||||||
|
.andExpect(status().isOk());
|
||||||
|
org.junit.jupiter.api.Assertions.assertNull(p.getCategory());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user