-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathApnSender.cs
More file actions
155 lines (130 loc) · 6.26 KB
/
ApnSender.cs
File metadata and controls
155 lines (130 loc) · 6.26 KB
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CorePush.Interfaces;
using CorePush.Models;
using CorePush.Utils;
using CorePush.Serialization;
namespace CorePush.Apple;
/// <summary>
/// HTTP2 Apple Push Notification sender
/// </summary>
/// <remarks>
/// This type is thread safe.
/// </remarks>
public class ApnSender : IApnSender
{
private static readonly ConcurrentDictionary<string, Tuple<string, DateTime>> tokens = new();
private static readonly Dictionary<ApnServerType, string> servers = new()
{
{ApnServerType.Development, "https://api.development.push.apple.com:443" },
{ApnServerType.Production, "https://api.push.apple.com:443" }
};
private const string apnIdHeader = "apns-id";
private const int tokenExpiresMinutes = 50;
private readonly ApnSettings settings;
private readonly HttpClient http;
private readonly IJsonSerializer serializer;
/// <param name="http">A <see cref="HttpClient"/> dedicated to this <see cref="ApnSender"/>. Do not use a shared <see cref="HttpClient"/> instance, since its instance-level state may be modified. However, its <see cref="HttpClientHandler" can be shared.</param>
public ApnSender(ApnSettings settings, HttpClient http) : this(settings, http, new DefaultCorePushJsonSerializer())
{
}
/// <summary>
/// Apple push notification sender constructor
/// </summary>
/// <param name="settings">Apple Push Notification settings</param>
/// <param name="http">HTTP client instance</param>
/// <param name="serializer">JSON serializer</param>
public ApnSender(ApnSettings settings, HttpClient http, IJsonSerializer serializer)
{
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.http = http ?? throw new ArgumentNullException(nameof(http));
this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
if (http.BaseAddress == null)
{
http.BaseAddress = new Uri(servers[settings.ServerType]);
}
}
/// <summary>
/// Serialize and send notification to APN. Please see how your message should be formatted here:
/// https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW1
/// !IMPORTANT: If you send many messages at once, make sure to retry those calls. Apple typically doesn't like
/// to receive too many requests and may occasionally respond with HTTP 429. Just try/catch this call and retry as needed.
/// </summary>
/// <exception cref="HttpRequestException">Throws exception when not successful</exception>
public async Task<PushResult> SendAsync(
object notification,
string deviceToken,
string apnsId = null,
int apnsExpiration = 0,
int apnsPriority = 10,
ApnPushType apnPushType = ApnPushType.Alert,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(deviceToken);
var path = $"/3/device/{deviceToken}";
var json = serializer.Serialize(notification);
using var message = new HttpRequestMessage(HttpMethod.Post, path);
message.Version = new Version(2, 0);
message.Content = new StringContent(json);
message.Headers.Authorization = new AuthenticationHeaderValue("bearer", GetJwtToken());
message.Headers.TryAddWithoutValidation(":method", "POST");
message.Headers.TryAddWithoutValidation(":path", path);
message.Headers.Add("apns-topic", settings.AppBundleIdentifier);
message.Headers.Add("apns-expiration", apnsExpiration.ToString());
message.Headers.Add("apns-priority", apnsPriority.ToString());
message.Headers.Add("apns-push-type", apnPushType.ToString().ToLowerInvariant()); // required for iOS 13+
if (!string.IsNullOrWhiteSpace(apnsId))
{
message.Headers.Add(apnIdHeader, apnsId);
}
using var response = await http.SendAsync(message, cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
var error = response.IsSuccessStatusCode
? null
: serializer.Deserialize<ApnsError>(content)?.Reason;
return new PushResult((int)response.StatusCode, response.IsSuccessStatusCode, content, error);
}
private string GetJwtToken()
{
var cacheKey = $"{settings.AppBundleIdentifier}:{settings.P8PrivateKeyId}";
var (token, date) = tokens.GetOrAdd(cacheKey, _ => new Tuple<string, DateTime>(CreateJwtToken(), DateTime.UtcNow));
if (date < DateTime.UtcNow.AddMinutes(-tokenExpiresMinutes))
{
tokens.TryRemove(cacheKey, out _);
return GetJwtToken();
}
return token;
}
private string CreateJwtToken()
{
var header = serializer.Serialize(new { alg = "ES256", kid = CryptoHelper.CleanP8Key(settings.P8PrivateKeyId) });
var payload = serializer.Serialize(new { iss = settings.TeamId, iat = CryptoHelper.GetEpochTimestamp() });
var headerBase64 = Base64UrlEncode(header);
var payloadBase64 = Base64UrlEncode(payload);
var unsignedJwtData = $"{headerBase64}.{payloadBase64}";
var unsignedJwtBytes = Encoding.UTF8.GetBytes(unsignedJwtData);
var privateKeyBytes = Convert.FromBase64String(CryptoHelper.CleanP8Key(settings.P8PrivateKey));
using var dsa = ECDsa.Create();
dsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
var signature = dsa.SignData(unsignedJwtBytes, HashAlgorithmName.SHA256);
var signatureBase64 = Base64UrlEncode(signature);
return $"{unsignedJwtData}.{signatureBase64}";
}
private static string Base64UrlEncode(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
return Base64UrlEncode(bytes);
}
private static string Base64UrlEncode(byte[] bytes) =>
Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.TrimEnd('=');
}