From 99029064d38f96f35ee230c64aa999ea8085bb9f Mon Sep 17 00:00:00 2001 From: "sungjin.choi" Date: Fri, 27 Nov 2026 17:33:46 +0900 Subject: [PATCH] =?UTF-8?q?feat=20:=20=ED=99=88=ED=8E=98=EC=9D=B4=EC=A7=80?= =?UTF-8?q?=20=EC=9E=90=EB=A3=8C=EC=8B=A4=EC=97=90=20=EB=8B=A4=EC=9A=B4?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EC=A7=84=ED=96=89=EB=A5=A0=20=EC=95=8C?= =?UTF-8?q?=EB=A6=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - yt-dlp --newline 으로 진행률 줄을 읽어 2초에 한 번 콜백 (result=PROGRESS, progress %, speed) Co-Authored-By: Claude Opus 5.5 --- src/main/java/DiscordDownloadBot.java | 44 +++++++++++++++++++++------ 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/src/main/java/DiscordDownloadBot.java b/src/main/java/DiscordDownloadBot.java index ca1094d..51b455d 100644 --- a/src/main/java/DiscordDownloadBot.java +++ b/src/main/java/DiscordDownloadBot.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.BiConsumer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; @@ -49,6 +50,10 @@ public class DiscordDownloadBot extends ListenerAdapter { private enum Result { VIDEO, IMAGE, FAIL } + // yt-dlp 진행률 줄: "[download] 45.3% of ~ 120.00MiB at 3.20MiB/s ETA 00:30" → (45.3, 3.20MiB/s) + // ponytail: 영상+음성을 따로 받으면 0→100%가 두 번 나옴. 거슬리면 "(2/2)" 같은 단계 표시 추가 + static final Pattern PROGRESS_LINE = Pattern.compile("^\\[download\\]\\s+([\\d.]+)%(?:.*?\\bat\\s+(\\S+/s))?"); + private static String env(String key, String def) { String v = System.getenv(key); return (v == null || v.isEmpty()) ? def : v; @@ -132,9 +137,20 @@ public class DiscordDownloadBot extends ListenerAdapter { String saveDir = baseDir + File.separator + folder; new File(saveDir).mkdirs(); executor.submit(() -> { - Result result = download(url, saveDir); + // 진행률은 2초에 한 번만 알림 (yt-dlp는 초당 여러 줄을 출력함) + long[] lastSent = {0}; + BiConsumer progress = callbackUrl.isEmpty() ? null : (percent, speed) -> { + long now = System.currentTimeMillis(); + if (now - lastSent[0] < 2000) return; + lastSent[0] = now; + sendCallback(callbackUrl, DataObject.empty().put("folder", folder).put("result", "PROGRESS") + .put("progress", percent).put("speed", speed == null ? "" : speed)); + }; + Result result = download(url, saveDir, progress); System.out.println("🌐 [HTTP] " + folder + " ← " + url + " : " + result); - if (!callbackUrl.isEmpty()) sendCallback(callbackUrl, folder, result); + if (!callbackUrl.isEmpty()) { + sendCallback(callbackUrl, DataObject.empty().put("folder", folder).put("result", result.name())); + } }); send(ex, 202, DataObject.empty().put("status", "accepted").put("folder", folder)); })); @@ -142,8 +158,9 @@ public class DiscordDownloadBot extends ListenerAdapter { System.out.println("🌐 HTTP 창구 실행: " + HTTP_PORT); } - // 다운로드 결과를 홈페이지 백엔드에 알림. 실패해도 파일은 남아 있으니 로그만 - private static void sendCallback(String callbackUrl, String folder, Result result) { + // 다운로드 진행률·결과를 홈페이지 백엔드에 알림. 실패해도 파일은 남아 있으니 로그만 + private static void sendCallback(String callbackUrl, DataObject body) { + String folder = body.getString("folder", ""); try { HttpURLConnection conn = (HttpURLConnection) new URL(callbackUrl).openConnection(); conn.setRequestMethod("POST"); @@ -152,9 +169,10 @@ public class DiscordDownloadBot extends ListenerAdapter { conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("X-Api-Key", API_KEY); - byte[] json = DataObject.empty().put("folder", folder).put("result", result.name()).toString().getBytes(StandardCharsets.UTF_8); + byte[] json = body.toString().getBytes(StandardCharsets.UTF_8); try (OutputStream os = conn.getOutputStream()) { os.write(json); } - System.out.println("📮 콜백 " + conn.getResponseCode() + " ← " + folder); + int code = conn.getResponseCode(); + if (!"PROGRESS".equals(body.getString("result", ""))) System.out.println("📮 콜백 " + code + " ← " + folder); conn.disconnect(); } catch (Exception e) { System.out.println("⚠️ 콜백 실패: " + folder + " (" + e.getMessage() + ")"); @@ -268,14 +286,15 @@ public class DiscordDownloadBot extends ListenerAdapter { } // ⬇️ [최종 전략] 1차(영상) 시도 -> 실패시 -> 2차(사진) 시도. 디스코드/HTTP 공용 - private Result download(String url, String saveDir) { + // progress: (퍼센트, 속도)를 받을 함수. 필요 없으면 null (디스코드) + private Result download(String url, String saveDir, BiConsumer progress) { // URL에서 번호 뽑기 String targetIndexStr = getImgIndex(url); String targetIndex = (targetIndexStr != null) ? targetIndexStr : "1"; System.out.println("🎯 타겟 번호: " + targetIndex + "번"); // 👊 1타: 동영상이라고 가정하고 다운로드 시도 - if (tryDownloadAsVideo(url, saveDir, targetIndex)) return Result.VIDEO; + if (tryDownloadAsVideo(url, saveDir, targetIndex, progress)) return Result.VIDEO; System.out.println("⚠️ 동영상 다운로드 실패(사진인듯). 2차 시도 시작..."); @@ -290,7 +309,7 @@ public class DiscordDownloadBot extends ListenerAdapter { try { progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete(); String folder = new File(saveDir).getName(); - switch (download(url, saveDir)) { + switch (download(url, saveDir, null)) { case VIDEO: progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue(); break; @@ -307,7 +326,7 @@ public class DiscordDownloadBot extends ListenerAdapter { } // 🎥 1타: 동영상 모드 (Index 지정) - private boolean tryDownloadAsVideo(String url, String saveDir, String index) { + private boolean tryDownloadAsVideo(String url, String saveDir, String index, BiConsumer progress) { try { List cmdList = new ArrayList<>(); cmdList.add(YTDLP_PATH); @@ -325,6 +344,7 @@ public class DiscordDownloadBot extends ListenerAdapter { cmdList.add("bestvideo+bestaudio/best"); cmdList.add("--merge-output-format"); cmdList.add("mp4"); + cmdList.add("--newline"); // 진행률을 같은 줄 덮어쓰기 대신 한 줄씩 출력 → readLine으로 읽힘 cmdList.add("-o"); cmdList.add(saveDir + File.separator + "%(title)s_%(id)s_Video" + index + ".%(ext)s"); @@ -342,6 +362,10 @@ public class DiscordDownloadBot extends ListenerAdapter { boolean success = false; while ((line = reader.readLine()) != null) { // System.out.println("[Video] " + line); // 너무 시끄러우면 주석 처리 + if (progress != null) { + Matcher m = PROGRESS_LINE.matcher(line); + if (m.find()) progress.accept((int) Double.parseDouble(m.group(1)), m.group(2)); + } if (line.contains("100%") || line.contains("Destination")) { success = true; }