11using System ;
2+ using System . Net ;
23using System . Threading ;
34using System . Threading . Tasks ;
45using Microsoft . Extensions . Options ;
@@ -13,12 +14,13 @@ internal class PushServicePushNotificationService : IPushNotificationService
1314 {
1415 private readonly PushNotificationServiceOptions _options ;
1516 private readonly PushServiceClient _pushClient ;
17+ private readonly IPushSubscriptionStoreAccessorProvider _subscriptionStoreAccessorProvider ;
1618
1719 private readonly ILogger _logger ;
1820
1921 public string PublicKey { get { return _options . PublicKey ; } }
2022
21- public PushServicePushNotificationService ( IOptions < PushNotificationServiceOptions > optionsAccessor , PushServiceClient pushClient , IVapidTokenCache vapidTokenCache , ILogger < PushServicePushNotificationService > logger )
23+ public PushServicePushNotificationService ( IOptions < PushNotificationServiceOptions > optionsAccessor , PushServiceClient pushClient , IVapidTokenCache vapidTokenCache , IPushSubscriptionStoreAccessorProvider subscriptionStoreAccessorProvider , ILogger < PushServicePushNotificationService > logger )
2224 {
2325 _options = optionsAccessor . Value ;
2426
@@ -29,6 +31,7 @@ public PushServicePushNotificationService(IOptions<PushNotificationServiceOption
2931 TokenCache = vapidTokenCache
3032 } ;
3133
34+ _subscriptionStoreAccessorProvider = subscriptionStoreAccessorProvider ;
3235 _logger = logger ;
3336 }
3437
@@ -45,7 +48,28 @@ public async Task SendNotificationAsync(PushSubscription subscription, PushMessa
4548 }
4649 catch ( Exception ex )
4750 {
48- _logger ? . LogError ( ex , "Failed requesting push message delivery to {0}." , subscription . Endpoint ) ;
51+ await HandlePushMessageDeliveryExceptionAsync ( ex , subscription ) ;
52+ }
53+ }
54+
55+ private async Task HandlePushMessageDeliveryExceptionAsync ( Exception exception , PushSubscription subscription )
56+ {
57+ PushServiceClientException pushServiceClientException = exception as PushServiceClientException ;
58+
59+ if ( pushServiceClientException is null )
60+ {
61+ _logger ? . LogError ( exception , "Failed requesting push message delivery to {0}." , subscription . Endpoint ) ;
62+ }
63+ else
64+ {
65+ if ( ( pushServiceClientException . StatusCode == HttpStatusCode . NotFound ) || ( pushServiceClientException . StatusCode == HttpStatusCode . Gone ) )
66+ {
67+ using ( IPushSubscriptionStoreAccessor subscriptionStoreAccessor = _subscriptionStoreAccessorProvider . GetPushSubscriptionStoreAccessor ( ) )
68+ {
69+ await subscriptionStoreAccessor . PushSubscriptionStore . DiscardSubscriptionAsync ( subscription . Endpoint ) ;
70+ }
71+ _logger ? . LogInformation ( "Subscription has expired or is no longer valid and has been removed." ) ;
72+ }
4973 }
5074 }
5175 }
0 commit comments