diff options
| -rw-r--r-- | src/slskd/Application/Service.cs | 22 | ||||
| -rw-r--r-- | src/slskd/Integrations/Pushbullet/IPushbulletService.cs | 36 | ||||
| -rw-r--r-- | src/slskd/Integrations/Pushbullet/PushbulletService.cs | 136 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 82 | ||||
| -rw-r--r-- | src/slskd/Properties/analysis.ruleset | 1 | ||||
| -rw-r--r-- | src/slskd/Properties/slskd.yml | 10 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 5 |
7 files changed, 290 insertions, 2 deletions
diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 60fae0cc..acaea6ce 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)); + + 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) 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 file="IPushbulletService.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Integrations.Pushbullet +{ + using System.Threading.Tasks; + + /// <summary> + /// Pushbullet integration service. + /// </summary> + public interface IPushbulletService + { + /// <summary> + /// Sends a push notification to Pushbullet. + /// </summary> + /// <param name="title">The notification title.</param> + /// <param name="cacheKey">A unique cache key for the notification.</param> + /// <param name="body">The notification body.</param> + /// <returns>The operation context.</returns> + 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..cb31e6dc --- /dev/null +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -0,0 +1,136 @@ +// <copyright file="PushbulletService.cs" company="slskd Team"> +// 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/. +// </copyright> + +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; + + /// <summary> + /// Pushbullet integration service. + /// </summary> + public class PushbulletService : IPushbulletService + { + private static readonly string PushUri = "https://api.pushbullet.com/v2/pushes"; + + /// <summary> + /// Initializes a new instance of the <see cref="PushbulletService"/> class. + /// </summary> + /// <param name="httpClientFactory">The HttpClientFactory to use.</param> + /// <param name="optionsMonitor">The options monitor used to derive application options.</param> + /// <param name="log">The logger.</param> + public PushbulletService( + IHttpClientFactory httpClientFactory, + Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor, + ILogger<PushbulletService> log) + { + HttpClientFactory = httpClientFactory; + Options = optionsMonitor.CurrentValue; + Log = log; + + RecentlySent = new MemoryCache(new MemoryCacheOptions()); + } + + private IHttpClientFactory HttpClientFactory { get; } + private Options Options { get; } + private ILogger<PushbulletService> Log { get; } + private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet; + private IMemoryCache RecentlySent { get; } + + /// <summary> + /// Sends a push notification to Pushbullet. + /// </summary> + /// <param name="title">The notification title.</param> + /// <param name="cacheKey">A unique cache key for the notification.</param> + /// <param name="body">The notification body.</param> + /// <returns>The operation context.</returns> + 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(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)); + } + + if (RecentlySent.TryGetValue(cacheKey, out _)) + { + return Task.CompletedTask; + } + + RecentlySent.Set(cacheKey, value: true, 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); + } + } + } +} diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index f8190fc7..7c697b43 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -568,6 +568,12 @@ namespace slskd public FTPOptions FTP { get; private set; } = new FTPOptions(); /// <summary> + /// Gets Pushbullet options. + /// </summary> + [Validate] + public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); + + /// <summary> /// FTP options. /// </summary> public class FTPOptions : IValidatableObject @@ -676,6 +682,82 @@ namespace slskd return results; } } + + /// <summary> + /// Pushbullet options. + /// </summary> + public class PushbulletOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// </summary> + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET_ENABLED")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; private set; } = false; + + /// <summary> + /// Gets the Pushbullet API access token. + /// </summary> + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + public string AccessToken { get; private set; } + + /// <summary> + /// Gets the prefix for Pushbullet notification titles. + /// </summary> + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; private set; } = "From slskd:"; + + /// <summary> + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// </summary> + [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; + + /// <summary> + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// </summary> + [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; + + /// <summary> + /// Gets the number of times failing Pushbullet notifications will be retried. + /// </summary> + [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; + + /// <summary> + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// </summary> + [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 + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); + } + + return results; + } + } } } }
\ No newline at end of file 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 @@ </Rules> <Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp"> <Rule Id="S101" Action="None" /> + <Rule Id="S1075" Action="None" /> <Rule Id="S2219" Action="None" /> <Rule Id="S2589" Action="None" /> <Rule Id="S3011" Action="None" /> diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index a0356e6f..43c87f90 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: "From slskd:" +# notify_on_private_message: true +# notify_on_room_mention: true +# retry_attempts: 3 +# cooldown_time: 900000
\ No newline at end of file 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<ITransferTracker, TransferTracker>(); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); @@ -191,6 +194,8 @@ namespace slskd services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); services.AddTransient<IFTPService, FTPService>(); + services.AddSingleton<IPushbulletService, PushbulletService>(); + services.AddHostedService<Service>(); services.AddSingleton(_ => Service.SoulseekClient); } |
