-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpluginManager.js
More file actions
345 lines (314 loc) · 10.5 KB
/
Copy pathpluginManager.js
File metadata and controls
345 lines (314 loc) · 10.5 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
import fs from "fs";
import path from "path";
import { promisify } from "util";
import env from "./env.js";
import database from "./database.js";
const fsReaddirAsync = promisify(fs.readdir);
String.prototype.replaceAll = function(strReplace, strWith) {
// See http://stackoverflow.com/a/3561711/556609
var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var reg = new RegExp(esc, 'ig');
return this.replace(reg, strWith);
};
class PluginManager {
constructor(isRss) {
this.plugins = [];
this.rssQueue = [];
this.rssSendInterval = setInterval(() => this.processRssQueue(), 4000);
}
startInterval() {
if (!this.rssSendInterval) {
this.rssSendInterval = setInterval(() => this.processRssQueue(), 4000);
}
}
async loadPlugins() {
const internalPluginFiles = await fsReaddirAsync("src/plugins");
const thirdPartyFiles = await fsReaddirAsync(
path.join(env.DATA_PATH, "plugins")
).catch((e) => []);
const internalPlugins = await Promise.all(
internalPluginFiles
.filter((f) => !f.endsWith(".src"))
.map((f) => import("./" + path.join("plugins", f)))
);
const thirdPartyPlugins = await Promise.all(
thirdPartyFiles.map((f) => import("./" + path.join("plugins", f)))
);
this.plugins = [].concat(internalPlugins.map((p) => p.default)).concat(
thirdPartyPlugins.map((p) => {
p.default.thirdParty = true;
return p.default;
})
);
const pluginsUsedInGroups = new Set(
(database.data.groupPluginSettings || []).map((s) => s.pluginId)
);
this._initializedPlugins = new Set();
await Promise.all(
this.plugins
.filter((p) => {
const globallyEnabled = database.data.pluginSettings.find((ps) => ps.id === p.id)?.enabled ?? false;
return globallyEnabled || pluginsUsedInGroups.has(p.id);
})
.map((p) => {
this._initializedPlugins.add(p.id);
return p.onPluginEnabled && p.onPluginEnabled();
})
);
}
async handleEvents(events, newData) {
let hostEvents = [];
let hostPlugins = {};
if (newData.enabledNotifList) {
const eventsList = Object.values(newData.enabledNotifList)
.filter((e) => !e.value)
.map((e) => e.events)
.flat();
hostEvents = [...eventsList];
}
if (!newData.enabledPlugins) {
hostPlugins = {
ALL_PLUGINS: {
value: true,
},
TELEGRAM: {
value: true,
},
SLACK: {
value: true,
},
EMAIL: {
value: true,
},
};
} else {
hostPlugins = newData.enabledPlugins;
}
const pluginsForHost = [
["telegram-notifications", "TELEGRAM"],
["slack-notifications", "SLACK"],
["gmail-notifications", "EMAIL"],
["email-notifications", "EMAIL"],
];
function getEnabledPluginsForHost() {
if (hostPlugins.ALL_PLUGINS.value) {
return pluginsForHost.map((p) => {
return p[0];
});
} else {
let newArr = [];
pluginsForHost.forEach((p) => {
if (hostPlugins[p[1]].value) {
newArr.push(p[0]);
}
});
return newArr;
}
}
const enabledPlugins = getEnabledPluginsForHost();
for (let eventType of events) {
console.log(`[PluginManager] Event: ${eventType} | host: ${newData.HOST_NAME || newData.url || '?'} | hostEvents disabled: [${hostEvents.join(',')}] | enabledPlugins: [${enabledPlugins.join(',')}]`);
const plugins = this.plugins
.map((p) => {
const globalSettings =
database.data.pluginSettings.find((ps) => ps.id === p.id) || {};
// Merge group-specific plugin settings on top of global settings
const groupEntry = newData.HOST_GROUP?.pluginSettings?.[p.id];
const settings = groupEntry
? {
...globalSettings,
params: { ...globalSettings.params, ...groupEntry.params },
// Only override enabledEvents when explicitly set in group entry
...('enabledEvents' in groupEntry ? { enabledEvents: groupEntry.enabledEvents } : {}),
}
: globalSettings;
return { plugin: p, settings };
})
.filter((p) => {
const effectiveEnabledEvents = p.plugin.getEffectiveEnabledEvents
? p.plugin.getEffectiveEnabledEvents({ data: newData, settings: p.settings })
: p.settings.enabledEvents;
const hasGroupOverride = !!newData.HOST_GROUP?.pluginSettings?.[p.plugin.id];
const effectiveEnabled = hasGroupOverride || p.settings.enabled;
const pass =
effectiveEnabled &&
effectiveEnabledEvents?.includes(eventType) &&
!hostEvents.includes(eventType) &&
enabledPlugins.includes(p.plugin.id);
if (!pass) {
console.log(`[PluginManager] Skip plugin ${p.plugin.id}: enabled=${effectiveEnabled}(group=${hasGroupOverride}) hasEvent=${effectiveEnabledEvents?.includes(eventType)} notSuppressed=${!hostEvents.includes(eventType)} inEnabledList=${enabledPlugins.includes(p.plugin.id)}`);
}
return pass;
});
console.log(`[PluginManager] Dispatching ${eventType} to ${plugins.length} plugin(s): [${plugins.map(p => p.plugin.id).join(',')}]`);
// handle event by all plugins in parallel
await Promise.all(
plugins.map(async (p) => {
try {
await p.plugin.handleEvent({
eventType,
data: newData,
settings: p.settings,
});
} catch (e) {
console.error("Error in plugin", p.plugin.id, e, "stack:", e.stack);
}
})
);
}
}
async processRssQueue() {
if (this.rssQueue.length) {
const { rssFormatedMessage, enabledPlugins, hostGroup } = this.rssQueue.shift();
const hostPlugins = enabledPlugins || {
ALL_PLUGINS: {
value: true,
},
TELEGRAM: {
value: true,
},
SLACK: {
value: true,
},
EMAIL: {
value: true,
},
};
const pluginsForHost = [
["telegram-notifications", "TELEGRAM"],
["slack-notifications", "SLACK"],
["gmail-notifications", "EMAIL"],
["email-notifications", "EMAIL"],
];
function getEnabledPluginsForHost() {
if (hostPlugins.ALL_PLUGINS.value) {
return pluginsForHost.map((p) => {
return p[0];
});
} else {
let newArr = [];
pluginsForHost.forEach((p) => {
if (hostPlugins[p[1]].value) {
newArr.push(p[0]);
}
});
return newArr;
}
}
const enabledPluginsArr = getEnabledPluginsForHost();
const plugins = this.plugins
.map((p) => {
const globalSettings = database.data.pluginSettings.find((ps) => ps.id === p.id) || {};
const groupEntry = hostGroup?.pluginSettings?.[p.id];
const settings = groupEntry
? { ...globalSettings, params: { ...globalSettings.params, ...groupEntry.params } }
: globalSettings;
return { plugin: p, settings };
})
.filter((p) => {
const hasGroupOverride = !!hostGroup?.pluginSettings?.[p.plugin.id];
return (hasGroupOverride || p.settings.enabled) && enabledPluginsArr.includes(p.plugin.id);
});
await Promise.all(
plugins.map(async (p) => {
try {
await p.plugin.sendMessage(p.settings, rssFormatedMessage);
} catch (e) {
console.error("Error in plugin", p.plugin.id, e, "stack:", e.stack);
}
})
);
}
const rssMonitor = database.data.httpMonitoringData.find(
(p) => p.monitor_type === "rss_parser"
);
if (!rssMonitor) {
this.stopProcessRssQueue();
}
}
async handleRssEvent({ rssFormatedMessage, enabledPlugins, data, hostGroup }) {
let needExceptMessage = false;
let needBeHighlighted = false;
let fullMessageString = "";
let messageString = "";
let excludedFields = [
"content:encoded",
"content:encodedSnippet",
"contentSnippet",
"isoDate",
];
const exceptionsList =
data &&
data.rssFilters.filter((e) => {
return e.name === "Exclude";
})[0].data;
const highlightedList =
data &&
data.rssFilters.filter((e) => {
return e.name === "Highlighted";
})[0].data;
const onlyPrio =
data &&
data.rssFilters.filter((e) => {
return e.name === "OnlyPrio";
})[0].data;
Object.entries(rssFormatedMessage).forEach((e) => {
fullMessageString = `${fullMessageString}${e[0]}${e[1]}`;
});
exceptionsList.forEach((ex) => {
if (fullMessageString.toLowerCase().includes(ex.toLowerCase())) {
needExceptMessage = true;
}
});
highlightedList.forEach((hig) => {
if (fullMessageString.toLowerCase().includes(hig.toLowerCase())) {
needBeHighlighted = true;
messageString = messageString.replaceAll(hig.toLowerCase(), `🔥${hig}`);
}
});
const prepareMessage = (cutField) => {
const CHARACTERS_LIMIT = 500;
Object.entries(rssFormatedMessage).forEach((e) => {
if (!excludedFields.includes(e[0])) {
if (!cutField) {
messageString = `${messageString}\n✅-${e[0]
.charAt(0)
.toUpperCase()}${e[0].slice(1)}:${e[1]})`;
} else {
messageString = `${messageString}\n⚠️-${e[0]
.charAt(0)
.toUpperCase()}${e[0].slice(1)}:${e[1].slice(
0,
CHARACTERS_LIMIT
)}(short message...)`;
}
}
});
};
prepareMessage();
if (messageString.length > 4000) {
messageString = "";
prepareMessage(true);
}
if (!needExceptMessage) {
if (needBeHighlighted) {
messageString = `🔥🔥🔥 [PRIO] \n${messageString}\n🔥🔥🔥}`;
}
if (!onlyPrio || needBeHighlighted) {
this.rssQueue.push({ rssFormatedMessage: messageString, enabledPlugins, hostGroup });
}
}
}
stopProcessRssQueue() {
clearInterval(this.rssSendInterval);
this.rssSendInterval = null;
}
}
let _instance;
const PluginManagerSingleton = () => {
if (!_instance) {
_instance = new PluginManager();
}
return _instance;
};
export default PluginManagerSingleton;