-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
219 lines (182 loc) · 7.26 KB
/
Copy pathserver.js
File metadata and controls
219 lines (182 loc) · 7.26 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
require('dotenv').config();
const path = require('path');
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const AfricasTalking = require('africastalking');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3000;
const HELP_MESSAGE = 'Invalid report format. Use: StationID#Registered#Cast#Incident e.g. ST001#500#475#None';
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'frontend')));
const sms = process.env.AFRICASTALKING_API_KEY
? AfricasTalking({
username: process.env.AFRICASTALKING_USERNAME || 'sandbox',
apiKey: process.env.AFRICASTALKING_API_KEY
}).SMS
: null;
// Connect to MongoDB
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/election_db';
const connectWithRetry = () => {
mongoose.connect(MONGODB_URI)
.then(() => console.log('Connected to MongoDB successfully'))
.catch(err => {
console.error('MongoDB initial connection error:', err.message);
console.log('Retrying in 5 seconds...');
setTimeout(connectWithRetry, 5000);
});
};
mongoose.connection.on('disconnected', () => {
console.warn('Lost MongoDB connection. Mongoose will attempt to auto-reconnect...');
});
mongoose.connection.on('reconnected', () => {
console.log('Reconnected to MongoDB successfully.');
});
connectWithRetry();
// Define the Report Schema and Model
const reportSchema = new mongoose.Schema({
id: String,
stationId: String,
registered: Number,
cast: Number,
incident: String,
status: String,
severity: String,
receivedAt: String,
sender: String
});
const Report = mongoose.model('Report', reportSchema);
function parsePositiveInteger(value, fieldName) {
const trimmed = String(value || '').trim();
if (!/^\d+$/.test(trimmed)) {
throw new Error(`${fieldName} must be a whole number`);
}
return Number(trimmed);
}
function parseSmsReport(text) {
if (typeof text !== 'string' || text.trim().length === 0) {
throw new Error('SMS text is required');
}
const parts = text.split('#').map(part => part.trim());
if (parts.length !== 4 || parts.some(part => part.length === 0)) {
throw new Error('Expected exactly 4 non-empty fields');
}
const [stationId, registeredRaw, castRaw, incident] = parts;
const registered = parsePositiveInteger(registeredRaw, 'Registered voters');
const cast = parsePositiveInteger(castRaw, 'Cast votes');
const fraudSuspected = cast > registered;
return {
id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
stationId,
registered,
cast,
incident,
status: fraudSuspected ? 'Fraud Suspected' : 'Valid',
severity: fraudSuspected ? 'critical' : incident.toLowerCase() === 'none' ? 'info' : 'warning',
receivedAt: new Date().toISOString()
};
}
function getIncomingSmsPayload(body) {
return {
sender: body.from || body.msisdn || body.sender || body.phoneNumber,
text: body.text || body.message || body.sms || ''
};
}
async function sendHelpSms(to) {
if (!to) {
console.warn('Could not send help SMS: sender phone number missing.');
return;
}
if (!sms) {
console.warn(`Africa's Talking API key missing. Help SMS not sent to ${to}.`);
return;
}
const payload = {
to: [to],
message: HELP_MESSAGE
};
if (process.env.AFRICASTALKING_SENDER_ID) {
payload.from = process.env.AFRICASTALKING_SENDER_ID;
}
await sms.send(payload);
}
app.get('/health', async (req, res) => {
const count = await Report.countDocuments();
res.json({ ok: true, reports: count });
});
app.get('/reports', async (req, res) => {
const reports = await Report.find().sort({ receivedAt: -1 }).limit(100);
res.json({ reports });
});
const mockObservers = [
{ id: 'obs1', name: 'Aisha Bello', phone: '+2348012345678', location: 'Lagos', lastReport: new Date(Date.now() - 5 * 60 * 1000).toISOString(), reliabilityScore: 95, status: 'active' },
{ id: 'obs2', name: 'Chidi Okoro', phone: '+2348023456789', location: 'Abuja', lastReport: new Date(Date.now() - 40 * 60 * 1000).toISOString(), reliabilityScore: 80, status: 'idle' },
{ id: 'obs3', name: 'Fatima Musa', phone: '+2348034567890', location: 'Kano', lastReport: new Date(Date.now() - 120 * 60 * 1000).toISOString(), reliabilityScore: 70, status: 'offline' },
{ id: 'obs4', name: 'David Eka', phone: '+2348045678901', location: 'Rivers', lastReport: new Date(Date.now() - 10 * 60 * 1000).toISOString(), reliabilityScore: 90, status: 'active' },
{ id: 'obs5', name: 'Grace Ade', phone: '+2348056789012', location: 'Oyo', lastReport: new Date(Date.now() - 70 * 60 * 1000).toISOString(), reliabilityScore: 65, status: 'offline' },
];
app.get('/observers', (req, res) => {
// In a real app, you'd fetch this from a database.
// For hackathon, we'll return mock data and update status based on lastReport time.
const updatedObservers = mockObservers.map(obs => {
const lastReportTime = new Date(obs.lastReport).getTime();
const now = Date.now();
const diffMinutes = (now - lastReportTime) / (1000 * 60);
let status = 'offline';
if (diffMinutes < 30) {
status = 'active';
} else if (diffMinutes < 60) { // Idle if no report in last 30-60 mins
status = 'idle';
}
return { ...obs, status };
});
res.json({ observers: updatedObservers });
});
app.post('/broadcast-sms', async (req, res) => {
const { message, recipients } = req.body; // recipients could be an array of phone numbers or a region
// Implement Africa's Talking Bulk SMS API call here
console.log(`Broadcasting SMS: "${message}" to ${recipients.join(', ')}`);
// await sms.send({ to: recipients, message: message });
res.json({ success: true, message: 'Broadcast initiated (mocked)' });
});
app.post('/webhook', async (req, res, next) => {
const { sender, text } = getIncomingSmsPayload(req.body);
try {
const report = parseSmsReport(text);
report.sender = sender || 'unknown';
// Save the new report into MongoDB
await Report.create(report);
io.emit('sms:report', report);
res.status(200).json({ ok: true, report });
} catch (error) {
try {
await sendHelpSms(sender);
} catch (smsError) {
console.error('Failed to send help SMS:', smsError);
}
res.status(400).json({
ok: false,
error: error.message,
help: HELP_MESSAGE
});
}
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({
ok: false,
error: 'Internal server error'
});
});
io.on('connection', async socket => {
// Send the latest 50 reports to newly connected clients
const reports = await Report.find().sort({ receivedAt: -1 }).limit(50);
socket.emit('reports:snapshot', reports);
});
server.listen(PORT, () => {
console.log(`ElectionGuard server running on http://localhost:${PORT}`);
});