From 79c88f8fd254662c8f670735d9a2f457c14aaf6a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Jul 2021 17:14:59 -0500 Subject: add PushbulletService --- .../Integrations/Pushbullet/IPushbulletService.cs | 36 ++++++ .../Integrations/Pushbullet/PushbulletService.cs | 131 +++++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 src/slskd/Integrations/Pushbullet/IPushbulletService.cs create mode 100644 src/slskd/Integrations/Pushbullet/PushbulletService.cs (limited to 'src/slskd/Integrations') diff --git a/src/slskd/Integrations/Pushbullet/IPushbulletService.cs b/src/slskd/Integrations/Pushbullet/IPushbulletService.cs new file mode 100644 index 00000000..6da42326 --- /dev/null +++ b/src/slskd/Integrations/Pushbullet/IPushbulletService.cs @@ -0,0 +1,36 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Integrations.Pushbullet +{ + using System.Threading.Tasks; + + /// + /// Pushbullet integration service. + /// + public interface IPushbulletService + { + /// + /// Sends a push notification to Pushbullet. + /// + /// The notification title. + /// A unique cache key for the notification. + /// The notification body. + /// The operation context. + Task PushAsync(string title, string cacheKey, string body); + } +} diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs new file mode 100644 index 00000000..a9b3121a --- /dev/null +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -0,0 +1,131 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Integrations.Pushbullet +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text.Json; + using System.Threading.Tasks; + using Microsoft.Extensions.Caching.Memory; + using Microsoft.Extensions.Logging; + using static slskd.Options.IntegrationOptions; + + /// + /// Pushbullet integration service. + /// + public class PushbulletService : IPushbulletService + { + private static readonly string PushUri = "https://api.pushbullet.com/v2/pushes"; + + /// + /// Initializes a new instance of the class. + /// + /// The HttpClientFactory to use. + /// The options monitor used to derive application options. + /// The logger. + public PushbulletService( + IHttpClientFactory httpClientFactory, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + ILogger log) + { + HttpClientFactory = httpClientFactory; + Options = optionsMonitor.CurrentValue; + Log = log; + + RecentlySent = new MemoryCache(new MemoryCacheOptions()); + } + + private IHttpClientFactory HttpClientFactory { get; } + private Options Options { get; } + private ILogger Log { get; } + private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet; + private IMemoryCache RecentlySent { get; } + + /// + /// Sends a push notification to Pushbullet. + /// + /// The notification title. + /// A unique cache key for the notification. + /// The notification body. + /// The operation context. + public Task PushAsync(string title, string cacheKey, string body) + { + if (string.IsNullOrWhiteSpace(title)) + { + throw new ArgumentException("A notification title must be supplied", nameof(title)); + } + + if (string.IsNullOrWhiteSpace(body)) + { + throw new ArgumentException("A notification body must be supplied", nameof(body)); + } + + if (RecentlySent.TryGetValue(cacheKey, out _)) + { + return Task.CompletedTask; + } + + RecentlySent.Set(cacheKey, value: 0, absoluteExpirationRelativeToNow: TimeSpan.FromMilliseconds(PushbulletOptions.CooldownTime)); + + return PushInternalAsync(title, body); + } + + private async Task PushInternalAsync(string title, string body) + { + try + { + title = $"{PushbulletOptions.NotificationPrefix} {title}"; + + var json = JsonSerializer.Serialize(new + { + title, + body, + type = "note", + }); + + var content = new StringContent(json); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + content.Headers.Add("Access-Token", PushbulletOptions.AccessToken); + + using var http = HttpClientFactory.CreateClient(); + + http.DefaultRequestHeaders.UserAgent.TryParseAdd(Program.AppName + Program.Version); + + Log.LogDebug("Sending Pushbullet notification {Title} {Body}", title, body); + + await Retry.Do( + task: () => http.PostAsync(PushUri, content), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => Log.LogWarning("Failed attempt {Attempts} to send Pushbullet notification {Title} {Body}: {Message}", attempts, title, body, ex.Message), + maxAttempts: PushbulletOptions.RetryAttempts, + maxDelayInMilliseconds: 30000); + + Log.LogInformation("Sent Pushbullet notification {Title} {Body}", title, body); + } + catch (RetryException ex) + { + Log.LogError(ex, "Fatal error retrying send of Pushbullet notification {Title} {Body}: {Message}", title, body, ex.Message); + } + catch (Exception ex) + { + Log.LogWarning("Failed to send Pushbullet notification {Title} {Body} after {Attempts} attempts: {Message}", title, body, PushbulletOptions.RetryAttempts, ex.Message); + } + } + } +} -- cgit v1.2.3 From 74b96901a1cc4919b81c2c2a5d11de00f43e9648 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Jul 2021 14:10:08 -0500 Subject: guard cacheKey --- src/slskd/Integrations/Pushbullet/PushbulletService.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src/slskd/Integrations') diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index a9b3121a..cb31e6dc 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -71,6 +71,11 @@ namespace slskd.Integrations.Pushbullet throw new ArgumentException("A notification title must be supplied", nameof(title)); } + if (string.IsNullOrWhiteSpace(cacheKey)) + { + throw new ArgumentException("A notification cache key must be supplied", nameof(cacheKey)); + } + if (string.IsNullOrWhiteSpace(body)) { throw new ArgumentException("A notification body must be supplied", nameof(body)); @@ -81,7 +86,7 @@ namespace slskd.Integrations.Pushbullet return Task.CompletedTask; } - RecentlySent.Set(cacheKey, value: 0, absoluteExpirationRelativeToNow: TimeSpan.FromMilliseconds(PushbulletOptions.CooldownTime)); + RecentlySent.Set(cacheKey, value: true, absoluteExpirationRelativeToNow: TimeSpan.FromMilliseconds(PushbulletOptions.CooldownTime)); return PushInternalAsync(title, body); } -- cgit v1.2.3