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
+152
-38
No files matched your search
@@ -15,6 +15,7 @@ jobs:
|
|||||||
- name: Build & deploy
|
- name: Build & deploy
|
||||||
env:
|
env:
|
||||||
BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
|
BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
|
||||||
|
API_KEY: ${{ secrets.DOWNLOADER_API_KEY }} # 홈페이지 백엔드 호출용 키 (Discord 토큰 아님, 무작위 값)
|
||||||
run: |
|
run: |
|
||||||
docker compose up -d --build
|
docker compose up -d --build
|
||||||
docker image prune -f
|
docker image prune -f
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- TZ=Asia/Seoul
|
- TZ=Asia/Seoul
|
||||||
- BOT_TOKEN=${BOT_TOKEN} # CI: Gitea secret / 수동: 같은 폴더의 .env
|
- BOT_TOKEN=${BOT_TOKEN} # CI: Gitea secret / 수동: 같은 폴더의 .env
|
||||||
|
- API_KEY=${API_KEY} # 홈페이지 백엔드와 같은 값. 비어 있으면 HTTP 창구 꺼짐
|
||||||
|
ports:
|
||||||
|
- "192.168.0.215:18090:8090" # 홈페이지 백엔드 전용 HTTP 창구 (LAN에서만, 공유기 포워딩 금지)
|
||||||
volumes:
|
volumes:
|
||||||
- /volume1/downloads:/downloads
|
- /volume1/downloads:/downloads
|
||||||
# 호스트 절대경로 (CI job 컨테이너에서 실행해도 NAS 경로로 마운트되도록)
|
# 호스트 절대경로 (CI job 컨테이너에서 실행해도 NAS 경로로 마운트되도록)
|
||||||
|
|||||||
@@ -7,9 +7,22 @@ import net.dv8tion.jda.api.interactions.components.selections.StringSelectMenu;
|
|||||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||||
import org.jetbrains.annotations.NotNull;
|
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.BufferedReader;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
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.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
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 YTDLP_PATH = env("YTDLP_PATH", "yt-dlp");
|
||||||
private static final String COOKIES_PATH = env("COOKIES_PATH", "cookies.txt");
|
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");
|
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) {
|
private static String env(String key, String def) {
|
||||||
String v = System.getenv(key);
|
String v = System.getenv(key);
|
||||||
@@ -43,9 +61,11 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
|||||||
}
|
}
|
||||||
new File(BASE_DOWNLOAD_DIR).mkdirs();
|
new File(BASE_DOWNLOAD_DIR).mkdirs();
|
||||||
try {
|
try {
|
||||||
|
DiscordDownloadBot bot = new DiscordDownloadBot();
|
||||||
|
bot.startHttpServer(); // 디스코드 로그인이 실패해도 홈페이지 창구는 살아 있도록 먼저 켬
|
||||||
JDABuilder.createDefault(BOT_TOKEN)
|
JDABuilder.createDefault(BOT_TOKEN)
|
||||||
.enableIntents(GatewayIntent.MESSAGE_CONTENT)
|
.enableIntents(GatewayIntent.MESSAGE_CONTENT)
|
||||||
.addEventListeners(new DiscordDownloadBot())
|
.addEventListeners(bot)
|
||||||
.build();
|
.build();
|
||||||
System.out.println("🤖 봇 실행 완료! (더블 탭 전략)");
|
System.out.println("🤖 봇 실행 완료! (더블 탭 전략)");
|
||||||
} catch (Exception e) {
|
} 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) {
|
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("📂 저장할 폴더를 선택하세요");
|
StringSelectMenu.Builder menuBuilder = StringSelectMenu.create("folder-select").setPlaceholder("📂 저장할 폴더를 선택하세요");
|
||||||
|
|
||||||
if (directories != null) {
|
for (String name : listFolders()) {
|
||||||
for (File dir : directories) {
|
if (menuBuilder.getOptions().size() >= 24) break;
|
||||||
if (menuBuilder.getOptions().size() >= 24) break;
|
menuBuilder.addOption("📂 " + name, name);
|
||||||
menuBuilder.addOption("📂 " + dir.getName(), dir.getName());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
menuBuilder.addOption("➕ 새 폴더 만들기", "create_new_folder");
|
menuBuilder.addOption("➕ 새 폴더 만들기", "create_new_folder");
|
||||||
event.getChannel().sendMessage("영상 링크를 확인했습니다! **어디에 저장할까요?**").addActionRow(menuBuilder.build()).queue();
|
event.getChannel().sendMessage("영상 링크를 확인했습니다! **어디에 저장할까요?**").addActionRow(menuBuilder.build()).queue();
|
||||||
@@ -111,7 +222,7 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
|||||||
|
|
||||||
private void createNewFolderAndDownload(MessageReceivedEvent event, String folderName) {
|
private void createNewFolderAndDownload(MessageReceivedEvent event, String folderName) {
|
||||||
String userId = event.getAuthor().getId();
|
String userId = event.getAuthor().getId();
|
||||||
folderName = folderName.replaceAll("[^a-zA-Z0-9가-힣_\\-]", "");
|
folderName = sanitizeFolder(folderName);
|
||||||
if (folderName.isEmpty()) folderName = "NewFolder";
|
if (folderName.isEmpty()) folderName = "NewFolder";
|
||||||
String newFolderPath = BASE_DOWNLOAD_DIR + File.separator + folderName;
|
String newFolderPath = BASE_DOWNLOAD_DIR + File.separator + folderName;
|
||||||
new File(newFolderPath).mkdirs();
|
new File(newFolderPath).mkdirs();
|
||||||
@@ -125,40 +236,39 @@ public class DiscordDownloadBot extends ListenerAdapter {
|
|||||||
pendingUrls.remove(userId);
|
pendingUrls.remove(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ⬇️ [최종 전략] 1차(영상) 시도 -> 실패시 -> 2차(사진) 시도
|
// ⬇️ [최종 전략] 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타: 동영상이라고 가정하고 다운로드 시도
|
||||||
|
if (tryDownloadAsVideo(url, saveDir, targetIndex)) return Result.VIDEO;
|
||||||
|
|
||||||
|
System.out.println("⚠️ 동영상 다운로드 실패(사진인듯). 2차 시도 시작...");
|
||||||
|
|
||||||
|
// 👊 2타: 사진이라고 가정하고 다운로드 시도
|
||||||
|
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) {
|
private void processDownload(String url, net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel, String saveDir) {
|
||||||
Message progressMessage = null;
|
Message progressMessage = null;
|
||||||
try {
|
try {
|
||||||
progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete();
|
progressMessage = channel.sendMessage("⏳ **다운로드 시도 중...**").complete();
|
||||||
|
String folder = new File(saveDir).getName();
|
||||||
// 1. URL에서 번호 뽑기
|
switch (download(url, saveDir)) {
|
||||||
String targetIndexStr = getImgIndex(url);
|
case VIDEO:
|
||||||
String targetIndex = (targetIndexStr != null) ? targetIndexStr : "1";
|
progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue();
|
||||||
System.out.println("🎯 타겟 번호: " + targetIndex + "번");
|
break;
|
||||||
|
case IMAGE:
|
||||||
// ==========================================
|
progressMessage.editMessage("✅ **사진 다운로드 완료!**\n📂 폴더: `" + folder + "`").queue();
|
||||||
// 👊 1타: 동영상이라고 가정하고 다운로드 시도
|
break;
|
||||||
// ==========================================
|
default:
|
||||||
boolean isVideoSuccess = tryDownloadAsVideo(url, saveDir, targetIndex);
|
progressMessage.editMessage("❌ **최종 실패.** (쿠키 만료 또는 게시물 삭제됨)").queue();
|
||||||
|
|
||||||
if (isVideoSuccess) {
|
|
||||||
progressMessage.editMessage("✅ **동영상 다운로드 완료!**\n📂 폴더: `" + new File(saveDir).getName() + "`").queue();
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (progressMessage != null) progressMessage.editMessage("🔥 오류: " + e.getMessage()).queue();
|
if (progressMessage != null) progressMessage.editMessage("🔥 오류: " + e.getMessage()).queue();
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
|
|||||||
Reference in new issue
Block a user