mirror of
https://github.com/headporter81/specialsource-homepage-backend.git
synced 2026-12-06 07:41:09 +09:00
feat : 자료실 카테고리·검색·다운로드 진행률 추가
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 55s
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:
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.data.domain.Page;
|
||||
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.HttpHeaders;
|
||||
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.RestClientResponseException;
|
||||
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
@@ -25,7 +29,9 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.Principal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
@@ -64,14 +70,18 @@ public class MediaPostController {
|
||||
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 MediaPostResponse(Long id, String title, String sourceUrl, MediaPost.Status status,
|
||||
String author, LocalDateTime createdAt, List<FileItem> files) {}
|
||||
public record MediaPostResponse(Long id, String title, String sourceUrl, String category, MediaPost.Status status,
|
||||
Integer progress, String speed, String author, LocalDateTime createdAt,
|
||||
List<FileItem> files) {}
|
||||
|
||||
private static final DateTimeFormatter FOLDER_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
// 등록: 글을 만들고 봇에 다운로드 요청. 봇이 거절하면 글도 지움
|
||||
@PostMapping
|
||||
@@ -82,14 +92,19 @@ public class MediaPostController {
|
||||
}
|
||||
String title = request.title() == null || request.title().isBlank() ? url : request.title().trim();
|
||||
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()
|
||||
.title(title)
|
||||
.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)
|
||||
.author(principal.getName())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.createdAt(now)
|
||||
.build());
|
||||
|
||||
try {
|
||||
@@ -113,16 +128,43 @@ public class MediaPostController {
|
||||
return ResponseEntity.ok(toResponse(post, false));
|
||||
}
|
||||
|
||||
// 목록 (무한 스크롤: before = 마지막으로 받은 글 id)
|
||||
// 목록 + 검색. 조건은 준 것만 적용
|
||||
// category: 없으면 전체, 빈 문자열("")이면 미분류
|
||||
// q: 제목에 포함 (대소문자 무시), from/to: 등록일 범위 (yyyy-MM-dd, to 당일 포함)
|
||||
// before: 무한 스크롤 커서 (이 id보다 오래된 글)
|
||||
@GetMapping
|
||||
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(defaultValue = "20") int size) {
|
||||
return repository
|
||||
.findByIdLessThanOrderByIdDesc(before == null ? Long.MAX_VALUE : before, PageRequest.of(0, Math.min(size, 100)))
|
||||
Specification<MediaPost> spec = (root, query, cb) -> {
|
||||
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));
|
||||
}
|
||||
|
||||
// 카테고리 목록 (글에 쓰인 분류를 이름순으로). 탭·등록 칸 자동완성용
|
||||
@GetMapping("/categories")
|
||||
public List<String> categories() {
|
||||
return repository.findCategories();
|
||||
}
|
||||
|
||||
// 상세: 폴더의 파일 목록과 1시간짜리 파일 주소 포함
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<MediaPostResponse> detail(@PathVariable Long id) {
|
||||
@@ -180,6 +222,18 @@ public class MediaPostController {
|
||||
MediaPost post = repository.findByFolder(request.folder()).orElse(null);
|
||||
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());
|
||||
boolean ok = !"FAIL".equals(request.result()) && !files.isEmpty();
|
||||
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));
|
||||
}
|
||||
}
|
||||
return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getStatus(),
|
||||
post.getAuthor(), post.getCreatedAt(), items);
|
||||
return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getCategory(),
|
||||
post.getStatus(), post.getProgress(), post.getSpeed(), post.getAuthor(), post.getCreatedAt(), items);
|
||||
}
|
||||
|
||||
// 다 받은 파일만 (yt-dlp 작업 중 파일 .part/.ytdl 제외), 이름순 → 순번이 파일 주소가 됨
|
||||
|
||||
Reference in new issue
Block a user