Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove PushKit #3268

Merged
merged 27 commits into from
May 29, 2020
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
53bb87d
Create notification service extension
ismailgulek May 22, 2020
a3890c6
update fastlane commands for new target
ismailgulek May 25, 2020
7335682
Configure log files correctly
ismailgulek May 25, 2020
9475cd7
Fix Manu's comments
ismailgulek May 25, 2020
f85aee0
Implement a workaround to delete some notifications afterwards
ismailgulek May 25, 2020
87e702a
Swiftify some ifs
ismailgulek May 25, 2020
23203af
Swiftify some ifs
ismailgulek May 25, 2020
db01577
Swiftify some ifs
ismailgulek May 25, 2020
4e25323
Swiftify code, ignore session state
ismailgulek May 25, 2020
09353f4
Swiftify content function, use switch for ifs when possible
ismailgulek May 25, 2020
f25e3b6
Swiftify code, style changes
ismailgulek May 25, 2020
7f39581
Swiftify extension methods
ismailgulek May 25, 2020
63d4a16
Update Riot/Utils/Constants.swift
ismailgulek May 26, 2020
db8b5a4
Update RiotNSE/NotificationService.swift
ismailgulek May 26, 2020
ba50f47
Remove some commented code
ismailgulek May 26, 2020
b1a654d
Change logs for fallback cases
ismailgulek May 26, 2020
69d9b5b
Add fallback method calls on some points
ismailgulek May 26, 2020
c4bdf33
Remove some redundant semicolons
ismailgulek May 26, 2020
fa44dae
Update RiotNSE/NotificationService.swift
ismailgulek May 26, 2020
a0e9540
Update RiotNSE/NotificationService.swift
ismailgulek May 26, 2020
f5324ae
Update RiotNSE/NotificationService.swift
ismailgulek May 26, 2020
3bd9e6b
Change some guarding to if check
ismailgulek May 26, 2020
bcd9683
Implement a memory store specific to NSE
ismailgulek May 27, 2020
d859ce8
Drop MXKAccount and MXFileStore usages
ismailgulek May 27, 2020
845363b
Fix Manu's comments
ismailgulek May 29, 2020
4ef5e17
Add some comments
ismailgulek May 29, 2020
0b639e8
Adapt to new method, change timeout to seconds
ismailgulek May 29, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ abstract_target 'RiotPods' do
import_MatrixKitAppExtension
end

target "RiotNSE" do
import_MatrixKitAppExtension
end

end


Expand Down
208 changes: 208 additions & 0 deletions Riot.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

46 changes: 38 additions & 8 deletions Riot/AppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,28 @@ - (void)registerForRemoteNotificationsWithCompletion:(nullable void (^)(NSError
[self.pushNotificationService registerForRemoteNotificationsWithCompletion:completion];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[self.pushNotificationService didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

NSString * deviceTokenString = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""];

NSLog(@"The generated device token string is : %@",deviceTokenString);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[self.pushNotificationService didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[self.pushNotificationService didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

#pragma mark -

- (NSString*)appVersion
Expand Down Expand Up @@ -484,6 +506,9 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
[MXSDKOptions sharedInstance].analyticsDelegate = [Analytics sharedInstance];
[DecryptionFailureTracker sharedInstance].delegate = [Analytics sharedInstance];
[[Analytics sharedInstance] start];

// Disable CallKit
[MXKAppSettings standardAppSettings].enableCallKit = NO;

self.pushNotificationService = [PushNotificationService new];
self.pushNotificationService.delegate = self;
Expand Down Expand Up @@ -1953,7 +1978,7 @@ - (void)initMatrixSessions
if (isPushRegistered)
{
// Enable push notifications by default on new added account
[account enablePushKitNotifications:YES success:nil failure:nil];
[account enablePushNotifications:YES success:nil failure:nil];
}
else
{
Expand Down Expand Up @@ -2034,13 +2059,13 @@ - (void)initMatrixSessions
accountManager.storeClass = [MXFileStore class];

// Disable APNS use.
if (accountManager.apnsDeviceToken)
{
// We use now Pushkit, unregister for all remote notifications received via Apple Push Notification service.
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
[accountManager setApnsDeviceToken:nil];
}
// if (accountManager.apnsDeviceToken)
// {
// // We use now Pushkit, unregister for all remote notifications received via Apple Push Notification service.
// [[UIApplication sharedApplication] unregisterForRemoteNotifications];
// [accountManager setApnsDeviceToken:nil];
// }

// Observers have been defined, we can start a matrix session for each enabled accounts.
NSLog(@"[AppDelegate] initMatrixSessions: prepareSessionForActiveAccounts (app state: %tu)", [[UIApplication sharedApplication] applicationState]);
[accountManager prepareSessionForActiveAccounts];
Expand Down Expand Up @@ -4541,6 +4566,11 @@ - (void)setupUserDefaults
NSDictionary *defaults = [NSDictionary dictionaryWithContentsOfFile:defaultsPathFromApp];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

if (!RiotSettings.shared.isUserDefaultsMigrated)
{
[RiotSettings.shared migrate];
}

// Now use RiotSettings and NSUserDefaults to store `showDecryptedContentInNotifications` setting option
// Migrate this information from main MXKAccount to RiotSettings, if value is not in UserDefaults

Expand Down
4 changes: 4 additions & 0 deletions Riot/Assets/Riot-Defaults.plist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
<string>im.vector.app.ios.voip.prod</string>
<key>pushKitAppIdDev</key>
<string>im.vector.app.ios.voip.dev</string>
<key>pusherAppIdDev</key>
<string>im.vector.app.ios.dev</string>
<key>pusherAppIdProd</key>
<string>im.vector.app.ios.prod</string>
<key>identityserverurl</key>
<string>https://vector.im</string>
<key>homeserverurl</key>
Expand Down
32 changes: 32 additions & 0 deletions Riot/Categories/UNUserNotificationCenter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Copyright 2020 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Foundation
import UserNotifications

@objc extension UNUserNotificationCenter {

func removeUnwantedNotifications() {
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
// get identifiers of notifications whose category identifiers are "TO_BE_REMOVED"
let identifiersToBeRemoved = notifications.compactMap({ $0.request.content.categoryIdentifier == Constants.toBeRemovedNotificationCategoryIdentifier ? $0.request.identifier : nil })

// remove the notifications with these id's
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiersToBeRemoved)
}
}

}
2 changes: 2 additions & 0 deletions Riot/Generated/RiotDefaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ internal enum RiotDefaults {
internal static let pushGatewayURL: String = _document["pushGatewayURL"]
internal static let pushKitAppIdDev: String = _document["pushKitAppIdDev"]
internal static let pushKitAppIdProd: String = _document["pushKitAppIdProd"]
internal static let pusherAppIdDev: String = _document["pusherAppIdDev"]
internal static let pusherAppIdProd: String = _document["pusherAppIdProd"]
internal static let roomDirectoryServers: [String: Any] = _document["roomDirectoryServers"]
internal static let showAllEventsInRoomHistory: Bool = _document["showAllEventsInRoomHistory"]
internal static let showLeftMembersInRoomMemberList: Bool = _document["showLeftMembersInRoomMemberList"]
Expand Down
14 changes: 12 additions & 2 deletions Riot/Managers/PushNotification/PushNotificationService.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,19 @@
limitations under the License.
*/

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <PushKit/PushKit.h>
#import <UserNotifications/UserNotifications.h>

@class MXSession;
@class MXEvent;
@class MXPushRule;
@class MXKAccount;
@protocol PushNotificationServiceDelegate;

NS_ASSUME_NONNULL_BEGIN

@interface PushNotificationService : NSObject <PKPushRegistryDelegate, UNUserNotificationCenterDelegate>
@interface PushNotificationService : NSObject <UNUserNotificationCenterDelegate>

/**
Is push really registered.
Expand All @@ -48,6 +51,13 @@ NS_ASSUME_NONNULL_BEGIN
*/
- (void)registerForRemoteNotificationsWithCompletion:(nullable void (^)(NSError *))completion;

- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

/**
Perform deregistration for remote notifications.
*/
Expand Down
123 changes: 49 additions & 74 deletions Riot/Managers/PushNotification/PushNotificationService.m
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ @interface PushNotificationService()
NSMutableDictionary <NSNumber *, MXOnNotification> *notificationListenerBlocks;
}

@property (nonatomic, strong) PKPushRegistry *pushRegistry;
//@property (nonatomic, strong) PKPushRegistry *pushRegistry;

@property (nonatomic) NSMutableDictionary <NSNumber *, NSMutableArray <NSString *> *> *incomingPushEventIds;

Expand Down Expand Up @@ -110,16 +110,56 @@ - (void)registerUserNotificationSettings

- (void)registerForRemoteNotificationsWithCompletion:(nullable void (^)(NSError *))completion
{
self.pushRegistry = [[PKPushRegistry alloc] initWithQueue:nil];
self.pushRegistry.delegate = self;
self.pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];

self.registrationForRemoteNotificationsCompletion = completion;

dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}

- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
MXKAccountManager* accountManager = [MXKAccountManager sharedManager];
[accountManager setApnsDeviceToken:deviceToken];
// remove PushKit pusher if exists
if (accountManager.pushDeviceToken)
{
[accountManager setPushDeviceToken:nil withPushOptions:nil];
}
// Sanity check: Make sure the Pushkit push token is deleted
NSParameterAssert(!accountManager.isPushAvailable);
NSParameterAssert(!accountManager.pushDeviceToken);

_isPushRegistered = YES;

if (self.registrationForRemoteNotificationsCompletion)
{
self.registrationForRemoteNotificationsCompletion(nil);
self.registrationForRemoteNotificationsCompletion = nil;
}
}

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[self clearPushNotificationToken];

if (self.registrationForRemoteNotificationsCompletion)
{
self.registrationForRemoteNotificationsCompletion(error);
self.registrationForRemoteNotificationsCompletion = nil;
}
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(@"[PushNotificationService][Push] didReceiveRemoteNotification: applicationState: %tu - payload: %@", [UIApplication sharedApplication].applicationState, userInfo);

completionHandler(UIBackgroundFetchResultNewData);
}

- (void)deregisterRemoteNotifications
{
self.pushRegistry = nil;
_isPushRegistered = NO;
}

Expand All @@ -131,6 +171,8 @@ - (void)applicationWillEnterForeground
[array removeAllObjects];
}
[incomingPushPayloads removeAllObjects];

[[UNUserNotificationCenter currentNotificationCenter] removeUnwantedNotifications];
}

- (void)addMatrixSession:(MXSession *)mxSession
Expand Down Expand Up @@ -259,65 +301,6 @@ - (void)handleSessionStateChangesInBackgroundFor:(MXSession *)mxSession
}
}

#pragma mark - PKPushRegistryDelegate

- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type
{
NSData *token = credentials.token;

NSLog(@"[PushNotificationService][Push] didUpdatePushCredentials: Got Push token: %@. Type: %@", [MXKTools logForPushToken:token], type);

MXKAccountManager* accountManager = [MXKAccountManager sharedManager];
[accountManager setPushDeviceToken:token withPushOptions:@{@"format": @"event_id_only"}];

_isPushRegistered = YES;

if (self.registrationForRemoteNotificationsCompletion)
{
self.registrationForRemoteNotificationsCompletion(nil);
self.registrationForRemoteNotificationsCompletion = nil;
}
}

- (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type
{
NSLog(@"[PushNotificationService][Push] didInvalidatePushTokenForType: Type: %@", type);

[self clearPushNotificationToken];
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type
{
NSLog(@"[PushNotificationService][Push] didReceiveIncomingPushWithPayload: applicationState: %tu - type: %@ - payload: %@", [UIApplication sharedApplication].applicationState, payload.type, payload.dictionaryPayload);

// Display local notifications only when the app is running in background.
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
NSLog(@"[PushNotificationService][Push] didReceiveIncomingPushWithPayload while app is in background");

// Check whether an event id is provided.
NSString *eventId = payload.dictionaryPayload[@"event_id"];
if (eventId)
{
// Add this event identifier in the pending push array for each session.
for (NSMutableArray *array in self.incomingPushEventIds.allValues)
{
[array addObject:eventId];
}

// Cache payload for further usage
incomingPushPayloads[eventId] = payload.dictionaryPayload;
}
else
{
NSLog(@"[PushNotificationService][Push] didReceiveIncomingPushWithPayload - Unexpected payload %@", payload.dictionaryPayload);
}

// Trigger a background sync to handle notifications.
[self launchBackgroundSync];
}
}

#pragma mark - UNUserNotificationCenterDelegate

// iOS 10+, see application:handleActionWithIdentifier:forLocalNotification:withResponseInfo:completionHandler:
Expand Down Expand Up @@ -373,14 +356,6 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNoti
}
}

// iOS 10+, this is called when a notification is about to display in foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog(@"[PushNotificationService][Push] willPresentNotification: applicationState: %@", @([UIApplication sharedApplication].applicationState));

completionHandler(UNNotificationPresentationOptionNone);
}

#pragma mark - Other Methods

- (void)launchBackgroundSync
Expand Down Expand Up @@ -607,7 +582,7 @@ - (NSDictionary*)notificationUserInfoForEvent:(MXEvent*)event andUserId:(NSStrin
}

// iOS 10+, does the same thing as notificationBodyForEvent:pushRule:inAccount:onComplete:, except with more features
- (void)notificationContentForEvent:(MXEvent *)event pushRule:(MXPushRule *)rule inAccount:(MXKAccount *)account onComplete:(void (^)(UNNotificationContent * _Nullable notificationContent))onComplete;
- (void)notificationContentForEvent:(MXEvent *)event pushRule:(MXPushRule *)rule inAccount:(MXKAccount *)account onComplete:(void (^)(UNNotificationContent * _Nullable notificationContent))onComplete
{
if (!event.content || !event.content.count)
{
Expand Down
Loading