Advertisement
pvcodes

Untitled

Mar 18th, 2025
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require("fs").promises;
  2. const path = require("path");
  3.  
  4. class GoogleDriveDownloader {
  5.     constructor(dirName = `downloads_${Date.now()}`) {
  6.         this.downloadDir = path.join(process.cwd(), dirName);
  7.         this.downloadedFiles = [];
  8.         this.failedDownloads = [];
  9.     }
  10.  
  11.     // Create download directory if it doesn't exist
  12.     async createDownloadDirectory() {
  13.         try {
  14.             await fs.mkdir(this.downloadDir, { recursive: true });
  15.             console.log(`Download directory created: ${this.downloadDir}`);
  16.         } catch (error) {
  17.             console.error("Error creating download directory:", error);
  18.             throw error;
  19.         }
  20.     }
  21.  
  22.     // Extract file ID from Google Drive link
  23.     extractFileId(link) {
  24.         const match = link.match(/\/d\/([^/]+)/);
  25.         return match ? match[1] : null;
  26.     }
  27.  
  28.     // Generate safe filename
  29.     generateSafeFilename(originalFilename, fileId) {
  30.         return originalFilename
  31.             ? originalFilename.replace(/[^a-z0-9.]/gi, "_").replace(/__+/g, "_")
  32.             : `file-${fileId}-${Date.now()}`;
  33.     }
  34.  
  35.     // Download single file
  36.     async downloadFile(fileLink) {
  37.         try {
  38.             // Extract file ID
  39.             const fileId = this.extractFileId(fileLink);
  40.             if (!fileId) {
  41.                 throw new Error(`Invalid file link: ${fileLink}`);
  42.             }
  43.  
  44.             // Construct download URL
  45.             const downloadUrl = `https://drive.google.com/uc?export=download&id=${fileId}`;
  46.  
  47.             // Fetch file
  48.             const response = await fetch(downloadUrl, {
  49.                 method: "GET",
  50.                 headers: {
  51.                     "User-Agent": "Mozilla/5.0",
  52.                 },
  53.             });
  54.  
  55.             if (!response.ok) {
  56.                 throw new Error(`HTTP error! status: ${response.status}`);
  57.             }
  58.  
  59.             // Extract filename
  60.             const contentDisposition = response.headers.get(
  61.                 "Content-Disposition"
  62.             );
  63.             const originalFilename = contentDisposition
  64.                 ? contentDisposition.split("filename=")[1]?.replace(/['"]/g, "")
  65.                 : `file-${fileId}`;
  66.  
  67.             const safeFilename = this.generateSafeFilename(
  68.                 originalFilename,
  69.                 fileId
  70.             );
  71.             const downloadPath = path.join(this.downloadDir, safeFilename);
  72.  
  73.             // Convert response to buffer
  74.             const arrayBuffer = await response.arrayBuffer();
  75.             const buffer = Buffer.from(arrayBuffer);
  76.  
  77.             // Write file
  78.             await fs.writeFile(downloadPath, buffer);
  79.  
  80.             return {
  81.                 link: fileLink,
  82.                 path: downloadPath,
  83.                 filename: safeFilename,
  84.                 status: "downloaded",
  85.             };
  86.         } catch (error) {
  87.             return {
  88.                 link: fileLink,
  89.                 error: error.message,
  90.                 status: "failed",
  91.             };
  92.         }
  93.     }
  94.  
  95.     // Download multiple files
  96.     async downloadFiles(fileLinks, options = {}) {
  97.         const { concurrency = 3, onProgress = null } = options;
  98.  
  99.         // Create download directory
  100.         await this.createDownloadDirectory();
  101.  
  102.         // Reset download tracking
  103.         this.downloadedFiles = [];
  104.         this.failedDownloads = [];
  105.  
  106.         // Limit concurrent downloads
  107.         const downloadChunks = [];
  108.         for (let i = 0; i < fileLinks.length; i += concurrency) {
  109.             downloadChunks.push(fileLinks.slice(i, i + concurrency));
  110.         }
  111.  
  112.         // Process download chunks
  113.         for (const chunk of downloadChunks) {
  114.             const chunkResults = await Promise.all(
  115.                 chunk.map((link) => this.downloadFile(link))
  116.             );
  117.  
  118.             // Process results
  119.             chunkResults.forEach((result) => {
  120.                 if (result.status === "downloaded") {
  121.                     this.downloadedFiles.push(result);
  122.                 } else {
  123.                     this.failedDownloads.push(result);
  124.                 }
  125.  
  126.                 // Call progress callback if provided
  127.                 if (onProgress && typeof onProgress === "function") {
  128.                     onProgress({
  129.                         total: fileLinks.length,
  130.                         downloaded: this.downloadedFiles.length,
  131.                         failed: this.failedDownloads.length,
  132.                     });
  133.                 }
  134.             });
  135.         }
  136.  
  137.         // Return download summary
  138.         return {
  139.             total: fileLinks.length,
  140.             successful: this.downloadedFiles.length,
  141.             failed: this.failedDownloads.length,
  142.             downloadDir: this.downloadDir,
  143.             downloadedFiles: this.downloadedFiles,
  144.             failedDownloads: this.failedDownloads,
  145.         };
  146.     }
  147. }
  148.  
  149. // Node.js Usage Example
  150. async function nodeDownload() {
  151.     const downloader = new GoogleDriveDownloader(); // Creates a timestamped directory
  152.     const links = [
  153.         "https://drive.google.com/file/d/10N5oXw0yKu1QuTcXcPEU9-RIXcw8nisu/view?usp=drive_link",
  154.         "https://drive.google.com/file/d/10N5oXw0yKu1QuTcXcPEU9-RIXcw8nisu/view?usp=drive_link",
  155.     ];
  156.  
  157.     try {
  158.         const result = await downloader.downloadFiles(links, {
  159.             concurrency: 2,
  160.             onProgress: (progress) => {
  161.                 console.log("Download Progress:", progress);
  162.             },
  163.         });
  164.  
  165.         console.log("Download Complete:", result);
  166.     } catch (error) {
  167.         console.error("Download failed:", error);
  168.     }
  169. }
  170.  
  171. nodeDownload();
  172.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement