File size: 11,981 Bytes
ebccf84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
const fs = require('fs');
const path = require('path');
const CONFIG = require('./config');
const WhatsAppAccountManager = require('./AccountManager');
const { accounts } = require('./shared');

const htmlTemplate = fs.readFileSync(path.join(__dirname, 'views', 'index.html'), 'utf8');

module.exports = function (req, res) {
    if (req.url === '/app' && req.method === 'GET') {
        handleRoot(req, res);
    } else if (req.method === 'POST' && req.url === '/add-account') {
        handleAddAccount(req, res);
    } else if (req.method === 'POST' && req.url.startsWith('/start/')) {
        handleStartAccount(req, res);
    } else if (req.url.startsWith('/qrcode/')) {
        handleQrCode(req, res);
    }
    else if (req.url === '/shared_state.json') {
        handleSharedState(req, res);
    } else if (req.url === '/shared_statuses.csv') {
        handleSharedStatuses(req, res);
    }else if (req.url === '/dashboard-data') {
        handleDashboardData(req, res);
    }else if (req.url === '/accounts-status') {
        handleAccountsStatus(req, res);
    }  else if (req.method === 'POST' && req.url === '/add-number-to-group') {
        // Handle adding number to group
        let body = '';
        req.on('data', chunk => body += chunk);
        req.on('end', async () => {
            try {
                const { accountId, phone, groupName } = JSON.parse(body);
                const manager = accounts.get(accountId);
                
                if (!manager) {
                    res.writeHead(404);
                    return res.end(JSON.stringify({ success: false, message: 'Account not found' }));
                }

                const result = await manager.addNumberToGroup(phone, groupName);
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify(result));
            } catch (error) {
                res.writeHead(500);
                res.end(JSON.stringify({ success: false, message: error.message }));
            }
        });
    }
    else {
        res.writeHead(404);
        res.end('Not found');
    }
};

function handleAccountsStatus(req, res) {
    const accountsData = Array.from(accounts).map(([id, manager]) => ({
        id,
        status: manager.status
    }));
    
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ accounts: accountsData }));
}


function checkSessionFolders() {
    const sessionDir = CONFIG.SESSION_DIR;

    // Check if the session directory exists
    if (!fs.existsSync(sessionDir)) {
        console.log('Session directory does not exist.');
        return;
    }

    // Read all files/folders in the session directory
    const sessionFolders = fs.readdirSync(sessionDir);

    sessionFolders.forEach(folder => {
        // Only process folders that start with "session_"
        if (folder.startsWith('session_') && !folder.endsWith('.png')) {
            // Extract account ID from folder name (e.g., "session_123456")
            const accountId = folder.replace('session_', '');

            // Check if the account ID is not in the accounts map
            if (!accounts.has(accountId)) {
                console.log(`Found session folder for account ${accountId}, but no manager exists. Creating new manager...`);

                // Create a new WhatsAppAccountManager for this account
                accounts.set(accountId, new WhatsAppAccountManager(accountId));
            }
        }
    });
}

function handleAddAccount(req, res) {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
        try {
            const { accountId } = JSON.parse(body);
            if (!accountId) {
                res.writeHead(400);
                return res.end(JSON.stringify({ error: 'Account ID required' }));
            }

            if (accounts.has(accountId)) {
                res.writeHead(409);
                return res.end(JSON.stringify({ error: 'Account already exists' }));
            }

            accounts.set(accountId, new WhatsAppAccountManager(accountId));
            res.writeHead(201);
            res.end(JSON.stringify({ success: true }));
        } catch (error) {
            res.writeHead(500);
            res.end(JSON.stringify({ error: 'Invalid request' }));
        }
    });
}

function handleStartAccount(req, res) {
    const accountId = req.url.split('/')[2];
    const manager = accounts.get(accountId);
    
    if (!manager) {
        res.writeHead(404);
        return res.end(JSON.stringify({ error: 'Account not found' }));
    }

    manager.status = 'running';
    manager.processBatch();
    res.writeHead(200);
    res.end(JSON.stringify({ success: true }));
}

function handleQrCode(req, res) {
    const accountId = req.url.split('/')[2];
    const manager = accounts.get(accountId);
    
    if (!manager) {
        res.writeHead(404);
        return res.end('Account not found');
    }

    fs.readFile(manager.qrFile, (err, data) => {
        if (err) {
            res.writeHead(404);
            res.end('QR code not available');
        } else {
            res.writeHead(200, { 'Content-Type': 'image/png' });
            res.end(data);
        }
    });
}

// Add these new handler functions
function handleSharedState(req, res) {
    fs.readFile(CONFIG.STATE_FILE, (err, data) => {
        if (err) {
            res.writeHead(404);
            res.end('State file not found');
        } else {
            res.writeHead(200, {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="shared_state.json"'
            });
            res.end(data);
        }
    });
}

function handleSharedStatuses(req, res) {
    fs.readFile(CONFIG.CSV_FILE, (err, data) => {
        if (err) {
            res.writeHead(404);
            res.end('Status file not found');
        } else {
            res.writeHead(200, {
                'Content-Type': 'text/csv',
                'Content-Disposition': 'attachment; filename="shared_statuses.csv"'
            });
            res.end(data);
        }
    });
}



function handleRoot(req, res) {
    checkSessionFolders();
    let state = {};
    try {
        state = JSON.parse(fs.readFileSync(CONFIG.STATE_FILE));
    } catch (error) {
        state = {
            currentGroup: null,
            groupCounter: 1,
            activeGroups: [],
            lastProcessed: 0
        };
    }



    let accountsHTML = '';
    accounts.forEach((manager, id) => {
        accountsHTML += generateAccountCard(id, manager);
    });

    let html = htmlTemplate
        .replace('{{ACCOUNTS}}', accountsHTML);

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
}

function generateAccountCard(accountId, manager) {
    let content = '';
    const baseContent = 
        `<h3 class='text-xl font-semibold text-gray-900 mb-2'>${accountId}</h3>
        <p class='text-sm font-medium py-1 px-3 rounded-full text-white ${manager.status === 'ready' ? 'bg-green-500' : manager.status === 'running' ? 'bg-blue-500' : 'bg-yellow-500'}'>
            ${manager.status.replace('_', ' ')}
        </p>`;

    if (manager.status === 'initializing') {
        content = 
            `${baseContent}
            <div class='flex items-center gap-2 text-gray-600 mt-2'>
                <i class='fas fa-spinner fa-spin'></i>
                <span>Initializing...</span>
            </div>`;
    } else if (manager.status === 'awaiting_qr') {
        content = 
            `${baseContent}
            <div class='flex flex-col items-center mt-4'>
                <img src='/qrcode/${accountId}' class='w-64 h-64 rounded-lg shadow-md border' alt='QR Code'>
                <p class='mt-2 text-gray-600'>Scan this QR code with your phone</p>
            </div>`;
    } else if (manager.status === 'ready') {
        content = 
            `${baseContent}
            <button onclick="startAccount('${accountId}')" class='w-full mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg shadow-md hover:bg-blue-700 flex items-center justify-center'>
                <i class='fas fa-play mr-2'></i> Start Processing
            </button>`;
    } else if (manager.status === 'running') {
        content = 
            `${baseContent}
            <div class='flex items-center gap-2 text-gray-600 mt-2'>
                <i class='fas fa-spinner fa-spin'></i>
                <span>Processing...</span>
            </div>`;
    } else {
        content = baseContent;
    }

    const processDetails = manager.status === 'running' ? `
        <div class="mt-4 w-full">
            <h4 class="text-lg font-semibold mb-2">Process Details</h4>
            <button onclick="toggleDetails('${accountId}')" class="text-blue-600 hover:text-blue-800 text-sm">
                ${manager.processDetailsOpen ? 'Hide Details' : 'Show Details'}
            </button>
            <div id="details-${accountId}" class="details-section ${manager.processDetailsOpen ? '' : 'hidden'}">
                <table class="w-full border-collapse border border-gray-300">
                    <thead>
                        <tr class="bg-gray-200">
                            <th class="border border-gray-300 px-4 py-2">Phone</th>
                            <th class="border border-gray-300 px-4 py-2">Name</th>
                            <th class="border border-gray-300 px-4 py-2">Status</th>
                            <th class="border border-gray-300 px-4 py-2">Error Code</th>
                            <th class="border border-gray-300 px-4 py-2">Message</th>
                            <th class="border border-gray-300 px-4 py-2">Invite Sent</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${manager.processDetails.map(detail => `
                            <tr>
                                <td class="border border-gray-300 px-4 py-2">${detail.phone}</td>
                                <td class="border border-gray-300 px-4 py-2">${detail.name}</td>
                                <td class="border border-gray-300 px-4 py-2">${detail.status}</td>
                            <td class="border border-gray-300 px-4 py-2">${detail.error_code || 'N/A'}</td>
                            <td class="border border-gray-300 px-4 py-2">${detail.message || 'N/A'}</td>
                            <td class="border border-gray-300 px-4 py-2">${detail.is_invite_sent || 'N/A'}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        </div>
    ` : '';

    return `
        <div class='bg-white p-6 rounded-lg shadow-lg border flex flex-col items-center' data-status="${manager.status}" data-account-id="${accountId}">
            ${content}
            ${processDetails}
        </div>`;
}


function handleDashboardData(req, res) {
    try {
        const state = JSON.parse(fs.readFileSync(CONFIG.STATE_FILE));
        const data = {
            currentGroupName: state.currentGroupName ? 
                `${CONFIG.BASE_GROUP_NAME} ${state.groupCounter - 1}` : 'No active group',
            currentGroupMembers: state.currentGroup ? 
                (state.activeGroups.find(g => g.id === state.currentGroup)?.members || 0) : 0,
            maxGroupSize: CONFIG.MAX_GROUP_SIZE,
            currentGroupId: state.currentGroup ? 
                state.currentGroup.substring(0, 8) + '...' : 'N/A',
            totalProcessed: state.lastProcessed,
            activeGroupsCount: state.activeGroups.length,
            nextGroupName: `${CONFIG.BASE_GROUP_NAME} ${state.groupCounter}`
        };
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(data));
    } catch (error) {
        res.writeHead(500);
        res.end(JSON.stringify({ error: 'Could not load dashboard data' }));
    }
}