AUXteam commited on
Commit
bdf4689
·
verified ·
1 Parent(s): f7a8ac1

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. src/app.ts +46 -147
src/app.ts CHANGED
@@ -5,18 +5,12 @@ import fs from 'fs';
5
  import path from 'path';
6
  import { exec } from 'child_process';
7
 
8
- // Set public DNS to avoid resolution issues in some environments
9
- try {
10
- dns.setServers(['8.8.8.8', '1.1.1.1']);
11
- } catch (e) {
12
- console.warn('Could not set custom DNS servers:', e.message);
13
- }
14
-
15
  const app = express();
16
  const port = process.env.PORT || 7860;
17
  let whatsappClient: wppconnect.Whatsapp | null = null;
18
  let isInitializing = false;
19
  let lastQR: { base64?: string, ascii?: string, timestamp?: number } | null = null;
 
20
  let initError: string | null = null;
21
 
22
  app.use(express.json());
@@ -36,96 +30,40 @@ const checkDNS = (host: string): Promise<boolean> => {
36
  });
37
  };
38
 
39
- const cleanupProcesses = () => {
40
- return new Promise((resolve) => {
41
- console.log('Cleaning up any existing Chromium processes...');
42
- exec('pkill -f chromium', (err) => {
43
- if (err) {
44
- // pkill exits with 1 if no processes were found, which is fine
45
- console.log('Cleanup: No existing processes or pkill not found.');
46
- } else {
47
- console.log('Cleanup complete.');
48
- }
49
- resolve(true);
50
- });
51
- });
52
- };
53
-
54
  app.get('/health', (req, res) => {
55
  res.status(200).json({
56
  status: 'UP',
57
  initializing: isInitializing,
58
  connected: !!whatsappClient,
 
59
  hasQR: !!lastQR,
60
  initError: initError,
61
  uptime: process.uptime()
62
  });
63
  });
64
 
65
- app.get('/api-docs', (req, res) => {
66
- res.status(200).json({
67
- message: 'WPPConnect API Documentation',
68
- endpoints: {
69
- '/health': 'GET: Health check endpoint',
70
- '/api-docs': 'GET: API documentation',
71
- '/qr': 'GET: Get the latest QR code as an image',
72
- '/qr-ascii': 'GET: Get the latest QR code as ASCII text',
73
- '/send-message': 'POST: Send a text message (telnumber, message)',
74
- '/send-poll': 'POST: Send a poll message (telnumber, name, choices)',
75
- '/get-connection-status': 'GET: Get the current WhatsApp connection status',
76
- '/restart': 'POST: Restart the WhatsApp instance'
77
- },
78
- });
79
- });
80
-
81
  app.get('/qr', (req, res) => {
82
  if (lastQR && lastQR.base64) {
83
  const base64Data = lastQR.base64.replace(/^data:image\/png;base64,/, '');
84
  const img = Buffer.from(base64Data, 'base64');
85
- res.writeHead(200, {
86
- 'Content-Type': 'image/png',
87
- 'Content-Length': img.length
88
- });
89
  res.end(img);
90
  } else {
91
- res.status(404).json({ status: false, message: 'QR code not available yet.' });
92
  }
93
  });
94
 
95
  app.get('/qr-ascii', (req, res) => {
96
  if (lastQR && lastQR.ascii) {
97
- res.send(`<html><body><pre style="font-family: monospace; white-space: pre;">${lastQR.ascii}</pre></body></html>`);
98
  } else {
99
- res.status(404).send('QR code not available yet.');
100
- }
101
- });
102
-
103
- app.post('/restart', async (req, res) => {
104
- if (isInitializing) {
105
- return res.status(409).json({ status: false, message: 'Already initializing' });
106
- }
107
- res.json({ status: true, message: 'Restarting WhatsApp instance...' });
108
- startWPP();
109
- });
110
-
111
- app.get('/get-connection-status', async (req, res) => {
112
- if (whatsappClient) {
113
- try {
114
- const state = await whatsappClient.getConnectionState();
115
- res.json({ status: true, message: state });
116
- } catch (error) {
117
- res.status(500).json({ status: false, message: error.message });
118
- }
119
- } else {
120
- res.status(503).json({ status: false, message: 'WhatsApp instance not initialized' });
121
  }
122
  });
123
 
124
  app.post('/send-message', async (req, res) => {
125
  const { telnumber, message } = req.body;
126
- if (!whatsappClient) {
127
- return res.status(503).json({ status: false, message: 'WhatsApp instance not initialized' });
128
- }
129
  try {
130
  const result = await whatsappClient.sendText(`${telnumber}@c.us`, message);
131
  res.json({ status: true, message: 'Message sent', result });
@@ -136,13 +74,8 @@ app.post('/send-message', async (req, res) => {
136
 
137
  app.post('/send-poll', async (req, res) => {
138
  const { telnumber, name, choices } = req.body;
139
- if (!whatsappClient) {
140
- return res.status(503).json({ status: false, message: 'WhatsApp instance not initialized' });
141
- }
142
  try {
143
- if (!telnumber || !name || !Array.isArray(choices)) {
144
- return res.status(400).json({ status: false, message: 'Invalid parameters.' });
145
- }
146
  const result = await whatsappClient.sendPollMessage(`${telnumber}@c.us`, name, choices);
147
  res.json({ status: true, message: 'Poll sent', result });
148
  } catch (error) {
@@ -150,83 +83,49 @@ app.post('/send-poll', async (req, res) => {
150
  }
151
  });
152
 
153
- async function startWPP(retries = 20, delay = 30000) {
154
  if (isInitializing) return;
155
  isInitializing = true;
156
- initError = null;
157
- console.log('Starting WPPConnect initialization sequence...');
158
-
159
- const sessionName = 'hf-space-session';
160
- const tokenPath = path.join(process.cwd(), 'tokens', sessionName);
161
-
162
- for (let i = 1; i <= retries; i++) {
163
- console.log(`Attempt ${i} to start WPPConnect...`);
164
-
165
- // Check network
166
- const dnsOk = await checkDNS('web.whatsapp.com');
167
- if (!dnsOk && i < 5) {
168
- console.log('Network/DNS not ready, waiting...');
169
- await new Promise(r => setTimeout(r, delay));
170
- continue;
171
- }
172
-
173
- try {
174
- await cleanupProcesses();
175
- const lockPath = path.join(tokenPath, 'SingletonLock');
176
- if (fs.existsSync(lockPath)) {
177
- try { fs.unlinkSync(lockPath); console.log('Removed SingletonLock'); } catch (e) {}
178
- }
179
 
180
- whatsappClient = await wppconnect.create({
181
- session: sessionName,
182
- catchQR: (base64Qr, asciiQR) => {
183
- console.log('QR Code generated.');
184
- lastQR = { base64: base64Qr, ascii: asciiQR, timestamp: Date.now() };
185
- },
186
- statusFind: (statusSession, session) => {
187
- console.log('Status Session: ', statusSession);
188
- if (statusSession === 'isLogged' || statusSession === 'inChat') {
189
- lastQR = null;
190
- }
191
- },
192
- headless: true,
193
- useChrome: false,
194
- puppeteerOptions: {
195
- executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium',
196
- args: [
197
- '--no-sandbox',
198
- '--disable-setuid-sandbox',
199
- '--disable-dev-shm-usage',
200
- '--disable-gpu',
201
- '--no-zygote',
202
- ],
203
- },
204
- logQR: true,
205
- tokenStore: 'file',
206
- folderNameToken: './tokens',
207
- autoClose: 0,
208
- });
209
-
210
- console.log('WPPConnect initialized successfully.');
211
- isInitializing = false;
212
- return;
213
- } catch (error) {
214
- console.error(`Attempt ${i} failed: ${error.message}`);
215
- initError = error.message;
216
-
217
- if (i === retries) {
218
- console.error('All retries exhausted.');
219
- isInitializing = false;
220
- } else {
221
- console.log(`Retrying in ${delay / 1000} seconds...`);
222
- await new Promise(r => setTimeout(r, delay));
223
- }
224
- }
225
  }
226
  }
227
 
228
  app.listen(port, () => {
229
- console.log(`Server listening on port ${port}`);
230
- // Initialization in background
231
- startWPP().catch(e => console.error('Background init failed:', e));
232
  });
 
5
  import path from 'path';
6
  import { exec } from 'child_process';
7
 
 
 
 
 
 
 
 
8
  const app = express();
9
  const port = process.env.PORT || 7860;
10
  let whatsappClient: wppconnect.Whatsapp | null = null;
11
  let isInitializing = false;
12
  let lastQR: { base64?: string, ascii?: string, timestamp?: number } | null = null;
13
+ let lastStatus: string = 'Starting';
14
  let initError: string | null = null;
15
 
16
  app.use(express.json());
 
30
  });
31
  };
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  app.get('/health', (req, res) => {
34
  res.status(200).json({
35
  status: 'UP',
36
  initializing: isInitializing,
37
  connected: !!whatsappClient,
38
+ whatsappStatus: lastStatus,
39
  hasQR: !!lastQR,
40
  initError: initError,
41
  uptime: process.uptime()
42
  });
43
  });
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  app.get('/qr', (req, res) => {
46
  if (lastQR && lastQR.base64) {
47
  const base64Data = lastQR.base64.replace(/^data:image\/png;base64,/, '');
48
  const img = Buffer.from(base64Data, 'base64');
49
+ res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': img.length });
 
 
 
50
  res.end(img);
51
  } else {
52
+ res.status(404).json({ status: false, message: 'QR code not available.' });
53
  }
54
  });
55
 
56
  app.get('/qr-ascii', (req, res) => {
57
  if (lastQR && lastQR.ascii) {
58
+ res.send(`<html><body style="background: #000; color: #fff;"><pre style="font-family: monospace; white-space: pre;">${lastQR.ascii}</pre></body></html>`);
59
  } else {
60
+ res.status(404).send('QR code not available.');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
  });
63
 
64
  app.post('/send-message', async (req, res) => {
65
  const { telnumber, message } = req.body;
66
+ if (!whatsappClient) return res.status(503).json({ status: false, message: 'WhatsApp instance not initialized' });
 
 
67
  try {
68
  const result = await whatsappClient.sendText(`${telnumber}@c.us`, message);
69
  res.json({ status: true, message: 'Message sent', result });
 
74
 
75
  app.post('/send-poll', async (req, res) => {
76
  const { telnumber, name, choices } = req.body;
77
+ if (!whatsappClient) return res.status(503).json({ status: false, message: 'WhatsApp instance not initialized' });
 
 
78
  try {
 
 
 
79
  const result = await whatsappClient.sendPollMessage(`${telnumber}@c.us`, name, choices);
80
  res.json({ status: true, message: 'Poll sent', result });
81
  } catch (error) {
 
83
  }
84
  });
85
 
86
+ async function startWPP() {
87
  if (isInitializing) return;
88
  isInitializing = true;
89
+ lastStatus = 'Initializing';
90
+ console.log('Starting WPPConnect...');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ const sessionName = 'hf-space-session';
93
+
94
+ // Minimal config to avoid DNS/Network issues at startup
95
+ try {
96
+ whatsappClient = await wppconnect.create({
97
+ session: sessionName,
98
+ catchQR: (base64Qr, asciiQR) => {
99
+ lastQR = { base64: base64Qr, ascii: asciiQR, timestamp: Date.now() };
100
+ console.log('QR Generated');
101
+ },
102
+ statusFind: (statusSession) => {
103
+ lastStatus = statusSession;
104
+ if (statusSession === 'isLogged' || statusSession === 'inChat') lastQR = null;
105
+ },
106
+ headless: true,
107
+ useChrome: false,
108
+ puppeteerOptions: {
109
+ executablePath: '/usr/bin/chromium',
110
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
111
+ },
112
+ logQR: true,
113
+ tokenStore: 'file',
114
+ folderNameToken: './tokens',
115
+ autoClose: 0,
116
+ });
117
+ console.log('WPPConnect Ready');
118
+ isInitializing = false;
119
+ } catch (error) {
120
+ console.error('WPPConnect Failed:', error.message);
121
+ initError = error.message;
122
+ isInitializing = false;
123
+ // Retry after a delay
124
+ setTimeout(startWPP, 30000);
 
 
 
 
 
 
 
 
 
 
 
 
125
  }
126
  }
127
 
128
  app.listen(port, () => {
129
+ console.log(`Server port ${port}`);
130
+ startWPP();
 
131
  });