-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.js
More file actions
281 lines (237 loc) · 9.63 KB
/
database.js
File metadata and controls
281 lines (237 loc) · 9.63 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import fs from 'fs';
function _formatAlertIdentity(identity) {
if (!identity) {
return 'null';
}
if (typeof identity === 'string') {
return identity;
}
const officeId = identity.officeId || '?';
const phenomena = identity.phenomena || '?';
const significance = identity.significance || '?';
const eventTrackingNumber = identity.eventTrackingNumber || '?';
return `${officeId}.${phenomena}.${significance}.${eventTrackingNumber}`;
}
function _getUpdatedProps(updatedMessage) {
// Cancellation mesesages have no props
// Thus, a PDS tornado warning for example may appear downgraded
// We need to ignore cancellation messages for props
const messages = updatedMessage.split('#####');
// Loop until latest non-cancellation message
let latestMessageForProps = '';
for (let i = messages.length - 1; i >= 0; i--) {
const thisMessage = messages[i].trim();
if (thisMessage) {
if (thisMessage.toLowerCase().includes('has been cancelled')){
continue; // Skip cancellation messages
} else {
// This is the latest non-cancellation message, use it for properties
latestMessageForProps = thisMessage;
break;
}
}
}
return {
isPds: latestMessageForProps.toLowerCase().includes('particularly dangerous situation') || false,
isConsiderable: latestMessageForProps.toLowerCase().includes('thunderstorm damage threat...considerable') || false,
isDestructive: latestMessageForProps.toLowerCase().includes('thunderstorm damage threat...destructive') || false,
isEmergency: latestMessageForProps.toLowerCase().includes('tornado emergency') || latestMessageForProps.toLowerCase().includes('flash flood emergency') || false,
isTorPossible: latestMessageForProps.toLowerCase().includes('tornado...possible') || false,
isTorConfirmed: latestMessageForProps.toLowerCase().includes('tornado...observed') || false,
isTorRadarIndicated: latestMessageForProps.toLowerCase().includes('tornado...radar indicated') || false,
isWaterspoutPossible: latestMessageForProps.toLowerCase().includes('waterspout...possible') || false,
};
}
function _isMatchingAlert(alert, identity) {
if (!identity) {
return false;
}
const alertVtec = alert?.vtec;
if (!alertVtec) {
return false;
}
if (typeof identity === 'string') {
return alertVtec.eventTrackingNumber === identity;
}
return (
alertVtec.eventTrackingNumber === identity.eventTrackingNumber &&
alertVtec.officeId === identity.officeId &&
alertVtec.phenomena === identity.phenomena &&
alertVtec.significance === identity.significance
);
}
// Function to read the alert database
function readAlertDatabase() {
try {
const data = fs.readFileSync('alerts.json', 'utf8');
return JSON.parse(data);
} catch (err) {
if (err.code === 'ENOENT') {
fs.writeFileSync('alerts.json', JSON.stringify([]), 'utf8');
return [];
} else {
throw new Error('Error reading alert database: ' + err.message);
}
}
}
function addNewAlert(alert) {
try {
const alerts = readAlertDatabase();
alerts.push(alert);
// No formatting to reduce file size
fs.writeFileSync('alerts.json', JSON.stringify(alerts), 'utf8');
} catch (err) {
throw new Error('Error adding new alert: ' + err.message);
}
}
function checkAndRemoveExpiredAlerts() {
try {
const alerts = readAlertDatabase();
const now = new Date();
// Filter out expired alerts
const activeAlerts = alerts.filter(alert => {
const expireTime = alert.expiresAt ? new Date(alert.expiresAt) : alert.vtec?.expireTime ? new Date(alert.vtec.expireTime) : null;
if (!expireTime) return true; // If no expiration, keep it
return expireTime > now;
});
// Write the updated list back to the database
fs.writeFileSync('alerts.json', JSON.stringify(activeAlerts), 'utf8');
console.log("Expired alert cleanup ran successfully.\n");
} catch (err) {
throw new Error('Error checking/removing expired alerts: ' + err.message);
}
}
function deleteAlert(alertIdentity) {
try {
if (!alertIdentity) {
throw new Error('Cannot delete alert: alert identity is required');
}
const alerts = readAlertDatabase();
const updatedAlerts = alerts.filter(alert => !_isMatchingAlert(alert, alertIdentity));
if (updatedAlerts.length === alerts.length) {
throw new Error(`Alert not found with identity ${_formatAlertIdentity(alertIdentity)}`);
}
fs.writeFileSync('alerts.json', JSON.stringify(updatedAlerts), 'utf8');
} catch (err) {
throw new Error('Error deleting alert: ' + err.message);
}
}
function updateAlert(alertIdentity, updatedData) {
// Use VTEC identity to identify alert
try {
if (!alertIdentity) {
throw new Error('Cannot update alert: alert identity is required');
}
const alerts = readAlertDatabase();
let alertFound = false;
let updatedAlert = null;
const updatedAlerts = alerts.map(alert => {
if (_isMatchingAlert(alert, alertIdentity)) {
alertFound = true;
console.log(`Updating alert with identity ${_formatAlertIdentity(alertIdentity)}`);
const updatedMessage = updatedData.message + "\n\n#####\n\n" + (alert.message || ''); // Prepend update message to original message
const updatedProps = _getUpdatedProps(updatedMessage);
updatedAlert = {
id: alert.id,
productCode: alert.productCode,
productName: alert.productName,
receivedAt: new Date().toISOString(),
expiresAt: updatedData.expiresAt || new Date(Date.now() + 3600000).toISOString(), // Default to 1 hour if no expiration provided
nwsOffice: updatedData.nwsOffice,
vtec: updatedData.vtec,
message: updatedMessage,
geometry: updatedData.geometry,
properties: updatedProps
};
return updatedAlert;
}
return alert;
});
if (!alertFound) {
throw new Error(`Alert not found with identity ${_formatAlertIdentity(alertIdentity)}`);
}
fs.writeFileSync('alerts.json', JSON.stringify(updatedAlerts), 'utf8');
return updatedAlert;
} catch (err) {
throw new Error('Error updating alert: ' + err.message);
}
}
function cancelAlert(alertIdentity, updatedData) {
// Find alert by VTEC identity
try {
if (!alertIdentity) {
throw new Error('Cannot cancel alert: alert identity is required');
}
const alerts = readAlertDatabase();
let alertFound = false;
let updatedAlert = null;
const updatedAlerts = alerts.map(alert => {
if (_isMatchingAlert(alert, alertIdentity)) {
alertFound = true;
console.log(`Cancelling alert with identity ${_formatAlertIdentity(alertIdentity)}`);
const updatedMessage = updatedData.message + "\n\n#####\n\n" + (alert.message || ''); // Prepend update message to original message
const updatedProps = _getUpdatedProps(updatedMessage);
updatedAlert = {
id: alert.id,
productCode: alert.productCode,
productName: alert.productName,
receivedAt: new Date().toISOString(),
expiresAt: alert.expiresAt,
nwsOffice: alert.nwsOffice,
vtec: updatedData.vtec,
message: updatedMessage,
geometry: updatedData.geometry, // Use updated geometry
properties: updatedProps
};
return updatedAlert;
}
return alert;
});
if (!alertFound) {
throw new Error(`Alert not found with identity ${_formatAlertIdentity(alertIdentity)}`);
}
fs.writeFileSync('alerts.json', JSON.stringify(updatedAlerts), 'utf8');
return updatedAlert;
} catch (err) {
throw new Error('Error canceling alert: ' + err.message);
}
}
function storeProduct(code, productData) {
try {
let json, filePath;
try {
json = JSON.stringify(productData);
filePath = `products/${code.toLowerCase()}.json`;
} catch (err) {
json = String(productData);
filePath = `products/${code.toLowerCase()}.txt`;
}
fs.mkdirSync('products', { recursive: true });
fs.writeFileSync(filePath, json, 'utf8');
} catch (err) {
throw new Error('Error storing product data: ' + err.message);
}
}
function getProduct(code) {
try {
const filePath = `products/${code.toLowerCase()}.json`;
if (!fs.existsSync(filePath)) {
throw new Error(`Product with code ${code} not found`);
}
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (err) {
throw new Error('Error retrieving product data: ' + err.message);
}
}
// Export the database functions
export {
readAlertDatabase,
addNewAlert,
checkAndRemoveExpiredAlerts,
deleteAlert,
updateAlert,
cancelAlert,
storeProduct,
getProduct
};