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 55s
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 55s
- media_posts 테이블: 링크 등록 → 다운로드 봇 요청 → 봇 콜백으로 완료/실패 반영 (자동 삭제 없음)
- POST/GET /api/media-posts, GET /api/media-posts/{id} (로그인 필요)
- GET /api/media-posts/files/{folder}/{index}?t= : 폴더 한정 1시간 미디어 토큰으로 파일 전송 (Range 지원)
- POST /api/media-posts/callback : X-Api-Key(DOWNLOADER_API_KEY) 검증
- 미디어 토큰(aud=media)은 로그인 토큰으로 쓸 수 없게 분리
- 배포: /volume2/data/media 마운트, 봇 주소·키·콜백 주소 환경변수
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
27d89f35a2
commit
73bcd872aa
9 files changed
+453
-5
No files matched your search
@@ -0,0 +1,208 @@
|
||||
package company.specialsource.controller;
|
||||
|
||||
import company.specialsource.config.JwtTokenProvider;
|
||||
import company.specialsource.entity.MediaPost;
|
||||
import company.specialsource.repository.MediaPostRepository;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
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.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.MediaTypeFactory;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestClientResponseException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.Principal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* 다운로드 게시판: 링크를 등록하면 다운로드 봇이 받아서 media.dir/<folder>/ 에 저장하고,
|
||||
* 완료되면 /callback 으로 알려준다. 파일은 ?t= 미디어 토큰으로만 열람 가능.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/media-posts")
|
||||
public class MediaPostController {
|
||||
|
||||
private final MediaPostRepository repository;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final Path mediaDir;
|
||||
private final String downloaderUrl;
|
||||
private final String apiKey;
|
||||
private final String callbackUrl;
|
||||
private final RestClient restClient = RestClient.create();
|
||||
|
||||
public MediaPostController(
|
||||
MediaPostRepository repository,
|
||||
JwtTokenProvider jwtTokenProvider,
|
||||
@Value("${media.dir}") String mediaDir,
|
||||
@Value("${media.downloader-url}") String downloaderUrl,
|
||||
@Value("${media.downloader-api-key}") String apiKey,
|
||||
@Value("${media.callback-url}") String callbackUrl) {
|
||||
this.repository = repository;
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
this.mediaDir = Paths.get(mediaDir).toAbsolutePath().normalize();
|
||||
this.downloaderUrl = downloaderUrl;
|
||||
this.apiKey = apiKey;
|
||||
this.callbackUrl = callbackUrl;
|
||||
}
|
||||
|
||||
public record CreateRequest(String url, String title) {}
|
||||
|
||||
public record CallbackRequest(String folder, String result) {}
|
||||
|
||||
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) {}
|
||||
|
||||
// 등록: 글을 만들고 봇에 다운로드 요청. 봇이 거절하면 글도 지움
|
||||
@PostMapping
|
||||
public ResponseEntity<?> create(@RequestBody CreateRequest request, Principal principal) {
|
||||
String url = request.url() == null ? "" : request.url().trim();
|
||||
if (!url.matches("https?://\\S+") || url.length() > 1000) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "올바른 링크가 아닙니다"));
|
||||
}
|
||||
String title = request.title() == null || request.title().isBlank() ? url : request.title().trim();
|
||||
if (title.length() > 500) title = title.substring(0, 500);
|
||||
|
||||
MediaPost post = repository.save(MediaPost.builder()
|
||||
.title(title)
|
||||
.sourceUrl(url)
|
||||
.folder(UUID.randomUUID().toString().replace("-", ""))
|
||||
.status(MediaPost.Status.DOWNLOADING)
|
||||
.author(principal.getName())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.build());
|
||||
|
||||
try {
|
||||
restClient.post()
|
||||
.uri(downloaderUrl + "/download")
|
||||
.header("X-Api-Key", apiKey)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Map.of("url", url, "folder", post.getFolder(), "callbackUrl", callbackUrl))
|
||||
.retrieve()
|
||||
.toBodilessEntity();
|
||||
} catch (RestClientResponseException e) {
|
||||
repository.delete(post);
|
||||
// 봇의 {"error": "..."} 를 그대로 전달 (예: 지원하지 않는 링크)
|
||||
return ResponseEntity.status(e.getStatusCode().is4xxClientError() ? 400 : 502)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(e.getResponseBodyAsString());
|
||||
} catch (RestClientException e) {
|
||||
repository.delete(post);
|
||||
return ResponseEntity.status(502).body(Map.of("error", "다운로드 봇에 연결할 수 없습니다"));
|
||||
}
|
||||
return ResponseEntity.ok(toResponse(post, false));
|
||||
}
|
||||
|
||||
// 목록 (무한 스크롤: before = 마지막으로 받은 글 id)
|
||||
@GetMapping
|
||||
public Page<MediaPostResponse> list(
|
||||
@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)))
|
||||
.map(post -> toResponse(post, false));
|
||||
}
|
||||
|
||||
// 상세: 폴더의 파일 목록과 1시간짜리 파일 주소 포함
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<MediaPostResponse> detail(@PathVariable Long id) {
|
||||
return repository.findById(id)
|
||||
.map(post -> ResponseEntity.ok(toResponse(post, true)))
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
// 파일 전송 (<video>/<img> src). 로그인 헤더 대신 ?t= 토큰 검사. Range 요청(영상 탐색) 자동 지원
|
||||
@GetMapping("/files/{folder}/{index}")
|
||||
public ResponseEntity<Resource> file(@PathVariable String folder, @PathVariable int index, @RequestParam String t) {
|
||||
if (!jwtTokenProvider.validateMediaToken(t, folder)) {
|
||||
return ResponseEntity.status(403).build();
|
||||
}
|
||||
List<Path> files = listFiles(folder);
|
||||
if (index < 0 || index >= files.size()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Path file = files.get(index);
|
||||
String name = file.getFileName().toString();
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaTypeFactory.getMediaType(name).orElse(MediaType.APPLICATION_OCTET_STREAM))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline().filename(name, StandardCharsets.UTF_8).build().toString())
|
||||
.body(new FileSystemResource(file));
|
||||
}
|
||||
|
||||
// 봇이 다운로드를 끝내면 호출 (X-Api-Key = DOWNLOADER_API_KEY)
|
||||
@PostMapping("/callback")
|
||||
public ResponseEntity<Void> callback(@RequestHeader(value = "X-Api-Key", required = false) String key,
|
||||
@RequestBody CallbackRequest request) {
|
||||
if (apiKey.isEmpty() || key == null
|
||||
|| !MessageDigest.isEqual(key.getBytes(StandardCharsets.UTF_8), apiKey.getBytes(StandardCharsets.UTF_8))) {
|
||||
return ResponseEntity.status(401).build();
|
||||
}
|
||||
MediaPost post = repository.findByFolder(request.folder()).orElse(null);
|
||||
if (post == null) return ResponseEntity.notFound().build();
|
||||
|
||||
List<Path> files = listFiles(post.getFolder());
|
||||
boolean ok = !"FAIL".equals(request.result()) && !files.isEmpty();
|
||||
post.setStatus(ok ? MediaPost.Status.DONE : MediaPost.Status.FAILED);
|
||||
// 제목을 안 적었으면(= 링크) 첫 파일 이름으로. 봇 파일명 "제목_영상id_Video1.mp4" 에서 뒤쪽 제거
|
||||
// ponytail: 영상 id에 '_'가 있으면 일부가 제목에 남음. 거슬리면 봇이 콜백에 제목을 실어 보내게
|
||||
if (ok && post.getTitle().equals(post.getSourceUrl())) {
|
||||
String name = files.get(0).getFileName().toString().replaceFirst("\\.[^.]+$", "");
|
||||
post.setTitle(name.replaceFirst("_[^_]+_(Video|Image)\\d+$", ""));
|
||||
}
|
||||
repository.save(post);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private MediaPostResponse toResponse(MediaPost post, boolean withFiles) {
|
||||
List<FileItem> items = List.of();
|
||||
if (withFiles) {
|
||||
String token = jwtTokenProvider.createMediaToken(post.getFolder());
|
||||
List<Path> files = listFiles(post.getFolder());
|
||||
items = new ArrayList<>();
|
||||
for (int i = 0; i < files.size(); i++) {
|
||||
String name = files.get(i).getFileName().toString();
|
||||
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));
|
||||
}
|
||||
}
|
||||
return new MediaPostResponse(post.getId(), post.getTitle(), post.getSourceUrl(), post.getStatus(),
|
||||
post.getAuthor(), post.getCreatedAt(), items);
|
||||
}
|
||||
|
||||
// 다 받은 파일만 (yt-dlp 작업 중 파일 .part/.ytdl 제외), 이름순 → 순번이 파일 주소가 됨
|
||||
private List<Path> listFiles(String folder) {
|
||||
Path dir = mediaDir.resolve(folder).normalize();
|
||||
if (!dir.getParent().equals(mediaDir) || !Files.isDirectory(dir)) return List.of();
|
||||
try (Stream<Path> stream = Files.list(dir)) {
|
||||
return stream
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(p -> {
|
||||
String n = p.getFileName().toString();
|
||||
return !n.startsWith(".") && !n.endsWith(".part") && !n.endsWith(".ytdl") && !n.contains(".temp.");
|
||||
})
|
||||
.sorted()
|
||||
.toList();
|
||||
} catch (IOException e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user