This commit is contained in:
Mekan1206
2026-06-02 14:28:25 +05:00
commit b154d5c198
9 changed files with 2049 additions and 0 deletions

51
queueWorker.js Normal file
View File

@@ -0,0 +1,51 @@
const db = require('./db');
function startQueueWorker(io) {
console.log('Starting SMS Queue Worker...');
setInterval(() => {
// Check if there are any connected devices (we'll broadcast to the 'devices' room)
// For simplicity, we just fetch one pending message and emit it.
// If the app is connected, it will process it.
db.get(`SELECT * FROM sms_queue WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1`, (err, row) => {
if (err) {
console.error('Queue Worker Error:', err);
return;
}
if (row) {
console.log(`Processing SMS ID: ${row.id} for ${row.phone}`);
// Mark as processing
db.run(`UPDATE sms_queue SET status = 'processing', updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [row.id], (updateErr) => {
if (updateErr) {
console.error('Error updating status to processing:', updateErr);
return;
}
// Emit to authenticated devices
io.to('devices').emit('send_sms', {
id: row.id,
phone: row.phone,
message: row.message
});
// Note: If no device is connected, it stays in 'processing' state.
// A robust system would have a timeout to revert 'processing' back to 'pending'.
// We will add a simple timeout mechanism.
setTimeout(() => {
db.get(`SELECT status FROM sms_queue WHERE id = ?`, [row.id], (checkErr, checkRow) => {
if (checkRow && checkRow.status === 'processing') {
console.log(`SMS ID: ${row.id} timed out. Reverting to pending.`);
db.run(`UPDATE sms_queue SET status = 'pending' WHERE id = ?`, [row.id]);
}
});
}, 30000); // 30 seconds timeout
});
}
});
}, 5000); // Check every 5 seconds
}
module.exports = startQueueWorker;