flucto 1.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +366 -0
- package/README.md +373 -0
- package/dist-electron/cli/args.js +209 -0
- package/dist-electron/cli/args.js.map +1 -0
- package/dist-electron/cli/index.js +579 -0
- package/dist-electron/cli/index.js.map +1 -0
- package/dist-electron/cli/jobOutput.js +32 -0
- package/dist-electron/cli/jobOutput.js.map +1 -0
- package/dist-electron/cli/output.js +176 -0
- package/dist-electron/cli/output.js.map +1 -0
- package/dist-electron/cli/theme.js +42 -0
- package/dist-electron/cli/theme.js.map +1 -0
- package/dist-electron/main/config.js +19 -0
- package/dist-electron/main/config.js.map +1 -0
- package/dist-electron/main/handlers.js +148 -0
- package/dist-electron/main/handlers.js.map +1 -0
- package/dist-electron/main/historyStore.js +20 -0
- package/dist-electron/main/historyStore.js.map +1 -0
- package/dist-electron/main/index.js +827 -0
- package/dist-electron/main/index.js.map +1 -0
- package/dist-electron/main/logger.js +57 -0
- package/dist-electron/main/logger.js.map +1 -0
- package/dist-electron/main/media/threads.js +152 -0
- package/dist-electron/main/media/threads.js.map +1 -0
- package/dist-electron/main/media/ytDlp.js +81 -0
- package/dist-electron/main/media/ytDlp.js.map +1 -0
- package/dist-electron/main/net/captionNetwork.js +81 -0
- package/dist-electron/main/net/captionNetwork.js.map +1 -0
- package/dist-electron/main/platforms/bilibili.js +33 -0
- package/dist-electron/main/platforms/bilibili.js.map +1 -0
- package/dist-electron/main/platforms/createRegistry.js +24 -0
- package/dist-electron/main/platforms/createRegistry.js.map +1 -0
- package/dist-electron/main/platforms/errors.js +13 -0
- package/dist-electron/main/platforms/errors.js.map +1 -0
- package/dist-electron/main/platforms/generic.js +12 -0
- package/dist-electron/main/platforms/generic.js.map +1 -0
- package/dist-electron/main/platforms/index.js +12 -0
- package/dist-electron/main/platforms/index.js.map +1 -0
- package/dist-electron/main/platforms/instagram.js +16 -0
- package/dist-electron/main/platforms/instagram.js.map +1 -0
- package/dist-electron/main/platforms/reddit.js +26 -0
- package/dist-electron/main/platforms/reddit.js.map +1 -0
- package/dist-electron/main/platforms/registry.js +23 -0
- package/dist-electron/main/platforms/registry.js.map +1 -0
- package/dist-electron/main/platforms/threads.js +168 -0
- package/dist-electron/main/platforms/threads.js.map +1 -0
- package/dist-electron/main/platforms/tiktok.js +15 -0
- package/dist-electron/main/platforms/tiktok.js.map +1 -0
- package/dist-electron/main/platforms/twitter.js +41 -0
- package/dist-electron/main/platforms/twitter.js.map +1 -0
- package/dist-electron/main/platforms/types.js +2 -0
- package/dist-electron/main/platforms/types.js.map +1 -0
- package/dist-electron/main/platforms/vimeo.js +10 -0
- package/dist-electron/main/platforms/vimeo.js.map +1 -0
- package/dist-electron/main/platforms/youtube.js +11 -0
- package/dist-electron/main/platforms/youtube.js.map +1 -0
- package/dist-electron/main/platforms/yt-dlp-adapter.js +17 -0
- package/dist-electron/main/platforms/yt-dlp-adapter.js.map +1 -0
- package/dist-electron/main/services/batch.js +26 -0
- package/dist-electron/main/services/batch.js.map +1 -0
- package/dist-electron/main/services/binaryInstaller.js +283 -0
- package/dist-electron/main/services/binaryInstaller.js.map +1 -0
- package/dist-electron/main/services/binaryRefresh.js +102 -0
- package/dist-electron/main/services/binaryRefresh.js.map +1 -0
- package/dist-electron/main/services/binaryResolver.js +62 -0
- package/dist-electron/main/services/binaryResolver.js.map +1 -0
- package/dist-electron/main/services/cliUpdater.js +149 -0
- package/dist-electron/main/services/cliUpdater.js.map +1 -0
- package/dist-electron/main/services/githubRelease.js +57 -0
- package/dist-electron/main/services/githubRelease.js.map +1 -0
- package/dist-electron/main/services/githubStar.js +69 -0
- package/dist-electron/main/services/githubStar.js.map +1 -0
- package/dist-electron/main/services/markdownFile.js +26 -0
- package/dist-electron/main/services/markdownFile.js.map +1 -0
- package/dist-electron/main/services/markdownPipeline.js +138 -0
- package/dist-electron/main/services/markdownPipeline.js.map +1 -0
- package/dist-electron/main/services/mediaDownload.js +226 -0
- package/dist-electron/main/services/mediaDownload.js.map +1 -0
- package/dist-electron/main/services/mediaInfo.js +230 -0
- package/dist-electron/main/services/mediaInfo.js.map +1 -0
- package/dist-electron/main/services/orchestrator.js +208 -0
- package/dist-electron/main/services/orchestrator.js.map +1 -0
- package/dist-electron/main/services/platformAssets.js +45 -0
- package/dist-electron/main/services/platformAssets.js.map +1 -0
- package/dist-electron/main/services/settingsDefaults.js +80 -0
- package/dist-electron/main/services/settingsDefaults.js.map +1 -0
- package/dist-electron/main/services/transcriptMarkdown.js +175 -0
- package/dist-electron/main/services/transcriptMarkdown.js.map +1 -0
- package/dist-electron/main/spawn.js +74 -0
- package/dist-electron/main/spawn.js.map +1 -0
- package/dist-electron/main/store.js +94 -0
- package/dist-electron/main/store.js.map +1 -0
- package/dist-electron/main/supabase.js +148 -0
- package/dist-electron/main/supabase.js.map +1 -0
- package/dist-electron/main/transcript/captionExtractor.js +455 -0
- package/dist-electron/main/transcript/captionExtractor.js.map +1 -0
- package/dist-electron/main/transcript/circuitBreaker.js +37 -0
- package/dist-electron/main/transcript/circuitBreaker.js.map +1 -0
- package/dist-electron/main/transcript/markdownFormatter.js +124 -0
- package/dist-electron/main/transcript/markdownFormatter.js.map +1 -0
- package/dist-electron/main/transcript/transcriptCache.js +51 -0
- package/dist-electron/main/transcript/transcriptCache.js.map +1 -0
- package/dist-electron/main/transcript/transcriptError.js +45 -0
- package/dist-electron/main/transcript/transcriptError.js.map +1 -0
- package/dist-electron/main/transcript/transcriptHandlers.js +74 -0
- package/dist-electron/main/transcript/transcriptHandlers.js.map +1 -0
- package/dist-electron/main/transcript/transcriptTypes.js +2 -0
- package/dist-electron/main/transcript/transcriptTypes.js.map +1 -0
- package/dist-electron/main/updater.js +253 -0
- package/dist-electron/main/updater.js.map +1 -0
- package/dist-electron/main/utils.js +108 -0
- package/dist-electron/main/utils.js.map +1 -0
- package/dist-electron/preload/index.js +93 -0
- package/dist-electron/preload/index.js.map +1 -0
- package/dist-electron/shared/types.js +2 -0
- package/dist-electron/shared/types.js.map +1 -0
- package/package.json +117 -0
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
import { app, BrowserWindow, ipcMain, shell, dialog, Notification } from "electron";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import { fileURLToPath } from "url";
|
|
5
|
+
import { execa } from "./spawn.js";
|
|
6
|
+
import { getBinaryPath, checkSystemHealth } from "./utils.js";
|
|
7
|
+
import { logger } from "./logger.js";
|
|
8
|
+
import { config } from "./config.js";
|
|
9
|
+
import { initializeAutoUpdater } from "./updater.js";
|
|
10
|
+
import { settingsStore, getStoredDownloadSettings } from './store.js';
|
|
11
|
+
import { appendHistoryEntry, clearHistory, getHistoryEntries } from './historyStore.js';
|
|
12
|
+
import { getCommonYtDlpArgs, getRefererForUrl, parseLastJsonObjectFromStdout } from './media/ytDlp.js';
|
|
13
|
+
import { createPlatformRegistry } from './platforms/index.js';
|
|
14
|
+
import { runMediaDownload } from './services/mediaDownload.js';
|
|
15
|
+
import { setupUtilities, versionFor } from './services/binaryInstaller.js';
|
|
16
|
+
import { checkAndRefreshBinaries } from './services/binaryRefresh.js';
|
|
17
|
+
import './handlers.js';
|
|
18
|
+
import './transcript/transcriptHandlers.js';
|
|
19
|
+
const registry = createPlatformRegistry();
|
|
20
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
21
|
+
const __dirname = path.dirname(__filename);
|
|
22
|
+
const toStringValue = (value) => {
|
|
23
|
+
return typeof value === "string" ? value : null;
|
|
24
|
+
};
|
|
25
|
+
const toNumberValue = (value) => {
|
|
26
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "string") {
|
|
30
|
+
const parsed = Number(value);
|
|
31
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
32
|
+
}
|
|
33
|
+
return 0;
|
|
34
|
+
};
|
|
35
|
+
const toMetadata = (value) => {
|
|
36
|
+
return typeof value === "object" && value !== null ? value : null;
|
|
37
|
+
};
|
|
38
|
+
const getErrorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
39
|
+
const sleep = (ms) => {
|
|
40
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
41
|
+
setTimeout(resolve, ms);
|
|
42
|
+
return promise;
|
|
43
|
+
};
|
|
44
|
+
const getVideoFormatSelector = (preset) => {
|
|
45
|
+
const constrainedSelector = (height) => {
|
|
46
|
+
return `bestvideo[ext=mp4][height<=${height}]+bestaudio[ext=m4a]/best[ext=mp4][height<=${height}][acodec!=none]/best[ext=mp4][acodec!=none]/worst[ext=mp4][acodec!=none]/mp4/best`;
|
|
47
|
+
};
|
|
48
|
+
switch (preset) {
|
|
49
|
+
case '4k':
|
|
50
|
+
return constrainedSelector(2160);
|
|
51
|
+
case '1440p':
|
|
52
|
+
return constrainedSelector(1440);
|
|
53
|
+
case '1080p':
|
|
54
|
+
return constrainedSelector(1080);
|
|
55
|
+
case '720p':
|
|
56
|
+
return constrainedSelector(720);
|
|
57
|
+
case '480p':
|
|
58
|
+
return constrainedSelector(480);
|
|
59
|
+
case '360p':
|
|
60
|
+
return constrainedSelector(360);
|
|
61
|
+
case 'worst':
|
|
62
|
+
return 'worst[ext=mp4]/mp4/worst';
|
|
63
|
+
default:
|
|
64
|
+
return constrainedSelector(1080);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const getAudioQualityValue = (preset) => {
|
|
68
|
+
switch (preset) {
|
|
69
|
+
case '320kbps':
|
|
70
|
+
return '320K';
|
|
71
|
+
case '256kbps':
|
|
72
|
+
return '256K';
|
|
73
|
+
case '192kbps':
|
|
74
|
+
return '192K';
|
|
75
|
+
case '128kbps':
|
|
76
|
+
return '128K';
|
|
77
|
+
case '64kbps':
|
|
78
|
+
return '64K';
|
|
79
|
+
case 'worst':
|
|
80
|
+
return '64K';
|
|
81
|
+
default:
|
|
82
|
+
return '320K';
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const isInstagramUrl = (url) => {
|
|
86
|
+
return url.includes("instagram.com");
|
|
87
|
+
};
|
|
88
|
+
const getOverrideVideoFormatSelector = (formatId) => {
|
|
89
|
+
return `${formatId}+bestaudio[ext=m4a]/${formatId}+bestaudio/${formatId}/best[ext=mp4][acodec!=none]/best`;
|
|
90
|
+
};
|
|
91
|
+
const getResolvedVideoFormatSelector = (url, preset, overrideFormatId) => {
|
|
92
|
+
if (isInstagramUrl(url)) {
|
|
93
|
+
return "best[ext=mp4]/best";
|
|
94
|
+
}
|
|
95
|
+
return overrideFormatId
|
|
96
|
+
? getOverrideVideoFormatSelector(overrideFormatId)
|
|
97
|
+
: getVideoFormatSelector(preset);
|
|
98
|
+
};
|
|
99
|
+
const showDesktopNotification = (title, body) => {
|
|
100
|
+
try {
|
|
101
|
+
if (Notification.isSupported()) {
|
|
102
|
+
new Notification({ title, body }).show();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
logger.warn('Notification failed', { error: getErrorMessage(error) });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
const getDesktopBinaries = () => ({
|
|
110
|
+
ytDlpPath: getBinaryPath("yt-dlp"),
|
|
111
|
+
ffmpegPath: getBinaryPath("ffmpeg"),
|
|
112
|
+
});
|
|
113
|
+
// 가비지 컬렉션 방지를 위한 전역 변수
|
|
114
|
+
let mainWindow = null;
|
|
115
|
+
function createWindow() {
|
|
116
|
+
mainWindow = new BrowserWindow({
|
|
117
|
+
width: 900,
|
|
118
|
+
height: 670,
|
|
119
|
+
title: "Flucto",
|
|
120
|
+
show: false, // 준비될 때까지 숨김 (깜빡임 방지)
|
|
121
|
+
autoHideMenuBar: true,
|
|
122
|
+
backgroundColor: "#111827", // 다크모드 배경색
|
|
123
|
+
webPreferences: {
|
|
124
|
+
preload: path.join(__dirname, "../preload/index.js"),
|
|
125
|
+
sandbox: false,
|
|
126
|
+
nodeIntegration: false,
|
|
127
|
+
contextIsolation: true,
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
|
131
|
+
void shell.openExternal(url);
|
|
132
|
+
return { action: "deny" };
|
|
133
|
+
});
|
|
134
|
+
mainWindow.webContents.on("will-navigate", (event, url) => {
|
|
135
|
+
const currentUrl = mainWindow?.webContents.getURL();
|
|
136
|
+
if (currentUrl && url !== currentUrl) {
|
|
137
|
+
event.preventDefault();
|
|
138
|
+
void shell.openExternal(url);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
mainWindow.on("ready-to-show", () => {
|
|
142
|
+
mainWindow?.show();
|
|
143
|
+
});
|
|
144
|
+
// HMR for development or load production build
|
|
145
|
+
// Use app.isPackaged for reliable environment detection
|
|
146
|
+
if (!app.isPackaged && process.env.NODE_ENV === "development") {
|
|
147
|
+
mainWindow.loadURL("http://localhost:5173");
|
|
148
|
+
// mainWindow.webContents.openDevTools(); // 개발자 도구 필요시 주석 해제
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
// In production, load the built renderer from dist/
|
|
152
|
+
mainWindow.loadFile(path.join(__dirname, "../../dist/index.html"));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// --- App Lifecycle ---
|
|
156
|
+
app.whenReady().then(async () => {
|
|
157
|
+
// 1. 시스템 무결성 검사
|
|
158
|
+
const health = await checkSystemHealth();
|
|
159
|
+
if (!health.valid) {
|
|
160
|
+
logger.error("Missing required binaries:", { missing: health.missing });
|
|
161
|
+
logger.info("Attempting to repair missing binaries in the managed Flucto bin directory.");
|
|
162
|
+
const repair = await setupUtilities({ onStatus: (message) => logger.info(message) });
|
|
163
|
+
const repairedHealth = repair.valid ? await checkSystemHealth() : repair;
|
|
164
|
+
if (!repairedHealth.valid) {
|
|
165
|
+
const missing = repairedHealth.missing.length > 0 ? repairedHealth.missing : health.missing;
|
|
166
|
+
dialog.showMessageBoxSync({
|
|
167
|
+
type: "error",
|
|
168
|
+
title: "Flucto - System Error",
|
|
169
|
+
message: "Required system components are missing.",
|
|
170
|
+
detail: `The following binaries were not found or could not be repaired:\n${missing.join(", ")}\n\nRun flucto setup or reinstall the application.`,
|
|
171
|
+
buttons: ["Exit"],
|
|
172
|
+
});
|
|
173
|
+
app.quit();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
logger.info("Missing binaries repaired successfully.");
|
|
177
|
+
}
|
|
178
|
+
// 2. 윈도우 생성
|
|
179
|
+
createWindow();
|
|
180
|
+
await initializeAutoUpdater();
|
|
181
|
+
// Packaged binaries are frozen at release time; refresh yt-dlp in the managed dir
|
|
182
|
+
// without blocking startup. Failures are logged and retried on the next launch.
|
|
183
|
+
void (async () => {
|
|
184
|
+
const result = await checkAndRefreshBinaries({
|
|
185
|
+
currentVersion: await versionFor(getBinaryPath('yt-dlp'), ['--version']),
|
|
186
|
+
onStatus: (message) => logger.info(`[binary-refresh] ${message}`),
|
|
187
|
+
});
|
|
188
|
+
if (result.error) {
|
|
189
|
+
logger.warn('Binary refresh skipped:', { error: result.error });
|
|
190
|
+
}
|
|
191
|
+
else if (result.refreshed) {
|
|
192
|
+
logger.info('yt-dlp refreshed successfully:', { version: result.version });
|
|
193
|
+
}
|
|
194
|
+
})().catch((error) => {
|
|
195
|
+
logger.warn('Binary refresh crashed:', { error: getErrorMessage(error) });
|
|
196
|
+
});
|
|
197
|
+
logger.info("Electron application is ready and healthy.");
|
|
198
|
+
app.on("activate", () => {
|
|
199
|
+
if (BrowserWindow.getAllWindows().length === 0)
|
|
200
|
+
createWindow();
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
app.on("window-all-closed", () => {
|
|
204
|
+
if (process.platform !== "darwin") {
|
|
205
|
+
app.quit();
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
// --- IPC Handlers ---
|
|
209
|
+
// [추가] 최적의 썸네일 추출 헬퍼 함수
|
|
210
|
+
const extractBestThumbnail = (info) => {
|
|
211
|
+
// 1. 최우선: thumbnail 필드에 유효한 URL이 있는 경우
|
|
212
|
+
if (info.thumbnail &&
|
|
213
|
+
typeof info.thumbnail === "string" &&
|
|
214
|
+
info.thumbnail.startsWith("http")) {
|
|
215
|
+
return info.thumbnail;
|
|
216
|
+
}
|
|
217
|
+
// 2. 차선: thumbnails 배열이 있는 경우 가장 마지막 항목(통상적으로 고화질) 선택
|
|
218
|
+
if (info.thumbnails &&
|
|
219
|
+
Array.isArray(info.thumbnails) &&
|
|
220
|
+
info.thumbnails.length > 0) {
|
|
221
|
+
// url 필드가 있는 마지막 아이템을 찾음
|
|
222
|
+
const validItems = info.thumbnails.filter((thumbnail) => {
|
|
223
|
+
if (typeof thumbnail !== "object" || thumbnail === null || !("url" in thumbnail)) {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
return typeof thumbnail.url === "string";
|
|
227
|
+
});
|
|
228
|
+
if (validItems.length > 0) {
|
|
229
|
+
const candidate = validItems[validItems.length - 1];
|
|
230
|
+
return candidate?.url ?? null;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return null;
|
|
234
|
+
};
|
|
235
|
+
// 1. Get Playlist Info Handler [최종 수정]
|
|
236
|
+
ipcMain.handle("get-playlist-info", async (_event, url) => {
|
|
237
|
+
const ytDlpPath = getBinaryPath("yt-dlp");
|
|
238
|
+
try {
|
|
239
|
+
logger.info(`Fetching playlist info for: ${url}`);
|
|
240
|
+
const referer = getRefererForUrl(url) ?? "";
|
|
241
|
+
// [보완 1] { reject: false } 추가: 일부 영상 다운 불가 에러로 인해 전체 프로세스가 멈추지 않도록 함
|
|
242
|
+
const result = await execa(ytDlpPath, [
|
|
243
|
+
url,
|
|
244
|
+
"--flat-playlist",
|
|
245
|
+
"--dump-json",
|
|
246
|
+
"--no-warnings",
|
|
247
|
+
"--skip-download",
|
|
248
|
+
"--ignore-errors",
|
|
249
|
+
"--compat-options",
|
|
250
|
+
"no-youtube-unavailable-videos", // [보완 2] 삭제된 동영상 정보 제외
|
|
251
|
+
"--compat-options",
|
|
252
|
+
"no-youtube-unavailable-videos", // [보완 2] 삭제된 동영상 정보 제외
|
|
253
|
+
...(referer ? ["--add-header", `referer:${referer}`] : []), // 플랫폼별 Referer 추가
|
|
254
|
+
...getCommonYtDlpArgs(url), // [추가] 플랫폼별 특화 옵션 적용
|
|
255
|
+
], { reject: false }); // <-- 중요: 에러가 발생해도 멈추지 않고 결과 반환
|
|
256
|
+
// stdout이 아예 비어있으면 진짜 에러
|
|
257
|
+
if (result.failed && !result.stdout.trim()) {
|
|
258
|
+
throw new Error(result.stderr || "Failed to fetch playlist info (No output)");
|
|
259
|
+
}
|
|
260
|
+
const playlistItems = result.stdout
|
|
261
|
+
.split(/\r?\n/) // [보완 3] 윈도우(\r\n)와 리눅스(\n) 줄바꿈 모두 대응하는 정규식 사용
|
|
262
|
+
.filter((line) => line.trim() !== "")
|
|
263
|
+
.map((line) => {
|
|
264
|
+
try {
|
|
265
|
+
return JSON.parse(line);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
// 파싱 실패한 줄은 경고 로그만 남기고 무시
|
|
269
|
+
logger.warn("Skipping invalid JSON line");
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
})
|
|
273
|
+
.filter((item) => {
|
|
274
|
+
// [보완 4] 유효한 비디오 아이템인지 검증 (플레이리스트 자체 메타데이터 제외)
|
|
275
|
+
const metadata = toMetadata(item);
|
|
276
|
+
return (metadata !== null &&
|
|
277
|
+
typeof metadata.id === "string" &&
|
|
278
|
+
metadata._type !== "playlist");
|
|
279
|
+
});
|
|
280
|
+
if (playlistItems.length === 0) {
|
|
281
|
+
logger.warn("Playlist is empty or all items were filtered out", { url });
|
|
282
|
+
}
|
|
283
|
+
return playlistItems.map((item) => ({
|
|
284
|
+
id: toStringValue(item.id) ?? "Unknown",
|
|
285
|
+
title: toStringValue(item.title) ?? "Untitled Video",
|
|
286
|
+
// [수정] 썸네일 추출 로직 강화
|
|
287
|
+
thumbnail: extractBestThumbnail(item),
|
|
288
|
+
duration: toNumberValue(item.duration),
|
|
289
|
+
uploader: toStringValue(item.uploader) ??
|
|
290
|
+
toStringValue(item.channel) ??
|
|
291
|
+
"Unknown",
|
|
292
|
+
view_count: toNumberValue(item.view_count),
|
|
293
|
+
originalUrl: toStringValue(item.url) ??
|
|
294
|
+
`https://www.youtube.com/watch?v=${toStringValue(item.id) ?? ""}`,
|
|
295
|
+
}));
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
const errorMessage = getErrorMessage(error);
|
|
299
|
+
logger.error("Get Playlist Info Error:", {
|
|
300
|
+
url,
|
|
301
|
+
error: errorMessage,
|
|
302
|
+
});
|
|
303
|
+
throw new Error(`Failed to fetch playlist info: ${errorMessage}`);
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
// 2. Get Video Info Handler [수정됨: SNS 지원 및 에러 방지 강화]
|
|
307
|
+
ipcMain.handle("get-video-info", async (_event, url) => {
|
|
308
|
+
const ytDlpPath = getBinaryPath("yt-dlp");
|
|
309
|
+
try {
|
|
310
|
+
logger.info(`Fetching video info for: ${url}`);
|
|
311
|
+
// Custom adapter check (e.g. Threads)
|
|
312
|
+
const adapter = registry.resolve(url);
|
|
313
|
+
if (adapter) {
|
|
314
|
+
const strategy = adapter.getStrategy(url);
|
|
315
|
+
if ((strategy === 'custom-api' || strategy === 'browser') && adapter.extractInfo) {
|
|
316
|
+
return await adapter.extractInfo(url);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const referer = getRefererForUrl(url) ?? "";
|
|
320
|
+
// 재시도 로직을 위한 함수
|
|
321
|
+
const tryFetch = async (retryCount = 0) => {
|
|
322
|
+
const args = [
|
|
323
|
+
url,
|
|
324
|
+
"--dump-json",
|
|
325
|
+
"--no-warnings",
|
|
326
|
+
"--no-playlist", // 단일 영상 정보만 요청
|
|
327
|
+
"--ignore-errors", // 에러 무시 (삭제된 트윗 등)
|
|
328
|
+
"--compat-options",
|
|
329
|
+
"no-youtube-unavailable-videos",
|
|
330
|
+
"--compat-options",
|
|
331
|
+
"no-youtube-unavailable-videos",
|
|
332
|
+
...(referer ? ["--add-header", `referer:${referer}`] : []), // 플랫폼별 Referer 추가
|
|
333
|
+
// [추가] 플랫폼별 특화 옵션 적용
|
|
334
|
+
...getCommonYtDlpArgs(url),
|
|
335
|
+
];
|
|
336
|
+
// Twitter/X의 경우 재시도 시 다른 API 옵션 시도
|
|
337
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
338
|
+
retryCount > 0) {
|
|
339
|
+
args.push("--extractor-args", "twitter:api=graph");
|
|
340
|
+
}
|
|
341
|
+
// { reject: false }로 실행 (경고 무시)
|
|
342
|
+
const result = await execa(ytDlpPath, args, { reject: false });
|
|
343
|
+
// 결과값이 아예 없으면 에러
|
|
344
|
+
if (result.failed && !result.stdout.trim()) {
|
|
345
|
+
// Twitter/X의 경우 404/403 오류 시 재시도
|
|
346
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
347
|
+
retryCount < 2) {
|
|
348
|
+
logger.warn(`Retrying Twitter/X fetch (attempt ${retryCount + 1})`);
|
|
349
|
+
await sleep(1000 * (retryCount + 1)); // 지수 백오프
|
|
350
|
+
return tryFetch(retryCount + 1);
|
|
351
|
+
}
|
|
352
|
+
throw new Error(result.stderr || "No output from yt-dlp");
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
return parseLastJsonObjectFromStdout(result.stdout);
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
// Twitter/X의 경우 재시도
|
|
359
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
360
|
+
retryCount < 2) {
|
|
361
|
+
logger.warn(`Retrying Twitter/X fetch due to parse error (attempt ${retryCount + 1})`);
|
|
362
|
+
await sleep(1000 * (retryCount + 1)); // 지수 백오프
|
|
363
|
+
return tryFetch(retryCount + 1);
|
|
364
|
+
}
|
|
365
|
+
throw new Error("Could not parse video metadata from yt-dlp output");
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
const info = await tryFetch();
|
|
369
|
+
// SNS별 메타데이터 필드 정규화
|
|
370
|
+
return {
|
|
371
|
+
id: toStringValue(info.id) ?? "",
|
|
372
|
+
title: toStringValue(info.title) ||
|
|
373
|
+
toStringValue(info.description)?.slice(0, 50) ||
|
|
374
|
+
"Untitled Media", // 트위터/인스타는 제목이 없을 수 있음
|
|
375
|
+
// [수정] 썸네일 추출 로직 강화
|
|
376
|
+
thumbnail: extractBestThumbnail(info),
|
|
377
|
+
duration: toNumberValue(info.duration),
|
|
378
|
+
uploader: toStringValue(info.uploader) ??
|
|
379
|
+
toStringValue(info.uploader_id) ??
|
|
380
|
+
"Unknown",
|
|
381
|
+
view_count: toNumberValue(info.view_count) || toNumberValue(info.like_count), // 뷰 카운트 없으면 좋아요 수로 대체
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
const errorMessage = getErrorMessage(error);
|
|
386
|
+
logger.error("Get Info Error:", { url, error: errorMessage });
|
|
387
|
+
throw new Error(`Failed to fetch video info: ${errorMessage}`);
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
ipcMain.handle("get-available-formats", async (_event, url) => {
|
|
391
|
+
const ytDlpPath = getBinaryPath('yt-dlp');
|
|
392
|
+
const referer = getRefererForUrl(url);
|
|
393
|
+
const result = await execa(ytDlpPath, [
|
|
394
|
+
url,
|
|
395
|
+
'-J',
|
|
396
|
+
'--no-warnings',
|
|
397
|
+
'--no-playlist',
|
|
398
|
+
...(referer ? ['--add-header', `referer:${referer}`] : []),
|
|
399
|
+
...getCommonYtDlpArgs(url),
|
|
400
|
+
], { reject: false });
|
|
401
|
+
if (result.failed && !result.stdout.trim()) {
|
|
402
|
+
throw new Error(result.stderr || 'Failed to fetch available formats');
|
|
403
|
+
}
|
|
404
|
+
const parsed = parseLastJsonObjectFromStdout(result.stdout);
|
|
405
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
406
|
+
return [];
|
|
407
|
+
}
|
|
408
|
+
const root = parsed;
|
|
409
|
+
if (!Array.isArray(root.formats)) {
|
|
410
|
+
return [];
|
|
411
|
+
}
|
|
412
|
+
const formats = [];
|
|
413
|
+
for (const raw of root.formats) {
|
|
414
|
+
if (!raw || typeof raw !== 'object') {
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
const format = raw;
|
|
418
|
+
const formatId = typeof format.format_id === 'string' ? format.format_id : null;
|
|
419
|
+
if (!formatId) {
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
formats.push({
|
|
423
|
+
formatId,
|
|
424
|
+
ext: typeof format.ext === 'string' ? format.ext : undefined,
|
|
425
|
+
resolution: typeof format.resolution === 'string' ? format.resolution : undefined,
|
|
426
|
+
width: typeof format.width === 'number' ? format.width : undefined,
|
|
427
|
+
height: typeof format.height === 'number' ? format.height : undefined,
|
|
428
|
+
fps: typeof format.fps === 'number' ? format.fps : undefined,
|
|
429
|
+
vcodec: typeof format.vcodec === 'string' ? format.vcodec : undefined,
|
|
430
|
+
acodec: typeof format.acodec === 'string' ? format.acodec : undefined,
|
|
431
|
+
abrKbps: typeof format.abr === 'number' ? format.abr : undefined,
|
|
432
|
+
tbrKbps: typeof format.tbr === 'number' ? format.tbr : undefined,
|
|
433
|
+
filesizeBytes: typeof format.filesize === 'number' ? format.filesize : undefined,
|
|
434
|
+
filesizeApproxBytes: typeof format.filesize_approx === 'number' ? format.filesize_approx : undefined,
|
|
435
|
+
note: typeof format.format_note === 'string'
|
|
436
|
+
? format.format_note
|
|
437
|
+
: typeof format.format === 'string'
|
|
438
|
+
? format.format
|
|
439
|
+
: undefined,
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
return formats;
|
|
443
|
+
});
|
|
444
|
+
// 2. Download Multiple Videos Handler
|
|
445
|
+
ipcMain.handle("download-multiple", async (event, { urls, format, quality, titles, formatOverrides, notifyPerItemInBatch, }) => {
|
|
446
|
+
const ytDlpPath = getBinaryPath("yt-dlp");
|
|
447
|
+
const ffmpegPath = getBinaryPath("ffmpeg");
|
|
448
|
+
const settings = getStoredDownloadSettings();
|
|
449
|
+
const selectedQuality = quality ?? settings.qualityPreferences;
|
|
450
|
+
const resolvedOverrides = formatOverrides ?? settings.formatOverrides;
|
|
451
|
+
const shouldNotifyPerItem = notifyPerItemInBatch ?? settings.notifyPerItemInBatch;
|
|
452
|
+
const outputTemplate = path.join(settings.downloadsDirectory || config.paths.downloads, "%(title)s.%(ext)s");
|
|
453
|
+
showDesktopNotification('Batch Download Started', `${urls.length} media item(s) started.`);
|
|
454
|
+
const downloadPromises = urls.map(async (url, index) => {
|
|
455
|
+
const requestId = `batch-${Date.now()}-${index}`;
|
|
456
|
+
const mediaTitle = titles?.[index] ?? url;
|
|
457
|
+
try {
|
|
458
|
+
event.sender.send("download-progress", {
|
|
459
|
+
requestId,
|
|
460
|
+
url,
|
|
461
|
+
status: "downloading",
|
|
462
|
+
progress: 0,
|
|
463
|
+
title: mediaTitle,
|
|
464
|
+
});
|
|
465
|
+
// Custom adapter check (e.g. Threads)
|
|
466
|
+
const adapter = registry.resolve(url);
|
|
467
|
+
if (adapter) {
|
|
468
|
+
const strategy = adapter.getStrategy(url);
|
|
469
|
+
if ((strategy === 'custom-api' || strategy === 'browser') && adapter.download) {
|
|
470
|
+
const result = await adapter.download({ url, outputDir: settings.downloadsDirectory || config.paths.downloads, format, requestId, title: mediaTitle }, (progress) => event.sender.send("download-progress", progress));
|
|
471
|
+
if (result.filePath) {
|
|
472
|
+
appendHistoryEntry({ id: requestId, url, title: mediaTitle, timestamp: Date.now(), status: 'success', filePath: result.filePath, format });
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
appendHistoryEntry({ id: requestId, url, title: mediaTitle, timestamp: Date.now(), status: 'error', filePath: null, errorMessage: result.message, format });
|
|
476
|
+
}
|
|
477
|
+
if (result.success && shouldNotifyPerItem) {
|
|
478
|
+
showDesktopNotification('Download Complete', mediaTitle);
|
|
479
|
+
}
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const referer = getRefererForUrl(url) ?? "";
|
|
484
|
+
// 재시도 로직을 위한 함수
|
|
485
|
+
const tryDownload = async (retryCount = 0) => {
|
|
486
|
+
// 다운로드 인자 구성
|
|
487
|
+
const args = [
|
|
488
|
+
url,
|
|
489
|
+
"--output",
|
|
490
|
+
outputTemplate,
|
|
491
|
+
"--encoding",
|
|
492
|
+
"utf-8",
|
|
493
|
+
"--no-check-certificates",
|
|
494
|
+
"--no-warnings",
|
|
495
|
+
"--newline",
|
|
496
|
+
"--no-playlist",
|
|
497
|
+
"--force-overwrites",
|
|
498
|
+
...(referer ? ["--add-header", `referer:${referer}`] : []),
|
|
499
|
+
"--ffmpeg-location",
|
|
500
|
+
path.dirname(ffmpegPath),
|
|
501
|
+
// [추가] 플랫폼별 특화 옵션 적용
|
|
502
|
+
...getCommonYtDlpArgs(url),
|
|
503
|
+
];
|
|
504
|
+
// Twitter/X의 경우 재시도 시 다른 API 옵션 시도
|
|
505
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
506
|
+
retryCount > 0) {
|
|
507
|
+
args.push("--extractor-args", "twitter:api=graph");
|
|
508
|
+
}
|
|
509
|
+
if (format === "mp3") {
|
|
510
|
+
const resolvedAudioOverrideId = isInstagramUrl(url) ? null : resolvedOverrides.audioFormatId;
|
|
511
|
+
if (resolvedAudioOverrideId) {
|
|
512
|
+
args.push("--format", resolvedAudioOverrideId);
|
|
513
|
+
}
|
|
514
|
+
const resolvedAudioQuality = getAudioQualityValue(selectedQuality.audio);
|
|
515
|
+
args.push("--extract-audio", "--audio-format", "mp3", "--audio-quality", resolvedAudioQuality);
|
|
516
|
+
logger.info('Batch download audio selection', {
|
|
517
|
+
requestId,
|
|
518
|
+
url,
|
|
519
|
+
preset: selectedQuality.audio,
|
|
520
|
+
overrideFormatId: resolvedAudioOverrideId,
|
|
521
|
+
resolvedAudioQuality,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
const resolvedVideoSelector = getResolvedVideoFormatSelector(url, selectedQuality.video, resolvedOverrides.videoFormatId);
|
|
526
|
+
args.push("--format", resolvedVideoSelector, "--merge-output-format", "mp4");
|
|
527
|
+
logger.info('Batch download video selection', {
|
|
528
|
+
requestId,
|
|
529
|
+
url,
|
|
530
|
+
preset: selectedQuality.video,
|
|
531
|
+
overrideFormatId: isInstagramUrl(url) ? null : resolvedOverrides.videoFormatId,
|
|
532
|
+
resolvedVideoSelector,
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
try {
|
|
536
|
+
const subprocess = execa(ytDlpPath, args);
|
|
537
|
+
subprocess.stdout?.on("data", (data) => {
|
|
538
|
+
const output = data.toString();
|
|
539
|
+
const progressMatch = output.match(/(\d+\.?\d*)%.*?(\d+\.?\d*\w+\/s).*?ETA\s+(\d+:\d+)/);
|
|
540
|
+
if (progressMatch) {
|
|
541
|
+
event.sender.send("download-progress", {
|
|
542
|
+
requestId,
|
|
543
|
+
url,
|
|
544
|
+
status: "downloading",
|
|
545
|
+
progress: parseFloat(progressMatch[1]),
|
|
546
|
+
speed: progressMatch[2],
|
|
547
|
+
eta: progressMatch[3],
|
|
548
|
+
title: mediaTitle,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
await subprocess;
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
// Twitter/X의 경우 404/403 오류 시 재시도
|
|
556
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
557
|
+
retryCount < 2) {
|
|
558
|
+
logger.warn(`Retrying Twitter/X download (attempt ${retryCount + 1}) for ${url}`);
|
|
559
|
+
await sleep(1000 * (retryCount + 1)); // 지수 백오프
|
|
560
|
+
return tryDownload(retryCount + 1);
|
|
561
|
+
}
|
|
562
|
+
throw error;
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
await tryDownload();
|
|
566
|
+
appendHistoryEntry({
|
|
567
|
+
id: requestId,
|
|
568
|
+
url,
|
|
569
|
+
title: mediaTitle,
|
|
570
|
+
timestamp: Date.now(),
|
|
571
|
+
status: 'success',
|
|
572
|
+
filePath: outputTemplate,
|
|
573
|
+
format,
|
|
574
|
+
});
|
|
575
|
+
event.sender.send("download-progress", {
|
|
576
|
+
requestId,
|
|
577
|
+
url,
|
|
578
|
+
status: "completed",
|
|
579
|
+
progress: 100,
|
|
580
|
+
title: mediaTitle,
|
|
581
|
+
});
|
|
582
|
+
if (shouldNotifyPerItem) {
|
|
583
|
+
showDesktopNotification('Download Complete', mediaTitle);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
const errorMessage = getErrorMessage(error);
|
|
588
|
+
logger.error(`Download Error for ${url}:`, { error: errorMessage });
|
|
589
|
+
appendHistoryEntry({
|
|
590
|
+
id: requestId,
|
|
591
|
+
url,
|
|
592
|
+
title: mediaTitle,
|
|
593
|
+
timestamp: Date.now(),
|
|
594
|
+
status: 'error',
|
|
595
|
+
filePath: null,
|
|
596
|
+
errorMessage,
|
|
597
|
+
format,
|
|
598
|
+
});
|
|
599
|
+
event.sender.send("download-progress", {
|
|
600
|
+
requestId,
|
|
601
|
+
url,
|
|
602
|
+
status: "error",
|
|
603
|
+
progress: 0,
|
|
604
|
+
error: errorMessage,
|
|
605
|
+
title: mediaTitle,
|
|
606
|
+
});
|
|
607
|
+
if (shouldNotifyPerItem) {
|
|
608
|
+
showDesktopNotification('Download Failed', `${mediaTitle}: ${errorMessage}`);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
await Promise.all(downloadPromises);
|
|
613
|
+
showDesktopNotification('Batch Download Finished', `${urls.length} media item(s) processed.`);
|
|
614
|
+
});
|
|
615
|
+
// 3. Download Video Handler (single)
|
|
616
|
+
ipcMain.handle("download-video", async (_event, args) => {
|
|
617
|
+
const { url, format } = args;
|
|
618
|
+
const settings = getStoredDownloadSettings();
|
|
619
|
+
const quality = args.quality ?? settings.qualityPreferences;
|
|
620
|
+
// 다운로드 경로 설정
|
|
621
|
+
const outputTemplate = path.join(settings.downloadsDirectory || config.paths.downloads, "%(title)s.%(ext)s");
|
|
622
|
+
// 바이너리 경로 가져오기 (utils.ts 활용)
|
|
623
|
+
const ytDlpPath = getBinaryPath("yt-dlp");
|
|
624
|
+
const ffmpegPath = getBinaryPath("ffmpeg");
|
|
625
|
+
logger.info(`Starting download: ${url} (Format: ${format})`);
|
|
626
|
+
logger.debug(`Binaries - yt-dlp: ${ytDlpPath}, ffmpeg: ${ffmpegPath}`);
|
|
627
|
+
showDesktopNotification('Download Started', 'Download has started.');
|
|
628
|
+
try {
|
|
629
|
+
// Custom adapter check (e.g. Threads)
|
|
630
|
+
const adapter = registry.resolve(url);
|
|
631
|
+
if (adapter) {
|
|
632
|
+
const strategy = adapter.getStrategy(url);
|
|
633
|
+
if ((strategy === 'custom-api' || strategy === 'browser') && adapter.download) {
|
|
634
|
+
const requestId = `custom-${Date.now()}`;
|
|
635
|
+
const result = await adapter.download({ url, outputDir: settings.downloadsDirectory || config.paths.downloads, format, requestId, title: args.title }, (progress) => _event.sender.send("download-progress", progress));
|
|
636
|
+
if (result.filePath) {
|
|
637
|
+
appendHistoryEntry({ id: requestId, url, title: args.title ?? 'Downloaded Media', timestamp: Date.now(), status: 'success', filePath: result.filePath, format });
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
appendHistoryEntry({ id: requestId, url, title: args.title ?? 'Failed Download', timestamp: Date.now(), status: 'error', filePath: null, errorMessage: result.message, format });
|
|
641
|
+
}
|
|
642
|
+
return result;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
const referer = getRefererForUrl(url) ?? "";
|
|
646
|
+
// 재시도 로직을 위한 함수
|
|
647
|
+
const tryDownload = async (retryCount = 0) => {
|
|
648
|
+
const downloadArgs = [
|
|
649
|
+
url,
|
|
650
|
+
"--output",
|
|
651
|
+
outputTemplate,
|
|
652
|
+
"--encoding",
|
|
653
|
+
"utf-8",
|
|
654
|
+
"--no-check-certificates",
|
|
655
|
+
"--no-warnings",
|
|
656
|
+
"--no-playlist",
|
|
657
|
+
"--force-overwrites",
|
|
658
|
+
...(referer ? ["--add-header", `referer:${referer}`] : []),
|
|
659
|
+
"--ffmpeg-location",
|
|
660
|
+
path.dirname(ffmpegPath),
|
|
661
|
+
// [추가] 플랫폼별 특화 옵션 적용
|
|
662
|
+
...getCommonYtDlpArgs(url),
|
|
663
|
+
];
|
|
664
|
+
// Twitter/X의 경우 재시도 시 다른 API 옵션 시도
|
|
665
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
666
|
+
retryCount > 0) {
|
|
667
|
+
downloadArgs.push("--extractor-args", "twitter:api=graph");
|
|
668
|
+
}
|
|
669
|
+
if (format === "mp3") {
|
|
670
|
+
downloadArgs.push("--extract-audio", "--audio-format", "mp3", "--audio-quality", getAudioQualityValue(quality.audio));
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
downloadArgs.push("--format", getResolvedVideoFormatSelector(url, quality.video), "--merge-output-format", "mp4");
|
|
674
|
+
}
|
|
675
|
+
logger.debug(`Executing: ${ytDlpPath} ${downloadArgs.join(" ")}`);
|
|
676
|
+
try {
|
|
677
|
+
// 실행 (execa)
|
|
678
|
+
await execa(ytDlpPath, downloadArgs);
|
|
679
|
+
}
|
|
680
|
+
catch (error) {
|
|
681
|
+
// Twitter/X의 경우 404/403 오류 시 재시도
|
|
682
|
+
if ((url.includes("x.com") || url.includes("twitter.com")) &&
|
|
683
|
+
retryCount < 2) {
|
|
684
|
+
logger.warn(`Retrying Twitter/X download (attempt ${retryCount + 1}) for ${url}`);
|
|
685
|
+
await sleep(1000 * (retryCount + 1)); // 지수 백오프
|
|
686
|
+
return tryDownload(retryCount + 1);
|
|
687
|
+
}
|
|
688
|
+
throw error;
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
await tryDownload();
|
|
692
|
+
return {
|
|
693
|
+
success: true,
|
|
694
|
+
message: "Download Complete!",
|
|
695
|
+
filePath: outputTemplate,
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
catch (error) {
|
|
699
|
+
const errorMessage = getErrorMessage(error);
|
|
700
|
+
logger.error("Download Error:", { error: errorMessage });
|
|
701
|
+
showDesktopNotification('Download Failed', errorMessage);
|
|
702
|
+
return { success: false, message: errorMessage || "Process Failed" };
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
// 4. Read Batch File Handler
|
|
706
|
+
ipcMain.handle("read-batch-file", async () => {
|
|
707
|
+
if (!mainWindow)
|
|
708
|
+
return null;
|
|
709
|
+
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
|
|
710
|
+
title: "Select Batch File (URL List)",
|
|
711
|
+
properties: ["openFile"],
|
|
712
|
+
filters: [{ name: "Text Files", extensions: ["txt", "list"] }],
|
|
713
|
+
});
|
|
714
|
+
if (canceled || filePaths.length === 0) {
|
|
715
|
+
return null;
|
|
716
|
+
}
|
|
717
|
+
try {
|
|
718
|
+
const content = fs.readFileSync(filePaths[0], "utf-8");
|
|
719
|
+
// yt-dlp --batch-file 규칙에 따른 파싱
|
|
720
|
+
const urls = content
|
|
721
|
+
.split("\n")
|
|
722
|
+
.map((line) => line.trim())
|
|
723
|
+
.filter((line) => {
|
|
724
|
+
// 빈 줄 제거
|
|
725
|
+
if (!line)
|
|
726
|
+
return false;
|
|
727
|
+
// 주석 제거 (#, ;, ])
|
|
728
|
+
const firstChar = line.charAt(0);
|
|
729
|
+
return !["#", ";", "]"].includes(firstChar);
|
|
730
|
+
});
|
|
731
|
+
return urls;
|
|
732
|
+
}
|
|
733
|
+
catch (error) {
|
|
734
|
+
const errorMessage = getErrorMessage(error);
|
|
735
|
+
logger.error("Batch File Read Error:", { error: errorMessage });
|
|
736
|
+
throw new Error("Failed to read batch file");
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
// 5. Open Folder Handler
|
|
740
|
+
ipcMain.handle("open-downloads-folder", async () => {
|
|
741
|
+
const settings = getStoredDownloadSettings();
|
|
742
|
+
const downloadsPath = settings.downloadsDirectory || config.paths.downloads;
|
|
743
|
+
await shell.openPath(downloadsPath);
|
|
744
|
+
});
|
|
745
|
+
// 6. Download Settings Handlers
|
|
746
|
+
ipcMain.handle("get-download-settings", async () => {
|
|
747
|
+
return getStoredDownloadSettings();
|
|
748
|
+
});
|
|
749
|
+
ipcMain.handle("set-download-settings", async (_event, settings) => {
|
|
750
|
+
const current = getStoredDownloadSettings();
|
|
751
|
+
const next = {
|
|
752
|
+
downloadsDirectory: settings.downloadsDirectory ?? current.downloadsDirectory,
|
|
753
|
+
qualityPreferences: settings.qualityPreferences ?? current.qualityPreferences,
|
|
754
|
+
formatOverrides: settings.formatOverrides ?? current.formatOverrides,
|
|
755
|
+
notifyPerItemInBatch: settings.notifyPerItemInBatch ?? current.notifyPerItemInBatch,
|
|
756
|
+
};
|
|
757
|
+
settingsStore.set('downloadSettings', next);
|
|
758
|
+
});
|
|
759
|
+
ipcMain.handle("set-download-directory", async (_event, path) => {
|
|
760
|
+
const settings = getStoredDownloadSettings();
|
|
761
|
+
settings.downloadsDirectory = path;
|
|
762
|
+
settingsStore.set('downloadSettings', settings);
|
|
763
|
+
});
|
|
764
|
+
ipcMain.handle("select-download-directory", async () => {
|
|
765
|
+
if (!mainWindow)
|
|
766
|
+
return null;
|
|
767
|
+
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
|
|
768
|
+
title: "Select Download Directory",
|
|
769
|
+
properties: ["openDirectory"],
|
|
770
|
+
});
|
|
771
|
+
if (canceled || filePaths.length === 0) {
|
|
772
|
+
return null;
|
|
773
|
+
}
|
|
774
|
+
const selectedPath = filePaths[0];
|
|
775
|
+
const settings = getStoredDownloadSettings();
|
|
776
|
+
settings.downloadsDirectory = selectedPath;
|
|
777
|
+
settingsStore.set('downloadSettings', settings);
|
|
778
|
+
return selectedPath;
|
|
779
|
+
});
|
|
780
|
+
ipcMain.handle("get-download-history", async () => {
|
|
781
|
+
return getHistoryEntries();
|
|
782
|
+
});
|
|
783
|
+
ipcMain.handle("clear-download-history", async () => {
|
|
784
|
+
clearHistory();
|
|
785
|
+
});
|
|
786
|
+
ipcMain.handle("download-single", async (event, args) => {
|
|
787
|
+
const { url, format, requestId, title } = args;
|
|
788
|
+
const settings = getStoredDownloadSettings();
|
|
789
|
+
const downloadsPath = settings.downloadsDirectory || config.paths.downloads;
|
|
790
|
+
const quality = args.quality ?? settings.qualityPreferences;
|
|
791
|
+
const formatOverrides = args.formatOverrides ?? settings.formatOverrides;
|
|
792
|
+
logger.info(`Starting single download: ${url} (Format: ${format}, RequestId: ${requestId})`);
|
|
793
|
+
showDesktopNotification('Download Started', title || 'Download has started.');
|
|
794
|
+
const response = await runMediaDownload({
|
|
795
|
+
url,
|
|
796
|
+
format,
|
|
797
|
+
outputDir: downloadsPath,
|
|
798
|
+
quality,
|
|
799
|
+
formatOverrides,
|
|
800
|
+
requestId,
|
|
801
|
+
title,
|
|
802
|
+
}, {
|
|
803
|
+
binaries: getDesktopBinaries(),
|
|
804
|
+
onProgress: (progress) => {
|
|
805
|
+
event.sender.send("download-progress", progress);
|
|
806
|
+
},
|
|
807
|
+
});
|
|
808
|
+
appendHistoryEntry({
|
|
809
|
+
id: requestId,
|
|
810
|
+
url,
|
|
811
|
+
title: title || (response.success ? "Downloaded Media" : "Failed Download"),
|
|
812
|
+
timestamp: Date.now(),
|
|
813
|
+
status: response.success ? "success" : "error",
|
|
814
|
+
filePath: response.filePath ?? null,
|
|
815
|
+
errorMessage: response.success ? undefined : response.message,
|
|
816
|
+
format,
|
|
817
|
+
});
|
|
818
|
+
if (response.success) {
|
|
819
|
+
showDesktopNotification('Download Complete', title || 'Your media has been downloaded successfully.');
|
|
820
|
+
}
|
|
821
|
+
else {
|
|
822
|
+
logger.error("Download Single Error:", { error: response.message });
|
|
823
|
+
showDesktopNotification('Download Failed', response.message);
|
|
824
|
+
}
|
|
825
|
+
return { success: response.success, message: response.message, filePath: response.filePath };
|
|
826
|
+
});
|
|
827
|
+
//# sourceMappingURL=index.js.map
|