feat : 홈페이지 자료실에 다운로드 진행률 알림
deploy / deploy (push) Successful in 24s

- yt-dlp --newline 으로 진행률 줄을 읽어 2초에 한 번 콜백 (result=PROGRESS, progress %, speed)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-27 17:33:46 +09:00
1 parent 91a87eea6d
commit 99029064d3
1 file changed
+34 -10
+34 -10
View File
@@ -29,6 +29,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.BiConsumer;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -49,6 +50,10 @@ public class DiscordDownloadBot extends ListenerAdapter {
private enum Result { VIDEO, IMAGE, FAIL } 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) { private static String env(String key, String def) {
String v = System.getenv(key); String v = System.getenv(key);
return (v == null || v.isEmpty()) ? def : v; return (v == null || v.isEmpty()) ? def : v;
@@ -132,9 +137,20 @@ public class DiscordDownloadBot extends ListenerAdapter {
String saveDir = baseDir + File.separator + folder; String saveDir = baseDir + File.separator + folder;
new File(saveDir).mkdirs(); new File(saveDir).mkdirs();
executor.submit(() -> { executor.submit(() -> {
Result result = download(url, saveDir); // 진행률은 2초에 한 번만 알림 (yt-dlp는 초당 여러 줄을 출력함)
long[] lastSent = {0};
BiConsumer<Integer, String> 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); 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)); 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); 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 { try {
HttpURLConnection conn = (HttpURLConnection) new URL(callbackUrl).openConnection(); HttpURLConnection conn = (HttpURLConnection) new URL(callbackUrl).openConnection();
conn.setRequestMethod("POST"); conn.setRequestMethod("POST");
@@ -152,9 +169,10 @@ public class DiscordDownloadBot extends ListenerAdapter {
conn.setDoOutput(true); conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("X-Api-Key", API_KEY); 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); } 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(); conn.disconnect();
} catch (Exception e) { } catch (Exception e) {
System.out.println("⚠️ 콜백 실패: " + folder + " (" + e.getMessage() + ")"); System.out.println("⚠️ 콜백 실패: " + folder + " (" + e.getMessage() + ")");
@@ -268,14 +286,15 @@ public class DiscordDownloadBot extends ListenerAdapter {
} }
// ⬇️ [최종 전략] 1차(영상) 시도 -> 실패시 -> 2차(사진) 시도. 디스코드/HTTP 공용 // ⬇️ [최종 전략] 1차(영상) 시도 -> 실패시 -> 2차(사진) 시도. 디스코드/HTTP 공용
private Result download(String url, String saveDir) { // progress: (퍼센트, 속도)를 받을 함수. 필요 없으면 null (디스코드)
private Result download(String url, String saveDir, BiConsumer<Integer, String> progress) {
// URL에서 번호 뽑기 // URL에서 번호 뽑기
String targetIndexStr = getImgIndex(url); String targetIndexStr = getImgIndex(url);
String targetIndex = (targetIndexStr != null) ? targetIndexStr : "1"; String targetIndex = (targetIndexStr != null) ? targetIndexStr : "1";
System.out.println("🎯 타겟 번호: " + targetIndex + "번"); System.out.println("🎯 타겟 번호: " + targetIndex + "번");
// 👊 1타: 동영상이라고 가정하고 다운로드 시도 // 👊 1타: 동영상이라고 가정하고 다운로드 시도
if (tryDownloadAsVideo(url, saveDir, targetIndex)) return Result.VIDEO; if (tryDownloadAsVideo(url, saveDir, targetIndex, progress)) return Result.VIDEO;
System.out.println("⚠️ 동영상 다운로드 실패(사진인듯). 2차 시도 시작..."); System.out.println("⚠️ 동영상 다운로드 실패(사진인듯). 2차 시도 시작...");
@@ -290,7 +309,7 @@ public class DiscordDownloadBot extends ListenerAdapter {
try { try {
progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete(); progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete();
String folder = new File(saveDir).getName(); String folder = new File(saveDir).getName();
switch (download(url, saveDir)) { switch (download(url, saveDir, null)) {
case VIDEO: case VIDEO:
progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue(); progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue();
break; break;
@@ -307,7 +326,7 @@ public class DiscordDownloadBot extends ListenerAdapter {
} }
// 🎥 1타: 동영상 모드 (Index 지정) // 🎥 1타: 동영상 모드 (Index 지정)
private boolean tryDownloadAsVideo(String url, String saveDir, String index) { private boolean tryDownloadAsVideo(String url, String saveDir, String index, BiConsumer<Integer, String> progress) {
try { try {
List<String> cmdList = new ArrayList<>(); List<String> cmdList = new ArrayList<>();
cmdList.add(YTDLP_PATH); cmdList.add(YTDLP_PATH);
@@ -325,6 +344,7 @@ public class DiscordDownloadBot extends ListenerAdapter {
cmdList.add("bestvideo+bestaudio/best"); cmdList.add("bestvideo+bestaudio/best");
cmdList.add("--merge-output-format"); cmdList.add("--merge-output-format");
cmdList.add("mp4"); cmdList.add("mp4");
cmdList.add("--newline"); // 진행률을 같은 줄 덮어쓰기 대신 한 줄씩 출력 → readLine으로 읽힘
cmdList.add("-o"); cmdList.add("-o");
cmdList.add(saveDir + File.separator + "%(title)s_%(id)s_Video" + index + ".%(ext)s"); 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; boolean success = false;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
// System.out.println("[Video] " + line); // 너무 시끄러우면 주석 처리 // 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")) { if (line.contains("100%") || line.contains("Destination")) {
success = true; success = true;
} }