import { supabase } from './supabase'; import { execSync } from 'child_process'; import fs from 'fs'; import path from 'path'; const SESSION_DIR = '/tmp/.wwebjs_auth'; export async function uploadSession(accountId) { console.log(`[Sync] Packing session for ${accountId}...`); try { const sessionFolder = path.join(SESSION_DIR, `session-${accountId}`); if (!fs.existsSync(sessionFolder)) { console.log(`[Sync] No session folder found for ${accountId}, skipping upload.`); return; } const tarFile = `/tmp/session-${accountId}.tar.gz`; // Use tar to compress the folder // -C changes to the parent dir, then compress specifically that folder execSync(`tar -czf ${tarFile} -C ${SESSION_DIR} session-${accountId}`); const fileBuffer = fs.readFileSync(tarFile); const { error } = await supabase.storage .from('whatsapp-sessions') .upload(`${accountId}.tar.gz`, fileBuffer, { upsert: true, contentType: 'application/gzip' }); if (error) throw error; console.log(`[Sync] ✅ Session uploaded to Supabase for ${accountId}`); fs.unlinkSync(tarFile); // Cleanup } catch (err) { console.error(`[Sync] ❌ Upload failed for ${accountId}:`, err.message); } } export async function downloadSession(accountId) { console.log(`[Sync] Attempting to restore session for ${accountId}...`); try { const { data, error } = await supabase.storage .from('whatsapp-sessions') .download(`${accountId}.tar.gz`); if (error || !data) { console.log(`[Sync] No cloud session found for ${accountId}. Starting fresh.`); return false; } const tarFile = `/tmp/session-${accountId}.tar.gz`; const buffer = Buffer.from(await data.arrayBuffer()); fs.writeFileSync(tarFile, buffer); if (!fs.existsSync(SESSION_DIR)) { fs.mkdirSync(SESSION_DIR, { recursive: true }); } // Extract tar to the auth directory execSync(`tar -xzf ${tarFile} -C ${SESSION_DIR}`); console.log(`[Sync] ✅ Session restored from Supabase for ${accountId}`); fs.unlinkSync(tarFile); // Cleanup return true; } catch (err) { console.error(`[Sync] ❌ Restore failed for ${accountId}:`, err.message); return false; } }