-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathWebPushClient.cs
423 lines (366 loc) · 17.8 KB
/
WebPushClient.cs
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using WebPush.Model;
using WebPush.Util;
[assembly: InternalsVisibleTo("WebPush.Test")]
namespace WebPush
{
public class WebPushClient : IWebPushClient
{
// default TTL is 4 weeks.
private const int DefaultTtl = 2419200;
private readonly HttpClientHandler _httpClientHandler;
private string _gcmApiKey;
private HttpClient _httpClient;
private VapidDetails _vapidDetails;
// Used so we only cleanup internally created http clients
private bool _isHttpClientInternallyCreated;
public WebPushClient()
{
}
public WebPushClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public WebPushClient(HttpClientHandler httpClientHandler)
{
_httpClientHandler = httpClientHandler;
}
protected HttpClient HttpClient
{
get
{
if (_httpClient != null)
{
return _httpClient;
}
_isHttpClientInternallyCreated = true;
_httpClient = _httpClientHandler == null
? new HttpClient()
: new HttpClient(_httpClientHandler);
return _httpClient;
}
}
/// <summary>
/// When sending messages to a GCM endpoint you need to set the GCM API key
/// by either calling setGcmApiKey() or passing in the API key as an option
/// to sendNotification()
/// </summary>
/// <param name="gcmApiKey">The API key to send with the GCM request.</param>
public void SetGcmApiKey(string gcmApiKey)
{
if (gcmApiKey == null)
{
_gcmApiKey = null;
return;
}
if (string.IsNullOrEmpty(gcmApiKey))
{
throw new ArgumentException(@"The GCM API Key should be a non-empty string or null.");
}
_gcmApiKey = gcmApiKey;
}
/// <summary>
/// When marking requests where you want to define VAPID details, call this method
/// before sendNotifications() or pass in the details and options to
/// sendNotification.
/// </summary>
/// <param name="vapidDetails"></param>
public void SetVapidDetails(VapidDetails vapidDetails)
{
VapidHelper.ValidateSubject(vapidDetails.Subject);
VapidHelper.ValidatePublicKey(vapidDetails.PublicKey);
VapidHelper.ValidatePrivateKey(vapidDetails.PrivateKey);
_vapidDetails = vapidDetails;
}
/// <summary>
/// When marking requests where you want to define VAPID details, call this method
/// before sendNotifications() or pass in the details and options to
/// sendNotification.
/// </summary>
/// <param name="subject">This must be either a URL or a 'mailto:' address</param>
/// <param name="publicKey">The public VAPID key as a base64 encoded string</param>
/// <param name="privateKey">The private VAPID key as a base64 encoded string</param>
public void SetVapidDetails(string subject, string publicKey, string privateKey)
{
SetVapidDetails(new VapidDetails(subject, publicKey, privateKey));
}
/// <summary>
/// To get a request without sending a push notification call this method.
/// This method will throw an ArgumentException if there is an issue with the input.
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="options">
/// Options for the GCM API key and vapid keys can be passed in if they are unique for each
/// notification.
/// </param>
/// <returns>A HttpRequestMessage object that can be sent.</returns>
public HttpRequestMessage GenerateRequestDetails(PushSubscription subscription, string payload,
Dictionary<string, object> options = null)
{
if (!Uri.IsWellFormedUriString(subscription.Endpoint, UriKind.Absolute))
{
throw new ArgumentException(@"You must pass in a subscription with at least a valid endpoint");
}
var request = new HttpRequestMessage(HttpMethod.Post, subscription.Endpoint);
if (!string.IsNullOrEmpty(payload) && (string.IsNullOrEmpty(subscription.Auth) ||
string.IsNullOrEmpty(subscription.P256DH)))
{
throw new ArgumentException(
@"To send a message with a payload, the subscription must have 'auth' and 'p256dh' keys.");
}
var currentGcmApiKey = _gcmApiKey;
var currentVapidDetails = _vapidDetails;
var timeToLive = DefaultTtl;
var extraHeaders = new Dictionary<string, object>();
if (options != null)
{
var validOptionsKeys = new List<string> { "headers", "gcmAPIKey", "vapidDetails", "TTL" };
foreach (var key in options.Keys)
{
if (!validOptionsKeys.Contains(key))
{
throw new ArgumentException(key + " is an invalid options. The valid options are" +
string.Join(",", validOptionsKeys));
}
}
if (options.ContainsKey("headers"))
{
var headers = options["headers"] as Dictionary<string, object>;
extraHeaders = headers ?? throw new ArgumentException("options.headers must be of type Dictionary<string,object>");
}
if (options.ContainsKey("gcmAPIKey"))
{
var gcmApiKey = options["gcmAPIKey"] as string;
currentGcmApiKey = gcmApiKey ?? throw new ArgumentException("options.gcmAPIKey must be of type string");
}
if (options.ContainsKey("vapidDetails"))
{
var vapidDetails = options["vapidDetails"] as VapidDetails;
currentVapidDetails = vapidDetails ?? throw new ArgumentException("options.vapidDetails must be of type VapidDetails");
}
if (options.ContainsKey("TTL"))
{
var ttl = options["TTL"] as int?;
if (ttl == null)
{
throw new ArgumentException("options.TTL must be of type int");
}
//at this stage ttl cannot be null.
timeToLive = (int)ttl;
}
}
string cryptoKeyHeader = null;
request.Headers.Add("TTL", timeToLive.ToString());
foreach (var header in extraHeaders)
{
request.Headers.Add(header.Key, header.Value.ToString());
}
if (!string.IsNullOrEmpty(payload))
{
if (string.IsNullOrEmpty(subscription.P256DH) || string.IsNullOrEmpty(subscription.Auth))
{
throw new ArgumentException(
@"Unable to send a message with payload to this subscription since it doesn't have the required encryption key");
}
var encryptedPayload = EncryptPayload(subscription, payload);
request.Content = new ByteArrayContent(encryptedPayload.Payload);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
request.Content.Headers.ContentLength = encryptedPayload.Payload.Length;
request.Content.Headers.ContentEncoding.Add("aesgcm");
request.Headers.Add("Encryption", "salt=" + encryptedPayload.Base64EncodeSalt());
cryptoKeyHeader = @"dh=" + encryptedPayload.Base64EncodePublicKey();
}
else
{
request.Content = new ByteArrayContent(new byte[0]);
request.Content.Headers.ContentLength = 0;
}
var isGcm = subscription.Endpoint.StartsWith(@"https://android.googleapis.com/gcm/send");
var isFcm = subscription.Endpoint.StartsWith(@"https://fcm.googleapis.com/fcm/send/");
if (isGcm)
{
if (!string.IsNullOrEmpty(currentGcmApiKey))
{
request.Headers.TryAddWithoutValidation("Authorization", "key=" + currentGcmApiKey);
}
}
else if (currentVapidDetails != null)
{
var uri = new Uri(subscription.Endpoint);
var audience = uri.Scheme + @"://" + uri.Host;
var vapidHeaders = VapidHelper.GetVapidHeaders(audience, currentVapidDetails.Subject,
currentVapidDetails.PublicKey, currentVapidDetails.PrivateKey, currentVapidDetails.Expiration);
request.Headers.Add(@"Authorization", vapidHeaders["Authorization"]);
if (string.IsNullOrEmpty(cryptoKeyHeader))
{
cryptoKeyHeader = vapidHeaders["Crypto-Key"];
}
else
{
cryptoKeyHeader += @";" + vapidHeaders["Crypto-Key"];
}
}
else if (isFcm && !string.IsNullOrEmpty(currentGcmApiKey))
{
request.Headers.TryAddWithoutValidation("Authorization", "key=" + currentGcmApiKey);
}
request.Headers.Add("Crypto-Key", cryptoKeyHeader);
return request;
}
private static EncryptionResult EncryptPayload(PushSubscription subscription, string payload)
{
try
{
return Encryptor.Encrypt(subscription.P256DH, subscription.Auth, payload);
}
catch (Exception ex)
{
if (ex is FormatException || ex is ArgumentException)
{
throw new InvalidEncryptionDetailsException("Unable to encrypt the payload with the encryption key of this subscription.", subscription);
}
throw;
}
}
/// <summary>
/// To send a push notification call this method with a subscription, optional payload and any options
/// Will exception if unsuccessful
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="options">
/// Options for the GCM API key and vapid keys can be passed in if they are unique for each
/// notification.
/// </param>
public void SendNotification(PushSubscription subscription, string payload = null,
Dictionary<string, object> options = null)
{
SendNotificationAsync(subscription, payload, options).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// To send a push notification call this method with a subscription, optional payload and any options
/// Will exception if unsuccessful
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="vapidDetails">The vapid details for the notification.</param>
public void SendNotification(PushSubscription subscription, string payload, VapidDetails vapidDetails)
{
var options = new Dictionary<string, object> { ["vapidDetails"] = vapidDetails };
SendNotification(subscription, payload, options);
}
/// <summary>
/// To send a push notification call this method with a subscription, optional payload and any options
/// Will exception if unsuccessful
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="gcmApiKey">The GCM API key</param>
public void SendNotification(PushSubscription subscription, string payload, string gcmApiKey)
{
var options = new Dictionary<string, object> { ["gcmAPIKey"] = gcmApiKey };
SendNotification(subscription, payload, options);
}
/// <summary>
/// To send a push notification asynchronous call this method with a subscription, optional payload and any options
/// Will exception if unsuccessful
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="options">
/// Options for the GCM API key and vapid keys can be passed in if they are unique for each
/// notification.
/// </param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
public async Task SendNotificationAsync(PushSubscription subscription, string payload = null,
Dictionary<string, object> options = null, CancellationToken cancellationToken = default)
{
var request = GenerateRequestDetails(subscription, payload, options);
var response = await HttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
await HandleResponse(response, subscription).ConfigureAwait(false);
}
/// <summary>
/// To send a push notification asynchronous call this method with a subscription, optional payload and any options
/// Will exception if unsuccessful
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="vapidDetails">The vapid details for the notification.</param>
/// <param name="cancellationToken"></param>
public async Task SendNotificationAsync(PushSubscription subscription, string payload,
VapidDetails vapidDetails, CancellationToken cancellationToken = default)
{
var options = new Dictionary<string, object> { ["vapidDetails"] = vapidDetails };
await SendNotificationAsync(subscription, payload, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// To send a push notification asynchronous call this method with a subscription, optional payload and any options
/// Will exception if unsuccessful
/// </summary>
/// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
/// <param name="payload">The payload you wish to send to the user</param>
/// <param name="gcmApiKey">The GCM API key</param>
/// <param name="cancellationToken"></param>
public async Task SendNotificationAsync(PushSubscription subscription, string payload, string gcmApiKey, CancellationToken cancellationToken = default)
{
var options = new Dictionary<string, object> { ["gcmAPIKey"] = gcmApiKey };
await SendNotificationAsync(subscription, payload, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Handle Web Push responses.
/// </summary>
/// <param name="response"></param>
/// <param name="subscription"></param>
private static async Task HandleResponse(HttpResponseMessage response, PushSubscription subscription)
{
// Successful
if (response.IsSuccessStatusCode)
{
return;
}
// Error
var responseCodeMessage = @"Received unexpected response code: " + (int)response.StatusCode;
switch (response.StatusCode)
{
case HttpStatusCode.BadRequest:
responseCodeMessage = "Bad Request";
break;
case HttpStatusCode.RequestEntityTooLarge:
responseCodeMessage = "Payload too large";
break;
case (HttpStatusCode)429:
responseCodeMessage = "Too many request";
break;
case HttpStatusCode.NotFound:
case HttpStatusCode.Gone:
responseCodeMessage = "Subscription no longer valid";
break;
}
string details = null;
if (response.Content != null)
{
details = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
var message = string.IsNullOrEmpty(details)
? responseCodeMessage
: $"{responseCodeMessage}. Details: {details}";
throw new WebPushException(message, subscription, response);
}
public void Dispose()
{
if (_httpClient != null && _isHttpClientInternallyCreated)
{
_httpClient.Dispose();
_httpClient = null;
}
}
}
}