-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
199 lines (167 loc) · 5.14 KB
/
server.js
File metadata and controls
199 lines (167 loc) · 5.14 KB
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
import express from 'express';
import venom from 'venom-bot';
import http from 'http';
import { Server } from 'socket.io';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public'), {
setHeaders: (res, filePath) => {
if (filePath.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
}
}
}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
const activeSessions = {
client: null,
qrCode: null
};
const messagesPath = path.join(__dirname, 'db', 'messages.json');
const contactsPath = path.join(__dirname, 'db', 'contacts.json');
function readJSON(filePath) {
try {
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (err) {
return [];
}
}
function writeJSON(filePath, data) {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
}
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'dashboard.html'));
});
app.post('/save-message', (req, res) => {
const messages = readJSON(messagesPath);
const newMessage = {
id: Date.now(),
text: req.body.message,
createdAt: new Date().toISOString()
};
messages.push(newMessage);
writeJSON(messagesPath, messages);
res.json({ success: true });
});
app.get('/get-messages', (req, res) => {
const messages = readJSON(messagesPath);
const sortedMessages = messages.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
res.json(sortedMessages);
});
app.post('/update-message', (req, res) => {
const { id, text } = req.body;
const messages = readJSON(messagesPath);
const messageIndex = messages.findIndex(m => m.id === id);
if (messageIndex !== -1) {
messages[messageIndex].text = text;
messages[messageIndex].updatedAt = new Date().toISOString();
writeJSON(messagesPath, messages);
res.json({ success: true });
} else {
res.status(404).json({ error: 'Message not found' });
}
});
app.post('/delete-message', (req, res) => {
const { id } = req.body;
const messages = readJSON(messagesPath);
const filteredMessages = messages.filter(m => m.id !== id);
writeJSON(messagesPath, filteredMessages);
res.json({ success: true });
});
app.post('/save-contact', (req, res) => {
const contacts = readJSON(contactsPath);
const newContact = {
id: Date.now(),
name: req.body.name,
phone: req.body.phone,
createdAt: new Date().toISOString()
};
contacts.push(newContact);
writeJSON(contactsPath, contacts);
res.json({ success: true });
});
app.get('/get-contacts', (req, res) => {
const contacts = readJSON(contactsPath);
res.json(contacts);
});
app.post('/delete-contact', (req, res) => {
const { id } = req.body;
const contacts = readJSON(contactsPath);
const filteredContacts = contacts.filter(c => c.id !== id);
writeJSON(contactsPath, filteredContacts);
res.json({ success: true });
});
app.post('/send-whatsapp', async (req, res) => {
const { phone, message } = req.body;
try {
if (!activeSessions.client) {
throw new Error('Conecte-se ao WhatsApp primeiro');
}
const formattedPhone = `${phone.replace(/\D/g, '')}@c.us`;
await activeSessions.client.sendText(formattedPhone, message);
res.json({ success: true });
} catch (err) {
res.status(500).json({
error: 'Falha no envio',
details: err.message
});
}
});
io.on('connection', (socket) => {
console.log('Cliente conectado:', socket.id);
socket.on('start_connection', async () => {
try {
if (activeSessions.client) {
await activeSessions.client.close();
}
socket.emit('status_update', {
status: 'waiting_qr',
message: '🔄 Aguardando QR Code...'
});
const client = await venom.create({
session: 'whatsapp-session',
headless: true,
multidevice: true,
catchQR: (base64Qrimg) => {
activeSessions.qrCode = base64Qrimg;
socket.emit('qr_code', base64Qrimg);
}
});
activeSessions.client = client;
socket.emit('status_update', {
status: 'connected',
message: '✅ WhatsApp conectado!',
redirect: true
});
} catch (err) {
console.error('Erro na conexão:', err);
socket.emit('status_update', {
status: 'error',
message: `❌ Erro: ${err.message}`
});
}
});
socket.on('disconnect', () => {
console.log('Cliente desconectado:', socket.id);
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Servidor rodando em http://localhost:${PORT}`);
if (!fs.existsSync(messagesPath)) writeJSON(messagesPath, []);
if (!fs.existsSync(contactsPath)) writeJSON(contactsPath, []);
});