Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
NotificationConfiguration.cs
1using System;
3using System.Net.Mail;
4using System.Threading.Tasks;
5using Waher.Content;
12
14{
19 {
20 private static NotificationConfiguration instance = null;
21 private HttpResource testAddresses = null;
22
23 private CaseInsensitiveString[] addresses = Array.Empty<CaseInsensitiveString>();
24 private CaseInsensitiveString[] urls = Array.Empty<CaseInsensitiveString>();
25
30 : base()
31 {
32 }
33
37 public static NotificationConfiguration Instance => instance;
38
42 [DefaultValueNull]
44 {
45 get => this.addresses;
46 set => this.addresses = value;
47 }
48
52 [DefaultValueNull]
54 {
55 get => this.urls;
56 set => this.urls = value;
57 }
58
62 public override string Resource => "/Settings/Notification.md";
63
67 public override int Priority => 600;
68
74 public override Task<string> Title(Language Language)
75 {
76 return Language.GetStringAsync(typeof(Gateway), 2, "Notification");
77 }
78
82 public override Task ConfigureSystem()
83 {
84 return Task.CompletedTask;
85 }
86
91 public override void SetStaticInstance(ISystemConfiguration Configuration)
92 {
93 instance = Configuration as NotificationConfiguration;
94 }
95
100 public override Task InitSetup(HttpServer WebServer)
101 {
102 this.testAddresses = WebServer.Register("/Settings/TestNotificationAddresses", null, this.TestNotificationAddresses, true, false, true);
103
104 return base.InitSetup(WebServer);
105 }
106
111 public override Task UnregisterSetup(HttpServer WebServer)
112 {
113 WebServer.Unregister(this.testAddresses);
114
115 return base.UnregisterSetup(WebServer);
116 }
117
121 protected override string ConfigPrivilege => "Admin.Communication.Notification";
122
123 private async Task TestNotificationAddresses(HttpRequest Request, HttpResponse Response)
124 {
125 Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);
126
127 if (!Request.HasData)
128 {
129 await Response.SendResponse(new BadRequestException());
130 return;
131 }
132
133 ContentResponse Content = await Request.DecodeDataAsync();
134 if (Content.HasError ||
135 !(Content.Decoded is Dictionary<string, object> Obj) ||
136 !Obj.TryGetValue("NotificationAddresses", out object Obj2) ||
137 !(Obj2 is string NotificationAddresses) ||
138 !Obj.TryGetValue("NotificationUrls", out Obj2) ||
139 !(Obj2 is string NotificationUrls))
140 {
141 await Response.SendResponse(new BadRequestException());
142 return;
143 }
144
145 string TabID = Request.Header["X-TabID"];
146
147 List<CaseInsensitiveString> Addresses = new List<CaseInsensitiveString>();
148 List<CaseInsensitiveString> WebHooks = new List<CaseInsensitiveString>();
149
150 Response.StatusCode = 200;
151 Response.StatusMessage = "OK";
152
153 try
154 {
155 foreach (string Part in NotificationAddresses.Split(CommonTypes.CRLF, StringSplitOptions.RemoveEmptyEntries))
156 {
157 string s = Part.Trim();
158 if (string.IsNullOrEmpty(s))
159 continue;
160
161 if (string.Compare(s, Gateway.XmppClient.BareJID, true) == 0)
162 continue;
163
164 MailAddress Addr = new MailAddress(s);
165 Addresses.Add(Addr.Address);
166 }
167
168 foreach (string Part in NotificationUrls.Split(CommonTypes.CRLF, StringSplitOptions.RemoveEmptyEntries))
169 {
170 string s = Part.Trim();
171 if (string.IsNullOrEmpty(s))
172 continue;
173
174 Uri Uri = new Uri(s);
175 WebHooks.Add(Uri.ToString());
176 }
177
178 this.addresses = Addresses.ToArray();
179 this.urls = WebHooks.ToArray();
180
181 await Database.Update(this);
182
183 if (this.addresses.Length > 0 || this.urls.Length > 0)
184 {
185 await Gateway.SendNotification("Test\r\n===========\r\n\r\nThis message was generated to test the notification feature of **" +
187 }
188
189 if (!string.IsNullOrEmpty(TabID))
190 await Response.Write(1);
191 }
192 catch (Exception ex)
193 {
194 if (!string.IsNullOrEmpty(TabID))
195 await Response.Write(0);
196 else
197 {
198 await Response.SendResponse(new BadRequestException(ex.Message));
199 return;
200 }
201 }
202
203 await Response.SendResponse();
204 }
205
210 public override Task<bool> SimplifiedConfiguration()
211 {
212 return Task.FromResult(true);
213 }
214
219
224
229 public override Task<bool> EnvironmentConfiguration()
230 {
231 bool ValuesSet = false;
232 CaseInsensitiveString Value = Environment.GetEnvironmentVariable(GATEWAY_NOTIFICATION_JIDS);
233
235 {
236 CaseInsensitiveString[] Jids = Value.Split(',');
237 foreach (CaseInsensitiveString Jid in Jids)
238 {
239 if (!XmppClient.BareJidRegEx.IsMatch(Jid))
240 {
241 this.LogEnvironmentError("Invalid JID.", GATEWAY_NOTIFICATION_JIDS, Jid);
242 return Task.FromResult(false);
243 }
244 }
245
246 this.addresses = Jids;
247 ValuesSet = true;
248 }
249
250 Value = Environment.GetEnvironmentVariable(GATEWAY_NOTIFICATION_URLS);
251
253 {
254 CaseInsensitiveString[] Urls = Value.Split(',');
255 foreach (CaseInsensitiveString Url in Urls)
256 {
257 if (!Uri.TryCreate(Url, UriKind.Absolute, out _))
258 {
259 this.LogEnvironmentError("Invalid URL.", GATEWAY_NOTIFICATION_URLS, Url);
260 return Task.FromResult(false);
261 }
262 }
263
264 this.urls = Urls;
265 ValuesSet = true;
266 }
267
268 return Task.FromResult(ValuesSet);
269 }
270
271 }
272}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:15
static readonly char[] CRLF
Contains the CR LF character sequence.
Definition: CommonTypes.cs:19
Contains information about a response to a content request.
bool HasError
If an error occurred.
object Decoded
Decoded object.
Contains a markdown document. This markdown document class supports original markdown,...
static string Encode(string s)
Encodes all special characters in a string so that it can be included in a markdown document without ...
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static IUser AssertUserAuthenticated(HttpRequest Request, string Privilege)
Makes sure a request is being made from a session with a successful user login.
Definition: Gateway.cs:3868
static Task SendNotification(Graph Graph)
Sends a graph as a notification message to configured notification recipients.
Definition: Gateway.cs:4677
static XmppClient XmppClient
XMPP Client connection of gateway.
Definition: Gateway.cs:4038
static string ApplicationName
Application Name.
Definition: Gateway.cs:3158
override Task< bool > SimplifiedConfiguration()
Simplified configuration by configuring simple default values.
override Task ConfigureSystem()
Is called during startup to configure the system.
override Task InitSetup(HttpServer WebServer)
Initializes the setup object.
override string ConfigPrivilege
Minimum required privilege for a user to be allowed to change the configuration defined by the class.
CaseInsensitiveString[] Urls
Notification addresses.
override Task< bool > EnvironmentConfiguration()
Environment configuration by configuring values available in environment variables.
override int Priority
Priority of the setting. Configurations are sorted in ascending order.
override Task UnregisterSetup(HttpServer WebServer)
Unregisters the setup object.
static NotificationConfiguration Instance
Current instance of configuration.
const string GATEWAY_NOTIFICATION_JIDS
JIDs of operators of gateway.
const string GATEWAY_NOTIFICATION_URLS
Webhook URLs of operators of gateway.
override void SetStaticInstance(ISystemConfiguration Configuration)
Sets the static instance of the configuration.
override Task< string > Title(Language Language)
Gets a title for the system configuration.
CaseInsensitiveString[] Addresses
Notification addresses.
Abstract base class for system configurations.
void LogEnvironmentError(string EnvironmentVariable, object Value)
Logs an error to the event log, telling the operator an environment variable value contains an error.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
Represents an HTTP request.
Definition: HttpRequest.cs:22
HttpRequestHeader Header
Request header.
Definition: HttpRequest.cs:182
bool HasData
If the request has data.
Definition: HttpRequest.cs:113
async Task< ContentResponse > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:139
Base class for all HTTP resources.
Definition: HttpResource.cs:23
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:23
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
Task Write(byte[] Data)
Returns binary data in the response.
Implements an HTTP server.
Definition: HttpServer.cs:41
HttpResource Register(HttpResource Resource)
Registers a resource with the server.
Definition: HttpServer.cs:1568
bool Unregister(HttpResource Resource)
Unregisters a resource from the server.
Definition: HttpServer.cs:1743
Manages an XMPP client connection. Implements XMPP, as defined in https://tools.ietf....
Definition: XmppClient.cs:58
static readonly Regex BareJidRegEx
Regular expression for Bare JIDs
Definition: XmppClient.cs:187
Represents a case-insensitive string.
static readonly CaseInsensitiveString Empty
Empty case-insensitive string
int Length
Gets the number of characters in the current CaseInsensitiveString object.
static bool IsNullOrEmpty(CaseInsensitiveString value)
Indicates whether the specified string is null or an CaseInsensitiveString.Empty string.
CaseInsensitiveString Trim()
Removes all leading and trailing white-space characters from the current CaseInsensitiveString object...
CaseInsensitiveString[] Split(params char[] separator)
Returns a string array that contains the substrings in this instance that are delimited by elements o...
Static interface for database persistence. In order to work, a database provider has to be assigned t...
Definition: Database.cs:21
static async Task Update(object Object)
Updates an object in the database.
Definition: Database.cs:1211
Contains information about a language.
Definition: Language.cs:17
Task< string > GetStringAsync(Type Type, int Id, string Default)
Gets the string value of a string ID. If no such string exists, a string is created with the default ...
Definition: Language.cs:209
Interface for system configurations. The gateway will scan all module for system configuration classe...
Definition: ImplTypes.g.cs:58