-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo.js
More file actions
240 lines (221 loc) · 9.94 KB
/
Copy pathvideo.js
File metadata and controls
240 lines (221 loc) · 9.94 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
const axios = require('axios');
const yts = require('yt-search');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);
const princeVideoApi = {
base: 'https://api.princetechn.com/api/download/ytmp4',
apikey: process.env.PRINCE_API_KEY || 'prince',
async fetchMeta(videoUrl) {
const params = new URLSearchParams({ apikey: this.apikey, url: videoUrl });
const url = `${this.base}?${params.toString()}`;
const { data } = await axios.get(url, { timeout: 20000, headers: { 'user-agent': 'Mozilla/5.0', accept: 'application/json' } });
return data;
}
};
async function videoCommand(sock, chatId, message) {
try {
const text = message.message?.conversation || message.message?.extendedTextMessage?.text;
const searchQuery = text.split(' ').slice(1).join(' ').trim();
if (!searchQuery) {
await sock.sendMessage(chatId, { text: 'What video do you want to download?' }, { quoted: message });
return;
}
// Determine if input is a YouTube link
let videoUrl = '';
let videoTitle = '';
let videoThumbnail = '';
if (searchQuery.startsWith('http://') || searchQuery.startsWith('https://')) {
videoUrl = searchQuery;
} else {
// Search YouTube for the video
const { videos } = await yts(searchQuery);
if (!videos || videos.length === 0) {
await sock.sendMessage(chatId, { text: 'No videos found!' }, { quoted: message });
return;
}
videoUrl = videos[0].url;
videoTitle = videos[0].title;
videoThumbnail = videos[0].thumbnail;
}
// Send thumbnail immediately
try {
const ytId = (videoUrl.match(/(?:youtu\.be\/|v=)([a-zA-Z0-9_-]{11})/) || [])[1];
const thumb = videoThumbnail || (ytId ? `https://i.ytimg.com/vi/${ytId}/sddefault.jpg` : undefined);
const captionTitle = videoTitle || searchQuery;
if (thumb) {
await sock.sendMessage(chatId, {
image: { url: thumb },
caption: `*${captionTitle}*\nDownloading...`
}, { quoted: message });
}
} catch (e) { console.error('[VIDEO] thumb error:', e?.message || e); }
// Validate YouTube URL
let urls = videoUrl.match(/(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.|m\.)?youtube\.com\/(?:watch\?v=|v\/|embed\/|shorts\/|playlist\?list=)?)([a-zA-Z0-9_-]{11})/gi);
if (!urls) {
await sock.sendMessage(chatId, { text: 'This is not a valid YouTube link!' }, { quoted: message });
return;
}
// PrinceTech video API
let videoDownloadUrl = '';
let title = '';
try {
const meta = await princeVideoApi.fetchMeta(videoUrl);
if (meta?.success && meta?.result?.download_url) {
videoDownloadUrl = meta.result.download_url;
title = meta.result.title || 'video';
} else {
await sock.sendMessage(chatId, { text: 'Failed to fetch video from the API.' }, { quoted: message });
return;
}
} catch (e) {
console.error('[VIDEO] prince api error:', e?.message || e);
await sock.sendMessage(chatId, { text: 'Failed to fetch video from the API.' }, { quoted: message });
return;
}
const filename = `${title}.mp4`;
// Try sending the video directly from the remote URL (like play.js)
try {
await sock.sendMessage(chatId, {
video: { url: videoDownloadUrl },
mimetype: 'video/mp4',
fileName: filename,
caption: `*${title}*\n\n> *_Downloaded by JINNY OF ASHES BOT XMD_*`
}, { quoted: message });
return;
} catch (directSendErr) {
console.log('[video.js] Direct send from URL failed:', directSendErr.message);
}
// If direct send fails, fallback to downloading and converting
// Download the video file first
const tempDir = path.join(__dirname, '../temp');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
const tempFile = path.join(tempDir, `${Date.now()}.mp4`);
const convertedFile = path.join(tempDir, `converted_${Date.now()}.mp4`);
let buffer;
let download403 = false;
try {
const videoRes = await axios.get(videoDownloadUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Referer': 'https://youtube.com/'
},
responseType: 'arraybuffer'
});
buffer = Buffer.from(videoRes.data);
} catch (err) {
if (err.response && err.response.status === 403) {
// try alternate URL pattern as best-effort
download403 = true;
} else {
await sock.sendMessage(chatId, { text: 'Failed to download the video file.' }, { quoted: message });
return;
}
}
// Fallback: try another URL if 403
if (download403) {
let altUrl = videoDownloadUrl.replace(/(cdn|s)\d+/, 's5');
try {
const videoRes = await axios.get(altUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Referer': 'https://youtube.com/'
},
responseType: 'arraybuffer'
});
buffer = Buffer.from(videoRes.data);
} catch (err2) {
await sock.sendMessage(chatId, { text: 'Failed to download the video file from alternate CDN.' }, { quoted: message });
return;
}
}
if (!buffer || buffer.length < 1024) {
await sock.sendMessage(chatId, { text: 'Downloaded file is empty or too small.' }, { quoted: message });
return;
}
fs.writeFileSync(tempFile, buffer);
try {
await execPromise(`ffmpeg -i "${tempFile}" -c:v libx264 -c:a aac -preset veryfast -crf 26 -movflags +faststart "${convertedFile}"`);
// Check if conversion was successful
if (!fs.existsSync(convertedFile)) {
await sock.sendMessage(chatId, { text: 'Converted file missing.' }, { quoted: message });
return;
}
const stats = fs.statSync(convertedFile);
const maxSize = 62 * 1024 * 1024; // 62MB
if (stats.size > maxSize) {
await sock.sendMessage(chatId, { text: 'Video is too large to send on WhatsApp.' }, { quoted: message });
return;
}
// Try sending the converted video
try {
await sock.sendMessage(chatId, {
video: { url: convertedFile },
mimetype: 'video/mp4',
fileName: filename,
caption: `*${title}*`
}, { quoted: message });
} catch (sendErr) {
console.error('[VIDEO] send url failed, trying buffer:', sendErr?.message || sendErr);
const videoBuffer = fs.readFileSync(convertedFile);
await sock.sendMessage(chatId, {
video: videoBuffer,
mimetype: 'video/mp4',
fileName: filename,
caption: `*${title}*`
}, { quoted: message });
}
} catch (conversionError) {
console.error('[VIDEO] conversion failed, trying original file:', conversionError?.message || conversionError);
try {
if (!fs.existsSync(tempFile)) {
await sock.sendMessage(chatId, { text: 'Temp file missing.' }, { quoted: message });
return;
}
const origStats = fs.statSync(tempFile);
const maxSize = 62 * 1024 * 1024; // 62MB
if (origStats.size > maxSize) {
await sock.sendMessage(chatId, { text: 'Video is too large to send on WhatsApp.' }, { quoted: message });
return;
}
} catch {}
// Try sending the original file
try {
await sock.sendMessage(chatId, {
video: { url: tempFile },
mimetype: 'video/mp4',
fileName: filename,
caption: `*${title}*`
}, { quoted: message });
} catch (sendErr2) {
console.error('[VIDEO] send original url failed, trying buffer:', sendErr2?.message || sendErr2);
const videoBuffer = fs.readFileSync(tempFile);
await sock.sendMessage(chatId, {
video: videoBuffer,
mimetype: 'video/mp4',
fileName: filename,
caption: `*${title}*`
}, { quoted: message });
}
}
// Clean up temp files
setTimeout(() => {
try {
if (fs.existsSync(tempFile)) {
fs.unlinkSync(tempFile);
}
if (fs.existsSync(convertedFile)) {
fs.unlinkSync(convertedFile);
}
} catch (cleanupErr) {
console.error('[VIDEO] cleanup error:', cleanupErr?.message || cleanupErr);
}
}, 3000);
} catch (error) {
console.error('[VIDEO] Command Error:', error?.message || error);
await sock.sendMessage(chatId, { text: 'Download failed: ' + (error?.message || 'Unknown error') }, { quoted: message });
}
}
module.exports = videoCommand;