feat : 자료실 카테고리·검색·다운로드 진행률 추가
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 55s

- media_posts: category, progress, speed 컬럼 (ddl-auto로 자동 추가)
- GET /api/media-posts: category(""=미분류), q(제목), from/to(등록일) 조건 검색
- GET /api/media-posts/categories: 글에 쓰인 분류 목록
- 콜백 result=PROGRESS 로 진행률 갱신 (받는 중일 때만)
- 폴더 이름: yyyyMMdd_무작위12자리 (File Station 이름순 = 날짜순)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-27 17:33:50 +09:00
1 parent f98cf0912d
commit 4521cab2a5
4 files changed
+128 -18

No files matched your search

@@ -8,6 +8,9 @@ import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ContentDisposition; import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -18,6 +21,7 @@ import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException; import org.springframework.web.client.RestClientResponseException;
import jakarta.persistence.criteria.Predicate;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
@@ -25,7 +29,9 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.Principal; import java.security.Principal;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
@@ -64,14 +70,18 @@ public class MediaPostController {
this.callbackUrl = callbackUrl; this.callbackUrl = callbackUrl;
} }
public record CreateRequest(String url, String title) {} public record CreateRequest(String url, String title, String category) {}
public record CallbackRequest(String folder, String result) {} // result: VIDEO / IMAGE / FAIL = 끝남, PROGRESS = 받는 중 (progress %, 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, String url) {}
public record MediaPostResponse(Long id, String title, String sourceUrl, MediaPost.Status status, public record MediaPostResponse(Long id, String title, String sourceUrl, String category, MediaPost.Status status,
String author, LocalDateTime createdAt, List<FileItem> files) {} Integer progress, String speed, String author, LocalDateTime createdAt,
List<FileItem> files) {}
private static final DateTimeFormatter FOLDER_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
// 등록: 글을 만들고 봇에 다운로드 요청. 봇이 거절하면 글도 지움 // 등록: 글을 만들고 봇에 다운로드 요청. 봇이 거절하면 글도 지움
@PostMapping @PostMapping
@@ -82,14 +92,19 @@ 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();
if (category != null && category.length() > 50) category = category.substring(0, 50);
LocalDateTime now = LocalDateTime.now();
MediaPost post = repository.save(MediaPost.builder() MediaPost post = repository.save(MediaPost.builder()
.title(title) .title(title)
.sourceUrl(url) .sourceUrl(url)
.folder(UUID.randomUUID().toString().replace("-", "")) .category(category)
// 날짜_무작위: File Station에서 이름순 정렬 = 날짜순
.folder(now.format(FOLDER_DATE) + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12))
.status(MediaPost.Status.DOWNLOADING) .status(MediaPost.Status.DOWNLOADING)
.author(principal.getName()) .author(principal.getName())
.createdAt(LocalDateTime.now()) .createdAt(now)
.build()); .build());
try { try {
@@ -113,16 +128,43 @@ public class MediaPostController {
return ResponseEntity.ok(toResponse(post, false)); return ResponseEntity.ok(toResponse(post, false));
} }
// 목록 (무한 스크롤: before = 마지막으로 받은 글 id) // 목록 + 검색. 조건은 준 것만 적용
// category: 없으면 전체, 빈 문자열("")이면 미분류
// q: 제목에 포함 (대소문자 무시), from/to: 등록일 범위 (yyyy-MM-dd, to 당일 포함)
// before: 무한 스크롤 커서 (이 id보다 오래된 글)
@GetMapping @GetMapping
public Page<MediaPostResponse> list( public Page<MediaPostResponse> list(
@RequestParam(required = false) String category,
@RequestParam(required = false) String q,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to,
@RequestParam(required = false) Long before, @RequestParam(required = false) Long before,
@RequestParam(defaultValue = "20") int size) { @RequestParam(defaultValue = "20") int size) {
return repository Specification<MediaPost> spec = (root, query, cb) -> {
.findByIdLessThanOrderByIdDesc(before == null ? Long.MAX_VALUE : before, PageRequest.of(0, Math.min(size, 100))) List<Predicate> where = new ArrayList<>();
if (category != null) {
where.add(category.isEmpty() ? cb.isNull(root.get("category")) : cb.equal(root.get("category"), category));
}
if (q != null && !q.isBlank()) {
// LIKE 특수문자(%, _)는 글자 그대로 찾도록 이스케이프
String pattern = "%" + q.trim().toLowerCase().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%";
where.add(cb.like(cb.lower(root.get("title")), pattern, '\\'));
}
if (from != null) where.add(cb.greaterThanOrEqualTo(root.get("createdAt"), from.atStartOfDay()));
if (to != null) where.add(cb.lessThan(root.get("createdAt"), to.plusDays(1).atStartOfDay()));
if (before != null) where.add(cb.lessThan(root.get("id"), before));
return cb.and(where.toArray(Predicate[]::new));
};
return repository.findAll(spec, PageRequest.of(0, Math.min(size, 100), Sort.by(Sort.Direction.DESC, "id")))
.map(post -> toResponse(post, false)); .map(post -> toResponse(post, false));
} }
// 카테고리 목록 (글에 쓰인 분류를 이름순으로). 탭·등록 칸 자동완성용
@GetMapping("/categories")
public List<String> categories() {
return repository.findCategories();
}
// 상세: 폴더의 파일 목록과 1시간짜리 파일 주소 포함 // 상세: 폴더의 파일 목록과 1시간짜리 파일 주소 포함
@GetMapping("/{id}") @GetMapping("/{id}")
public ResponseEntity<MediaPostResponse> detail(@PathVariable Long id) { public ResponseEntity<MediaPostResponse> detail(@PathVariable Long id) {
@@ -180,6 +222,18 @@ public class MediaPostController {
MediaPost post = repository.findByFolder(request.folder()).orElse(null); MediaPost post = repository.findByFolder(request.folder()).orElse(null);
if (post == null) return ResponseEntity.notFound().build(); if (post == null) return ResponseEntity.notFound().build();
// 받는 중 진행률: 상태는 그대로 두고 %·속도만 갱신 (이미 끝난 글이면 무시: 늦게 도착한 진행률 알림)
if ("PROGRESS".equals(request.result())) {
if (post.getStatus() == MediaPost.Status.DOWNLOADING && request.progress() != null) {
post.setProgress(Math.max(0, Math.min(100, request.progress())));
post.setSpeed(request.speed() == null ? null : request.speed().substring(0, Math.min(30, request.speed().length())));
repository.save(post);
}
return ResponseEntity.noContent().build();
}
post.setProgress(null);
post.setSpeed(null);
List<Path> files = listFiles(post.getFolder()); List<Path> files = listFiles(post.getFolder());
boolean ok = !"FAIL".equals(request.result()) && !files.isEmpty(); boolean ok = !"FAIL".equals(request.result()) && !files.isEmpty();
post.setStatus(ok ? MediaPost.Status.DONE : MediaPost.Status.FAILED); post.setStatus(ok ? MediaPost.Status.DONE : MediaPost.Status.FAILED);
@@ -205,8 +259,8 @@ public class MediaPostController {
items.add(new FileItem(name, type, "/api/media-posts/files/" + post.getFolder() + "/" + i + "?t=" + token)); items.add(new FileItem(name, type, "/api/media-posts/files/" + post.getFolder() + "/" + i + "?t=" + token));
} }
} }
return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getStatus(), return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getCategory(),
post.getAuthor(), post.getCreatedAt(), items); post.getStatus(), post.getProgress(), post.getSpeed(), post.getAuthor(), post.getCreatedAt(), items);
} }
// 다 받은 파일만 (yt-dlp 작업 중 파일 .part/.ytdl 제외), 이름순 → 순번이 파일 주소가 됨 // 다 받은 파일만 (yt-dlp 작업 중 파일 .part/.ytdl 제외), 이름순 → 순번이 파일 주소가 됨
@@ -43,4 +43,14 @@ public class MediaPost {
@Column(name = "created_at", nullable = false) @Column(name = "created_at", nullable = false)
private LocalDateTime createdAt; private LocalDateTime createdAt;
@Column(length = 50)
private String category; // 자료실 분류. null = 미분류. 목록은 글들에서 자동으로 모음
@Setter
private Integer progress; // 다운로드 진행률(%). 받는 중일 때만 값이 있음
@Setter
@Column(length = 30)
private String speed; // 다운로드 속도 (yt-dlp 표기 그대로, 예: 3.20MiB/s)
} }
@@ -1,15 +1,17 @@
package company.specialsource.repository; package company.specialsource.repository;
import company.specialsource.entity.MediaPost; import company.specialsource.entity.MediaPost;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Optional; import java.util.Optional;
public interface MediaPostRepository extends JpaRepository<MediaPost, Long> { // JpaSpecificationExecutor: 검색 조건(분류·제목·날짜)을 있는 것만 골라 조합
// 무한 스크롤 커서: 이 id보다 오래된 글 public interface MediaPostRepository extends JpaRepository<MediaPost, Long>, JpaSpecificationExecutor<MediaPost> {
Page<MediaPost> findByIdLessThanOrderByIdDesc(Long id, Pageable pageable);
Optional<MediaPost> findByFolder(String folder); Optional<MediaPost> findByFolder(String folder);
@Query("select distinct p.category from MediaPost p where p.category is not null order by p.category")
List<String> findCategories();
} }
@@ -123,7 +123,7 @@ class MediaPostControllerTest {
mvc.perform(post("/api/media-posts").header("Authorization", "Bearer " + jwt.createToken("admin")) mvc.perform(post("/api/media-posts").header("Authorization", "Bearer " + jwt.createToken("admin"))
.contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"https://youtu.be/x\"}")) .contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"https://youtu.be/x\"}"))
.andExpect(status().isBadGateway()); .andExpect(status().isBadGateway());
verify(repository).delete(any()); verify(repository).delete(any(MediaPost.class));
} }
@Test @Test
@@ -150,4 +150,48 @@ class MediaPostControllerTest {
org.junit.jupiter.api.Assertions.assertFalse(Files.exists(dir)); org.junit.jupiter.api.Assertions.assertFalse(Files.exists(dir));
verify(repository).delete(p); verify(repository).delete(p);
} }
@Test
void 진행률_콜백은_받는중일때만_반영되고_끝나면_지워진다() throws Exception {
MediaPost p = samplePost();
when(repository.findByFolder(FOLDER)).thenReturn(Optional.of(p));
String progress = "{\"folder\":\"" + FOLDER + "\",\"result\":\"PROGRESS\",\"progress\":45,\"speed\":\"3.20MiB/s\"}";
mvc.perform(post("/api/media-posts/callback").header("X-Api-Key", KEY).contentType(MediaType.APPLICATION_JSON).content(progress))
.andExpect(status().isNoContent());
org.junit.jupiter.api.Assertions.assertEquals(45, p.getProgress());
org.junit.jupiter.api.Assertions.assertEquals("3.20MiB/s", p.getSpeed());
org.junit.jupiter.api.Assertions.assertEquals(MediaPost.Status.DOWNLOADING, p.getStatus());
mvc.perform(post("/api/media-posts/callback").header("X-Api-Key", KEY).contentType(MediaType.APPLICATION_JSON)
.content("{\"folder\":\"" + FOLDER + "\",\"result\":\"VIDEO\"}"))
.andExpect(status().isNoContent());
org.junit.jupiter.api.Assertions.assertNull(p.getProgress());
org.junit.jupiter.api.Assertions.assertEquals(MediaPost.Status.DONE, p.getStatus());
// 늦게 도착한 진행률 알림은 무시
mvc.perform(post("/api/media-posts/callback").header("X-Api-Key", KEY).contentType(MediaType.APPLICATION_JSON).content(progress))
.andExpect(status().isNoContent());
org.junit.jupiter.api.Assertions.assertNull(p.getProgress());
}
@Test
void 카테고리_목록은_글번호_경로와_안겹친다() throws Exception {
when(repository.findCategories()).thenReturn(java.util.List.of("요리", "주짓수"));
mvc.perform(get("/api/media-posts/categories").header("Authorization", "Bearer " + jwt.createToken("admin")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[1]").value("주짓수"));
}
@Test
void 검색_파라미터를_받고_날짜형식이_틀리면_400() throws Exception {
when(repository.findAll(any(org.springframework.data.jpa.domain.Specification.class), any(org.springframework.data.domain.Pageable.class)))
.thenReturn(org.springframework.data.domain.Page.empty());
String auth = "Bearer " + jwt.createToken("admin");
mvc.perform(get("/api/media-posts").header("Authorization", auth)
.param("category", "").param("q", "50%_off").param("from", "2026-11-01").param("to", "2026-11-30"))
.andExpect(status().isOk());
mvc.perform(get("/api/media-posts").header("Authorization", auth).param("from", "11/01/2026"))
.andExpect(status().isBadRequest());
}
} }