aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Integrations/Pushbullet/PushbulletService.cs
blob: d5fa5b979e3fef3b42d59b9af7cef6bb7209ccd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// <copyright file="PushbulletService.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ Copyright (c) JP Dillingham.
//   │
//   │ 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, version 3.
//   │
//   │ 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/.
//   │
//   │ This program is distributed with Additional Terms pursuant to Section 7
//   │ of the AGPLv3.  See the LICENSE file in the root directory of this
//   │ project for the complete terms and conditions.
//   │
//   │ https://slskd.org
//   │
//   ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
//   │ SPDX-FileCopyrightText: JP Dillingham
//   │ SPDX-License-Identifier: AGPL-3.0-only
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

using Microsoft.Extensions.Options;

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.IntegrationsOptions;

    /// <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,
            IOptionsMonitor<Options> optionsMonitor,
            ILogger<PushbulletService> log)
        {
            HttpClientFactory = httpClientFactory;
            OptionsMonitor = optionsMonitor;
            Log = log;

            RecentlySent = new MemoryCache(new MemoryCacheOptions());
        }

        private bool Disposed { get; set; }
        private IHttpClientFactory HttpClientFactory { get; }
        private ILogger<PushbulletService> Log { get; }
        private IOptionsMonitor<Options> OptionsMonitor { get; }
        private PushbulletOptions PushbulletOptions => OptionsMonitor.CurrentValue.Integrations.Pushbullet;
        private IMemoryCache RecentlySent { get; }

        /// <summary>
        ///     Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }

        /// <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 (!PushbulletOptions.Enabled)
            {
                return Task.CompletedTask;
            }

            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);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    RecentlySent.Dispose();
                }

                Disposed = true;
            }
        }

        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} v{Program.FullVersion}");

                Log.LogDebug("Sending Pushbullet notification {Title} {Body}", title, body);

                await Retry.Do(
                    task: async () =>
                    {
                        using var response = await http.PostAsync(PushUri, content);
                        response.EnsureSuccessStatusCode();
                    },
                    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,
                    baseDelayInMilliseconds: 1000,
                    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);
            }
        }
    }
}