[Death to TSAccountManager, long live TSAccountManager][9] Migrate usages of old TSAccountManager to new

This commit is contained in:
Harry 2023-10-05 08:56:08 -07:00 committed by GitHub
parent 56d2d58cbb
commit aa0e250cb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
244 changed files with 1921 additions and 1650 deletions

View File

@ -791,13 +791,15 @@
662C44092A1567E4001F83E2 /* svr2.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662C44082A1567E4001F83E2 /* svr2.pb.swift */; };
662C440B2A156DF7001F83E2 /* SecureValueRecovery2Impl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662C440A2A156DF7001F83E2 /* SecureValueRecovery2Impl.swift */; };
662C440F2A17DB8A001F83E2 /* OrchestratingSVRImpl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662C440E2A17DB8A001F83E2 /* OrchestratingSVRImpl.swift */; };
662C44132A1835F4001F83E2 /* SVRLocalStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662C44122A1835F4001F83E2 /* SVRLocalStorage.swift */; };
662C44172A1D21D7001F83E2 /* SecureValueRecovery2Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662C44152A1D2101001F83E2 /* SecureValueRecovery2Tests.swift */; };
663BA3182A4B8595004B9A43 /* SpoilerRenderState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 663BA3172A4B8595004B9A43 /* SpoilerRenderState.swift */; };
663BA31C2A4C9997004B9A43 /* safety-numbers.json in Resources */ = {isa = PBXBuildFile; fileRef = 663BA31B2A4C9997004B9A43 /* safety-numbers.json */; };
663BA3202A4CF96B004B9A43 /* MessageBodyDisplayConfigurations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 663BA31F2A4CF96B004B9A43 /* MessageBodyDisplayConfigurations.swift */; };
663D6A7C292319BC00CABC49 /* ConversationPickerFailedRecipientsSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 663D6A7B292319BC00CABC49 /* ConversationPickerFailedRecipientsSheet.swift */; };
6640639E294D20A900997E0B /* OutgoingCallEventSyncMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6640639D294D20A900997E0B /* OutgoingCallEventSyncMessage.swift */; };
6640DD5E2ACCCDC000CE9A8C /* RegistrationStateChangeManagerObjcTestUtil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6640DD5D2ACCCDC000CE9A8C /* RegistrationStateChangeManagerObjcTestUtil.swift */; };
6640DD602ACDBEC500CE9A8C /* IncomingPniChangeNumberProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6640DD5F2ACDBEC500CE9A8C /* IncomingPniChangeNumberProcessor.swift */; };
6640DD632ACDD5DE00CE9A8C /* SVRLocalStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6640DD622ACDD5DE00CE9A8C /* SVRLocalStorage.swift */; };
664160D029A6D60A00F5BA85 /* ChatServiceAuth.swift in Sources */ = {isa = PBXBuildFile; fileRef = 664160CF29A6D60A00F5BA85 /* ChatServiceAuth.swift */; };
6642A8702A8D7B4B00E591C2 /* OWSPaymentActivationRequestFinishedMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = 6642A86F2A8D7B3400E591C2 /* OWSPaymentActivationRequestFinishedMessage.h */; settings = {ATTRIBUTES = (Public, ); }; };
6642A8722A8D7C5700E591C2 /* OWSPaymentActivationRequestFinishedMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = 6642A8712A8D7C5700E591C2 /* OWSPaymentActivationRequestFinishedMessage.m */; };
@ -820,6 +822,7 @@
6646573F2AC3B9190099DE1C /* MockRegistrationStateChangeManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6646573E2AC3B9190099DE1C /* MockRegistrationStateChangeManager.swift */; };
664657412AC4FB720099DE1C /* NotificationsProtocolSwift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 664657402AC4FB720099DE1C /* NotificationsProtocolSwift.swift */; };
664657452ACB34AA0099DE1C /* TSAccountManagerImpl+Shims.swift in Sources */ = {isa = PBXBuildFile; fileRef = 664657442ACB34AA0099DE1C /* TSAccountManagerImpl+Shims.swift */; };
664657472ACB66630099DE1C /* TSAccountManagerObjcBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 664657462ACB66630099DE1C /* TSAccountManagerObjcBridge.swift */; };
6652DF672A04494200EF90E7 /* StyleOnlyMessageBody.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6652DF662A04494200EF90E7 /* StyleOnlyMessageBody.swift */; };
6652DF6A2A045EF000EF90E7 /* StyleOnlyMessageBodyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6652DF682A045ED600EF90E7 /* StyleOnlyMessageBodyTests.swift */; };
6652DF6C2A04828800EF90E7 /* StoryMessageAttachment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6652DF6B2A04828800EF90E7 /* StoryMessageAttachment.swift */; };
@ -3351,13 +3354,15 @@
662C44082A1567E4001F83E2 /* svr2.pb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = svr2.pb.swift; sourceTree = "<group>"; };
662C440A2A156DF7001F83E2 /* SecureValueRecovery2Impl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureValueRecovery2Impl.swift; sourceTree = "<group>"; };
662C440E2A17DB8A001F83E2 /* OrchestratingSVRImpl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrchestratingSVRImpl.swift; sourceTree = "<group>"; };
662C44122A1835F4001F83E2 /* SVRLocalStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SVRLocalStorage.swift; sourceTree = "<group>"; };
662C44152A1D2101001F83E2 /* SecureValueRecovery2Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureValueRecovery2Tests.swift; sourceTree = "<group>"; };
663BA3172A4B8595004B9A43 /* SpoilerRenderState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpoilerRenderState.swift; sourceTree = "<group>"; };
663BA31B2A4C9997004B9A43 /* safety-numbers.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = "safety-numbers.json"; sourceTree = "<group>"; };
663BA31F2A4CF96B004B9A43 /* MessageBodyDisplayConfigurations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageBodyDisplayConfigurations.swift; sourceTree = "<group>"; };
663D6A7B292319BC00CABC49 /* ConversationPickerFailedRecipientsSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationPickerFailedRecipientsSheet.swift; sourceTree = "<group>"; };
6640639D294D20A900997E0B /* OutgoingCallEventSyncMessage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OutgoingCallEventSyncMessage.swift; sourceTree = "<group>"; };
6640DD5D2ACCCDC000CE9A8C /* RegistrationStateChangeManagerObjcTestUtil.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegistrationStateChangeManagerObjcTestUtil.swift; sourceTree = "<group>"; };
6640DD5F2ACDBEC500CE9A8C /* IncomingPniChangeNumberProcessor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IncomingPniChangeNumberProcessor.swift; sourceTree = "<group>"; };
6640DD622ACDD5DE00CE9A8C /* SVRLocalStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SVRLocalStorage.swift; sourceTree = "<group>"; };
664160CF29A6D60A00F5BA85 /* ChatServiceAuth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatServiceAuth.swift; sourceTree = "<group>"; };
6642A86F2A8D7B3400E591C2 /* OWSPaymentActivationRequestFinishedMessage.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OWSPaymentActivationRequestFinishedMessage.h; sourceTree = "<group>"; };
6642A8712A8D7C5700E591C2 /* OWSPaymentActivationRequestFinishedMessage.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = OWSPaymentActivationRequestFinishedMessage.m; sourceTree = "<group>"; };
@ -3380,6 +3385,7 @@
6646573E2AC3B9190099DE1C /* MockRegistrationStateChangeManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockRegistrationStateChangeManager.swift; sourceTree = "<group>"; };
664657402AC4FB720099DE1C /* NotificationsProtocolSwift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsProtocolSwift.swift; sourceTree = "<group>"; };
664657442ACB34AA0099DE1C /* TSAccountManagerImpl+Shims.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TSAccountManagerImpl+Shims.swift"; sourceTree = "<group>"; };
664657462ACB66630099DE1C /* TSAccountManagerObjcBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TSAccountManagerObjcBridge.swift; sourceTree = "<group>"; };
6652DF662A04494200EF90E7 /* StyleOnlyMessageBody.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StyleOnlyMessageBody.swift; sourceTree = "<group>"; };
6652DF682A045ED600EF90E7 /* StyleOnlyMessageBodyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StyleOnlyMessageBodyTests.swift; sourceTree = "<group>"; };
6652DF6B2A04828800EF90E7 /* StoryMessageAttachment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoryMessageAttachment.swift; sourceTree = "<group>"; };
@ -6690,6 +6696,7 @@
661170C02ABA459D00A1B16D /* RegistrationIdGenerator.swift */,
664657442ACB34AA0099DE1C /* TSAccountManagerImpl+Shims.swift */,
661170C72ABA4F3A00A1B16D /* TSAccountManagerImpl.swift */,
664657462ACB66630099DE1C /* TSAccountManagerObjcBridge.swift */,
661170C32ABA4D9900A1B16D /* TSAccountManagerProtocol.swift */,
6615553E2ABA5A7500AA302B /* TSRegistrationState.swift */,
);
@ -6756,6 +6763,14 @@
path = SVR2;
sourceTree = "<group>";
};
6640DD612ACDD5CD00CE9A8C /* LocalStorage */ = {
isa = PBXGroup;
children = (
6640DD622ACDD5DE00CE9A8C /* SVRLocalStorage.swift */,
);
path = LocalStorage;
sourceTree = "<group>";
};
6645F30629BF8D1000B58EBD /* AccountAttributes */ = {
isa = PBXGroup;
children = (
@ -6785,6 +6800,7 @@
6646573E2AC3B9190099DE1C /* MockRegistrationStateChangeManager.swift */,
6646573A2AC388C70099DE1C /* RegistrationStateChangeManager.swift */,
6646573C2AC3894D0099DE1C /* RegistrationStateChangeManagerImpl.swift */,
6640DD5D2ACCCDC000CE9A8C /* RegistrationStateChangeManagerObjcTestUtil.swift */,
);
path = RegistrationStateChangeManager;
sourceTree = "<group>";
@ -6839,6 +6855,7 @@
isa = PBXGroup;
children = (
66C2B1342A0DA16F008DDE72 /* KeyBackupService */,
6640DD612ACDD5CD00CE9A8C /* LocalStorage */,
66C2B13E2A0E9147008DDE72 /* Orchestrating */,
66C2B13B2A0E9108008DDE72 /* SVR2 */,
66138FB5298326C7002E0CFE /* SecureValueRecovery.swift */,
@ -6979,7 +6996,6 @@
66C2B13C2A0E9116008DDE72 /* SVR2AuthCredential.swift */,
669947B92A20129000E4DC0C /* SVR2Shims.swift */,
66C2B1552A1400E8008DDE72 /* SVR2WebsocketConfigurator.swift */,
662C44122A1835F4001F83E2 /* SVRLocalStorage.swift */,
);
path = SVR2;
sourceTree = "<group>";
@ -8852,6 +8868,7 @@
F9C5C99D289453B100548EEE /* EarlyMessageManager.swift */,
F9C5C999289453B100548EEE /* FailedAttachmentDownloadsJob.swift */,
F9C5C92B289453B100548EEE /* FailedMessagesJob.swift */,
6640DD5F2ACDBEC500CE9A8C /* IncomingPniChangeNumberProcessor.swift */,
F9C5C97B289453B100548EEE /* IncompleteCallsJob.swift */,
F9C5C97F289453B100548EEE /* MessageFetcherJob.swift */,
F9C5C95E289453B100548EEE /* MessagePipelineSupervisor.swift */,
@ -12413,6 +12430,7 @@
F9C5CDA5289453B400548EEE /* IncomingGroupsV2MessageJob+SDS.swift in Sources */,
F9C5CDA0289453B400548EEE /* IncomingGroupsV2MessageJob.m in Sources */,
D9AE0AD1291870220063488B /* IncomingGroupSyncJobRecord.swift in Sources */,
6640DD602ACDBEC500CE9A8C /* IncomingPniChangeNumberProcessor.swift in Sources */,
F9C5CC69289453B300548EEE /* IncompleteCallsJob.swift in Sources */,
D9B95A9B29E8923B00D7CB95 /* InMemoryDatabase.swift in Sources */,
6612780C2996BC2900A1D5A1 /* InMemoryKeyValueStore.swift in Sources */,
@ -12726,6 +12744,7 @@
6691E7F22996E9BC0032A68A /* RegistrationSessionManagerMock.swift in Sources */,
6646573B2AC388C70099DE1C /* RegistrationStateChangeManager.swift in Sources */,
6646573D2AC3894D0099DE1C /* RegistrationStateChangeManagerImpl.swift in Sources */,
6640DD5E2ACCCDC000CE9A8C /* RegistrationStateChangeManagerObjcTestUtil.swift in Sources */,
F9C5CCB0289453B300548EEE /* RemoteAttestation.swift in Sources */,
F9C5CCB1289453B300548EEE /* RemoteAttestationQuote.m in Sources */,
F9C5CE17289453B400548EEE /* RemoteConfigManager.swift in Sources */,
@ -12851,7 +12870,7 @@
6673FF702978C40300F96CFD /* SVRAuthCredentialStorage.swift in Sources */,
6673FF722979B33800F96CFD /* SVRAuthCredentialStorageImpl.swift in Sources */,
C18E3C742AA0F8CE003D1CF1 /* SVRAuthCredentialStorageMock.swift in Sources */,
662C44132A1835F4001F83E2 /* SVRLocalStorage.swift in Sources */,
6640DD632ACDD5DE00CE9A8C /* SVRLocalStorage.swift in Sources */,
66C2B1362A0DB02E008DDE72 /* SVRUtil.swift in Sources */,
F9C5CE2F289453B400548EEE /* SwiftSingletons.swift in Sources */,
F9C5CE04289453B400548EEE /* SyncManagerProtocol.swift in Sources */,
@ -12882,6 +12901,7 @@
F9C5CCAB289453B300548EEE /* TSAccountManager.swift in Sources */,
664657452ACB34AA0099DE1C /* TSAccountManagerImpl+Shims.swift in Sources */,
661170C82ABA4F3A00A1B16D /* TSAccountManagerImpl.swift in Sources */,
664657472ACB66630099DE1C /* TSAccountManagerObjcBridge.swift in Sources */,
661170C42ABA4D9900A1B16D /* TSAccountManagerProtocol.swift in Sources */,
D9C2D77C299D4F2600D79715 /* TSAccountState.swift in Sources */,
F9C5CC77289453B300548EEE /* TSAttachment+SDS.swift in Sources */,

View File

@ -310,7 +310,8 @@ typedef void (^OrphanDataBlock)(OWSOrphanData *);
NSString *grdbHotswapDirectoryPath =
[GRDBDatabaseStorageAdapter databaseDirUrlWithDirectoryMode:DirectoryModeHotswapLegacy].path;
NSString *grdbTransferDirectoryPath = nil;
if (GRDBDatabaseStorageAdapter.hasAssignedTransferDirectory && TSAccountManager.shared.isTransferInProgress) {
if (GRDBDatabaseStorageAdapter.hasAssignedTransferDirectory &&
[TSAccountManagerObjcBridge isTransferInProgressWithMaybeTransaction]) {
grdbTransferDirectoryPath =
[GRDBDatabaseStorageAdapter databaseDirUrlWithDirectoryMode:DirectoryModeTransfer].path;
}

View File

@ -26,7 +26,7 @@ extension OWSOrphanDataCleaner {
let currentAppVersion = AppVersionImpl.shared.currentAppReleaseVersion
return databaseStorage.read { transaction -> Bool in
guard TSAccountManager.shared.isRegistered(transaction: transaction) else {
guard DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isRegistered else {
Logger.info("Orphan data audit skipped because we're not registered")
return false
}

View File

@ -23,7 +23,6 @@ extension RegistrationCoordinatorImpl {
public typealias PushRegistrationManager = _RegistrationCoordinator_PushRegistrationManagerShim
public typealias ReceiptManager = _RegistrationCoordinator_ReceiptManagerShim
public typealias RemoteConfig = _RegistrationCoordinator_RemoteConfigShim
public typealias TSAccountManager = _RegistrationCoordinator_TSAccountManagerShim
public typealias UDManager = _RegistrationCoordinator_UDManagerShim
}
public enum Wrappers {
@ -38,7 +37,6 @@ extension RegistrationCoordinatorImpl {
public typealias PushRegistrationManager = _RegistrationCoordinator_PushRegistrationManagerWrapper
public typealias ReceiptManager = _RegistrationCoordinator_ReceiptManagerWrapper
public typealias RemoteConfig = _RegistrationCoordinator_RemoteConfigWrapper
public typealias TSAccountManager = _RegistrationCoordinator_TSAccountManagerWrapper
public typealias UDManager = _RegistrationCoordinator_UDManagerWrapper
}
}
@ -410,140 +408,6 @@ public class _RegistrationCoordinator_RemoteConfigWrapper: _RegistrationCoordina
}
}
// MARK: - TSAccountManager
public protocol _RegistrationCoordinator_TSAccountManagerShim {
func isManualMessageFetchEnabled(_ transaction: DBReadTransaction) -> Bool
func setIsManualMessageFetchEnabled(_ isEnabled: Bool, _ transaction: DBWriteTransaction)
func getOrGenerateRegistrationId(_ transaction: DBWriteTransaction) -> UInt32
func getOrGeneratePniRegistrationId(_ transaction: DBWriteTransaction) -> UInt32
func hasDefinedIsDiscoverableByPhoneNumber(_ transaction: DBReadTransaction) -> Bool
func isDiscoverableByPhoneNumber(_ transaction: DBReadTransaction) -> Bool
func setIsDiscoverableByPhoneNumber(
_ isDiscoverable: Bool,
updateStorageService: Bool,
authedAccount: AuthedAccount,
_ transaction: DBWriteTransaction
)
func resetForReregistration(
e164: E164,
aci: Aci,
_ tx: DBWriteTransaction
)
func didRegister(
e164: E164,
aci: Aci,
pni: Pni,
authToken: String,
_ tx: DBWriteTransaction
)
func updateLocalPhoneNumber(
e164: E164,
aci: Aci,
pni: Pni,
_ tx: DBWriteTransaction
)
func setIsOnboarded(_ tx: DBWriteTransaction)
}
public class _RegistrationCoordinator_TSAccountManagerWrapper: _RegistrationCoordinator_TSAccountManagerShim {
private let manager: TSAccountManager
public init(_ manager: TSAccountManager) { self.manager = manager }
public func hasDefinedIsDiscoverableByPhoneNumber(_ transaction: DBReadTransaction) -> Bool {
return manager.hasDefinedIsDiscoverableByPhoneNumber(with: SDSDB.shimOnlyBridge(transaction))
}
public func setIsManualMessageFetchEnabled(_ isEnabled: Bool, _ transaction: DBWriteTransaction) {
manager.setIsManualMessageFetchEnabled(isEnabled, transaction: SDSDB.shimOnlyBridge(transaction))
}
public func isManualMessageFetchEnabled(_ transaction: DBReadTransaction) -> Bool {
return manager.isManualMessageFetchEnabled(SDSDB.shimOnlyBridge(transaction))
}
public func getOrGenerateRegistrationId(_ transaction: DBWriteTransaction) -> UInt32 {
return manager.getOrGenerateRegistrationId(transaction: SDSDB.shimOnlyBridge(transaction))
}
public func getOrGeneratePniRegistrationId(_ transaction: DBWriteTransaction) -> UInt32 {
return manager.getOrGeneratePniRegistrationId(transaction: SDSDB.shimOnlyBridge(transaction))
}
public func isDiscoverableByPhoneNumber(_ transaction: DBReadTransaction) -> Bool {
return manager.isDiscoverableByPhoneNumber(with: SDSDB.shimOnlyBridge(transaction))
}
public func setIsDiscoverableByPhoneNumber(
_ isDiscoverable: Bool,
updateStorageService: Bool,
authedAccount: AuthedAccount,
_ transaction: DBWriteTransaction
) {
manager.setIsDiscoverableByPhoneNumber(
isDiscoverable,
updateStorageService: updateStorageService,
authedAccount: authedAccount,
transaction: SDSDB.shimOnlyBridge(transaction)
)
}
public func resetForReregistration(
e164: E164,
aci: Aci,
_ tx: DBWriteTransaction
) {
manager.resetForReregistration(
localPhoneNumber: e164,
localAci: aci,
wasPrimaryDevice: true,
transaction: SDSDB.shimOnlyBridge(tx)
)
}
public func didRegister(
e164: E164,
aci: Aci,
pni: Pni,
authToken: String,
_ tx: DBWriteTransaction
) {
manager.didRegisterPrimary(
withE164: E164ObjC(e164),
aci: AciObjC(aci),
pni: PniObjC(pni),
authToken: authToken,
transaction: SDSDB.shimOnlyBridge(tx)
)
}
public func updateLocalPhoneNumber(
e164: E164,
aci: Aci,
pni: Pni,
_ tx: DBWriteTransaction
) {
manager.updateLocalPhoneNumber(
E164ObjC(e164),
aci: AciObjC(aci),
pni: PniObjC(pni),
transaction: SDSDB.shimOnlyBridge(tx)
)
}
public func setIsOnboarded(_ tx: DBWriteTransaction) {
manager.setIsOnboarded(true, transaction: SDSDB.shimOnlyBridge(tx))
}
}
// MARK: - UDManager
public protocol _RegistrationCoordinator_UDManagerShim {

View File

@ -19,10 +19,12 @@ public struct RegistrationCoordinatorDependencies {
public let messagePipelineSupervisor: RegistrationCoordinatorImpl.Shims.MessagePipelineSupervisor
public let messageProcessor: RegistrationCoordinatorImpl.Shims.MessageProcessor
public let ows2FAManager: RegistrationCoordinatorImpl.Shims.OWS2FAManager
public let phoneNumberDiscoverabilityManager: PhoneNumberDiscoverabilityManager
public let preKeyManager: PreKeyManager
public let profileManager: RegistrationCoordinatorImpl.Shims.ProfileManager
public let pushRegistrationManager: RegistrationCoordinatorImpl.Shims.PushRegistrationManager
public let receiptManager: RegistrationCoordinatorImpl.Shims.ReceiptManager
public let registrationStateChangeManager: RegistrationStateChangeManager
public let remoteConfig: RegistrationCoordinatorImpl.Shims.RemoteConfig
public let schedulers: Schedulers
public let sessionManager: RegistrationSessionManager
@ -30,7 +32,7 @@ public struct RegistrationCoordinatorDependencies {
public let storageServiceManager: StorageServiceManager
public let svr: SecureValueRecovery
public let svrAuthCredentialStore: SVRAuthCredentialStorage
public let tsAccountManager: RegistrationCoordinatorImpl.Shims.TSAccountManager
public let tsAccountManager: TSAccountManagerProtocol
public let udManager: RegistrationCoordinatorImpl.Shims.UDManager
public static func from(_ object: NSObject) -> RegistrationCoordinatorDependencies {
@ -47,10 +49,12 @@ public struct RegistrationCoordinatorDependencies {
messagePipelineSupervisor: RegistrationCoordinatorImpl.Wrappers.MessagePipelineSupervisor(object.messagePipelineSupervisor),
messageProcessor: RegistrationCoordinatorImpl.Wrappers.MessageProcessor(object.messageProcessor),
ows2FAManager: RegistrationCoordinatorImpl.Wrappers.OWS2FAManager(object.ows2FAManager),
phoneNumberDiscoverabilityManager: DependenciesBridge.shared.phoneNumberDiscoverabilityManager,
preKeyManager: DependenciesBridge.shared.preKeyManager,
profileManager: RegistrationCoordinatorImpl.Wrappers.ProfileManager(object.profileManager),
pushRegistrationManager: RegistrationCoordinatorImpl.Wrappers.PushRegistrationManager(object.pushRegistrationManager),
receiptManager: RegistrationCoordinatorImpl.Wrappers.ReceiptManager(object.receiptManager),
registrationStateChangeManager: DependenciesBridge.shared.registrationStateChangeManager,
remoteConfig: RegistrationCoordinatorImpl.Wrappers.RemoteConfig(object.remoteConfigManager),
schedulers: DependenciesBridge.shared.schedulers,
sessionManager: DependenciesBridge.shared.registrationSessionManager,
@ -58,7 +62,7 @@ public struct RegistrationCoordinatorDependencies {
storageServiceManager: object.storageServiceManager,
svr: DependenciesBridge.shared.svr,
svrAuthCredentialStore: DependenciesBridge.shared.svrCredentialStorage,
tsAccountManager: RegistrationCoordinatorImpl.Wrappers.TSAccountManager(object.tsAccountManager),
tsAccountManager: DependenciesBridge.shared.tsAccountManager,
udManager: RegistrationCoordinatorImpl.Wrappers.UDManager(object.udManager)
)
}

View File

@ -874,9 +874,9 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
}
loadSVRAuthCredentialCandidates(tx)
inMemoryState.isManualMessageFetchEnabled = deps.tsAccountManager.isManualMessageFetchEnabled(tx)
inMemoryState.registrationId = deps.tsAccountManager.getOrGenerateRegistrationId(tx)
inMemoryState.pniRegistrationId = deps.tsAccountManager.getOrGeneratePniRegistrationId(tx)
inMemoryState.isManualMessageFetchEnabled = deps.tsAccountManager.isManualMessageFetchEnabled(tx: tx)
inMemoryState.registrationId = deps.tsAccountManager.getOrGenerateAciRegistrationId(tx: tx)
inMemoryState.pniRegistrationId = deps.tsAccountManager.getOrGeneratePniRegistrationId(tx: tx)
inMemoryState.allowUnrestrictedUD = deps.udManager.shouldAllowUnrestrictedAccessLocal(transaction: tx)
@ -932,15 +932,14 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
deps.experienceManager.clearIntroducingPinsExperience(tx)
}
deps.tsAccountManager.didRegister(
deps.registrationStateChangeManager.didRegisterPrimary(
e164: accountIdentity.e164,
aci: accountIdentity.aci,
pni: accountIdentity.pni,
authToken: accountIdentity.authPassword,
tx
tx: tx
)
deps.tsAccountManager.setIsOnboarded(tx)
deps.tsAccountManager.setIsManualMessageFetchEnabled(inMemoryState.isManualMessageFetchEnabled, tx)
deps.tsAccountManager.setIsManualMessageFetchEnabled(inMemoryState.isManualMessageFetchEnabled, tx: tx)
}
func setupContactsAndFinish() -> Guarantee<RegistrationStep> {
@ -2986,7 +2985,7 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
return .value(.showErrorSheet(.genericError))
}
strongSelf.db.write { tx in
strongSelf.deps.tsAccountManager.setIsManualMessageFetchEnabled(true, tx)
strongSelf.deps.tsAccountManager.setIsManualMessageFetchEnabled(true, tx: tx)
strongSelf.updatePersistedState(tx) {
// Say that we synced push tokens so that we skip this step hereafter.
$0.legacy_didSyncPushTokens = true
@ -3305,8 +3304,10 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
inMemoryState.udAccessKey = udAccessKey
inMemoryState.hasProfileName = deps.profileManager.hasProfileName
db.read { tx in
inMemoryState.hasDefinedIsDiscoverableByPhoneNumber = deps.tsAccountManager.hasDefinedIsDiscoverableByPhoneNumber(tx)
inMemoryState.isDiscoverableByPhoneNumber = deps.tsAccountManager.isDiscoverableByPhoneNumber(tx)
inMemoryState.hasDefinedIsDiscoverableByPhoneNumber =
deps.phoneNumberDiscoverabilityManager.hasDefinedIsDiscoverableByPhoneNumber(tx: tx)
inMemoryState.isDiscoverableByPhoneNumber =
deps.phoneNumberDiscoverabilityManager.isDiscoverableByPhoneNumber(tx: tx)
}
}
@ -3332,11 +3333,11 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
db.write { tx in
// We will update storage service at the end of registration.
deps.tsAccountManager.setIsDiscoverableByPhoneNumber(
deps.phoneNumberDiscoverabilityManager.setIsDiscoverableByPhoneNumber(
true,
updateStorageService: false,
authedAccount: accountIdentity.authedAccount,
tx
tx: tx
)
}
}
@ -3385,11 +3386,11 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
// We do these here, and not in export state, so that we don't risk
// syncing out-of-date state to storage service.
strongSelf.deps.tsAccountManager.updateLocalPhoneNumber(
e164: accountIdentity.e164,
strongSelf.deps.registrationStateChangeManager.didUpdateLocalPhoneNumber(
accountIdentity.e164,
aci: accountIdentity.aci,
pni: accountIdentity.pni,
tx
tx: tx
)
// Make sure we update our local account.
strongSelf.deps.storageServiceManager.recordPendingLocalAccountUpdates()
@ -3440,10 +3441,12 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
case .reRegistering(let state):
if persistedState.hasResetForReRegistration.negated {
db.write { tx in
deps.tsAccountManager.resetForReregistration(
e164: state.e164,
aci: state.aci,
tx
let isPrimaryDevice = deps.tsAccountManager.registrationState(tx: tx).isPrimaryDevice ?? true
deps.registrationStateChangeManager.resetForReregistration(
localPhoneNumber: state.e164,
localAci: state.aci,
wasPrimaryDevice: isPrimaryDevice,
tx: tx
)
updatePersistedState(tx) {
$0.hasResetForReRegistration = true
@ -3483,7 +3486,7 @@ public class RegistrationCoordinatorImpl: RegistrationCoordinator {
self.inMemoryState.isManualMessageFetchEnabled = isManualMessageFetchEnabled
if isManualMessageFetchEnabled {
self.db.write { tx in
self.deps.tsAccountManager.setIsManualMessageFetchEnabled(true, tx)
self.deps.tsAccountManager.setIsManualMessageFetchEnabled(true, tx: tx)
}
}
let accountAttributes = self.makeAccountAttributes(

View File

@ -18,11 +18,11 @@ private enum OpenableUrl {
class UrlOpener {
private let databaseStorage: SDSDatabaseStorage
private let tsAccountManager: TSAccountManager
private let tsAccountManager: TSAccountManagerProtocol
init(
databaseStorage: SDSDatabaseStorage,
tsAccountManager: TSAccountManager
tsAccountManager: TSAccountManagerProtocol
) {
self.databaseStorage = databaseStorage
self.tsAccountManager = tsAccountManager
@ -103,7 +103,7 @@ class UrlOpener {
// MARK: - Opening URLs
func openUrl(_ parsedUrl: ParsedUrl, in window: UIWindow) {
guard tsAccountManager.isRegistered else {
guard tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return owsFailDebug("Ignoring URL; not registered.")
}
guard let rootViewController = window.rootViewController else {
@ -148,7 +148,7 @@ class UrlOpener {
rootViewController.present(ProxyLinkSheetViewController(url: url)!, animated: true)
case .linkDevice(let deviceProvisioningURL):
guard tsAccountManager.isPrimaryDevice else {
guard tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice else {
return owsFailDebug("Ignoring URL; not primary device.")
}
let linkedDevicesViewController = LinkedDevicesTableViewController()

View File

@ -78,11 +78,13 @@ extension AppDelegate {
Logger.warn("handleActivation.")
databaseStorage.read { tx in
let tsRegistrationState: TSRegistrationState = DependenciesBridge.shared.db.read { tx in
// Always check prekeys after app launches, and sometimes check on app activation.
if TSAccountManager.shared.isRegisteredAndReady(transaction: tx) {
DependenciesBridge.shared.preKeyManager.checkPreKeysIfNecessary(tx: tx.asV2Read)
let registrationState = DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx)
if registrationState.isRegistered {
DependenciesBridge.shared.preKeyManager.checkPreKeysIfNecessary(tx: tx)
}
return registrationState
}
if !Self.hasActivated {
@ -90,12 +92,11 @@ extension AppDelegate {
RTCInitializeSSL()
if tsAccountManager.isRegistered {
if tsRegistrationState.isRegistered {
// At this point, potentially lengthy DB locking migrations could be running.
// Avoid blocking app launch by putting all further possible DB access in async block
DispatchQueue.global(qos: .default).async {
let localAddress = self.tsAccountManager.localAddress
Logger.info("running post launch block for registered user: \(String(describing: localAddress))")
Logger.info("running post launch block for registered user.")
// Clean up any messages that expired since last launch immediately
// and continue cleaning in the background.
@ -110,7 +111,7 @@ extension AppDelegate {
}
// Every time we become active...
if tsAccountManager.isRegistered {
if tsRegistrationState.isRegistered {
// At this point, potentially lengthy DB locking migrations could be running.
// Avoid blocking app launch by putting all further possible DB access in async block
DispatchQueue.main.async {

View File

@ -24,7 +24,6 @@
#import <SignalServiceKit/OWSReceiptManager.h>
#import <SignalServiceKit/SignalServiceKit-Swift.h>
#import <SignalServiceKit/StickerInfo.h>
#import <SignalServiceKit/TSAccountManager.h>
#import <UserNotifications/UserNotifications.h>
#import <WebRTC/WebRTC.h>
@ -196,7 +195,7 @@ static void uncaughtExceptionHandler(NSException *exception)
}
AppReadinessRunNowOrWhenUIDidBecomeReadySync(^{
if (![self.tsAccountManager isRegisteredAndReady]) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
ActionSheetController *controller = [[ActionSheetController alloc]
initWithTitle:NSLocalizedString(@"REGISTER_CONTACTS_WELCOME", nil)
message:NSLocalizedString(@"REGISTRATION_RESTRICTED_MESSAGE", nil)];
@ -261,7 +260,7 @@ static void uncaughtExceptionHandler(NSException *exception)
}
AppReadinessRunNowOrWhenAppDidBecomeReadySync(^{
if (![self.tsAccountManager isRegisteredAndReady]) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}
@ -292,7 +291,7 @@ static void uncaughtExceptionHandler(NSException *exception)
}
AppReadinessRunNowOrWhenAppDidBecomeReadySync(^{
if (![self.tsAccountManager isRegisteredAndReady]) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}
@ -349,7 +348,7 @@ static void uncaughtExceptionHandler(NSException *exception)
}
AppReadinessRunNowOrWhenAppDidBecomeReadySync(^{
if (![self.tsAccountManager isRegisteredAndReady]) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}
@ -390,7 +389,7 @@ static void uncaughtExceptionHandler(NSException *exception)
BOOL isVideo = startCallIntent.callCapability == INCallCapabilityVideoCall;
AppReadinessRunNowOrWhenAppDidBecomeReadySync(^{
if (![self.tsAccountManager isRegisteredAndReady]) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}

View File

@ -245,6 +245,10 @@ extension AppDelegate {
Logger.info("")
AssertIsOnMainThread()
// First thing; clean up any transfer state in case we are launching after a transfer.
// This needs to happen before we check any registration state.
DependenciesBridge.shared.registrationStateChangeManager.cleanUpTransferStateOnAppLaunchIfNeeded()
let regLoader = RegistrationCoordinatorLoaderImpl(dependencies: .from(self))
// Before we mark ready, block message processing on any pending change numbers.
@ -256,13 +260,6 @@ extension AppDelegate {
messagePipelineSupervisor.suspendMessageProcessingWithoutHandle(for: .pendingChangeNumber)
}
// If user is missing profile name, redirect to onboarding flow.
if !profileManager.hasProfileName {
databaseStorage.write { transaction in
tsAccountManager.setIsOnboarded(false, transaction: transaction)
}
}
let launchInterface = buildLaunchInterface(regLoader: regLoader)
let hasInProgressRegistration: Bool
@ -293,7 +290,10 @@ extension AppDelegate {
)
case nil:
firstly {
LaunchJobs.run(tsAccountManager: tsAccountManager, databaseStorage: databaseStorage)
LaunchJobs.run(
tsAccountManager: DependenciesBridge.shared.tsAccountManager,
databaseStorage: databaseStorage
)
}.done(on: DispatchQueue.main) {
self.setAppIsReady(
launchInterface: launchInterface,
@ -324,22 +324,25 @@ extension AppDelegate {
CurrentAppContext().appUserDefaults().removeObject(forKey: kAppLaunchesAttemptedKey)
if tsAccountManager.isRegistered {
databaseStorage.read { transaction in
let localAddress = self.tsAccountManager.localAddress(with: transaction)
let deviceId = self.tsAccountManager.storedDeviceId(transaction: transaction)
let deviceCount = OWSDevice.anyCount(transaction: transaction)
let tsAccountManager = DependenciesBridge.shared.tsAccountManager
let tsRegistrationState: TSRegistrationState = databaseStorage.read { tx in
let registrationState = tsAccountManager.registrationState(tx: tx.asV2Read)
if registrationState.isRegistered {
let localAddress = tsAccountManager.localIdentifiers(tx: tx.asV2Read)?.aciAddress
let deviceId = tsAccountManager.storedDeviceId(tx: tx.asV2Read)
let deviceCount = OWSDevice.anyCount(transaction: tx)
let linkedDeviceMessage = deviceCount > 1 ? "\(deviceCount) devices including the primary" : "no linked devices"
Logger.info("localAddress: \(String(describing: localAddress)), deviceId: \(deviceId) (\(linkedDeviceMessage))")
}
return registrationState
}
if tsAccountManager.isRegisteredAndReady {
if tsRegistrationState.isRegistered {
// This should happen at any launch, background or foreground.
SyncPushTokensJob.run()
}
if tsAccountManager.isRegisteredAndReady {
if tsRegistrationState.isRegistered {
APNSRotationStore.rotateIfNeededOnAppLaunchAndReadiness(performRotation: {
SyncPushTokensJob.run(mode: .rotateIfEligible)
}).map {
@ -352,7 +355,7 @@ extension AppDelegate {
AppVersionImpl.shared.mainAppLaunchDidComplete()
enableBackgroundRefreshIfNecessary()
Self.updateApplicationShortcutItems(isRegisteredAndReady: tsAccountManager.isRegisteredAndReady)
Self.updateApplicationShortcutItems(isRegistered: tsRegistrationState.isRegistered)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
@ -381,14 +384,17 @@ extension AppDelegate {
)
}
checkDatabaseIntegrityIfNecessary(isRegistered: tsAccountManager.isRegistered)
checkDatabaseIntegrityIfNecessary(isRegistered: tsRegistrationState.isRegistered)
SignalApp.shared.showLaunchInterface(launchInterface, launchStartedAt: launchStartedAt)
}
private func enableBackgroundRefreshIfNecessary() {
let interval: TimeInterval
if OWS2FAManager.shared.isRegistrationLockEnabled, self.tsAccountManager.isRegisteredAndReady {
if
OWS2FAManager.shared.isRegistrationLockEnabled,
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered
{
// Ping server once a day to keep-alive reglock clients.
interval = 24 * 60 * 60
} else {
@ -441,39 +447,45 @@ extension AppDelegate {
// MARK: - Registration
private func buildLaunchInterface(regLoader: RegistrationCoordinatorLoader) -> LaunchInterface {
// If user is missing profile name, we will redirect to onboarding flow.
let hasProfileName = profileManager.hasProfileName
let (
isOnboarded,
isRegistered,
tsRegistrationState,
lastMode
) = databaseStorage.read { tx in
return (
tsAccountManager.isOnboarded(transaction: tx),
tsAccountManager.isRegistered(transaction: tx),
DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx.asV2Read),
regLoader.restoreLastMode(transaction: tx.asV2Read)
)
}
if let lastMode {
Logger.info("Found ongoing registration; continuing")
return .registration(regLoader, lastMode)
// TODO[Registration]: use a db migration to move isOnboarded state to reg coordinator.
} else if !(isOnboarded && isRegistered) {
} else if !(hasProfileName && tsRegistrationState.isRegistered) {
if UIDevice.current.isIPad {
return .secondaryProvisioning
} else {
let desiredMode: RegistrationMode
if
let reregNumber = tsAccountManager.reregistrationPhoneNumber,
let reregE164 = E164(reregNumber),
let reregAci = tsAccountManager.reregistrationAci
{
Logger.info("Found legacy re-registration; continuing in new registration")
// A user who started re-registration before the new
// registration flow shipped; kick them to new re-reg.
desiredMode = .reRegistering(.init(e164: reregE164, aci: reregAci))
} else {
Logger.info("Found legacy initial registration; continuing in new registration")
switch tsRegistrationState {
case .reregistering(let reregNumber, let reregAci):
if let reregE164 = E164(reregNumber), let reregAci {
Logger.info("Found legacy re-registration; continuing in new registration")
// A user who started re-registration before the new
// registration flow shipped; kick them to new re-reg.
desiredMode = .reRegistering(.init(e164: reregE164, aci: reregAci))
} else {
// If we're missing the e164 or aci, drop into normal reg.
Logger.info("Found legacy initial registration; continuing in new registration")
desiredMode = .registering
}
default:
// We got here (past the isRegistered check above) which means we should register
// but its not a reregistration.
desiredMode = .registering
}
return .registration(regLoader, desiredMode)
}
} else {
@ -774,7 +786,7 @@ extension AppDelegate {
AssertIsOnMainThread()
AppReadiness.runNowOrWhenAppDidBecomeReadySync {
guard self.tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
Logger.info("Ignoring remote notification; user is not registered.")
return
}
@ -818,11 +830,12 @@ extension AppDelegate {
enableBackgroundRefreshIfNecessary()
let isRegisteredAndReady = tsAccountManager.isRegisteredAndReady
if isRegisteredAndReady {
let tsAccountManager = DependenciesBridge.shared.tsAccountManager
let isRegistered = tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered
if isRegistered {
AppReadiness.runNowOrWhenAppDidBecomeReadySync {
self.databaseStorage.write { transaction in
let localAddress = self.tsAccountManager.localAddress(with: transaction)
let localAddress = tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress
Logger.info("localAddress: \(String(describing: localAddress))")
ExperienceUpgradeFinder.markAllCompleteForNewUser(transaction: transaction.unwrapGrdbWrite)
@ -834,7 +847,7 @@ extension AppDelegate {
}
}
Self.updateApplicationShortcutItems(isRegisteredAndReady: isRegisteredAndReady)
Self.updateApplicationShortcutItems(isRegistered: isRegistered)
}
@objc
@ -844,13 +857,13 @@ extension AppDelegate {
// MARK: - Utilities
public static func updateApplicationShortcutItems(isRegisteredAndReady: Bool) {
public static func updateApplicationShortcutItems(isRegistered: Bool) {
guard CurrentAppContext().isMainApp else { return }
UIApplication.shared.shortcutItems = applicationShortcutItems(isRegisteredAndReady: isRegisteredAndReady)
UIApplication.shared.shortcutItems = applicationShortcutItems(isRegistered: isRegistered)
}
static func applicationShortcutItems(isRegisteredAndReady: Bool) -> [UIApplicationShortcutItem] {
guard isRegisteredAndReady else { return [] }
static func applicationShortcutItems(isRegistered: Bool) -> [UIApplicationShortcutItem] {
guard isRegistered else { return [] }
return [.init(
type: "\(Bundle.main.bundleIdPrefix).quickCompose",
localizedTitle: OWSLocalizedString(
@ -879,7 +892,7 @@ extension AppDelegate {
AppReadiness.runNowOrWhenUIDidBecomeReadySync {
let urlOpener = UrlOpener(
databaseStorage: self.databaseStorage,
tsAccountManager: self.tsAccountManager
tsAccountManager: DependenciesBridge.shared.tsAccountManager
)
urlOpener.openUrl(parsedUrl, in: self.window!)

View File

@ -198,7 +198,7 @@ public final class CallService: LightweightCallManager {
}
AppReadiness.runNowOrWhenAppWillBecomeReady {
if let localAci = self.tsAccountManager.localAci {
if let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci {
self.callManager.setSelfUuid(localAci.rawUUID)
}
}
@ -615,8 +615,8 @@ public final class CallService: LightweightCallManager {
@discardableResult
@objc
public func initiateCall(thread: TSThread, isVideo: Bool) -> Bool {
guard tsAccountManager.isOnboarded else {
Logger.warn("aborting due to user not being onboarded.")
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
Logger.warn("aborting due to user not being registered.")
OWSActionSheets.showActionSheet(title: OWSLocalizedString("YOU_MUST_COMPLETE_ONBOARDING_BEFORE_PROCEEDING",
comment: "alert body shown when trying to use features in the app before completing registration-related setup."))
return false
@ -726,7 +726,7 @@ public final class CallService: LightweightCallManager {
@objc
private func registrationChanged() {
AssertIsOnMainThread()
if let localAci = tsAccountManager.localAci {
if let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci {
callManager.setSelfUuid(localAci.rawUUID)
}
}

View File

@ -47,7 +47,7 @@ final public class IndividualCallService: NSObject {
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoingIncomplete)
// Get the current local device Id, must be valid for lifetime of the call.
let localDeviceId = tsAccountManager.storedDeviceId
let localDeviceId = DependenciesBridge.shared.tsAccountManager.storedDeviceIdWithMaybeTransaction
do {
try callManager.placeCall(call: call, callMediaType: call.individualCall.offerMediaType.asCallMediaType, localDevice: localDeviceId)
@ -216,8 +216,8 @@ final public class IndividualCallService: NSObject {
BenchEventStart(title: "Incoming Call Connection", eventId: "call-\(newCall.localId)")
guard tsAccountManager.isOnboarded(transaction: transaction) else {
Logger.warn("user is not onboarded, skipping call.")
guard DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isRegistered else {
Logger.warn("user is not registered, skipping call.")
newCall.individualCall.createOrUpdateCallInteraction(callType: .incomingMissed, transaction: transaction)
newCall.individualCall.state = .localFailure
@ -272,7 +272,7 @@ final public class IndividualCallService: NSObject {
Logger.info("Ignoring call offer from \(thread.contactAddress) due to insufficient permissions.")
// Send the need permission message to the caller, so they know why we rejected their call.
let localDeviceId = tsAccountManager.storedDeviceId(transaction: transaction)
let localDeviceId = DependenciesBridge.shared.tsAccountManager.storedDeviceId(tx: transaction.asV2Read)
callManager(
callManager,
shouldSendHangup: callId,
@ -320,8 +320,8 @@ final public class IndividualCallService: NSObject {
}
// Get the current local device Id, must be valid for lifetime of the call.
let localDeviceId = tsAccountManager.storedDeviceId(transaction: transaction)
let isPrimaryDevice = tsAccountManager.isPrimaryDevice(transaction: transaction)
let localDeviceId = DependenciesBridge.shared.tsAccountManager.storedDeviceId(tx: transaction.asV2Read)
let isPrimaryDevice = DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isPrimaryDevice ?? true
do {
try callManager.receivedOffer(call: newCall,

View File

@ -149,7 +149,7 @@ public class WebRTCCallMessageHandler: NSObject, OWSCallMessageHandler {
messageAgeSec = (serverDeliveryTimestamp - serverReceivedTimestamp) / 1000
}
let localDeviceId = Self.tsAccountManager.storedDeviceId(transaction: transaction)
let localDeviceId = DependenciesBridge.shared.tsAccountManager.storedDeviceId(tx: transaction.asV2Read)
self.callService.callManager.receivedCallMessage(
senderUuid: caller.rawUUID,

View File

@ -86,7 +86,7 @@ final class CallKitCallManager: NSObject {
}
let phoneNumber: String? = {
guard let localNumber = tsAccountManager.localNumber else {
guard let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber else {
return nil
}
let phoneNumbers = PhoneNumber.tryParsePhoneNumbers(

View File

@ -98,7 +98,11 @@ class GroupCallMemberSheet: InteractiveSheetViewController {
)
}
guard let localAddress = self.tsAccountManager.localAddress else { return members }
guard let localAddress = DependenciesBridge.shared.tsAccountManager
.localIdentifiersWithMaybeSneakyTransaction?.aciAddress
else {
return members
}
let displayName = CommonStrings.you
let comparableName = displayName

View File

@ -170,7 +170,7 @@ class GroupCallLocalMemberView: GroupCallMemberView {
// In full-screen mode the image is shown as part of the "Your camera is off" message.
videoOffIndicatorImage.isHidden = noVideoView.isHidden || isFullScreen
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
return owsFailDebug("missing local address")
}

View File

@ -106,7 +106,7 @@ class GroupCallViewController: UIViewController {
@discardableResult
class func presentLobby(thread: TSGroupThread, videoMuted: Bool = false) -> Bool {
guard tsAccountManager.isOnboarded else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
Logger.warn("aborting due to user not being onboarded.")
OWSActionSheets.showActionSheet(title: OWSLocalizedString(
"YOU_MUST_COMPLETE_ONBOARDING_BEFORE_PROCEEDING",
@ -616,7 +616,7 @@ extension GroupCallViewController: CallViewControllerWindowReference {
var remoteVideoAddress: SignalServiceAddress {
guard let firstMember = groupCall.remoteDeviceStates.sortedByAddedTime.first else {
return tsAccountManager.localAddress!
return DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction!.aciAddress
}
return firstMember.address
}

View File

@ -92,7 +92,7 @@ class RemoteMegaphone: MegaphoneView {
}
guard DonationUtilities.canDonateInAnyWay(
localNumber: Self.tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
) else {
done()
DonationViewsUtil.openDonateWebsite()

View File

@ -8,12 +8,12 @@ import SignalServiceKit
enum LaunchJobs {
static func run(
tsAccountManager: TSAccountManager,
tsAccountManager: TSAccountManagerProtocol,
databaseStorage: SDSDatabaseStorage
) -> Guarantee<Void> {
AssertIsOnMainThread()
guard tsAccountManager.isRegistered else {
guard tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return .value(())
}

View File

@ -54,46 +54,41 @@ public class AccountManager: NSObject, Dependencies {
// MARK: Linking
func completeSecondaryLinking(provisionMessage: ProvisionMessage, deviceName: String) -> Promise<Void> {
// * Primary devices _can_ re-register with a new uuid.
// * Secondary devices _cannot_ be re-linked to primaries with a different uuid.
if tsAccountManager.isReregistering {
// * Primary devices that are re-registering can provision instead with a new uuid.
// * Secondary devices _cannot_ be re-linked to primaries with a different uuid, but
// `reregistering` state does not apply to secondaries.
switch DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction {
case .reregistering(let reregistrationPhoneNumber, let reregistrationAci):
var canChangePhoneNumbers = false
if let oldAci = tsAccountManager.reregistrationAci, let newAci = provisionMessage.aci {
if !tsAccountManager.isPrimaryDevice, oldAci != newAci {
Logger.warn("Cannot re-link with a different uuid.")
return Promise(error: AccountManagerError.reregistrationDifferentAccount)
} else if oldAci == newAci {
// Secondary devices _can_ re-link to primaries with different
// phone numbers if the uuid is present and has not changed.
canChangePhoneNumbers = true
}
if let oldAci = reregistrationAci, let newAci = provisionMessage.aci, oldAci == newAci {
canChangePhoneNumbers = true
}
// * Primary devices _cannot_ re-register with a new phone number.
// * Secondary devices _cannot_ be re-linked to primaries with a different phone number
// unless the uuid is present and has not changed.
if !canChangePhoneNumbers,
let reregistrationPhoneNumber = tsAccountManager.reregistrationPhoneNumber,
reregistrationPhoneNumber != provisionMessage.phoneNumber {
Logger.warn("Cannot re-register with a different phone number.")
if
!canChangePhoneNumbers,
reregistrationPhoneNumber != provisionMessage.phoneNumber
{
Logger.warn("Cannot provision with a different phone number from reregistration.")
return Promise(error: AccountManagerError.reregistrationDifferentAccount)
}
default:
break
}
guard let phoneNumber = E164(provisionMessage.phoneNumber).map({ E164ObjC($0) }) else {
guard let phoneNumber = E164(provisionMessage.phoneNumber) else {
return Promise(error: OWSAssertionError("Primary E164 isn't valid"))
}
guard let aci = provisionMessage.aci.map({ AciObjC($0) }) else {
guard let aci = provisionMessage.aci else {
return Promise(error: OWSAssertionError("Missing ACI in provisioning message!"))
}
guard let pni = provisionMessage.pni.map({ PniObjC($0) }) else {
guard let pni = provisionMessage.pni else {
return Promise(error: OWSAssertionError("Missing PNI in provisioning message!"))
}
tsAccountManager.phoneNumberAwaitingVerification = phoneNumber
tsAccountManager.aciAwaitingVerification = aci
tsAccountManager.pniAwaitingVerification = pni
// Cycle socket and censorship circumvention state as e164 could be changing.
signalService.updateHasCensoredPhoneNumberDuringProvisioning(phoneNumber)
socketManager.cycleSocket()
let serverAuthToken = generateServerAuthToken()
@ -140,7 +135,7 @@ public class AccountManager: NSObject, Dependencies {
prekeyBundles: prekeyBundles
)
}.done { (response: VerifySecondaryDeviceResponse) in
if pni.wrappedPniValue != response.pni {
if pni != response.pni {
throw OWSAssertionError("PNI from primary is out of sync with the server!")
}
@ -173,17 +168,13 @@ public class AccountManager: NSObject, Dependencies {
)
}
self.tsAccountManager.storeLocalNumber(
phoneNumber,
DependenciesBridge.shared.registrationStateChangeManager.didLinkSecondary(
e164: phoneNumber,
aci: aci,
pni: pni,
transaction: transaction
)
self.tsAccountManager.setStoredServerAuthToken(
serverAuthToken,
authToken: serverAuthToken,
deviceId: response.deviceId,
transaction: transaction
tx: transaction.asV2Write
)
}
}.then { _ -> Promise<Void> in
@ -208,7 +199,9 @@ public class AccountManager: NSObject, Dependencies {
}
return self.serviceClient.updateSecondaryDeviceCapabilities(hasBackedUpMasterKey: hasBackedUpMasterKey)
}.done {
self.tsAccountManager.postRegistrationStateDidChangeNotification()
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.didFinishProvisioningSecondary(tx: tx)
}
}.then { _ -> Promise<Void> in
BenchEventStart(title: "waiting for initial storage service restore", eventId: "initial-storage-service-restore")

View File

@ -36,7 +36,7 @@ class AccountSettingsViewController: OWSTableViewController2 {
let contents = OWSTableContents()
// Show the change pin and reglock sections
if tsAccountManager.isRegisteredPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice {
let pinSection = OWSTableSection()
pinSection.headerTitle = OWSLocalizedString(
"SETTINGS_PINS_TITLE",
@ -121,9 +121,10 @@ class AccountSettingsViewController: OWSTableViewController2 {
let accountSection = OWSTableSection()
accountSection.headerTitle = OWSLocalizedString("SETTINGS_ACCOUNT", comment: "Title for the 'account' link in settings.")
if tsAccountManager.isDeregistered {
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction
if tsRegistrationState.isDeregistered {
accountSection.add(.actionItem(
withText: tsAccountManager.isPrimaryDevice
withText: tsRegistrationState.isPrimaryDevice ?? true
? OWSLocalizedString("SETTINGS_REREGISTER_BUTTON", comment: "Label for re-registration button.")
: OWSLocalizedString("SETTINGS_RELINK_BUTTON", comment: "Label for re-link button."),
textColor: .ows_accentBlue,
@ -141,7 +142,7 @@ class AccountSettingsViewController: OWSTableViewController2 {
self?.deleteUnregisterUserData()
}
))
} else if tsAccountManager.isRegisteredPrimaryDevice {
} else if tsRegistrationState.isRegisteredPrimaryDevice {
switch self.changeNumberState() {
case .disallowed:
break
@ -250,7 +251,9 @@ class AccountSettingsViewController: OWSTableViewController2 {
guard self.legacyChangePhoneNumber.localUserSupportsChangePhoneNumber(transaction: transaction) else {
return .disallowed
}
guard self.tsAccountManager.isDeregistered(transaction: transaction).negated else {
let tsAccountManager = DependenciesBridge.shared.tsAccountManager
let tsRegistrationState = tsAccountManager.registrationState(tx: transaction.asV2Read)
guard tsRegistrationState.isRegistered else {
return .disallowed
}
let loader = RegistrationCoordinatorLoaderImpl(dependencies: .from(self))
@ -262,9 +265,9 @@ class AccountSettingsViewController: OWSTableViewController2 {
return .disallowed
}
guard
let localIdentifiers = tsAccountManager.localIdentifiers(transaction: transaction),
let localIdentifiers = tsAccountManager.localIdentifiers(tx: transaction.asV2Read),
let localE164 = E164(localIdentifiers.phoneNumber),
let authToken = tsAccountManager.storedServerAuthToken(transaction: transaction),
let authToken = tsAccountManager.storedServerAuthToken(tx: transaction.asV2Read),
let localRecipient = SignalRecipient.fetchRecipient(
for: localIdentifiers.aciAddress,
onlyIfRegistered: false,
@ -274,7 +277,7 @@ class AccountSettingsViewController: OWSTableViewController2 {
else {
return .disallowed
}
let localDeviceId = tsAccountManager.storedDeviceId(transaction: transaction)
let localDeviceId = tsAccountManager.storedDeviceId(tx: transaction.asV2Read)
let localUserAllDeviceIds = localRecipient.deviceIds
return .allowed(RegistrationMode.ChangeNumberParams(

View File

@ -342,17 +342,13 @@ class DeleteAccountConfirmationViewController: OWSTableViewController2 {
private func unregisterAccount() -> Promise<Void> {
Logger.info("Unregistering...")
let (promise, future) = Promise<Void>.pending()
TSAccountManager.unregisterTextSecure {
future.resolve()
} failure: { error in
future.reject(error)
return Promise.wrapAsync {
try await DependenciesBridge.shared.registrationStateChangeManager.unregisterFromService(auth: .implicit())
}
return promise
}
var hasEnteredLocalNumber: Bool {
guard let localNumber = TSAccountManager.localNumber else {
guard let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber else {
owsFailDebug("local number unexpectedly nil")
return false
}
@ -382,7 +378,7 @@ extension DeleteAccountConfirmationViewController: CountryCodeViewControllerDele
}
func populateDefaultCountryCode() {
guard let localNumber = TSAccountManager.localNumber else {
guard let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber else {
return owsFailDebug("Local number unexpectedly nil")
}

View File

@ -30,7 +30,7 @@ class AppSettingsViewController: OWSTableViewController2 {
updateHasExpiredGiftBadge()
updateTableContents()
if let localAddress = tsAccountManager.localAddress {
if let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress {
bulkProfileFetch.fetchProfile(address: localAddress)
}
@ -142,7 +142,7 @@ class AppSettingsViewController: OWSTableViewController2 {
self?.navigationController?.pushViewController(vc, animated: true)
}
))
if self.tsAccountManager.isPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == true {
section1.add(.disclosureItem(
icon: .settingsLinkedDevices,
name: OWSLocalizedString("LINKED_DEVICES_TITLE", comment: "Menu item and navbar title for the device manager"),
@ -389,7 +389,7 @@ class AppSettingsViewController: OWSTableViewController2 {
localUserDisplayMode: .asUser
)
if let localAddress = tsAccountManager.localAddress {
if let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress {
avatarImageView.updateWithSneakyTransactionIfNecessary { config in
config.dataSource = .address(localAddress)
}
@ -438,7 +438,7 @@ class AppSettingsViewController: OWSTableViewController2 {
addSubtitleLabel(text: OWSUserProfile.bioForDisplay(bio: snapshot.bio, bioEmoji: snapshot.bioEmoji))
if let phoneNumber = tsAccountManager.localNumber {
if let phoneNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber {
addSubtitleLabel(
text: PhoneNumber.bestEffortFormatPartialUserSpecifiedText(toLookLikeAPhoneNumber: phoneNumber),
isLast: true
@ -501,7 +501,9 @@ class AppSettingsViewController: OWSTableViewController2 {
let vc: UIViewController
if DonationSettingsViewController.hasAnythingToShowWithSneakyTransaction() {
vc = DonationSettingsViewController()
} else if DonationUtilities.canDonateInAnyWay(localNumber: tsAccountManager.localNumber) {
} else if DonationUtilities.canDonateInAnyWay(
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
) {
vc = DonateViewController(preferredDonateMode: .oneTime) { finishResult in
let frontVc = { CurrentAppContext().frontmostViewController() }
switch finishResult {

View File

@ -160,7 +160,7 @@ class BadgeGiftingConfirmationViewController: OWSTableViewController2 {
forDonationMode: .gift,
usingCurrency: self.price.currencyCode,
withConfiguration: self.paymentMethodsConfiguration,
localNumber: Self.tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
)
) { [weak self] (sheet, paymentMethod) in
sheet.dismiss(animated: true) { [weak self] in

View File

@ -70,11 +70,16 @@ class DonationSettingsViewController: OWSTableViewController2 {
private lazy var statusLabel = LinkingTextView()
private static var canDonateInAnyWay: Bool {
DonationUtilities.canDonateInAnyWay(localNumber: tsAccountManager.localNumber)
DonationUtilities.canDonateInAnyWay(
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
)
}
private static var canSendGiftBadges: Bool {
DonationUtilities.canDonate(inMode: .gift, localNumber: tsAccountManager.localNumber)
DonationUtilities.canDonate(
inMode: .gift,
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
)
}
public override func viewDidLoad() {
@ -226,7 +231,7 @@ class DonationSettingsViewController: OWSTableViewController2 {
private func setUpAvatarView() {
databaseStorage.read { transaction in
self.avatarView.update(transaction) { config in
if let address = tsAccountManager.localAddress(with: transaction) {
if let address = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress {
config.dataSource = .address(address)
config.addBadgeIfApplicable = true
}

View File

@ -104,13 +104,14 @@ class InternalSettingsViewController: OWSTableViewController2 {
// The first version of the app that was run on this device.
infoSection.add(.copyableItem(label: "First Version", value: AppVersionImpl.shared.firstAppVersion))
infoSection.add(.copyableItem(label: "Local Phone Number", value: tsAccountManager.localNumber))
let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction
infoSection.add(.copyableItem(label: "Local Phone Number", value: localIdentifiers?.phoneNumber))
infoSection.add(.copyableItem(label: "Local ACI", value: tsAccountManager.localAci?.serviceIdString))
infoSection.add(.copyableItem(label: "Local ACI", value: localIdentifiers?.aci.serviceIdString))
infoSection.add(.copyableItem(label: "Local PNI", value: tsAccountManager.localPni?.serviceIdString))
infoSection.add(.copyableItem(label: "Local PNI", value: localIdentifiers?.pni?.serviceIdString))
infoSection.add(.copyableItem(label: "Device ID", value: "\(tsAccountManager.storedDeviceId)"))
infoSection.add(.copyableItem(label: "Device ID", value: "\(DependenciesBridge.shared.tsAccountManager.storedDeviceIdWithMaybeTransaction)"))
if let buildDetails = Bundle.main.object(forInfoDictionaryKey: "BuildDetails") as? [String: AnyObject] {
if let signalCommit = (buildDetails["SignalCommit"] as? String)?.strippedOrNil?.prefix(12) {

View File

@ -141,7 +141,7 @@ class LinkDeviceViewController: OWSViewController {
var pniIdentityKeyPair: ECKeyPair?
var areReadReceiptsEnabled: Bool = true
databaseStorage.read { tx in
localIdentifiers = tsAccountManager.localIdentifiers(transaction: tx)
localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: tx.asV2Read)
let identityManager = DependenciesBridge.shared.identityManager
aciIdentityKeyPair = identityManager.identityKeyPair(for: .aci, tx: tx.asV2Read)
pniIdentityKeyPair = identityManager.identityKeyPair(for: .pni, tx: tx.asV2Read)

View File

@ -218,7 +218,7 @@ class AdvancedPrivacySettingsViewController: OWSTableViewController2 {
}
))
if tsAccountManager.isRegisteredPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice {
sealedSenderSection.add(.switch(
withText: OWSLocalizedString(
"SETTINGS_UNIDENTIFIED_DELIVERY_UNRESTRICTED_ACCESS",

View File

@ -17,7 +17,8 @@ class PhoneNumberPrivacySettingsViewController: OWSTableViewController2 {
override func viewDidLoad() {
super.viewDidLoad()
sharingFeatureEnabled = FeatureFlags.phoneNumberSharing
discoverabilityFeatureEnabled = FeatureFlags.phoneNumberDiscoverability && tsAccountManager.isPrimaryDevice
discoverabilityFeatureEnabled = FeatureFlags.phoneNumberDiscoverability
&& (DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? true)
phoneNumberSharingMode = databaseStorage.read { tx in udManager.phoneNumberSharingMode(tx: tx) }
title = OWSLocalizedString(
"SETTINGS_PHONE_NUMBER_PRIVACY_TITLE",
@ -71,7 +72,9 @@ class PhoneNumberPrivacySettingsViewController: OWSTableViewController2 {
// MARK: Update Setting Values
private func discoverabilityItem(_ isDiscoverable: Bool) -> OWSTableItem {
let currentlyIsDiscoverable = tsAccountManager.isDiscoverableByPhoneNumber()
let currentlyIsDiscoverable = DependenciesBridge.shared.db.read(
block: DependenciesBridge.shared.tsAccountManager.isDiscoverableByPhoneNumber(tx:)
)
return OWSTableItem(
text: PhoneNumberDiscoverability.nameForDiscoverability(isDiscoverable),
actionBlock: { [weak self] in
@ -94,17 +97,18 @@ class PhoneNumberPrivacySettingsViewController: OWSTableViewController2 {
// MARK: Update Table UI
private func updateDiscoverability(_ isDiscoverable: Bool) {
guard tsAccountManager.isDiscoverableByPhoneNumber() != isDiscoverable else { return }
let currentlyIsDiscoverable = DependenciesBridge.shared.db.read(
block: DependenciesBridge.shared.tsAccountManager.isDiscoverableByPhoneNumber(tx:)
)
guard currentlyIsDiscoverable != isDiscoverable else { return }
databaseStorage.asyncWrite(block: { [weak self] transaction in
self?.tsAccountManager.setIsDiscoverableByPhoneNumber(
databaseStorage.asyncWrite(block: { transaction in
DependenciesBridge.shared.phoneNumberDiscoverabilityManager.setIsDiscoverableByPhoneNumber(
isDiscoverable,
updateStorageService: true,
authedAccount: .implicit(),
transaction: transaction
tx: transaction.asV2Write
)
}) { [weak self] in
self?.updateTableContents()
}
@ -119,11 +123,11 @@ class PhoneNumberPrivacySettingsViewController: OWSTableViewController2 {
// If sharing is set to `everybody`, discovery needs to be
// updated to match this.
if mode == .everybody {
self?.tsAccountManager.setIsDiscoverableByPhoneNumber(
DependenciesBridge.shared.phoneNumberDiscoverabilityManager.setIsDiscoverableByPhoneNumber(
true,
updateStorageService: true,
authedAccount: .implicit(),
transaction: transaction
tx: transaction.asV2Write
)
}
}) { [weak self] in
@ -162,7 +166,10 @@ struct PhoneNumberDiscoverability {
extension PhoneNumberPrivacySettingsViewController {
fileprivate class var descriptionForCurrentDiscoverability: String {
return PhoneNumberDiscoverability.descriptionForDiscoverability(tsAccountManager.isDiscoverableByPhoneNumber())
let isDiscoverable = DependenciesBridge.shared.db.read {
return DependenciesBridge.shared.tsAccountManager.isDiscoverableByPhoneNumber(tx: $0)
}
return PhoneNumberDiscoverability.descriptionForDiscoverability(isDiscoverable)
}
fileprivate var descriptionForCurrentPhoneNumberSharingMode: String {

View File

@ -36,7 +36,7 @@ class PrivacySettingsViewController: OWSTableViewController2 {
if FeatureFlags.phoneNumberSharing ||
(FeatureFlags.phoneNumberDiscoverability &&
tsAccountManager.isPrimaryDevice) {
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == true) {
whoCanSection.add(.disclosureItem(
withText: OWSLocalizedString(
"SETTINGS_PHONE_NUMBER_PRIVACY_TITLE",

View File

@ -158,7 +158,7 @@ class BadgeConfigurationViewController: OWSTableViewController2, BadgeCollection
guard let self = self else { return cell }
let collectionView = BadgeCollectionView(dataSource: self)
if let localAddress = self.tsAccountManager.localAddress {
if let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress {
let localShortName = self.databaseStorage.read { self.contactsManager.shortDisplayName(for: localAddress, transaction: $0) }
collectionView.badgeSelectionMode = .detailsSheet(owner: .local(shortName: localShortName))
} else {

View File

@ -34,7 +34,7 @@ extension ConversationViewController {
public func didTapBodyTextItem(_ item: CVTextLabel.Item) {
AssertIsOnMainThread()
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return
}
@ -75,7 +75,7 @@ extension ConversationViewController {
public func didLongPressBodyTextItem(_ item: CVTextLabel.Item) {
AssertIsOnMainThread()
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return
}

View File

@ -33,7 +33,7 @@ extension ConversationViewController: MessageRequestDelegate {
return
}
guard let localIdentifiers = tsAccountManager.localIdentifiers else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction else {
owsFailDebug("Missing local identifiers!")
return
}

View File

@ -280,7 +280,8 @@ extension ConversationViewController {
return incoming.authorAddress.aci == draftReply.author
}
if candidate is TSOutgoingMessage {
return tsAccountManager.localIdentifiers(transaction: transaction)?.aci == draftReply.author
return DependenciesBridge.shared.tsAccountManager
.localIdentifiers(tx: transaction.asV2Read)?.aci == draftReply.author
}
return false
},

View File

@ -26,7 +26,7 @@ class ConversationViewModel {
}
let unreadMentionMessageIds = MentionFinder.messagesMentioning(
aci: NSObject.tsAccountManager.localIdentifiers(transaction: tx)!.aci,
aci: DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: tx.asV2Read)!.aci,
in: thread,
includeReadMessages: false,
tx: tx

View File

@ -22,7 +22,7 @@ public class InteractionReactionState: NSObject {
// No reactions on non-message interactions
guard let message = interaction as? TSMessage else { return nil }
guard let localAddress = TSAccountManager.shared.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress else {
owsFailDebug("missing local address")
return nil
}

View File

@ -52,7 +52,7 @@ class DebugUIGroupsV2: DebugUIPage, Dependencies {
// MARK: -
private func kickOtherGroupMembers(groupModel: TSGroupModelV2) {
guard let localAci = tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
return owsFailDebug("Missing localAddress.")
}

View File

@ -3345,7 +3345,7 @@ class DebugUIMessages: DebugUIPage, Dependencies {
private static func createUUIDGroup() {
let uuidMembers = (0...3).map { _ in CommonGenerator.address(hasPhoneNumber: false) }
let members = uuidMembers + [TSAccountManager.localAddress!]
let members = uuidMembers + [DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction!.aciAddress]
let groupName = "UUID Group"
_ = GroupManager.localCreateNewGroup(members: members, name: groupName, disappearingMessageToken: .disabledToken, shouldSendMessage: true)
@ -3697,7 +3697,7 @@ class DebugUIMessages: DebugUIPage, Dependencies {
member: SignalServiceAddress,
completion: @escaping (TSGroupThread) -> Void
) {
let members = [ member, TSAccountManager.localAddress! ]
let members = [ member, DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction!.aciAddress ]
GroupManager.localCreateNewGroup(
members: members,
disappearingMessageToken: .disabledToken,
@ -4205,7 +4205,7 @@ class DebugUIMessages: DebugUIPage, Dependencies {
if let contactThread = thread as? TSContactThread {
return contactThread.contactAddress
} else if let groupThread = thread as? TSGroupThread {
guard let localAddress = Self.tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return nil
}
@ -4230,7 +4230,7 @@ class DebugUIMessages: DebugUIPage, Dependencies {
wasReceivedByUD: false,
serverDeliveryTimestamp: 0,
shouldDiscardVisibleMessages: false,
localIdentifiers: tsAccountManager.localIdentifiers(transaction: tx)!,
localIdentifiers: DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: tx.asV2Read)!,
tx: tx
)
}

View File

@ -103,7 +103,9 @@ class DebugUIMisc: DebugUIPage, Dependencies {
}),
OWSTableItem(title: "Update account attributes", actionBlock: {
TSAccountManager.shared.updateAccountAttributes()
Task {
try? await DependenciesBridge.shared.accountAttributesUpdater.updateAccountAttributes(authedAccount: .implicit())
}
}),
OWSTableItem(title: "Check Prekeys", actionBlock: {
@ -378,7 +380,7 @@ class DebugUIMisc: DebugUIPage, Dependencies {
}
private static func logLocalAccount() {
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return
}

View File

@ -63,7 +63,10 @@ class DebugUIProfile: DebugUIPage, Dependencies {
Self.profileManagerImpl.logLocalProfile()
},
OWSTableItem(title: "Fetch Local Profile") {
ProfileFetcherJob.fetchProfile(address: TSAccountManager.localAddress!, ignoreThrottling: true)
ProfileFetcherJob.fetchProfile(
address: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction!.aciAddress,
ignoreThrottling: true
)
}
].compactMap { $0 }

View File

@ -215,7 +215,7 @@ class DebugUIStress: DebugUIPage, Dependencies {
return SignalServiceAddress(serviceId: Aci(fromUUID: UUID()), phoneNumber: phoneNumber)
}
if let localAddress = tsAccountManager.localAddress {
if let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress {
recipientAddresses.append(localAddress)
}

View File

@ -164,7 +164,7 @@ class BadgeDetailsSheet: OWSTableSheetViewController {
private func didTapDonate() {
dismiss(animated: true) {
if DonationUtilities.canDonateInAnyWay(
localNumber: Self.tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
) {
let frontVc = { CurrentAppContext().frontmostViewController() }

View File

@ -168,7 +168,7 @@ class BadgeExpirationSheet: OWSTableSheetViewController {
badge: badge,
mode: mode,
canDonate: DonationUtilities.canDonateInAnyWay(
localNumber: Self.tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
)
)
owsAssertDebug(state.badge.assets != nil)

View File

@ -209,7 +209,7 @@ class DonateChoosePaymentMethodSheet: OWSTableSheetViewController {
let paymentMethods: [DonationPaymentMethod]
let applePayFirstRegions = PhoneNumberRegions(arrayLiteral: "1")
if let localNumber = Self.tsAccountManager.localNumber,
if let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber,
applePayFirstRegions.contains(e164: localNumber) {
paymentMethods = [
.applePay,

View File

@ -15,7 +15,7 @@ class DonateViewController: OWSViewController, OWSNavigationChildController {
) -> Bool {
DonationUtilities.canDonate(
inMode: donateMode.asDonationMode,
localNumber: tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
)
}
@ -631,7 +631,7 @@ class DonateViewController: OWSViewController, OWSNavigationChildController {
previousMonthlySubscriptionCurrencyCode: previousSubscriberCurrencyCode,
previousMonthlySubscriptionPaymentMethod: previousSubscriberPaymentMethod,
locale: Locale.current,
localNumber: Self.tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
)
return .value(loadedState)
@ -688,7 +688,7 @@ class DonateViewController: OWSViewController, OWSNavigationChildController {
databaseStorage.read { [weak self] transaction in
self?.avatarView.update(transaction) { config in
guard let address = self?.tsAccountManager.localAddress(with: transaction) else {
guard let address = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress else {
return
}
config.dataSource = .address(address)

View File

@ -423,7 +423,7 @@ private class GroupInviteLinksActionSheet: ActionSheetController, Dependencies {
}
private var doesLocalUserSupportGroupsV2: Bool {
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("missing local address")
return false
}

View File

@ -38,7 +38,7 @@ public class CLVReminderViews: Dependencies {
let deregisteredText: String
let deregisteredActionTitle: String
if TSAccountManager.shared.isPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? true {
deregisteredText = OWSLocalizedString(
"DEREGISTRATION_WARNING",
comment: "Label warning the user that they have been de-registered."
@ -199,7 +199,8 @@ extension ChatListViewController {
AssertIsOnMainThread()
archiveReminderView.isHidden = chatListMode != .archive
deregisteredView.isHidden = !tsAccountManager.isDeregistered || tsAccountManager.isTransferInProgress
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction
deregisteredView.isHidden = !tsRegistrationState.isDeregistered
outageView.isHidden = !OutageDetection.shared.hasOutage
expiredView.update()

View File

@ -587,7 +587,7 @@ public class ChatListViewController: OWSViewController {
}
private func addPullToRefreshIfNeeded() {
if tsAccountManager.isPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? true {
return
}
@ -601,7 +601,7 @@ public class ChatListViewController: OWSViewController {
@objc
private func pullToRefreshPerformed(_ refreshControl: UIRefreshControl) {
AssertIsOnMainThread()
owsAssert(!tsAccountManager.isPrimaryDevice)
owsAssert(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == false)
syncManager.sendAllSyncRequestMessages(timeout: 20).ensure {
refreshControl.endRefreshing()
@ -983,7 +983,7 @@ extension ChatListViewController {
let avatarView = ConversationAvatarView(sizeClass: .twentyEight, localUserDisplayMode: .asUser)
databaseStorage.read { readTx in
avatarView.update(readTx) { config in
if let address = tsAccountManager.localAddress(with: readTx) {
if let address = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: readTx.asV2Read)?.aciAddress {
config.dataSource = .address(address)
config.applyConfigurationSynchronously()
}
@ -1103,7 +1103,7 @@ extension ChatListViewController {
case let .donate(donateMode):
guard DonationUtilities.canDonate(
inMode: donateMode.asDonationMode,
localNumber: tsAccountManager.localNumber
localNumber: DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber
) else {
DonationViewsUtil.openDonateWebsite()
return

View File

@ -96,7 +96,7 @@ class MyStoryCell: UITableViewCell {
addStoryButton.block = addStoryAction
avatarView.updateWithSneakyTransactionIfNecessary { config in
config.dataSource = .address(Self.tsAccountManager.localAddress!)
config.dataSource = .address(DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction!.aciAddress)
// We reload the row when this state changes, so don't make the avatar auto update.
config.storyConfiguration = .fixed(model.messages.isEmpty ? .noStories : .viewed)
config.usePlaceholderImages()

View File

@ -221,10 +221,12 @@ class StoryGroupReplyLoader: Dependencies {
var messages = [(SignalServiceAddress, TSMessage)]()
var authorAddresses = Set<SignalServiceAddress>()
let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress
for interaction in loadedInteractions {
if let outgoingMessage = interaction as? TSOutgoingMessage {
messages.append((tsAccountManager.localAddress!, outgoingMessage))
authorAddresses.insert(tsAccountManager.localAddress!)
messages.append((localAddress, outgoingMessage))
authorAddresses.insert(localAddress)
} else if let incomingMessage = interaction as? TSIncomingMessage {
messages.append((incomingMessage.authorAddress, incomingMessage))
authorAddresses.insert(incomingMessage.authorAddress)

View File

@ -263,7 +263,7 @@ private class StoryThreadCell: ContactTableViewCell {
configuration = ContactCellConfiguration(groupThread: groupThread, localUserDisplayMode: .noteToSelf)
case .privateStory(_, let isMyStory):
if isMyStory {
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Unexpectedly missing local address")
return
}

View File

@ -306,7 +306,7 @@ class StoriesViewController: OWSViewController, StoryListDataSourceDelegate {
let avatarView = ConversationAvatarView(sizeClass: .twentyEight, localUserDisplayMode: .asUser)
databaseStorage.read { transaction in
avatarView.update(transaction) { config in
if let address = tsAccountManager.localAddress(with: transaction) {
if let address = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress {
config.dataSource = .address(address)
config.applyConfigurationSynchronously()
}

View File

@ -460,7 +460,7 @@ class MediaGallery: Dependencies {
return incomingMessage.authorAddress
}
return tsAccountManager.localAddress(with: transaction)
return DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress
}()
if let senderAddress {

View File

@ -203,7 +203,7 @@ public class NewGroupConfirmViewController: OWSTableViewController2 {
private func createNewGroup() {
AssertIsOnMainThread()
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("missing local address")
return
}

View File

@ -250,7 +250,7 @@ public class PinSetupViewController: OWSViewController, OWSNavigationChildContro
enableRegistrationLock: Bool,
completionHandler: @escaping (PinSetupViewController, Error?) -> Void
) {
assert(TSAccountManager.shared.isRegisteredPrimaryDevice)
assert(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice)
self.mode = mode
self.initialMode = initialMode
self.pinType = pinType
@ -671,7 +671,9 @@ public class PinSetupViewController: OWSViewController, OWSNavigationChildContro
// registration recovery password.
// We might have already done this in the steps above, but re-upload to be sure.
// Just kick it off, don't wait on the result.
_ = TSAccountManager.shared.updateAccountAttributes().cauterize()
DependenciesBridge.shared.db.write {
DependenciesBridge.shared.accountAttributesUpdater.scheduleAccountAttributesUpdate(authedAccount: .implicit(), tx: $0)
}
}
.done {
AssertIsOnMainThread()

View File

@ -9,7 +9,14 @@ import SignalUI
class OutgoingDeviceTransferProgressViewController: DeviceTransferBaseViewController {
override var requiresDismissConfirmation: Bool { TSAccountManager.shared.isTransferInProgress }
override var requiresDismissConfirmation: Bool {
switch DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction {
case .transferringLinkedOutgoing, .transferringPrimaryOutgoing:
return true
default:
return false
}
}
let progressView: TransferProgressView
init(progress: Progress) {

View File

@ -204,7 +204,8 @@ extension OutgoingDeviceTransferQRScanningViewController: QRCodeScanDelegate {
return
case .modeMismatch:
let desiredMode: DeviceTransferService.TransferMode =
TSAccountManager.shared.isPrimaryDevice ? .linked : .primary
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? true
? .linked : .primary
switch desiredMode {
case .linked:
self.showError(

View File

@ -167,7 +167,7 @@ public class SendPaymentViewController: OWSViewController {
showEnablePaymentsActionSheet()
return
}
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
Logger.info("Local user is not registered and ready.")
showNotRegisteredActionSheet()
return
@ -356,7 +356,7 @@ public class SendPaymentViewController: OWSViewController {
message: interaction.asPreparer,
transaction: transaction
)
if let localAci = self.tsAccountManager.localIdentifiers(transaction: transaction)?.aci {
if let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aci {
let infoMessage = TSInfoMessage(
thread: thread,
messageType: .paymentsActivationRequest,

View File

@ -339,7 +339,7 @@ public class ProvisioningController: NSObject {
public func provisioningDidComplete(from viewController: UIViewController) {
self.databaseStorage.write {
Logger.info("completed provisioning")
self.tsAccountManager.setIsOnboarded(true, transaction: $0)
DependenciesBridge.shared.registrationStateChangeManager.didFinishProvisioningSecondary(tx: $0.asV2Write)
}
SignalApp.shared.showConversationSplitView()
}

View File

@ -260,7 +260,11 @@ class ConversationSettingsViewController: OWSTableViewController2, BadgeCollecti
private(set) var groupMemberStateMap = [SignalServiceAddress: OWSVerificationState]()
private(set) var sortedGroupMembers = [SignalServiceAddress]()
func updateGroupMembers(transaction tx: SDSAnyReadTransaction) {
guard let groupModel = currentGroupModel, !groupModel.isPlaceholder, let localAddress = tsAccountManager.localAddress else {
guard
let groupModel = currentGroupModel,
!groupModel.isPlaceholder,
let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress
else {
groupMemberStateMap = [:]
sortedGroupMembers = []
return
@ -642,7 +646,7 @@ class ConversationSettingsViewController: OWSTableViewController2, BadgeCollecti
guard let groupModelV2 = groupThread.groupModel as? TSGroupModelV2 else {
return true
}
guard let localAci = tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
owsFailDebug("missing local address")
return true
}
@ -660,7 +664,7 @@ class ConversationSettingsViewController: OWSTableViewController2, BadgeCollecti
guard let groupModelV2 = groupThread.groupModel as? TSGroupModelV2 else {
return []
}
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("missing local address")
return []
}

View File

@ -227,7 +227,7 @@ public class GroupMemberRequestsAndInvitesViewController: OWSTableViewController
}
private func addContentsForPendingInvites(contents: OWSTableContents) {
guard let localAci = tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
owsFailDebug("missing local address")
return
}

View File

@ -57,7 +57,7 @@ extension GroupViewHelper {
groupThread.isGroupV2Thread else {
return false
}
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return false
}
@ -91,7 +91,7 @@ extension GroupViewHelper {
groupThread.isGroupV2Thread else {
return false
}
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return false
}
@ -125,7 +125,7 @@ extension GroupViewHelper {
groupThread.isGroupV2Thread else {
return false
}
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return false
}

View File

@ -59,7 +59,7 @@ class GroupViewHelper: Dependencies {
// All users can edit v1 groups.
return true
}
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return false
}

View File

@ -88,7 +88,7 @@ public class AppEnvironment: NSObject {
AppReadiness.runNowOrWhenAppDidBecomeReadyAsync {
let isPrimaryDevice = self.databaseStorage.read { tx -> Bool in
return self.tsAccountManager.isPrimaryDevice(transaction: tx)
return DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx.asV2Read).isPrimaryDevice ?? true
}
let db = DependenciesBridge.shared.db

View File

@ -264,7 +264,7 @@ extension SignalApp {
OWSFileSystem.deleteContents(ofDirectory: OWSFileSystem.cachesDirectoryPath())
OWSFileSystem.deleteContents(ofDirectory: OWSTemporaryDirectory())
OWSFileSystem.deleteContents(ofDirectory: NSTemporaryDirectory())
AppDelegate.updateApplicationShortcutItems(isRegisteredAndReady: false)
AppDelegate.updateApplicationShortcutItems(isRegistered: false)
}
DebugLogger.shared().wipeLogsAlways(appContext: CurrentAppContext() as! MainAppContext)

View File

@ -171,7 +171,7 @@ extension DeviceTransferService {
stopTransfer()
return owsFailDebug("Failed to parse manifest proto")
}
guard !tsAccountManager.isRegistered else {
guard !DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
stopTransfer()
return owsFailDebug("Ignoring incoming transfer to a registered device")
}
@ -198,7 +198,9 @@ extension DeviceTransferService {
progress: progress
)
tsAccountManager.isTransferInProgress = true
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setIsTransferInProgress(tx: tx)
}
notifyObservers { $0.deviceTransferServiceDidStartTransfer(progress: progress) }

View File

@ -362,7 +362,7 @@ extension DeviceTransferService: MCSessionDelegate {
guard case .outgoing(let newDevicePeerId, let expectedCertificateHash, _, _, _) = transferState else {
// Accept all connections if we're not doing an outgoing transfer AND we aren't yet registered.
// Registered devices can only ever perform outgoing transfers.
certificateIsTrusted = !tsAccountManager.isRegistered
certificateIsTrusted = !DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered
return
}

View File

@ -547,13 +547,17 @@ extension DeviceTransferService {
let (promise, future) = Guarantee<Void>.pending()
AppReadiness.runNowOrWhenAppDidBecomeReadySync {
self.tsAccountManager.isTransferInProgress = false
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setIsTransferComplete(
sendStateUpdateNotification: true,
tx: tx
)
}
// Consult both the modern and legacy restoration flag
let currentPhase = (try? self.restorationPhase) ?? .noCurrentRestoration
if currentPhase == .cleanup || LegacyRestorationFlags.pendingWasTransferredClear {
Logger.info("Performing one-time post-restore cleanup...")
self.tsAccountManager.wasTransferred = false
GRDBDatabaseStorageAdapter.removeOrphanedGRDBDirectories()
LegacyRestorationFlags.pendingWasTransferredClear = false
self.rawRestorationPhase = RestorationPhase.noCurrentRestoration.rawValue

View File

@ -58,7 +58,8 @@ extension DeviceTransferService {
throw Error.unsupportedVersion
}
let currentMode: TransferMode = tsAccountManager.isPrimaryDevice ? .primary : .linked
let currentMode: TransferMode = DependenciesBridge.shared.tsAccountManager
.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == true ? .primary : .linked
guard let rawMode = queryItemsDictionary[DeviceTransferService.transferModeKey],
rawMode == currentMode.rawValue else {

View File

@ -183,11 +183,20 @@ class DeviceTransferService: NSObject {
// Marking the transfer as "in progress" does a few things, most notably it:
// * prevents any WAL checkpoints while the transfer is in progress
// * causes the device to behave is if it's not registered
tsAccountManager.isTransferInProgress = true
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setIsTransferInProgress(tx: tx)
}
defer {
// If we failed to start the transfer, clear the transfer in progress flag
if case .idle = transferState { tsAccountManager.isTransferInProgress = false }
if case .idle = transferState {
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setIsTransferComplete(
sendStateUpdateNotification: true,
tx: tx
)
}
}
}
let manifest = try buildManifest()
@ -268,10 +277,11 @@ class DeviceTransferService: NSObject {
// simply return in the .idle case above since none of the values being
// reset should have values if we are idle, but I am scared of it.
if case .idle = transferState {} else {
if notifyRegState {
tsAccountManager.isTransferInProgress = false
} else {
tsAccountManager.setIsTransferInProgressWithoutNotification(false)
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setIsTransferComplete(
sendStateUpdateNotification: notifyRegState,
tx: tx
)
}
}
@ -357,7 +367,9 @@ class DeviceTransferService: NSObject {
}
Promise.when(fulfilled: promises).done {
self.tsAccountManager.wasTransferred = true
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setWasTransferred(tx: tx)
}
try self.sendDoneMessage(to: newDevicePeerId)
}.catch { error in
if !(error is DeviceTransferOperation.CancelError) {

View File

@ -16,13 +16,13 @@ public class RegistrationUtils: Dependencies {
AssertIsOnMainThread()
// If this is not the primary device, jump directly to the re-linking flow.
guard tsAccountManager.isPrimaryDevice else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == true else {
showRelinkingUI()
return
}
guard
let localIdentifiers = tsAccountManager.localIdentifiers,
let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction,
let e164 = E164(localIdentifiers.phoneNumber)
else {
owsFailDebug("could not get local address for re-registration.")
@ -38,7 +38,7 @@ public class RegistrationUtils: Dependencies {
class func showReregistrationUI(fromViewController viewController: UIViewController) {
// If this is not the primary device, jump directly to the re-linking flow.
guard tsAccountManager.isPrimaryDevice else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == true else {
showRelinkingUI()
return
}
@ -62,7 +62,22 @@ public class RegistrationUtils: Dependencies {
private class func showRelinkingUI() {
Logger.info("showRelinkingUI")
guard tsAccountManager.resetForReregistration() else {
let success = DependenciesBridge.shared.db.write { tx -> Bool in
guard
let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: tx),
let localE164 = E164(localIdentifiers.phoneNumber)
else {
return false
}
DependenciesBridge.shared.registrationStateChangeManager.resetForReregistration(
localPhoneNumber: localE164,
localAci: localIdentifiers.aci,
wasPrimaryDevice: DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx).isPrimaryDevice ?? false,
tx: tx
)
return true
}
guard success else {
owsFailDebug("could not reset for re-registration.")
return
}

View File

@ -12,10 +12,10 @@ class AppDelegateTest: XCTestCase {
shortcuts.contains(where: { $0.type.contains("quickCompose") })
}
let unregistered = AppDelegate.applicationShortcutItems(isRegisteredAndReady: false)
let unregistered = AppDelegate.applicationShortcutItems(isRegistered: false)
XCTAssertFalse(hasNewMessageShortcut(unregistered))
let registered = AppDelegate.applicationShortcutItems(isRegisteredAndReady: true)
let registered = AppDelegate.applicationShortcutItems(isRegistered: true)
XCTAssertTrue(hasNewMessageShortcut(registered))
}
}

View File

@ -40,16 +40,18 @@ public class RegistrationCoordinatorTest: XCTestCase {
private var mockMessageProcessor: RegistrationCoordinatorImpl.TestMocks.MessageProcessor!
private var mockURLSession: TSRequestOWSURLSessionMock!
private var ows2FAManagerMock: RegistrationCoordinatorImpl.TestMocks.OWS2FAManager!
private var phoneNumberDiscoverabilityManagerMock: MockPhoneNumberDiscoverabilityManager!
private var preKeyManagerMock: RegistrationCoordinatorImpl.TestMocks.PreKeyManager!
private var profileManagerMock: RegistrationCoordinatorImpl.TestMocks.ProfileManager!
private var pushRegistrationManagerMock: RegistrationCoordinatorImpl.TestMocks.PushRegistrationManager!
private var receiptManagerMock: RegistrationCoordinatorImpl.TestMocks.ReceiptManager!
private var registrationStateChangeManagerMock: MockRegistrationStateChangeManager!
private var remoteConfigMock: RegistrationCoordinatorImpl.TestMocks.RemoteConfig!
private var sessionManager: RegistrationSessionManagerMock!
private var storageServiceManagerMock: FakeStorageServiceManager!
private var svr: SecureValueRecoveryMock!
private var svrAuthCredentialStore: SVRAuthCredentialStorageMock!
private var tsAccountManagerMock: RegistrationCoordinatorImpl.TestMocks.TSAccountManager!
private var tsAccountManagerMock: MockTSAccountManager!
public override func setUp() {
super.setUp()
@ -71,14 +73,16 @@ public class RegistrationCoordinatorTest: XCTestCase {
mockMessagePipelineSupervisor = RegistrationCoordinatorImpl.TestMocks.MessagePipelineSupervisor()
mockMessageProcessor = RegistrationCoordinatorImpl.TestMocks.MessageProcessor()
ows2FAManagerMock = RegistrationCoordinatorImpl.TestMocks.OWS2FAManager()
phoneNumberDiscoverabilityManagerMock = MockPhoneNumberDiscoverabilityManager()
preKeyManagerMock = RegistrationCoordinatorImpl.TestMocks.PreKeyManager()
profileManagerMock = RegistrationCoordinatorImpl.TestMocks.ProfileManager()
pushRegistrationManagerMock = RegistrationCoordinatorImpl.TestMocks.PushRegistrationManager()
receiptManagerMock = RegistrationCoordinatorImpl.TestMocks.ReceiptManager()
registrationStateChangeManagerMock = MockRegistrationStateChangeManager()
remoteConfigMock = RegistrationCoordinatorImpl.TestMocks.RemoteConfig()
sessionManager = RegistrationSessionManagerMock()
storageServiceManagerMock = FakeStorageServiceManager()
tsAccountManagerMock = RegistrationCoordinatorImpl.TestMocks.TSAccountManager()
tsAccountManagerMock = MockTSAccountManager(dateProvider: dateProvider)
let mockURLSession = TSRequestOWSURLSessionMock()
self.mockURLSession = mockURLSession
@ -102,10 +106,12 @@ public class RegistrationCoordinatorTest: XCTestCase {
messagePipelineSupervisor: mockMessagePipelineSupervisor,
messageProcessor: mockMessageProcessor,
ows2FAManager: ows2FAManagerMock,
phoneNumberDiscoverabilityManager: phoneNumberDiscoverabilityManagerMock,
preKeyManager: preKeyManagerMock,
profileManager: profileManagerMock,
pushRegistrationManager: pushRegistrationManagerMock,
receiptManager: receiptManagerMock,
registrationStateChangeManager: registrationStateChangeManagerMock,
remoteConfig: remoteConfigMock,
schedulers: TestSchedulers(scheduler: scheduler),
sessionManager: sessionManager,
@ -3346,7 +3352,7 @@ public class RegistrationCoordinatorTest: XCTestCase {
}
private func setAllProfileInfo() {
tsAccountManagerMock.hasDefinedIsDiscoverableByPhoneNumberMock = { true }
phoneNumberDiscoverabilityManagerMock.hasDefinedIsDiscoverableByPhoneNumberMock = { true }
profileManagerMock.hasProfileNameMock = { true }
}

View File

@ -24,7 +24,6 @@ extension RegistrationCoordinatorImpl {
public typealias PushRegistrationManager = _RegistrationCoordinator_PushRegistrationManagerMock
public typealias ReceiptManager = _RegistrationCoordinator_ReceiptManagerMock
public typealias RemoteConfig = _RegistrationCoordinator_RemoteConfigMock
public typealias TSAccountManager = _RegistrationCoordinator_TSAccountManagerMock
public typealias UDManager = _RegistrationCoordinator_UDManagerMock
}
}
@ -294,107 +293,6 @@ public class _RegistrationCoordinator_RemoteConfigMock: _RegistrationCoordinator
}
}
// MARK: - TSAccountManager
public class _RegistrationCoordinator_TSAccountManagerMock: _RegistrationCoordinator_TSAccountManagerShim {
public init() {}
public var hasDefinedIsDiscoverableByPhoneNumberMock: (() -> Bool)?
public func hasDefinedIsDiscoverableByPhoneNumber(_ transaction: DBReadTransaction) -> Bool {
return hasDefinedIsDiscoverableByPhoneNumberMock!()
}
public var isDiscoverableByPhoneNumberMock: () -> Bool = { true }
public func isDiscoverableByPhoneNumber(_ transaction: DBReadTransaction) -> Bool {
return isDiscoverableByPhoneNumberMock()
}
public var setIsDiscoverableByPhoneNumberMock: ((_ isDiscoverable: Bool, _ authedAccount: AuthedAccount, _ updateStorageService: Bool) -> Void)?
public func setIsDiscoverableByPhoneNumber(
_ isDiscoverable: Bool,
updateStorageService: Bool,
authedAccount: AuthedAccount,
_ transaction: SignalServiceKit.DBWriteTransaction
) {
setIsDiscoverableByPhoneNumberMock?(isDiscoverable, authedAccount, updateStorageService)
}
public var isManualMessageFetchEnabledMock: () -> Bool = { false }
public func isManualMessageFetchEnabled(_ transaction: DBReadTransaction) -> Bool {
return isManualMessageFetchEnabledMock()
}
public var setIsManualMessageFetchEnabledMock: ((_ isEnabled: Bool) -> Void)?
public func setIsManualMessageFetchEnabled(_ isEnabled: Bool, _ transaction: DBWriteTransaction) {
setIsManualMessageFetchEnabledMock?(isEnabled)
}
public var resetForReregistrationMock: ((
_ e164: E164,
_ aci: Aci
) -> Void)?
public func resetForReregistration(
e164: E164,
aci: Aci,
_ tx: DBWriteTransaction
) {
resetForReregistrationMock?(e164, aci)
}
public var didRegisterMock: ((
_ e164: E164,
_ aci: Aci,
_ pni: Pni,
_ authToken: String
) -> Void)?
public func didRegister(
e164: E164,
aci: Aci,
pni: Pni,
authToken: String,
_ tx: DBWriteTransaction
) {
didRegisterMock?(e164, aci, pni, authToken)
}
public var updateLocalPhoneNumberMock: ((
_ e164: E164,
_ aci: Aci,
_ pni: Pni
) -> Void)?
public func updateLocalPhoneNumber(
e164: E164,
aci: Aci,
pni: Pni,
_ tx: DBWriteTransaction
) {
updateLocalPhoneNumberMock?(e164, aci, pni)
}
public var registrationIdMock: (() -> UInt32) = { 8 /* an arbitrary default value */ }
public func getOrGenerateRegistrationId(_ transaction: DBWriteTransaction) -> UInt32 {
return registrationIdMock()
}
public var pniRegistrationIdMock: (() -> UInt32) = { 9 /* an arbitrary default value */ }
public func getOrGeneratePniRegistrationId(_ transaction: DBWriteTransaction) -> UInt32 {
return pniRegistrationIdMock()
}
public func setIsOnboarded(_ tx: SignalServiceKit.DBWriteTransaction) {}
}
// MARK: UDManager
public class _RegistrationCoordinator_UDManagerMock: _RegistrationCoordinator_UDManagerShim {

View File

@ -19,7 +19,12 @@ class OWSContactsManagerTest: SignalBaseTest {
super.setUp()
// Create local account.
tsAccountManager.registerForTests(localIdentifiers: .forUnitTests)
databaseStorage.write { tx in
(DependenciesBridge.shared.registrationStateChangeManager as! RegistrationStateChangeManagerImpl).registerForTests(
localIdentifiers: .forUnitTests,
tx: tx.asV2Write
)
}
// Replace the fake contacts manager with the real one just for this test.
SSKEnvironment.shared.setContactsManagerForUnitTests(makeContactsManager())

View File

@ -14,7 +14,12 @@ class ContactStreamTest: SignalBaseTest {
override func setUp() {
super.setUp()
tsAccountManager.registerForTests(localIdentifiers: .forUnitTests)
Self.databaseStorage.write { tx in
(DependenciesBridge.shared.registrationStateChangeManager as! RegistrationStateChangeManagerImpl).registerForTests(
localIdentifiers: .forUnitTests,
tx: tx.asV2Write
)
}
}
// MARK: -

View File

@ -172,10 +172,19 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
// ensure local client has necessary "registered" state
let localE164Identifier = "+13235551234"
let localUUID = UUID()
tsAccountManager.registerForTests(withLocalNumber: localE164Identifier, uuid: localUUID)
databaseStorage.write { tx in
(DependenciesBridge.shared.registrationStateChangeManager as! RegistrationStateChangeManagerImpl).registerForTests(
localIdentifiers: .init(
aci: .init(fromUUID: localUUID),
pni: nil,
e164: E164(localE164Identifier)!
),
tx: tx.asV2Write
)
}
self.write { transaction in
let bookClubGroupThread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, self.tsAccountManager.localAddress!],
let bookClubGroupThread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress],
name: "Book Club",
transaction: transaction)
self.bookClubThread = ThreadViewModel(thread: bookClubGroupThread,
@ -412,7 +421,7 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
var thread: TSGroupThread! = nil
self.write { transaction in
thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, self.tsAccountManager.localAddress!],
thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress],
name: "Lifecycle",
transaction: transaction)
}
@ -466,7 +475,7 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
func testModelLifecycle2() {
self.write { transaction in
let thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, self.tsAccountManager.localAddress!],
let thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress],
name: "Lifecycle",
transaction: transaction)
@ -495,7 +504,7 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
func testDiacritics() {
self.write { transaction in
let thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, self.tsAccountManager.localAddress!],
let thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress],
name: "Lifecycle",
transaction: transaction)
@ -545,7 +554,7 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
var thread: TSGroupThread! = nil
self.write { transaction in
thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, self.tsAccountManager.localAddress!],
thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress],
name: "Lifecycle",
transaction: transaction)
}
@ -578,7 +587,16 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
let aliceE164 = "+13213214321"
let aliceUuid = UUID()
tsAccountManager.registerForTests(withLocalNumber: aliceE164, uuid: aliceUuid)
databaseStorage.write { tx in
(DependenciesBridge.shared.registrationStateChangeManager as! RegistrationStateChangeManagerImpl).registerForTests(
localIdentifiers: .init(
aci: .init(fromUUID: aliceUuid),
pni: nil,
e164: E164(aliceE164)!
),
tx: tx.asV2Write
)
}
let string1 = "krazy"
let string2 = "kat"
@ -586,7 +604,7 @@ class GRDBFullTextSearcherTest: SignalBaseTest {
Bench(title: "Populate Index", memorySamplerRatio: 1) { _ in
self.write { transaction in
let thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, self.tsAccountManager.localAddress!],
let thread = try! GroupManager.createGroupForTests(members: [self.aliceRecipient, self.bobRecipient, DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)!.aciAddress],
name: "Perf",
transaction: transaction)

View File

@ -17,7 +17,16 @@ class GRDBFinderTest: SignalBaseTest {
// ensure local client has necessary "registered" state
let localE164Identifier = "+13235551234"
let localUUID = UUID()
tsAccountManager.registerForTests(withLocalNumber: localE164Identifier, uuid: localUUID)
databaseStorage.write { tx in
(DependenciesBridge.shared.registrationStateChangeManager as! RegistrationStateChangeManagerImpl).registerForTests(
localIdentifiers: .init(
aci: .init(fromUUID: localUUID),
pni: nil,
e164: E164(localE164Identifier)!
),
tx: tx.asV2Write
)
}
}
func testThreadFinder() {

View File

@ -12,7 +12,12 @@ class UserProfileTest: SignalBaseTest {
override func setUp() {
super.setUp()
// Create local account.
tsAccountManager.registerForTests(localIdentifiers: .forUnitTests)
databaseStorage.write { tx in
(DependenciesBridge.shared.registrationStateChangeManager as! RegistrationStateChangeManagerImpl).registerForTests(
localIdentifiers: .forUnitTests,
tx: tx.asV2Write
)
}
}
func testUserProfileForAci() {

View File

@ -51,7 +51,7 @@ public class IncomingContactSyncJobQueue: NSObject, JobQueue {
}
public func buildOperation(jobRecord: IncomingContactSyncJobRecord, transaction: SDSAnyReadTransaction) throws -> IncomingContactSyncOperation {
guard let localIdentifiers = tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Not registered.")
}
return IncomingContactSyncOperation(jobRecord: jobRecord, localIdentifiers: localIdentifiers)

View File

@ -513,7 +513,7 @@ public class NotificationPresenter: NSObject, NotificationsProtocolSwift {
return false
}
let localAci = tsAccountManager.localIdentifiers(transaction: transaction)?.aci
let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aci
// Always notify for replies to group stories you sent
if storyAuthorAci == localAci { return true }
@ -535,7 +535,7 @@ public class NotificationPresenter: NSObject, NotificationsProtocolSwift {
guard thread.isGroupThread else { return false }
guard let localAddress = TSAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing local address")
return false
}
@ -1166,7 +1166,7 @@ public class NotificationPresenter: NSObject, NotificationsProtocolSwift {
// Use a default sound so we don't read from
// the db (which doesn't work until we relaunch)
sound: .standard(.note),
forceBeforeOnboarded: true,
forceBeforeRegistered: true,
completion: {
innerCompletion()
completion?()

View File

@ -185,13 +185,13 @@ class UserNotificationPresenter: Dependencies {
interaction: INInteraction?,
sound: Sound?,
replacingIdentifier: String? = nil,
forceBeforeOnboarded: Bool = false,
forceBeforeRegistered: Bool = false,
completion: NotificationActionCompletion?
) {
dispatchPrecondition(condition: .onQueue(notifyQueue))
guard forceBeforeOnboarded || tsAccountManager.isOnboarded else {
Logger.info("suppressing notification since user hasn't yet completed onboarding.")
guard forceBeforeRegistered || DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
Logger.info("suppressing notification since user hasn't yet completed registration.")
completion?()
return
}

View File

@ -166,9 +166,11 @@ public class PaymentsCurrenciesImpl: NSObject, PaymentsCurrenciesSwift, Payments
private let isUpdateInFlight = AtomicBool(false)
func updateConversationRates() {
guard AppReadiness.isAppReady,
CurrentAppContext().isMainAppAndActive,
Self.tsAccountManager.isRegisteredAndReady else {
guard
AppReadiness.isAppReady,
CurrentAppContext().isMainAppAndActive,
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered
else {
return
}
guard Self.paymentsHelper.arePaymentsEnabled else {

View File

@ -31,10 +31,10 @@ public class PaymentsHelperImpl: Dependencies, PaymentsHelperSwift, PaymentsHelp
}
public var hasValidPhoneNumberForPayments: Bool {
guard Self.tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return false
}
guard let localNumber = Self.tsAccountManager.localNumber else {
guard let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.phoneNumber else {
return false
}
let paymentsDisabledRegions = RemoteConfig.paymentsDisabledRegions
@ -203,7 +203,7 @@ public class PaymentsHelperImpl: Dependencies, PaymentsHelperSwift, PaymentsHelp
paymentsEvents.updateLastKnownLocalPaymentAddressProtoData(transaction: transaction)
let localAci = self.tsAccountManager.localIdentifiers(transaction: transaction)?.aci
let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aci
TSPaymentsActivationRequestModel
.allThreadsWithPaymentActivationRequests(transaction: transaction)
.forEach { thread in
@ -248,7 +248,7 @@ public class PaymentsHelperImpl: Dependencies, PaymentsHelperSwift, PaymentsHelp
}
private static func loadPaymentsState(transaction: SDSAnyReadTransaction) -> PaymentsState {
guard tsAccountManager.isRegisteredAndReady(transaction: transaction) else {
guard DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isRegistered else {
return .disabled
}
let paymentsEntropy = keyValueStore.getData(paymentsEntropyKey, transaction: transaction)
@ -344,7 +344,7 @@ public class PaymentsHelperImpl: Dependencies, PaymentsHelperSwift, PaymentsHelp
if
Self.loadPaymentsState(transaction: transaction).isEnabled
{
if self.tsAccountManager.isPrimaryDevice(transaction: transaction) {
if DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isPrimaryDevice ?? false {
let message = OWSPaymentActivationRequestFinishedMessage(thread: thread, transaction: transaction)
Self.sskJobQueues.messageSenderJobQueue.add(message: message.asPreparer, transaction: transaction)
}
@ -506,7 +506,7 @@ public class PaymentsHelperImpl: Dependencies, PaymentsHelperSwift, PaymentsHelp
if
paymentType == .outgoingPaymentFromLinkedDevice,
let recipientAci,
recipientAci != tsAccountManager.localIdentifiers(transaction: transaction)?.aci
recipientAci != DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aci
{
let thread = TSContactThread.getOrCreateThread(
withContactAddress: SignalServiceAddress(recipientAci),

View File

@ -42,7 +42,7 @@ public class StorageServiceManagerImpl: NSObject, StorageServiceManager {
}
AppReadiness.runNowOrWhenMainAppDidBecomeReadyAsync {
guard self.tsAccountManager.isRegisteredAndReady else { return }
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else { return }
// Schedule a restore. This will do nothing unless we've never
// registered a manifest before.
@ -219,7 +219,7 @@ public class StorageServiceManagerImpl: NSObject, StorageServiceManager {
case .implicit:
// Under the new reg flow, we will sync kbs keys before being fully ready with
// ts account manager auth set up. skip if so.
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredOrFinishingProvisioning else {
Logger.info("Skipping storage service operation with implicit auth during registration.")
return nil
}
@ -721,7 +721,7 @@ class StorageServiceOperation: OWSOperation {
let identifiers = StorageService.StorageIdentifier.deduplicate(identifiersParam)
var manifestBuilder = StorageServiceProtoManifestRecord.builder(version: manifestVersion)
manifestBuilder.setKeys(try identifiers.map { try $0.buildRecord() })
manifestBuilder.setSourceDevice(tsAccountManager.storedDeviceId)
manifestBuilder.setSourceDevice(DependenciesBridge.shared.tsAccountManager.storedDeviceIdWithMaybeTransaction)
return try manifestBuilder.build()
}
@ -762,7 +762,7 @@ class StorageServiceOperation: OWSOperation {
if case .manifestDecryptionFailed(let previousManifestVersion) = storageError {
// If this is the primary device, throw everything away and re-encrypt
// the social graph with the keys we have locally.
if TSAccountManager.shared.isPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice {
Logger.info("Manifest decryption failed, recreating manifest.")
return self.createNewManifest(version: previousManifestVersion + 1)
}
@ -783,7 +783,7 @@ class StorageServiceOperation: OWSOperation {
}
} else if
case .manifestProtoDeserializationFailed(let previousManifestVersion) = storageError,
TSAccountManager.shared.isPrimaryDevice
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice
{
// If decryption succeeded but proto deserialization failed, we somehow ended up with
// byte garbage in storage service. Our only recourse is to throw everything away and
@ -1139,7 +1139,7 @@ class StorageServiceOperation: OWSOperation {
if case .itemDecryptionFailed = storageError {
// If this is the primary device, throw everything away and re-encrypt
// the social graph with the keys we have locally.
if TSAccountManager.shared.isPrimaryDevice {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice {
Logger.info("Item decryption failed, recreating manifest.")
return self.createNewManifest(version: manifest.version + 1)
}
@ -1160,7 +1160,7 @@ class StorageServiceOperation: OWSOperation {
}
} else if
case .itemProtoDeserializationFailed = storageError,
TSAccountManager.shared.isPrimaryDevice
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice
{
// If decryption succeeded but proto deserialization failed, we somehow ended up with
// byte garbage in storage service. Our only recourse is to throw everything away and
@ -1439,13 +1439,15 @@ class StorageServiceOperation: OWSOperation {
legacyChangePhoneNumber: legacyChangePhoneNumber,
localUsernameManager: DependenciesBridge.shared.localUsernameManager,
paymentsHelper: paymentsHelperSwift,
phoneNumberDiscoverabilityManager: DependenciesBridge.shared.phoneNumberDiscoverabilityManager,
preferences: preferences,
profileManager: profileManagerImpl,
receiptManager: receiptManager,
registrationStateChangeManager: DependenciesBridge.shared.registrationStateChangeManager,
storageServiceManager: storageServiceManager,
subscriptionManager: subscriptionManager,
systemStoryManager: systemStoryManager,
tsAccountManager: tsAccountManager,
tsAccountManager: DependenciesBridge.shared.tsAccountManager,
typingIndicators: typingIndicatorsImpl,
udManager: udManager,
usernameEducationManager: DependenciesBridge.shared.usernameEducationManager
@ -1466,7 +1468,7 @@ class StorageServiceOperation: OWSOperation {
contactsManager: contactsManagerImpl,
identityManager: DependenciesBridge.shared.identityManager,
profileManager: profileManagerImpl,
tsAccountManager: tsAccountManager,
tsAccountManager: DependenciesBridge.shared.tsAccountManager,
usernameLookupManager: DependenciesBridge.shared.usernameLookupManager,
recipientMerger: DependenciesBridge.shared.recipientMerger,
recipientHidingManager: DependenciesBridge.shared.recipientHidingManager

View File

@ -175,7 +175,7 @@ class StorageServiceContactRecordUpdater: StorageServiceRecordUpdater {
private let contactsManager: OWSContactsManager
private let identityManager: OWSIdentityManager
private let profileManager: OWSProfileManager
private let tsAccountManager: TSAccountManager
private let tsAccountManager: TSAccountManagerProtocol
private let usernameLookupManager: UsernameLookupManager
private let recipientMerger: RecipientMerger
private let recipientHidingManager: RecipientHidingManager
@ -188,7 +188,7 @@ class StorageServiceContactRecordUpdater: StorageServiceRecordUpdater {
contactsManager: OWSContactsManager,
identityManager: OWSIdentityManager,
profileManager: OWSProfileManager,
tsAccountManager: TSAccountManager,
tsAccountManager: TSAccountManagerProtocol,
usernameLookupManager: UsernameLookupManager,
recipientMerger: RecipientMerger,
recipientHidingManager: RecipientHidingManager
@ -296,8 +296,9 @@ class StorageServiceContactRecordUpdater: StorageServiceRecordUpdater {
// case, we want to preserve the name the primary device
// originally uploaded.
let isPrimaryAndHasLocalContact = tsAccountManager.isPrimaryDevice && contact.isFromLocalAddressBook
let isLinkedAndHasSyncedContact = !tsAccountManager.isPrimaryDevice && !contact.isFromLocalAddressBook
let isPrimary = tsAccountManager.registrationState(tx: transaction.asV2Read).isPrimaryDevice ?? false
let isPrimaryAndHasLocalContact = isPrimary && contact.isFromLocalAddressBook
let isLinkedAndHasSyncedContact = !isPrimary && !contact.isFromLocalAddressBook
if isPrimaryAndHasLocalContact || isLinkedAndHasSyncedContact {
if let systemGivenName = contact.firstName {
@ -566,7 +567,7 @@ class StorageServiceContactRecordUpdater: StorageServiceRecordUpdater {
let localAccount = contactsManager.fetchSignalAccount(for: address, transaction: transaction)
if tsAccountManager.isPrimaryDevice {
if tsAccountManager.registrationState(tx: transaction.asV2Read).isPrimaryDevice ?? false {
let localContact = localAccount?.contact?.isFromLocalAddressBook == true ? localAccount?.contact : nil
let localSystemGivenName = localContact?.firstName?.nilIfEmpty
let localSystemFamilyName = localContact?.lastName?.nilIfEmpty
@ -918,13 +919,15 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
private let legacyChangePhoneNumber: LegacyChangePhoneNumber
private let localUsernameManager: LocalUsernameManager
private let paymentsHelper: PaymentsHelperSwift
private let phoneNumberDiscoverabilityManager: PhoneNumberDiscoverabilityManager
private let preferences: Preferences
private let profileManager: OWSProfileManager
private let receiptManager: OWSReceiptManager
private let registrationStateChangeManager: RegistrationStateChangeManager
private let storageServiceManager: StorageServiceManager
private let subscriptionManager: SubscriptionManager
private let systemStoryManager: SystemStoryManagerProtocol
private let tsAccountManager: TSAccountManager
private let tsAccountManager: TSAccountManagerProtocol
private let typingIndicators: TypingIndicators
private let udManager: OWSUDManager
private let usernameEducationManager: UsernameEducationManager
@ -936,13 +939,15 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
legacyChangePhoneNumber: LegacyChangePhoneNumber,
localUsernameManager: LocalUsernameManager,
paymentsHelper: PaymentsHelperSwift,
phoneNumberDiscoverabilityManager: PhoneNumberDiscoverabilityManager,
preferences: Preferences,
profileManager: OWSProfileManager,
receiptManager: OWSReceiptManager,
registrationStateChangeManager: RegistrationStateChangeManager,
storageServiceManager: StorageServiceManager,
subscriptionManager: SubscriptionManager,
systemStoryManager: SystemStoryManagerProtocol,
tsAccountManager: TSAccountManager,
tsAccountManager: TSAccountManagerProtocol,
typingIndicators: TypingIndicators,
udManager: OWSUDManager,
usernameEducationManager: UsernameEducationManager
@ -953,9 +958,11 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
self.legacyChangePhoneNumber = legacyChangePhoneNumber
self.localUsernameManager = localUsernameManager
self.paymentsHelper = paymentsHelper
self.phoneNumberDiscoverabilityManager = phoneNumberDiscoverabilityManager
self.preferences = preferences
self.profileManager = profileManager
self.receiptManager = receiptManager
self.registrationStateChangeManager = registrationStateChangeManager
self.storageServiceManager = storageServiceManager
self.subscriptionManager = subscriptionManager
self.systemStoryManager = systemStoryManager
@ -1050,7 +1057,7 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
let phoneNumberSharingMode = udManager.phoneNumberSharingMode(tx: transaction)
builder.setPhoneNumberSharingMode(phoneNumberSharingMode.asProtoMode)
let notDiscoverableByPhoneNumber = !tsAccountManager.isDiscoverableByPhoneNumber(with: transaction)
let notDiscoverableByPhoneNumber = !tsAccountManager.isDiscoverableByPhoneNumber(tx: transaction.asV2Read)
builder.setNotDiscoverableByPhoneNumber(notDiscoverableByPhoneNumber)
let pinnedConversationProtos = PinnedThreadManager.pinnedConversationProtos(transaction: transaction)
@ -1140,7 +1147,8 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
// allows us to restore your profile during onboarding,
// but ensures no other device can ever change the profile
// key other than the primary device.
let allowsRemoteProfileKeyChanges = !profileManager.hasLocalProfile() || !tsAccountManager.isPrimaryDevice
let isPrimary = tsAccountManager.registrationState(tx: transaction.asV2Read).isPrimaryDevice ?? false
let allowsRemoteProfileKeyChanges = !profileManager.hasLocalProfile() || !isPrimary
if allowsRemoteProfileKeyChanges, let profileKey = record.profileKey, localProfileKey?.keyData != profileKey {
profileManager.setProfileKeyData(
profileKey,
@ -1257,13 +1265,13 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
}
}
let localNotDiscoverableByPhoneNumber = !tsAccountManager.isDiscoverableByPhoneNumber(with: transaction)
if record.notDiscoverableByPhoneNumber != localNotDiscoverableByPhoneNumber || !tsAccountManager.hasDefinedIsDiscoverableByPhoneNumber(with: transaction) {
tsAccountManager.setIsDiscoverableByPhoneNumber(
let localNotDiscoverableByPhoneNumber = !tsAccountManager.isDiscoverableByPhoneNumber(tx: transaction.asV2Read)
if record.notDiscoverableByPhoneNumber != localNotDiscoverableByPhoneNumber || !tsAccountManager.hasDefinedIsDiscoverableByPhoneNumber(tx: transaction.asV2Read) {
phoneNumberDiscoverabilityManager.setIsDiscoverableByPhoneNumber(
!record.notDiscoverableByPhoneNumber,
updateStorageService: false,
authedAccount: authedAccount,
transaction: transaction
tx: transaction.asV2Write
)
}
@ -1368,7 +1376,7 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
if localAddress.e164 != serviceLocalE164 {
Logger.warn("localAddress.e164: \(String(describing: localAddress.e164)) != serviceLocalE164: \(serviceLocalE164)")
if tsAccountManager.isPrimaryDevice(transaction: transaction) {
if tsAccountManager.registrationState(tx: transaction.asV2Read).isPrimaryDevice ?? false {
// It's not clear how we got into this scenario, but if we
// do it's bad. Once all clients are PNI-capable we can
// ignore the AccountRecord's e164 entirely, and remove
@ -1389,14 +1397,14 @@ class StorageServiceAccountRecordUpdater: StorageServiceRecordUpdater {
// the primary needs to update the storage service.
self.storageServiceManager.recordPendingLocalAccountUpdates()
}
} else if let localIdentifiers = tsAccountManager.localIdentifiers(transaction: transaction) {
} else if let localIdentifiers = tsAccountManager.localIdentifiers(tx: transaction.asV2Read) {
// If we're a linked device, we should always take the e164
// from StorageService.
tsAccountManager.updateLocalPhoneNumber(
E164ObjC(serviceLocalE164),
aci: AciObjC(localIdentifiers.aci),
pni: localIdentifiers.pni.map { PniObjC($0) },
transaction: transaction
registrationStateChangeManager.didUpdateLocalPhoneNumber(
serviceLocalE164,
aci: localIdentifiers.aci,
pni: localIdentifiers.pni,
tx: transaction.asV2Write
)
} else {
owsFailDebug("Linked device missing local ACI!")

View File

@ -743,7 +743,7 @@ public class SubscriptionManagerImpl: NSObject {
Logger.info("[Donations] Performing subscription heartbeat")
guard tsAccountManager.isPrimaryDevice else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? false else {
Logger.info("[Donations] Bailing out of remaining heartbeat tasks, this is not the primary device")
return
}

View File

@ -86,7 +86,7 @@ NSString *const OWSContactsManagerCollection = @"OWSContactsManagerCollection";
- (BOOL)isEditingAllowed
{
return self.tsAccountManager.isPrimaryDevice;
return [TSAccountManagerObjcBridge isPrimaryDeviceWithMaybeTransaction];
}
- (ContactAuthorizationForEditing)editingAuthorization

View File

@ -193,7 +193,7 @@ private extension OWSContactsManager {
return cachedValue
}
let result: Bool = {
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aciAddress else {
owsFailDebug("Missing localAddress.")
return false
}
@ -768,7 +768,7 @@ extension OWSContactsManager {
allSignalAccountsBeforeFetch: [SignalServiceAddress: SignalAccount],
allSignalAccountsAfterFetch: [SignalServiceAddress: SignalAccount]
) {
guard tsAccountManager.isPrimaryDevice else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? false else {
Logger.info("Skipping updating StorageService on contact change, not primary device!")
return
}
@ -862,7 +862,7 @@ extension OWSContactsManager {
private func _updateContacts(_ addressBookContacts: [Contact]?, isUserRequested: Bool) {
let (localNumber, contactsMaps) = databaseStorage.write { tx in
let localNumber = tsAccountManager.localNumber(with: tx)
let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: tx.asV2Read)?.phoneNumber
let contactsMaps = ContactsMaps.build(contacts: addressBookContacts ?? [], localNumber: localNumber)
setContactsMaps(contactsMaps, localNumber: localNumber, transaction: tx)
return (localNumber, contactsMaps)
@ -1185,12 +1185,13 @@ extension OWSContactsManager {
}
private func updateSystemContactsDataProvider(forcePrimary: Bool = false) {
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction
let dataProvider: SystemContactsDataProvider?
if forcePrimary {
dataProvider = PrimaryDeviceSystemContactsDataProvider()
} else if !tsAccountManager.isRegistered {
} else if !tsRegistrationState.isRegistered {
dataProvider = nil
} else if tsAccountManager.isPrimaryDevice {
} else if tsRegistrationState.isPrimaryDevice ?? true {
dataProvider = PrimaryDeviceSystemContactsDataProvider()
} else {
dataProvider = LinkedDeviceSystemContactsDataProvider()
@ -1237,7 +1238,7 @@ extension OWSContactsManager {
transaction: SDSAnyReadTransaction
) -> ContactsMaps {
let systemContacts = dataProvider.fetchAllSystemContacts(transaction: transaction)
let localNumber = tsAccountManager.localNumber(with: transaction)
let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.phoneNumber
return ContactsMaps.build(contacts: systemContacts, localNumber: localNumber)
}
@ -1274,7 +1275,7 @@ extension OWSContactsManager {
owsFailDebug("Can't access contacts until registration is finished.")
return []
}
let localNumber = tsAccountManager.localNumber(with: transaction)
let localNumber = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.phoneNumber
return dataProvider.fetchAllSystemContacts(transaction: transaction)
.filter { !$0.hasPhoneNumber(localNumber) }
}

View File

@ -61,11 +61,11 @@ NSString *const OWSSyncManagerSyncRequestedAppVersionKey = @"SyncRequestedAppVer
AppReadinessRunNowOrWhenMainAppDidBecomeReadyAsync(^{
[self addObservers];
if ([self.tsAccountManager isRegisteredAndReady]) {
if ([TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
OWSAssertDebug(self.contactsManagerImpl.isSetup);
if (self.tsAccountManager.isPrimaryDevice) {
if ([TSAccountManagerObjcBridge isPrimaryDeviceWithMaybeTransaction]) {
// Flush any pending changes.
//
// sendSyncContactsMessageIfNecessary will skipIfRedundant,
@ -141,10 +141,7 @@ NSString *const OWSSyncManagerSyncRequestedAppVersionKey = @"SyncRequestedAppVer
// Don't bother if the contacts manager hasn't finished setup.
return NO;
}
if (!self.tsAccountManager.isRegisteredAndReady) {
return NO;
}
if (!self.tsAccountManager.isRegisteredPrimaryDevice) {
if (![TSAccountManagerObjcBridge isRegisteredPrimaryDeviceWithMaybeTransaction]) {
return NO;
}
return YES;
@ -152,7 +149,7 @@ NSString *const OWSSyncManagerSyncRequestedAppVersionKey = @"SyncRequestedAppVer
- (void)sendConfigurationSyncMessage {
AppReadinessRunNowOrWhenAppDidBecomeReadyAsync(^{
if (!self.tsAccountManager.isRegisteredAndReady) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
return;
}
@ -165,7 +162,7 @@ NSString *const OWSSyncManagerSyncRequestedAppVersionKey = @"SyncRequestedAppVer
- (void)sendConfigurationSyncMessage_AppReady {
OWSLogInfo(@"");
if (!self.tsAccountManager.isRegisteredAndReady) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
return;
}
@ -329,7 +326,8 @@ typedef NS_ENUM(NSUInteger, OWSContactSyncMode) {
}
// This might create a transaction -- call it outside of our own transaction.
SignalServiceAddress *const localAddress = self.tsAccountManager.localAddress;
SignalServiceAddress *const localAddress =
[TSAccountManagerObjcBridge localAciAddressWithMaybeTransaction];
__block NSString *fullSyncRequestId;
__block BOOL fullSyncRequired = YES;
@ -516,7 +514,7 @@ typedef NS_ENUM(NSUInteger, OWSContactSyncMode) {
{
OWSLogInfo(@"");
if (!self.tsAccountManager.isRegisteredAndReady) {
if (![TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
OWSFailDebug(@"Unexpectedly tried to send sync message before registration.");
return;
}

View File

@ -23,7 +23,7 @@ extension OWSSyncManager: SyncManagerProtocol, SyncManagerProtocolSwift {
}
private func _sendAllSyncRequestMessages(onlyIfNecessary: Bool) -> Promise<Void> {
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return Promise(error: OWSAssertionError("Unexpectedly tried to send sync request before registration."))
}
@ -65,11 +65,11 @@ extension OWSSyncManager: SyncManagerProtocol, SyncManagerProtocolSwift {
public func sendKeysSyncMessage() {
Logger.info("")
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return owsFailDebug("Unexpectedly tried to send sync request before registration.")
}
guard tsAccountManager.isRegisteredPrimaryDevice else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? false else {
return owsFailDebug("Keys sync should only be initiated from the primary device")
}
@ -92,7 +92,7 @@ extension OWSSyncManager: SyncManagerProtocol, SyncManagerProtocolSwift {
@objc
public func processIncomingKeysSyncMessage(_ syncMessage: SSKProtoSyncMessageKeys, transaction: SDSAnyWriteTransaction) {
guard !tsAccountManager.isRegisteredPrimaryDevice else {
guard !DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isRegisteredPrimaryDevice else {
return owsFailDebug("Key sync messages should only be processed on linked devices")
}
@ -161,7 +161,7 @@ extension OWSSyncManager: SyncManagerProtocol, SyncManagerProtocolSwift {
public func sendMessageRequestResponseSyncMessage(thread: TSThread, responseType: OWSSyncMessageRequestResponseType) {
Logger.info("")
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return owsFailDebug("Unexpectedly tried to send sync message before registration.")
}
@ -177,7 +177,7 @@ extension OWSSyncManager: SyncManagerProtocol, SyncManagerProtocolSwift {
) {
Logger.info("")
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isRegistered else {
return owsFailDebug("Unexpectedly tried to send sync message before registration.")
}
@ -192,7 +192,7 @@ public extension OWSSyncManager {
func sendInitialSyncRequestsAwaitingCreatedThreadOrdering(timeoutSeconds: TimeInterval) -> Promise<[String]> {
Logger.info("")
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return Promise(error: OWSAssertionError("Unexpectedly tried to send sync request before registration."))
}
@ -238,11 +238,11 @@ public extension OWSSyncManager {
Logger.info("keys")
}
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return owsFailDebug("Unexpectedly tried to send sync request before registration.")
}
guard !tsAccountManager.isRegisteredPrimaryDevice else {
guard !DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice else {
return owsFailDebug("Sync request should only be sent from a linked device")
}

View File

@ -112,7 +112,7 @@ public class AppSetup {
// MARK: SSK environment properties
let appExpiry = DependenciesBridge.shared.appExpiry
let appExpiry = dependenciesBridge.appExpiry
let contactsManager = OWSContactsManager(swiftValues: .makeWithValuesFromDependenciesBridge())
let linkPreviewManager = OWSLinkPreviewManager()
let pendingReceiptRecorder = MessageRequestPendingReceipts()
@ -121,8 +121,8 @@ public class AppSetup {
let remoteConfigManager = ServiceRemoteConfigManager(
appExpiry: appExpiry,
db: DependenciesBridge.shared.db,
keyValueStoreFactory: DependenciesBridge.shared.keyValueStoreFactory,
tsAccountManager: tsAccountManager,
keyValueStoreFactory: dependenciesBridge.keyValueStoreFactory,
tsAccountManager: dependenciesBridge.tsAccountManager,
serviceClient: SignalServiceRestClient.shared
)
let messageDecrypter = OWSMessageDecrypter()
@ -140,7 +140,7 @@ public class AppSetup {
let bulkProfileFetch = BulkProfileFetch(
databaseStorage: databaseStorage,
reachabilityManager: reachabilityManager,
tsAccountManager: tsAccountManager
tsAccountManager: dependenciesBridge.tsAccountManager
)
let earlyMessageManager = EarlyMessageManager()
let messagePipelineSupervisor = MessagePipelineSupervisor()
@ -157,7 +157,7 @@ public class AppSetup {
recipientFetcher: dependenciesBridge.recipientFetcher,
recipientMerger: dependenciesBridge.recipientMerger,
recipientStore: dependenciesBridge.recipientStore,
tsAccountManager: tsAccountManager,
tsAccountManager: dependenciesBridge.tsAccountManager,
udManager: udManager,
websocketFactory: webSocketFactory
)

View File

@ -43,7 +43,7 @@ public class GroupV2UpdatesImpl: Dependencies {
// On launch, we refresh a few randomly-selected groups.
private func autoRefreshGroupOnLaunch() {
guard CurrentAppContext().isMainApp,
tsAccountManager.isRegisteredAndReady,
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered,
reachabilityManager.isReachable,
!CurrentAppContext().isRunningTests else {
return
@ -166,7 +166,7 @@ extension GroupV2UpdatesImpl: GroupV2UpdatesSwift {
guard groupThread.groupModel.groupsVersion == .V2 else {
throw OWSAssertionError("Invalid groupsVersion.")
}
guard let localIdentifiers = tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Not registered.")
}
let changedGroupModel = try GroupsV2IncomingChanges.applyChangesToGroupModel(
@ -637,7 +637,7 @@ private extension GroupV2UpdatesImpl {
groupModelOptions: TSGroupModelOptions
) -> Promise<TSGroupThread> {
return databaseStorage.write(.promise) { (transaction: SDSAnyWriteTransaction) throws -> TSGroupThread in
guard let localIdentifiers = Self.tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Missing localIdentifiers.")
}
@ -1020,7 +1020,7 @@ private extension GroupV2UpdatesImpl {
let localProfileKey = profileManager.localProfileKey()
return databaseStorage.write(.promise) { (transaction: SDSAnyWriteTransaction) throws -> TSGroupThread in
guard let localIdentifiers = Self.tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Missing localIdentifiers.")
}
let localAci = localIdentifiers.aci

View File

@ -111,7 +111,7 @@ public extension GroupsV2Impl {
case .explicit:
break
case .implicit:
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return false
}
}

View File

@ -23,7 +23,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
// if we've just reset the zkgroup state, since that
// have the same effect.
guard !didReset,
self.tsAccountManager.isRegisteredAndReady else {
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return
}
@ -81,7 +81,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
self.serviceStore.setInt(zkgroupVersionCounter, key: lastZKgroupVersionCounterKey, transaction: transaction)
}
AppReadiness.runNowOrWhenAppDidBecomeReadyAsync {
if self.tsAccountManager.isRegisteredAndReady {
if DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered {
Logger.info("Re-uploading local profile due to zkgroup update.")
firstly {
self.reuploadLocalProfilePromise()
@ -205,7 +205,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
groupV2Params: GroupV2Params,
shouldForceRefreshProfileKeyCredentials: Bool = false
) -> Promise<GroupsProtoGroup> {
guard let localAci = tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
return Promise(error: OWSAssertionError("Missing localAci."))
}
@ -1084,7 +1084,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
behavior404: Behavior404,
remainingRetries: UInt = 3
) -> Promise<HTTPResponse> {
guard let localIdentifiers = tsAccountManager.localIdentifiers else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction else {
return Promise(error: OWSAssertionError("Missing localIdentifiers."))
}
@ -1932,7 +1932,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
self.groupV2Updates.tryToRefreshV2GroupUpToCurrentRevisionImmediately(groupId: groupId,
groupSecretParamsData: groupV2Params.groupSecretParamsData)
}.then(on: DispatchQueue.global()) { (groupThread: TSGroupThread) -> Promise<TSGroupThread> in
guard let localAci = self.tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
throw OWSAssertionError("Missing localAci.")
}
guard let groupModelV2 = groupThread.groupModel as? TSGroupModelV2 else {
@ -2069,7 +2069,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
throw OWSAssertionError("Missing revisionForPlaceholderModel.")
}
return try databaseStorage.write { (transaction) throws -> TSGroupThread in
guard let localIdentifiers = Self.tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Missing localIdentifiers.")
}
@ -2168,7 +2168,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
groupV2Params: GroupV2Params,
revisionForPlaceholderModel: AtomicOptional<UInt32>) -> Promise<GroupsProtoGroupChangeActions> {
guard let localAci = self.tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
return Promise(error: OWSAssertionError("Missing localAci."))
}
@ -2261,7 +2261,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
newRevision proposedRevision: UInt32?
) throws -> TSGroupThread {
return try databaseStorage.write { transaction -> TSGroupThread in
guard let localIdentifiers = self.tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Missing localIdentifiers.")
}
TSGroupThread.ensureGroupIdMapping(forGroupId: groupId, transaction: transaction)
@ -2362,7 +2362,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
revisionForPlaceholderModel: AtomicOptional<UInt32>) -> Promise<GroupsProtoGroupChangeActions> {
return firstly(on: DispatchQueue.global()) { () -> GroupsProtoGroupChangeActions in
guard let localAci = self.tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
throw OWSAssertionError("Missing localAci.")
}
let oldRevision = groupInviteLinkPreview.revision
@ -2417,7 +2417,7 @@ public class GroupsV2Impl: GroupsV2Swift, GroupsV2, Dependencies {
firstly(on: DispatchQueue.global()) {
let groupId = try self.groupId(forGroupSecretParamsData: groupSecretParamsData)
try self.databaseStorage.write { transaction in
guard let localIdentifiers = self.tsAccountManager.localIdentifiers(transaction: transaction) else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read) else {
throw OWSAssertionError("Missing localIdentifiers.")
}
TSGroupThread.ensureGroupIdMapping(forGroupId: groupId, transaction: transaction)

View File

@ -246,7 +246,7 @@ public class GroupsV2OutgoingChangesImpl: Dependencies, GroupsV2OutgoingChanges
guard groupId == currentGroupModel.groupId else {
return Promise(error: OWSAssertionError("Mismatched groupId."))
}
guard let localAci = tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
return Promise(error: OWSAssertionError("Missing localAci."))
}
@ -319,7 +319,7 @@ public class GroupsV2OutgoingChangesImpl: Dependencies, GroupsV2OutgoingChanges
let groupV2Params = try currentGroupModel.groupV2Params()
var actionsBuilder = GroupsProtoGroupChangeActions.builder()
guard let localIdentifiers = tsAccountManager.localIdentifiers else {
guard let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction else {
throw OWSAssertionError("Missing local identifiers!")
}

View File

@ -88,12 +88,13 @@ class GroupsV2ProfileKeyUpdater: Dependencies {
private func tryToScheduleGroupForProfileKeyUpdate(groupThread: TSGroupThread,
transaction: SDSAnyWriteTransaction) {
guard !CurrentAppContext().isRunningTests,
tsAccountManager.isRegisteredAndReady,
tsAccountManager.isPrimaryDevice else {
guard
!CurrentAppContext().isRunningTests,
DependenciesBridge.shared.tsAccountManager.registrationState(tx: transaction.asV2Read).isRegisteredPrimaryDevice
else {
return
}
guard let localAddress = tsAccountManager.localAddress else {
guard let localAddress = DependenciesBridge.shared.tsAccountManager.localIdentifiers(tx: transaction.asV2Read)?.aciAddress else {
owsFailDebug("missing local address")
return
}
@ -119,10 +120,11 @@ class GroupsV2ProfileKeyUpdater: Dependencies {
private var isUpdating = false
private func tryToUpdateNext(retryDelay: TimeInterval = 1) {
guard CurrentAppContext().isMainAppAndActive,
!CurrentAppContext().isRunningTests,
tsAccountManager.isRegisteredAndReady,
tsAccountManager.isPrimaryDevice else {
guard
CurrentAppContext().isMainAppAndActive,
!CurrentAppContext().isRunningTests,
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice
else {
return
}
guard reachabilityManager.isReachable else {
@ -216,7 +218,7 @@ class GroupsV2ProfileKeyUpdater: Dependencies {
private func tryToUpdate(groupId: Data) -> Promise<Void> {
let profileKeyData = profileManager.localProfileKey().keyData
guard let localAci = tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
owsFailDebug("missing local address")
return Promise(error: GroupsV2Error.shouldDiscard)
}

View File

@ -107,15 +107,15 @@ NSString *const kNSNotificationKey_UserProfileWriter = @"kNSNotificationKey_User
OWSSingletonAssert();
AppReadinessRunNowOrWhenAppDidBecomeReadySync(^{
if (CurrentAppContext().isMainApp && !CurrentAppContext().isRunningTests
&& TSAccountManager.shared.isRegistered) {
if (CurrentAppContext().isMainApp && !CurrentAppContext().isRunningTests &&
[TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
[self logLocalAvatarStatus];
[self fetchLocalUsersProfileWithAuthedAccount:AuthedAccount.implicit];
}
});
AppReadinessRunNowOrWhenAppDidBecomeReadyAsync(^{
if (TSAccountManager.shared.isRegistered) {
if ([TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]) {
[self rotateLocalProfileKeyIfNecessary];
[self updateProfileOnServiceIfNecessaryWithAuthedAccount:AuthedAccount.implicit];
[OWSProfileManager updateStorageServiceIfNecessary];
@ -149,7 +149,7 @@ NSString *const kNSNotificationKey_UserProfileWriter = @"kNSNotificationKey_User
{
OWSAssertDebug(CurrentAppContext().isMainApp);
OWSAssertDebug(!CurrentAppContext().isRunningTests);
OWSAssertDebug(TSAccountManager.shared.isRegistered);
OWSAssertDebug([TSAccountManagerObjcBridge isRegisteredWithMaybeTransaction]);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self logLocalAvatarStatus:self.localUserProfile label:@"cached copy"];
@ -430,7 +430,7 @@ NSString *const kNSNotificationKey_UserProfileWriter = @"kNSNotificationKey_User
if (authAddress != nil) {
localAddress = authAddress;
} else {
localAddress = self.tsAccountManager.localAddress;
localAddress = [TSAccountManagerObjcBridge localAciAddressWithMaybeTransaction];
}
if (!localAddress.isValid) {
return;
@ -445,7 +445,12 @@ NSString *const kNSNotificationKey_UserProfileWriter = @"kNSNotificationKey_User
- (AnyPromise *)fetchLocalUsersProfilePromiseWithAuthedAccount:(AuthedAccount *)authedAccount
{
ServiceIdObjC *_Nullable localAci = self.tsAccountManager.localAddress.serviceIdObjC;
LocalIdentifiersObjC *_Nullable localIdentifiers =
[TSAccountManagerObjcBridge localIdentifiersWithMaybeTransaction];
if (!localIdentifiers) {
return [AnyPromise promiseWithError:OWSErrorMakeAssertionError(@"Missing local address.")];
}
ServiceIdObjC *localAci = localIdentifiers.aci;
if (![localAci isKindOfClass:[AciObjC class]]) {
return [AnyPromise promiseWithError:OWSErrorMakeAssertionError(@"Missing local address.")];
}
@ -544,9 +549,8 @@ NSString *const kNSNotificationKey_UserProfileWriter = @"kNSNotificationKey_User
transaction:transaction
completion:nil];
});
[self.tsAccountManager updateAccountAttributes].catch(^(NSError *error) {
OWSLogError(@"Error: %@.", error);
});
[AccountAttributesUpdaterObjcBridge updateAccountAttributes].catch(
^(NSError *error) { OWSLogError(@"Error: %@.", error); });
}
- (void)setLocalProfileKey:(OWSAES256Key *)key

View File

@ -51,7 +51,7 @@ public extension OWSProfileManager {
case .explicit(let info):
localAci = info.localIdentifiers.aci
case .implicit:
guard let implicitLocalAci = TSAccountManager.shared.localIdentifiers?.aci else {
guard let implicitLocalAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
throw OWSAssertionError("missing local address")
}
localAci = implicitLocalAci
@ -154,13 +154,11 @@ public extension OWSProfileManager {
return
}
let isPrimaryDevice = tsAccountManager.isPrimaryDevice(transaction: tx)
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx.asV2Read)
guard
tsAccountManager.isRegistered(transaction: tx),
isPrimaryDevice
tsRegistrationState.isRegisteredPrimaryDevice
else {
owsAssertDebug(self.tsAccountManager.isRegistered)
Logger.verbose("Not rotating profile key on unregistered and/or non-primary device")
owsFailDebug("Not rotating profile key on unregistered and/or non-primary device")
return
}
@ -173,7 +171,7 @@ public extension OWSProfileManager {
guard !triggers.isEmpty else {
// No need to rotate the profile key.
if isPrimaryDevice {
if tsRegistrationState.isPrimaryDevice ?? true {
// But if it's been more than a week since we checked that our groups are up to date, schedule that.
if -(lastGroupProfileKeyCheckTimestamp?.timeIntervalSinceNow ?? 0) > kWeekInterval {
self.groupsV2.scheduleAllGroupsV2ForProfileKeyUpdate(transaction: tx)
@ -264,7 +262,7 @@ public extension OWSProfileManager {
return .value(())
}
guard tsAccountManager.isRegisteredPrimaryDevice else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice else {
return Promise(error: OWSAssertionError("tsAccountManager.isRegistered was unexpectedly false"))
}
@ -293,7 +291,7 @@ public extension OWSProfileManager {
let newProfileKey = OWSAES256Key.generateRandom()
return self.reuploadLocalProfilePromise(unsavedRotatedProfileKey: newProfileKey, authedAccount: authedAccount).map { newProfileKey }
}.then(on: DispatchQueue.global()) { newProfileKey -> Promise<Void> in
guard let localAci = self.tsAccountManager.localIdentifiers?.aci else {
guard let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
throw OWSAssertionError("Missing localAci.")
}
@ -337,7 +335,9 @@ public extension OWSProfileManager {
}
}.then(on: DispatchQueue.global()) { () -> Promise<Void> in
Logger.info("Updating account attributes after profile key rotation.")
return self.tsAccountManager.updateAccountAttributes()
return Promise.wrapAsync {
try await DependenciesBridge.shared.accountAttributesUpdater.updateAccountAttributes(authedAccount: authedAccount)
}
}.done(on: DispatchQueue.global()) {
Logger.info("Completed profile key rotation.")
self.groupsV2.processProfileKeyUpdates()
@ -542,12 +542,13 @@ public extension OWSProfileManager {
}
class func updateStorageServiceIfNecessary() {
guard CurrentAppContext().isMainApp,
!CurrentAppContext().isRunningTests,
tsAccountManager.isRegisteredAndReady,
tsAccountManager.isRegisteredPrimaryDevice else {
return
}
guard
CurrentAppContext().isMainApp,
!CurrentAppContext().isRunningTests,
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice
else {
return
}
let hasUpdated = databaseStorage.read { transaction in
storageServiceStore.getBool(Self.hasUpdatedStorageServiceKey,
@ -719,7 +720,7 @@ extension OWSProfileManager {
guard AppReadiness.isAppReady else {
return .notReady
}
guard tsAccountManager.isRegisteredAndReady else {
guard DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
return .notReady
}
guard !profileManagerImpl.isUpdatingProfileOnService else {
@ -766,7 +767,10 @@ extension OWSProfileManager {
guard avatarRepairNeeded() else {
return
}
guard TSAccountManager.shared.isPrimaryDevice, self.localProfileAvatarData() != nil else {
guard
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? false,
self.localProfileAvatarData() != nil
else {
clearAvatarRepairNeeded()
return
}
@ -904,7 +908,8 @@ extension OWSProfileManager {
//
// NOTE: We also inform the desktop in the failure case,
// since that _may have_ affected service state.
if self.tsAccountManager.isRegisteredPrimaryDevice {
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction
if tsRegistrationState.isRegisteredPrimaryDevice {
firstly {
self.syncManager.syncLocalContact()
}.catch { error in
@ -914,7 +919,7 @@ extension OWSProfileManager {
// Notify all our devices that the profile has changed.
// Older linked devices may not handle this message.
if tsAccountManager.isRegisteredAndReady {
if tsRegistrationState.isRegistered {
self.syncManager.sendFetchLatestProfileSyncMessage()
}
@ -1068,11 +1073,12 @@ internal extension OWSProfileManager {
/// - Parameter tx: The transaction to use for this operation.
@objc
func rotateProfileKeyUponRecipientHideObjC(tx: SDSAnyWriteTransaction) {
guard tsAccountManager.isRegistered(transaction: tx) else {
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx.asV2Read)
guard tsRegistrationState.isRegistered else {
OWSLogger.verbose("[Recipient Hiding] Not rotating profile key on unregistered device.")
return
}
guard tsAccountManager.isPrimaryDevice(transaction: tx) else {
guard tsRegistrationState.isPrimaryDevice ?? false else {
OWSLogger.verbose("[Recipient Hiding] Not rotating profile key on non-primary device.")
return
}
@ -1084,11 +1090,12 @@ internal extension OWSProfileManager {
@objc
func forceRotateLocalProfileKeyForGroupDepartureObjc(tx: SDSAnyWriteTransaction) {
guard tsAccountManager.isRegistered(transaction: tx) else {
let tsRegistrationState = DependenciesBridge.shared.tsAccountManager.registrationState(tx: tx.asV2Read)
guard tsRegistrationState.isRegistered else {
OWSLogger.verbose("Not rotating profile key on unregistered device.")
return
}
guard tsAccountManager.isPrimaryDevice(transaction: tx) else {
guard tsRegistrationState.isPrimaryDevice ?? false else {
OWSLogger.verbose("Not rotating profile key on non-primary device.")
return
}

View File

@ -137,7 +137,7 @@ public class VersionedProfilesImpl: NSObject, VersionedProfilesSwift, VersionedP
case .explicit(let info):
localAci = info.localIdentifiers.aci
case .implicit:
guard let implicitLocalAci = self.tsAccountManager.localIdentifiers?.aci else {
guard let implicitLocalAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci else {
throw OWSAssertionError("Missing localUuid.")
}
localAci = implicitLocalAci

Some files were not shown because too many files have changed in this diff Show More