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// 에 저장하고, * 완료되면 /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 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 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 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 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 spec = (root, query, cb) -> { List 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 categories() { return repository.findCategories(); } // 상세: 폴더의 파일 목록과 1시간짜리 파일 주소 포함 @GetMapping("/{id}") public ResponseEntity 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 walk = Files.walk(dir)) { for (Path p : walk.sorted(Comparator.reverseOrder()).toList()) Files.delete(p); // 안쪽 파일부터 } } repository.delete(post); return ResponseEntity.noContent().build(); } // 파일 전송 (