mirror of
https://github.com/headporter81/specialsource-homepage-backend.git
synced 2026-12-06 07:41:09 +09:00
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 53s
- POST /api/media-posts/upload: 내 PC 파일을 바로 완료된 글로 등록 (sourceUrl = "") - 제목 미입력 시 설명 첫 줄을 제목으로 쓰는 건 인스타만 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
375 lines
20 KiB
Java
375 lines
20 KiB
Java
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.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;
|
|
import org.springframework.http.MediaTypeFactory;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.web.bind.annotation.*;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
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;
|
|
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;
|
|
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, String category) {}
|
|
|
|
public record UpdateRequest(String title, String category) {}
|
|
|
|
// result: VIDEO / IMAGE / FAIL = 끝남, PROGRESS = 받는 중 (progress %, speed)
|
|
// description: 끝날 때 원본 게시물 설명글 (인스타 본문, 없으면 null)
|
|
public record CallbackRequest(String folder, String result, Integer progress, String speed, String description) {}
|
|
|
|
public record FileItem(String name, String type, long size, String url) {} // size: 바이트
|
|
|
|
public record MediaPostResponse(Long id, String title, String description, 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
|
|
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);
|
|
String category = normalizeCategory(request.category());
|
|
|
|
LocalDateTime now = LocalDateTime.now();
|
|
MediaPost post = repository.save(MediaPost.builder()
|
|
.title(title)
|
|
.sourceUrl(url)
|
|
.category(category)
|
|
// 날짜_무작위: File Station에서 이름순 정렬 = 날짜순
|
|
.folder(now.format(FOLDER_DATE) + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12))
|
|
.status(MediaPost.Status.DOWNLOADING)
|
|
.author(principal.getName())
|
|
.createdAt(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));
|
|
}
|
|
|
|
// 업로드: 내 PC 파일을 바로 글로 등록 (봇 거치지 않음 → 바로 DONE). 원본 링크가 없어서 sourceUrl = ""
|
|
// 파일을 다 저장한 뒤에 글을 만들고, 저장 중 실패하면 폴더를 지움
|
|
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
|
public ResponseEntity<?> upload(@RequestParam("files") List<MultipartFile> files,
|
|
@RequestParam(value = "title", required = false) String title,
|
|
@RequestParam(value = "category", required = false) String category,
|
|
Principal principal) throws IOException {
|
|
files = files.stream().filter(f -> !f.isEmpty()).toList();
|
|
if (files.isEmpty()) return ResponseEntity.badRequest().body(Map.of("error", "파일을 선택하세요"));
|
|
|
|
LocalDateTime now = LocalDateTime.now();
|
|
String folder = now.format(FOLDER_DATE) + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
|
Path dir = mediaDir.resolve(folder);
|
|
Files.createDirectories(dir);
|
|
try {
|
|
for (int i = 0; i < files.size(); i++) {
|
|
// 경로 조각·윈도우 금지 문자 제거. 숨김(.)·빈 이름이면 번호 이름, 같은 이름이 있으면 앞에 번호
|
|
String name = Paths.get(String.valueOf(files.get(i).getOriginalFilename())).getFileName().toString()
|
|
.replaceAll("[\\\\/:*?\"<>|]", "_").trim();
|
|
if (name.isEmpty() || name.startsWith(".") || name.equals("null")) name = "file" + (i + 1) + name;
|
|
if (Files.exists(dir.resolve(name))) name = (i + 1) + "_" + name;
|
|
files.get(i).transferTo(dir.resolve(name));
|
|
}
|
|
} catch (IOException e) {
|
|
try (Stream<Path> walk = Files.walk(dir)) {
|
|
for (Path p : walk.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(p);
|
|
}
|
|
return ResponseEntity.status(500).body(Map.of("error", "파일 저장에 실패했습니다"));
|
|
}
|
|
|
|
// 제목을 비우면 첫 파일 이름 (확장자 빼고)
|
|
String t = title == null || title.isBlank()
|
|
? listFiles(folder).stream().findFirst().map(p -> p.getFileName().toString().replaceFirst("\\.[^.]+$", "")).orElse("업로드")
|
|
: title.trim();
|
|
MediaPost post = repository.save(MediaPost.builder()
|
|
.title(t.length() > 500 ? t.substring(0, 500) : t)
|
|
.sourceUrl("")
|
|
.category(normalizeCategory(category))
|
|
.folder(folder)
|
|
.status(MediaPost.Status.DONE)
|
|
.author(principal.getName())
|
|
.createdAt(now)
|
|
.build());
|
|
return ResponseEntity.ok(toResponse(post, false));
|
|
}
|
|
|
|
// 목록 + 검색. 조건은 준 것만 적용
|
|
// 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) {
|
|
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) {
|
|
return repository.findById(id)
|
|
.map(post -> ResponseEntity.ok(toResponse(post, true)))
|
|
.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 + 이유로 응답)
|
|
// ponytail: 받는 중에 지우면 봇이 폴더를 다시 만들어 파일이 남을 수 있음. 문제 되면 DOWNLOADING 중 삭제 막기
|
|
@DeleteMapping("/{id}")
|
|
public ResponseEntity<?> delete(@PathVariable Long id, Principal principal) throws IOException {
|
|
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", "본인이 등록한 글만 삭제할 수 있습니다"));
|
|
}
|
|
Path dir = mediaDir.resolve(post.getFolder()).normalize();
|
|
if (dir.getParent().equals(mediaDir) && Files.isDirectory(dir)) {
|
|
try (Stream<Path> walk = Files.walk(dir)) {
|
|
for (Path p : walk.sorted(Comparator.reverseOrder()).toList()) Files.delete(p); // 안쪽 파일부터
|
|
}
|
|
}
|
|
repository.delete(post);
|
|
return ResponseEntity.noContent().build();
|
|
}
|
|
|
|
// 파일 전송 (<video>/<img> src). 로그인 헤더 대신 ?t= 토큰 검사. Range 요청(영상 탐색·이어받기) 자동 지원
|
|
// dl=1 이면 브라우저가 재생하지 않고 파일로 저장 (attachment)
|
|
@GetMapping("/files/{folder}/{index}")
|
|
public ResponseEntity<Resource> file(@PathVariable String folder, @PathVariable int index, @RequestParam String t,
|
|
@RequestParam(defaultValue = "false") boolean dl) {
|
|
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, (dl ? ContentDisposition.attachment() : 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();
|
|
|
|
// 받는 중 진행률: 상태는 그대로 두고 %·속도만 갱신 (이미 끝난 글이면 무시: 늦게 도착한 진행률 알림)
|
|
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);
|
|
String description = request.description() == null || request.description().isBlank() ? null : request.description().trim();
|
|
if (ok && description != null) post.setDescription(description);
|
|
// 제목을 안 적었으면(= 링크): 인스타는 설명글 첫 줄(최대 100자, 인스타엔 제목이 따로 없음),
|
|
// 그 밖(유튜브)이나 설명이 없으면 첫 파일 이름. 봇 파일명 "제목_영상id_Video1.mp4" 에서 뒤쪽 제거
|
|
// ponytail: 영상 id에 '_'가 있으면 일부가 제목에 남음. 거슬리면 봇이 콜백에 제목을 실어 보내게
|
|
if (ok && post.getTitle().equals(post.getSourceUrl())) {
|
|
if (description != null && post.getSourceUrl().contains("instagram.com")) {
|
|
String first = description.lines().map(String::strip).filter(l -> !l.isEmpty()).findFirst().orElse(description);
|
|
post.setTitle(first.length() > 100 ? first.substring(0, 100) + "…" : first);
|
|
} else {
|
|
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 / ...
|
|
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.getDescription(), post.getSourceUrl(), post.getCategory(),
|
|
post.getStatus(), post.getProgress(), post.getSpeed(), 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();
|
|
}
|
|
}
|
|
}
|