From 5111471cea28c1ce7da6e323fc549298a3625601 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Jul 2021 17:14:35 -0500 Subject: add options for pushbullet --- src/slskd/Options.cs | 70 ++++++++++++++++++++++++++++++++++++++++++ src/slskd/Properties/slskd.yml | 10 +++++- 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index f8190fc7..d2f2ddef 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -567,6 +567,12 @@ namespace slskd [Validate] public FTPOptions FTP { get; private set; } = new FTPOptions(); + /// + /// Gets Pushbullet options. + /// + [Validate] + public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); + /// /// FTP options. /// @@ -676,6 +682,70 @@ namespace slskd return results; } } + + /// + /// Pushbullet options. + /// + public class PushbulletOptions + { + /// + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET_ENABLED")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; private set; } = false; + + /// + /// Gets the Pushbullet API access token. + /// + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + public string AccessToken { get; private set; } + + /// + /// Gets the prefix for Pushbullet notification titles. + /// + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; private set; } = "From slskd:"; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// + [Argument(default, "pushbullet-notify-on-pm")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] + [Description("send Pushbullet notifications when private messages are received")] + public bool NotifyOnPrivateMessage { get; private set; } = true; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// + [Argument(default, "pushbullet-notify-on-room-mention")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] + [Description("send Pushbullet notifications when your username is mentioned in a room")] + public bool NotifyOnRoomMention { get; private set; } = true; + + /// + /// Gets the number of times failing Pushbullet notifications will be retried. + /// + [Argument(default, "pushbullet-retry-attempts")] + [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] + [Description("number of times failing Pushbullet notifications will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + /// + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// + [Argument(default, "pushbullet-cooldown")] + [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] + [Description("cooldown time for Pushbullet notifications, in milliseconds")] + public int CooldownTime { get; private set; } = 900000; // 15 minutes + } } } } \ No newline at end of file diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index a0356e6f..c5e46b5d 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -61,4 +61,12 @@ # remote_path: / # overwrite_existing: true # connection_timeout: 5000 -# retry_attempts: 5 \ No newline at end of file +# retry_attempts: 3 +# pushbullet: +# enabled: false +# access_token: ~ +# notification_prefix: ~ +# notify_on_private_message: true +# notify_on_room_mention: true +# retry_attempts: 3 +# cooldown_time: 900000 \ No newline at end of file -- cgit v1.2.3 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 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 e15ac0155e7c5d3d559c3284611b35968bfa4226 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Jul 2021 17:15:20 -0500 Subject: DI HttpClientFactory and PushbulletService --- src/slskd/Startup.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 65781e6e..635a6890 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -36,6 +36,7 @@ namespace slskd using slskd.Authentication; using slskd.Cryptography; using slskd.Integrations.FTP; + using slskd.Integrations.Pushbullet; using slskd.Management; using slskd.Messaging; using slskd.Peer; @@ -177,6 +178,8 @@ namespace slskd options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "peer.db")}"); }); + services.AddHttpClient(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -191,6 +194,8 @@ namespace slskd services.AddSingleton(); services.AddTransient(); + services.AddSingleton(); + services.AddHostedService(); services.AddSingleton(_ => Service.SoulseekClient); } -- cgit v1.2.3 From 6a2b21bc531a965dda4e15577be80c0dd9638359 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Jul 2021 17:15:45 -0500 Subject: push notifications on DMs and room mentions --- src/slskd/Application/Service.cs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 60fae0cc..6a23435d 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -28,6 +28,7 @@ namespace slskd using Microsoft.Extensions.Options; using Serilog; using Serilog.Events; + using slskd.Integrations.Pushbullet; using slskd.Messaging; using slskd.Peer; using slskd.Search; @@ -47,7 +48,8 @@ namespace slskd IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, - ISharedFileCache sharedFileCache) + ISharedFileCache sharedFileCache, + IPushbulletService pushbulletService) { Options = options.Value; TransferTracker = transferTracker; @@ -55,6 +57,7 @@ namespace slskd ConversationTracker = conversationTracker; RoomTracker = roomTracker; SharedFileCache = sharedFileCache; + Pushbullet = pushbulletService; ProxyOptions proxyOptions = default; @@ -139,6 +142,7 @@ namespace slskd private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue; + private IPushbulletService Pushbullet { get; } public async Task StartAsync(CancellationToken cancellationToken) { @@ -269,11 +273,22 @@ namespace slskd private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); + Console.WriteLine($"PM : {args.Username} {args.Message}"); + if (Options.Integration.Pushbullet.Enabled && !args.Replayed) + { + Console.WriteLine("Pushing..."); + _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); + } } private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); + + if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + { + _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); + } } private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) @@ -294,6 +309,11 @@ namespace slskd { var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); + + if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + { + _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); + } } private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) -- cgit v1.2.3 From a22a5c67336bc64d8553534a244ddc7e2e2301d4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Jul 2021 08:06:53 -0500 Subject: disable S1075 --- src/slskd/Properties/analysis.ruleset | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset index db01a09c..09e99d9e 100644 --- a/src/slskd/Properties/analysis.ruleset +++ b/src/slskd/Properties/analysis.ruleset @@ -32,6 +32,7 @@ + -- cgit v1.2.3 From a075536708d4e3d4a7656d8efc493b4dc294caa8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Jul 2021 14:04:31 -0500 Subject: remove errant log --- src/slskd/Application/Service.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 6a23435d..acaea6ce 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -273,7 +273,7 @@ namespace slskd private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - Console.WriteLine($"PM : {args.Username} {args.Message}"); + if (Options.Integration.Pushbullet.Enabled && !args.Replayed) { Console.WriteLine("Pushing..."); -- 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(-) 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 From 98c86cc81271a61d9c0f2f41072c8a0e7da5eb8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Jul 2021 14:19:55 -0500 Subject: validate AccessToken when Enabled --- src/slskd/Options.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index d2f2ddef..7c697b43 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -686,7 +686,7 @@ namespace slskd /// /// Pushbullet options. /// - public class PushbulletOptions + public class PushbulletOptions : IValidatableObject { /// /// Gets a value indicating whether the Pushbullet integration is enabled. @@ -745,6 +745,18 @@ namespace slskd [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] [Description("cooldown time for Pushbullet notifications, in milliseconds")] public int CooldownTime { get; private set; } = 900000; // 15 minutes + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); + } + + return results; + } } } } -- cgit v1.2.3 From b5e7a1b697c61589d212e9166a3f617ce9a89c62 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Jul 2021 14:20:01 -0500 Subject: add default prefix to docs --- src/slskd/Properties/slskd.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index c5e46b5d..43c87f90 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -65,7 +65,7 @@ # pushbullet: # enabled: false # access_token: ~ -# notification_prefix: ~ +# notification_prefix: "From slskd:" # notify_on_private_message: true # notify_on_room_mention: true # retry_attempts: 3 -- cgit v1.2.3