-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMM-CommonAlertingProtocol.js
executable file
·344 lines (303 loc) · 9.03 KB
/
MMM-CommonAlertingProtocol.js
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
/* global Module */
/* Magic Mirror
* Module: MMM-CommonAlertingProtocol
* Based on NewsFeed by Michael Teeuw.
*
* By Ross Younger
* MIT Licensed.
*/
Module.register("MMM-CommonAlertingProtocol", {
defaults: {
/*
Recommendation R.2. – Polling Frequency
MetService recommends the CAP Feed is polled at least every five minutes to ensure timely
receipt of all Warnings and Watches, but not polled more frequently than every two minutes.
*/
reloadInterval: 5 * 60 * 1000,
feeds: [
{
title: "MetService",
url: "https://alerts.metservice.com/cap/rss",
config: {
// You can override settings in commonConfig on a per-feed basis.
},
}
],
maxDisplayItems: 0,
prohibitedWords: [],
removeStartTags: "",
removeEndTags: "",
broadcastAlertUpdates: true,
showAsList: true,
animationSpeed: 2500,
updateInterval: 10000, // How often to update the display when showAsList is false
hideLoading: false,
commonConfig: {
showSourceTitle: true,
showPublishDate: true,
showAreaDescription: true,
showIcon: true,
showAlertTitle: true,
showOnset: true,
showDescription: true,
lengthDescription: 100,
truncDescription: true,
wrapDescription: true,
/* If you want to display the list horizontally (say, showing the icons only) this can be done with custom CSS:
.cap-list li { display: inline-block; }
*/
},
cacheFeed: false, // Intended for development only
lat: null, // Geo-filter location
lon: null, // Geo-filter location
},
requiresVersion: "2.1.0", // Required version of MagicMirror
start: function() {
Log.info(`Starting module: ${this.name}`);
this.alertItems = [];
this.activeItem = 0;
this.loaded = false;
this.error = null;
this.registerFeeds();
},
getUrlPrefix: function (item) {
if (item.useCorsProxy) {
return `${location.protocol}//${location.host}/cors?url=`;
} else {
return "";
}
},
getScripts: function() {
return ["moment.js"];
},
getStyles: function () {
return ["font-awesome.css", "weather-icons.css", "MMM-CommonAlertingProtocol.css"];
},
// Load translations files
getTranslations: function() {
return {
en: "translations/en.json",
};
},
getTemplate: function () {
return "cap.njk";
},
getTemplateData: function () {
if (this.activeItem >= this.alertItems.length)
this.activeItem = 0;
return {
config: this.config,
item: this.alertItems[this.activeItem],
items: this.alertItems,
loaded: this.loaded,
};
},
registerFeeds: function () {
for (let feed of this.config.feeds) {
this.sendSocketNotification("ADD_FEED", {
feed: feed,
config: this.config
});
}
},
socketNotificationReceived: function (notification, payload) {
if (notification === "FEED_ITEMS") {
this.generateAlerts(payload);
if (!this.loaded) {
if (this.config.hideLoading) {
this.show();
}
this.updateDom(this.config.animationSpeed);
this.scheduleUpdateInterval();
}
this.loaded = true;
this.error = null;
this.updateDom(100);
} else if (notification === "FEED_ERROR") {
this.error = this.translate(payload.error_type);
this.updateDom(this.config.animationSpeed);
this.scheduleUpdateInterval();
}
},
/** Map MetService event types into WI icons */
convertEventType: function (event) {
let s = String(event).toLowerCase();
switch (s) {
case "wind":
return "strong-wind";
case "localStorm":
return "thunderstorm";
default:
return s;
}
},
/**
* Generate a merged config block for a feed
* @note If multiple feeds are configured with the same URL, the results may be surprising.
* The helper assumes feed URLs are unique.
*/
configForFeed: function (url) {
for (let iter in this.config.feeds) {
const feed = this.config.feeds[iter];
if (feed.url === url) {
return { ...this.defaults.commonConfig, ... this.config.commonConfig, ...feed.config };
}
}
console.log(`Missing feed config?! ${url}`);
return { ...this.defaults.commonConfig, ... this.config.commonConfig };
},
/**
* Generate an ordered list of items for this configured module.
* @param {object} feeds An object with feeds returned by the node helper.
*/
generateAlerts: function (feeds) {
let newsItems = [];
for (let feed in feeds) {
const feedItems = feeds[feed];
const thisFeedConfig = this.configForFeed(feed);
if (this.subscribedToFeed(feed)) {
for (let item of feedItems) {
item.sourceTitle = this.titleForFeed(feed);
item.config = thisFeedConfig;
if (!(this.config.ignoreOldItems && Date.now() - new Date(item.pubdate) > this.config.ignoreOlderThan)) {
newsItems.push(item);
}
}
}
}
newsItems.sort(function (a, b) {
const dateA = new Date(a.pubdate);
const dateB = new Date(b.pubdate);
return dateB - dateA;
});
if (this.config.maxDisplayItems > 0) {
newsItems = newsItems.slice(0, this.config.maxDisplayItems);
}
if (this.config.prohibitedWords.length > 0) {
newsItems = newsItems.filter(function (item) {
for (let word of this.config.prohibitedWords) {
if (item.title.toLowerCase().indexOf(word.toLowerCase()) > -1) {
return false;
}
}
return true;
}, this);
}
newsItems.forEach((item) => {
//Remove selected tags from the beginning of rss feed items (title or description)
if (this.config.removeStartTags === "title" || this.config.removeStartTags === "both") {
for (let startTag of this.config.startTags) {
if (item.title.slice(0, startTag.length) === startTag) {
item.title = item.title.slice(startTag.length, item.title.length);
}
}
}
if (this.config.removeStartTags === "description" || this.config.removeStartTags === "both") {
if (this.isShowingDescription) {
for (let startTag of this.config.startTags) {
if (item.description.slice(0, startTag.length) === startTag) {
item.description = item.description.slice(startTag.length, item.description.length);
}
}
}
}
//Remove selected tags from the end of rss feed items (title or description)
if (this.config.removeEndTags) {
for (let endTag of this.config.endTags) {
if (item.title.slice(-endTag.length) === endTag) {
item.title = item.title.slice(0, -endTag.length);
}
}
if (this.isShowingDescription) {
for (let endTag of this.config.endTags) {
if (item.description.slice(-endTag.length) === endTag) {
item.description = item.description.slice(0, -endTag.length);
}
}
}
}
// process data we want to directly report
item.publishDate = moment(new Date(item.pubdate)).fromNow();
item.severity = item.detail[0]?.severity || "unknown"; // Minor, Moderate, Severe
item.iconClass = this.convertEventType(item.detail[0]?.event);
var areas = [];
item.detail.forEach((detail) => {
detail.area.forEach((area) => {
if (area.areaDesc)
areas.push(area.areaDesc);
});
});
item.areas = areas.join(", ");
let onset = item.detail[0]?.onset;
if (onset) {
item.onset = moment(new Date(onset)).calendar();
}
});
// sort (b-a) so that highest severity appears first
newsItems.sort((a, b) => numericSeverity(b) - numericSeverity(a));
// get updated news items and broadcast them
const updatedItems = [];
newsItems.forEach((value) => {
if (this.alertItems.findIndex((value1) => value1 === value) === -1) {
// Add item to updated items list
updatedItems.push(value);
}
});
// check if updated items exist, if so and if we should broadcast these updates, then lets do so
if (this.config.broadcastAlertUpdates && updatedItems.length > 0) {
this.sendNotification("CAP_ALERT_UPDATE", { items: updatedItems });
}
this.alertItems = newsItems;
},
/**
* Returns title for the specific feed url.
* @param {string} feedUrl Url of the feed
* @returns {string} The title of the feed
*/
titleForFeed: function (feedUrl) {
for (let feed of this.config.feeds) {
if (feed.url === feedUrl) {
return feed.title || "";
}
}
return "";
},
/**
* Check if this module is configured to show this feed.
* @param {string} feedUrl Url of the feed to check.
* @returns {boolean} True if it is subscribed, false otherwise
*/
subscribedToFeed: function (feedUrl) {
for (let feed of this.config.feeds) {
if (feed.url === feedUrl) {
return true;
}
}
return false;
},
/**
* Schedule visual update, when in single-item mode
*/
scheduleUpdateInterval: function () {
this.updateDom(this.config.animationSpeed);
// Clear timer if it already exists
if (this.timer) clearInterval(this.timer);
if (!this.config.showAsList) {
this.timer = setInterval(() => {
if (this.alertItems.length > 1) {
this.activeItem++;
this.updateDom(this.config.animationSpeed);
}
}, this.config.updateInterval);
}
},
});
function numericSeverity(event) {
let s = String(event?.severity || "unknown").toLowerCase();
switch (s) {
case "minor": return 1;
case "moderate": return 2;
case "severe": return 3;
default: return 0;
}
}