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
@@ -53,16 +53,48 @@ public class JwtTokenProvider {
|
||||
}
|
||||
|
||||
// 3. 토큰이 유효한지(만료되진 않았는지, 위조되진 않았는지) 검증하는 메서드
|
||||
// 로그인 토큰만 통과: aud가 붙은 미디어 토큰은 로그인 용도로 쓸 수 없게 거부
|
||||
public boolean validateToken(String token) {
|
||||
try {
|
||||
Jwts.parser()
|
||||
Claims claims = Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token);
|
||||
return true; // 아무 에러도 안 나면 정상적인 토큰!
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
return claims.getAudience() == null || claims.getAudience().isEmpty(); // 아무 에러도 안 나면 정상적인 토큰!
|
||||
} catch (JwtException | IllegalArgumentException e) {
|
||||
// 토큰이 만료되었거나, 위조되었거나, 형식이 잘못되었을 때 여기로 빠집니다.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final String MEDIA_AUDIENCE = "media";
|
||||
private static final long MEDIA_TOKEN_MS = 60 * 60 * 1000L;
|
||||
|
||||
// 4. 미디어 파일 주소(?t=)용 토큰: <video>/<img>는 Authorization 헤더를 못 보내서 주소에 붙임
|
||||
// 폴더 하나에만, 1시간만 유효
|
||||
public String createMediaToken(String folder) {
|
||||
Date now = new Date();
|
||||
return Jwts.builder()
|
||||
.subject(folder)
|
||||
.audience().add(MEDIA_AUDIENCE).and()
|
||||
.issuedAt(now)
|
||||
.expiration(new Date(now.getTime() + MEDIA_TOKEN_MS))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public boolean validateMediaToken(String token, String folder) {
|
||||
try {
|
||||
Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.requireAudience(MEDIA_AUDIENCE)
|
||||
.requireSubject(folder)
|
||||
.build()
|
||||
.parseSignedClaims(token);
|
||||
return true;
|
||||
} catch (JwtException | IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
// 로그인 API, 파일 동기화 업로드 API, 메인 화면 IT 헤드라인은 인증 없이 누구나 접근 가능하도록 허용
|
||||
.requestMatchers("/api/login", "/api/sync/upload", "/api/headlines").permitAll()
|
||||
// 미디어 파일은 주소의 ?t= 토큰으로, 봇 콜백은 X-Api-Key로 컨트롤러에서 직접 검사
|
||||
.requestMatchers("/api/media-posts/files/**", "/api/media-posts/callback").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
@@ -15,6 +15,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(visitorInterceptor)
|
||||
// .addPathPatterns("/api/**") // 🟢 모든 API 주소로 들어오는 길목을 차단하여 감시
|
||||
.excludePathPatterns("/api/analytics/**", "/static/**", "/favicon.ico"); // 통계 조회 API 자체는 중복 카운팅 차단
|
||||
.excludePathPatterns("/api/analytics/**", "/api/media-posts/files/**", "/static/**", "/favicon.ico"); // 통계 조회 API 자체는 중복 카운팅 차단
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package company.specialsource.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 링크로 다운로드한 영상/이미지 게시글. 직접 등록하는 글이라 자동 삭제하지 않는다.
|
||||
* 파일 목록은 DB에 두지 않고, 글마다 하나인 폴더(media.dir/folder)를 조회할 때 읽는다.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "media_posts")
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class MediaPost {
|
||||
|
||||
public enum Status { DOWNLOADING, DONE, FAILED }
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Setter
|
||||
@Column(nullable = false, length = 500)
|
||||
private String title;
|
||||
|
||||
@Column(name = "source_url", nullable = false, length = 1000)
|
||||
private String sourceUrl;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 64)
|
||||
private String folder; // 추측할 수 없는 무작위 값 (UUID)
|
||||
|
||||
@Setter
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private Status status;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String author;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package company.specialsource.repository;
|
||||
|
||||
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 java.util.Optional;
|
||||
|
||||
public interface MediaPostRepository extends JpaRepository<MediaPost, Long> {
|
||||
// 무한 스크롤 커서: 이 id보다 오래된 글
|
||||
Page<MediaPost> findByIdLessThanOrderByIdDesc(Long id, Pageable pageable);
|
||||
|
||||
Optional<MediaPost> findByFolder(String folder);
|
||||
}
|
||||
Reference in new issue
Block a user