-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMagicMirror-air-raid-monitor-ua.js
More file actions
393 lines (335 loc) · 10.4 KB
/
Copy pathMagicMirror-air-raid-monitor-ua.js
File metadata and controls
393 lines (335 loc) · 10.4 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
const AIR_RAID_MODULE_NAME = 'MagicMirror-air-raid-monitor-ua';
// Ukraine Alert API oblast regionId -> `name` attribute of the region shape in public/ua.svg.
// regionIds are the API's stable identifiers; names/types are not reliable keys.
const OBLAST_ID_TO_SVG_NAME = {
'3': "Khmel'nyts'kyy",
'4': 'Vinnytsya',
'5': 'Rivne',
'8': 'Volyn',
'9': "Dnipropetrovs'k",
'10': 'Zhytomyr',
'11': 'Transcarpathia',
'12': 'Zaporizhzhya',
'13': "Ivano-Frankivs'k",
'14': 'Kyiv',
'15': 'Kirovohrad',
'16': "Luhans'k",
'17': 'Mykolayiv',
'18': 'Odessa',
'19': 'Poltava',
'20': 'Sumy',
'21': "Ternopil'",
'22': 'Kharkiv',
'23': 'Kherson',
'24': 'Cherkasy',
'25': 'Chernihiv',
'26': 'Chernivtsi',
'27': "L'viv",
'28': "Donets'k",
'31': 'Kyiv City',
'9999': 'Crimea',
};
// City communities that the API lists at the top level of /regions (typed "State"
// although they are not oblasts) -> the oblast they belong to.
const TOP_LEVEL_COMMUNITY_TO_OBLAST = {
'564': '12', // м. Запоріжжя та Запорізька ТГ -> Запорізька область
'1293': '22', // м. Харків та Харківська ТГ -> Харківська область
};
// How often to re-request the regions hierarchy; administrative changes are rare.
const REGIONS_REFRESH_INTERVAL = 7 * 24 * 60 * 60 * 1000;
Module.register(AIR_RAID_MODULE_NAME, {
requiresVersion: "2.19.0",
styleSelectorPrefix: 'air-raid-status',
status: {
no_data: 'no_data',
partial: 'partial',
full: 'full'
},
defaults: {
// The API rate-limits each key to roughly 1 request/minute (exceeding it
// returns empty 401s), so polling faster than 60s locks the module out.
updateInterval: 60 * 1.5, // seconds, also the minimum
// An oblast is painted "full" once more than this fraction of its
// districts/communities have an active alert of their own.
fullAlertThreshold: 0.5,
},
isLoading: false,
airRaidData: [],
requestTimer: null,
mapSVG: null,
storedActionIndex: null,
regionToOblast: null,
totalPartsByOblast: null,
childrenByRegionId: null,
regionsLoadedAt: 0,
getStyles: function() {
return [
this.file(`${AIR_RAID_MODULE_NAME}.css`)
];
},
start: function() {
this.loadAirRaidData();
this.initLoaderTimer();
},
stop: function() {
this.clearTimer();
},
getDom: async function() {
const wrapper = document.createElement("div");
wrapper.className = `${AIR_RAID_MODULE_NAME}-wrapper`;
let content = await this.mapTemplate();
if (this.isLoading) {
content += this.getPreloaderLoader();
}
wrapper.innerHTML = content;
return wrapper;
},
getUpdateTimerInterval: function() {
return Math.max(this.config.updateInterval, this.defaults.updateInterval) * 1000;
},
// All node_helper routes share the auth header and error contract.
fetchLocal: async function(path) {
const response = await fetch(path, {
headers: {
'Authorization': this.config.apiKey,
}
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
return response.json();
},
getMapSVG: async function() {
if (this.mapSVG) {
return this.mapSVG;
}
try {
const responseData = await fetch(`/${AIR_RAID_MODULE_NAME}/ua.svg`);
this.mapSVG = await responseData.text();
} catch (e) {
Log.error(e);
}
return this.mapSVG;
},
// Builds regionId -> oblast regionId, oblastId -> descendant part count, and
// regionId -> immediate child regionIds, from the /regions hierarchy. Cached by
// the node_helper, so only the first request after a MagicMirror start goes upstream.
loadRegions: async function() {
if (this.regionToOblast && Date.now() - this.regionsLoadedAt < REGIONS_REFRESH_INTERVAL) {
return;
}
try {
const { states } = await this.fetchLocal('/regions');
const regionToOblast = {};
const totalPartsByOblast = {};
const childrenByRegionId = {};
const walk = (region, oblastId) => {
regionToOblast[region.regionId] = oblastId;
if (region.regionId !== oblastId) {
totalPartsByOblast[oblastId] = (totalPartsByOblast[oblastId] || 0) + 1;
}
const childIds = (region.regionChildIds || []).map(child => child.regionId);
if (childIds.length) {
childrenByRegionId[region.regionId] = childIds;
}
(region.regionChildIds || []).forEach(child => walk(child, oblastId));
};
states.forEach(state => walk(state, TOP_LEVEL_COMMUNITY_TO_OBLAST[state.regionId] || state.regionId));
this.regionToOblast = regionToOblast;
this.totalPartsByOblast = totalPartsByOblast;
this.childrenByRegionId = childrenByRegionId;
this.regionsLoadedAt = Date.now();
} catch (e) {
Log.error(e);
}
},
loadAirRaidData: async function() {
const hadRegions = Boolean(this.regionToOblast);
await this.loadRegions();
const regionsJustLoaded = !hadRegions && Boolean(this.regionToOblast);
const shouldUpdateStatus = await this.shouldUpdateStatus();
if (!shouldUpdateStatus) {
// The map renders gray while the regions hierarchy is missing, so a late
// /regions arrival must trigger a re-render even without new alert data.
if (regionsJustLoaded) {
this.updateDom();
}
return;
}
this.isLoading = true;
this.updateDom();
try {
this.airRaidData = await this.fetchLocal('/alerts');
const activeRegions = Array.isArray(this.airRaidData)
? this.airRaidData.filter(region => region.activeAlerts?.length)
: [];
Log.info(`Air raid alerts: ${activeRegions.length} region(s) with active alerts`, this.airRaidData);
} catch(e) {
Log.error(e);
// The action index is already committed, so without a reset the next cycle
// would see "no change" and this failed /alerts fetch would never be retried.
this.storedActionIndex = null;
}
this.isLoading = false;
this.updateDom();
},
shouldUpdateStatus: async function() {
try {
const { lastActionIndex } = await this.fetchLocal('/status');
const shouldUpdate = this.storedActionIndex !== lastActionIndex;
this.storedActionIndex = lastActionIndex;
return shouldUpdate;
} catch(e) {
Log.error(e);
// Skip the /alerts call this cycle: a failed /status is usually the API
// rate limiter, and another request would keep the key locked out.
return false;
}
},
initLoaderTimer: function() {
this.clearTimer();
this.requestTimer = setTimeout(() => {
this.loadAirRaidData();
this.initLoaderTimer();
}, this.getUpdateTimerInterval());
},
clearTimer: function() {
if (this.requestTimer) {
clearTimeout(this.requestTimer);
this.requestTimer = null;
}
},
// Turns the API's alert entries into { svgRegionName: status }: an oblast's
// own alert always marks it "full"; a district's own alert covers all of
// its communities too (the real API reports alerts at district
// granularity, not per-community); otherwise it's "full" once more than
// config.fullAlertThreshold of its districts/communities are covered,
// else "partial" for any lesser fraction.
getRegionStatuses: function () {
const result = {};
if (!Array.isArray(this.airRaidData) || !this.regionToOblast) {
return result;
}
const selfAlertedOblasts = new Set();
const coveredPartsByOblast = {};
const addCovered = (oblastId, regionId) => {
if (!coveredPartsByOblast[oblastId]) {
coveredPartsByOblast[oblastId] = new Set();
}
const covered = coveredPartsByOblast[oblastId];
if (covered.has(regionId)) {
return;
}
covered.add(regionId);
(this.childrenByRegionId?.[regionId] || []).forEach(childId => addCovered(oblastId, childId));
};
this.airRaidData.forEach(entry => {
if (!entry.activeAlerts?.length) {
return;
}
const oblastId = this.regionToOblast[entry.regionId];
if (!oblastId) {
return;
}
if (entry.regionId === oblastId) {
selfAlertedOblasts.add(oblastId);
} else {
addCovered(oblastId, entry.regionId);
}
});
const alertedOblastIds = new Set([...selfAlertedOblasts, ...Object.keys(coveredPartsByOblast)]);
alertedOblastIds.forEach(oblastId => {
const svgName = OBLAST_ID_TO_SVG_NAME[oblastId];
if (!svgName) {
return;
}
if (selfAlertedOblasts.has(oblastId)) {
result[svgName] = this.status.full;
return;
}
const totalParts = this.totalPartsByOblast?.[oblastId] || 0;
const alertedParts = coveredPartsByOblast[oblastId]?.size || 0;
const ratio = totalParts > 0 ? alertedParts / totalParts : 0;
result[svgName] = ratio > this.config.fullAlertThreshold ? this.status.full : this.status.partial;
});
return result;
},
mapTemplate: async function () {
return `
${this.getMapStyles()}
${await this.getMapSVG()}
${this.getMapLegend()}
`;
},
getMapStyles: function () {
const statuses = {
[this.status.no_data]: {
selectors: [`.${this.styleSelectorPrefix}-${this.status.no_data}`],
styles: `{
fill: rgba(255,255,255,0.25);
background-color: rgba(255,255,255,0.25);
border: 1px solid red;
stroke: red;
}`
},
[this.status.partial]: {
selectors: [`.${this.styleSelectorPrefix}-${this.status.partial}`],
styles: `{
background-color: rgba(255,255,255,0.5);
border: 1px solid #ffffff;
fill: rgba(255,255,255,0.5);
stroke: #000000;
}`
},
[this.status.full]: {
selectors: [`.${this.styleSelectorPrefix}-${this.status.full}`],
styles: `{
background-color: rgba(255,255,255,0.9);
border: 1px solid #ffffff;
fill: rgba(255,255,255,1);
stroke: #000000;
}`
}
};
const regionStatuses = this.getRegionStatuses();
Object.keys(regionStatuses).map(region => {
const status = regionStatuses[region];
if (!status || !statuses[status]) {
return;
}
statuses[status].selectors.push(`[name="${region}"]`);
});
const stylesList = Object.keys(statuses).map(status => {
const {selectors, styles} = statuses[status];
if (!selectors?.length) {
return '';
}
return `${selectors.join(',')} ${styles}`;
});
return `<style>${stylesList.join(' ')}</style>`;
},
getMapLegend: function () {
const itemsList = Object.keys(this.status).map(key => {
const status = this.status[key];
return `
<li class="graph-legend-item">
<span class="${this.styleSelectorPrefix}-${status}"></span> ${this.translate(status)}
</li>
`;
});
return `<ul class="graph-legend">${itemsList.join('')}</ul>`;
},
getPreloaderLoader: function () {
return `
<div class="preloader">
<div class="preloader__spinner"></div>
</div>
`;
},
getTranslations: function() {
return {
en: "translations/en.json",
uk: "translations/uk.json"
}
}
});