161 lines
4.8 KiB
JavaScript
161 lines
4.8 KiB
JavaScript
const { Client, LocalAuth } = require('whatsapp-web.js');
|
|
const express = require('express');
|
|
const qrcode = require('qrcode');
|
|
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use(express.static(path.join(__dirname, 'ui')));
|
|
|
|
let lastQr = "";
|
|
let isReady = false;
|
|
let isInitializing = true;
|
|
|
|
const SESSION_DATA = '/data/auth';
|
|
|
|
async function handleCrash(errorContext) {
|
|
console.error(`💥 CRITICAL ERROR CAUGHT: ${errorContext}`);
|
|
isReady = false;
|
|
|
|
try {
|
|
console.log('Versuche Browser sauber zu schließen, um Session zu retten...');
|
|
if (client && client.pupBrowser) {
|
|
await client.pupBrowser.close().catch(() => {});
|
|
}
|
|
} catch (e) {
|
|
console.error('Browser konnte nicht sauber geschlossen werden:', e);
|
|
}
|
|
|
|
console.log('Add-on wird beendet. HA Watchdog startet es sauber neu...');
|
|
process.exit(1);
|
|
}
|
|
|
|
process.on('uncaughtException', async (err) => {
|
|
if (err.message.includes('ProtocolError') || err.message.includes('Runtime.callFunctionOn') || err.message.includes('Target closed')) {
|
|
await handleCrash('Puppeteer Protocol Timeout / Crash');
|
|
} else {
|
|
console.error('Uncaught Exception:', err);
|
|
}
|
|
});
|
|
|
|
process.on('unhandledRejection', async (reason, promise) => {
|
|
if (reason && reason.message && reason.message.includes('Session closed')) {
|
|
await handleCrash('Unhandled Puppeteer Session Rejection');
|
|
} else {
|
|
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
}
|
|
});
|
|
|
|
const client = new Client({
|
|
authStrategy: new LocalAuth({
|
|
dataPath: SESSION_DATA,
|
|
clientId: "ha_bridge_session"
|
|
}),
|
|
authTimeoutMs: 90000,
|
|
qrMaxRetries: 5,
|
|
puppeteer: {
|
|
executablePath: '/usr/bin/chromium-browser',
|
|
protocolTimeout: 0,
|
|
args: [
|
|
'--no-sandbox',
|
|
'--disable-setuid-sandbox',
|
|
'--disable-dev-shm-usage',
|
|
'--disable-gpu',
|
|
'--no-zygote',
|
|
'--single-process',
|
|
'--disable-extensions'
|
|
]
|
|
}
|
|
});
|
|
|
|
client.on('qr', (qr) => {
|
|
lastQr = qr;
|
|
isReady = false;
|
|
isInitializing = false;
|
|
console.log('Neuer QR Code generiert.');
|
|
});
|
|
|
|
client.on('ready', () => {
|
|
isReady = true;
|
|
lastQr = "";
|
|
isInitializing = false;
|
|
console.log('WhatsApp ist bereit!');
|
|
});
|
|
|
|
client.on('disconnected', async (reason) => {
|
|
console.log(`WhatsApp Verbindung manuell oder extern getrennt (Grund: ${reason}).`);
|
|
await handleCrash('Externer Disconnect');
|
|
});
|
|
|
|
// --- ROUTES ---
|
|
|
|
app.get('/', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'ui', 'index.html'));
|
|
});
|
|
|
|
app.get('/api/status', async (req, res) => {
|
|
try {
|
|
let qrData = null;
|
|
if (lastQr) {
|
|
qrData = await qrcode.toDataURL(lastQr);
|
|
}
|
|
|
|
let clientState = 'DISCONNECTED';
|
|
if (isReady) {
|
|
clientState = await client.getState().catch(() => 'ERROR');
|
|
}
|
|
|
|
res.json({
|
|
isReady: isReady,
|
|
hasQr: lastQr !== "",
|
|
qrCode: qrData,
|
|
isInitializing: isInitializing,
|
|
clientState: clientState
|
|
});
|
|
} catch (e) {
|
|
res.status(500).json({ error: e.message });
|
|
}
|
|
});
|
|
|
|
app.post('/auth/logout', async (req, res) => {
|
|
try {
|
|
console.log("Manueller Logout über Web-UI...");
|
|
await client.logout().catch(() => {});
|
|
await fs.remove(path.join(SESSION_DATA, 'session-ha_bridge_session')).catch(() => {});
|
|
res.json({ success: true, message: "Erfolgreich abgemeldet. Ordner gelöscht. Addon startet neu..." });
|
|
setTimeout(() => process.exit(0), 2000);
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
app.delete('/system/reset', async (req, res) => {
|
|
try {
|
|
await client.destroy().catch(() => {});
|
|
await fs.emptyDir('/data').catch(() => {});
|
|
res.json({ success: true, message: "Werkseinstellungen aktiv. Alles gelöscht. Neustart..." });
|
|
setTimeout(() => process.exit(0), 2000);
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
app.post('/send', async (req, res) => {
|
|
const { number, message } = req.body;
|
|
if (!isReady) return res.status(503).json({ error: 'Client nicht bereit' });
|
|
try {
|
|
const chatId = number.includes('@c.us') ? number : `${number}@c.us`;
|
|
await client.sendMessage(chatId, message);
|
|
res.json({ success: true });
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
console.log('Initialisiere WhatsApp Client...');
|
|
client.initialize().catch(async (err) => {
|
|
await handleCrash(`Initialisierungsfehler: ${err.message}`);
|
|
});
|
|
|
|
app.listen(3000, () => console.log('WhatsApp Bridge Server läuft auf Port 3000')); |