Bulk Messaging System

An Electron Desktop app for marketing campaign & broadcast management, using either whatsapp, gmail or a SMTP server

Whats app event system

Introduction#

Events the WhatsApp client pushes from main to renderer: QR, ready, auth failure, disconnect, and per-message send progress.

  • Client Lifecycle Events. Covering initialization, authentication, and disconnection states
  • QR Code Events. Managing QR code generation and display for authentication
  • Mass Messaging Events. Real-time progress tracking during bulk message operations

System architecture#

Events move main → preload → renderer like this:

Event types and payloads#

Event categories#

The system emits three distinct event types with specific payload characteristics:

1. client lifecycle events (whatsapp-status)#

  • Purpose. Real-time status updates for WhatsApp client lifecycle
  • Payload Type. String message describing current state
  • Frequency. Variable (as events occur)
  • Timing. Immediate notification upon state change

2. QR code events (whatsapp-qr)#

  • Purpose. QR code data for authentication
  • Payload Type. Data URL string (image data) or null
  • Frequency. Generated when QR becomes available
  • Timing. Generated asynchronously after QR event from client

3. mass messaging events (whatsapp-send-status)#

  • Purpose. Progress tracking for bulk message operations
  • Payload Type. String progress messages
  • Frequency. Multiple updates per operation
  • Timing. Real-time during message sending process

Client lifecycle events#

Event emission flow#

The client lifecycle events follow a predictable sequence during WhatsApp client initialization:

Lifecycle states#

The system manages the following client states:

State Description Event Emission
Initializing Client creation and setup whatsapp-status with initialization message
Starting Client initialization process whatsapp-status with start message
Waiting for QR Client ready, waiting for QR code whatsapp-status with QR instruction
Authenticated Successful authentication whatsapp-status with success message
Ready Client fully operational whatsapp-status with readiness message
Disconnected Client lost connection whatsapp-status with disconnection reason

QR code events#

QR code generation process#

The QR code system operates through a two-stage process:

QR code payload schema#

Property Type Description Example
qr String QR code string from WhatsApp client "0AKCD..."
dataUrl String | null Base64 encoded image data "data:image/png;base64,iVBOR..."
status String Current authentication status "Scan QR code"

QR code display integration#

The UI component handles QR code display with reliable error handling:

Mass messaging events#

Event emission pattern#

The mass messaging system provides granular progress tracking:

Progress event payloads#

Event Type Payload Format Purpose
whatsapp-send-status "Sending messages to N contacts..." Operation start
whatsapp-send-status "Sent to +1234567890" Individual success
whatsapp-send-status "Failed: +1234567890 not registered" Registration failure
whatsapp-send-status "Failed to send to +1234567890: Error message" General failure
whatsapp-send-status "Mass messaging complete. Sent: X, Failed: Y" Operation completion

Event listener implementation#

Renderer process integration#

The event listeners are implemented in the BulkMailer component with proper cleanup:

Listener registration pattern#

The event listeners follow a consistent registration and cleanup pattern:

javascript
// Event listener setup
const removeWaStatus = window.electronAPI.onWhatsAppStatus((_, status) =>
 setWaStatus(status)
);

const removeWaQR = window.electronAPI.onWhatsAppQR((_, qr) =>
 setWaQR(qr)
);

const removeWaSendStatus = window.electronAPI.onWhatsAppSendStatus(
 (_, msg) => {
 setWaStatus(msg);
 setWaResults(prev => [...prev, msg]);
 }
);

// Cleanup on component unmount
return () => {
 if (removeWaStatus) removeWaStatus();
 if (removeWaQR) removeWaQR();
 if (removeWaSendStatus) removeWaSendStatus();
};

State management integration#

React state synchronization#

The event system integrates cleanly with React’s state management:

UI component state mapping#

Event Type State Variable UI Impact
whatsapp-status waStatus Updates status indicator, loading states
whatsapp-qr waQR Displays QR code or clears display
whatsapp-send-status waResults Adds progress entries to activity log
whatsapp-send-status waStatus Updates current operation status

Event ordering and concurrency#

Event ordering guarantees#

The system maintains strict event ordering through several mechanisms:

  1. Sequential Event Processing. Events are processed in the order they are emitted
  2. State Consistency. React state updates ensure UI reflects current state
  3. Cleanup Mechanisms. Proper listener cleanup prevents stale event handling

Concurrency considerations#

The system handles concurrent operations safely:

Race condition prevention#

The system prevents race conditions through:

  • Single Client Instance. Only one WhatsApp client instance is maintained
  • Sequential Message Processing. Messages are sent one at a time with delays
  • Proper Cleanup. Event listeners are removed when components unmount

Error handling and propagation#

Error propagation pattern#

Errors propagate through the system with appropriate handling:

Error handling strategies#

Error Type Handler Response
Initialization Failure whatsapp-status Error message with details
Authentication Failure whatsapp-status Failure reason and cleanup
QR Generation Failure whatsapp-status Error message and fallback
Message Send Failure whatsapp-send-status Individual failure report
Client Disconnection whatsapp-status Disconnection reason and reset

Performance considerations#

Event frequency optimization#

The system optimizes event frequency to balance responsiveness with performance:

  • QR Events. Minimal frequency (only when QR becomes available)
  • Status Events. Moderate frequency (state transitions)
  • Progress Events. High frequency during bulk operations (every 3-5 seconds)

Memory management#

The system implements several memory management strategies:

  • Automatic Cleanup. Event listeners are removed on component unmount
  • Client Instance Management. Single client instance prevents memory leaks
  • QR Data Handling. QR images are cleared when no longer needed

Rate limiting implementation#

The mass messaging system includes built-in rate limiting:

  • 3-second delay for registered users
  • 5-second delay for failed attempts
  • Individual contact processing prevents overwhelming the API

Memory leak prevention#

Listener cleanup pattern#

The system implements detailed listener cleanup:

Cleanup implementation#

Cleanup removes listeners so they do not pile up:

javascript
// Cleanup function returned by listener registration
const removeWaStatus = window.electronAPI.onWhatsAppStatus((_, status) =>
 setWaStatus(status)
);

// Component unmount cleanup
return () => {
 if (removeWaStatus) removeWaStatus();
 if (removeWaQR) removeWaQR();
 if (removeWaSendStatus) removeWaSendStatus();
};

Troubleshooting guide#

Common issues and solutions#

Issue Symptoms Solution
QR Code Not Loading Blank QR area, error message Check network connectivity, retry connection
Authentication Fails Repeated authentication failures Clear cached authentication files, restart client
Messages Not Sending Progress shows failures Check contact registration, verify message format
UI Not Updating Status remains static Verify event listeners are registered, check console errors

Debugging event flow#

To debug event flow issues:

  1. Enable Developer Tools. Use mainWindow.webContents.openDevTools()
  2. Monitor Console Output. Check for error messages in main process
  3. Verify Event Registration. Ensure listeners are properly registered
  4. Test Individual Events. Isolate specific event types for testing

Performance monitoring#

Monitor system performance through:

  • Event Frequency. Track event emission rates
  • Memory Usage. Monitor renderer process memory consumption
  • UI Responsiveness. Measure UI update latency
  • Error Rates. Track error occurrence frequency

Conclusion#

Subscribe early, unsubscribe on unmount. Leaking QR or progress listeners is an easy way to grow renderer memory during long sessions.