Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require("fs").promises;
- const path = require("path");
- class GoogleDriveDownloader {
- constructor(dirName = `downloads_${Date.now()}`) {
- this.downloadDir = path.join(process.cwd(), dirName);
- this.downloadedFiles = [];
- this.failedDownloads = [];
- }
- // Create download directory if it doesn't exist
- async createDownloadDirectory() {
- try {
- await fs.mkdir(this.downloadDir, { recursive: true });
- console.log(`Download directory created: ${this.downloadDir}`);
- } catch (error) {
- console.error("Error creating download directory:", error);
- throw error;
- }
- }
- // Extract file ID from Google Drive link
- extractFileId(link) {
- const match = link.match(/\/d\/([^/]+)/);
- return match ? match[1] : null;
- }
- // Generate safe filename
- generateSafeFilename(originalFilename, fileId) {
- return originalFilename
- ? originalFilename.replace(/[^a-z0-9.]/gi, "_").replace(/__+/g, "_")
- : `file-${fileId}-${Date.now()}`;
- }
- // Download single file
- async downloadFile(fileLink) {
- try {
- // Extract file ID
- const fileId = this.extractFileId(fileLink);
- if (!fileId) {
- throw new Error(`Invalid file link: ${fileLink}`);
- }
- // Construct download URL
- const downloadUrl = `https://drive.google.com/uc?export=download&id=${fileId}`;
- // Fetch file
- const response = await fetch(downloadUrl, {
- method: "GET",
- headers: {
- "User-Agent": "Mozilla/5.0",
- },
- });
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- // Extract filename
- const contentDisposition = response.headers.get(
- "Content-Disposition"
- );
- const originalFilename = contentDisposition
- ? contentDisposition.split("filename=")[1]?.replace(/['"]/g, "")
- : `file-${fileId}`;
- const safeFilename = this.generateSafeFilename(
- originalFilename,
- fileId
- );
- const downloadPath = path.join(this.downloadDir, safeFilename);
- // Convert response to buffer
- const arrayBuffer = await response.arrayBuffer();
- const buffer = Buffer.from(arrayBuffer);
- // Write file
- await fs.writeFile(downloadPath, buffer);
- return {
- link: fileLink,
- path: downloadPath,
- filename: safeFilename,
- status: "downloaded",
- };
- } catch (error) {
- return {
- link: fileLink,
- error: error.message,
- status: "failed",
- };
- }
- }
- // Download multiple files
- async downloadFiles(fileLinks, options = {}) {
- const { concurrency = 3, onProgress = null } = options;
- // Create download directory
- await this.createDownloadDirectory();
- // Reset download tracking
- this.downloadedFiles = [];
- this.failedDownloads = [];
- // Limit concurrent downloads
- const downloadChunks = [];
- for (let i = 0; i < fileLinks.length; i += concurrency) {
- downloadChunks.push(fileLinks.slice(i, i + concurrency));
- }
- // Process download chunks
- for (const chunk of downloadChunks) {
- const chunkResults = await Promise.all(
- chunk.map((link) => this.downloadFile(link))
- );
- // Process results
- chunkResults.forEach((result) => {
- if (result.status === "downloaded") {
- this.downloadedFiles.push(result);
- } else {
- this.failedDownloads.push(result);
- }
- // Call progress callback if provided
- if (onProgress && typeof onProgress === "function") {
- onProgress({
- total: fileLinks.length,
- downloaded: this.downloadedFiles.length,
- failed: this.failedDownloads.length,
- });
- }
- });
- }
- // Return download summary
- return {
- total: fileLinks.length,
- successful: this.downloadedFiles.length,
- failed: this.failedDownloads.length,
- downloadDir: this.downloadDir,
- downloadedFiles: this.downloadedFiles,
- failedDownloads: this.failedDownloads,
- };
- }
- }
- // Node.js Usage Example
- async function nodeDownload() {
- const downloader = new GoogleDriveDownloader(); // Creates a timestamped directory
- const links = [
- "https://drive.google.com/file/d/10N5oXw0yKu1QuTcXcPEU9-RIXcw8nisu/view?usp=drive_link",
- "https://drive.google.com/file/d/10N5oXw0yKu1QuTcXcPEU9-RIXcw8nisu/view?usp=drive_link",
- ];
- try {
- const result = await downloader.downloadFiles(links, {
- concurrency: 2,
- onProgress: (progress) => {
- console.log("Download Progress:", progress);
- },
- });
- console.log("Download Complete:", result);
- } catch (error) {
- console.error("Download failed:", error);
- }
- }
- nodeDownload();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement