const { google } = require('googleapis'); const { Readable } = require('stream'); const path = require('path'); const fs = require('fs'); /** * Build an authenticated Google Drive client using a Service Account. * Credentials can be supplied as: * - GOOGLE_SERVICE_ACCOUNT_JSON (the full JSON string, good for env-var deployments) * - GOOGLE_SERVICE_ACCOUNT_KEY_PATH (path to the JSON key file) */ function getDriveClient() { let credentials; if (process.env.GOOGLE_SERVICE_ACCOUNT_JSON) { // Preferred for cloud deployments: full JSON embedded in env var credentials = JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_JSON); } else if (process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH) { const keyPath = path.resolve(process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH); credentials = JSON.parse(fs.readFileSync(keyPath, 'utf8')); } else { return null; // Credentials not configured — caller should fall back } const auth = new google.auth.GoogleAuth({ credentials, scopes: [ // drive.file only covers files created by the app in its own Drive. // We need the broader 'drive' scope to write into a folder shared by another user. 'https://www.googleapis.com/auth/drive', ], }); return google.drive({ version: 'v3', auth }); } /** * Converts an HTML string to a DOCX buffer via the Google Drive API. * * Flow: * 1. Upload HTML → Google Drive with MIME type conversion → Google Doc * 2. Export Google Doc → DOCX buffer * 3. Delete the temporary Google Doc immediately * * @param {string} html - Complete standalone HTML document * @param {string} [title] - Optional document title * @returns {Promise} DOCX file buffer * @throws {Error} if Drive API is unreachable or credentials are missing */ async function convertHtmlToDocxViaGoogleDrive(html, title = 'CVBora Document') { const drive = getDriveClient(); if (!drive) { throw new Error('Google Drive credentials not configured. Set GOOGLE_SERVICE_ACCOUNT_JSON or GOOGLE_SERVICE_ACCOUNT_KEY_PATH.'); } let fileId = null; try { // ── Step 1: Upload HTML → Google Docs (Drive converts it automatically) ── // If GOOGLE_DRIVE_FOLDER_ID is set, the file is created inside that shared // folder and counts against the folder-owner's quota (not the service account's). const htmlStream = Readable.from([html]); const fileMetadata = { name: title, mimeType: 'application/vnd.google-apps.document', // triggers HTML → Google Doc conversion }; const folderId = process.env.GOOGLE_DRIVE_FOLDER_ID; if (folderId) { fileMetadata.parents = [folderId]; console.log(`📁 Uploading into shared folder: ${folderId}`); } const uploadRes = await drive.files.create({ requestBody: fileMetadata, media: { mimeType: 'text/html', body: htmlStream, }, fields: 'id', // supportsAllDrives allows writing into Shared Drives (Team Drives) too supportsAllDrives: true, }); fileId = uploadRes.data.id; console.log(`📄 Google Doc created: ${fileId}`); // ── Step 2: Export as DOCX ─────────────────────────────────────────────── const exportRes = await drive.files.export( { fileId, mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }, { responseType: 'arraybuffer' } ); const docxBuffer = Buffer.from(exportRes.data); console.log(`✅ DOCX exported (${docxBuffer.length} bytes)`); return docxBuffer; } finally { // ── Step 3: Always delete the temp file from Drive ────────────────────── if (fileId) { try { await drive.files.delete({ fileId, supportsAllDrives: true }); console.log(`🗑️ Temp Google Doc deleted: ${fileId}`); } catch (deleteErr) { // Non-fatal — log but don't throw console.warn(`⚠️ Could not delete temp Google Doc ${fileId}:`, deleteErr.message); } } } } /** * Returns true if Google Drive credentials are configured in the environment. */ function isGoogleDriveConfigured() { return !!(process.env.GOOGLE_SERVICE_ACCOUNT_JSON || process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH); } module.exports = { convertHtmlToDocxViaGoogleDrive, isGoogleDriveConfigured };