@media-downloaders/v2 2.0.1

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.
@@ -0,0 +1,528 @@
1
+ /**
2
+ *
3
+ * Last update :
4
+ * Added rotation option for videos : left or right
5
+ *
6
+ */
7
+
8
+ const axios = require('axios');
9
+ const fs = require('fs');
10
+ const { alldown } = require("nayan-videos-downloader");
11
+ // Import btch-downloader as a fallback method
12
+ const { igdl, ttdl, fbdown, twitter, youtube } = require('btch-downloader');
13
+
14
+ const pathToFfmpeg = require('ffmpeg-ffprobe-static');
15
+ const ffmpeg = require('fluent-ffmpeg');
16
+ ffmpeg.setFfmpegPath(pathToFfmpeg.ffmpegPath);
17
+
18
+ // Liste des URL des plateformes de vidéos
19
+ const videoPlatforms = [
20
+ "https://open.spotify.com",
21
+ "https://www.facebook.com",
22
+ "https://facebook.com",
23
+ "https://www.tiktok.com",
24
+ "https://tiktok.com",
25
+ "https://www.x.com",
26
+ "https://x.com",
27
+ "https://www.twitter.com",
28
+ "https://twitter.com",
29
+ "https://www.instagram.com",
30
+ "https://instagram.com",
31
+ "https://www.youtube.com",
32
+ "https://youtube.com",
33
+ "https://youtu.be",
34
+ "https://www.pinterest.com",
35
+ "https://pinterest.com",
36
+ "https://drive.google.com",
37
+ "https://www.google.com/drive",
38
+ "https://www.capcut.com",
39
+ "https://capcut.com",
40
+ "https://www.likee.video",
41
+ "https://likee.video",
42
+ "https://www.threads.net",
43
+ "https://threads.net"
44
+ ];
45
+
46
+ // Blacklist links
47
+ const linkCant = [{ link: "https://vm.tiktok.com", reason: "Use real link like 'https://www.tiktok.com'. (just click on your link and copy the link in the browser)" }];
48
+
49
+ // Fonction pour vérifier si un lien correspond à une vidéo
50
+ const isVideoLink = (link) => {
51
+ return videoPlatforms.some(platform => link.startsWith(platform));
52
+ };
53
+
54
+ function blacklistLink(link) {
55
+ const found = linkCant.find(item => link.includes(item.link));
56
+ return found;
57
+ }
58
+
59
+ const defaultConfig = {
60
+ autocrop: false,
61
+ limitSizeMB: null,
62
+ rotation: null, // Added rotation parameter
63
+ };
64
+
65
+ // Fonction pour obtenir le type de plateforme à partir de l'URL
66
+ function getPlatformType(url) {
67
+ if (url.includes("instagram.com")) return "instagram";
68
+ if (url.includes("tiktok.com")) return "tiktok";
69
+ if (url.includes("facebook.com")) return "facebook";
70
+ if (url.includes("twitter.com") || url.includes("x.com")) return "twitter";
71
+ if (url.includes("youtube.com") || url.includes("youtu.be")) return "youtube";
72
+ return "unknown";
73
+ }
74
+
75
+ // Nouvelle fonction pour essayer la méthode btch-downloader comme fallback
76
+ async function tryFallbackDownload(url) {
77
+ const platform = getPlatformType(url);
78
+ let data;
79
+
80
+ try {
81
+ switch (platform) {
82
+ case "instagram":
83
+ data = await igdl(url);
84
+ break;
85
+ case "tiktok":
86
+ data = await ttdl(url);
87
+ break;
88
+ case "facebook":
89
+ data = await fbdown(url);
90
+ break;
91
+ case "twitter":
92
+ data = await twitter(url);
93
+ break;
94
+ case "youtube":
95
+ data = await youtube(url);
96
+ break;
97
+ default:
98
+ throw new Error("Platform not supported by fallback downloader");
99
+ }
100
+ //console.log(data)
101
+
102
+ // Extract the video URL from the response
103
+ let videoUrl = null;
104
+
105
+ if (data) {
106
+ // Handle different response formats for different platforms
107
+ if (platform === "instagram" && data && data.length > 0) {
108
+ videoUrl = data[0].url;
109
+ } else if (platform === "tiktok" && data && data.video && data.video[0]) {
110
+ videoUrl = data.video[0];
111
+ } else if (platform === "twitter" && data && data.url && data.url.length > 0 && data.url[1] && data.url[1].sd) {
112
+ videoUrl = data.url[1].sd
113
+ } else if (platform === "youtube" && data.link && data.link.length > 0) {
114
+ // Get the highest quality video URL
115
+ data.link.sort((a, b) => (b.size || 0) - (a.size || 0));
116
+ videoUrl = data.link[0].url;
117
+ }
118
+ }
119
+
120
+
121
+ return videoUrl;
122
+ } catch (error) {
123
+ console.log(`Fallback download failed for ${platform}: ${error.message}`);
124
+ return null;
125
+ }
126
+ }
127
+
128
+ const MediaDownloader = async (url, options = {}) => {
129
+ const config = { ...defaultConfig, ...options };
130
+
131
+ if (!url || !url.includes("http")) {
132
+ throw new Error("Please specify a video URL...");
133
+ }
134
+
135
+ url = extractUrlFromString(url);
136
+
137
+ if (blacklistLink(url)) {
138
+ let obj = blacklistLink(url);
139
+ if (obj.reason) {
140
+ throw new Error("URL not supported. " + obj.reason);
141
+ } else {
142
+ throw new Error("URL blacklisted and not supported");
143
+ }
144
+ }
145
+
146
+ else if (!isVideoLink(url)) {
147
+ const videofile = await downloadDirectVideo(url, config);
148
+
149
+ if (videofile) {
150
+ return videofile;
151
+ } else {
152
+ throw new Error("URL not supported. Please provide a video URL from a valid platform.");
153
+ }
154
+ }
155
+
156
+ await deleteTempVideos();
157
+
158
+ if(url.includes('youtube' || url.includes('youtu.be'))){
159
+ if (!options.cookie) {
160
+ throw new Error("YouTube download requires a cookie. Please provide a valid cookie.");
161
+ }
162
+ const videofile = await downloadYoutubeVideo(url, config, options.cookie);
163
+ if (videofile) {
164
+ return videofile;
165
+ } else {
166
+ throw new Error("URL not supported. Please provide a video URL from a valid platform.");
167
+ }
168
+ }
169
+
170
+ else if (url.includes("http")) {
171
+ try {
172
+ // Try the primary method first
173
+ const videofile = await downloadSmartVideo(url, config);
174
+ return videofile;
175
+ } catch (error) {
176
+ console.log(`Primary download method failed: ${error.message}`);
177
+ console.log(`Trying fallback method for ${url}...`);
178
+
179
+ // Try the fallback method if the primary fails
180
+ const fallbackUrl = await tryFallbackDownload(url);
181
+ if (fallbackUrl) {
182
+ // console.log(`Fallback URL found: ${fallbackUrl}`);
183
+ return await downloadDirectVideo(fallbackUrl, config);
184
+ } else {
185
+ throw new Error(`Failed to download video from ${url} with both methods.`);
186
+ }
187
+ }
188
+ } else {
189
+ throw new Error("Please specify a video URL from Instagram, YouTube, or TikTok...");
190
+ }
191
+ };
192
+
193
+ async function downloadSmartVideo(url, config) {
194
+ try {
195
+ let data = await alldown(url);
196
+
197
+ if (!data || !data.data) {
198
+ throw new Error("Can't download this link.");
199
+ }
200
+ if (data.data.low) {
201
+ url = data.data.low;
202
+ } else if (data.data.high) {
203
+ url = data.data.high;
204
+ } else {
205
+ throw new Error("Can't download this link.");
206
+ }
207
+
208
+ const response = await axios({
209
+ url: url,
210
+ method: 'GET',
211
+ responseType: 'stream'
212
+ });
213
+
214
+ let fileName = 'temp_video.mp4';
215
+ let count = 1;
216
+ while (fs.existsSync(fileName)) {
217
+ fileName = `temp_video_${count}.mp4`;
218
+ count++;
219
+ }
220
+
221
+ const videoWriter = fs.createWriteStream(fileName);
222
+ response.data.pipe(videoWriter);
223
+
224
+ return new Promise((resolve, reject) => {
225
+ videoWriter.on('finish', async () => {
226
+ try {
227
+ let processedFile = fileName;
228
+
229
+ // Apply rotation if specified
230
+ if (config.rotation) {
231
+ processedFile = await rotateVideo(processedFile, config.rotation);
232
+ }
233
+
234
+ // Apply autocrop if specified
235
+ if (config.autocrop) {
236
+ processedFile = await autoCrop(processedFile);
237
+ }
238
+
239
+ // Check and compress if size limit is specified
240
+ processedFile = await checkAndCompressVideo(processedFile, config.limitSizeMB);
241
+
242
+ resolve(processedFile);
243
+ } catch (error) {
244
+ reject(error);
245
+ }
246
+ });
247
+ videoWriter.on('error', (error) => reject(error));
248
+ });
249
+
250
+ } catch (error) {
251
+ throw new Error(`An error occurred while downloading video: ${error.message}`);
252
+ }
253
+ }
254
+
255
+ async function downloadDirectVideo(url, config) {
256
+ try {
257
+ const response = await axios({
258
+ url: url,
259
+ method: 'GET',
260
+ responseType: 'stream'
261
+ });
262
+
263
+ let fileName = 'temp_video.mp4';
264
+ let count = 1;
265
+ while (fs.existsSync(fileName)) {
266
+ fileName = `temp_video_${count}.mp4`;
267
+ count++;
268
+ }
269
+
270
+ const videoWriter = fs.createWriteStream(fileName);
271
+ response.data.pipe(videoWriter);
272
+
273
+ return new Promise((resolve, reject) => {
274
+ videoWriter.on('finish', async () => {
275
+ try {
276
+ let processedFile = fileName;
277
+
278
+ // Apply rotation if specified
279
+ if (config.rotation) {
280
+ processedFile = await rotateVideo(processedFile, config.rotation);
281
+ }
282
+
283
+ // Apply autocrop if specified
284
+ if (config.autocrop) {
285
+ processedFile = await autoCrop(processedFile);
286
+ }
287
+
288
+ // Check and compress if size limit is specified
289
+ processedFile = await checkAndCompressVideo(processedFile, config.limitSizeMB);
290
+
291
+ resolve(processedFile);
292
+ } catch (error) {
293
+ reject(error);
294
+ }
295
+ });
296
+ videoWriter.on('error', (error) => reject(error));
297
+ });
298
+ } catch (error) {
299
+ throw new Error(`An error occurred while downloading video: ${error.message}`);
300
+ }
301
+ }
302
+
303
+ async function downloadYoutubeVideo(url, config, cookie) {
304
+ try {
305
+ const info = await ytdl.getInfo(url, {
306
+ requestOptions: {
307
+ headers: {
308
+ cookie: cookie,
309
+ },
310
+ },
311
+ });
312
+
313
+ const durationSeconds = parseInt(info.videoDetails.lengthSeconds, 10);
314
+
315
+ if (durationSeconds > 60) {
316
+ throw new Error('❌ The video is longer than 1 minute. Aborting.');
317
+ }
318
+
319
+ const formats = info.formats.filter(format => {
320
+ return format.contentLength &&
321
+ parseInt(format.contentLength) <= 10 * 1024 * 1024 && // ≤ 10 MB
322
+ format.hasAudio && format.hasVideo;
323
+ });
324
+
325
+ if (formats.length === 0) {
326
+ throw new Error('❌ No format found under 10 MB.');
327
+ }
328
+
329
+ const bestFormat = formats.sort((a, b) => b.height - a.height)[0];
330
+
331
+ let fileName = 'temp_video.mp4';
332
+ let count = 1;
333
+ while (fs.existsSync(fileName)) {
334
+ fileName = `temp_video_${count}.mp4`;
335
+ count++;
336
+ }
337
+
338
+ const videoStream = ytdl(url, {
339
+ format: bestFormat,
340
+ requestOptions: {
341
+ headers: {
342
+ cookie: cookie,
343
+ },
344
+ },
345
+ });
346
+
347
+ const videoWriter = fs.createWriteStream(fileName);
348
+ videoStream.pipe(videoWriter);
349
+
350
+ return new Promise((resolve, reject) => {
351
+ videoWriter.on('finish', async () => {
352
+ try {
353
+ let processedFile = fileName;
354
+
355
+ // Apply rotation if specified
356
+ if (config.rotation) {
357
+ processedFile = await rotateVideo(processedFile, config.rotation);
358
+ }
359
+
360
+ // Apply autocrop if specified
361
+ if (config.autocrop) {
362
+ processedFile = await autoCrop(processedFile);
363
+ }
364
+
365
+ // Check and compress if size limit is specified
366
+ processedFile = await checkAndCompressVideo(processedFile, config.limitSizeMB);
367
+
368
+ resolve(processedFile);
369
+ } catch (error) {
370
+ reject(error);
371
+ }
372
+ });
373
+ videoWriter.on('error', (error) => reject(error));
374
+ });
375
+
376
+ } catch (error) {
377
+ throw new Error(`An error occurred while downloading the YouTube video: ${error.message}`);
378
+ }
379
+ }
380
+ // New function to handle video rotation
381
+ async function rotateVideo(fileName, rotation) {
382
+ const outputPath = fileName.split('.')[0] + "_rotated.mp4";
383
+
384
+ // Determine rotation angle
385
+ let angle;
386
+ switch (rotation.toLowerCase()) {
387
+ case "left":
388
+ angle = "90";
389
+ break;
390
+ case "right":
391
+ angle = "270";
392
+ break;
393
+ case "180":
394
+ case "flip":
395
+ angle = "180";
396
+ break;
397
+ default:
398
+ throw new Error("Invalid rotation value. Use 'left', 'right', '180', or 'flip'");
399
+ }
400
+
401
+ return new Promise((resolve, reject) => {
402
+ ffmpeg(fileName)
403
+ .videoFilters(`transpose=${angle === "90" ? 2 : angle === "270" ? 1 : 0}${angle === "180" ? ",hflip,vflip" : ""}`)
404
+ .output(outputPath)
405
+ .on('end', () => {
406
+ // Delete the original file since we now have the rotated version
407
+ fs.unlinkSync(fileName);
408
+ resolve(outputPath);
409
+ })
410
+ .on('error', (err) => {
411
+ reject(new Error(`Error during video rotation: ${err.message}`));
412
+ })
413
+ .run();
414
+ });
415
+ }
416
+
417
+ function extractUrlFromString(text) {
418
+ const urlRegex = /(https?:\/\/[^\s]+)/;
419
+ const match = text.match(urlRegex);
420
+ if (match) {
421
+ return match[0];
422
+ } else {
423
+ return null;
424
+ }
425
+ }
426
+
427
+ async function deleteTempVideos() {
428
+ try {
429
+ const files = fs.readdirSync("./");
430
+ const tempVideoFiles = files.filter(file => file.startsWith('temp_video'));
431
+
432
+ for (const file of tempVideoFiles) {
433
+ fs.unlinkSync("./" + file);
434
+ }
435
+ } catch (error) {
436
+ throw new Error(`Error deleting temp_video files: ${error.message}`);
437
+ }
438
+ }
439
+
440
+ async function autoCrop(fileName) {
441
+ const inputPath = fileName;
442
+ const outputPath = fileName.split('.')[0] + "_cropped.mp4";
443
+
444
+ return new Promise((resolve, reject) => {
445
+ ffmpeg(inputPath)
446
+ .videoFilters('cropdetect')
447
+ .output(outputPath)
448
+ .on('end', function (stdout, stderr) {
449
+ const crop = parseCrop(stderr);
450
+ if (!crop) {
451
+ reject(new Error('Erreur: Impossible de détecter les valeurs de crop.'));
452
+ return;
453
+ }
454
+
455
+ ffmpeg(inputPath)
456
+ .videoFilters(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`)
457
+ .on('end', () => {
458
+ // Delete the original file since we now have the cropped version
459
+ fs.unlinkSync(inputPath);
460
+ resolve(outputPath);
461
+ })
462
+ .on('error', (err) => {
463
+ reject(new Error('Erreur lors du rognage: ' + err.message));
464
+ })
465
+ .save(outputPath);
466
+ })
467
+ .on('error', (err) => {
468
+ reject(new Error('Erreur lors de la détection du crop: ' + err.message));
469
+ })
470
+ .run();
471
+ });
472
+
473
+ function parseCrop(stderr) {
474
+ const cropRegex = /crop=([0-9]+):([0-9]+):([0-9]+):([0-9]+)/;
475
+ const match = stderr.match(cropRegex);
476
+ if (match) {
477
+ return {
478
+ width: match[1],
479
+ height: match[2],
480
+ x: match[3],
481
+ y: match[4],
482
+ };
483
+ } else {
484
+ return null;
485
+ }
486
+ }
487
+ }
488
+
489
+ async function checkAndCompressVideo(filePath, limitSizeMB) {
490
+ if (!limitSizeMB) return filePath;
491
+
492
+ const stats = fs.statSync(filePath);
493
+ const fileSizeInMB = stats.size / (1024 * 1024);
494
+
495
+ if (fileSizeInMB <= limitSizeMB) {
496
+ return filePath;
497
+ }
498
+
499
+ const compressedFilePath = filePath.split('.')[0] + "_compressed.mp4";
500
+
501
+ return new Promise((resolve, reject) => {
502
+ ffmpeg(filePath)
503
+ .outputOptions([
504
+ '-vf', 'scale=640:-2',
505
+ '-b:v', '500k',
506
+ '-b:a', '128k',
507
+ '-movflags', 'faststart'
508
+ ])
509
+ .output(compressedFilePath)
510
+ .on('end', () => {
511
+ fs.unlinkSync(filePath);
512
+ resolve(compressedFilePath);
513
+ })
514
+ .on('error', (err) => {
515
+ reject(new Error('Erreur lors de la compression: ' + err.message));
516
+ })
517
+ .run();
518
+ });
519
+ }
520
+
521
+
522
+
523
+
524
+
525
+
526
+ MediaDownloader.isVideoLink = isVideoLink;
527
+
528
+ module.exports = MediaDownloader;