File size: 2,470 Bytes
f7894a3
 
 
 
 
 
bfbb055
f7894a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

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;
    }
}