-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
385 lines (348 loc) · 15.2 KB
/
index.js
File metadata and controls
385 lines (348 loc) · 15.2 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
const { app, BrowserWindow, session, screen } = require('electron');
const { exec } = require('child_process');
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');
const https = require('https'); // Add this import
const { v4: uuidv4 } = require('uuid');
const { Decoder } = require('ts-ebml');
const { shell } = require('electron');
let savePath = path.join(os.homedir(), 'Downloads');
const expressApp = express();
let serverPort, ytWin;
let youtubeCookies = "";
const baseDir = path.join(os.homedir(), 'Library/Application Support/videosnatcher');
const logsDir = path.join(baseDir, 'logs');
const liveLogPath = path.join(logsDir, 'live.log');
const userDataDir = path.join(baseDir, 'UserData');
const executablesDir = path.join(baseDir, 'AppExecutables');
// Ensure logs directory exists and clear log file on startup
if (!fs.existsSync(logsDir)) fs.mkdirSync(logsDir, { recursive: true });
fs.writeFileSync(liveLogPath, '', 'utf8');
// Override console.log and console.error to also write to a log file
const logStream = fs.createWriteStream(liveLogPath, { flags: 'a' });
['log', 'error'].forEach(method => {
const original = console[method];
console[method] = (...args) => {
original(...args);
logStream.write(args.join(' ') + '\n');
};
});
function convertCookiesToNetscapeFormat(cookies) {
return [
"# Netscape HTTP Cookie File", // Required header
...cookies.map(cookie => {
let domain = cookie.domain || "";
if (!domain.startsWith(".")) {
domain = "." + domain; // Ensure proper domain format
}
return [
domain,
"TRUE", // Include subdomains (assumed safe for most use cases)
cookie.path || "/", // Default to root path if missing
cookie.secure ? "TRUE" : "FALSE", // Secure flag
Math.floor(cookie.expirationDate || 0), // Ensure it's a valid timestamp
cookie.name,
cookie.value
].join("\t");
})
].join("\n");
}
function ensureFile(filePath, url) {
if (!fs.existsSync(filePath)) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
if (url) {
const file = fs.createWriteStream(filePath);
https.get(url, (response) => {
if (response.statusCode === 200) {
response.pipe(file);
file.on('finish', () => {
file.close();
fs.chmodSync(filePath, '755'); // Make the file executable
console.log(`${path.basename(filePath)} downloaded and made executable.`);
});
} else {
console.error(`Failed to download ${url}. Status code: ${response.statusCode}`);
}
}).on('error', (err) => {
console.error(`Error downloading ${url}:`, err.message);
});
} else {
fs.writeFileSync(filePath, '', 'utf8');
console.log(`${path.basename(filePath)} created successfully.`);
}
} else {
console.log(`${path.basename(filePath)} already exists.`);
}
}
function parseVideoFormats(output) {
const filtered = output.split('\n').filter(line => {
line = line.trim();
if (!line) return false;
if (/(Downloading|Available formats|ID|-------------------)/.test(line)) return false;
const matches = line.match(/\[[^\]]*\]/g);
if (matches) {
for (const m of matches) {
const content = m.slice(1, -1);
// Allow only if content has exactly two letters.
if (!/^[A-Za-z]{2}$/.test(content)) return false;
}
}
return true;
});
const result = filtered.map(line => {
if (line.toLowerCase().includes('quic')) return null; // Skip lines containing 'quic'
let parts = line.split(/\s{2,}/).map(x => x.trim()).flatMap(part =>
part.split('|').map(x => x.trim()).filter(Boolean)
);
const firstSplit = parts[0].split(' ').map(x => x.trim());
parts[0] = firstSplit[0];
parts.splice(1, 0, firstSplit[1] || '', firstSplit.slice(2).join(' ') || '');
parts = parts.flatMap(part => part.split(' ').map(x => x.trim())).filter(x => x && x !== 'unknown' && x !== 'Original');
for (let i = 0; i < parts.length - 1; i++) {
if ((parts[i] === 'video' && parts[i + 1] === 'only') ||
(parts[i] === 'audio' && parts[i + 1] === 'only')) {
parts[i] = `${parts[i]} only`;
parts.splice(i + 1, 1);
break;
}
}
return parts;
}).filter(parts => parts && parts.length > 1 && !parts.includes('images'));
// Remove duplicate entries
const unique = Array.from(new Set(result.map(a => JSON.stringify(a)))).map(e => JSON.parse(e));
return unique.map(item => Array.from(new Set(item)));
}
function createMainWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { nodeIntegration: true }
});
win.loadURL(`file://${__dirname}/web/index.html?port=${serverPort}`);
win.on('closed', () => app.quit());
}
function createYoutubePopup() {
const { width: screenWidth, height: screenHeight } = screen.getPrimaryDisplay().workAreaSize;
const winWidth = Math.min(600, Math.floor(screenWidth * 0.7));
const infoHeight = Math.min(200, Math.floor(screenHeight * 0.2));
const ytHeight = Math.min(400, Math.floor(screenHeight * 0.3));
const startX = Math.floor((screenWidth - winWidth) / 2);
const infoY = Math.floor((screenHeight - (infoHeight + ytHeight)) / 2);
const ytY = infoY + infoHeight;
const infoWin = new BrowserWindow({
x: startX,
y: infoY,
width: winWidth,
height: infoHeight,
resizable: false,
webPreferences: { nodeIntegration: true }
});
ytWin = new BrowserWindow({
x: startX,
y: ytY,
width: winWidth,
height: ytHeight,
resizable: false,
webPreferences: { nodeIntegration: true }
});
ytWin.loadURL('https://youtube.com');
ytWin.on('closed', () => {
if (!infoWin.isDestroyed()) infoWin.close();
youtubeCookies = "";
});
infoWin.loadURL(`file://${__dirname}/web/yt_cookie_retriver.html?port=${serverPort}`);
infoWin.on('closed', () => {
if (!ytWin.isDestroyed()) ytWin.close();
youtubeCookies = "";
});
}
function createListWindow() {
const win = new BrowserWindow({
width: 450,
height: 600,
webPreferences: { nodeIntegration: true }
});
win.loadURL(`file://${__dirname}/web/supported.html`);
}
// Start express server on a random port
const server = expressApp.listen(0, () => {
serverPort = server.address().port;
console.log(`Server running on port ${serverPort}`);
});
expressApp.get('/get_vid_options', (req, res) => {
const videoUrl = req.query.url;
const vimeoPass = req.query.vimeoPass;
if (!videoUrl) return res.status(400).send('Missing "url" parameter');
let parameters = videoUrl.includes("youtube.com")
? ` --cookies "${path.join(userDataDir, 'yt-cookie.txt')}"`
: '';
parameters = vimeoPass
? ` --video-password "${vimeoPass}"`
: '';
const command = `"${path.join(executablesDir, 'yt-dlp-mac')}"${parameters} -F "${videoUrl}"`;
exec(command, { encoding: 'utf8', maxBuffer: 1024 * 1024 }, (error, stdout) => {
if (error) {
console.error(error);
return res.status(500).send('Error fetching video options');
}
try {
const parsed = parseVideoFormats(stdout);
res.send(parsed);
} catch (e) {
console.error(e);
res.status(500).send('Error parsing video options');
}
});
});
expressApp.get('/download_vid', (req, res) => {
const videoUrl = req.query.url;
const vimeoPass = req.query.vimeoPass;
const videoFormat = req.query.id;
const videoType = req.query.format;
if (!videoUrl) return res.status(400).send('Missing "url" parameter');
if (!videoFormat) return res.status(400).send('Missing "format" parameter');
if (!videoType) return res.status(400).send('Missing "type" parameter');
let parameters = videoUrl.includes("youtube.com")
? ` --cookies "${path.join(userDataDir, 'yt-cookie.txt')}"`
: '';
parameters = vimeoPass && vimeoPass !== undefined
? ` --video-password "${vimeoPass}"`
: '';
if (videoFormat.includes('vid') && videoFormat.includes('aud')) {
const video_download_id = uuidv4();
const audio_download_id = uuidv4();
const [videoId, audioId] = videoFormat
.split(',')
.map(part => part.split(':')[1].trim());
const [videoForm, audioForm] = videoType
.split(',')
.map(part => part.split(':')[1].trim());
// Download video parts
const download_path = `${path.join(baseDir, 'OutputFiles')}/${video_download_id}.${videoForm}`
const vid_command = `"${path.join(executablesDir, 'yt-dlp-mac')}"${parameters} -f "${videoId}" "${videoUrl}" -o "${path.join(baseDir, 'OutputFiles/tmp')}/${video_download_id}.${videoForm}"`;
const aud_command = `"${path.join(executablesDir, 'yt-dlp-mac')}"${parameters} -f "${audioId}" "${videoUrl}" -o "${path.join(baseDir, 'OutputFiles/tmp')}/${audio_download_id}.${audioForm}"`;
exec(aud_command, { encoding: 'utf8', maxBuffer: 1024 * 1024 }, (error, stdout) => {
if (error) {
console.error(error);
return res.status(500).send('Error downloading audio');
}
try {
console.log('Audio Downloaded');
exec(vid_command, { encoding: 'utf8', maxBuffer: 1024 * 1024 }, (error, stdout) => {
if (error) {
console.error(error);
return res.status(500).send('Error downloading video');
}
try {
console.log('Video Downloaded');
// combine video and audio
const combine_command = `"${path.join(executablesDir, 'ffmpeg-mac')}" -i "${path.join(baseDir, 'OutputFiles/tmp')}/${video_download_id}.${videoForm}" -i "${path.join(baseDir, 'OutputFiles/tmp')}/${audio_download_id}.${audioForm}" -c:v copy -map 0:v:0 -map 1:a:0 -shortest "${download_path}"`;
exec(combine_command, { encoding: 'utf8', maxBuffer: 1024 * 1024 }, (error, stdout) => {
if (error) {
console.error('Error combining video and audio:', error.message);
return res.status(500).send('Error combining video and audio');
}
console.log('FFmpeg Output:', stdout); // Log stdout for debugging
try {
console.log('Video and Audio Combined');
fs.rm(path.join(baseDir, 'OutputFiles/tmp'), { recursive: true, force: true }, (err) => {
if (err) {
console.error('Error removing temporary directory:', err);
} else {
console.log('Temporary directory removed successfully.');
res.send(JSON.stringify({ path: download_path }));
}
});
} catch (e) {
console.error(e);
res.status(500).send('Error combining video and audio');
}
});
} catch (e) {
console.error(e);
res.status(500).send('Error downloading video');
}
});
} catch (e) {
console.error(e);
res.status(500).send('Error downloading audio');
}
});
} else {
const video_download_id = uuidv4();
const command = `"${path.join(executablesDir, 'yt-dlp-mac')}"${parameters} -f "${videoFormat}" "${videoUrl}" -o "${path.join(baseDir, 'OutputFiles')}/${video_download_id}.${videoType}"`;
exec(command, { encoding: 'utf8', maxBuffer: 1024 * 1024 }, (error, stdout) => {
if (error) {
console.error(error);
return res.status(500).send('Error downloading video');
}
try {
const download_path = `${path.join(baseDir, 'OutputFiles')}/${video_download_id}.${videoType}`
res.send(JSON.stringify({ path: download_path }));
} catch (e) {
console.error(e);
res.status(500).send('Error downloading video');
}
});
}
});
expressApp.get('/show_supported_list', (req, res) => {
createListWindow();
res.send('Success');
});
expressApp.get('/run_youtube_signin', (req, res) => {
createYoutubePopup();
res.send('Success');
});
expressApp.get('/get_youtube_cookies', async (req, res) => {
try {
const cookies = await session.defaultSession.cookies.get({ url: 'https://youtube.com' });
youtubeCookies = convertCookiesToNetscapeFormat(cookies);
res.send("Success");
} catch (error) {
console.error("Error getting YouTube cookies:", error);
res.status(500).send('Error getting YouTube cookies');
}
});
expressApp.get('/finish_youtube_cookies', (req, res) => {
fs.writeFileSync(path.join(userDataDir, 'yt-cookie.txt'), youtubeCookies);
res.send("Success");
if (ytWin && !ytWin.isDestroyed()) ytWin.close();
});
app.whenReady().then(() => {
ensureFile(path.join(userDataDir, 'yt-cookie.txt'));
ensureFile(
path.join(executablesDir, 'yt-dlp-mac'),
'https://jemcats.software/github_pages/VideoSnatcher/files/yt-dlp-mac'
);
exec('/usr/sbin/softwareupdate --install-rosetta --agree-to-license', (error, stdout, stderr) => {
if (error) {
console.error(`Error installing Rosetta: ${error.message}`);
} else {
console.log('Rosetta installed successfully.');
}
});
ensureFile(
path.join(executablesDir, 'ffmpeg-mac'),
'https://jemcats.software/github_pages/VideoSnatcher/files/ffmpeg-mac'
);
createMainWindow();
});
expressApp.get('/get_vid', (req, res) => {
const videoPath = req.query.path;
if (!videoPath) return res.status(400).send('Missing "path" parameter');
const destinationPath = path.join(savePath, path.basename(videoPath));
fs.rename(videoPath, destinationPath, (err) => {
if (err) {
console.error('Error moving file:', err);
return res.status(500).send('Error moving file');
}
shell.showItemInFolder(destinationPath);
res.send(JSON.stringify({ path: destinationPath }));
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});