-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
294 lines (254 loc) · 10.1 KB
/
Copy pathmain.js
File metadata and controls
294 lines (254 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const { spawn } = require('child_process');
const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');
const isDev = process.argv.includes('--dev');
// Ignorar erros de certificado e esconder warnings do Chromium (como SSL handshake failed nas thumbnails)
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');
app.commandLine.appendSwitch('log-level', '3');
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
icon: path.join(__dirname, 'public/icon.ico'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#0f172a',
symbolColor: '#ffffff',
},
});
// Remove menu
win.setMenu(null);
if (isDev) {
// In dev mode, we can still try to load the file if it exists,
// but usually dev mode implies a server.
// However, the user specifically said "no localhost:3000".
const indexPath = path.join(__dirname, 'dist/index.html');
if (fs.existsSync(indexPath)) {
win.loadFile(indexPath);
} else {
// Fallback to localhost if dist doesn't exist yet in dev
win.loadURL('http://localhost:3000');
}
} else {
win.loadFile(path.join(__dirname, 'dist/index.html'));
}
// Open DevTools in dev mode
if (isDev) {
win.webContents.openDevTools();
}
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// IPC Handlers
ipcMain.handle('select-folder', async () => {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
});
return result.canceled ? null : result.filePaths[0];
});
ipcMain.handle('select-file', async (event, filters) => {
const result = await dialog.showOpenDialog({
properties: ['openFile'],
filters: filters || [],
});
return result.canceled ? null : result.filePaths[0];
});
ipcMain.handle('get-video-info', async (event, { url, ytDlpPath, cookiesPath }) => {
return new Promise((resolve, reject) => {
const args = ['--encoding', 'utf-8', '--js-runtimes', 'node', '--dump-single-json', '--flat-playlist', url];
if (cookiesPath) {
args.unshift('--cookies', cookiesPath);
}
const ytProcess = spawn(ytDlpPath || 'yt-dlp', args, {
env: { ...process.env, PYTHONIOENCODING: 'utf-8' }
});
let output = '';
let errorOutput = '';
ytProcess.stdout.on('data', (data) => {
output += data.toString();
});
ytProcess.stderr.on('data', (data) => {
errorOutput += data.toString();
});
ytProcess.on('close', (code) => {
if (code === 0) {
try {
const lines = output.trim().split('\n');
// Find the line that looks like JSON (usually the last one if there are warnings)
let jsonInfo = null;
for (let i = lines.length - 1; i >= 0; i--) {
try {
jsonInfo = JSON.parse(lines[i]);
break;
} catch (e) {}
}
if (jsonInfo) {
resolve(jsonInfo);
} else {
reject(new Error('Não foi possível encontrar informações válidas no retorno do yt-dlp.'));
}
} catch (e) {
reject(new Error('Falha ao processar informações do vídeo.'));
}
} else {
// Check if error is related to cookies
if (errorOutput.includes('Netscape format cookies file')) {
reject(new Error('ERRO DE COOKIES: O arquivo cookies.txt selecionado não está no formato Netscape correto. Por favor, use uma extensão como "Get cookies.txt LOCALLY" para exportar corretamente.'));
} else {
reject(new Error(errorOutput || `Erro ao buscar informações (Código: ${code})`));
}
}
});
});
});
ipcMain.on('start-download', (event, { url, options, ytDlpPath, outputPath, videoInfo }) => {
const sender = event.sender;
const args = [...options, url];
const ytProcess = spawn(ytDlpPath || 'yt-dlp', args, {
cwd: outputPath || undefined,
env: { ...process.env, PYTHONIOENCODING: 'utf-8' }
});
let finalFilePath = null;
ytProcess.stdout.on('data', (data) => {
const message = data.toString();
sender.send('download-log', { url, message });
// Tentar encontrar o destino do arquivo (novo ou já baixado)
let destMatch = message.match(/\[(?:download|ExtractAudio)\] Destination:\s*(.+)/);
if (!destMatch) destMatch = message.match(/\[download\]\s*(.+?)\s*has already been downloaded/);
if (destMatch) {
finalFilePath = destMatch[1].trim();
}
// Try to parse progress
const progressMatch = message.match(/(\d+\.\d+)%/);
if (progressMatch) {
const progress = parseFloat(progressMatch[1]);
sender.send('download-progress', { url, progress });
}
});
ytProcess.stderr.on('data', (data) => {
const message = data.toString();
sender.send('download-log', { url, message, isError: true });
});
ytProcess.on('close', (code) => {
// Se o filepath for relativo (sem "C:\..."), nós o unimos com o outputPath, que é de onde o comando partiu (comando cd /d)
let filePathAbs = finalFilePath;
if (finalFilePath && !path.isAbsolute(finalFilePath) && outputPath) {
filePathAbs = path.join(outputPath, finalFilePath);
}
sender.send('download-complete', { url, success: code === 0, code, filePath: filePathAbs, videoInfo });
});
});
ipcMain.handle('upload-to-discord', async (event, { filePath, videoInfo, audioQuality, webhookUrl, discordMode, userName }) => {
try {
if (!fs.existsSync(filePath)) {
throw new Error("Arquivo não encontrado no disco: " + filePath);
}
const stats = fs.statSync(filePath);
const fileSizeInMB = stats.size / (1024 * 1024);
const formatDuration = (seconds) => {
if (!seconds) return 'N/A';
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60).toString().padStart(2, '0');
return `${m}:${s}`;
};
const form = new FormData();
const baseVideoUrl = videoInfo?.id ? `https://www.youtube.com/watch?v=${videoInfo.id}` : (videoInfo?.url || 'https://youtube.com');
const embed = {
author: {
name: `Usuário: ${userName || 'Desconhecido'}`,
icon_url: "https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/YouTube_full-color_icon_%282017%29.svg/1024px-YouTube_full-color_icon_%282017%29.svg.png"
},
title: videoInfo?.title || 'Download Processado',
url: baseVideoUrl,
description: `✅ **Arquivo processado e enviado com exclusividade!**\nEscute a faixa direto pelo player nativo do Discord abaixo.`,
color: 0x8b5cf6, // Um roxo premium moderno combinando com o painel novo
image: { url: videoInfo?.thumbnail },
fields: [
{ name: '📨 Enviado por', value: `\`${userName || 'Desconhecido'}\``, inline: true },
{ name: '👤 Criador do Conteúdo', value: `\`${videoInfo?.uploader || 'Desconhecido'}\``, inline: true },
{ name: '🎵 Qualidade / Peso', value: `\`${audioQuality || 'Premium'} (${fileSizeInMB.toFixed(2)}MB)\``, inline: true },
{ name: '⏱️ Duração', value: `\`${formatDuration(videoInfo?.duration)}\``, inline: true },
],
footer: { text: 'Bot de Orquestração Sequencial do YouTube Ultra', icon_url: "https://media.discordapp.net/attachments/1466580570904723771/1488288319052714014/icon.png?ex=69cd8d82&is=69cc3c02&hm=b3223bdf12a1b938657f78b7f0165587dbde6a8c754b2f4f8d51a7b53825d36c&=&format=webp&quality=lossless&width=794&height=794" },
timestamp: new Date().toISOString()
};
// Configuração do Botão Link Direto para o Usuário poder "Copiar / Abrir Link"
const components = [
{
type: 1,
components: [
{
type: 2,
style: 5,
label: "🔗 Abrir / Copiar o Link Original",
url: baseVideoUrl
}
]
}
];
if (fileSizeInMB > 25) {
embed.description = `⚠️ **Arquivo muito grande para o Discord!**\nO limite gratuito do Discord é 25MB.\nO arquivo foi salvo no seu computador em segurança.`;
embed.color = 0xFFA500;
form.append('payload_json', JSON.stringify({ embeds: [embed], components }));
await axios.post(webhookUrl, form, { headers: { ...form.getHeaders() }, maxBodyLength: Infinity });
throw new Error(`Cancelado: Arquivo muito grande (${fileSizeInMB.toFixed(1)}MB) para limite de 25MB do Discord. Mantido no PC.`);
}
form.append('payload_json', JSON.stringify({ embeds: [embed], components }));
form.append('file', fs.createReadStream(filePath));
await axios.post(webhookUrl, form, { headers: { ...form.getHeaders() }, maxBodyLength: Infinity });
// Deleta o arquivo se for EXCLUSIVO do discord
if (discordMode === 'discord') {
try {
fs.unlinkSync(filePath);
} catch (err) {
console.error('Erro ao excluir arquivo após enviar pro discord', err);
}
}
return true;
} catch (err) {
console.error(err);
throw err;
}
});
ipcMain.handle('save-log', async (event, { logsPath, logMessage, clearFirst }) => {
if (!logsPath) return false;
try {
if (!fs.existsSync(logsPath)) {
fs.mkdirSync(logsPath, { recursive: true });
}
const logFile = path.join(logsPath, 'latest.log');
if (clearFirst) {
fs.writeFileSync(logFile, logMessage + '\n');
} else {
fs.appendFileSync(logFile, logMessage + '\n');
}
return true;
} catch (err) {
console.error('Erro ao salvar log:', err);
return false;
}
});
ipcMain.on('open-logs-folder', (event, logsPath) => {
if (logsPath && fs.existsSync(logsPath)) {
require('child_process').exec(`explorer "${logsPath}"`);
}
});