This repository was archived by the owner on Mar 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvanced_emergency_system.js
More file actions
169 lines (146 loc) · 5.04 KB
/
Copy pathadvanced_emergency_system.js
File metadata and controls
169 lines (146 loc) · 5.04 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
const express = require('express');
const mongoose = require('mongoose');
const twilio = require('twilio');
const { Translate } = require('@google-cloud/translate').v2;
const axios = require('axios');
const i18n = require('i18n');
const crypto = require('crypto');
require('dotenv').config();
const app = express();
app.use(express.json());
// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/hospitalDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.once('open', () => {
console.log('Connected to MongoDB');
});
// Twilio Setup for Emergency Calls
const twilioClient = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
// Google Translate API Setup
const translate = new Translate({ key: process.env.GOOGLE_TRANSLATE_API_KEY });
// i18n Configuration for Multilingual Support
i18n.configure({
locales: ['en', 'ar', 'es', 'fr', 'zh', 'hi'],
directory: `${__dirname}/locales`,
defaultLocale: 'en',
});
app.use(i18n.init);
// Schema Definitions
const patientSchema = new mongoose.Schema({
name: String,
phoneNumber: String,
medicalHistory: [String],
preferredLanguage: { type: String, default: 'en' },
emergencyContacts: [{ name: String, phone: String }],
});
const volunteerSchema = new mongoose.Schema({
name: String,
phoneNumber: String,
location: {
latitude: Number,
longitude: Number,
},
skills: [String],
});
const Patient = mongoose.model('Patient', patientSchema);
const Volunteer = mongoose.model('Volunteer', volunteerSchema);
// Emergency Assistance Endpoint
app.post('/emergency', async (req, res) => {
const { patientId, emergencyType, location } = req.body;
const patient = await Patient.findById(patientId).exec();
if (!patient) {
return res.status(404).send({ message: 'Patient not found' });
}
const guidance = await translateText(
i18n.__(`emergency.guidance.${emergencyType}`),
patient.preferredLanguage
);
twilioClient.calls
.create({
url: `${req.protocol}://${req.get('host')}/twiml/${emergencyType}`,
to: patient.phoneNumber,
from: process.env.TWILIO_PHONE_NUMBER,
})
.then((call) => console.log('Emergency call initiated:', call.sid))
.catch((error) => console.error('Error initiating emergency call:', error));
const volunteers = await findNearbyVolunteers(location, emergencyType);
volunteers.forEach((volunteer) => {
twilioClient.messages
.create({
body: `Emergency Alert: A ${emergencyType} has occurred nearby. Please assist if possible.`,
from: process.env.TWILIO_PHONE_NUMBER,
to: volunteer.phoneNumber,
})
.then((message) => console.log('Notification sent to volunteer:', message.sid))
.catch((error) => console.error('Error notifying volunteer:', error));
});
res.status(200).send({
message: 'Emergency assistance is on the way.',
guidance,
volunteersNotified: volunteers.length,
});
});
// First Aid Booklet API
app.get('/first-aid', async (req, res) => {
const language = req.query.language || 'en';
i18n.setLocale(language);
const booklet = {
title: res.__('firstAid.title'),
chapters: [
{ title: res.__('firstAid.chapter1.title'), content: res.__('firstAid.chapter1.content') },
{ title: res.__('firstAid.chapter2.title'), content: res.__('firstAid.chapter2.content') },
],
audioUrl: `${req.protocol}://${req.get('host')}/first-aid/audio/${language}`,
};
res.status(200).send(booklet);
});
// First Aid Audio API
app.get('/first-aid/audio/:language', (req, res) => {
const language = req.params.language || 'en';
const audioFilePath = `${__dirname}/audio/first-aid-${language}.mp3`;
res.download(audioFilePath, 'first-aid.mp3', (err) => {
if (err) res.status(500).send({ message: 'Audio file not found' });
});
});
// Translate Text
async function translateText(text, targetLanguage) {
try {
const [translation] = await translate.translate(text, targetLanguage);
return translation;
} catch (error) {
console.error('Translation error:', error);
return text;
}
}
// Find Nearby Volunteers
async function findNearbyVolunteers(location, emergencyType) {
const volunteers = await Volunteer.find().exec();
return volunteers.filter((volunteer) => {
const distance = calculateDistance(
location.latitude,
location.longitude,
volunteer.location.latitude,
volunteer.location.longitude
);
return distance <= 10 && volunteer.skills.includes(emergencyType);
});
}
// Calculate Distance (Haversine Formula)
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = ((lat2 - lat1) * Math.PI) / 180;
const dLon = ((lon2 - lon1) * Math.PI) / 180;
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});