mirror of
https://github.com/headporter81/DiscordDownloaderBot.git
synced 2026-12-06 07:41:10 +09:00
- 다운로드 로직(download)을 디스코드와 분리해 디스코드/HTTP가 함께 사용 - GET /folders, POST /download (X-Api-Key 인증, 202 응답 후 백그라운드 다운로드) - compose: API_KEY 환경변수, 192.168.0.215:18090 포트(LAN 전용) - CI: Gitea secret DOWNLOADER_API_KEY 전달 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4a2f149ca4
commit
77067a8285
3 files changed
+145
-31
No files matched your search
@@ -15,6 +15,7 @@ jobs:
|
||||
- name: Build & deploy
|
||||
env:
|
||||
BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
|
||||
API_KEY: ${{ secrets.DOWNLOADER_API_KEY }} # 홈페이지 백엔드 호출용 키 (Discord 토큰 아님, 무작위 값)
|
||||
run: |
|
||||
docker compose up -d --build
|
||||
docker image prune -f
|
||||
|
||||
@@ -8,6 +8,9 @@ services:
|
||||
environment:
|
||||
- TZ=Asia/Seoul
|
||||
- BOT_TOKEN=${BOT_TOKEN} # CI: Gitea secret / 수동: 같은 폴더의 .env
|
||||
- API_KEY=${API_KEY} # 홈페이지 백엔드와 같은 값. 비어 있으면 HTTP 창구 꺼짐
|
||||
ports:
|
||||
- "192.168.0.215:18090:8090" # 홈페이지 백엔드 전용 HTTP 창구 (LAN에서만, 공유기 포워딩 금지)
|
||||
volumes:
|
||||
- /volume1/downloads:/downloads
|
||||
# 호스트 절대경로 (CI job 컨테이너에서 실행해도 NAS 경로로 마운트되도록)
|
||||
|
||||
@@ -7,9 +7,22 @@ import net.dv8tion.jda.api.interactions.components.selections.StringSelectMenu;
|
||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import net.dv8tion.jda.api.exceptions.ParsingException;
|
||||
import net.dv8tion.jda.api.utils.data.DataArray;
|
||||
import net.dv8tion.jda.api.utils.data.DataObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -26,6 +39,11 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
||||
private static final String YTDLP_PATH = env("YTDLP_PATH", "yt-dlp");
|
||||
private static final String COOKIES_PATH = env("COOKIES_PATH", "cookies.txt");
|
||||
private static final String BASE_DOWNLOAD_DIR = env("DOWNLOAD_DIR", System.getProperty("user.dir") + File.separator + "Downloads");
|
||||
// 홈페이지 백엔드가 호출하는 HTTP 창구. API_KEY가 없으면 HTTP 창구는 켜지지 않음
|
||||
private static final String API_KEY = env("API_KEY", null);
|
||||
private static final int HTTP_PORT = Integer.parseInt(env("HTTP_PORT", "8090"));
|
||||
|
||||
private enum Result { VIDEO, IMAGE, FAIL }
|
||||
|
||||
private static String env(String key, String def) {
|
||||
String v = System.getenv(key);
|
||||
@@ -43,9 +61,11 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
||||
}
|
||||
new File(BASE_DOWNLOAD_DIR).mkdirs();
|
||||
try {
|
||||
DiscordDownloadBot bot = new DiscordDownloadBot();
|
||||
bot.startHttpServer(); // 디스코드 로그인이 실패해도 홈페이지 창구는 살아 있도록 먼저 켬
|
||||
JDABuilder.createDefault(BOT_TOKEN)
|
||||
.enableIntents(GatewayIntent.MESSAGE_CONTENT)
|
||||
.addEventListeners(new DiscordDownloadBot())
|
||||
.addEventListeners(bot)
|
||||
.build();
|
||||
System.out.println("🤖 봇 실행 완료! (더블 탭 전략)");
|
||||
} catch (Exception e) {
|
||||
@@ -71,16 +91,107 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 🌐 HTTP 창구 (홈페이지 백엔드 전용)
|
||||
// GET /folders → {"folders":["주짓수", ...]}
|
||||
// POST /download {"url","folder"} → 202 {"status":"accepted"} (다운로드는 뒤에서 진행)
|
||||
// 모든 요청에 X-Api-Key 헤더 필요
|
||||
// ==========================================
|
||||
private void startHttpServer() throws IOException {
|
||||
if (API_KEY == null) {
|
||||
System.out.println("ℹ️ API_KEY 환경변수가 없어 HTTP 창구는 끔");
|
||||
return;
|
||||
}
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress(HTTP_PORT), 0);
|
||||
server.createContext("/folders", ex -> handle(ex, "GET", () -> {
|
||||
DataArray arr = DataArray.empty();
|
||||
for (String name : listFolders()) arr.add(name);
|
||||
send(ex, 200, DataObject.empty().put("folders", arr));
|
||||
}));
|
||||
server.createContext("/download", ex -> handle(ex, "POST", () -> {
|
||||
DataObject body;
|
||||
try {
|
||||
body = DataObject.fromJson(readBody(ex.getRequestBody()));
|
||||
} catch (ParsingException e) {
|
||||
send(ex, 400, error("JSON 형식이 아닙니다"));
|
||||
return;
|
||||
}
|
||||
String url = extractUrl(body.getString("url", ""));
|
||||
String folder = sanitizeFolder(body.getString("folder", ""));
|
||||
if (url == null) { send(ex, 400, error("지원하지 않는 링크입니다 (유튜브/인스타)")); return; }
|
||||
if (folder.isEmpty()) { send(ex, 400, error("폴더 이름이 올바르지 않습니다")); return; }
|
||||
|
||||
String saveDir = BASE_DOWNLOAD_DIR + File.separator + folder;
|
||||
new File(saveDir).mkdirs();
|
||||
executor.submit(() -> System.out.println("🌐 [HTTP] " + folder + " ← " + url + " : " + download(url, saveDir)));
|
||||
send(ex, 202, DataObject.empty().put("status", "accepted").put("folder", folder));
|
||||
}));
|
||||
server.start();
|
||||
System.out.println("🌐 HTTP 창구 실행: " + HTTP_PORT);
|
||||
}
|
||||
|
||||
private interface Action { void run() throws Exception; }
|
||||
|
||||
// 공통 처리: 메서드·API 키 확인, 예외는 500으로 (안 잡으면 연결이 그냥 끊김)
|
||||
private void handle(HttpExchange ex, String method, Action action) throws IOException {
|
||||
try {
|
||||
String key = ex.getRequestHeaders().getFirst("X-Api-Key");
|
||||
if (key == null || !MessageDigest.isEqual(key.getBytes(StandardCharsets.UTF_8), API_KEY.getBytes(StandardCharsets.UTF_8))) {
|
||||
send(ex, 401, error("인증 실패"));
|
||||
} else if (!ex.getRequestMethod().equals(method)) {
|
||||
send(ex, 405, error("허용되지 않는 메서드"));
|
||||
} else {
|
||||
action.run();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
send(ex, 500, error("서버 오류: " + e.getMessage()));
|
||||
} finally {
|
||||
ex.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static DataObject error(String msg) {
|
||||
return DataObject.empty().put("error", msg);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange ex, int status, DataObject json) throws IOException {
|
||||
byte[] bytes = json.toString().getBytes(StandardCharsets.UTF_8);
|
||||
ex.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||
ex.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream os = ex.getResponseBody()) { os.write(bytes); }
|
||||
}
|
||||
|
||||
private static String readBody(InputStream in) throws IOException {
|
||||
ByteArrayOutputStream buf = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[4096];
|
||||
int n;
|
||||
while ((n = in.read(chunk)) != -1) {
|
||||
buf.write(chunk, 0, n);
|
||||
if (buf.size() > 64 * 1024) throw new IOException("요청 본문이 너무 큽니다");
|
||||
}
|
||||
return new String(buf.toByteArray(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static List<String> listFolders() {
|
||||
File[] dirs = new File(BASE_DOWNLOAD_DIR).listFiles(File::isDirectory);
|
||||
List<String> names = new ArrayList<>();
|
||||
if (dirs != null) for (File d : dirs) names.add(d.getName());
|
||||
names.sort(null);
|
||||
return names;
|
||||
}
|
||||
|
||||
// 영문/숫자/한글/_/- 만 남김 → "../" 같은 경로 탈출 차단
|
||||
private static String sanitizeFolder(String name) {
|
||||
return name.replaceAll("[^a-zA-Z0-9가-힣_\\-]", "");
|
||||
}
|
||||
|
||||
private void sendFolderSelectionMenu(MessageReceivedEvent event) {
|
||||
File baseDir = new File(BASE_DOWNLOAD_DIR);
|
||||
File[] directories = baseDir.listFiles(File::isDirectory);
|
||||
StringSelectMenu.Builder menuBuilder = StringSelectMenu.create("folder-select").setPlaceholder("📂 저장할 폴더를 선택하세요");
|
||||
|
||||
if (directories != null) {
|
||||
for (File dir : directories) {
|
||||
for (String name : listFolders()) {
|
||||
if (menuBuilder.getOptions().size() >= 24) break;
|
||||
menuBuilder.addOption("📂 " + dir.getName(), dir.getName());
|
||||
}
|
||||
menuBuilder.addOption("📂 " + name, name);
|
||||
}
|
||||
menuBuilder.addOption("➕ 새 폴더 만들기", "create_new_folder");
|
||||
event.getChannel().sendMessage("영상 링크를 확인했습니다! **어디에 저장할까요?**").addActionRow(menuBuilder.build()).queue();
|
||||
@@ -111,7 +222,7 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
||||
|
||||
private void createNewFolderAndDownload(MessageReceivedEvent event, String folderName) {
|
||||
String userId = event.getAuthor().getId();
|
||||
folderName = folderName.replaceAll("[^a-zA-Z0-9가-힣_\\-]", "");
|
||||
folderName = sanitizeFolder(folderName);
|
||||
if (folderName.isEmpty()) folderName = "NewFolder";
|
||||
String newFolderPath = BASE_DOWNLOAD_DIR + File.separator + folderName;
|
||||
new File(newFolderPath).mkdirs();
|
||||
@@ -125,40 +236,39 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
||||
pendingUrls.remove(userId);
|
||||
}
|
||||
|
||||
// ⬇️ [최종 전략] 1차(영상) 시도 -> 실패시 -> 2차(사진) 시도
|
||||
private void processDownload(String url, net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel, String saveDir) {
|
||||
Message progressMessage = null;
|
||||
try {
|
||||
progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete();
|
||||
|
||||
// 1. URL에서 번호 뽑기
|
||||
// ⬇️ [최종 전략] 1차(영상) 시도 -> 실패시 -> 2차(사진) 시도. 디스코드/HTTP 공용
|
||||
private Result download(String url, String saveDir) {
|
||||
// URL에서 번호 뽑기
|
||||
String targetIndexStr = getImgIndex(url);
|
||||
String targetIndex = (targetIndexStr != null) ? targetIndexStr : "1";
|
||||
System.out.println("🎯 타겟 번호: " + targetIndex + "번");
|
||||
|
||||
// ==========================================
|
||||
// 👊 1타: 동영상이라고 가정하고 다운로드 시도
|
||||
// ==========================================
|
||||
boolean isVideoSuccess = tryDownloadAsVideo(url, saveDir, targetIndex);
|
||||
|
||||
if (isVideoSuccess) {
|
||||
progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + new File(saveDir).getName() + "`").queue();
|
||||
return;
|
||||
}
|
||||
if (tryDownloadAsVideo(url, saveDir, targetIndex)) return Result.VIDEO;
|
||||
|
||||
System.out.println("⚠️ 동영상 다운로드 실패(사진인듯). 2차 시도 시작...");
|
||||
|
||||
// ==========================================
|
||||
// 👊 2타: 사진이라고 가정하고 다운로드 시도
|
||||
// ==========================================
|
||||
boolean isImageSuccess = tryDownloadAsImage(url, saveDir, targetIndex);
|
||||
|
||||
if (isImageSuccess) {
|
||||
progressMessage.editMessage("✅ **사진 다운로드 완료!**\n📂 폴더: `" + new File(saveDir).getName() + "`").queue();
|
||||
} else {
|
||||
progressMessage.editMessage("❌ **최종 실패.** (쿠키 만료 또는 게시물 삭제됨)").queue();
|
||||
if (tryDownloadAsImage(url, saveDir, targetIndex)) return Result.IMAGE;
|
||||
return Result.FAIL;
|
||||
}
|
||||
|
||||
// 디스코드용: download() 결과를 진행 메시지로 표시
|
||||
private void processDownload(String url, net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel, String saveDir) {
|
||||
Message progressMessage = null;
|
||||
try {
|
||||
progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete();
|
||||
String folder = new File(saveDir).getName();
|
||||
switch (download(url, saveDir)) {
|
||||
case VIDEO:
|
||||
progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue();
|
||||
break;
|
||||
case IMAGE:
|
||||
progressMessage.editMessage("✅ **사진 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue();
|
||||
break;
|
||||
default:
|
||||
progressMessage.editMessage("❌ **최종 실패.** (쿠키 만료 또는 게시물 삭제됨)").queue();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (progressMessage != null) progressMessage.editMessage("🔥 오류: " + e.getMessage()).queue();
|
||||
e.printStackTrace();
|
||||
|
||||
Reference in new issue
Block a user