From ebe3012c694ea1006b2fae995007f90287e87c8c Mon Sep 17 00:00:00 2001 From: Glax Date: Sat, 1 Jun 2024 22:08:59 +0200 Subject: [PATCH] NTFY check endpoint URI and add optional custom topic #183 --- Tranga/NotificationConnectors/Ntfy.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Tranga/NotificationConnectors/Ntfy.cs b/Tranga/NotificationConnectors/Ntfy.cs index fef0f90..c725b8a 100644 --- a/Tranga/NotificationConnectors/Ntfy.cs +++ b/Tranga/NotificationConnectors/Ntfy.cs @@ -1,4 +1,5 @@ using System.Text; +using System.Text.RegularExpressions; using Newtonsoft.Json; namespace Tranga.NotificationConnectors; @@ -8,7 +9,7 @@ public class Ntfy : NotificationConnector // ReSharper disable twice MemberCanBePrivate.Global public string endpoint { get; init; } public string auth { get; init; } - private const string Topic = "tranga"; + private readonly string _topic = "tranga"; private readonly HttpClient _client = new(); [JsonConstructor] @@ -16,19 +17,25 @@ public class Ntfy : NotificationConnector { if (!baseUrlRex.IsMatch(endpoint)) throw new ArgumentException("endpoint does not match pattern"); - this.endpoint = endpoint; + Regex rootUriRex = new(@"(https?:\/\/[a-zA-Z0-9-\.]+\.[a-zA-Z0-9]+)(?:\/([a-zA-Z0-9-\.]+))?.*"); + Match match = rootUriRex.Match(endpoint); + if(!match.Success) + Log($"Error getting URI from provided endpoint-URI: {endpoint}"); + this.endpoint = match.Groups[1].Value; + if (match.Groups[2].Success) + _topic = match.Groups[2].Value; this.auth = auth; } public override string ToString() { - return $"Ntfy {endpoint} {Topic}"; + return $"Ntfy {endpoint} {_topic}"; } public override void SendNotification(string title, string notificationText) { Log($"Sending notification: {title} - {notificationText}"); - MessageData message = new(title, notificationText); + MessageData message = new(title, _topic, notificationText); HttpRequestMessage request = new(HttpMethod.Post, $"{this.endpoint}?auth={this.auth}"); request.Content = new StringContent(JsonConvert.SerializeObject(message, Formatting.None), Encoding.UTF8, "application/json"); HttpResponseMessage response = _client.Send(request); @@ -47,9 +54,9 @@ public class Ntfy : NotificationConnector public string message { get; } public int priority { get; } - public MessageData(string title, string message) + public MessageData(string title, string topic, string message) { - this.topic = Topic; + this.topic = topic; this.title = title; this.message = message; this.priority = 3;