Merge branch 'dev' into voice-calls-2

This commit is contained in:
Ryan Zhao 2022-03-09 11:33:18 +11:00
commit a68ed28a7a
41 changed files with 535 additions and 525 deletions

View File

@ -142,6 +142,10 @@
7B1581E4271FC59D00848B49 /* CallModal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1581E3271FC59C00848B49 /* CallModal.swift */; };
7B1581E6271FD2A100848B49 /* VideoPreviewVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1581E5271FD2A100848B49 /* VideoPreviewVC.swift */; };
7B1581E827210ECC00848B49 /* RenderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1581E727210ECC00848B49 /* RenderView.swift */; };
7B1D74AA27BCC16E0030B423 /* NSENotificationPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1D74A927BCC16E0030B423 /* NSENotificationPresenter.swift */; };
7B1D74AC27BDE7510030B423 /* Promise+Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1D74AB27BDE7510030B423 /* Promise+Timeout.swift */; };
7B1D74AE27C346220030B423 /* UnreadMentionMigtation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1D74AD27C346220030B423 /* UnreadMentionMigtation.swift */; };
7B1D74B027C365960030B423 /* Timer+MainThread.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1D74AF27C365960030B423 /* Timer+MainThread.swift */; };
7B4C75CB26B37E0F0000AC89 /* UnsendRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B4C75CA26B37E0F0000AC89 /* UnsendRequest.swift */; };
7B4C75CD26BB92060000AC89 /* DeletedMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B4C75CC26BB92060000AC89 /* DeletedMessageView.swift */; };
7B7CB189270430D20079FF93 /* CallMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B7CB188270430D20079FF93 /* CallMessageView.swift */; };
@ -815,6 +819,19 @@
EF764C351DB67CC5000D9A87 /* UIViewController+Permissions.m in Sources */ = {isa = PBXBuildFile; fileRef = EF764C341DB67CC5000D9A87 /* UIViewController+Permissions.m */; };
FC3BD9881A30A790005B96BB /* Social.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FC3BD9871A30A790005B96BB /* Social.framework */; };
FCB11D8C1A129A76002F93FB /* CoreMedia.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FCB11D8B1A129A76002F93FB /* CoreMedia.framework */; };
FD5D200F27AA2B6000FEA984 /* MessageRequestResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5D200E27AA2B6000FEA984 /* MessageRequestResponse.swift */; };
FD5D201127AA331F00FEA984 /* ConfigurationMessage+Convenience.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5D201027AA331F00FEA984 /* ConfigurationMessage+Convenience.swift */; };
FD659AC027A7649600F12C02 /* MessageRequestsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD659ABF27A7649600F12C02 /* MessageRequestsViewController.swift */; };
FD705A8C278CDB5600F16121 /* SAEScreenLockViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD705A8B278CDB5600F16121 /* SAEScreenLockViewController.swift */; };
FD705A8E278CE29800F16121 /* String+Localization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD705A8D278CE29800F16121 /* String+Localization.swift */; };
FD705A90278CEBBC00F16121 /* ShareAppExtensionContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD705A8F278CEBBC00F16121 /* ShareAppExtensionContext.swift */; };
FD705A92278D051200F16121 /* ReusableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD705A91278D051200F16121 /* ReusableView.swift */; };
FD705A94278D052B00F16121 /* UITableView+ReusableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD705A93278D052B00F16121 /* UITableView+ReusableView.swift */; };
FD705A98278E9F4D00F16121 /* UIColor+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD705A97278E9F4D00F16121 /* UIColor+Extensions.swift */; };
FD859F0027C4691300510D0C /* MockDataGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD859EFF27C4691300510D0C /* MockDataGenerator.swift */; };
FD88BAD927A7439C00BBC442 /* MessageRequestsCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD88BAD827A7439C00BBC442 /* MessageRequestsCell.swift */; };
FD88BADB27A750F200BBC442 /* MessageRequestsMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD88BADA27A750F200BBC442 /* MessageRequestsMigration.swift */; };
FDC4389E27BA2B8A00C60D73 /* SessionUtilitiesKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C3C2A679255388CC00C340D1 /* SessionUtilitiesKit.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@ -1154,6 +1171,10 @@
7B1581E3271FC59C00848B49 /* CallModal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CallModal.swift; sourceTree = "<group>"; };
7B1581E5271FD2A100848B49 /* VideoPreviewVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoPreviewVC.swift; sourceTree = "<group>"; };
7B1581E727210ECC00848B49 /* RenderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RenderView.swift; sourceTree = "<group>"; };
7B1D74A927BCC16E0030B423 /* NSENotificationPresenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSENotificationPresenter.swift; sourceTree = "<group>"; };
7B1D74AB27BDE7510030B423 /* Promise+Timeout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Promise+Timeout.swift"; sourceTree = "<group>"; };
7B1D74AD27C346220030B423 /* UnreadMentionMigtation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnreadMentionMigtation.swift; sourceTree = "<group>"; };
7B1D74AF27C365960030B423 /* Timer+MainThread.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Timer+MainThread.swift"; sourceTree = "<group>"; };
7B2DB2AD26F1B0FF0035B509 /* si */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = si; path = si.lproj/Localizable.strings; sourceTree = "<group>"; };
7B4C75CA26B37E0F0000AC89 /* UnsendRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnsendRequest.swift; sourceTree = "<group>"; };
7B4C75CC26BB92060000AC89 /* DeletedMessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeletedMessageView.swift; sourceTree = "<group>"; };
@ -2170,6 +2191,7 @@
C31C219B255BC92200EC2D66 /* Meta */,
7BDCFC07242186E700641C39 /* NotificationServiceExtensionContext.swift */,
7BC01A3D241F40AB00BC7C55 /* NotificationServiceExtension.swift */,
7B1D74A927BCC16E0030B423 /* NSENotificationPresenter.swift */,
);
path = SessionNotificationServiceExtension;
sourceTree = "<group>";
@ -2386,6 +2408,7 @@
C3C2A5D32553860900C340D1 /* Promise+Delaying.swift */,
C3A7225D2558C38D0043A11F /* Promise+Retaining.swift */,
C3C2A5D62553860B00C340D1 /* Promise+Retrying.swift */,
7B1D74AB27BDE7510030B423 /* Promise+Timeout.swift */,
);
path = PromiseKit;
sourceTree = "<group>";
@ -2448,6 +2471,7 @@
C33FDB45255A580C00E217F9 /* NSString+SSK.m */,
C352A3762557859C00338F3E /* NSTimer+Proxying.h */,
C352A36C2557858D00338F3E /* NSTimer+Proxying.m */,
7B1D74AF27C365960030B423 /* Timer+MainThread.swift */,
C33FDB51255A580D00E217F9 /* NSUserDefaults+OWS.h */,
C33FDB77255A581000E217F9 /* NSUserDefaults+OWS.m */,
C33FDB14255A580800E217F9 /* OWSMath.h */,
@ -3176,6 +3200,8 @@
children = (
7B93D07227CF19C800811CB6 /* MessageRequestsMigration.swift */,
B8B32044258C117C0020074B /* ContactsMigration.swift */,
7B1D74AD27C346220030B423 /* UnreadMentionMigtation.swift */,
FD88BADA27A750F200BBC442 /* MessageRequestsMigration.swift */,
C38EF271255B6D79007E1867 /* OWSDatabaseMigration.h */,
C38EF270255B6D79007E1867 /* OWSDatabaseMigration.m */,
C38EF26F255B6D79007E1867 /* OWSDatabaseMigrationRunner.h */,
@ -4554,6 +4580,7 @@
files = (
7BDCFC08242186E700641C39 /* NotificationServiceExtensionContext.swift in Sources */,
7BC01A3E241F40AB00BC7C55 /* NotificationServiceExtension.swift in Sources */,
7B1D74AA27BCC16E0030B423 /* NSENotificationPresenter.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@ -4705,6 +4732,7 @@
C38EF40B255B6DF7007E1867 /* TappableStackView.swift in Sources */,
C38EF31D255B6DBF007E1867 /* UIImage+OWS.swift in Sources */,
C38EF359255B6DCC007E1867 /* SheetViewController.swift in Sources */,
7B1D74AE27C346220030B423 /* UnreadMentionMigtation.swift in Sources */,
B8F5F52925EC4F8A003BF8D4 /* BlockListUIUtils.m in Sources */,
C38EF386255B6DD2007E1867 /* AttachmentApprovalInputAccessoryView.swift in Sources */,
B8C2B2C82563685C00551B4D /* CircleView.swift in Sources */,
@ -4745,9 +4773,12 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3AABDDF2553ECF00042FF4C /* Array+Utilities.swift in Sources */,
7B1D74AC27BDE7510030B423 /* Promise+Timeout.swift in Sources */,
C3AABDDF2553ECF00042FF4C /* Array+Utilities.swift in Sources */,
C32C5A47256DB8F0003C73A2 /* ECKeyPair+Hexadecimal.swift in Sources */,
C3D9E41525676C320040E4F3 /* Storage.swift in Sources */,
7B1D74B027C365960030B423 /* Timer+MainThread.swift in Sources */,
C32C5D83256DD5B6003C73A2 /* SSKKeychainStorage.swift in Sources */,
C3D9E39B256763C20040E4F3 /* AppContext.m in Sources */,
C3BBE0A82554D4DE0050F1E3 /* JSON.swift in Sources */,
@ -5234,6 +5265,11 @@
target = C33FD9AA255A548A00E217F9 /* SignalUtilitiesKit */;
targetProxy = C3D90A7025773A44002C9DF5 /* PBXContainerItemProxy */;
};
FDC438A127BA2B8A00C60D73 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = C3C2A678255388CC00C340D1 /* SessionUtilitiesKit */;
targetProxy = FDC438A027BA2B8A00C60D73 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */

View File

@ -718,11 +718,6 @@ extension ConversationVC : InputViewDelegate, MessageCellDelegate, ContextMenuAc
}
func delete(_ viewItem: ConversationViewItem) {
if (!self.isUnsendRequestsEnabled) {
viewItem.deleteAction()
return
}
guard let message = viewItem.interaction as? TSMessage else { return self.deleteLocally(viewItem) }
// Handle open group messages the old way
@ -1142,22 +1137,6 @@ extension ConversationVC: UIDocumentInteractionControllerDelegate {
// MARK: - Message Request Actions
extension ConversationVC {
@objc func handleBackPressed() {
// If this thread started as a message request but isn't one anymore then we want to skip the
// `MessageRequestsViewController` when going back
guard
threadStartedAsMessageRequest,
!thread.isMessageRequest(),
let viewControllers: [UIViewController] = navigationController?.viewControllers,
let messageRequestsIndex = viewControllers.firstIndex(where: { $0 is MessageRequestsViewController }),
messageRequestsIndex > 0
else {
navigationController?.popViewController(animated: true)
return
}
navigationController?.popToViewController(viewControllers[messageRequestsIndex - 1], animated: true)
}
fileprivate func approveMessageRequestIfNeeded(for thread: TSThread?, with transaction: YapDatabaseReadWriteTransaction, isNewThread: Bool, timestamp: UInt64) -> Promise<Void> {
guard let contactThread: TSContactThread = thread as? TSContactThread else { return Promise.value(()) }
@ -1229,6 +1208,13 @@ extension ConversationVC {
// Update UI
self?.updateNavBarButtons()
if let viewControllers: [UIViewController] = self?.navigationController?.viewControllers,
let messageRequestsIndex = viewControllers.firstIndex(where: { $0 is MessageRequestsViewController }),
messageRequestsIndex > 0 {
var newViewControllers = viewControllers
newViewControllers.remove(at: messageRequestsIndex)
self?.navigationController?.setViewControllers(newViewControllers, animated: false)
}
// Send a sync message with the details of the contact
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {

View File

@ -8,11 +8,11 @@ import UIKit
// Remaining search glitchiness
final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversationSettingsViewDelegate, ConversationSearchControllerDelegate, UITableViewDataSource, UITableViewDelegate {
let isUnsendRequestsEnabled = true // Set to true once unsend requests are done on all platforms
let thread: TSThread
let threadStartedAsMessageRequest: Bool
let focusedMessageID: String? // This is used for global search
var focusedMessageIndexPath: IndexPath?
var initialUnreadCount: UInt = 0
var unreadViewItems: [ConversationViewItem] = []
var scrollButtonBottomConstraint: NSLayoutConstraint?
var scrollButtonMessageRequestsBottomConstraint: NSLayoutConstraint?
@ -78,7 +78,7 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
return Mnemonic.encode(hexEncodedString: hexEncodedSeed)
}()
lazy var viewModel = ConversationViewModel(thread: thread, focusMessageIdOnOpen: focusedMessageID, delegate: self)
lazy var viewModel = ConversationViewModel(thread: thread, focusMessageIdOnOpen: nil, delegate: self)
lazy var mediaCache: NSCache<NSString, AnyObject> = {
let result = NSCache<NSString, AnyObject>()
@ -278,11 +278,10 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
self.threadStartedAsMessageRequest = thread.isMessageRequest()
self.focusedMessageID = focusedMessageID
super.init(nibName: nil, bundle: nil)
var unreadCount: UInt = 0
Storage.read { transaction in
unreadCount = self.thread.unreadMessageCount(transaction: transaction)
self.initialUnreadCount = self.thread.unreadMessageCount(transaction: transaction)
}
let clampedUnreadCount = min(unreadCount, UInt(kConversationInitialMaxRangeSize), UInt(viewItems.endIndex))
let clampedUnreadCount = min(self.initialUnreadCount, UInt(kConversationInitialMaxRangeSize), UInt(viewItems.endIndex))
unreadViewItems = clampedUnreadCount != 0 ? [ConversationViewItem](viewItems[viewItems.endIndex - Int(clampedUnreadCount) ..< viewItems.endIndex]) : []
}
@ -394,10 +393,6 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
super.viewDidLayoutSubviews()
if !didFinishInitialLayout {
// Scroll to the last unread message if possible; otherwise scroll to the bottom.
var unreadCount: UInt = 0
Storage.read { transaction in
unreadCount = self.thread.unreadMessageCount(transaction: transaction)
}
// When the unread message count is more than the number of view items of a page,
// the screen will scroll to the bottom instead of the first unread message.
// unreadIndicatorIndex is calculated during loading of the viewItems, so it's
@ -408,7 +403,7 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
} else {
let firstUnreadMessageIndex = self.viewModel.viewState.unreadIndicatorIndex?.intValue
?? (self.viewItems.count - self.unreadViewItems.count)
if unreadCount > 0, let viewItem = self.viewItems[ifValid: firstUnreadMessageIndex], let interactionID = viewItem.interaction.uniqueId {
if self.initialUnreadCount > 0, let viewItem = self.viewItems[ifValid: firstUnreadMessageIndex], let interactionID = viewItem.interaction.uniqueId {
self.scrollToInteraction(with: interactionID, position: .top, isAnimated: false)
self.unreadCountView.alpha = self.scrollButton.alpha
} else {
@ -455,6 +450,7 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
let viewItem = viewItems[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: MessageCell.getCellType(for: viewItem).identifier) as! MessageCell
cell.delegate = self
cell.thread = thread
cell.viewItem = viewItem
return cell
}
@ -469,7 +465,6 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
navigationItem.rightBarButtonItems = []
}
else {
navigationItem.leftBarButtonItem = UIViewController.createOWSBackButton(withTarget: self, selector: #selector(handleBackPressed))
var rightBarButtonItems: [UIBarButtonItem] = []
if let contactThread: TSContactThread = thread as? TSContactThread {
// Don't show the settings button for message requests
@ -647,9 +642,6 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
}
self.markAllAsRead()
}
if shouldScrollToBottom {
self.scrollToBottom(isAnimated: false)
}
}
// Update the input state if this is a contact thread
@ -752,17 +744,8 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
}
func scrollToBottom(isAnimated: Bool) {
guard !isUserScrolling else { return }
if let interactionID = viewItems.last?.interaction.uniqueId {
self.scrollToInteraction(with: interactionID, position: .top, isAnimated: isAnimated)
return
}
// Ensure the view is fully up to date before we try to scroll to the bottom, since
// we use the table view's bounds to determine where the bottom is.
view.layoutIfNeeded()
let firstContentPageTop: CGFloat = 0
let contentOffsetY = max(firstContentPageTop, lastPageTop)
messagesTableView.setContentOffset(CGPoint(x: 0, y: contentOffsetY), animated: isAnimated)
guard !isUserScrolling && !viewItems.isEmpty else { return }
messagesTableView.scrollToRow(at: IndexPath(row: viewItems.count - 1, section: 0), at: .bottom, animated: isAnimated)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
@ -795,7 +778,7 @@ final class ConversationVC : BaseVC, ConversationViewModelDelegate, OWSConversat
func autoLoadMoreIfNeeded() {
let isMainAppAndActive = CurrentAppContext().isMainAppAndActive
guard isMainAppAndActive && viewModel.canLoadMoreItems() && !isLoadingMore
guard isMainAppAndActive && didFinishInitialLayout && viewModel.canLoadMoreItems() && !isLoadingMore
&& messagesTableView.contentOffset.y < ConversationVC.loadMoreThreshold else { return }
isLoadingMore = true
viewModel.loadAnotherPageOfMessages()

View File

@ -120,9 +120,7 @@ static const int kYapDatabaseRangeMaxLength = 250000;
focusMessageIdOnOpen:(nullable NSString *)focusMessageIdOnOpen
delegate:(id<ConversationViewModelDelegate>)delegate NS_DESIGNATED_INITIALIZER;
- (void)ensureDynamicInteractionsAndUpdateIfNecessary:(BOOL)updateIfNecessary;
- (void)clearUnreadMessagesIndicator;
- (void)ensureDynamicInteractionsAndUpdateIfNecessary;
- (void)loadAnotherPageOfMessages;

View File

@ -295,13 +295,6 @@ NS_ASSUME_NONNULL_BEGIN
object:nil];
}
- (void)signalAccountsDidChange:(NSNotification *)notification
{
OWSAssertIsOnMainThread();
[self ensureDynamicInteractionsAndUpdateIfNecessary:YES];
}
- (void)profileWhitelistDidChange:(NSNotification *)notification
{
OWSAssertIsOnMainThread();
@ -334,7 +327,7 @@ NS_ASSUME_NONNULL_BEGIN
self.typingIndicatorsSender = [self.typingIndicators typingRecipientIdForThread:self.thread];
self.collapseCutoffDate = [NSDate new];
[self ensureDynamicInteractionsAndUpdateIfNecessary:NO];
[self ensureDynamicInteractionsAndUpdateIfNecessary];
[self.primaryStorage updateUIDatabaseConnectionToLatest];
[self createNewMessageMapping];
@ -490,7 +483,7 @@ NS_ASSUME_NONNULL_BEGIN
self.collapseCutoffDate = [NSDate new];
}
- (void)ensureDynamicInteractionsAndUpdateIfNecessary:(BOOL)updateIfNecessary
- (void)ensureDynamicInteractionsAndUpdateIfNecessary
{
OWSAssertIsOnMainThread();
@ -508,7 +501,7 @@ NS_ASSUME_NONNULL_BEGIN
BOOL didChange = ![NSObject isNullableObject:self.dynamicInteractions equalTo:dynamicInteractions];
self.dynamicInteractions = dynamicInteractions;
if (didChange && updateIfNecessary) {
if (didChange) {
if (![self reloadViewItems]) {
OWSFailDebug(@"Failed to reload view items.");
}
@ -517,37 +510,6 @@ NS_ASSUME_NONNULL_BEGIN
}
}
- (void)clearUnreadMessagesIndicator
{
OWSAssertIsOnMainThread();
// TODO: Remove by making unread indicator a view model concern.
id<ConversationViewItem> _Nullable oldIndicatorItem = [self.viewState unreadIndicatorViewItem];
if (oldIndicatorItem) {
// TODO ideally this would be happening within the *same* transaction that caused the unreadMessageIndicator
// to be cleared.
[LKStorage writeWithBlock:^(YapDatabaseReadWriteTransaction *_Nonnull transaction) {
[oldIndicatorItem.interaction touchWithTransaction:transaction];
}];
}
if (self.hasClearedUnreadMessagesIndicator) {
// ensureDynamicInteractionsForThread is somewhat expensive
// so we don't want to call it unnecessarily.
return;
}
// Once we've cleared the unread messages indicator,
// make sure we don't show it again.
self.hasClearedUnreadMessagesIndicator = YES;
if (self.dynamicInteractions.unreadIndicator) {
// If we've just cleared the "unread messages" indicator,
// update the dynamic interactions.
[self ensureDynamicInteractionsAndUpdateIfNecessary:YES];
}
}
#pragma mark - Storage access
- (void)uiDatabaseDidUpdateExternally:(NSNotification *)notification
@ -984,7 +946,7 @@ NS_ASSUME_NONNULL_BEGIN
self.collapseCutoffDate = [NSDate new];
[self ensureDynamicInteractionsAndUpdateIfNecessary:NO];
[self ensureDynamicInteractionsAndUpdateIfNecessary];
if (![self reloadViewItems]) {
OWSFailDebug(@"failed to reload view items in resetMapping.");
@ -1423,7 +1385,7 @@ NS_ASSUME_NONNULL_BEGIN
self.collapseCutoffDate = [NSDate new];
[self ensureDynamicInteractionsAndUpdateIfNecessary:NO];
[self ensureDynamicInteractionsAndUpdateIfNecessary];
if (![self reloadViewItems]) {
OWSFailDebug(@"failed to reload view items in resetMapping.");
@ -1447,7 +1409,7 @@ NS_ASSUME_NONNULL_BEGIN
self.collapseCutoffDate = [NSDate new];
[self ensureDynamicInteractionsAndUpdateIfNecessary:NO];
[self ensureDynamicInteractionsAndUpdateIfNecessary];
if (![self reloadViewItems]) {
OWSFailDebug(@"failed to reload view items in resetMapping.");

View File

@ -1,6 +1,7 @@
final class QuoteView : UIView {
private let mode: Mode
private let thread: TSThread
private let direction: Direction
private let hInset: CGFloat
private let maxWidth: CGFloat
@ -34,25 +35,6 @@ final class QuoteView : UIView {
}
}
private var threadID: String {
switch mode {
case .regular(let viewItem): return viewItem.interaction.uniqueThreadId
case .draft(let model): return model.threadId
}
}
private var isGroupThread: Bool {
switch mode {
case .regular(let viewItem): return viewItem.isGroupThread
case .draft(let model):
var result = false
Storage.read { transaction in
result = TSThread.fetch(uniqueId: model.threadId, transaction: transaction)?.isGroupThread() ?? false
}
return result
}
}
private var authorID: String {
switch mode {
case .regular(let viewItem): return viewItem.quotedReply!.authorId
@ -93,8 +75,9 @@ final class QuoteView : UIView {
static let cancelButtonSize: CGFloat = 33
// MARK: Lifecycle
init(for viewItem: ConversationViewItem, direction: Direction, hInset: CGFloat, maxWidth: CGFloat) {
init(for viewItem: ConversationViewItem, in thread: TSThread?, direction: Direction, hInset: CGFloat, maxWidth: CGFloat) {
self.mode = .regular(viewItem)
self.thread = thread ?? TSThread.fetch(uniqueId: viewItem.interaction.uniqueThreadId)!
self.maxWidth = maxWidth
self.direction = direction
self.hInset = hInset
@ -105,6 +88,7 @@ final class QuoteView : UIView {
init(for model: OWSQuotedReplyModel, direction: Direction, hInset: CGFloat, maxWidth: CGFloat, delegate: QuoteViewDelegate) {
self.mode = .draft(model)
self.thread = TSThread.fetch(uniqueId: model.threadId)!
self.maxWidth = maxWidth
self.direction = direction
self.hInset = hInset
@ -188,16 +172,15 @@ final class QuoteView : UIView {
bodyLabel.lineBreakMode = .byTruncatingTail
let isOutgoing = (direction == .outgoing)
bodyLabel.font = .systemFont(ofSize: Values.smallFontSize)
bodyLabel.attributedText = given(body) { MentionUtilities.highlightMentions(in: $0, isOutgoingMessage: isOutgoing, threadID: threadID, attributes: [:]) }
?? given(attachments.first?.contentType) { NSAttributedString(string: MIMETypeUtil.isAudio($0) ? "Audio" : "Document") } ?? NSAttributedString(string: "Document")
bodyLabel.attributedText = given(body) { MentionUtilities.highlightMentions(in: $0, isOutgoingMessage: isOutgoing, threadID: thread.uniqueId!, attributes: [:]) } ?? given(attachments.first?.contentType) { NSAttributedString(string: MIMETypeUtil.isAudio($0) ? "Audio" : "Document") } ?? NSAttributedString(string: "Document")
bodyLabel.textColor = textColor
let bodyLabelSize = bodyLabel.systemLayoutSizeFitting(availableSpace)
// Label stack view
var authorLabelHeight: CGFloat?
if isGroupThread {
if let groupThread = thread as? TSGroupThread {
let authorLabel = UILabel()
authorLabel.lineBreakMode = .byTruncatingTail
let context: Contact.Context = (TSGroupThread.fetch(uniqueId: threadID)?.isOpenGroup == true) ? .openGroup : .regular
let context: Contact.Context = groupThread.isOpenGroup ? .openGroup : .regular
authorLabel.text = Storage.shared.getContact(with: authorID)?.displayName(for: context) ?? authorID
authorLabel.textColor = textColor
authorLabel.font = .boldSystemFont(ofSize: Values.smallFontSize)
@ -225,7 +208,7 @@ final class QuoteView : UIView {
// Constraints
contentView.addSubview(mainStackView)
mainStackView.pin(to: contentView)
if !isGroupThread {
if !thread.isGroupThread() {
bodyLabel.set(.width, to: bodyLabelSize.width)
}
let bodyLabelHeight = bodyLabelSize.height.clamp(0, maxBodyLabelHeight)

View File

@ -1,4 +1,5 @@
import UIKit
import SessionMessagingKit
public enum SwipeState {
case began
@ -8,7 +9,16 @@ public enum SwipeState {
class MessageCell : UITableViewCell {
weak var delegate: MessageCellDelegate?
var viewItem: ConversationViewItem? { didSet { update() } }
var thread: TSThread? {
didSet {
if viewItem != nil { update() }
}
}
var viewItem: ConversationViewItem? {
didSet {
if thread != nil { update() }
}
}
// MARK: Settings
class var identifier: String { preconditionFailure("Must be overridden by subclasses.") }

View File

@ -66,6 +66,7 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
lazy var bubbleView: UIView = {
let result = UIView()
result.layer.cornerRadius = VisibleMessageCell.largeCornerRadius
result.set(.width, greaterThanOrEqualTo: VisibleMessageCell.largeCornerRadius * 2)
return result
}()
@ -263,7 +264,7 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
messageStatusImageView.image = image
messageStatusImageView.backgroundColor = backgroundColor
if let message = message as? TSOutgoingMessage {
messageStatusImageView.isHidden = (message.isCallMessage || message.messageState == .sent && message.thread.lastInteraction != message)
messageStatusImageView.isHidden = (message.isCallMessage || message.messageState == .sent && thread?.lastInteraction != message)
} else {
messageStatusImageView.isHidden = true
}
@ -329,11 +330,13 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
linkPreviewView.linkPreviewState = LinkPreviewSent(linkPreview: linkPreview, imageAttachment: viewItem.linkPreviewAttachment)
snContentView.addSubview(linkPreviewView)
linkPreviewView.pin(to: snContentView)
linkPreviewView.layer.mask = bubbleViewMaskLayer
} else if let openGroupInvitationName = message.openGroupInvitationName, let openGroupInvitationURL = message.openGroupInvitationURL {
let openGroupInvitationView = OpenGroupInvitationView(name: openGroupInvitationName, url: openGroupInvitationURL, textColor: bodyLabelTextColor, isOutgoing: isOutgoing)
openGroupInvitationView.layer.mask = bubbleViewMaskLayer
snContentView.addSubview(openGroupInvitationView)
openGroupInvitationView.pin(to: snContentView)
openGroupInvitationView.layer.mask = bubbleViewMaskLayer
} else {
// Stack view
let stackView = UIStackView(arrangedSubviews: [])
@ -343,7 +346,7 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
if viewItem.quotedReply != nil {
let direction: QuoteView.Direction = isOutgoing ? .outgoing : .incoming
let hInset: CGFloat = 2
let quoteView = QuoteView(for: viewItem, direction: direction, hInset: hInset, maxWidth: maxWidth)
let quoteView = QuoteView(for: viewItem, in: thread, direction: direction, hInset: hInset, maxWidth: maxWidth)
let quoteViewContainer = UIView(wrapping: quoteView, withInsets: UIEdgeInsets(top: 0, leading: hInset, bottom: 0, trailing: hInset))
stackView.addArrangedSubview(quoteViewContainer)
}
@ -357,7 +360,7 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
}
case .mediaMessage:
if viewItem.interaction is TSIncomingMessage,
let thread = viewItem.interaction.thread as? TSContactThread,
let thread = thread as? TSContactThread,
Storage.shared.getContact(with: thread.contactSessionID())?.isTrusted != true {
showMediaPlaceholder()
} else {
@ -390,18 +393,19 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
}
case .audio:
if viewItem.interaction is TSIncomingMessage,
let thread = viewItem.interaction.thread as? TSContactThread,
let thread = thread as? TSContactThread,
Storage.shared.getContact(with: thread.contactSessionID())?.isTrusted != true {
showMediaPlaceholder()
} else {
let voiceMessageView = VoiceMessageView(viewItem: viewItem)
snContentView.addSubview(voiceMessageView)
voiceMessageView.pin(to: snContentView)
voiceMessageView.layer.mask = bubbleViewMaskLayer
viewItem.lastAudioMessageView = voiceMessageView
}
case .genericAttachment:
if viewItem.interaction is TSIncomingMessage,
let thread = viewItem.interaction.thread as? TSContactThread,
let thread = thread as? TSContactThread,
Storage.shared.getContact(with: thread.contactSessionID())?.isTrusted != true {
showMediaPlaceholder()
} else {
@ -681,7 +685,7 @@ final class VisibleMessageCell : MessageCell, LinkPreviewViewDelegate {
private static func shouldShowProfilePicture(for viewItem: ConversationViewItem) -> Bool {
guard let message = viewItem.interaction as? TSMessage else { preconditionFailure() }
let isGroupThread = message.thread.isGroupThread()
let isGroupThread = viewItem.isGroupThread
let senderSessionID = (message as? TSIncomingMessage)?.authorId
return isGroupThread && viewItem.shouldShowSenderProfilePicture && senderSessionID != nil
}

View File

@ -124,30 +124,10 @@ class GlobalSearchViewController: BaseVC, UITableViewDelegate, UITableViewDataSo
var refreshTimer: Timer?
private func refreshSearchResults() {
guard !searchResultSet.isEmpty else {
// To avoid incorrectly showing the "no results" state,
// always search immediately if the current result set is empty.
refreshTimer?.invalidate()
refreshTimer = nil
updateSearchResults(searchText: searchText)
return
}
if refreshTimer != nil {
// Don't start a new refresh timer if there's already one active.
return
}
refreshTimer?.invalidate()
refreshTimer = WeakTimer.scheduledTimer(timeInterval: 0.1, target: self, userInfo: nil, repeats: false) { [weak self] _ in
guard let self = self else {
return
}
guard let self = self else { return }
self.updateSearchResults(searchText: self.searchText)
self.refreshTimer = nil
}
}
@ -170,13 +150,14 @@ class GlobalSearchViewController: BaseVC, UITableViewDelegate, UITableViewDataSo
self.isLoading = true
// The max search result count is set according to the keyword length. This is just a workaround for performance issue.
// The longer and more accurate the keyword is, the less search results should there be.
searchResults = self.searcher.searchForHomeScreen(searchText: searchText, maxSearchResults: min(searchText.count * 50, 500), transaction: transaction)
searchResults = self.searcher.searchForHomeScreen(searchText: searchText, maxSearchResults: 500, transaction: transaction)
}, completionBlock: { [weak self] in
AssertIsOnMainThread()
guard let self = self, let results = searchResults, self.lastSearchText == searchText else { return }
self.searchResultSet = results
self.isLoading = false
self.reloadTableData()
self.refreshTimer = nil
})
}
@ -232,12 +213,12 @@ extension GlobalSearchViewController {
SNLog("shouldn't be able to tap 'no results' section")
case .contacts:
let sectionResults = searchResultSet.conversations
guard let searchResult = sectionResults[safe: indexPath.row], let threadId = searchResult.thread.threadRecord.uniqueId, let thread = TSThread.fetch(uniqueId: threadId) else { return }
show(thread, highlightedMessageID: nil, animated: true)
guard let searchResult = sectionResults[safe: indexPath.row] else { return }
show(searchResult.thread.threadRecord, highlightedMessageID: nil, animated: true)
case .messages:
let sectionResults = searchResultSet.messages
guard let searchResult = sectionResults[safe: indexPath.row], let threadId = searchResult.thread.threadRecord.uniqueId, let thread = TSThread.fetch(uniqueId: threadId) else { return }
show(thread, highlightedMessageID: searchResult.messageId, animated: true)
guard let searchResult = sectionResults[safe: indexPath.row] else { return }
show(searchResult.thread.threadRecord, highlightedMessageID: searchResult.message?.uniqueId, animated: true)
case .recent:
guard let threadId = recentSearchResults[safe: indexPath.row], let thread = TSThread.fetch(uniqueId: threadId) else { return }
show(thread, highlightedMessageID: nil, animated: true, isFromRecent: true)
@ -376,7 +357,7 @@ extension GlobalSearchViewController {
cell.isShowingGlobalSearchResult = true
let searchResult = sectionResults[safe: indexPath.row]
cell.threadViewModel = searchResult?.thread
cell.configure(messageDate: searchResult?.messageDate, snippet: searchResult?.snippet, searchText: searchResultSet.searchText)
cell.configure(snippet: searchResult?.snippet, searchText: searchResultSet.searchText)
return cell
case .messages:
let sectionResults = searchResultSet.messages
@ -384,9 +365,7 @@ extension GlobalSearchViewController {
cell.isShowingGlobalSearchResult = true
let searchResult = sectionResults[safe: indexPath.row]
cell.threadViewModel = searchResult?.thread
var message: TSMessage? = nil
if let messageId = searchResult?.messageId { message = TSMessage.fetch(uniqueId: messageId) }
cell.configure(messageDate: searchResult?.messageDate, snippet: searchResult?.snippet, searchText: searchResultSet.searchText, message: message)
cell.configure(snippet: searchResult?.snippet, searchText: searchResultSet.searchText, message: searchResult?.message)
return cell
case .recent:
let cell = tableView.dequeueReusableCell(withIdentifier: ConversationCell.reuseIdentifier) as! ConversationCell

View File

@ -20,6 +20,8 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, NewConv
return result
}()
private var isReloading = false
// MARK: UI Components
private lazy var seedReminderView: SeedReminderView = {
let result = SeedReminderView(hasContinueButton: true)
@ -135,6 +137,7 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, NewConv
notificationCenter.addObserver(self, selector: #selector(handleLocalProfileDidChangeNotification(_:)), name: Notification.Name(kNSNotificationName_LocalProfileDidChange), object: nil)
notificationCenter.addObserver(self, selector: #selector(handleSeedViewedNotification(_:)), name: .seedViewed, object: nil)
notificationCenter.addObserver(self, selector: #selector(handleBlockedContactsUpdatedNotification(_:)), name: .blockedContactsUpdated, object: nil)
notificationCenter.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: .OWSApplicationDidBecomeActive, object: nil)
// Threads (part 2)
threads = YapDatabaseViewMappings(groups: [ TSMessageRequestGroup, TSInboxGroup ], view: TSThreadDatabaseViewExtensionName) // The extension should be registered at this point
threads.setIsReversed(true, forGroup: TSInboxGroup)
@ -167,6 +170,10 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, NewConv
reload()
}
@objc private func applicationDidBecomeActive(_ notification: Notification) {
reload()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@ -209,6 +216,8 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, NewConv
private func reload() {
AssertIsOnMainThread()
guard !isReloading else { return }
isReloading = true
dbConnection.beginLongLivedReadTransaction() // Jump to the latest commit
dbConnection.read { transaction in
self.threads.update(with: transaction)
@ -216,6 +225,7 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, NewConv
threadViewModelCache.removeAll()
tableView.reloadData()
emptyStateView.isHidden = (threadCount != 0)
isReloading = false
}
@objc private func handleYapDatabaseModifiedNotification(_ yapDatabase: YapDatabase) {

View File

@ -6,7 +6,11 @@ import SessionMessagingKit
@objc
class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDataSource {
private var threads: YapDatabaseViewMappings!
private var threads: YapDatabaseViewMappings! = {
let result = YapDatabaseViewMappings(groups: [ TSMessageRequestGroup ], view: TSThreadDatabaseViewExtensionName)
result.setIsReversed(true, forGroup: TSMessageRequestGroup)
return result
}()
private var threadViewModelCache: [String: ThreadViewModel] = [:] // Thread ID to ThreadViewModel
private var tableViewTopConstraint: NSLayoutConstraint!
@ -85,16 +89,13 @@ class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDat
ViewControllerUtilities.setUpDefaultSessionStyle(for: self, title: NSLocalizedString("MESSAGE_REQUESTS_TITLE", comment: ""), hasCustomBackButton: false)
// Threads (part 1)
// Freeze the connection for use on the main thread (this gives us a stable data source that doesn't change until we tell it to)
dbConnection.beginLongLivedReadTransaction()
// Add the UI (MUST be done after the thread freeze so the 'tableView' creation and setting
// the dataSource has the correct data)
view.addSubview(tableView)
view.addSubview(emptyStateLabel)
view.addSubview(fadeView)
view.addSubview(clearAllButton)
setupLayout()
// Notifications
NotificationCenter.default.addObserver(
@ -116,18 +117,11 @@ class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDat
object: nil
)
// Threads (part 2)
threads = YapDatabaseViewMappings(groups: [ TSMessageRequestGroup ], view: TSThreadDatabaseViewExtensionName) // The extension should be registered at this point
dbConnection.read { transaction in
self.threads.update(with: transaction) // Perform the initial update
}
setupLayout()
reload()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
reload()
}
@ -188,7 +182,6 @@ class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDat
tableView.reloadData()
clearAllButton.isHidden = (messageRequestCount == 0)
emptyStateLabel.isHidden = (messageRequestCount != 0)
emptyStateLabel.isHidden = (messageRequestCount != 0)
}
@objc private func handleYapDatabaseModifiedNotification(_ yapDatabase: YapDatabase) {

View File

@ -584,12 +584,6 @@ static NSTimeInterval launchStartedAt;
[self.pushRegistrationManager didReceiveVanillaPushToken:deviceToken];
OWSLogInfo(@"Registering for push notifications with token: %@.", deviceToken);
BOOL isUsingFullAPNs = [NSUserDefaults.standardUserDefaults boolForKey:@"isUsingFullAPNs"];
if (isUsingFullAPNs) {
__unused AnyPromise *promise = [LKPushNotificationAPI registerWithToken:deviceToken hexEncodedPublicKey:self.tsAccountManager.localNumber isForcedUpdate:NO];
} else {
__unused AnyPromise *promise = [LKPushNotificationAPI unregisterToken:deviceToken];
}
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

View File

@ -226,6 +226,9 @@ NSString *const ReportedApplicationStateDidChangeNotification = @"ReportedApplic
- (void)setMainAppBadgeNumber:(NSInteger)value
{
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:value];
NSUserDefaults *sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.loki-project.loki-messenger"];
[sharedUserDefaults setInteger:value forKey:@"currentBadgeNumber"];
[sharedUserDefaults synchronize];
}
- (nullable UIViewController *)frontmostViewController

View File

@ -167,16 +167,8 @@ public class NotificationPresenter: NSObject, NotificationsProtocol {
// so just ignore those and if the user has hidden message requests then we want to show the
// notification regardless of how many message requests there are)
if !thread.isGroupThread() && thread.isMessageRequest() && !CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] {
let dbConnection: YapDatabaseConnection = OWSPrimaryStorage.shared().newDatabaseConnection()
dbConnection.objectCacheLimit = 2
dbConnection.beginLongLivedReadTransaction() // Freeze the connection for use on the main thread (this gives us a stable data source that doesn't change until we tell it to)
let threads: YapDatabaseViewMappings = YapDatabaseViewMappings(groups: [ TSMessageRequestGroup ], view: TSThreadDatabaseViewExtensionName)
dbConnection.read { transaction in
threads.update(with: transaction) // Perform the initial update
}
let threads = transaction.ext(TSThreadDatabaseViewExtensionName) as! YapDatabaseViewTransaction
let numMessageRequests = threads.numberOfItems(inGroup: TSMessageRequestGroup)
dbConnection.endLongLivedReadTransaction()
// Allow this to show a notification if there are no message requests (ie. this is the first one)
guard numMessageRequests == 0 else { return }
@ -225,7 +217,7 @@ public class NotificationPresenter: NSObject, NotificationsProtocol {
notificationTitle = (thread.isMessageRequest() ? "Session" : senderName)
case is TSGroupThread:
var groupName = thread.name()
var groupName = thread.name(with: transaction)
if groupName.count < 1 {
groupName = MessageStrings.newGroupDefaultTitle
}

View File

@ -84,7 +84,7 @@ class BaseVC : UIViewController {
internal func setUpNavBarSessionHeading() {
let headingImageView = UIImageView()
headingImageView.tintColor = Colors.sessionHeading
headingImageView.tintColor = Colors.text
headingImageView.image = UIImage(named: "SessionHeading")?.withRenderingMode(.alwaysTemplate)
headingImageView.contentMode = .scaleAspectFit
headingImageView.set(.width, to: 150)

View File

@ -221,10 +221,11 @@ final class ConversationCell : UITableViewCell {
timestampLabel.isHidden = true
}
public func configure(messageDate: Date?, snippet: String?, searchText: String, message: TSMessage? = nil) {
public func configure(snippet: String?, searchText: String, message: TSMessage? = nil) {
let normalizedSearchText = searchText.lowercased()
if let messageDate = messageDate, let snippet = snippet {
if let messageTimestamp = message?.timestamp, let snippet = snippet {
// Message
let messageDate = NSDate.ows_date(withMillisecondsSince1970: messageTimestamp)
displayNameLabel.attributedText = NSMutableAttributedString(string: getDisplayName(), attributes: [.foregroundColor:Colors.text])
timestampLabel.isHidden = false
timestampLabel.text = DateUtil.formatDate(forDisplay: messageDate)

View File

@ -10,27 +10,19 @@ public final class MentionUtilities : NSObject {
@objc public static func highlightMentions(in string: String, isOutgoingMessage: Bool, threadID: String, attributes: [NSAttributedString.Key:Any]) -> NSAttributedString {
let openGroupV2 = Storage.shared.getV2OpenGroup(for: threadID)
OWSPrimaryStorage.shared().dbReadConnection.read { transaction in
MentionsManager.populateUserPublicKeyCacheIfNeeded(for: threadID, in: transaction)
}
var string = string
let regex = try! NSRegularExpression(pattern: "@[0-9a-fA-F]{66}", options: [])
let knownPublicKeys = MentionsManager.userPublicKeyCache[threadID] ?? [] // Should always be populated at this point
var mentions: [(range: NSRange, publicKey: String)] = []
var outerMatch = regex.firstMatch(in: string, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: string.utf16.count))
while let match = outerMatch {
let publicKey = String((string as NSString).substring(with: match.range).dropFirst()) // Drop the @
let matchEnd: Int
if knownPublicKeys.contains(publicKey) {
let context: Contact.Context = (openGroupV2 != nil) ? .openGroup : .regular
let displayName = Storage.shared.getContact(with: publicKey)?.displayName(for: context)
if let displayName = displayName {
string = (string as NSString).replacingCharacters(in: match.range, with: "@\(displayName)")
mentions.append((range: NSRange(location: match.range.location, length: displayName.utf16.count + 1), publicKey: publicKey)) // + 1 to include the @
matchEnd = match.range.location + displayName.utf16.count
} else {
matchEnd = match.range.location + match.range.length
}
let context: Contact.Context = (openGroupV2 != nil) ? .openGroup : .regular
let displayName = Storage.shared.getContact(with: publicKey)?.displayName(for: context)
if let displayName = displayName {
string = (string as NSString).replacingCharacters(in: match.range, with: "@\(displayName)")
mentions.append((range: NSRange(location: match.range.location, length: displayName.utf16.count + 1), publicKey: publicKey)) // + 1 to include the @
matchEnd = match.range.location + displayName.utf16.count
} else {
matchEnd = match.range.location + match.range.length
}

View File

@ -68,6 +68,7 @@ void VerifyRegistrationsForPrimaryStorage(OWSStorage *storage)
self.database.maxConnectionPoolCount = 5; // Increase max connection pool count, default is 3.
_dbReadPool = [[YapDatabaseConnectionPool alloc] initWithDatabase:self.database];
_dbReadPool.connectionLimit = 10; // Increase max read connection limit. Default is 3.
_dbReadWriteConnection = [self newDatabaseConnection];
_uiDatabaseConnection = [self newDatabaseConnection];

View File

@ -17,7 +17,7 @@ typedef NS_ENUM(NSInteger, TSInfoMessageType) {
TSInfoMessageTypeScreenshotNotification,
TSInfoMessageTypeMediaSavedNotification,
TSInfoMessageTypeCall,
TSInfoMessageTypeMessageRequestAccepted
TSInfoMessageTypeMessageRequestAccepted = 99 // Avoid conficts wit TSInfoMessageTypeCall
};
typedef NS_ENUM(NSInteger, TSInfoMessageCallState) {

View File

@ -103,14 +103,6 @@ public final class VisibleMessage : Message {
// TODO: Contact
// Open group invitation
if let openGroupInvitation = openGroupInvitation, let openGroupInvitationProto = openGroupInvitation.toProto() { dataMessage.setOpenGroupInvitation(openGroupInvitationProto) }
// Expiration timer
// TODO: We * want * expiration timer updates to be explicit. But currently Android will disable the expiration timer for a conversation
// if it receives a message without the current expiration timer value attached to it...
var expiration: UInt32 = 0
if let disappearingMessagesConfiguration = OWSDisappearingMessagesConfiguration.fetch(uniqueId: threadID!, transaction: transaction) {
expiration = disappearingMessagesConfiguration.isEnabled ? disappearingMessagesConfiguration.durationSeconds : 0
}
dataMessage.setExpireTimer(expiration)
// Group context
do {
try setGroupContextIfNeeded(on: dataMessage, using: transaction)

View File

@ -185,7 +185,7 @@ NSUInteger const TSAttachmentSchemaVersion = 4;
if (self.isVoiceMessage || !self.sourceFilename || self.sourceFilename.length == 0) {
attachmentString = NSLocalizedString(@"ATTACHMENT_TYPE_VOICE_MESSAGE",
@"Short text label for a voice message attachment, used for thread preview and on the lock screen");
return [NSString stringWithFormat:@"🎤 %@", attachmentString];
return [NSString stringWithFormat:@"🎙️ %@", attachmentString];
}
}

View File

@ -321,7 +321,7 @@ extension MessageReceiver {
print("[Calls] Received pre-offer message.")
// It is enough just ignoring the pre offers, other call messages
// for this call would be dropped because of no Session call instance
guard let sender = message.sender, let thread = TSContactThread.fetch(for: sender, using: transaction), thread.hasOutgoingInteraction(with: transaction) else { return }
guard let sender = message.sender, let contact = Storage.shared.getContact(with: sender), contact.isApproved else { return }
handleNewCallOfferMessageIfNeeded?(message, transaction)
case .offer:
print("[Calls] Received offer message.")
@ -445,7 +445,7 @@ extension MessageReceiver {
}
// Notify the user if needed
guard (isMainAppAndActive || isBackgroundPoll), let tsIncomingMessage = TSMessage.fetch(uniqueId: tsMessageID, transaction: transaction) as? TSIncomingMessage,
guard let tsIncomingMessage = TSMessage.fetch(uniqueId: tsMessageID, transaction: transaction) as? TSIncomingMessage,
let thread = TSThread.fetch(uniqueId: threadID, transaction: transaction) else { return tsMessageID }
// Use the same identifier for notifications when in backgroud polling to prevent spam
let notificationIdentifier = isBackgroundPoll ? thread.uniqueId : UUID().uuidString
@ -509,7 +509,7 @@ extension MessageReceiver {
// MARK: - Closed Groups
private static func handleClosedGroupControlMessage(_ message: ClosedGroupControlMessage, using transaction: Any) {
public static func handleClosedGroupControlMessage(_ message: ClosedGroupControlMessage, using transaction: Any) {
switch message.kind! {
case .new: handleNewClosedGroup(message, using: transaction)
case .encryptionKeyPair: handleClosedGroupEncryptionKeyPair(message, using: transaction)

View File

@ -59,6 +59,7 @@ public final class MessageSender : NSObject {
signalAttachments.forEach {
let attachment = TSAttachmentStream(contentType: $0.mimeType, byteCount: UInt32($0.dataLength), sourceFilename: $0.sourceFilename,
caption: $0.captionText, albumMessageId: tsMessage.uniqueId!)
attachment.attachmentType = $0.isVoiceMessage ? .voiceMessage : .default
attachments.append(attachment)
attachment.write($0.dataSource)
attachment.save(with: transaction)

View File

@ -61,13 +61,11 @@ public final class ClosedGroupPoller : NSObject {
// MARK: Private API
private func setUpPolling(for groupPublicKey: String) {
poll(groupPublicKey).done2 { [weak self] _ in
DispatchQueue.main.async { // Timers don't do well on background queues
Threading.pollerQueue.async {
self.poll(groupPublicKey).done(on: Threading.pollerQueue) { [weak self] _ in
self?.pollRecursively(groupPublicKey)
}
}.catch2 { [weak self] error in
// The error is logged in poll(_:)
DispatchQueue.main.async { // Timers don't do well on background queues
}.catch(on: Threading.pollerQueue) { [weak self] error in
// The error is logged in poll(_:)
self?.pollRecursively(groupPublicKey)
}
}
@ -87,15 +85,13 @@ public final class ClosedGroupPoller : NSObject {
let a = (ClosedGroupPoller.maxPollInterval - minPollInterval) / limit
let nextPollInterval = a * min(timeSinceLastMessage, limit) + minPollInterval
SNLog("Next poll interval for closed group with public key: \(groupPublicKey) is \(nextPollInterval) s.")
timers[groupPublicKey] = Timer.scheduledTimer(withTimeInterval: nextPollInterval, repeats: false) { [weak self] timer in
timers[groupPublicKey] = Timer.scheduledTimerOnMainThread(withTimeInterval: nextPollInterval, repeats: false) { [weak self] timer in
timer.invalidate()
self?.poll(groupPublicKey).done2 { _ in
DispatchQueue.main.async { // Timers don't do well on background queues
Threading.pollerQueue.async {
self?.poll(groupPublicKey).done(on: Threading.pollerQueue) { _ in
self?.pollRecursively(groupPublicKey)
}
}.catch2 { error in
// The error is logged in poll(_:)
DispatchQueue.main.async { // Timers don't do well on background queues
}.catch(on: Threading.pollerQueue) { error in
// The error is logged in poll(_:)
self?.pollRecursively(groupPublicKey)
}
}

View File

@ -19,14 +19,11 @@ public final class OpenGroupPollerV2 : NSObject {
@objc public func startIfNeeded() {
guard !hasStarted else { return }
DispatchQueue.main.async { [weak self] in // Timers don't do well on background queues
guard let strongSelf = self else { return }
strongSelf.hasStarted = true
strongSelf.timer = Timer.scheduledTimer(withTimeInterval: strongSelf.pollInterval, repeats: true) { _ in
self?.poll().retainUntilComplete()
}
strongSelf.poll().retainUntilComplete()
hasStarted = true
timer = Timer.scheduledTimerOnMainThread(withTimeInterval: pollInterval, repeats: true) { _ in
self.poll().retainUntilComplete()
}
poll().retainUntilComplete()
}
@objc public func stop() {
@ -46,15 +43,17 @@ public final class OpenGroupPollerV2 : NSObject {
self.isPolling = true
let (promise, seal) = Promise<Void>.pending()
promise.retainUntilComplete()
OpenGroupAPIV2.compactPoll(server).done(on: OpenGroupAPIV2.workQueue) { [weak self] bodies in
guard let self = self else { return }
self.isPolling = false
bodies.forEach { self.handleCompactPollBody($0, isBackgroundPoll: isBackgroundPoll) }
seal.fulfill(())
}.catch(on: OpenGroupAPIV2.workQueue) { error in
SNLog("Open group polling failed due to error: \(error).")
self.isPolling = false
seal.fulfill(()) // The promise is just used to keep track of when we're done
Threading.pollerQueue.async {
OpenGroupAPIV2.compactPoll(self.server).done(on: OpenGroupAPIV2.workQueue) { [weak self] bodies in
guard let self = self else { return }
self.isPolling = false
bodies.forEach { self.handleCompactPollBody($0, isBackgroundPoll: isBackgroundPoll) }
seal.fulfill(())
}.catch(on: OpenGroupAPIV2.workQueue) { error in
SNLog("Open group polling failed due to error: \(error).")
self.isPolling = false
seal.fulfill(()) // The promise is just used to keep track of when we're done
}
}
return promise
}

View File

@ -45,19 +45,22 @@ public final class Poller : NSObject {
// MARK: Private API
private func setUpPolling() {
guard isPolling else { return }
let _ = SnodeAPI.getSwarm(for: getUserHexEncodedPublicKey()).then2 { [weak self] _ -> Promise<Void> in
guard let strongSelf = self else { return Promise { $0.fulfill(()) } }
strongSelf.usedSnodes.removeAll()
let (promise, seal) = Promise<Void>.pending()
strongSelf.pollNextSnode(seal: seal)
return promise
}.ensure(on: DispatchQueue.main) { [weak self] in // Timers don't do well on background queues
guard let strongSelf = self, strongSelf.isPolling else { return }
Timer.scheduledTimer(withTimeInterval: Poller.retryInterval, repeats: false) { _ in
guard let strongSelf = self else { return }
strongSelf.setUpPolling()
Threading.pollerQueue.async {
let _ = SnodeAPI.getSwarm(for: getUserHexEncodedPublicKey()).then(on: Threading.pollerQueue) { [weak self] _ -> Promise<Void> in
guard let strongSelf = self else { return Promise { $0.fulfill(()) } }
strongSelf.usedSnodes.removeAll()
let (promise, seal) = Promise<Void>.pending()
strongSelf.pollNextSnode(seal: seal)
return promise
}.ensure(on: Threading.pollerQueue) { [weak self] in // Timers don't do well on background queues
guard let strongSelf = self, strongSelf.isPolling else { return }
Timer.scheduledTimerOnMainThread(withTimeInterval: Poller.retryInterval, repeats: false) { _ in
guard let strongSelf = self else { return }
strongSelf.setUpPolling()
}
}
}
}
private func pollNextSnode(seal: Resolver<Void>) {
@ -77,7 +80,9 @@ public final class Poller : NSObject {
SNLog("Polling \(nextSnode) failed; dropping it and switching to next snode.")
SnodeAPI.dropSnodeFromSwarmIfNeeded(nextSnode, publicKey: userPublicKey)
}
self?.pollNextSnode(seal: seal)
Threading.pollerQueue.async {
self?.pollNextSnode(seal: seal)
}
}
} else {
seal.fulfill(())
@ -87,7 +92,7 @@ public final class Poller : NSObject {
private func poll(_ snode: Snode, seal longTermSeal: Resolver<Void>) -> Promise<Void> {
guard isPolling else { return Promise { $0.fulfill(()) } }
let userPublicKey = getUserHexEncodedPublicKey()
return SnodeAPI.getRawMessages(from: snode, associatedWith: userPublicKey).then(on: DispatchQueue.main) { [weak self] rawResponse -> Promise<Void> in
return SnodeAPI.getRawMessages(from: snode, associatedWith: userPublicKey).then(on: Threading.pollerQueue) { [weak self] rawResponse -> Promise<Void> in
guard let strongSelf = self, strongSelf.isPolling else { return Promise { $0.fulfill(()) } }
let messages = SnodeAPI.parseRawMessagesResponse(rawResponse, from: snode, associatedWith: userPublicKey)
if !messages.isEmpty {
@ -109,7 +114,7 @@ public final class Poller : NSObject {
if strongSelf.pollCount == Poller.maxPollCount {
throw Error.pollLimitReached
} else {
return withDelay(Poller.pollInterval, completionQueue: DispatchQueue.main) {
return withDelay(Poller.pollInterval, completionQueue: Threading.pollerQueue) {
guard let strongSelf = self, strongSelf.isPolling else { return Promise { $0.fulfill(()) } }
return strongSelf.poll(snode, seal: longTermSeal)
}

View File

@ -287,6 +287,10 @@ NSString *const OWSReadReceiptManagerAreReadReceiptsEnabled = @"areReadReceiptsE
for (id<OWSReadTracking> readItem in newlyReadList) {
[readItem markAsReadAtTimestamp:readTimestamp trySendReadReceipt:trySendReadReceipt transaction:transaction];
}
// Update unread mention.
thread.hasUnreadMentionMessage = false;
[thread saveWithTransaction:transaction];
}
#pragma mark - Settings

View File

@ -16,6 +16,7 @@ BOOL IsNoteToSelfEnabled(void);
*/
@interface TSThread : TSYapDatabaseObject
@property (nonatomic) BOOL hasUnreadMentionMessage;
@property (nonatomic) BOOL isPinned;
@property (nonatomic) BOOL shouldBeVisible;
@property (nonatomic, readonly) NSDate *creationDate;
@ -76,9 +77,6 @@ BOOL IsNoteToSelfEnabled(void);
- (NSUInteger)unreadMessageCountWithTransaction:(YapDatabaseReadTransaction *)transaction
NS_SWIFT_NAME(unreadMessageCount(transaction:));
- (BOOL)hasUnreadMentionMessageWithTransaction:(YapDatabaseReadTransaction *)transaction
NS_SWIFT_NAME(hasUnreadMentionMessage(transaction:));
- (void)markAllAsReadWithTransaction:(YapDatabaseReadWriteTransaction *)transaction;
/**

View File

@ -273,49 +273,28 @@ BOOL IsNoteToSelfEnabled(void)
- (NSUInteger)unreadMessageCountWithTransaction:(YapDatabaseReadTransaction *)transaction
{
__block NSUInteger count = 0;
YapDatabaseViewTransaction *unreadMessages = [transaction ext:TSUnreadDatabaseViewExtensionName];
[unreadMessages enumerateKeysAndObjectsInGroup:self.uniqueId
usingBlock:^(NSString *collection, NSString *key, id object, NSUInteger index, BOOL *stop) {
if (![object conformsToProtocol:@protocol(OWSReadTracking)]) {
return;
}
id<OWSReadTracking> unread = (id<OWSReadTracking>)object;
if (unread.read) {
NSLog(@"Found an already read message in the * unread * messages list.");
return;
}
count += 1;
}];
return count;
}
- (BOOL)hasUnreadMentionMessageWithTransaction:(YapDatabaseReadTransaction *)transaction
{
__block BOOL hasUnreadMention = false;
return [unreadMessages numberOfItemsInGroup:self.uniqueId];
YapDatabaseViewTransaction *unreadMessages = [transaction ext:TSUnreadDatabaseViewExtensionName];
[unreadMessages enumerateKeysAndObjectsInGroup:self.uniqueId
usingBlock:^(NSString *collection, NSString *key, id object, NSUInteger index, BOOL *stop) {
if (![object isKindOfClass:[TSIncomingMessage class]]) {
return;
}
TSIncomingMessage* unreadMessage = (TSIncomingMessage*)object;
if (unreadMessage.read) {
NSLog(@"Found an already read message in the * unread * messages list.");
return;
}
if (unreadMessage.isUserMentioned) {
hasUnreadMention = true;
*stop = YES;
}
}];
return hasUnreadMention;
// FIXME: Why did we have to do as the following?
// __block NSUInteger count = 0;
//
// YapDatabaseViewTransaction *unreadMessages = [transaction ext:TSUnreadDatabaseViewExtensionName];
// [unreadMessages enumerateKeysAndObjectsInGroup:self.uniqueId
// usingBlock:^(NSString *collection, NSString *key, id object, NSUInteger index, BOOL *stop) {
// if (![object conformsToProtocol:@protocol(OWSReadTracking)]) {
// return;
// }
// id<OWSReadTracking> unread = (id<OWSReadTracking>)object;
// if (unread.read) {
// NSLog(@"Found an already read message in the * unread * messages list.");
// return;
// }
// count += 1;
// }];
// return count;
}
- (void)markAllAsReadWithTransaction:(YapDatabaseReadWriteTransaction *)transaction
@ -323,6 +302,10 @@ BOOL IsNoteToSelfEnabled(void)
for (id<OWSReadTracking> message in [self unseenMessagesWithTransaction:transaction]) {
[message markAsReadAtTimestamp:[NSDate ows_millisecondTimeStamp] trySendReadReceipt:YES transaction:transaction];
}
// Update unread mention.
self.hasUnreadMentionMessage = false;
[super saveWithTransaction:transaction];
}
- (nullable TSInteraction *)lastInteractionForInboxWithTransaction:(YapDatabaseReadTransaction *)transaction
@ -388,6 +371,12 @@ BOOL IsNoteToSelfEnabled(void)
_lastInteractionDate = lastMessage.receivedAtDate;
[super saveWithTransaction:transaction];
}
// Update unread mention if there is a new incoming message.
if ([lastMessage isKindOfClass:[TSIncomingMessage class]] && ((TSIncomingMessage *)lastMessage).isUserMentioned) {
self.hasUnreadMentionMessage = true;
[super saveWithTransaction:transaction];
}
if (!self.shouldBeVisible) {
self.shouldBeVisible = YES;

View File

@ -3,4 +3,6 @@ import Foundation
internal enum Threading {
internal static let jobQueue = DispatchQueue(label: "SessionMessagingKit.jobQueue", qos: .userInitiated)
internal static let pollerQueue = DispatchQueue(label: "SessionMessagingKit.pollerQueue")
}

View File

@ -0,0 +1,133 @@
// Copyright © 2022 Rangeproof Pty Ltd. All rights reserved.
import SignalUtilitiesKit
import UserNotifications
public class NSENotificationPresenter: NSObject, NotificationsProtocol {
public func notifyUser(for incomingMessage: TSIncomingMessage, in thread: TSThread, transaction: YapDatabaseReadTransaction) {
guard !thread.isMuted else { return }
guard let threadID = thread.uniqueId else { return }
// If the thread is a message request and the user hasn't hidden message requests then we need
// to check if this is the only message request thread (group threads can't be message requests
// so just ignore those and if the user has hidden message requests then we want to show the
// notification regardless of how many message requests there are)
if !thread.isGroupThread() && thread.isMessageRequest() && !CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] {
let threads = transaction.ext(TSThreadDatabaseViewExtensionName) as! YapDatabaseViewTransaction
let numMessageRequests = threads.numberOfItems(inGroup: TSMessageRequestGroup)
// Allow this to show a notification if there are no message requests (ie. this is the first one)
guard numMessageRequests == 0 else { return }
}
else if thread.isMessageRequest() && CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] {
// If there are other interactions on this thread already then don't show the notification
if thread.numberOfInteractions() > 1 { return }
CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] = false
}
let senderPublicKey = incomingMessage.authorId
let userPublicKey = SNGeneralUtilities.getUserPublicKey()
guard senderPublicKey != userPublicKey else {
// Ignore PNs for messages sent by the current user
// after handling the message. Otherwise the closed
// group self-send messages won't show.
return
}
let context = Contact.context(for: thread)
let senderName = Storage.shared.getContact(with: senderPublicKey, using: transaction)?.displayName(for: context) ?? senderPublicKey
var notificationTitle = senderName
if let group = thread as? TSGroupThread {
if group.isOnlyNotifyingForMentions && !incomingMessage.isUserMentioned {
// Ignore PNs if the group is set to only notify for mentions
return
}
var groupName = thread.name(with: transaction)
if groupName.count < 1 {
groupName = MessageStrings.newGroupDefaultTitle
}
notificationTitle = String(format: NotificationStrings.incomingGroupMessageTitleFormat, senderName, groupName)
}
let snippet = incomingMessage.previewText(with: transaction).filterForDisplay?.replacingMentions(for: threadID, using: transaction)
?? "APN_Message".localized()
var userInfo: [String:Any] = [ NotificationServiceExtension.isFromRemoteKey : true ]
userInfo[NotificationServiceExtension.threadIdKey] = threadID
let notificationContent = UNMutableNotificationContent()
notificationContent.userInfo = userInfo
notificationContent.sound = OWSSounds.notificationSound(for: thread).notificationSound(isQuiet: false)
// Badge Number
let newBadgeNumber = CurrentAppContext().appUserDefaults().integer(forKey: "currentBadgeNumber") + 1
notificationContent.badge = NSNumber(value: newBadgeNumber)
CurrentAppContext().appUserDefaults().set(newBadgeNumber, forKey: "currentBadgeNumber")
// Title & body
let notificationsPreference = Environment.shared.preferences!.notificationPreviewType()
switch notificationsPreference {
case .namePreview:
notificationContent.title = notificationTitle
notificationContent.body = snippet
case .nameNoPreview:
notificationContent.title = notificationTitle
notificationContent.body = NotificationStrings.incomingMessageBody
case .noNameNoPreview:
notificationContent.title = "Session"
notificationContent.body = NotificationStrings.incomingMessageBody
default: break
}
// If it's a message request then overwrite the body to be something generic (only show a notification
// when receiving a new message request if there aren't any others or the user had hidden them)
if thread.isMessageRequest() {
notificationContent.body = "MESSAGE_REQUESTS_NOTIFICATION".localized()
}
// Add request
let identifier = incomingMessage.notificationIdentifier ?? UUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: nil)
SNLog("Add remote notification request")
UNUserNotificationCenter.current().add(request)
}
public func cancelNotification(_ identifier: String) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removePendingNotificationRequests(withIdentifiers: [ identifier ])
notificationCenter.removeDeliveredNotifications(withIdentifiers: [ identifier ])
}
public func clearAllNotifications() {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllPendingNotificationRequests()
notificationCenter.removeAllDeliveredNotifications()
}
}
private extension String {
func replacingMentions(for threadID: String, using transaction: YapDatabaseReadTransaction) -> String {
var result = self
let regex = try! NSRegularExpression(pattern: "@[0-9a-fA-F]{66}", options: [])
var mentions: [(range: NSRange, publicKey: String)] = []
var m0 = regex.firstMatch(in: result, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: result.utf16.count))
while let m1 = m0 {
let publicKey = String((result as NSString).substring(with: m1.range).dropFirst()) // Drop the @
var matchEnd = m1.range.location + m1.range.length
let displayName = Storage.shared.getContact(with: publicKey, using: transaction)?.displayName(for: .regular)
if let displayName = displayName {
result = (result as NSString).replacingCharacters(in: m1.range, with: "@\(displayName)")
mentions.append((range: NSRange(location: m1.range.location, length: displayName.utf16.count + 1), publicKey: publicKey)) // + 1 to include the @
matchEnd = m1.range.location + displayName.utf16.count
}
m0 = regex.firstMatch(in: result, options: .withoutAnchoringBounds, range: NSRange(location: matchEnd, length: result.utf16.count - matchEnd))
}
return result
}
}

View File

@ -3,20 +3,23 @@ import BackgroundTasks
import SessionMessagingKit
import SignalUtilitiesKit
import CallKit
import PromiseKit
public final class NotificationServiceExtension : UNNotificationServiceExtension {
private var didPerformSetup = false
private var areVersionMigrationsComplete = false
private var contentHandler: ((UNNotificationContent) -> Void)?
private var notificationContent: UNMutableNotificationContent?
private var request: UNNotificationRequest?
private static let isFromRemoteKey = "remote"
private static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId"
public static let isFromRemoteKey = "remote"
public static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId"
// MARK: Did receive a remote push notification request
override public func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
self.notificationContent = request.content.mutableCopy() as? UNMutableNotificationContent
let userPublicKey = SNGeneralUtilities.getUserPublicKey()
self.request = request
guard let notificationContent = request.content.mutableCopy() as? UNMutableNotificationContent else { return self.completeSilenty() }
// Abort if the main app is running
var isMainAppAndActive = false
@ -30,7 +33,12 @@ public final class NotificationServiceExtension : UNNotificationServiceExtension
// Handle the push notification
AppReadiness.runNowOrWhenAppDidBecomeReady {
let notificationContent = self.notificationContent!
let openGorupPollingPromises = self.pollForOpenGroups()
defer {
when(resolved: openGorupPollingPromises).done { _ in
self.completeSilenty()
}
}
guard let base64EncodedData = notificationContent.userInfo["ENCRYPTED_DATA"] as! String?, let data = Data(base64Encoded: base64EncodedData),
let envelope = try? MessageWrapper.unwrap(data: data), let envelopeAsData = try? envelope.serializedData() else {
return self.handleFailure(for: notificationContent)
@ -38,160 +46,50 @@ public final class NotificationServiceExtension : UNNotificationServiceExtension
Storage.write { transaction in // Intentionally capture self
do {
let (message, proto) = try MessageReceiver.parse(envelopeAsData, openGroupMessageServerID: nil, using: transaction)
let senderPublicKey = message.sender!
var senderDisplayName = Storage.shared.getContact(with: senderPublicKey)?.displayName(for: .regular) ?? senderPublicKey
let snippet: String
var userInfo: [String: Any] = [ NotificationServiceExtension.isFromRemoteKey: true ]
var isMessageRequest: Bool = false
switch message {
case let visibleMessage as VisibleMessage:
let tsIncomingMessageID = try MessageReceiver.handleVisibleMessage(visibleMessage, associatedWithProto: proto, openGroupID: nil, isBackgroundPoll: false, using: transaction)
guard let tsMessage = TSMessage.fetch(uniqueId: tsIncomingMessageID, transaction: transaction) else {
return self.completeSilenty()
}
let thread = tsMessage.thread(with: transaction)
let threadID = thread.uniqueId!
userInfo[NotificationServiceExtension.threadIdKey] = threadID
snippet = tsMessage.previewText(with: transaction).filterForDisplay?.replacingMentions(for: threadID, using: transaction)
?? "You've got a new message"
if let tsIncomingMessage = tsMessage as? TSIncomingMessage {
// Ignore PNs if the thread is muted
if thread.isMuted { return self.completeSilenty() }
if let thread = TSThread.fetch(uniqueId: threadID, transaction: transaction), let group = thread as? TSGroupThread,
group.groupModel.groupType == .closedGroup { // Should always be true because we don't get PNs for open groups
senderDisplayName = String(format: NotificationStrings.incomingGroupMessageTitleFormat, senderDisplayName, group.groupModel.groupName ?? MessageStrings.newGroupDefaultTitle)
if group.isOnlyNotifyingForMentions && !tsIncomingMessage.isUserMentioned {
// Ignore PNs if the group is set to only notify for mentions
return self.completeSilenty()
}
}
// If the thread is a message request and the user hasn't hidden message requests then we need
// to check if this is the only message request thread (group threads can't be message requests
// so just ignore those and if the user has hidden message requests then we want to show the
// notification regardless of how many message requests there are)
if !thread.isGroupThread() && thread.isMessageRequest() && !CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] {
let dbConnection: YapDatabaseConnection = OWSPrimaryStorage.shared().newDatabaseConnection()
dbConnection.objectCacheLimit = 2
dbConnection.beginLongLivedReadTransaction() // Freeze the connection for use on the main thread (this gives us a stable data source that doesn't change until we tell it to)
let threads: YapDatabaseViewMappings = YapDatabaseViewMappings(groups: [ TSMessageRequestGroup ], view: TSThreadDatabaseViewExtensionName)
dbConnection.read { transaction in
threads.update(with: transaction) // Perform the initial update
}
let numMessageRequests = threads.numberOfItems(inGroup: TSMessageRequestGroup)
dbConnection.endLongLivedReadTransaction()
// Allow this to show a notification if there are no message requests (ie. this is the first one)
guard numMessageRequests == 0 else { return self.completeSilenty() }
}
else if thread.isMessageRequest() && CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] {
// If there are other interactions on this thread already then don't show the notification
if thread.numberOfInteractions() > 1 { return }
CurrentAppContext().appUserDefaults()[.hasHiddenMessageRequests] = false
}
isMessageRequest = thread.isMessageRequest()
// Store the notification ID for unsend requests to later cancel this notification
tsIncomingMessage.setNotificationIdentifier(request.identifier, transaction: transaction)
}
else {
let semaphore = DispatchSemaphore(value: 0)
let center = UNUserNotificationCenter.current()
center.getDeliveredNotifications { notifications in
let matchingNotifications = notifications.filter({ $0.request.content.userInfo[NotificationServiceExtension.threadIdKey] as? String == threadID})
center.removeDeliveredNotifications(withIdentifiers: matchingNotifications.map({ $0.request.identifier }))
// Hack: removeDeliveredNotifications seems to be async,need to wait for some time before the delivered notifications can be removed.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { semaphore.signal() }
}
semaphore.wait()
}
notificationContent.sound = OWSSounds.notificationSound(for: thread).notificationSound(isQuiet: false)
case let unsendRequest as UnsendRequest:
MessageReceiver.handleUnsendRequest(unsendRequest, using: transaction)
return self.completeSilenty()
case let closedGroupControlMessage as ClosedGroupControlMessage:
// TODO: We could consider actually handling the update here. Not sure if there's enough time though, seeing as though
// in some cases we need to send messages (e.g. our sender key) to a number of other users.
switch closedGroupControlMessage.kind {
case .new(_, let name, _, _, _, _): snippet = "\(senderDisplayName) added you to \(name)"
default: return self.completeSilenty()
}
case let visibleMessage as VisibleMessage:
let tsMessageID = try MessageReceiver.handleVisibleMessage(visibleMessage, associatedWithProto: proto, openGroupID: nil, isBackgroundPoll: false, using: transaction)
case let callMessage as CallMessage:
MessageReceiver.handleCallMessage(callMessage, using: transaction)
guard case .preOffer = callMessage.kind else { return self.completeSilenty() }
if !SSKPreferences.areCallsEnabled {
if let sender = callMessage.sender, let thread = TSContactThread.fetch(for: sender, using: transaction), thread.hasOutgoingInteraction(with: transaction) {
let infoMessage = TSInfoMessage.from(callMessage, associatedWith: thread)
infoMessage.updateCallInfoMessage(.missed, using: transaction)
}
return self.completeSilenty()
// Remove the notificaitons if there is an outgoing messages from a linked device
if let tsMessage = TSMessage.fetch(uniqueId: tsMessageID, transaction: transaction), tsMessage.isKind(of: TSOutgoingMessage.self), let threadID = tsMessage.thread(with: transaction).uniqueId {
let semaphore = DispatchSemaphore(value: 0)
let center = UNUserNotificationCenter.current()
center.getDeliveredNotifications { notifications in
let matchingNotifications = notifications.filter({ $0.request.content.userInfo[NotificationServiceExtension.threadIdKey] as? String == threadID})
center.removeDeliveredNotifications(withIdentifiers: matchingNotifications.map({ $0.request.identifier }))
// Hack: removeDeliveredNotifications seems to be async,need to wait for some time before the delivered notifications can be removed.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { semaphore.signal() }
}
notificationContent.userInfo = userInfo
notificationContent.badge = 1
notificationContent.title = "Session"
notificationContent.body = "\(senderDisplayName) is calling..."
return self.handleSuccessForIncomingCall(for: notificationContent, callMessage: callMessage)
semaphore.wait()
}
default: return self.completeSilenty()
case let unsendRequest as UnsendRequest:
MessageReceiver.handleUnsendRequest(unsendRequest, using: transaction)
case let closedGroupControlMessage as ClosedGroupControlMessage:
MessageReceiver.handleClosedGroupControlMessage(closedGroupControlMessage, using: transaction)
case let callMessage as CallMessage:
MessageReceiver.handleCallMessage(callMessage, using: transaction)
guard case .preOffer = callMessage.kind else { return self.completeSilenty() }
if !SSKPreferences.areCallsEnabled {
if let sender = callMessage.sender, let thread = TSContactThread.fetch(for: sender, using: transaction), thread.hasOutgoingInteraction(with: transaction) {
let infoMessage = TSInfoMessage.from(callMessage, associatedWith: thread)
infoMessage.updateCallInfoMessage(.missed, using: transaction)
}
}
self.handleSuccessForIncomingCall(for: callMessage, using: transaction)
default: break
}
if (senderPublicKey == userPublicKey) {
// Ignore PNs for messages sent by the current user
// after handling the message. Otherwise the closed
// group self-send messages won't show.
return self.completeSilenty()
}
notificationContent.userInfo = userInfo
notificationContent.badge = 1
let notificationsPreference = Environment.shared.preferences!.notificationPreviewType()
switch notificationsPreference {
case .namePreview:
notificationContent.title = senderDisplayName
notificationContent.body = snippet
case .nameNoPreview:
notificationContent.title = senderDisplayName
notificationContent.body = NotificationStrings.incomingMessageBody
case .noNameNoPreview:
notificationContent.title = "Session"
notificationContent.body = NotificationStrings.incomingMessageBody
default: break
}
// If it's a message request then overwrite the body to be something generic (only show a notification
// when receiving a new message request if there aren't any others or the user had hidden them)
if isMessageRequest {
notificationContent.title = "Session"
notificationContent.body = NSLocalizedString("MESSAGE_REQUESTS_NOTIFICATION", comment: "")
}
self.handleSuccess(for: notificationContent)
}
catch {
} catch {
if let error = error as? MessageReceiver.Error, error.isRetryable {
self.handleFailure(for: notificationContent)
}
self.completeSilenty()
}
}
}
}
// MARK: Set up environment
// MARK: Setup
private func setUpIfNecessary(completion: @escaping () -> Void) {
AssertIsOnMainThread()
@ -218,7 +116,7 @@ public final class NotificationServiceExtension : UNNotificationServiceExtension
AppSetup.setupEnvironment(
appSpecificSingletonBlock: {
SSKEnvironment.shared.notificationsManager = NoopNotificationsManager()
SSKEnvironment.shared.notificationsManager = NSENotificationPresenter()
},
migrationCompletion: { [weak self] in
self?.versionMigrationsDidComplete()
@ -261,30 +159,26 @@ public final class NotificationServiceExtension : UNNotificationServiceExtension
AppReadiness.setAppIsReady()
}
// MARK: Completion
// MARK: Handle completion
override public func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
let userInfo: [String:Any] = [ NotificationServiceExtension.isFromRemoteKey : true ]
let notificationContent = self.notificationContent!
notificationContent.userInfo = userInfo
notificationContent.badge = 1
notificationContent.title = "Session"
notificationContent.body = "You've got a new message"
handleSuccess(for: notificationContent)
completeSilenty()
}
private func completeSilenty() {
contentHandler!(.init())
SNLog("Complete silenty")
self.contentHandler!(.init())
}
private func handleSuccessForIncomingCall(for content: UNMutableNotificationContent, callMessage: CallMessage) {
private func handleSuccessForIncomingCall(for callMessage: CallMessage, using transaction: YapDatabaseReadWriteTransaction) {
if #available(iOSApplicationExtension 14.5, *) {
if let uuid = callMessage.uuid, let caller = callMessage.sender, let timestamp = callMessage.sentTimestamp {
let payload: JSON = ["uuid": uuid, "caller": caller, "timestamp": timestamp]
CXProvider.reportNewIncomingVoIPPushPayload(payload) { error in
if let error = error {
self.handleSuccess(for: content)
self.handleFailureForVoIP(for: callMessage, using: transaction)
SNLog("Failed to notify main app of call message: \(error)")
} else {
self.completeSilenty()
@ -293,9 +187,31 @@ public final class NotificationServiceExtension : UNNotificationServiceExtension
}
}
} else {
self.handleSuccess(for: content)
self.handleFailureForVoIP(for: callMessage, using: transaction)
}
}
private func handleFailureForVoIP(for callMessage: CallMessage, using transaction: YapDatabaseReadWriteTransaction) {
let notificationContent = UNMutableNotificationContent()
notificationContent.userInfo = [ NotificationServiceExtension.isFromRemoteKey : true ]
notificationContent.title = "Session"
// Badge Number
let newBadgeNumber = CurrentAppContext().appUserDefaults().integer(forKey: "currentBadgeNumber") + 1
notificationContent.badge = NSNumber(value: newBadgeNumber)
CurrentAppContext().appUserDefaults().set(newBadgeNumber, forKey: "currentBadgeNumber")
if let sender = callMessage.sender, let contact = Storage.shared.getContact(with: sender, using: transaction) {
let senderDisplayName = contact.displayName(for: .regular) ?? sender
notificationContent.body = "\(senderDisplayName) is calling..."
} else {
notificationContent.body = "Incoming call..."
}
let identifier = self.request?.identifier ?? UUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: nil)
SNLog("Add remote notification request")
UNUserNotificationCenter.current().add(request)
}
private func handleSuccess(for content: UNMutableNotificationContent) {
contentHandler!(content)
@ -308,30 +224,20 @@ public final class NotificationServiceExtension : UNNotificationServiceExtension
content.userInfo = userInfo
contentHandler!(content)
}
}
private extension String {
func replacingMentions(for threadID: String, using transaction: YapDatabaseReadWriteTransaction) -> String {
MentionsManager.populateUserPublicKeyCacheIfNeeded(for: threadID, in: transaction)
var result = self
let regex = try! NSRegularExpression(pattern: "@[0-9a-fA-F]{66}", options: [])
let knownPublicKeys = MentionsManager.userPublicKeyCache[threadID] ?? []
var mentions: [(range: NSRange, publicKey: String)] = []
var m0 = regex.firstMatch(in: result, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: result.utf16.count))
while let m1 = m0 {
let publicKey = String((result as NSString).substring(with: m1.range).dropFirst()) // Drop the @
var matchEnd = m1.range.location + m1.range.length
if knownPublicKeys.contains(publicKey) {
let displayName = Storage.shared.getContact(with: publicKey)?.displayName(for: .regular)
if let displayName = displayName {
result = (result as NSString).replacingCharacters(in: m1.range, with: "@\(displayName)")
mentions.append((range: NSRange(location: m1.range.location, length: displayName.utf16.count + 1), publicKey: publicKey)) // + 1 to include the @
matchEnd = m1.range.location + displayName.utf16.count
}
}
m0 = regex.firstMatch(in: result, options: .withoutAnchoringBounds, range: NSRange(location: matchEnd, length: result.utf16.count - matchEnd))
// MARK: Poll for open groups
private func pollForOpenGroups() -> [Promise<Void>] {
var promises: [Promise<Void>] = []
let servers = Set(Storage.shared.getAllV2OpenGroups().values.map { $0.server })
servers.forEach { server in
let poller = OpenGroupPollerV2(for: server)
let promise = poller.poll().timeout(seconds: 20, timeoutError: NotificationServiceError.timeout)
promises.append(promise)
}
return result
return promises
}
private enum NotificationServiceError: Error {
case timeout
}
}

View File

@ -0,0 +1,13 @@
// Copyright © 2022 Rangeproof Pty Ltd. All rights reserved.
import Foundation
extension Timer {
@discardableResult
public static func scheduledTimerOnMainThread(withTimeInterval timeInterval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer {
let timer = Timer(timeInterval: timeInterval, repeats: repeats, block: block)
RunLoop.main.add(timer, forMode: .common)
return timer
}
}

View File

@ -2,12 +2,13 @@ import PromiseKit
/// Delay the execution of the promise constructed in `body` by `delay` seconds.
public func withDelay<T>(_ delay: TimeInterval, completionQueue: DispatchQueue, body: @escaping () -> Promise<T>) -> Promise<T> {
#if DEBUG
assert(Thread.current.isMainThread) // Timers don't do well on background queues
#endif
let (promise, seal) = Promise<T>.pending()
Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { _ in
body().done(on: completionQueue) { seal.fulfill($0) }.catch(on: completionQueue) { seal.reject($0) }
Timer.scheduledTimerOnMainThread(withTimeInterval: delay, repeats: false) { _ in
body().done(on: completionQueue) {
seal.fulfill($0)
}.catch(on: completionQueue) {
seal.reject($0)
}
}
return promise
}

View File

@ -0,0 +1,19 @@
// Copyright © 2022 Rangeproof Pty Ltd. All rights reserved.
import PromiseKit
public extension Promise {
func timeout(seconds: TimeInterval, timeoutError: Error) -> Promise<T> {
return Promise<T> { seal in
after(seconds: seconds).done {
seal.reject(timeoutError)
}
self.done { result in
seal.fulfill(result)
}.catch { err in
seal.reject(err)
}
}
}
}

View File

@ -26,6 +26,7 @@ NS_ASSUME_NONNULL_BEGIN
- (NSArray<OWSDatabaseMigration *> *)allMigrations
{
return @[
[SNUnreadMentionMigration new],
[SNMessageRequestsMigration new],
[SNContactsMigration new]
];

View File

@ -0,0 +1,41 @@
// Copyright © 2022 Rangeproof Pty Ltd. All rights reserved.
@objc(SNUnreadMentionMigration)
public class UnreadMentionMigration : OWSDatabaseMigration {
@objc
class func migrationId() -> String {
return "003" // leave "002" for message request migration
}
override public func runUp(completion: @escaping OWSDatabaseMigrationCompletion) {
self.doMigrationAsync(completion: completion)
}
private func doMigrationAsync(completion: @escaping OWSDatabaseMigrationCompletion) {
var threads: [TSThread] = []
Storage.read { transaction in
TSThread.enumerateCollectionObjects(with: transaction) { object, _ in
guard let thread = object as? TSThread, let threadID = thread.uniqueId else { return }
let unreadMessages = transaction.ext(TSUnreadDatabaseViewExtensionName) as! YapDatabaseViewTransaction
unreadMessages.enumerateKeysAndObjects(inGroup: threadID) { collection, key, object, index, stop in
guard let unreadMessage = object as? TSIncomingMessage else { return }
if unreadMessage.wasRead { return }
if unreadMessage.isUserMentioned {
thread.hasUnreadMentionMessage = true
stop.pointee = true
}
}
threads.append(thread)
}
}
Storage.write(with: { transaction in
threads.forEach { thread in
thread.save(with: transaction)
}
self.save(with: transaction) // Intentionally capture self
}, completion: {
completion()
})
}
}

View File

@ -22,18 +22,16 @@ public struct ConversationSortKey: Comparable {
public class ConversationSearchResult<SortKey>: Comparable where SortKey: Comparable {
public let thread: ThreadViewModel
public let messageId: String?
public let messageDate: Date?
public let message: TSMessage?
public let snippet: String?
private let sortKey: SortKey
init(thread: ThreadViewModel, sortKey: SortKey, messageId: String? = nil, messageDate: Date? = nil, snippet: String? = nil) {
init(thread: ThreadViewModel, sortKey: SortKey, message: TSMessage? = nil, snippet: String? = nil) {
self.thread = thread
self.sortKey = sortKey
self.messageId = messageId
self.messageDate = messageDate
self.message = message
self.snippet = snippet
}
@ -47,7 +45,7 @@ public class ConversationSearchResult<SortKey>: Comparable where SortKey: Compar
public static func == (lhs: ConversationSearchResult, rhs: ConversationSearchResult) -> Bool {
return lhs.thread.threadRecord.uniqueId == rhs.thread.threadRecord.uniqueId &&
lhs.messageId == rhs.messageId
lhs.message?.uniqueId == rhs.message?.uniqueId
}
}
@ -270,8 +268,7 @@ public class FullTextSearcher: NSObject {
let sortKey = message.sortId
let searchResult = ConversationSearchResult(thread: threadViewModel,
sortKey: sortKey,
messageId: message.uniqueId,
messageDate: NSDate.ows_date(withMillisecondsSince1970: message.timestamp),
message: message,
snippet: snippet)
messages.append(searchResult)

View File

@ -91,6 +91,7 @@ NS_ASSUME_NONNULL_BEGIN
NSLog(@"Found an already read message in the * unread * messages list.");
return;
}
// We have to filter those unread messages for groups that only notifiy for mentions
if ([object isKindOfClass:TSIncomingMessage.class] && isGroupThread) {
TSIncomingMessage *incomingMessage = (TSIncomingMessage *)object;
if (((TSGroupThread *)thread).isOnlyNotifyingForMentions && !incomingMessage.isUserMentioned) {
@ -103,13 +104,6 @@ NS_ASSUME_NONNULL_BEGIN
}];
return count;
__block NSUInteger numberOfItems;
[self.dbConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
numberOfItems = [[transaction ext:TSUnreadDatabaseViewExtensionName] numberOfItemsInAllGroups];
}];
return numberOfItems;
}
- (NSUInteger)unreadMessageRequestCount {
@ -124,20 +118,9 @@ NS_ASSUME_NONNULL_BEGIN
// Only increase the count for message requests
if (![thread isMessageRequestUsingTransaction:transaction]) { continue; }
[unreadMessages enumerateKeysAndObjectsInGroup:groupID
usingBlock:^(NSString *collection, NSString *key, id object, NSUInteger index, BOOL *stop) {
if (![object conformsToProtocol:@protocol(OWSReadTracking)]) {
return;
}
id<OWSReadTracking> unread = (id<OWSReadTracking>)object;
if (unread.read) {
NSLog(@"Found an already read message in the * unread * messages list.");
return;
}
if ([unreadMessages numberOfItemsInGroup:groupID] > 0) {
count += 1;
*stop = YES;
}];
}
}
}];

View File

@ -91,12 +91,15 @@ extension MessageSender {
let errors = results.compactMap { result -> Swift.Error? in
if case .rejected(let error) = result { return error } else { return nil }
}
if let error = errors.first { seal.reject(error) }
Storage.write{ transaction in
sendNonDurably(message, in: thread, using: transaction).done {
seal.fulfill(())
}.catch { error in
seal.reject(error)
if let error = errors.first {
seal.reject(error)
} else {
Storage.write{ transaction in
sendNonDurably(message, in: thread, using: transaction).done {
seal.fulfill(())
}.catch { error in
seal.reject(error)
}
}
}
return promise

View File

@ -52,7 +52,7 @@ public class ThreadViewModel: NSObject {
self.unreadCount = thread.unreadMessageCount(transaction: transaction)
self.hasUnreadMessages = unreadCount > 0
self.hasUnreadMentions = thread.hasUnreadMentionMessage(transaction: transaction)
self.hasUnreadMentions = thread.hasUnreadMentionMessage
}
@objc